aboutsummaryrefslogtreecommitdiffstats
path: root/src/app.html
blob: 42d00a9e8d8e3d276ec89af5dfcad872406c6d5e (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
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="description" content="The easiest way to get started with bitcoin" />
    <meta name="keywords" content="open source bitcoin lightning web wallet" />
    <meta name="theme-color" content="#fff" />
    <meta name="mobile-web-app-capable" content="yes" />
    <meta name="mobile-web-app-status-bar-style" content="black-translucent" />
    <link rel="apple-touch-icon" href="/images/icon-160.png" />
    <link rel="preload" href="/fonts/Public_Sans/static/PublicSans-Regular.woff2" as="font" type="font/woff2" crossorigin />
    <link rel="manifest" href="/manifest.webmanifest" />
    %sveltekit.head%
    <script>
      window.addEventListener("beforeinstallprompt", (e) => {
        e.preventDefault();
        window.__installPrompt = e;
      });
    </script>
  </head>
  <body data-sveltekit-preload-data="hover">
    <div style="display: contents">%sveltekit.body%</div>
  </body>
</html>
a> 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 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 7994 7995 7996 7997 7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018 8019 8020 8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033 8034 8035 8036 8037 8038 8039 8040 8041 8042 8043 8044 8045 8046 8047 8048 8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114 8115 8116 8117 8118 8119 8120 8121 8122 8123 8124 8125 8126 8127 8128 8129 8130 8131 8132 8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8160 8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8197 8198 8199 8200 8201 8202 8203 8204 8205 8206 8207 8208 8209 8210 8211 8212 8213 8214 8215 8216 8217 8218 8219 8220 8221 8222 8223 8224 8225 8226 8227 8228 8229 8230 8231 8232 8233 8234 8235 8236 8237 8238 8239 8240 8241 8242 8243 8244 8245 8246 8247 8248 8249 8250 8251 8252 8253 8254 8255 8256 8257 8258 8259 8260 8261 8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274 8275 8276 8277 8278 8279 8280 8281 8282 8283 8284 8285 8286 8287 8288 8289 8290 8291 8292 8293 8294 8295 8296 8297 8298 8299 8300 8301 8302 8303 8304 8305 8306 8307 8308 8309 8310 8311 8312 8313 8314 8315 8316 8317 8318 8319 8320 8321 8322 8323 8324 8325 8326 8327 8328 8329 8330 8331 8332 8333 8334 8335 8336 8337 8338 8339 8340 8341 8342 8343 8344 8345 8346 8347 8348 8349 8350 8351 8352 8353 8354 8355 8356 8357 8358 8359 8360 8361 8362 8363 8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375 8376 8377 8378 8379 8380 8381 8382 8383 8384 8385 8386 8387 8388 8389 8390 8391 8392 8393 8394 8395 8396 8397 8398 8399 8400 8401 8402 8403 8404 8405 8406 8407 8408 8409 8410 8411 8412 8413 8414 8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8427 8428 8429 8430 8431 8432 8433 8434 8435 8436 8437 8438 8439 8440 8441 8442 8443 8444 8445 8446 8447 8448 8449 8450 8451 8452 8453 8454 8455 8456 8457 8458 8459 8460 8461 8462 8463 8464 8465 8466 8467 8468 8469 8470 8471 8472 8473 8474 8475 8476 8477 8478 8479 8480 8481 8482 8483 8484 8485 8486 8487 8488 8489 8490 8491 8492 8493 8494 8495 8496 8497 8498 8499 8500 8501 8502 8503 8504 8505 8506 8507 8508 8509 8510 8511 8512 8513 8514 8515 8516 8517 8518 8519 8520 8521 8522 8523 8524 8525 8526 8527 8528 8529 8530 8531 8532 8533 8534 8535 8536 8537 8538 8539 8540 8541 8542 8543 8544 8545 8546 8547 8548 8549 8550 8551 8552 8553 8554 8555 8556 8557 8558 8559 8560 8561 8562 8563 8564 8565 8566 8567 8568 8569 8570 8571 8572 8573 8574 8575 8576 8577 8578 8579 8580 8581 8582 8583 8584 8585 8586 8587 8588 8589 8590 8591 8592 8593 8594 8595 8596 8597 8598 8599 8600 8601 8602 8603 8604 8605 8606 8607 8608 8609 8610 8611 8612 8613 8614 8615 8616 8617 8618 8619 8620 8621 8622 8623 8624 8625 8626 8627 8628 8629 8630 8631 8632 8633 8634 8635 8636 8637 8638 8639 8640 8641 8642 8643 8644 8645 8646 8647 8648 8649 8650 8651 8652 8653 8654 8655 8656 8657 8658 8659 8660 8661 8662 8663 8664 8665 8666 8667 8668 8669 8670 8671 8672 8673 8674 8675 8676 8677 8678 8679 8680 8681 8682 8683 8684 8685 8686 8687 8688 8689 8690 8691 8692 8693 8694 8695 8696 8697 8698 8699 8700 8701 8702 8703 8704 8705 8706 8707 8708 8709 8710 8711 8712 8713 8714 8715 8716 8717 8718 8719 8720 8721 8722 8723 8724 8725 8726 8727 8728 8729 8730 8731 8732 8733 8734 8735 8736 8737 8738 8739 8740 8741 8742 8743 8744 8745 8746 8747 8748 8749 8750 8751 8752 8753 8754 8755 8756 8757 8758 8759 8760 8761 8762 8763 8764 8765 8766 8767 8768 8769 8770 8771 8772 8773 8774 8775 8776 8777 8778 8779 8780 8781 8782 8783 8784 8785 8786 8787 8788 8789 8790 8791 8792 8793 8794 8795 8796 8797 8798 8799 8800 8801 8802 8803 8804 8805 8806 8807 8808 8809 8810 8811 8812 8813 8814 8815 8816 8817 8818 8819 8820 8821 8822 8823 8824 8825 8826 8827 8828 8829 8830 8831 8832 8833 8834 8835 8836 8837 8838 8839 8840 8841 8842 8843 8844 8845 8846 8847 8848 8849 8850 8851 8852 8853 8854 8855 8856 8857 8858 8859 8860 8861 8862 8863 8864 8865 8866 8867 8868 8869 8870 8871 8872 8873 8874 8875 8876 8877 8878 8879 8880 8881 8882 8883 8884 8885 8886 8887 8888 8889 8890 8891 8892 8893 8894 8895 8896 8897 8898 8899 8900 8901 8902 8903 8904 8905 8906 8907 8908 8909 8910 8911 8912 8913 8914 8915 8916 8917 8918 8919 8920 8921 8922 8923 8924 8925 8926 8927 8928 8929 8930 8931 8932 8933 8934 8935 8936 8937 8938 8939 8940 8941 8942 8943 8944 8945 8946 8947 8948 8949 8950 8951 8952 8953 8954 8955 8956 8957 8958 8959 8960 8961 8962 8963 8964 8965 8966 8967 8968 8969 8970 8971 8972 8973 8974 8975 8976 8977 8978 8979 8980 8981 8982 8983 8984 8985 8986 8987 8988 8989 8990 8991 8992 8993 8994 8995 8996 8997 8998 8999 9000 9001 9002 9003 9004 9005 9006 9007 9008 9009 9010 9011 9012 9013 9014 9015 9016 9017 9018 9019 9020 9021 9022 9023 9024 9025 9026 9027 9028 9029 9030 9031 9032 9033 9034 9035 9036 9037 9038 9039 9040 9041 9042 9043 9044 9045 9046 9047 9048 9049 9050 9051 9052 9053 9054 9055 9056 9057 9058 9059 9060 9061 9062 9063 9064 9065 9066 9067 9068 9069 9070 9071 9072 9073 9074 9075 9076 9077 9078 9079 9080 9081 9082 9083 9084 9085 9086 9087 9088 9089 9090 9091 9092 9093 9094 9095 9096 9097 9098 9099 9100 9101 9102 9103 9104 9105 9106 9107 9108 9109 9110 9111 9112 9113 9114 9115 9116 9117 9118 9119 9120 9121 9122 9123 9124 9125 9126 9127 9128 9129 9130 9131 9132 9133 9134 9135 9136 9137 9138 9139 9140 9141 9142 9143 9144 9145 9146 9147 9148 9149 9150 9151 9152 9153 9154 9155 9156 9157 9158 9159 9160 9161 9162 9163 9164 9165 9166 9167 9168 9169 9170 9171 9172 9173 9174 9175 9176 9177 9178 9179 9180 9181 9182 9183 9184 9185 9186 9187 9188 9189 9190 9191 9192 9193 9194 9195 9196 9197 9198 9199 9200 9201 9202 9203 9204 9205 9206 9207 9208 9209 9210 9211 9212 9213 9214 9215 9216 9217 9218 9219 9220 9221 9222 9223 9224 9225 9226 9227 9228 9229 9230 9231 9232 9233 9234 9235 9236 9237 9238 9239 9240 9241 9242 9243 9244 9245 9246 9247 9248 9249 9250 9251 9252 9253 9254 9255 9256 9257 9258 9259 9260 9261 9262 9263 9264 9265 9266 9267 9268 9269 9270 9271 9272 9273 9274 9275 9276 9277 9278 9279 9280 9281 9282 9283 9284 9285 9286 9287 9288 9289 9290 9291 9292 9293 9294 9295 9296 9297 9298 9299 9300 9301 9302 9303 9304 9305 9306 9307 9308 9309 9310 9311 9312 9313 9314 9315 9316 9317 9318 9319 9320 9321 9322 9323 9324 9325 9326 9327 9328 9329 9330 9331 9332 9333 9334 9335 9336 9337 9338 9339 9340 9341 9342 9343 9344 9345 9346 9347 9348 9349 9350 9351 9352 9353 9354 9355 9356 9357 9358 9359 9360 9361 9362 9363 9364 9365 9366 9367 9368 9369 9370 9371 9372 9373 9374 9375 9376 9377 9378 9379 9380 9381 9382 9383 9384 9385 9386 9387 9388 9389 9390 9391 9392 9393 9394 9395 9396 9397 9398 9399 9400 9401 9402 9403 9404 9405 9406 9407 9408 9409 9410 9411 9412 9413 9414 9415 9416 9417 9418 9419 9420 9421 9422 9423 9424 9425 9426 9427 9428 9429 9430 9431 9432 9433 9434 9435 9436 9437 9438 9439 9440 9441 9442 9443 9444 9445 9446 9447 9448 9449 9450 9451 9452 9453 9454 9455 9456 9457 9458 9459 9460 9461 9462 9463 9464 9465 9466 9467 9468 9469 9470 9471 9472 9473 9474 9475 9476 9477 9478 9479 9480 9481 9482 9483 9484 9485 9486 9487 9488 9489 9490 9491 9492 9493 9494 9495 9496 9497 9498 9499 9500 9501 9502 9503 9504 9505 9506 9507 9508 9509 9510 9511 9512 9513 9514 9515 9516 9517 9518 9519 9520 9521 9522 9523 9524 9525 9526 9527 9528 9529 9530 9531 9532 9533 9534 9535 9536 9537 9538 9539 9540 9541 9542 9543 9544 9545 9546 9547 9548 9549 9550 9551 9552 9553 9554 9555 9556 9557 9558 9559 9560 9561 9562 9563 9564 9565 9566 9567 9568 9569 9570 9571 9572 9573 9574 9575 9576 9577 9578 9579 9580 9581 9582 9583 9584 9585 9586 9587 9588 9589 9590 9591 9592 9593 9594 9595 9596 9597 9598 9599 9600 9601 9602 9603 9604 9605 9606 9607 9608 9609 9610 9611 9612 9613 9614 9615 9616 9617 9618 9619 9620 9621 9622 9623 9624 9625 9626 9627 9628 9629 9630 9631 9632 9633 9634 9635 9636 9637 9638 9639 9640 9641 9642 9643 9644 9645 9646 9647 9648 9649 9650 9651 9652 9653 9654 9655 9656 9657 9658 9659 9660 9661 9662 9663 9664 9665 9666 9667 9668 9669 9670 9671 9672 9673 9674 9675 9676 9677 9678 9679 9680 9681 9682 9683 9684 9685 9686 9687 9688 9689 9690 9691 9692 9693 9694 9695 9696 9697 9698 9699 9700 9701 9702 9703 9704 9705 9706 9707 9708 9709 9710 9711 9712 9713 9714 9715 9716 9717 9718 9719 9720 9721 9722 9723 9724 9725 9726 9727 9728 9729 9730 9731 9732 9733 9734 9735 9736 9737 9738 9739 9740 9741 9742 9743 9744 9745 9746 9747 9748 9749 9750 9751 9752 9753 9754 9755 9756 9757 9758 9759 9760 9761 9762 9763 9764 9765 9766 9767 9768 9769 9770 9771 9772 9773 9774 9775 9776 9777 9778 9779 9780 9781 9782 9783 9784 9785 9786 9787 9788 9789 9790 9791 9792 9793 9794 9795 9796 9797 9798 9799 9800 9801 9802 9803 9804 9805 9806 9807 9808 9809 9810 9811 9812 9813 9814 9815 9816 9817 9818 9819 9820 9821 9822 9823 9824 9825 9826 9827 9828 9829 9830 9831 9832 9833 9834 9835 9836 9837 9838 9839 9840 9841 9842 9843 9844 9845 9846 9847 9848 9849 9850 9851 9852 9853 9854 9855 9856 9857 9858 9859 9860 9861 9862 9863 9864 9865 9866 9867 9868 9869 9870 9871 9872 9873 9874 9875 9876 9877 9878 9879 9880 9881 9882 9883 9884 9885 9886 9887 9888 9889 9890 9891 9892 9893 9894 9895 9896 9897 9898 9899 9900 9901 9902 9903 9904 9905 9906 9907 9908 9909 9910 9911 9912 9913 9914 9915 9916 9917 9918 9919 9920 9921 9922 9923 9924 9925 9926 9927 9928 9929 9930 9931 9932 9933 9934 9935 9936 9937 9938 9939 9940 9941 9942 9943 9944 9945 9946 9947 9948 9949 9950 9951 9952 9953 9954 9955 9956 9957 9958 9959 9960 9961 9962 9963 9964 9965 9966 9967 9968 9969 9970 9971 9972 9973 9974 9975 9976 9977 9978 9979 9980 9981 9982 9983 9984 9985 9986 9987 9988 9989 9990 9991 9992 9993 9994 9995 9996 9997 9998 9999 10000 10001 10002 10003 10004 10005 10006 10007 10008 10009 10010 10011 10012 10013 10014 10015 10016 10017 10018 10019 10020 10021 10022 10023 10024 10025 10026 10027 10028 10029 10030 10031 10032 10033 10034 10035 10036 10037 10038 10039 10040 10041 10042 10043 10044 10045 10046 10047 10048 10049 10050 10051 10052 10053 10054 10055 10056 10057 10058 10059 10060 10061 10062 10063 10064 10065 10066 10067 10068 10069 10070 10071 10072 10073 10074 10075 10076 10077 10078 10079 10080 10081 10082 10083 10084 10085 10086 10087 10088 10089 10090 10091 10092 10093 10094 10095 10096 10097 10098 10099 10100 10101 10102 10103 10104 10105 10106 10107 10108 10109 10110 10111 10112 10113 10114 10115 10116 10117 10118 10119 10120 10121 10122 10123 10124 10125 10126 10127 10128 10129 10130 10131 10132 10133 10134 10135 10136 10137 10138 10139 10140 10141 10142 10143 10144 10145 10146 10147 10148 10149 10150 10151 10152 10153 10154 10155 10156 10157 10158 10159 10160 10161 10162 10163 10164 10165 10166 10167 10168 10169 10170 10171 10172 10173 10174 10175 10176 10177 10178 10179 10180 10181 10182 10183 10184 10185 10186 10187 10188 10189 10190 10191 10192 10193 10194 10195 10196 10197 10198 10199 10200 10201 10202 10203 10204 10205 10206 10207 10208 10209 10210 10211 10212 10213 10214 10215 10216 10217 10218 10219 10220 10221 10222 10223 10224 10225 10226 10227 10228 10229 10230 10231 10232 10233 10234 10235 10236 10237 10238 10239 10240 10241 10242 10243 10244 10245 10246 10247 10248 10249 10250 10251 10252 10253 10254 10255 10256 10257 10258 10259 10260 10261 10262 10263 10264 10265 10266 10267 10268 10269 10270 10271 10272 10273 10274 10275 10276 10277 10278 10279 10280 10281 10282 10283 10284 10285 10286 10287 10288 10289 10290 10291 10292 10293 10294 10295 10296 10297 10298 10299 10300 10301 10302 10303 10304 10305 10306 10307 10308 10309 10310 10311 10312 10313 10314 10315 10316 10317 10318 10319 10320 10321 10322 10323 10324 10325 10326 10327 10328 10329 10330 10331 10332 10333 10334 10335 10336 10337 10338 10339 10340 10341 10342 10343 10344 10345 10346 10347 10348 10349 10350 10351 10352 10353 10354 10355 10356 10357 10358 10359 10360 10361 10362 10363 10364 10365 10366 10367 10368 10369 10370 10371 10372 10373 10374 10375 10376 10377 10378 10379 10380 10381 10382 10383 10384 10385 10386 10387 10388 10389 10390 10391 10392 10393 10394 10395 10396 10397 10398 10399 10400 10401 10402 10403 10404 10405 10406 10407 10408 10409 10410 10411 10412 10413 10414 10415 10416 10417 10418 10419 10420 10421 10422 10423 10424 10425 10426 10427 10428 10429 10430 10431 10432 10433 10434 10435 10436 10437 10438 10439 10440 10441 10442 10443 10444 10445 10446 10447 10448 10449 10450 10451 10452 10453 10454 10455 10456 10457 10458 10459 10460 10461 10462 10463 10464 10465 10466 10467 10468 10469 10470 10471 10472 10473 10474 10475 10476 10477 10478 10479 10480 10481 10482 10483 10484 10485 10486 10487 10488 10489 10490 10491 10492 10493 10494 10495 10496 10497 10498 10499 10500 10501 10502 10503 10504 10505 10506 10507 10508 10509 10510 10511 10512 10513 10514 10515 10516 10517 10518 10519 10520 10521 10522 10523 10524 10525 10526 10527 10528 10529 10530 10531 10532 10533 10534 10535 10536 10537 10538 10539 10540 10541 10542 10543 10544 10545 10546 10547 10548 10549 10550 10551 10552 10553 10554 10555 10556 10557 10558 10559 10560 10561 10562 10563 10564 10565 10566 10567 10568 10569 10570 10571 10572 10573 10574 10575 10576 10577 10578 10579 10580 10581 10582 10583 10584 10585 10586 10587 10588 10589 10590 10591 10592 10593 10594 10595 10596 10597 10598 10599 10600 10601 10602 10603 10604 10605 10606 10607 10608 10609 10610 10611 10612 10613 10614 10615 10616 10617 10618 10619 10620 10621 10622 10623 10624 10625 10626 10627 10628 10629 10630 10631 10632 10633 10634 10635 10636 10637 10638 10639 10640 10641 10642 10643 10644 10645 10646 10647 10648 10649 10650 10651 10652 10653 10654 10655 10656 10657 10658 10659 10660 10661 10662 10663 10664 10665 10666 10667 10668 10669 10670 10671 10672 10673 10674 10675 10676 10677 10678 10679 10680 10681 10682 10683 10684 10685 10686 10687 10688 10689 10690 10691 10692 10693 10694 10695 10696 10697 10698 10699 10700 10701 10702 10703 10704 10705 10706 10707 10708 10709 10710 10711 10712 10713 10714 10715 10716 10717 10718 10719 10720 10721 10722 10723 10724 10725 10726 10727 10728 10729 10730 10731 10732 10733 10734 10735 10736 10737 10738 10739 10740 10741 10742 10743 10744 10745 10746 10747 10748 10749 10750 10751 10752 10753 10754 10755 10756 10757 10758 10759 10760 10761 10762 10763 10764 10765 10766 10767 10768 10769 10770 10771 10772 10773 10774 10775 10776 10777 10778 10779 10780 10781 10782 10783 10784 10785 10786 10787 10788 10789 10790 10791 10792 10793 10794 10795 10796 10797 10798 10799 10800 10801 10802 10803 10804 10805 10806 10807 10808 10809 10810 10811 10812 10813 10814 10815 10816 10817 10818 10819 10820 10821 10822 10823 10824 10825 10826 10827 10828 10829 10830 10831 10832 10833 10834 10835 10836 10837 10838 10839 10840 10841 10842 10843 10844 10845 10846 10847 10848 10849 10850 10851 10852 10853 10854 10855 10856 10857 10858 10859 10860 10861 10862 10863 10864 10865 10866 10867 10868 10869 10870 10871 10872 10873 10874 10875 10876 10877 10878 10879 10880 10881 10882 10883 10884 10885 10886 10887 10888 10889 10890 10891 10892 10893 10894 10895 10896 10897 10898 10899 10900 10901 10902 10903 10904 10905 10906 10907 10908 10909 10910 10911 10912 10913 10914 10915 10916 10917 10918 10919 10920 10921 10922 10923 10924 10925 10926 10927 10928 10929 10930 10931 10932 10933 10934 10935 10936 10937 10938 10939 10940 10941 10942 10943 10944 10945 10946 10947 10948 10949 10950 10951 10952 10953 10954 10955 10956 10957 10958 10959 10960 10961 10962 10963 10964 10965 10966 10967 10968 10969 10970 10971 10972 10973 10974 10975 10976 10977 10978 10979 10980 10981 10982 10983 10984 10985 10986 10987 10988 10989 10990 10991 10992 10993 10994 10995 10996 10997 10998 10999 11000 11001 11002 11003 11004 11005 11006 11007 11008 11009 11010 11011 11012 11013 11014 11015 11016 11017 11018 11019 11020 11021 11022 11023 11024 11025 11026 11027 11028 11029 11030 11031 11032 11033 11034 11035 11036 11037 11038 11039 11040 11041 11042 11043 11044 11045 11046 11047 11048 11049 11050 11051 11052 11053 11054 11055 11056 11057 11058 11059 11060 11061 11062 11063 11064 11065 11066 11067 11068 11069 11070 11071 11072 11073 11074 11075 11076 11077 11078 11079 11080 11081 11082 11083 11084 11085 11086 11087 11088 11089 11090 11091 11092 11093 11094 11095 11096 11097 11098 11099 11100 11101 11102 11103 11104 11105 11106 11107 11108 11109 11110 11111 11112 11113 11114 11115 11116 11117 11118 11119 11120 11121 11122 11123 11124 11125 11126 11127 11128 11129 11130 11131 11132 11133 11134 11135 11136 11137 11138 11139 11140 11141 11142 11143 11144 11145 11146 11147 11148 11149 11150 11151 11152 11153 11154 11155 11156 11157 11158 11159 11160 11161 11162 11163 11164 11165 11166 11167 11168 11169 11170 11171 11172 11173 11174 11175 11176 11177 11178 11179 11180 11181 11182 11183 11184 11185 11186 11187 11188 11189 11190 11191 11192 11193 11194 11195 11196 11197 11198 11199 11200 11201 11202 11203 11204 11205 11206 11207 11208 11209 11210 11211 11212 11213 11214 11215 11216 11217 11218 11219 11220 11221 11222 11223 11224 11225 11226 11227 11228 11229 11230 11231 11232 11233 11234 11235 11236 11237 11238 11239 11240 11241 11242 11243 11244 11245 11246 11247 11248 11249 11250 11251 11252 11253 11254 11255 11256 11257 11258 11259 11260 11261 11262 11263 11264 11265 11266 11267 11268 11269 11270 11271 11272 11273 11274 11275 11276 11277 11278 11279 11280 11281 11282 11283 11284 11285 11286 11287 11288 11289 11290 11291 11292 11293 11294 11295 11296 11297 11298 11299 11300 11301 11302 11303 11304 11305 11306 11307 11308 11309 11310 11311 11312 11313 11314 11315 11316 11317 11318 11319 11320 11321 11322 11323 11324 11325 11326 11327 11328 11329 11330 11331 11332 11333 11334 11335 11336 11337 11338 11339 11340 11341 11342 11343 11344 11345 11346 11347 11348 11349 11350 11351 11352 11353 11354 11355 11356 11357 11358 11359 11360 11361 11362 11363 11364 11365 11366 11367 11368 11369 11370 11371 11372 11373 11374 11375 11376 11377 11378 11379 11380 11381 11382 11383 11384 11385 11386 11387 11388 11389 11390 11391 11392 11393 11394 11395 11396 11397 11398 11399 11400 11401 11402 11403 11404 11405 11406 11407 11408 11409 11410 11411 11412 11413 11414 11415 11416 11417 11418 11419 11420 11421 11422 11423 11424 11425 11426 11427 11428 11429 11430 11431 11432 11433 11434 11435 11436 11437 11438 11439 11440 11441 11442 11443 11444 11445 11446 11447 11448 11449 11450 11451 11452 11453 11454 11455 11456 11457 11458 11459 11460 11461 11462 11463 11464 11465 11466 11467 11468 11469 11470 11471 11472 11473 11474 11475 11476 11477 11478 11479 11480 11481 11482 11483 11484 11485 11486 11487 11488 11489 11490 11491 11492 11493 11494 11495 11496 11497 11498 11499 11500 11501 11502 11503 11504 11505 11506 11507 11508 11509 11510 11511 11512 11513 11514 11515 11516 11517 11518 11519 11520 11521 11522 11523 11524 11525 11526 11527 11528 11529 11530 11531 11532 11533 11534 11535 11536 11537 11538 11539 11540 11541 11542 11543 11544 11545 11546 11547 11548 11549 11550 11551 11552 11553 11554 11555 11556 11557 11558 11559 11560 11561 11562 11563 11564 11565 11566 11567 11568 11569 11570 11571 11572 11573 11574 11575 11576 11577 11578 11579 11580 11581 11582 11583 11584 11585 11586 11587 11588 11589 11590 11591 11592 11593 11594 11595 11596 11597 11598 11599 11600 11601 11602 11603 11604 11605 11606 11607 11608 11609 11610 11611 11612 11613 11614 11615 11616 11617 11618 11619 11620 11621 11622 11623 11624 11625 11626 11627 11628 11629 11630 11631 11632 11633 11634 11635 11636 11637 11638 11639 11640 11641 11642 11643 11644 11645 11646 11647 11648 11649 11650 11651 11652 11653 11654 11655 11656 11657 11658 11659 11660 11661 11662 11663 11664 11665 11666 11667 11668 11669 11670 11671 11672 11673 11674 11675 11676 11677 11678 11679 11680 11681 11682 11683 11684 11685 11686 11687 11688 11689 11690 11691 11692 11693 11694 11695 11696 11697 11698 11699 11700 11701 11702 11703 11704 11705 11706 11707 11708 11709 11710 11711 11712 11713 11714 11715 11716 11717 11718 11719 11720 11721 11722 11723 11724 11725 11726 11727 11728 11729 11730 11731 11732 11733 11734 11735 11736 11737 11738 11739 11740 11741 11742 11743 11744 11745 11746 11747 11748 11749 11750 11751 11752 11753 11754 11755 11756 11757 11758 11759 11760 11761 11762 11763 11764 11765 11766 11767 11768 11769 11770 11771 11772 11773 11774 11775 11776 11777 11778 11779 11780 11781 11782 11783 11784 11785 11786 11787 11788 11789 11790 11791 11792 11793 11794 11795 11796 11797 11798 11799 11800 11801 11802 11803 11804 11805 11806 11807 11808 11809 11810 11811 11812 11813 11814 11815 11816 11817 11818 11819 11820 11821 11822 11823 11824 11825 11826 11827 11828 11829 11830 11831 11832 11833 11834 11835 11836 11837 11838 11839 11840 11841 11842 11843 11844 11845 11846 11847 11848 11849 11850 11851 11852 11853 11854 11855 11856 11857 11858 11859 11860 11861 11862 11863 11864 11865 11866 11867 11868 11869 11870 11871 11872 11873 11874 11875 11876 11877 11878 11879 11880 11881 11882 11883 11884 11885 11886 11887 11888 11889 11890 11891 11892 11893 11894 11895 11896 11897 11898 11899 11900 11901 11902 11903 11904 11905 11906 11907 11908 11909 11910 11911 11912 11913 11914 11915 11916 11917 11918 11919 11920 11921 11922 11923 11924 11925 11926 11927 11928 11929 11930 11931 11932 11933 11934 11935 11936 11937 11938 11939 11940 11941 11942 11943 11944 11945 11946 11947 11948 11949 11950 11951 11952 11953 11954 11955 11956 11957 11958 11959 11960 11961 11962 11963 11964 11965 11966 11967 11968 11969 11970 11971 11972 11973 11974 11975 11976 11977 11978 11979 11980 11981 11982 11983 11984 11985 11986 11987 11988 11989 11990 11991 11992 11993 11994 11995 11996 11997 11998 11999 12000 12001 12002 12003 12004 12005 12006 12007 12008 12009 12010 12011 12012 12013 12014 12015 12016 12017 12018 12019 12020 12021 12022 12023 12024 12025 12026 12027 12028 12029 12030 12031 12032 12033 12034 12035 12036 12037 12038 12039 12040 12041 12042 12043 12044 12045 12046 12047 12048 12049 12050 12051 12052 12053 12054 12055 12056 12057 12058 12059 12060 12061 12062 12063 12064 12065 12066 12067 12068 12069 12070 12071 12072 12073 12074 12075 12076 12077 12078 12079 12080 12081 12082 12083 12084 12085 12086 12087 12088 12089 12090 12091 12092 12093 12094 12095 12096 12097 12098 12099 12100 12101 12102 12103 12104 12105 12106 12107 12108 12109 12110 12111 12112 12113 12114 12115 12116 12117 12118 12119 12120 12121 12122 12123 12124 12125 12126 12127 12128 12129 12130 12131 12132 12133 12134 12135 12136 12137 12138 12139 12140 12141 12142 12143 12144 12145 12146 12147 12148 12149 12150 12151 12152 12153 12154 12155 12156 12157 12158 12159 12160 12161 12162 12163 12164 12165 12166 12167 12168 12169 12170 12171 12172 12173 12174 12175 12176 12177 12178 12179 12180 12181 12182 12183 12184 12185 12186 12187 12188 12189 12190 12191 12192 12193 12194 12195 12196 12197 12198 12199 12200 12201 12202 12203 12204 12205 12206 12207 12208 12209 12210 12211 12212 12213 12214 12215 12216 12217 12218 12219 12220 12221 12222 12223 12224 12225 12226 12227 12228 12229 12230 12231 12232 12233 12234 12235 12236 12237 12238 12239 12240 12241 12242 12243 12244 12245 12246 12247 12248 12249 12250 12251 12252 12253 12254 12255 12256 12257 12258 12259 12260 12261 12262 12263 12264 12265 12266 12267 12268 12269 12270 12271 12272 12273 12274 12275 12276 12277 12278 12279 12280 12281 12282 12283 12284 12285 12286 12287 12288 12289 12290 12291 12292 12293 12294 12295 12296 12297 12298 12299 12300 12301 12302 12303 12304 12305 12306 12307 12308 12309 12310 12311 12312 12313 12314 12315 12316 12317 12318 12319 12320 12321 12322 12323 12324 12325 12326 12327 12328 12329 12330 12331 12332 12333 12334 12335 12336 12337 12338 12339 12340 12341 12342 12343 12344 12345 12346 12347 12348 12349 12350 12351 12352 12353 12354 12355 12356 12357 12358 12359 12360 12361 12362 12363 12364 12365 12366 12367 12368 12369 12370 12371 12372 12373 12374 12375 12376 12377 12378 12379 12380 12381 12382 12383 12384 12385 12386 12387 12388 12389 12390 12391 12392 12393 12394 12395 12396 12397 12398 12399 12400 12401 12402 12403 12404 12405 12406 12407 12408 12409 12410 12411 12412 12413 12414 12415 12416 12417 12418 12419 12420 12421 12422 12423 12424 12425 12426 12427 12428 12429 12430 12431 12432 12433 12434 12435 12436 12437 12438 12439 12440 12441 12442 12443 12444 12445 12446 12447 12448 12449 12450 12451 12452 12453 12454 12455 12456 12457 12458 12459 12460 12461 12462 12463 12464 12465 12466 12467 12468 12469 12470 12471 12472 12473 12474 12475 12476 12477 12478 12479 12480 12481 12482 12483 12484 12485 12486 12487 12488 12489 12490 12491 12492 12493 12494 12495 12496 12497 12498 12499 12500 12501 12502 12503 12504 12505 12506 12507 12508 12509 12510 12511 12512 12513 12514 12515 12516 12517 12518 12519 12520 12521 12522 12523 12524 12525 12526 12527 12528 12529 12530 12531 12532 12533 12534 12535 12536 12537 12538 12539 12540 12541 12542 12543 12544 12545 12546 12547 12548 12549 12550 12551 12552 12553 12554 12555 12556 12557 12558 12559 12560 12561 12562 12563 12564 12565 12566 12567 12568 12569 12570 12571 12572 12573 12574 12575 12576 12577 12578 12579 12580 12581 12582 12583 12584 12585 12586 12587 12588 12589 12590 12591 12592 12593 12594 12595 12596 12597 12598 12599 12600 12601 12602 12603 12604 12605 12606 12607 12608 12609 12610 12611 12612 12613 12614 12615 12616 12617 12618 12619 12620 12621 12622 12623 12624 12625 12626 12627 12628 12629 12630 12631 12632 12633 12634 12635 12636 12637 12638 12639 12640 12641 12642 12643 12644 12645 12646 12647 12648 12649 12650 12651 12652 12653 12654 12655 12656 12657 12658 12659 12660 12661 12662 12663 12664 12665 12666 12667 12668 12669 12670 12671 12672 12673 12674 12675 12676 12677 12678 12679 12680 12681 12682 12683 12684 12685 12686 12687 12688 12689 12690 12691 12692 12693 12694 12695 12696 12697 12698 12699 12700 12701 12702 12703 12704 12705 12706 12707 12708 12709 12710 12711 12712 12713 12714 12715 12716 12717 12718 12719 12720 12721 12722 12723 12724 12725 12726 12727 12728 12729 12730 12731 12732 12733 12734 12735 12736 12737 12738 12739 12740 12741 12742 12743 12744 12745 12746 12747 12748 12749 12750 12751 12752 12753 12754 12755 12756 12757 12758 12759 12760 12761 12762 12763 12764 12765 12766 12767 12768 12769 12770 12771 12772 12773 12774 12775 12776 12777 12778 12779 12780 12781 12782 12783 12784 12785 12786 12787 12788 12789 12790 12791 12792 12793 12794 12795 12796 12797 12798 12799 12800 12801 12802 12803 12804 12805 12806 12807 12808 12809 12810 12811 12812 12813 12814 12815 12816 12817 12818 12819 12820 12821 12822 12823 12824 12825 12826 12827 12828 12829 12830 12831 12832 12833 12834 12835 12836 12837 12838 12839 12840 12841 12842 12843 12844 12845 12846 12847 12848 12849 12850 12851 12852 12853 12854 12855 12856 12857 12858 12859 12860 12861 12862 12863 12864 12865 12866 12867 12868 12869 12870 12871 12872 12873 12874 12875 12876 12877 12878 12879 12880 12881 12882 12883 12884 12885 12886 12887 12888 12889 12890 12891 12892 12893 12894 12895 12896 12897 12898 12899 12900 12901 12902 12903 12904 12905 12906 12907 12908 12909 12910 12911 12912 12913 12914 12915 12916 12917 12918 12919 12920 12921 12922 12923 12924 12925 12926 12927 12928 12929 12930 12931 12932 12933 12934 12935 12936 12937 12938 12939 12940 12941 12942 12943 12944 12945 12946 12947 12948 12949 12950 12951 12952 12953 12954 12955 12956 12957 12958 12959 12960 12961 12962 12963 12964 12965 12966 12967 12968 12969 12970 12971 12972 12973 12974 12975 12976 12977 12978 12979 12980 12981 12982 12983 12984 12985 12986 12987 12988 12989 12990 12991 12992 12993 12994 12995 12996 12997 12998 12999 13000 13001 13002 13003 13004 13005 13006 13007 13008 13009 13010 13011 13012 13013 13014 13015 13016 13017 13018 13019 13020 13021 13022 13023 13024 13025 13026 13027 13028 13029 13030 13031 13032 13033 13034 13035 13036 13037 13038 13039 13040 13041 13042 13043 13044 13045 13046 13047 13048 13049 13050 13051 13052 13053 13054 13055 13056 13057 13058 13059 13060 13061 13062 13063 13064 13065 13066 13067 13068 13069 13070 13071 13072 13073 13074 13075 13076 13077 13078 13079 13080 13081 13082 13083 13084 13085 13086 13087 13088 13089 13090 13091 13092 13093 13094 13095 13096 13097 13098 13099 13100 13101 13102 13103 13104 13105 13106 13107 13108 13109 13110 13111 13112 13113 13114 13115 13116 13117 13118 13119 13120 13121 13122 13123 13124 13125 13126 13127 13128 13129 13130 13131 13132 13133 13134 13135 13136 13137 13138 13139 13140 13141 13142 13143 13144 13145 13146 13147 13148 13149 13150 13151 13152 13153 13154 13155 13156 13157 13158 13159 13160 13161 13162 13163 13164 13165 13166 13167 13168 13169 13170 13171 13172 13173 13174 13175 13176 13177 13178 13179 13180 13181 13182 13183 13184 13185 13186 13187 13188 13189 13190 13191 13192 13193 13194 13195 13196 13197 13198 13199 13200 13201 13202 13203 13204 13205 13206 13207 13208 13209 13210 13211 13212 13213 13214 13215 13216 13217 13218 13219 13220 13221 13222 13223 13224 13225 13226 13227 13228 13229 13230 13231 13232 13233 13234 13235 13236 13237 13238 13239 13240 13241 13242 13243 13244 13245 13246 13247 13248 13249 13250 13251 13252 13253 13254 13255 13256 13257 13258 13259 13260 13261 13262 13263 13264 13265 13266 13267 13268 13269 13270 13271 13272 13273 13274 13275 13276 13277 13278 13279 13280 13281 13282 13283 13284 13285 13286 13287 13288 13289 13290 13291 13292 13293 13294 13295 13296 13297 13298 13299 13300 13301 13302 13303 13304 13305 13306 13307 13308 13309 13310 13311 13312 13313 13314 13315 13316 13317 13318 13319 13320 13321 13322 13323 13324 13325 13326 13327 13328 13329 13330 13331 13332 13333 13334 13335 13336 13337 13338 13339 13340 13341 13342 13343 13344 13345 13346 13347 13348 13349 13350 13351 13352 13353 13354 13355 13356 13357 13358 13359 13360 13361 13362 13363 13364 13365 13366 13367 13368 13369 13370 13371 13372 13373 13374 13375 13376 13377 13378 13379 13380 13381 13382 13383 13384 13385 13386 13387 13388 13389 13390 13391 13392 13393 13394 13395 13396 13397 13398 13399 13400 13401 13402 13403 13404 13405 13406 13407 13408 13409 13410 13411 13412 13413 13414 13415 13416 13417 13418 13419 13420 13421 13422 13423 13424 13425 13426 13427 13428 13429 13430 13431 13432 13433 13434 13435 13436 13437 13438 13439 13440 13441 13442 13443 13444 13445 13446 13447 13448 13449 13450 13451 13452 13453 13454 13455 13456 13457 13458 13459 13460 13461 13462 13463 13464 13465 13466 13467 13468 13469 13470 13471 13472 13473 13474 13475 13476 13477 13478 13479 13480 13481 13482 13483 13484 13485 13486 13487 13488 13489 13490 13491 13492 13493 13494 13495 13496 13497 13498 13499 13500 13501 13502 13503 13504 13505 13506 13507 13508 13509 13510 13511 13512 13513 13514 13515 13516 13517 13518 13519 13520 13521 13522 13523 13524 13525 13526 13527 13528 13529 13530 13531 13532 13533 13534 13535 13536 13537 13538 13539 13540 13541 13542 13543 13544 13545 13546 13547 13548 13549 13550 13551 13552 13553 13554 13555 13556 13557 13558 13559 13560 13561 13562 13563 13564 13565 13566 13567 13568 13569 13570 13571 13572 13573 13574 13575 13576 13577 13578 13579 13580 13581 13582 13583 13584 13585 13586 13587 13588 13589 13590 13591 13592 13593 13594 13595 13596 13597 13598 13599 13600 13601 13602 13603 13604 13605 13606 13607 13608 13609 13610 13611 13612 13613 13614 13615 13616 13617 13618 13619 13620 13621 13622 13623 13624 13625 13626 13627 13628 13629 13630 13631 13632 13633 13634 13635 13636 13637 13638 13639 13640 13641 13642 13643 13644 13645 13646 13647 13648 13649 13650 13651 13652 13653 13654 13655 13656 13657 13658 13659 13660 13661 13662 13663 13664 13665 13666 13667 13668 13669 13670 13671 13672 13673 13674 13675 13676 13677 13678 13679 13680 13681 13682 13683 13684 13685 13686 13687 13688 13689 13690 13691 13692 13693 13694 13695 13696 13697 13698 13699 13700 13701 13702 13703 13704 13705 13706 13707 13708 13709 13710 13711 13712 13713 13714 13715 13716 13717 13718 13719 13720 13721 13722 13723 13724 13725 13726 13727 13728 13729 13730 13731 13732 13733 13734 13735 13736 13737 13738 13739 13740 13741 13742 13743 13744 13745 13746 13747 13748 13749 13750 13751 13752 13753 13754 13755 13756 13757 13758 13759 13760 13761 13762 13763 13764 13765 13766 13767 13768 13769 13770 13771 13772 13773 13774 13775 13776 13777 13778 13779 13780 13781 13782 13783 13784 13785 13786 13787 13788 13789 13790 13791 13792 13793 13794 13795 13796 13797 13798 13799 13800 13801 13802 13803 13804 13805 13806 13807 13808 13809 13810 13811 13812 13813 13814 13815 13816 13817 13818 13819 13820 13821 13822 13823 13824 13825 13826 13827 13828 13829 13830 13831 13832 13833 13834 13835 13836 13837 13838 13839 13840 13841 13842 13843 13844 13845 13846 13847 13848 13849 13850 13851 13852 13853 13854 13855 13856 13857 13858 13859 13860 13861 13862 13863 13864 13865 13866 13867 13868 13869 13870 13871 13872 13873 13874 13875 13876 13877 13878 13879 13880 13881 13882 13883 13884 13885 13886 13887 13888 13889 13890 13891 13892 13893 13894 13895 13896 13897 13898 13899 13900 13901 13902 13903 13904 13905 13906 13907 13908 13909 13910 13911 13912 13913 13914 13915 13916 13917 13918 13919 13920 13921 13922 13923 13924 13925 13926 13927 13928 13929 13930 13931 13932 13933 13934 13935 13936 13937 13938 13939 13940 13941 13942 13943 13944 13945 13946 13947 13948 13949 13950 13951 13952 13953 13954 13955 13956 13957 13958 13959 13960 13961 13962 13963 13964 13965 13966 13967 13968 13969 13970 13971 13972 13973 13974 13975 13976 13977 13978 13979 13980 13981 13982 13983 13984 13985 13986 13987 13988 13989 13990 13991 13992 13993 13994 13995 13996 13997 13998 13999 14000 14001 14002 14003 14004 14005 14006 14007 14008 14009 14010 14011 14012 14013 14014 14015 14016 14017 14018 14019 14020 14021 14022 14023 14024 14025 14026 14027 14028 14029 14030 14031 14032 14033 14034 14035 14036 14037 14038 14039 14040 14041 14042 14043 14044 14045 14046 14047 14048 14049 14050 14051 14052 14053 14054 14055 14056 14057 14058 14059 14060 14061 14062 14063 14064 14065 14066 14067 14068 14069 14070 14071 14072 14073 14074 14075 14076 14077 14078 14079 14080 14081 14082 14083 14084 14085 14086 14087 14088 14089 14090 14091 14092 14093 14094 14095 14096 14097 14098 14099 14100 14101 14102 14103 14104 14105 14106 14107 14108 14109 14110 14111 14112 14113 14114 14115 14116 14117 14118 14119 14120 14121 14122 14123 14124 14125 14126 14127 14128 14129 14130 14131 14132 14133 14134 14135 14136 14137 14138 14139 14140 14141 14142 14143 14144 14145 14146 14147 14148 14149 14150 14151 14152 14153 14154 14155 14156 14157 14158 14159 14160 14161 14162 14163 14164 14165 14166 14167 14168 14169 14170 14171 14172 14173 14174 14175 14176 14177 14178 14179 14180 14181 14182 14183 14184 14185 14186 14187 14188 14189 14190 14191 14192 14193 14194 14195 14196 14197 14198 14199 14200 14201 14202 14203 14204 14205 14206 14207 14208 14209 14210 14211 14212 14213 14214 14215 14216 14217 14218 14219 14220 14221 14222 14223 14224 14225 14226 14227 14228 14229 14230 14231 14232 14233 14234 14235 14236 14237 14238 14239 14240 14241 14242 14243 14244 14245 14246 14247 14248 14249 14250 14251 14252 14253 14254 14255 14256 14257 14258 14259 14260 14261 14262 14263 14264 14265 14266 14267 14268 14269 14270 14271 14272 14273 14274 14275 14276 14277 14278 14279 14280 14281 14282 14283 14284 14285 14286 14287 14288 14289 14290 14291 14292 14293 14294 14295 14296 14297 14298 14299 14300 14301 14302 14303 14304 14305 14306 14307 14308 14309 14310 14311 14312 14313 14314 14315 14316 14317 14318 14319 14320 14321 14322 14323 14324 14325 14326 14327 14328 14329 14330 14331 14332 14333 14334 14335 14336 14337 14338 14339 14340 14341 14342 14343 14344 14345 14346 14347 14348 14349 14350 14351 14352 14353 14354 14355 14356 14357 14358 14359 14360 14361 14362 14363 14364 14365 14366 14367 14368 14369 14370 14371 14372 14373 14374 14375 14376 14377 14378 14379 14380 14381 14382 14383 14384 14385 14386 14387 14388 14389 14390 14391 14392 14393 14394 14395 14396 14397 14398 14399 14400 14401 14402 14403 14404 14405 14406 14407 14408 14409 14410 14411 14412 14413 14414 14415 14416 14417 14418 14419 14420 14421 14422 14423 14424 14425 14426 14427 14428 14429 14430 14431 14432 14433 14434 14435 14436 14437 14438 14439 14440 14441 14442 14443 14444 14445 14446 14447 14448 14449 14450 14451 14452 14453 14454 14455 14456 14457 14458 14459 14460 14461 14462 14463 14464 14465 14466 14467 14468 14469 14470 14471 14472 14473 14474 14475 14476 14477 14478 14479 14480 14481 14482 14483 14484 14485 14486 14487 14488 14489 14490 14491 14492 14493 14494 14495 14496 14497 14498 14499 14500 14501 14502 14503 14504 14505 14506 14507 14508 14509 14510 14511 14512 14513 14514 14515 14516 14517 14518 14519 14520 14521 14522 14523 14524 14525 14526 14527 14528 14529 14530 14531 14532 14533 14534 14535 14536 14537 14538 14539 14540 14541 14542 14543 14544 14545 14546 14547 14548 14549 14550 14551 14552 14553 14554 14555 14556 14557 14558 14559 14560 14561 14562 14563 14564 14565 14566 14567 14568 14569 14570 14571 14572 14573 14574 14575 14576 14577 14578 14579 14580 14581 14582 14583 14584 14585 14586 14587 14588 14589 14590 14591 14592 14593 14594 14595 14596 14597 14598 14599 14600 14601 14602 14603 14604 14605 14606 14607 14608 14609 14610 14611 14612 14613 14614 14615 14616 14617 14618 14619 14620 14621 14622 14623 14624 14625 14626 14627 14628 14629 14630 14631 14632 14633 14634 14635 14636 14637 14638 14639 14640 14641 14642 14643 14644 14645 14646 14647 14648 14649 14650 14651 14652 14653 14654 14655 14656 14657 14658 14659 14660 14661 14662 14663 14664 14665 14666 14667 14668 14669 14670 14671 14672 14673 14674 14675 14676 14677 14678 14679 14680 14681 14682 14683 14684 14685 14686 14687 14688 14689 14690 14691 14692 14693 14694 14695 14696 14697 14698 14699 14700 14701 14702 14703 14704 14705 14706 14707 14708 14709 14710 14711 14712 14713 14714 14715 14716 14717 14718 14719 14720 14721 14722 14723 14724 14725 14726 14727 14728 14729 14730 14731 14732 14733 14734 14735 14736 14737 14738 14739 14740 14741 14742 14743 14744 14745 14746 14747 14748 14749 14750 14751 14752 14753 14754 14755 14756 14757 14758 14759 14760 14761 14762 14763 14764 14765 14766 14767 14768 14769 14770 14771 14772 14773 14774 14775 14776 14777 14778 14779 14780 14781 14782 14783 14784 14785 14786 14787 14788 14789 14790 14791 14792 14793 14794 14795 14796 14797 14798 14799 14800 14801 14802 14803 14804 14805 14806 14807 14808 14809 14810 14811 14812 14813 14814 14815 14816 14817 14818 14819 14820 14821 14822 14823 14824 14825 14826 14827 14828 14829 14830 14831 14832 14833 14834 14835 14836 14837 14838 14839 14840 14841 14842 14843 14844 14845 14846 14847 14848 14849 14850 14851 14852 14853 14854 14855 14856 14857 14858 14859 14860 14861 14862 14863 14864 14865 14866 14867 14868 14869 14870 14871 14872 14873 14874 14875 14876 14877 14878 14879 14880 14881 14882 14883 14884 14885 14886 14887 14888 14889 14890 14891 14892 14893 14894 14895 14896 14897 14898 14899 14900 14901 14902 14903 14904 14905 14906 14907 14908 14909 14910 14911 14912 14913 14914 14915 14916 14917 14918 14919 14920 14921 14922 14923 14924 14925 14926 14927 14928 14929 14930 14931 14932 14933 14934 14935 14936 14937 14938 14939 14940 14941 14942 14943 14944 14945 14946 14947 14948 14949 14950 14951 14952 14953 14954 14955 14956 14957 14958 14959 14960 14961 14962 14963 14964 14965 14966 14967 14968 14969 14970 14971 14972 14973 14974 14975 14976 14977 14978 14979 14980 14981 14982 14983 14984 14985 14986 14987 14988 14989 14990 14991 14992 14993 14994 14995 14996 14997 14998 14999 15000 15001 15002 15003 15004 15005 15006 15007 15008 15009 15010 15011 15012 15013 15014 15015 15016 15017 15018 15019 15020 15021 15022 15023 15024 15025 15026 15027 15028 15029 15030 15031 15032 15033 15034 15035 15036 15037 15038 15039 15040 15041 15042 15043 15044 15045 15046 15047 15048 15049 15050 15051 15052 15053 15054 15055 15056 15057 15058 15059 15060 15061 15062 15063 15064 15065 15066 15067 15068 15069 15070 15071 15072 15073 15074 15075 15076 15077 15078 15079 15080 15081 15082 15083 15084 15085 15086 15087 15088 15089 15090 15091 15092 15093 15094 15095 15096 15097 15098 15099 15100 15101 15102 15103 15104 15105 15106 15107 15108 15109 15110 15111 15112 15113 15114 15115 15116 15117 15118 15119 15120 15121 15122 15123 15124 15125 15126 15127 15128 15129 15130 15131 15132 15133 15134 15135 15136 15137 15138 15139 15140 15141 15142 15143 15144 15145 15146 15147 15148 15149 15150 15151 15152 15153 15154 15155 15156 15157 15158 15159 15160 15161 15162 15163 15164 15165 15166 15167 15168 15169 15170 15171 15172 15173 15174 15175 15176 15177 15178 15179 15180 15181 15182 15183 15184 15185 15186 15187 15188 15189 15190 15191 15192 15193 15194 15195 15196 15197 15198 15199 15200 15201 15202 15203 15204 15205 15206 15207 15208 15209 15210 15211 15212 15213 15214 15215 15216 15217 15218 15219 15220 15221 15222 15223 15224 15225 15226 15227 15228 15229 15230 15231 15232 15233 15234 15235 15236 15237 15238 15239 15240 15241 15242 15243 15244 15245 15246 15247 15248 15249 15250 15251 15252 15253 15254 15255 15256 15257 15258 15259 15260 15261 15262 15263 15264 15265 15266 15267 15268 15269 15270 15271 15272 15273 15274 15275 15276 15277 15278 15279 15280 15281 15282 15283 15284 15285 15286 15287 15288 15289 15290 15291 15292 15293 15294 15295 15296 15297 15298 15299 15300 15301 15302 15303 15304 15305 15306 15307 15308 15309 15310 15311 15312 15313 15314 15315 15316 15317 15318 15319 15320 15321 15322 15323 15324 15325 15326 15327 15328 15329 15330 15331 15332 15333 15334 15335 15336 15337 15338 15339 15340 15341 15342 15343 15344 15345 15346 15347 15348 15349 15350 15351 15352 15353 15354 15355 15356 15357 15358 15359 15360 15361 15362 15363 15364 15365 15366 15367 15368 15369 15370 15371 15372 15373 15374 15375 15376 15377 15378 15379 15380 15381 15382 15383 15384 15385 15386 15387 15388 15389 15390 15391 15392 15393 15394 15395 15396 15397 15398 15399 15400 15401 15402 15403 15404 15405 15406 15407 15408 15409 15410 15411 15412 15413 15414 15415 15416 15417 15418 15419 15420 15421 15422 15423 15424 15425 15426 15427 15428 15429 15430 15431 15432 15433 15434 15435 15436 15437 15438 15439 15440 15441 15442 15443 15444 15445 15446 15447 15448 15449 15450 15451 15452 15453 15454 15455 15456 15457 15458 15459 15460 15461 15462 15463 15464 15465 15466 15467 15468 15469 15470 15471 15472 15473 15474 15475 15476 15477 15478 15479 15480 15481 15482 15483 15484 15485 15486 15487 15488 15489 15490 15491 15492 15493 15494 15495 15496 15497 15498 15499 15500 15501 15502 15503 15504 15505 15506 15507 15508 15509 15510 15511 15512 15513 15514 15515 15516 15517 15518 15519 15520 15521 15522 15523 15524 15525 15526 15527 15528 15529 15530 15531 15532 15533 15534 15535 15536 15537 15538 15539 15540 15541 15542 15543 15544 15545 15546 15547 15548 15549 15550 15551 15552 15553 15554 15555 15556 15557 15558 15559 15560 15561 15562 15563 15564 15565 15566 15567 15568 15569 15570 15571 15572 15573 15574 15575 15576 15577 15578 15579 15580 15581 15582 15583 15584 15585 15586 15587 15588 15589 15590 15591 15592 15593 15594 15595 15596 15597 15598 15599 15600 15601 15602 15603 15604 15605 15606 15607 15608 15609 15610 15611 15612 15613 15614 15615 15616 15617 15618 15619 15620 15621 15622 15623 15624 15625 15626 15627 15628 15629 15630 15631 15632 15633 15634 15635 15636 15637 15638 15639 15640 15641 15642 15643 15644 15645 15646 15647 15648 15649 15650 15651 15652 15653 15654 15655 15656 15657 15658 15659 15660 15661 15662 15663 15664 15665 15666 15667 15668 15669 15670 15671 15672 15673 15674 15675 15676 15677 15678 15679 15680 15681 15682 15683 15684 15685 15686 15687 15688 15689 15690 15691 15692 15693 15694 15695 15696 15697 15698 15699 15700 15701 15702 15703 15704 15705 15706 15707 15708 15709 15710 15711 15712 15713 15714 15715 15716 15717 15718 15719 15720 15721 15722 15723 15724 15725 15726 15727 15728 15729 15730 15731 15732 15733 15734 15735 15736 15737 15738 15739 15740 15741 15742 15743 15744 15745 15746 15747 15748 15749 15750 15751 15752 15753 15754 15755 15756 15757 15758 15759 15760 15761 15762 15763 15764 15765 15766 15767 15768 15769 15770 15771 15772 15773 15774 15775 15776 15777 15778 15779 15780 15781 15782 15783 15784 15785 15786 15787 15788 15789 15790 15791 15792 15793 15794 15795 15796 15797 15798 15799 15800 15801 15802 15803 15804 15805 15806 15807 15808 15809 15810 15811 15812 15813 15814 15815 15816 15817 15818 15819 15820 15821 15822 15823 15824 15825 15826 15827 15828 15829 15830 15831 15832 15833 15834 15835 15836 15837 15838 15839 15840 15841 15842 15843 15844 15845 15846 15847 15848 15849 15850 15851 15852 15853 15854 15855 15856 15857 15858 15859 15860 15861 15862 15863 15864 15865 15866 15867 15868 15869 15870 15871 15872 15873 15874 15875 15876 15877 15878 15879 15880 15881 15882 15883 15884 15885 15886 15887 15888 15889 15890 15891 15892 15893 15894 15895 15896 15897 15898 15899 15900 15901 15902 15903 15904 15905 15906 15907 15908 15909 15910 15911 15912 15913 15914 15915 15916 15917 15918 15919 15920 15921 15922 15923 15924 15925 15926 15927 15928 15929 15930 15931 15932 15933 15934 15935 15936 15937 15938 15939 15940 15941 15942 15943 15944 15945 15946 15947 15948 15949 15950 15951 15952 15953 15954 15955 15956 15957 15958 15959 15960 15961 15962 15963 15964 15965 15966 15967 15968 15969 15970 15971 15972 15973 15974 15975 15976 15977 15978 15979 15980 15981 15982 15983 15984 15985 15986 15987 15988 15989 15990 15991 15992 15993 15994 15995 15996 15997 15998 15999 16000 16001 16002 16003 16004 16005 16006 16007 16008 16009 16010 16011 16012 16013 16014 16015 16016 16017 16018 16019 16020 16021 16022 16023 16024 16025 16026 16027 16028 16029 16030 16031 16032 16033 16034 16035 16036 16037 16038 16039 16040 16041 16042 16043 16044 16045 16046 16047 16048 16049 16050 16051 16052 16053 16054 16055 16056 16057 16058 16059 16060 16061 16062 16063 16064 16065 16066 16067 16068 16069 16070 16071 16072 16073 16074 16075 16076 16077 16078 16079 16080 16081 16082 16083 16084 16085 16086 16087 16088 16089 16090 16091 16092 16093 16094 16095 16096 16097 16098 16099 16100 16101 16102 16103 16104 16105 16106 16107 16108 16109 16110 16111 16112 16113 16114 16115 16116 16117 16118 16119 16120 16121 16122 16123 16124 16125 16126 16127 16128 16129 16130 16131 16132 16133 16134 16135 16136 16137 16138 16139 16140 16141 16142 16143 16144 16145 16146 16147 16148 16149 16150 16151 16152 16153 16154 16155 16156 16157 16158 16159 16160 16161 16162 16163 16164 16165 16166 16167 16168 16169 16170 16171 16172 16173 16174 16175 16176 16177 16178 16179 16180 16181 16182 16183 16184 16185 16186 16187 16188 16189 16190 16191 16192 16193 16194 16195 16196 16197 16198 16199 16200 16201 16202 16203 16204 16205 16206 16207 16208 16209 16210 16211 16212 16213 16214 16215 16216 16217 16218 16219 16220 16221 16222 16223 16224 16225 16226 16227 16228 16229 16230 16231 16232 16233 16234 16235 16236 16237 16238 16239 16240 16241 16242 16243 16244 16245 16246 16247 16248 16249 16250 16251 16252 16253 16254 16255 16256 16257 16258 16259 16260 16261 16262 16263 16264 16265 16266 16267 16268 16269 16270 16271 16272 16273 16274 16275 16276 16277 16278 16279 16280 16281 16282 16283 16284 16285 16286 16287 16288 16289 16290 16291 16292 16293 16294 16295 16296 16297 16298 16299 16300 16301 16302 16303 16304 16305 16306 16307 16308 16309 16310 16311 16312 16313 16314 16315 16316 16317 16318 16319 16320 16321 16322 16323 16324 16325 16326 16327 16328 16329 16330 16331 16332 16333 16334 16335 16336 16337 16338 16339 16340 16341 16342 16343 16344 16345 16346 16347 16348 16349 16350 16351 16352 16353 16354 16355 16356 16357 16358 16359 16360 16361 16362 16363 16364 16365 16366 16367 16368 16369 16370 16371 16372 16373 16374 16375 16376 16377 16378 16379 16380 16381 16382 16383 16384 16385 16386 16387 16388 16389 16390 16391 16392 16393 16394 16395 16396 16397 16398 16399 16400 16401 16402 16403 16404 16405 16406 16407 16408 16409 16410 16411 16412 16413 16414 16415 16416 16417 16418 16419 16420 16421 16422 16423 16424 16425 16426 16427 16428 16429 16430 16431 16432 16433 16434 16435 16436 16437 16438 16439 16440 16441 16442 16443 16444 16445 16446 16447 16448 16449 16450 16451 16452 16453 16454 16455 16456 16457 16458 16459 16460 16461 16462 16463 16464 16465 16466 16467 16468 16469 16470 16471 16472 16473 16474 16475 16476 16477 16478 16479 16480 16481 16482 16483 16484 16485 16486 16487 16488 16489 16490 16491 16492 16493 16494 16495 16496 16497 16498 16499 16500 16501 16502 16503 16504 16505 16506 16507 16508 16509 16510 16511 16512 16513 16514 16515 16516 16517 16518 16519 16520 16521 16522 16523 16524 16525 16526 16527 16528 16529 16530 16531 16532 16533 16534 16535 16536 16537 16538 16539 16540 16541 16542 16543 16544 16545 16546 16547 16548 16549 16550 16551 16552 16553 16554 16555 16556 16557 16558 16559 16560 16561 16562 16563 16564 16565 16566 16567 16568 16569 16570 16571 16572 16573 16574 16575 16576 16577 16578 16579 16580 16581 16582 16583 16584 16585 16586 16587 16588 16589 16590 16591 16592 16593 16594 16595 16596 16597 16598 16599 16600 16601 16602 16603 16604 16605 16606 16607 16608 16609 16610 16611 16612 16613 16614 16615 16616 16617 16618 16619 16620 16621 16622 16623 16624 16625 16626 16627 16628 16629 16630 16631 16632 16633 16634 16635 16636 16637 16638 16639 16640 16641 16642 16643 16644 16645 16646 16647 16648 16649 16650 16651 16652 16653 16654 16655 16656 16657 16658 16659 16660 16661 16662 16663 16664 16665 16666 16667 16668 16669 16670 16671 16672 16673 16674 16675 16676 16677 16678 16679 16680 16681 16682 16683 16684 16685 16686 16687 16688 16689 16690 16691 16692 16693 16694 16695 16696 16697 16698 16699 16700 16701 16702 16703 16704 16705 16706 16707 16708 16709 16710 16711 16712 16713 16714 16715 16716 16717 16718 16719 16720 16721 16722 16723 16724 16725 16726 16727 16728 16729 16730 16731 16732 16733 16734 16735 16736 16737 16738 16739 16740 16741 16742 16743 16744 16745 16746 16747 16748 16749 16750 16751 16752 16753 16754 16755 16756 16757 16758 16759 16760 16761 16762 16763 16764 16765 16766 16767 16768 16769 16770 16771 16772 16773 16774 16775 16776 16777 16778 16779 16780 16781 16782 16783 16784 16785 16786 16787 16788 16789 16790 16791 16792 16793 16794 16795 16796 16797 16798 16799 16800 16801 16802 16803 16804 16805 16806 16807 16808 16809 16810 16811 16812 16813 16814 16815 16816 16817 16818 16819 16820 16821 16822 16823 16824 16825 16826 16827 16828 16829 16830 16831 16832 16833 16834 16835 16836 16837 16838 16839 16840 16841 16842 16843 16844 16845 16846 16847 16848 16849 16850 16851 16852 16853 16854 16855 16856 16857 16858 16859 16860 16861 16862 16863 16864 16865 16866 16867 16868 16869 16870 16871 16872 16873 16874 16875 16876 16877 16878 16879 16880 16881 16882 16883 16884 16885 16886 16887 16888 16889 16890 16891 16892 16893 16894 16895 16896 16897 16898 16899 16900 16901 16902 16903 16904 16905 16906 16907 16908 16909 16910 16911 16912 16913 16914 16915 16916 16917 16918 16919 16920 16921 16922 16923 16924 16925 16926 16927 16928 16929 16930 16931 16932 16933 16934 16935 16936 16937 16938 16939 16940 16941 16942 16943 16944 16945 16946 16947 16948 16949 16950 16951 16952 16953 16954 16955 16956 16957 16958 16959 16960 16961 16962 16963 16964 16965 16966 16967 16968 16969 16970 16971 16972 16973 16974 16975 16976 16977 16978 16979 16980 16981 16982 16983 16984 16985 16986 16987 16988 16989 16990 16991 16992 16993 16994 16995 16996 16997 16998 16999 17000 17001 17002 17003 17004 17005 17006 17007 17008 17009 17010 17011 17012 17013 17014 17015 17016 17017 17018 17019 17020 17021 17022 17023 17024 17025 17026 17027 17028 17029 17030 17031 17032 17033 17034 17035 17036 17037 17038 17039 17040 17041 17042 17043 17044 17045 17046 17047 17048 17049 17050 17051 17052 17053 17054 17055 17056 17057 17058 17059 17060 17061 17062 17063 17064 17065 17066 17067 17068 17069 17070 17071 17072 17073 17074 17075 17076 17077 17078 17079 17080 17081 17082 17083 17084 17085 17086 17087 17088 17089 17090 17091 17092 17093 17094 17095 17096 17097 17098 17099 17100 17101 17102 17103 17104 17105 17106 17107 17108 17109 17110 17111 17112 17113 17114 17115 17116 17117 17118 17119 17120 17121 17122 17123 17124 17125 17126 17127 17128 17129 17130 17131 17132 17133 17134 17135 17136 17137 17138 17139 17140 17141 17142 17143 17144 17145 17146 17147 17148 17149 17150 17151 17152 17153 17154 17155 17156 17157 17158 17159 17160 17161 17162 17163 17164 17165 17166 17167 17168 17169 17170 17171 17172 17173 17174 17175 17176 17177 17178 17179 17180 17181 17182 17183 17184 17185 17186 17187 17188 17189 17190 17191 17192 17193 17194 17195 17196 17197 17198 17199 17200 17201 17202 17203 17204 17205 17206 17207 17208 17209 17210 17211 17212 17213 17214 17215 17216 17217 17218 17219 17220 17221 17222 17223 17224 17225 17226 17227 17228 17229 17230 17231 17232 17233 17234 17235 17236 17237 17238 17239 17240 17241 17242 17243 17244 17245 17246 17247 17248 17249 17250 17251 17252 17253 17254 17255 17256 17257 17258 17259 17260 17261 17262 17263 17264 17265 17266 17267 17268 17269 17270 17271 17272 17273 17274 17275 17276 17277 17278 17279 17280 17281 17282 17283 17284 17285 17286 17287 17288 17289 17290 17291 17292 17293 17294 17295 17296 17297 17298 17299 17300 17301 17302 17303 17304 17305 17306 17307 17308 17309 17310 17311 17312 17313 17314 17315 17316 17317 17318 17319 17320 17321 17322 17323 17324 17325 17326 17327 17328 17329 17330 17331 17332 17333 17334 17335 17336 17337 17338 17339 17340 17341 17342 17343 17344 17345 17346 17347 17348 17349 17350 17351 17352 17353 17354 17355 17356 17357 17358 17359 17360 17361 17362 17363 17364 17365 17366 17367 17368 17369 17370 17371 17372 17373 17374 17375 17376 17377 17378 17379 17380 17381 17382 17383 17384 17385 17386 17387 17388 17389 17390 17391 17392 17393 17394 17395 17396 17397 17398 17399 17400 17401 17402 17403 17404 17405 17406 17407 17408 17409 17410 17411 17412 17413 17414 17415 17416 17417 17418 17419 17420 17421 17422 17423 17424 17425 17426 17427 17428 17429 17430 17431 17432 17433 17434 17435 17436 17437 17438 17439 17440 17441 17442 17443 17444 17445 17446 17447 17448 17449 17450 17451 17452 17453 17454 17455 17456 17457 17458 17459 17460 17461 17462 17463 17464 17465 17466 17467 17468 17469 17470 17471 17472 17473 17474 17475 17476 17477 17478 17479 17480 17481 17482 17483 17484 17485 17486 17487 17488 17489 17490 17491 17492 17493 17494 17495 17496 17497 17498 17499 17500 17501 17502 17503 17504 17505 17506 17507 17508 17509 17510 17511 17512 17513 17514 17515 17516 17517 17518 17519 17520 17521 17522 17523 17524 17525 17526 17527 17528 17529 17530 17531 17532 17533 17534 17535 17536 17537 17538 17539 17540 17541 17542 17543 17544 17545 17546 17547 17548 17549 17550 17551 17552 17553 17554 17555 17556 17557 17558 17559 17560 17561 17562 17563 17564 17565 17566 17567 17568 17569 17570 17571 17572 17573 17574 17575 17576 17577 17578 17579 17580 17581 17582 17583 17584 17585 17586 17587 17588 17589 17590 17591 17592 17593 17594 17595 17596 17597 17598 17599 17600 17601 17602 17603 17604 17605 17606 17607 17608 17609 17610 17611 17612 17613 17614 17615 17616 17617 17618 17619 17620 17621 17622 17623 17624 17625 17626 17627 17628 17629 17630 17631 17632 17633 17634 17635 17636 17637 17638 17639 17640 17641 17642 17643 17644 17645 17646 17647 17648 17649 17650 17651 17652 17653 17654 17655 17656 17657 17658 17659 17660 17661 17662 17663 17664 17665 17666 17667 17668 17669 17670 17671 17672 17673 17674 17675 17676 17677 17678 17679 17680 17681 17682 17683 17684 17685 17686 17687 17688 17689 17690 17691 17692 17693 17694 17695 17696 17697 17698 17699 17700 17701 17702 17703 17704 17705 17706 17707 17708 17709 17710 17711 17712 17713 17714 17715 17716 17717 17718 17719 17720 17721 17722 17723 17724 17725 17726 17727 17728 17729 17730 17731 17732 17733 17734 17735 17736 17737 17738 17739 17740 17741 17742 17743 17744 17745 17746 17747 17748 17749 17750 17751 17752 17753 17754 17755 17756 17757 17758 17759 17760 17761 17762 17763 17764 17765 17766 17767 17768 17769 17770 17771 17772 17773 17774 17775 17776 17777 17778 17779 17780 17781 17782 17783 17784 17785 17786 17787 17788 17789 17790 17791 17792 17793 17794 17795 17796 17797 17798 17799 17800 17801 17802 17803 17804 17805 17806 17807 17808 17809 17810 17811 17812 17813 17814 17815 17816 17817 17818 17819 17820 17821 17822 17823 17824 17825 17826 17827 17828 17829 17830 17831 17832 17833 17834 17835 17836 17837 17838 17839 17840 17841 17842 17843 17844 17845 17846 17847 17848 17849 17850 17851 17852 17853 17854 17855 17856 17857 17858 17859 17860 17861 17862 17863 17864 17865 17866 17867 17868 17869 17870 17871 17872 17873 17874 17875 17876 17877 17878 17879 17880 17881 17882 17883 17884 17885 17886 17887 17888 17889 17890 17891 17892 17893 17894 17895 17896 17897 17898 17899 17900 17901 17902 17903 17904 17905 17906 17907 17908 17909 17910 17911 17912 17913 17914 17915 17916 17917 17918 17919 17920 17921 17922 17923 17924 17925 17926 17927 17928 17929 17930 17931 17932 17933 17934 17935 17936 17937 17938 17939 17940 17941 17942 17943 17944 17945 17946 17947 17948 17949 17950 17951 17952 17953 17954 17955 17956 17957 17958 17959 17960 17961 17962 17963 17964 17965 17966 17967 17968 17969 17970 17971 17972 17973 17974 17975 17976 17977 17978 17979 17980 17981 17982 17983 17984 17985 17986 17987 17988 17989 17990 17991 17992 17993 17994 17995 17996 17997 17998 17999 18000 18001 18002 18003 18004 18005 18006 18007 18008 18009 18010 18011 18012 18013 18014 18015 18016 18017 18018 18019 18020 18021 18022 18023 18024 18025 18026 18027 18028 18029 18030 18031 18032 18033 18034 18035 18036 18037 18038 18039 18040 18041 18042 18043 18044 18045 18046 18047 18048 18049 18050 18051 18052 18053 18054 18055 18056 18057 18058 18059 18060 18061 18062 18063 18064 18065 18066 18067 18068 18069 18070 18071 18072 18073 18074 18075 18076 18077 18078 18079 18080 18081 18082 18083 18084 18085 18086 18087 18088 18089 18090 18091 18092 18093 18094 18095 18096 18097 18098 18099 18100 18101 18102 18103 18104 18105 18106 18107 18108 18109 18110 18111 18112 18113 18114 18115 18116 18117 18118 18119 18120 18121 18122 18123 18124 18125 18126 18127 18128 18129 18130 18131 18132 18133 18134 18135 18136 18137 18138 18139 18140 18141 18142 18143 18144 18145 18146 18147 18148 18149 18150 18151 18152 18153 18154 18155 18156 18157 18158 18159 18160 18161 18162 18163 18164 18165 18166 18167 18168 18169 18170 18171 18172 18173 18174 18175 18176 18177 18178 18179 18180 18181 18182 18183 18184 18185 18186 18187 18188 18189 18190 18191 18192 18193 18194 18195 18196 18197 18198 18199 18200 18201 18202 18203 18204 18205 18206 18207 18208 18209 18210 18211 18212 18213 18214 18215 18216 18217 18218 18219 18220 18221 18222 18223 18224 18225 18226 18227 18228 18229 18230 18231 18232 18233 18234 18235 18236 18237 18238 18239 18240 18241 18242 18243 18244 18245 18246 18247 18248 18249 18250 18251 18252 18253 18254 18255 18256 18257 18258 18259 18260 18261 18262 18263 18264 18265 18266 18267 18268 18269 18270 18271 18272 18273 18274 18275 18276 18277 18278 18279 18280 18281 18282 18283 18284 18285 18286 18287 18288 18289 18290 18291 18292 18293 18294 18295 18296 18297 18298 18299 18300 18301 18302 18303 18304 18305 18306 18307 18308 18309 18310 18311 18312 18313 18314 18315 18316 18317 18318 18319 18320 18321 18322
import { mediaMoment, momentTags, readMoment, mediaClock, mediaTimeline, markAt } from '../media-timeline.js';
import { mediaServers } from '../media-servers.js';
// 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, subscribeAuthed, publishOn, queryOn, queryManyOn, queryStreamOn, fetchInboxRelays, relayAlive, liveRelayList, readRelayList, resetRelay,
  npubOf, neventOf, parseNostrPubkey, parseNostrRef, generateSecretKey, getPublicKey, finalizeEvent, nip44,
  PROFILE_RELAYS, openWrapsOffthread, unwrapDMsOffthread, verifyEventsAsync, setSyncConfig, DEFAULT_SYNC_RELAYS,
} from '../nostr.js';
import { reconcileOn, syncOn, negentropyOff } from '../nostr.js'; // NIP-77: fetch only what we lack
import {
  channelKey, channelStream, channelEpoch, channelIsPrivate, 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 {
  EMOJI_SET_KIND, EMOJI_LIST_KIND, EMOJI_PARTIAL_RE, PACK_LINK_RE,
  emojiTagMap, splitEmoji, emojiOnlyCount, outboundEmojiTags, shortcodeOf,
  packAddr, packNaddr, parsePackRef, parsePackAddr, parseEmojiSet,
} from '../emoji.js';
import { saveInbox } from '../dm-inbox.js';
import { loadMediaIndex, saveMediaIndex, wipeMediaIndex } from '../media-cache.js';
import { mergeFeedWindow } from '../feed-window.js';
import { createThreadStore } from '../thread-cache.js';
import { createThreadPrefetch } from '../thread-prefetch.js';
import { makeImageThumbnails } from '../image-thumbnails.js';
import { createFeedCache, FEED_CACHE_POSTS, FEED_SEED_POSTS } from '../feed-cache.js';
import { POPULAR_RELAYS, FIREHOSE_RELAYS, popularCandidates } from '../popular-feed.js';
import { makeSearcher, resultRows, fallbackAvatar, warmSearch, punkImageUrl, punkSmallUrl, primalCache } from '../recipient-search.js';
import { getNetwork } from '../api.js';
import { decodeBolt11 } from '../ark/lightning.js';
import { hexToBytes, bytesToHex } from '@noble/hashes/utils';
import { sha256 } from '@noble/hashes/sha256';
import { base64urlnopad } from '@scure/base';
import { t, getLang, LANGS } from '../i18n.js';
import { verifyEvent } from 'nostr-tools/pure';
import { createGifPicker, gifMedia } from '../gif-picker.js';
import { inLanguage, isMachinePost, guessLang } from '../lang-guess.js';
import { translatePieces, translatable as transParts } from '../translate-split.js';
import { animateZap, warmZapSound } from '../zap-animation.js';
import { SIGNER_SILENT } from '../dm.js';
import { cacheStorage, onCacheReady, cacheIsReady } from '../cache-store.js';
import { dlog } from '../debug.js';
import { createCalls, openCall, wrapCall, CALL, CALL_WRAP, RING_S } from '../calls.js';
import { LIVE_KIND, LIVE_CHAT_KIND, LIVE_RELAYS, liveAddr, liveHost, liveTitle, liveSummary, liveImage, liveViewers, liveStarts, liveStream, liveRecording, liveStatus as announcedStatus, isLiveNow as isLiveAnnounced, liveRelays, newestByAddr, zapLine, setZapAddr, liveReactions } from '../live.js';
import { qrSvg } from '../qr.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';
import COMMUNITY_DIRECTORY from '../community-directory.json';
import { assetUrl } from '../asset-url.js';
import { mergeFeeds } from '../feed-sync.js';
// coinos's own relay and primal: both take DM gift wraps and pass call
// messages (ephemeral 21059) on live. nos.lol was here until 2026-10-19 — it
// refused or ignored the household IP's publishes, call answers among them.
const DM_RELAYS = ['wss://relay.coinos.io', 'wss://relay.primal.net'];
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 CALL_LOG = 1405; // a call, logged in its conversation (see logCall)
const CLIENT_TAG = ['client', 'coinos', '31990:72bdbc57bdd6dfc4e62685051de8041d148c3c68fe42bf301f71aa6cf53e52fb:coinos'];

// A view the URL asks to open (a notification tap): read once, then taken
// off the address so a reload doesn't repeat it.
const OPEN_VIEW = (() => {
  try {
    const v = new URLSearchParams(location.search).get('open');
    if (!v) return null;
    const u = new URL(location.href); u.searchParams.delete('open');
    history.replaceState(null, '', u.pathname + (u.search || ''));
    return v;
  } catch { return null; }
})();

export function messagesFeature(ctx) {
  const { h, ui, render, wallet, toast, hook } = ctx;
  const gifs = createGifPicker({ h, t, ui, render });
  // NIP-92: an attachment described, so clients needn't sniff the URL
  const mediaImeta = (m) => ['imeta', 'url ' + m.url, ...(m.m ? ['m ' + m.m] : []), ...(m.dim ? ['dim ' + m.dim] : []),
    ...(m.size ? ['size ' + m.size] : []), ...(m.duration ? ['duration ' + m.duration] : []), ...(m.alt ? ['alt ' + m.alt] : [])];

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

  // The messages state is a large blob (chat caches, DMs, feeds) and reading
  // it means parsing all of it. A repaint asks for it dozens of times (every
  // row's mute and spam checks go through it), so within a tick every caller
  // shares one parse; a write refreshes the copy. Another tab's write shows
  // up on the next tick.
  let stCache = null, stAt = 0;
  const ST_MEMO_MS = 50;
  const st = () => {
    if (stCache && Date.now() - stAt < ST_MEMO_MS) return stCache;
    const s = wallet.loadFeatureState('messages', {});
    stCache = s; stAt = Date.now();
    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
    s.feeds ||= []; // custom feeds: { id, name, follows, authors: [pk], topics: [tag] }
    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) => { stCache = s; stAt = Date.now(); wallet.saveFeatureState('messages', s); };

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

  // A [key, value] list cache folded into its Map. What this session already
  // learned stays (and stays newest); stored rows fill in around it — the
  // same call serves the first read and the re-read once IndexedDB opens.
  function mergeStored(map, key) {
    let rows;
    try { rows = JSON.parse(cacheStorage.getItem(key) || '[]'); } catch { return; }
    if (!Array.isArray(rows) || !rows.length) return;
    const mine = [...map];
    map.clear();
    for (const [k, v] of rows) map.set(k, v);
    for (const [k, v] of mine) { map.delete(k); map.set(k, v); }
  }

  // ---- custom emoji (NIP-30 tags, NIP-51 emoji sets) ----------------------
  // A message that says :pika_wave: carries an ["emoji", code, url] tag for
  // it, so RENDERING never needs anything held locally. Two sources feed
  // what you can type and pick: packs you hold (kind 30030 sets, listed in
  // your kind 10030 — the list Vector reads and writes too, so a pack added
  // in either app shows in both) and shortcodes LEARNED from messages seen,
  // so anyone can answer a :pika_wave: with one.
  const EMOJI_STATE = 'emoji';
  const LEARNED_MAX = 400;
  let emojiState = null;
  const emojiSt = () => {
    if (!emojiState) {
      const s = wallet.loadFeatureState(EMOJI_STATE, {}) || {};
      s.packs ||= {};   // { [addr]: { title, image, emojis: [[code, url]], at } }
      s.order ||= [];   // pack addrs in picker order
      s.learned ||= {}; // { [code]: url }, insertion-ordered, oldest first
      s.list ||= { at: 0, tags: [] }; // our kind 10030 as last seen or published
      s.unfetched ||= []; // listed packs no relay answered for — kept on the list
      emojiState = s;
    }
    return emojiState;
  };
  // Learned shortcodes arrive in bursts (a backfill), so those writes are
  // coalesced; a pack change is one deliberate act and lands at once — a
  // tap-then-navigate must never lose it.
  let emojiSaveTimer = 0;
  const saveEmoji = (now = false) => {
    clearTimeout(emojiSaveTimer);
    const write = () => { try { wallet.saveFeatureState(EMOJI_STATE, emojiSt()); } catch {} };
    if (now) write(); else emojiSaveTimer = setTimeout(write, 500);
  };
  // code → image url: held packs first (in order), then what's been seen
  // White Noise's own two emoji, which it sends as bare :codes: (no NIP-30
  // tag, no picture): drawn from its published artwork, through our picture
  // proxy — a copy served and cached here, as any picture in a post is, not
  // bundled (the app is AGPL, this one MIT).
  const WN_RAW = 'https://raw.githubusercontent.com/marmot-protocol/whitenoise-android/master/app/src/main/res/drawable-nodpi/';
  const BUILTIN_EMOJI = { marmot: WN_RAW + 'builtin_emoji_marmot.png', wn: WN_RAW + 'builtin_emoji_wn.png' };
  const emojiUrl = (code) => {
    const s = emojiSt();
    for (const addr of s.order) {
      const p = s.packs[addr];
      if (!p) continue;
      for (const [c, u] of p.emojis) if (c === code) return u;
    }
    return s.learned[code] || (BUILTIN_EMOJI[code] ? serverPic(BUILTIN_EMOJI[code], 'tile') : null);
  };
  // everything typeable: [{ code, url, pack }], packs first, newest-seen next
  function customEmojis() {
    const s = emojiSt();
    const out = [];
    const seen = new Set();
    for (const addr of s.order) {
      const p = s.packs[addr];
      if (!p) continue;
      for (const [code, url] of p.emojis) {
        if (seen.has(code)) continue;
        seen.add(code);
        out.push({ code, url, pack: p.title });
      }
    }
    for (const [code, url] of Object.entries(s.learned).reverse()) {
      if (seen.has(code)) continue;
      seen.add(code);
      out.push({ code, url, pack: '' });
    }
    return out;
  }
  // Remember the emoji tags a message (or reaction) arrived with. Bounded:
  // the oldest fall off, and re-seeing one moves it back to the front.
  function noteEmoji(rumor) {
    const m = emojiTagMap(rumor && rumor.tags);
    if (!m.size) return;
    const s = emojiSt();
    let changed = false;
    for (const [code, url] of m) {
      if (s.learned[code] === url) continue;
      delete s.learned[code];
      s.learned[code] = url;
      changed = true;
    }
    if (!changed) return;
    const keys = Object.keys(s.learned);
    for (const k of keys.slice(0, Math.max(0, keys.length - LEARNED_MAX))) delete s.learned[k];
    saveEmoji();
  }
  const emojiRelays = (extra = []) => [...new Set([...extra, ...zapRelays(), ...DM_RELAYS, ...STOCK_RELAYS])];
  async function fetchEmojiPack(ref) { // (not fetchPack: that name is the follow packs' further down, and a second declaration wins)
    const evs = await queryOn(emojiRelays(ref.relays), { kinds: [EMOJI_SET_KIND], authors: [ref.pubkey], '#d': [ref.identifier] }, 6000).catch(() => []);
    const newest = (evs || []).sort((a, b) => b.created_at - a.created_at)[0];
    return newest ? parseEmojiSet(newest) : null;
  }
  function holdPack(pack) {
    const s = emojiSt();
    s.packs[pack.addr] = { title: pack.title, image: pack.image, emojis: pack.emojis, at: pack.at };
    if (!s.order.includes(pack.addr)) s.order.push(pack.addr);
    s.unfetched = s.unfetched.filter((a) => a !== pack.addr);
    saveEmoji(true);
  }
  const hasPack = (addr) => !!emojiSt().packs[addr];
  // A pasted naddr / Vector share link, or the Add button on a pack link in
  // chat: fetch the set, hold it, and put it on our list.
  async function addPack(input) {
    const ref = parsePackRef(input);
    if (!ref) { toast(t('msgEmojiPackBad')); return false; }
    const addr = packAddr(ref.pubkey, ref.identifier);
    if (hasPack(addr)) { toast(t('msgEmojiPackHave')); return true; }
    ui.emojiBusy = true; render();
    const pack = await fetchEmojiPack(ref);
    ui.emojiBusy = false;
    if (!pack) { toast(t('msgEmojiPackBad')); render(); return false; }
    holdPack(pack);
    toast(t('msgEmojiPackAdded', { name: pack.title }));
    render();
    publishEmojiList().catch(() => {});
    return true;
  }
  function removePack(addr) {
    const s = emojiSt();
    delete s.packs[addr];
    s.order = s.order.filter((a) => a !== addr);
    s.unfetched = s.unfetched.filter((a) => a !== addr);
    saveEmoji(true);
    render();
    publishEmojiList().catch(() => {});
  }
  // a plain (unwrapped) event signed by the chat identity
  const signPlain = (id, evt) => (id.signer instanceof Uint8Array ? finalizeEvent(evt, id.signer) : id.signer.signEvent(evt));
  // Our kind 10030: the packs held as `a` tags. Every other tag of the list
  // we last saw rides along (inline emoji, whatever another client keeps
  // there), so publishing from here never strips what Vector wrote.
  async function publishEmojiList() {
    const id = await identity();
    if (!id) return;
    const s = emojiSt();
    const kept = (s.list.tags || []).filter((x) => x[0] !== 'a');
    const created_at = Math.max(Math.floor(Date.now() / 1000), (s.list.at || 0) + 1);
    const tags = [...kept, ...[...new Set([...s.order, ...s.unfetched])].map((a) => ['a', a])];
    const evt = await signPlain(id, { kind: EMOJI_LIST_KIND, content: '', tags, created_at });
    s.list = { at: created_at, tags };
    saveEmoji(true);
    publishOn(emojiRelays(), evt);
  }
  // Adopt the newest kind 10030 on the relays when it's newer than what we
  // hold: packs it lists arrive, packs it dropped go. Ten-minute throttle.
  let emojiSyncAt = 0;
  async function syncEmoji({ force = false } = {}) {
    if (!force && Date.now() - emojiSyncAt < 10 * 60_000) return;
    emojiSyncAt = Date.now();
    const pks = myPubkeys();
    if (!pks.length) return;
    try {
      const evs = await queryOn(emojiRelays(), { kinds: [EMOJI_LIST_KIND], authors: pks }, 5000);
      const newest = (evs || []).sort((a, b) => b.created_at - a.created_at)[0];
      const s = emojiSt();
      if (!newest || newest.created_at <= (s.list.at || 0)) return;
      const want = (newest.tags || []).filter((x) => x[0] === 'a' && parsePackAddr(x[1])).map((x) => x[1]);
      s.list = { at: newest.created_at, tags: newest.tags || [] };
      s.order = s.order.filter((a) => want.includes(a));
      for (const a of Object.keys(s.packs)) if (!s.order.includes(a)) delete s.packs[a];
      s.unfetched = [];
      saveEmoji();
      let changed = false;
      for (const addr of want) {
        if (s.packs[addr]) continue;
        const pack = await fetchEmojiPack(parsePackAddr(addr));
        if (pack) { holdPack(pack); changed = true; } else s.unfetched.push(addr);
      }
      // the list's own order wins over arrival order
      s.order = want.filter((a) => s.packs[a]);
      saveEmoji(true);
      if (changed) scheduleRepaint();
    } catch { emojiSyncAt = 0; }
  }
  const emojiImg = (code, url, cls = 'cemoji') =>
    feedPaint && !feedMedia(url) ? ':' + code + ':' : h('img', { class: cls, src: url, alt: ':' + code + ':', title: ':' + code + ':', loading: 'lazy' });
  // A reaction's emoji always draws as its picture. The feed's freeze
  // (emojiImg above) keeps a post's BODY from reflowing as pictures load, but
  // a reaction sits in the action bar at a fixed size — and usually lands
  // after its row was frozen, which left :kek_lord: as text for good.
  const reactImg = (code, url) => h('img', { class: 'cemoji', src: url, alt: ':' + code + ':', title: ':' + code + ':', loading: 'lazy' });
  // A reaction's content as shown on its chip: the picture for a :code: we
  // know (its own tag taught it to us), the text otherwise.
  function reactNode(emoji) {
    const code = shortcodeOf(emoji);
    const url = code && emojiUrl(code);
    return url ? reactImg(code, url) : emoji;
  }
  // the NIP-30 tag a :code: reaction travels with
  const reactEmojiTags = (emoji) => {
    const code = shortcodeOf(emoji);
    const url = code && emojiUrl(code);
    return url ? [['emoji', code, url]] : [];
  };
  // a bubble that is nothing but one to three custom emoji shows them big
  const emojiJumbo = (text, em) => {
    if (!em || !em.size) return false;
    const n = emojiOnlyCount(splitEmoji(text, (c) => em.get(c)));
    return n > 0 && n <= 3;
  };
  // A pack share link (Vector's, or ours) rendered as what it is: one tap
  // adds the pack right here. Never an outbound link — on a phone the
  // vectorapp.io address belongs to the Vector app, and a tap on it walked
  // out of coinos into Vector.
  function packLinkNode(url, naddr) {
    const ref = parsePackRef(naddr);
    const addr = ref && packAddr(ref.pubkey, ref.identifier);
    const have = !!addr && hasPack(addr);
    return h('button', {
      class: 'pack-link', type: 'button', title: url, disabled: have || !!ui.emojiBusy,
      onClick: (e) => { e.stopPropagation(); addPack(naddr); },
    }, '🎨 ' + t('msgEmojiPackLink'), ' · ', h('b', {}, have ? t('msgEmojiPackHave') : t('msgEmojiPackAdd')));
  }
  // our share link for a pack — opens in the coinos app on a phone
  const packShareLink = (addr) => APP_BASE + '/emojis/pack/' + packNaddr(addr);

  // ---- 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)));
    for (const g of wnGroups()) bump(wnRead(g.id), wnNewest(g));
    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;
    for (const g of wnGroups()) if (wnUnread(g)) 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); }
      },
    });
  }

  // Custom feeds sync across devices too (mergeFeeds: newest edit wins,
  // deletions remembered).
  if (wallet.registerCacheExtension && !wallet._feedsSync) {
    wallet._feedsSync = true;
    wallet.registerCacheExtension({
      domain: 'feeds',
      mergeAlways: true,
      save: () => {
        const m = wallet.loadFeatureState('messages', {});
        const feeds = m.feeds || [], gone = m.feedsGone || {};
        return feeds.length || Object.keys(gone).length ? { feeds, feedsGone: gone } : {};
      },
      load: (d) => {
        if (!Array.isArray(d.feeds) && !d.feedsGone) return;
        const m = wallet.loadFeatureState('messages', {});
        const got = mergeFeeds({ feeds: m.feeds, gone: m.feedsGone }, { feeds: d.feeds, gone: d.feedsGone });
        if (!got) return;
        m.feeds = got.feeds; m.feedsGone = got.gone;
        wallet.saveFeatureState('messages', m);
        stCache = null;
        try { for (const id of got.touched) feedStates.delete(id); } catch {} // its query may have changed
        scheduleRepaint();
      },
    });
  }
  // A feed added, edited or deleted here goes out on the next sync.
  let feedsPush = null;
  const feedsChanged = () => {
    // a feed that takes in your lists is built from the other feeds: a
    // changed list rebuilds it next time it's opened
    for (const f of st().feeds) if (expands(f)) for (const k of [f.id, f.id + VIEW_SUFFIX]) { const c = feedStates.get(k); if (c && c !== feed) feedStates.delete(k); }
    clearTimeout(feedsPush);
    feedsPush = setTimeout(() => { try { wallet.saveCache(); } catch {} }, 1000);
  };

  // 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++;
    for (const g of wnGroups())
      if (!g.fresh && wnNewest(g) > Math.max(seen, s.read[wnRead(g.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;
  }
  // NIP-42: sign a relay's AUTH challenge as the DM identity — an inbox
  // relay (auth.nostr1.com, a personal relay) shows gift wraps only to the
  // pubkey they're for, and some take writes only from authenticated users.
  // Never Amber by intent: an app trip per relay connection, for a read
  // nobody asked for.
  async function relayAuth(tmpl) {
    const id = await identity();
    if (!id) throw new Error('no identity');
    if (id.signer instanceof Uint8Array) return finalizeEvent(tmpl, id.signer);
    if (id.signer.interactive) throw new Error('signer is interactive');
    return id.signer.signEvent(tmpl);
  }
  // Our own kind-10050 inbox beyond DM_RELAYS (read at startDMs): sent
  // copies go there too, so other clients reading that list see them.
  let ownInbox = [];
  const toOwnInbox = (wrap) => { if (ownInbox.length) publishOn(ownInbox, wrap, { onauth: relayAuth }); };
  // NIP-71 video events: a clip posted as itself — normal (21) and short,
  // vertical (22), and the addressable 34235/34236 that divine.video and
  // others publish. The file is in an imeta tag, not the text.
  const VIDEO_KINDS = [21, 22, 34235, 34236];
  const isVideoEvent = (ev) => !!ev && VIDEO_KINDS.includes(ev.kind);
  // what a feed or a profile lists: notes, polls (NIP-88) and video events
  const FEED_KINDS = [1, 1068, ...VIDEO_KINDS];
  // A repost (NIP-18 kind 6) of someone's note shows in a feed of the
  // people who reposted it, as the note itself under "<name> reposted".
  // Only reposts that carry the note (every major client embeds it) and
  // whose copy checks out: the id it names, a valid signature.
  const REPOST = 6;
  const repostInners = new Map(); // repost id -> the note, or null
  function repostInner(ev) {
    if (!ev || ev.kind !== REPOST) return null;
    if (repostInners.has(ev.id)) return repostInners.get(ev.id);
    let inner = null;
    try {
      const e = JSON.parse(ev.content || 'null');
      const named = (ev.tags || []).filter((x) => x[0] === 'e').map((x) => x[1]);
      if (e && FEED_KINDS.includes(e.kind) && typeof e.id === 'string' && (!named.length || named.includes(e.id)) && verifyEvent(e)) {
        inner = { id: e.id, pubkey: e.pubkey, created_at: e.created_at, kind: e.kind, tags: e.tags, content: e.content, sig: e.sig };
      }
    } catch {}
    if (repostInners.size > 2000) repostInners.delete(repostInners.keys().next().value);
    repostInners.set(ev.id, inner);
    return inner;
  }
  let repostBy = null; // set while noteRow draws a repost's note
  // A profile shows its articles (NIP-23) among the notes, as Amethyst does.
  // Their boosts too, under "<name> reposted", as in a feed.
  const PROFILE_KINDS = [...FEED_KINDS, 30023, REPOST];
  // An edited article is a new event at the same address: keep the newest.
  const newestArticles = (evs) => {
    const best = new Map();
    for (const e of evs) {
      if (e.kind !== 30023) continue;
      const k = e.pubkey + ':' + ((e.tags.find((x) => x[0] === 'd') || [])[1] || '');
      if (!best.has(k) || best.get(k).created_at < e.created_at) best.set(k, e);
    }
    return evs.filter((e) => e.kind !== 30023 || best.get(e.pubkey + ':' + ((e.tags.find((x) => x[0] === 'd') || [])[1] || '')) === e);
  };
  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 = () => {
    if (signinAsk()) return; // no wallet at all: the way in, not a toast
    // 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 -----------------------------------------------------

  // Bumped on every stop(): an account switch. Async work started under the
  // previous identity (a relay query, a wrap mid-decrypt) checks it after
  // each await and drops what it got — it used to land in the NEXT account's
  // state and be saved there, so a throwaway account showed adam's DMs and
  // notifications for good.
  let session = 0;
  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 dmReactAt = new Map(); // `${rumorId}|${authorPk}` -> ms of the reaction that stands
  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;
  // One pass, once per wallet, over the last two weeks of wraps even though
  // the log calls them opened: caches written before rows kept file fields,
  // or clobbered by another tab, are missing messages no relay would ever be
  // asked for again. Only messages and reactions are re-applied.
  // v2 (2026-10-09): every wrap the relays still hold. Until then a login
  // signer that hadn't resumed yet counted as "complete", so a boot's whole
  // backfill could be given up on the wallet key alone and logged as opened.
  // The pass is only marked done once nothing it re-opened is still waiting
  // for the signer — a session closed before the bunker answered runs it again.
  const HEAL_VERSION = 2;
  let healSince = 0, healAt = 0, healTimer = 0;
  const healed = new Set();
  function loadSeenWraps() {
    if (wrapLog) return;
    const s = st();
    wrapLog = (s.wraps || []).slice(-WRAPS_MAX);
    for (const k of wrapLog) seenWraps.add(k);
    healSince = 0;
    if ((s.dmHeal || 0) < HEAL_VERSION) {
      if (wrapLog.length) {
        healSince = 1; healAt = Date.now();
        // wraps that open at once never reach the drain: check on a timer too
        clearTimeout(healTimer);
        const tick = () => { healDone(); if (healSince) healTimer = setTimeout(tick, 60_000); };
        healTimer = setTimeout(tick, 90_000);
      } else { s.dmHeal = HEAL_VERSION; save(s); }
    }
  }
  function healDone() {
    if (!healSince || Date.now() - healAt < 60_000 || !decryptorsComplete()) return;
    for (const p of pendingWraps.values()) if (p.heal) return;
    const s = st();
    s.dmHeal = HEAL_VERSION;
    save(s);
    healSince = 0;
  }
  const healing = (wrap) => !!healSince && wrap.created_at >= healSince && !healed.has(wrap.id) && !!healed.add(wrap.id);
  // The wraps this device holds — full id and time — for reconciliation
  // (NIP-77) with a relay that speaks it: a subscribe then fetches only the
  // wraps we lack instead of the relay's newest two hundred (half a
  // megabyte, every boot and every resubscribe), and the live subscription
  // opens with limit 0, nothing re-served. The prefix log above stays the
  // "skip this one" memory; a wrap it knows but this list doesn't (logged
  // before the list existed) is added as the relay re-serves it, once.
  const WRAP_ITEMS_MAX = 600; // the relay reconciles its newest 400: that many held, with room (46 KB of a phone's near-full localStorage)
  let wrapItems = null; // id -> created_at, oldest first
  function loadWrapItems() {
    if (wrapItems) return;
    wrapItems = new Map();
    try { for (const [id, ts] of st().wrapItems || []) if (/^[0-9a-f]{64}$/.test(id)) wrapItems.set(id, ts | 0); } catch {}
  }
  function noteWrapItem(id, ts) {
    if (!id || !ts) return;
    loadWrapItems();
    if (wrapItems.has(id)) return;
    wrapItems.set(id, ts);
    while (wrapItems.size > WRAP_ITEMS_MAX) wrapItems.delete(wrapItems.keys().next().value);
    scheduleWrapSave();
  }
  const wrapItemsHeld = () => { loadWrapItems(); return [...wrapItems].map(([id, ts]) => [ts, id]); };
  function scheduleWrapSave() {
    clearTimeout(wrapsTimer);
    wrapsTimer = setTimeout(() => {
      try {
        // another tab may have logged wraps since this one loaded: keep theirs
        const s = st();
        if (wrapLog) {
          const mine = new Set(wrapLog);
          s.wraps = [...(s.wraps || []).filter((k) => !mine.has(k)), ...wrapLog].slice(-WRAPS_MAX);
          wrapLog = s.wraps;
        }
        if (wrapItems) {
          const all = new Map(s.wrapItems || []);
          for (const [id, ts] of wrapItems) all.set(id, ts);
          s.wrapItems = [...all].slice(-WRAP_ITEMS_MAX);
        }
        save(s);
      } catch {}
    }, 1500);
  }
  function rememberWrap(id, ts) {
    const k = wrapKey(id);
    if (!wrapLog) wrapLog = [];
    if (!seenWraps.has(k)) wrapLog.push(k);
    seenWraps.add(k);
    if (ts) noteWrapItem(id, ts);
    scheduleWrapSave();
  }
  let dmStarted = false;
  let allUnsubs = [];
  let dmUnsubs = []; // the DM wrap subscriptions alone, so they can be rebuilt

  let repaintTimer = null;
  const scheduleRepaint = () => {
    if (repaintTimer) return;
    const run = () => {
      // not under a pager in motion: the page beneath is out of sight, and
      // its repaint (40–55 ms on Adam's phone) dropped frames from flights
      // through the pictures (2026-10-17) — it waits for the landing
      if (pagerMoving()) { repaintTimer = setTimeout(run, 120); return; }
      repaintTimer = null;
      // a visitor's public page (a profile, a thread, a feed) repaints too
      if (ui.screen === 'wallet' || ui.pubProf) renderThreadStable();
    };
    repaintTimer = setTimeout(run, 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;
    // The cache lives under the WALLET's namespace. The header avatar can
    // ask for a face before the wallet has its keys (a silent sign-in still
    // resuming at boot), and warming then read an empty slot under a bogus
    // key and counted itself done — online the relays papered over it, but
    // offline every cached face stayed a punk. Wait for the keys; init()
    // warms again once they're there.
    if (!wallet.mnemonic && !wallet.xprv && !wallet.xpub) return;
    profilesWarmed = true;
    const cached = profilesDisk();
    // (a row asked for before the cache opened — still loading, or a miss
    // while offline — gives way to the remembered face; a kind 0 that
    // really named nothing keeps its say)
    for (const [pk, p] of Object.entries(cached)) {
      const cur = profiles.get(pk);
      if (!cur || (!cur.name && !cur.picture && !cur.eventAt)) profiles.set(pk, p);
    }
    // someone known to have no face paints their punk from the first frame,
    // instead of a blank circle that turns into one when the relays answer
    for (const [pk, t] of Object.entries(facelessDisk())) {
      if (!profiles.has(pk)) profiles.set(pk, { name: null, picture: null, t, miss: 1 });
    }
  }
  // People with no face: no kind 0 on two asks running, or one naming
  // nothing. Kept apart from the profile blob (whose rows are for real
  // faces) as a small pubkey -> time map; one found with a face leaves it.
  const FACELESS_MAX = 1000;
  let facelessBlob = null, facelessFlush = null;
  const facelessDisk = () => (facelessBlob ||= wallet.loadFeatureState('profilesFaceless', {}) || {});
  function markFaceless(pk, on) {
    const s = facelessDisk();
    if (on ? s[pk] : !s[pk]) return;
    if (on) s[pk] = Date.now(); else delete s[pk];
    if (facelessFlush) return;
    facelessFlush = setTimeout(() => {
      facelessFlush = null;
      const keys = Object.keys(s);
      if (keys.length > FACELESS_MAX) for (const k of keys.sort((a, b) => s[a] - s[b]).slice(0, keys.length - FACELESS_MAX)) delete s[k];
      wallet.saveFeatureState('profilesFaceless', s);
    }, 500);
  }
  // The persisted profile blob (names, faces, thumbnails) lives parsed in
  // memory and is written back once per burst: a batch of thirty profiles
  // landing during a scroll used to parse and re-serialize the whole blob
  // thirty times over, on the main thread, mid-scroll.
  let profBlob = null, profFlush = null;
  const PROFILE_ROWS = 1500; // a row without a thumbnail is ~430 chars; IndexedDB has room
  const profilesDisk = () => (profBlob ||= wallet.loadFeatureState('profiles', {}));
  function flushProfiles() {
    profFlush = null;
    const s = profBlob;
    if (!s) return;
    // Who stays when space runs out: your own faces, the people you follow,
    // talk to and hear from in Notifications. A feed scroll through a
    // hundred strangers used to evict them all within minutes, and a reload
    // then painted a punk and an npub while their kind 0 was asked for again.
    const mine = new Set(myPubkeys());
    const keep = new Set([...mine, (hook('nostrLoginIdentity') || {}).pubkey,
      wallet.nostrPubkey && wallet.nostrPubkey()].filter(Boolean));
    const known = new Set(keep);
    try { for (const pk of followsNow().set) known.add(pk); } catch {}
    try { for (const pk of threads.keys()) known.add(pk); } catch {}
    try { for (const x of (notif ? notif.items : st().notifs) || []) if (x && x.actor) known.add(x.actor); } catch {}
    const evictFirst = (keys) => keys.sort((a, b) => (known.has(a) - known.has(b)) || ((s[a].t || 0) - (s[b].t || 0)));
    // Thumbnails are the bulk of this blob, so they live on a budget: the
    // least recently seen strangers give theirs up first. The row itself
    // stays — that face just paints the way it used to.
    let size = JSON.stringify(s).length;
    if (size > THUMB_BUDGET) {
      // never our own: the header face is the one that must paint offline
      for (const k of evictFirst(Object.keys(s).filter((k) => s[k].thumb && !mine.has(k)))) {
        size -= (s[k].thumb || '').length;
        delete s[k].thumb; delete s[k].thumbFor;
        if (size <= THUMB_BUDGET) break;
      }
    }
    const keys = Object.keys(s);
    if (keys.length > PROFILE_ROWS)
      for (const k of evictFirst(keys.filter((k) => !keep.has(k))).slice(0, keys.length - PROFILE_ROWS)) delete s[k];
    wallet.saveFeatureState('profiles', s);
  }
  function persistProfile(pk, p) {
    // A faceless answer is not a fact worth writing down here — persisting
    // {name:null, picture:null} rows only evicts real faces from the cap.
    // (It goes on the faceless list instead.)
    if (p && p.eventAt) markFaceless(pk, !p.name && !p.picture);
    if (!p || (!p.name && !p.picture)) return;
    const s = profilesDisk();
    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, eventAt: p.eventAt || 0, 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 } : {}) };
    if (!profFlush) profFlush = setTimeout(flushProfiles, 500);
  }
  // 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 ? punkImageUrl(m[1], !big) : 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, big = false) => {
    try {
      if (!p?.picture) return;
      const image = new Image();
      image.src = big ? localPunk(p.picture, true) || p.picture
        : localPunk(p.picture) || (p.thumbFor === p.picture && p.thumb) || p.picture;
      if (big) image.decode().catch(() => {});
    } 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.
  // Since the blob moved to IndexedDB (cache-store.js) the ceiling is no
  // longer localStorage's five million characters shared with everything:
  // 320K held thirty-odd faces on a phone that follows hundreds, and the
  // rest churned — thumbnail made, evicted, the original fetched again.
  const THUMB_BUDGET = 2_000_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();
  const thumbQueue = new Map();
  // Hosts that serve pictures without CORS headers (cdn.nostrcheck.me, most
  // personal sites): the browser refuses the bytes to
  // a fetch and prints a red line per face while the <img> paints fine. No
  // thumbnail is to be had there, so after a second quick refusal the host
  // is left alone for a week rather than asked about every new face.
  // v2: the first list was mostly wrong (primal's CDN, coinos.io) — see corsFetch
  // v3: v2 also caught dropped connections (primal again, on a phone)
  // v5: v4's reachability probe was answered from the HTTP cache
  const NOCORS_KEY = 'coinos-thumb-nocors-v5';
  try { for (const v of ['', '-v2', '-v3', '-v4']) localStorage.removeItem('coinos-thumb-nocors' + v); } catch {}
  const NOCORS_MS = 7 * 24 * 3600_000;
  let noCors = null; // host -> { n, until }
  const noCorsNow = () => { if (!noCors) { try { noCors = JSON.parse(localStorage.getItem(NOCORS_KEY) || '{}'); } catch { noCors = {}; } } return noCors; };
  const hostOf = (u) => { try { return new URL(u).hostname; } catch { return ''; } };
  const noCorsHost = (u) => { const h = noCorsNow()[hostOf(u)]; return !!h && h.n >= 2 && Date.now() < h.until; };
  const noteNoCors = (u) => {
    const host = hostOf(u); if (!host) return;
    const m = noCorsNow(); const cur = m[host] || { n: 0 };
    m[host] = { n: cur.n + 1, until: Date.now() + NOCORS_MS };
    if (Object.keys(m).length > 200) delete m[Object.keys(m)[0]];
    try { localStorage.setItem(NOCORS_KEY, JSON.stringify(m)); } catch {}
  };
  // The bytes of a picture, readable by script. The HTTP cache comes first:
  // the face was usually just painted from this URL. But a CDN that sends
  // its CORS header only to requests carrying an Origin, and caches the
  // plain answer without `Vary: Origin` (primal's r2a.primal.net does), hands
  // the cached copy — header-less — to our CORS fetch, which then fails as if
  // the host refused. That wrote primal and coinos.io off as "no CORS" and
  // left every picture hosted there painting from the full-size original.
  // So a refusal is retried once past the cache before anyone is blamed.
  // And a refusal looks exactly like a dropped connection (a phone between
  // networks, a DNS hiccup): both are a quick TypeError. Two of those wrote
  // blossom.primal.net off for a week on a phone. So the host is only
  // blamed (TypeError rethrown) when a plain no-cors ask of the same URL
  // goes through; otherwise it's the network, and the error says so.
  async function corsFetch(url, signal) {
    try {
      return await fetch(url, { mode: 'cors', signal });
    } catch (e) {
      if (!e || e.name !== 'TypeError') throw e;
      try {
        return await fetch(url, { mode: 'cors', cache: 'reload', signal });
      } catch (e2) {
        if (!e2 || e2.name !== 'TypeError') throw e2;
        // past the cache: the face was just painted from this URL, so a
        // cached copy would answer even with the network gone — and a dropped
        // connection got primal, nostr.build and coinos.io itself blamed
        let reachable = false;
        try { await fetch(url, { mode: 'no-cors', cache: 'reload', signal }); reachable = true; } catch {}
        if (reachable) { e2.corsRefused = true; throw e2; }
        const net = new Error('network'); net.name = 'NetworkError';
        throw net;
      }
    }
  }
  function makeThumb(pk, p) {
    if (!p || !p.picture || typeof document === 'undefined') return;
    if (noCorsHost(p.picture)) return; // a host that won't hand over bytes; the <img> shows it anyway
    // 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)) return;
    if (thumbing.size >= 3 && !isMe(pk)) { thumbQueue.set(pk, p); return; }
    // 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);
      persistThreadProfile(pk);
      if (patch.thumb) scheduleRepaint();
      // Every warmed face gets a turn; the old concurrency guard silently
      // discarded everyone after the first three in a batch.
      for (const [nextPk, next] of thumbQueue) {
        if (thumbing.size >= 3) break;
        thumbQueue.delete(nextPk);
        makeThumb(nextPk, profiles.get(nextPk) || next);
      }
    };
    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 {
        // the browser's cache is welcome: the face was just painted from this
        // very URL, and 'reload' re-downloaded every original (38 MB in one
        // scroll) — a stale copy still makes a fine thumbnail
        const res = await corsFetch(url, 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 (e) {
        // a quick TypeError is the CORS refusal (a dead host takes longer)
        // only a refusal corsFetch confirmed (a body cut off mid-download
        // is a TypeError too)
        if (e && e.corsRefused) noteNoCors(url);
        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);
  // A feed row keeps the presentation it had when admitted. Background
  // profile/quote refreshes must not rewrite text or replace faces mid-read.
  let feedPaint = null;
  function profileOf(pk) {
    if (!feedPaint) return liveProfileOf(pk);
    if (!feedPaint.profiles.has(pk)) {
      const p = { ...(liveProfileOf(pk) || {}) };
      let url = avatarUrl(p, pk);
      if (!feedMedia(url) && feedMedia(p.picture)) url = p.picture;
      if (!feedMedia(url)) p.picture = null;
      else p.picture = url;
      delete p.thumb;
      delete p.loading;
      feedPaint.profiles.set(pk, p);
    }
    return feedPaint.profiles.get(pk);
  }
  function liveProfileOf(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; }
    if (!m || typeof m !== 'object' || Array.isArray(m)) return false;
    const prev = profiles.get(pk);
    if ((prev?.eventAt || 0) > ev.created_at) return true;
    const p = {
      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,
    };
    const entry = keepThumb(pk, { ...p, eventAt: ev.created_at, t: Date.now(), miss: 0 });
    profiles.set(pk, entry);
    // A page and the batched avatar lookup must share their answer. A slow
    // page miss must never erase a name/photo the batch already found.
    if (fullInFlight.has(pk) || fullProfiles.has(pk)) {
      fullProfiles.set(pk, m);
      fullFetched.add(pk);
      fullMisses.delete(pk);
      persistPage('full', pk, m);
    }
    persistProfile(pk, entry);
    persistThreadProfile(pk);
    preloadPicture(entry);
    return true;
  }

  async function fetchProfiles(pks) {
    for (const pk of pks) profInFlight.add(pk);
    try {
      const found = new Set();
      // Our relays and the profile indexes at once, each answer applied as
      // it lands. Asking them one after the other, each waiting out its
      // slowest relay, put a five-second floor under anyone whose kind 0
      // only an index held: a visitor opening a shared post saw a punk and
      // an npub for seven and a half seconds.
      let painted = 0;
      const asked = new Set(pks);
      const take = (ev) => {
        if (ev && ev.kind === 0 && asked.has(ev.pubkey) && applyProfile(ev.pubkey, ev)) {
          found.add(ev.pubkey);
          if (!painted) painted = setTimeout(() => { painted = 0; scheduleRepaint(); }, 30);
        }
      };
      const relays = [...new Set([...zapRelays(), ...PROFILE_INDEX_RELAYS])];
      const asks = [];
      for (let i = 0; i < pks.length; i += PROF_BATCH) {
        asks.push(queryStreamOn(relays, { kinds: [0], authors: pks.slice(i, i + PROF_BATCH) }, take, 5000).catch(() => {}));
      }
      await Promise.all(asks);
      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) { if (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);
        const miss = ((prev && prev.miss) || 0) + 1;
        profiles.set(pk, { ...(prev || {}), t: Date.now(), miss });
        // remembered, so the next load paints their punk at once (never
        // someone whose face we do know; a face found later replaces it)
        if (!(prev && (prev.name || prev.picture))) markFaceless(pk, true);
      }
      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);
    // CORD-02 §5: a Community past the control_root split hands members the
    // Control Plane's signer pubkey in the invite — the address to read at —
    // while the wraps still decrypt under the community_root-derived key. A
    // legacy Community (the built-in coinos one) has no control_pk: the one
    // derivation is both address and key, and its sk still signs our writes.
    const controlRead = controlKey(root, jm.community_id, jm.root_epoch || EPOCH);
    const control = /^[0-9a-f]{64}$/.test(jm.control_pk || '') && jm.control_pk !== controlRead.pk
      ? { pk: jm.control_pk, sk: null, convKey: controlRead.convKey }
      : controlRead;
    // A channel's stream follows its own key and epoch (CORD-03): public ones
    // rotate with the base epoch, private ones carry theirs in the join
    // material. A channel only known from the Control fold is public.
    const chEntry = (id) => (jm.channels || []).find((c) => c.id === id) || { id };
    room = {
      jm,
      control,
      guestbook: guestbookKey(root, jm.community_id, jm.root_epoch || EPOCH),
      chStream: (id) => channelStream(jm, chEntry(id)),
      chEpoch: (id) => channelEpoch(jm, chEntry(id)),
      folded: null,
      controlEntries: [],
      guestEntries: [],
      // the wraps this room opened: a room rebuilt with fresher keys hands
      // them back to seenWraps, or its new subscription would skip the
      // replay and fold without them
      wrapIds: new Set(),
      members: new Map(),
      byChannel: new Map(),
      edits: new Map(),
      deletes: new Set(),
      reactions: new Map(),
      reactAt: new Map(), // `${target}|${author}` -> ms of the reaction that stands
      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, ownerHex: jm.owner });
      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();
        // An invite may grant no channels at all (a Vector link carries only
        // the private ones): the public channels are learned from the
        // Control fold, so a room open on the relays follows them as they
        // fold in — otherwise the room stays "No messages yet" forever.
        if (room.subscribed) for (const c of roomChannels(room)) subChannel(room, c.id);
        // 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;
    room.unsubs = room.unsubs || [];
    const keep = (...us) => { for (const u of us) { allUnsubs.push(u); room.unsubs.push(u); } };
    keep(
      subscribeOn(room.relays, { kinds: [1059], authors: [room.control.pk], limit: 500 }, (wrap) => {
        if (seenWraps.has(wrap.id)) return;
        seenWraps.add(wrap.id);
        room.wrapIds.add(wrap.id);
        openWrapBg(wrap, room.control, (opened) => {
          if (!opened || opened.rumor.kind !== 3308) return;
          room.controlEntries.push(opened);
          scheduleFold();
        });
      }, { onclose: noteSubClosed }),
      subscribeOn(room.relays, { kinds: [1059], authors: [room.guestbook.pk], limit: 500 }, (wrap) => {
        if (seenWraps.has(wrap.id)) return;
        seenWraps.add(wrap.id);
        room.wrapIds.add(wrap.id);
        openWrapBg(wrap, room.guestbook, (opened) => {
          if (!opened) return;
          room.guestEntries.push(opened);
          scheduleFold();
        });
      }, { onclose: noteSubClosed })
    );
    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);
    // a fold-discovered channel warms from its cache here, the way the
    // invite's own channels do when the room is built
    if (!room.byChannel.has(id)) {
      const msgs = new Map();
      for (const m of st().cache[id] || []) msgs.set(m.rumor.id, m);
      if (msgs.size) { room.byChannel.set(id, msgs); bumpMsgRev(); }
    }
    // 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);
    const u = subscribeOn(room.relays, { kinds: [1059, 21059], authors: [stream.pk], limit: 200 }, (wrap) => {
      if (seenWraps.has(wrap.id)) return;
      seenWraps.add(wrap.id);
      room.wrapIds.add(wrap.id);
      openWrapBg(wrap, stream, (opened) => {
        if (!opened) return;
        onChat(room, id, opened);
      });
    }, { onclose: noteSubClosed });
    allUnsubs.push(u); (room.unsubs = room.unsubs || []).push(u);
  }

  // The relay pool reconnects a dropped socket, but one that ERRORED is
  // given up on — and a phone freezing the tab does exactly that to every
  // subscription we hold. Messages sent while the app was away then never
  // arrived, and nothing after them did either, until a reload. So coming
  // back (and coming online) rebuilds every live wrap subscription: DMs and
  // rooms. The windows they ask for overlap what we already hold, and
  // seenWraps drops the repeats before any decryption, so this costs a few
  // round trips and nothing else.
  function resubscribeStreams() {
    const wasDm = dmStarted;
    const wanted = [...rooms.values()].filter((r) => r.subscribed);
    tearingDown = true; // our own closes are not a relay giving up on us
    try {
      if (wasDm) {
        for (const u of dmUnsubs) { try { u(); } catch {} }
        dmUnsubs = []; dmStarted = false;
      }
      for (const room of wanted) {
        for (const u of room.unsubs || []) { try { u(); } catch {} }
        room.unsubs = []; room.subscribed = false; room.subbed.clear();
      }
    } finally { tearingDown = false; }
    if (wasDm) startDMs();
    for (const room of wanted) subscribeRoom(room);
    if (wn) wn.resubscribe();
    if (cd) cd.resubscribe();
  }

  // ---- subscription watchdog ------------------------------------------------
  // The resume hook above rebuilds after an absence it was TOLD about. It
  // isn't told when a socket errors while the page stays on screen (a wifi
  // hop, a laptop lid, a phone freezing the tab without the away timer
  // noticing, another tab clearing that timer first) — and an errored
  // socket is dropped from the pool with every subscription it carried.
  // The room then sits quietly stale until a reload, while another client
  // is ringing about new messages. So whenever the app is on screen — on
  // focus, on becoming visible, and every ten seconds in between — the pool
  // is asked whether each relay the inbox and the rooms listen on still
  // holds a live socket; a relay that closed a subscription on us counts
  // too. Anything missing rebuilds the lot. A rebuild is a few round trips
  // (seenWraps drops the replay before any decryption), but a relay that
  // keeps refusing is retried on a growing backoff, not every tick.
  let tearingDown = false;
  let subsDead = false;
  let lastRebuild = 0;
  let rebuildBackoff = 15_000;
  let watchdogArmed = false;
  function noteSubClosed() {
    if (tearingDown || !allUnsubs.length) return;
    subsDead = true;
    setTimeout(ensureLive, 500);
  }
  function ensureLive() {
    if (typeof document !== 'undefined' && document.visibilityState === 'hidden') return;
    if (!allUnsubs.length) return; // nothing is meant to be live yet
    const urls = new Set();
    if (dmStarted) for (const u of liveRelayList(DM_RELAYS)) urls.add(u);
    for (const room of rooms.values()) if (room.subscribed) for (const u of liveRelayList(room.relays)) urls.add(u);
    if (wn) for (const u of liveRelayList(wn.relaysInUse())) urls.add(u);
    if (wn && wn.starved()) subsDead = true; // a group's relay came back after being skipped
    const dead = [...urls].filter((u) => !relayAlive(u));
    if (!dead.length && !subsDead) { rebuildBackoff = 15_000; return; }
    const now = Date.now();
    if (now - lastRebuild < rebuildBackoff) return;
    lastRebuild = now;
    rebuildBackoff = Math.min(rebuildBackoff * 2, 5 * 60_000);
    subsDead = false;
    console.warn('chat: relay socket gone (' + (dead.join(', ') || 'subscription closed') + ') — resubscribing');
    // a relay the pool is stuck dialing would just hand the rebuild the same
    // hung promise — drop it so the rebuild dials afresh
    tearingDown = true;
    try { for (const u of dead) resetRelay(u); } finally { tearingDown = false; }
    resubscribeStreams();
  }
  function armWatchdog() {
    if (watchdogArmed || typeof window === 'undefined') return;
    watchdogArmed = true;
    const soon = () => setTimeout(ensureLive, 300);
    window.addEventListener('focus', soon);
    window.addEventListener('pageshow', soon);
    document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'visible') soon(); });
    setInterval(ensureLive, 10_000);
  }

  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(room.chEpoch(channelId))) 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;
    }
    noteEmoji(rumor); // custom emoji seen here become custom emoji you can send
    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…"
      schedulePersist(room);
    } 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]);
      }
      schedulePersist(room);
    } 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) {
        // One reaction per author, the NEWEST by the rumor's own clock — not
        // the last to arrive. A reload's backfill hands them back in relay
        // order, and the flame swapped for confetti came back as the flame.
        const key = target + '|' + author;
        const at = eventMs(rumor) || rumor.created_at * 1000;
        if (at >= (room.reactAt.get(key) || 0)) {
          room.reactAt.set(key, at);
          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) {
      // a private channel is only ours if the invite handed us its key
      const held = (id) => (room.jm.channels || []).some((c) => c.id === id && channelIsPrivate(room.jm, c));
      return [...room.folded.channels.entries()]
        .filter(([id, c]) => !c.private || held(id))
        .map(([id, c]) => ({ id, name: c.name }));
    }
    return room.jm.channels || [];
  };

  // Messages that ARRIVE get cached too, not only ones we send: the cache
  // used to be written on our own actions alone, so a member who only reads
  // had nothing on an offline boot — the room said "No messages yet" with a
  // hundred messages read the day before. A backfill lands in a burst, so
  // the write waits for it to settle.
  const persistTimers = new Map(); // room -> timer
  function schedulePersist(room) {
    clearTimeout(persistTimers.get(room));
    persistTimers.set(room, setTimeout(() => { persistTimers.delete(room); try { persistCache(room); } catch {} }, 2500));
  }
  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);
  }
  // Cancel means discard, including across an immediate reload. Typing can
  // use the debounce above; an explicit destructive action is persisted now.
  function discardDraft(key) {
    sessionDrafts.set(key, '');
    clearTimeout(draftPersist); draftPersist = 0;
    const s = st();
    s.drafts ||= {};
    for (const [k, v] of sessionDrafts) { if (v) s.drafts[k] = v; else delete s.drafts[k]; }
    save(s);
  }

  // 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, '');
    ui.emojiAc = null;
    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;
    ui.emojiAc = null;
    // every :code: we can resolve travels with its picture (NIP-30), so the
    // room renders it whether or not anyone else holds the pack
    const rumor = rumorWithId({
      kind: 9, pubkey: id.pubkey, content: text,
      tags: [['channel', chId], ['epoch', String(room.chEpoch(chId))], ...(replyTo ? [['e', replyTo]] : []), ...outboundEmojiTags(text, emojiUrl), 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 = ['👍', '❤️', '😂', '🔥', '🎉', '🙏'];
  // The full picker behind the quick row: a searchable grid. Names are the
  // search terms; the list is curated rather than the whole Unicode table,
  // which is plenty for a reaction and keeps the bundle small.
  const EMOJI_LIB = `👀 eyes seen look|👍 thumbs up like yes|👎 thumbs down no|❤️ heart love red|🧡 orange heart|💛 yellow heart|💚 green heart|💙 blue heart|💜 purple heart|🖤 black heart|🤍 white heart|💔 broken heart|❤️‍🔥 heart fire|💯 100 hundred|😂 laugh joy tears|🤣 rofl laughing|😀 grin smile|😄 smile happy|😁 beaming grin|😅 sweat smile|😊 blush smile|🙂 slight smile|😉 wink|😍 heart eyes love|🥰 smiling hearts love|😘 kiss blow|😗 kiss|🤩 star struck wow|🥳 party celebrate|😎 cool sunglasses|🤓 nerd glasses|🧐 monocle thinking|🤔 thinking hmm|🤨 raised eyebrow skeptical|😐 neutral meh|😑 expressionless|😶 no mouth silent|🙄 eye roll|😏 smirk|😒 unamused|😞 disappointed sad|😔 pensive sad|😟 worried|😕 confused|🙁 frown sad|☹️ frowning sad|😢 cry tear sad|😭 sob crying|😤 huff steam angry|😠 angry|😡 rage furious|🤬 swearing cursing|🤯 mind blown exploding|😳 flushed embarrassed|🥺 pleading puppy eyes|😱 scream fear|😨 fearful|😰 anxious sweat|😥 sad relieved|😓 downcast sweat|🤗 hug|🤭 hand over mouth giggle|🤫 shush quiet|🤥 lying|😬 grimace awkward|😴 sleeping zzz|🤤 drooling|😪 sleepy|😷 mask sick|🤒 thermometer sick|🤕 bandage hurt|🤢 nauseated|🤮 vomit|🤧 sneeze|🥵 hot|🥶 cold freezing|🥴 woozy|😵 dizzy|😵‍💫 spiral dizzy|🤠 cowboy|🥸 disguise|😇 halo angel innocent|🤡 clown|👻 ghost|💀 skull dead|☠️ skull crossbones|👽 alien|🤖 robot|💩 poop|🙈 see no evil monkey|🙉 hear no evil|🙊 speak no evil|👋 wave hello bye|🤚 raised back hand|✋ raised hand stop|🖐️ hand fingers|🖖 vulcan spock|👌 ok perfect|🤌 pinched fingers italian|🤏 pinch small|✌️ peace victory|🤞 fingers crossed luck|🤟 love you gesture|🤘 rock horns|🤙 call me shaka|👈 point left|👉 point right|👆 point up|👇 point down|☝️ index up|👊 fist punch|✊ raised fist|🤛 left fist|🤜 right fist|👏 clap applause|🙌 raised hands hooray|🤲 palms up|🤝 handshake deal|🙏 pray thanks please|💪 muscle strong flex|🫡 salute|🫶 heart hands|🧠 brain smart|👑 crown king|🎩 top hat|🔥 fire lit hot|✨ sparkles|⭐ star|🌟 glowing star|💫 dizzy star|⚡ lightning zap bolt|💥 boom collision|💢 anger|💦 sweat drops|💨 dash wind|🎉 party popper tada|🎊 confetti|🎈 balloon|🎁 gift present|🏆 trophy win|🥇 gold medal first|🎯 bullseye target|🚀 rocket launch moon|🛸 ufo|🌙 moon|☀️ sun|🌈 rainbow|☕ coffee|🍺 beer|🍻 cheers beers|🥂 clink champagne|🍾 champagne bottle|🍕 pizza|🍔 burger|🍿 popcorn|🎂 cake birthday|🍰 cake slice|🍩 donut|🍪 cookie|🍎 apple|🥑 avocado|🌶️ hot pepper spicy|🧂 salt|🐐 goat|🐶 dog|🐱 cat|🐸 frog pepe|🐵 monkey|🦄 unicorn|🐝 bee|🦋 butterfly|🐢 turtle slow|🐍 snake|🦀 crab|🐋 whale|🦈 shark|🦅 eagle|🐔 chicken|🐷 pig|🐮 cow|🐻 bear|🐼 panda|🐨 koala|🦁 lion|🐯 tiger|🦊 fox|🐺 wolf|🐉 dragon|🌹 rose|🌻 sunflower|🌱 seedling grow|🌲 tree|🍀 clover luck|🍄 mushroom|💎 gem diamond|💰 money bag|💸 money wings|💵 dollar cash|🪙 coin|₿ bitcoin btc|🏦 bank|📈 chart up stonks|📉 chart down|🔑 key|🔒 lock|🔓 unlock|🛡️ shield|⚔️ swords|🗡️ dagger|🔨 hammer|🔧 wrench|⚙️ gear settings|🧲 magnet|💡 idea bulb|🔦 flashlight|🔋 battery|📱 phone|💻 laptop|🖥️ desktop|⌨️ keyboard|🖨️ printer|📷 camera|📸 flash camera|🎥 movie camera|🎬 clapper|🎵 music note|🎶 notes music|🎤 microphone|🎧 headphones|🎸 guitar|🎮 game controller|🎲 dice|🧩 puzzle|♟️ chess|🏀 basketball|⚽ soccer football|🏈 football|⚾ baseball|🎾 tennis|🏐 volleyball|🏓 ping pong|🥊 boxing|🏄 surf|🚴 bike|🏃 run|🧘 yoga meditate|🛌 bed sleep|🚗 car|🚕 taxi|🚌 bus|🚂 train|✈️ plane travel|⛵ sailboat|🚢 ship|🏠 house home|🏢 office|🏗️ construction crane|🗽 statue liberty|🗼 tower|🏔️ mountain|🏖️ beach|🌍 earth globe world|🗺️ map|🧭 compass|⏰ alarm clock|⏳ hourglass|⌛ hourglass done|📅 calendar|📌 pin|📎 paperclip|✂️ scissors|📝 memo note|📚 books|📖 book|📰 newspaper|✉️ envelope mail|📬 mailbox|📦 package box|🏷️ label tag|🔔 bell notification|🔕 bell off mute|📣 megaphone|📢 loudspeaker|💬 speech bubble|💭 thought bubble|🗯️ anger bubble|✅ check yes done|❌ cross no wrong|❓ question|❗ exclamation|‼️ double exclamation|⁉️ interrobang|⚠️ warning|🚫 prohibited|♻️ recycle|✔️ check mark|➕ plus|➖ minus|➗ divide|✖️ multiply|🔁 repeat|🔀 shuffle|▶️ play|⏸️ pause|⏹️ stop|⏩ fast forward|⏪ rewind|🔝 top|🆕 new|🆒 cool|🆓 free|🆗 ok|🔞 18 adult|🅰️ a|🅱️ b|🆎 ab|🅾️ o|🔴 red circle|🟠 orange circle|🟡 yellow circle|🟢 green circle|🔵 blue circle|🟣 purple circle|⚫ black circle|⚪ white circle|🟥 red square|🟧 orange square|🟨 yellow square|🟩 green square|🟦 blue square|🟪 purple square|⬛ black square|⬜ white square|🏁 checkered flag finish|🚩 red flag|🏳️ white flag|🏴‍☠️ pirate flag|🇨🇦 canada|🇺🇸 usa america|🇬🇧 uk britain|🇪🇺 eu europe|🇯🇵 japan|🇧🇷 brazil|🇩🇪 germany|🇫🇷 france|🇮🇹 italy|🇪🇸 spain|🇲🇽 mexico|🇦🇺 australia|🇸🇻 el salvador|🇦🇷 argentina|🇳🇬 nigeria|🇮🇳 india|🇨🇳 china|🇰🇷 korea|🇷🇺 russia|🇺🇦 ukraine|🇵🇹 portugal|🇳🇱 netherlands|🇸🇪 sweden|🇨🇭 switzerland`
    .split('|').map((x) => { const i = x.indexOf(' '); return { e: x.slice(0, i), k: x.slice(i + 1) }; });
  const RECENT_KEY = 'btc-wallet-recent-emoji';
  const recentEmojis = () => { try { return JSON.parse(localStorage.getItem(RECENT_KEY) || '[]'); } catch { return []; } };
  const noteRecent = (e) => { try { localStorage.setItem(RECENT_KEY, JSON.stringify([e, ...recentEmojis().filter((x) => x !== e)].slice(0, 24))); } catch {} };
  // The reaction row for a sheet: recents lead the quick row, and the last
  // button opens the full picker in place — a search box and the grid.
  // A picker entry: `e` is what gets sent (a character, or `:code:` for a
  // custom emoji, which then carries `url`), `k` what search matches.
  const emojiEntry = (e) => {
    const code = shortcodeOf(e);
    if (!code) return { e, k: '' };
    const url = emojiUrl(code);
    return url ? { e, k: code.toLowerCase(), url } : null; // a recent whose pack is gone
  };
  const emojiFace = (x) => (x.url ? emojiImg(shortcodeOf(x.e), x.url) : x.e);
  function reactRow(myReact, onPick) {
    const pick = (e) => { ui.emojiPick = null; noteRecent(e); onPick(e); };
    if (ui.emojiPick) {
      const q = (ui.emojiPick.q || '').trim().toLowerCase();
      // custom emoji lead — packs you hold, then ones you've seen — and the
      // standard set follows; a search matches shortcodes and keywords alike
      const custom = customEmojis().map((x) => ({ e: ':' + x.code + ':', k: x.code.toLowerCase(), url: x.url }));
      const std = EMOJI_LIB;
      let hits;
      if (q) hits = [...custom.filter((x) => x.k.includes(q)), ...std.filter((x) => x.k.includes(q) || x.e === q)];
      else hits = [...recentEmojis().map(emojiEntry).filter(Boolean), ...custom, ...std];
      const seen = new Set();
      hits = hits.filter((x) => !seen.has(x.e) && seen.add(x.e));
      const s = emojiSt();
      const packs = s.order.map((addr) => ({ addr, ...s.packs[addr] })).filter((p) => p.title !== undefined);
      return h('div', { class: 'col', style: 'gap:8px' },
        h('input', {
          type: 'text', placeholder: t('msgEmojiSearch'), value: ui.emojiPick.q || '', autofocus: true,
          onInput: (e) => { ui.emojiPick.q = e.target.value; render(); },
          onKeydown: (e) => { if (e.key === 'Enter' && hits.length) pick(hits[0].e); if (e.key === 'Escape') { ui.emojiPick = null; render(); } },
        }),
        h('div', { class: 'emoji-grid' },
          hits.slice(0, 200).map((x) => h('button', { class: x.e === myReact ? 'on' : '', title: x.url ? x.e : x.k, onClick: () => pick(x.e) }, emojiFace(x))),
          !hits.length ? h('div', { class: 'small muted', style: 'padding:8px' }, t('msgEmojiNone')) : null),
        // the packs behind the custom ones, and the way to add another —
        // Vector's share link or a bare naddr, both land the same set
        h('div', { class: 'emoji-packs' },
          packs.map((p) => h('span', { class: 'chat-react emoji-pack', title: p.addr },
            p.image ? h('img', { class: 'cemoji', src: p.image, alt: '' }) : null, ' ', p.title || '…',
            // its share link, ours: a tap on a phone opens the coinos app
            h('button', {
              type: 'button', class: 'linklike', title: t('msgEmojiPackShare'),
              onClick: async () => { try { await navigator.clipboard.writeText(packShareLink(p.addr)); toast(t('copied')); } catch {} },
            }, '⧉'),
            h('button', { type: 'button', class: 'linklike', title: t('msgEmojiPackRemove'), onClick: () => removePack(p.addr) }, '×'))),
          ui.emojiPick.addPack
            ? h('form', {
                class: 'row gap6', style: 'width:100%',
                onSubmit: async (e) => {
                  e.preventDefault();
                  const inp = e.target.querySelector('input');
                  if (await addPack(inp.value)) { ui.emojiPick.addPack = false; render(); }
                },
              },
                h('input', { type: 'text', class: 'grow', placeholder: t('msgEmojiPackHint'), autofocus: true, autocapitalize: 'none', autocomplete: 'off', spellcheck: 'false' }),
                h('button', { class: 'btn-sm', type: 'submit', disabled: !!ui.emojiBusy }, ui.emojiBusy ? h('span', { class: 'spinner sm' }) : t('msgEmojiPackAdd')))
            : h('button', { type: 'button', class: 'linklike small', onClick: () => { ui.emojiPick.addPack = true; render(); } }, '+ ' + t('msgEmojiAddPack'))));
    }
    const quick = [...new Set([...recentEmojis(), ...REACT_EMOJIS])].map(emojiEntry).filter(Boolean).slice(0, 6);
    return h('div', { class: 'msg-sheet-emojis' },
      quick.map((x) => h('button', { class: x.e === myReact ? 'on' : '', onClick: () => pick(x.e) }, emojiFace(x))),
      h('button', { class: 'more', title: t('msgEmojiMore'), onClick: () => { ui.emojiPick = { q: '' }; render(); } }, '+'));
  }
  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,
      // NIP-25 shape per CORD examples §2.3: e = the message, p = ITS AUTHOR,
      // k = its kind. Vector refuses a reaction without the p tag, so ours
      // never showed there until it was added.
      tags: [['channel', chId], ['epoch', String(room.chEpoch(chId))], ['e', m.rumor.id], ['p', m.author], ['k', '9'], ...reactEmojiTags(emoji), 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);
    room.reactAt.set(m.rumor.id + '|' + id.pubkey, eventMs(rumor)); // older ones arriving later stay out
    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.
  const foldedRumor = (room, m) => {
    const edit = room.edits.get(m.rumor.id);
    return edit && edit.author === m.author ? edit.rumor : m.rumor;
  };
  const oneLine = (text, max = 90) => {
    const one = String(text || '').replace(/\s+/g, ' ').trim();
    return one.length > max ? one.slice(0, max - 1) + '…' : one;
  };
  function msgSnippet(room, m, max = 90) {
    return oneLine(foldedRumor(room, m).content, max);
  }
  // The snippet as nodes: its custom emoji (NIP-30 tags on the rumor) show
  // as small pictures, as they do in the bubble being quoted. The cut lands
  // on the text first, so a shortcode is never sliced in half.
  function snippetNodes(rumor, max = 90) {
    const em = emojiTagMap(rumor && rumor.tags);
    const text = oneLine(rumor && rumor.content, max + 40);
    if (!em.size) return [oneLine(text, max)];
    const out = [];
    let left = max;
    for (const p of splitEmoji(text, (c) => em.get(c))) {
      if (left <= 0) { out.push('…'); break; }
      if (typeof p === 'string') {
        if (p.length > left) { out.push(p.slice(0, Math.max(0, left - 1)) + '…'); break; }
        out.push(p); left -= p.length;
      } else { out.push(emojiImg(p.code, p.url)); left -= 2; }
    }
    return out;
  }
  const msgSnippetNodes = (room, m, max = 90) => snippetNodes(foldedRumor(room, m), max);

  // 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' }, ...msgSnippetNodes(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; ui.emojiPick = 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' },
        reactRow(myReact, (e2) => { close(); sendReaction(room, chId, m, e2); }),
        ui.emojiPick ? null : item('↩', t('msgReply'), () => {
          ui.msgReplyTo = m.rumor.id;
          close();
          setTimeout(() => document.getElementById('msg-draft')?.focus(), 50);
        }),
        !ui.emojiPick && canZapPk(m.author) ? item('⚡', t('msgZap'), () => { close(); zapMessage(m.author, m.rumor.id); }) : null,
        ui.emojiPick ? null : item('⧉', t('copy'), async () => {
          try { await navigator.clipboard.writeText(msgSnippet(room, m, 100000)); toast(t('copied')); } catch {}
          close();
        }),
        !ui.emojiPick && 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' }, ...msgSnippetNodes(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(room.chEpoch(chId))], ['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,
      ...(room.jm.control_pk ? { control_pk: room.jm.control_pk } : {}),
      channels: channelList({ ...room.jm, channels: roomChannels(room).map((c) => (room.jm.channels || []).find((h) => h.id === c.id) || c) }),
      relays: room.relays, name: (room.folded?.metadata?.name) || room.jm.name,
      creator_npub: creatorPk,
    };
  }

  // Bundles minted before channel entries carried key + epoch never opened in
  // Vector. The link itself is fine (signer + token), so re-sign the bundle at
  // the same coordinate with the current shape; the relay replaces it. Once
  // per invite per device, and again whenever the shape changes.
  const BUNDLE_REV = 2;
  async function healInviteBundles() {
    const s = st();
    for (const [cid, inv] of Object.entries(s.invites || {})) {
      if (inv.rev === BUNDLE_REV || !inv.sk || !inv.token) continue;
      const jm = communityById(cid);
      if (!jm) continue;
      try {
        const room = ensureRoom(jm, { subscribe: false });
        const creator = inv.creator || (await identity())?.pubkey;
        const evt = makeInviteBundleEvent(hexToBytes(inv.sk), bundleFor(room, creator), hexToBytes(inv.token));
        if (await publishOn(room.relays, evt)) { inv.rev = BUNDLE_REV; save(s); }
      } catch {}
    }
  }

  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) { if (existing.rev !== BUNDLE_REV) healInviteBundles().catch(() => {}); 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), rev: BUNDLE_REV, creator: id.pubkey };
    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,
        control_pk: b.control_pk, channels: channelList(b),
        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, { where = 'top' } = {}) {
    pendingLink = { parsed, state: 'loading', where };
    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'), where };
    else if (b.revoked) pendingLink = { parsed, state: 'error', error: t('msgInviteRevoked'), where };
    else if (b.expired) pendingLink = { parsed, state: 'error', error: t('msgInviteExpired'), where };
    else pendingLink = { parsed, state: 'ready', bundle: b, where };
    scheduleRepaint();
  }

  // Public suggestions render immediately, including on a first/offline visit.
  // The bundled snapshot is a fallback; the device cache refreshes once a day.
  // Invite previews still check revocation and expiration on the relays.
  const HUB_URL = 'https://vectorapp.io/api/hub';
  const HUB_CACHE_KEY = 'coinos-community-directory-v1';
  const HUB_REFRESH_MS = 86400_000;
  function normalizeHub(list) {
    return list.filter((c) => c && c.name && parseInviteLink(c.invite_url || ''))
      .map((c) => ({
        name: String(c.name).slice(0, 64), description: String(c.description || '').slice(0, 200),
        category: String(c.category || '').slice(0, 64), invite: c.invite_url,
        members: Math.max(0, Number(c.member_count) || 0),
        icon: /^data:image\//.test(c.icon_url || '') && c.icon_url.length <= 32_768 ? c.icon_url : null,
      }))
      .sort((a, b) => b.members - a.members);
  }
  const hub = { list: normalizeHub(COMMUNITY_DIRECTORY), at: 0, attempted: false, loading: false };
  function loadHubCache() {
    try {
      const cached = JSON.parse(cacheStorage.getItem(HUB_CACHE_KEY) || 'null');
      if (cached && Array.isArray(cached.list) && Number.isFinite(cached.at) && cached.at > hub.at) {
        const list = normalizeHub(cached.list);
        if (list.length || !cached.list.length) { hub.list = list; hub.at = cached.at; }
      }
    } catch {}
  }
  loadHubCache();
  async function loadHub() {
    if (hub.loading || hub.attempted || (hub.at > 0 && Date.now() - hub.at < HUB_REFRESH_MS)) return;
    hub.attempted = true; hub.loading = true;
    try {
      const res = await fetch(HUB_URL, { signal: AbortSignal.timeout(20_000) });
      if (!res.ok) throw new Error('http ' + res.status);
      const raw = await res.json();
      if (!Array.isArray(raw)) throw new Error('invalid directory');
      const list = normalizeHub(raw);
      if (raw.length && !list.length) throw new Error('invalid invites');
      hub.list = list; hub.at = Date.now();
      try {
        // Bound icon sizes so public suggestions do not crowd out wallet data.
        const cached = list.map((c) => ({ name: c.name, description: c.description, category: c.category,
          invite_url: c.invite, member_count: c.members, icon_url: c.icon }));
        cacheStorage.setItem(HUB_CACHE_KEY, JSON.stringify({ at: hub.at, list: cached }));
      } catch {}
      scheduleRepaint();
    } catch { /* Keep the usable directory if refresh fails or we're offline. */ }
    finally { hub.loading = false; }
  }
  function hubRows({ preview = false } = {}) {
    const q = preview ? '' : (ui.msgJoinText || '').trim().toLowerCase();
    const have = new Set(communities().map((jm) => (rooms.get(jm.community_id)?.folded?.metadata?.name || jm.name || '').toLowerCase()));
    let rows = hub.list.filter((c) => !q || [c.name, c.description, c.category].some((x) => x.toLowerCase().includes(q)));
    if (preview) rows = rows.filter((c) => !have.has(c.name.toLowerCase())).slice(0, 6);
    if (!rows.length) return [h('div', { class: 'small muted' }, t(preview ? 'msgHubNoSuggestions' : 'msgNoMatches'))];
    return rows.map((c) => h('div', {
      class: 'item chat-thread-row clickable', role: 'button', tabindex: '0',
      onClick: (e) => { e.stopPropagation(); joinFromText(c.invite); },
      onKeydown: (e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); joinFromText(c.invite); } },
    },
      c.icon ? h('img', { class: 'chat-avatar hub-icon', src: c.icon, alt: '' }) : h('div', { class: 'chat-avatar fallback' }, c.name.slice(0, 2)),
      h('div', { class: 'col grow', style: 'min-width:0;gap:1px' },
        h('div', { class: 'row gap6', style: 'align-items:center' },
          h('span', { class: 'chat-name', style: 'overflow:hidden;text-overflow:ellipsis;white-space:nowrap' }, c.name),
          have.has(c.name.toLowerCase()) ? h('span', { class: 'tag conf' }, t('msgJoined')) : null),
        h('div', { class: 'small muted', style: 'overflow:hidden;text-overflow:ellipsis;white-space:nowrap' },
          (c.members ? t('msgMembers', { n: c.members }) + ' · ' : '') + c.category + (c.description ? ' · ' + c.description : '')))));
  }

  function hubPanel({ preview = false } = {}) {
    loadHub().catch(() => {});
    return h('div', { class: 'col community-discovery', style: 'gap:8px' },
      h('div', { class: 'row between', style: 'align-items:baseline' },
        h('h3', { style: 'margin:0' }, t(preview ? 'msgPopularCommunities' : 'msgDiscoverTitle')),
        preview ? h('button', { class: 'btn-sm', onClick: (e) => { e.stopPropagation(); ui.msgJoinText = ''; ui.msgHomePanel = 'join'; render(); } }, t('msgBrowseCommunities')) : null),
      h('div', { class: 'list' + (preview ? '' : ' hub-list') }, hubRows({ preview })));
  }

  function joinFromText(text) {
    const parsed = parseInviteLink(text);
    if (!parsed) { toast(t('msgBadInvite')); return; }
    ui.msgJoinText = '';
    ui.msgHomePanel = null;
    // the answer belongs where the question was asked: the preview replaces
    // the paste box under Communities, not a card at the top of a page the
    // user may have scrolled past
    loadLinkInvite(parsed, { where: 'communities' });
  }

  // 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's own pack share link, /emojis/pack/<naddr> — the Android app
  // owns every v3.coinos.io path, so one tapped on a phone lands here, not
  // in a browser; added once a wallet is open (init below).
  const urlPack = (() => {
    if (typeof location === 'undefined') return null;
    const m = location.pathname.match(/^\/emojis\/pack\/(naddr1[a-z0-9]+)\/?$/i);
    return m && parsePackRef(m[1]) ? m[1] : null;
  })();
  if (urlPack) { 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; a note reference is its own link
    if (m && (['chat', 'pos', 'feed'].includes(m[1]) || /^(note|nevent|naddr)1/i.test(m[1]))) return null;
    return m ? m[1] : null;
  })();
  if (urlProfile) { try { history.replaceState(null, '', '/'); } catch {} }
  // /feed/<npub> is the timeline that person sees (their follows), /feed/<naddr>
  // a follow pack or list, /feed/t/<tag> a topic, /feed?p=…&t=…&pack=… any mix.
  // Public content: a visitor with no wallet reads it over the front door.
  const urlFeed = (() => {
    if (typeof location === 'undefined' || urlInvite) return null;
    const m = location.pathname.match(/^\/feed(?:\/(.+?))?\/?$/i);
    return m ? { path: m[1] || '', search: location.search || '' } : null;
  })();
  if (urlFeed) { try { history.replaceState(null, '', '/'); } catch {} }
  // /note1… and /nevent1… open the thread the same way — the NIP-89 handler
  // event for coinos points njump and friends here for notes, /<npub> for
  // people. Public content: shown over the front door without a wallet.
  const urlNote = (() => {
    if (typeof location === 'undefined' || urlInvite || urlProfile) return null;
    const m = location.pathname.match(/^\/((?:note|nevent)1[a-z0-9]+)\/?$/i);
    const ref = m ? parseNostrRef(m[1].toLowerCase()) : null;
    return ref && ref.type === 'event' ? ref : null;
  })();
  // The app's history already holds this exact thread on a reload. Leave its
  // state and URL intact so wallet restore can paint the header and thread
  // together; the public deep-link path is only for a NEW visit.
  const restoringUrlThread = (() => {
    try { return !!urlNote && history.state?.nav?.noteThread?.focusId === urlNote.id; } catch { return false; }
  })();
  // The server renders /nevent1… and /note1… with the thread already in the
  // page (feed/note-page.js): the post, its root and replies, and their
  // authors' kind 0s, in a JSON script tag. Into the thread cache it goes,
  // in the shape a reload leaves there, so the thread opens from it with
  // names and faces on the first paint instead of after the relays answer.
  // No signature check: this data arrives in the same document as the code
  // that reads it (the server verified it off the relays).
  if (urlNote && !restoringUrlThread && typeof document !== 'undefined') {
    try {
      const el = document.getElementById('boot-thread');
      const d = el && JSON.parse(el.textContent);
      if (d && d.v === 1 && d.root && Array.isArray(d.replies)
        && [d.root, ...d.replies].some((e) => e && e.id === urlNote.id)) {
        const faces = {};
        for (const ev of d.profiles || []) {
          let m = null;
          try { m = JSON.parse(ev.content); } catch {}
          if (m && typeof m === 'object' && !Array.isArray(m) && ev.pubkey) {
            faces[ev.pubkey] = { name: m.display_name || m.name || null, picture: m.picture || null, eventAt: ev.created_at, t: Date.now() };
          }
        }
        createThreadStore().save({ root: d.root, replies: d.replies }, urlNote.id, faces, {}, d.quotes || []);
      }
    } catch {}
  }
  if (urlNote && !restoringUrlThread) {
    try { history.replaceState(null, '', '/'); } catch {}
    ui.pubProf = true;
    // holds the frame (screenView) until the thread opens, so the front door
    // never flashes up while the note is being found
    ui.pubNotePending = urlNote.id;
    // a reload of a thread the history restores by itself needs no fetch
    setTimeout(() => {
      if (ui.noteThread && ui.noteThread.focusId === urlNote.id) { ui.pubNotePending = null; return; }
      openNoteRef(urlNote).catch(() => {}).finally(() => { ui.pubNotePending = null; render(); });
    }, 0);
  }

  // /naddr1… of a live stream (kind 30311) opens the stream, public like a
  // note: a visitor watches over the front door. A reload the history
  // restores by itself needs nothing.
  const urlLive = (() => {
    if (typeof location === 'undefined' || urlInvite) return null;
    const m = location.pathname.match(/^\/(naddr1[a-z0-9]+)\/?$/i);
    let ref = null; try { ref = m ? parseNostrRef(m[1].toLowerCase()) : null; } catch {}
    return ref && ref.type === 'addr' && ref.kind === LIVE_KIND ? ref : null;
  })();
  if (urlLive && (() => { try { return history.state?.nav?.liveStream?.a !== LIVE_KIND + ':' + urlLive.pk + ':' + urlLive.d; } catch { return true; } })()) {
    try { history.replaceState(null, '', '/'); } catch {}
    ui.pubProf = true;
    ui.pubNotePending = 'live';
    setTimeout(() => { openLiveRef(urlLive).catch(() => {}).finally(() => { ui.pubNotePending = null; render(); }); }, 0);
  }

  // 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 (urlFeed) {
    ui.pubProf = true; ui.chatOpen = true; ui.msgView = 'feed';
    // hold the frame until the URL's feed is chosen: painted a tick early,
    // the feed view would open (and fetch) the default feed first
    ui.pubFeedPending = true;
    setTimeout(() => {
      ui.pubFeedPending = null;
      if (openFeedUrl(urlFeed.path, urlFeed.search)) return;
      ui.pubProf = null; ui.chatOpen = false; ui.msgView = null; // not a feed we know: the front door
      render();
    }, 0);
  }

  // (runs after construction: the caches it fills are declared further down)
  function seedBootProfile(path) {
    try {
      const el = typeof document !== 'undefined' && document.getElementById('boot-profile');
      const d = el && JSON.parse(el.textContent);
      if (!d || d.v !== 1 || !/^[0-9a-f]{64}$/.test(d.pk || '') || String(d.path || '').toLowerCase() !== path.toLowerCase()) return null;
      const pk = d.pk;
      for (const ev of [...(d.profiles || []), d.profile]) {
        if (ev && ev.kind === 0 && /^[0-9a-f]{64}$/.test(ev.pubkey || '')) applyProfile(ev.pubkey, ev);
      }
      // the page's own copy (not marked fetched: the relays still freshen it)
      if (d.profile && d.profile.pubkey === pk && !fullProfiles.has(pk)) {
        try { const m = JSON.parse(d.profile.content); if (m && typeof m === 'object' && !Array.isArray(m)) fullProfiles.set(pk, m); } catch {}
      }
      const notes = (d.notes || []).filter((e) => e && e.pubkey === pk && PROFILE_KINDS.includes(e.kind));
      if (notes.length && !notesCache.has(pk)) notesCache.set(pk, { status: 'ready', notes, fetchedAt: 0 });
      if (d.counts && !socialCounts.get(pk)?.at) {
        const num = (n) => (Number.isFinite(n) && n >= 0 ? n : null);
        socialCounts.set(pk, { follows: num(d.counts.follows), followers: num(d.counts.followers), at: Date.now() });
      }
      return pk;
    } catch { return null; }
  }
  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
      // The server renders profile links with the page already in them
      // (feed/profile-page.js): kind 0, latest posts, follow counts and the
      // faces the posts mention. Into the caches the page reads they go, so
      // it paints whole on its first frame; the usual fetches still freshen
      // it behind. A coinos name arrives already resolved.
      let pk = seedBootProfile(urlProfile) || 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(channelStream(jm, c).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 want = (k) => s.reasons?.[k] !== false;
    const reasons = { payment: want('payment'), zap: want('zap'), dm: want('dm'), mention: want('mention'), reaction: want('reaction'), call: want('call') };
    // 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('notifZap'), 'zap'),
      rowT(t('notifDm'), 'dm'),
      rowT(t('notifMention'), 'mention'),
      rowT(t('notifReaction'), 'reaction'),
      rowT(t('notifCall'), 'call'),
      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, inboxTries = 0;
  async function syncInbox({ force = false } = {}) {
    if (!force && Date.now() - inboxAt < 5 * 60_000) return;
    inboxAt = Date.now();
    try {
      const id = await identity();
      // the keys not there yet (a wallet still opening): try again shortly —
      // this used to count as done for five minutes, and a phone woken by a
      // push in that time had no key to open a DM or a call with
      if (!id) { if (++inboxTries <= 10) { inboxAt = 0; setTimeout(() => { syncInbox().catch(() => {}); }, 3000); } return; }
      inboxTries = 0;
      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()];
      // who may ring us when the app is shut: those we've written to (the
      // follows ride separately); `known` stays the DM filter's wider list
      const rings = known.filter((pk) => wroteTo(pk));
      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, rings, names, hasList: !!newest, updated: Date.now(),
        muted: [...mutesNow().set], // no buzz from a muted sender either
      });
    } 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 && !login.signer.interactive) 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;
  }

  // The channel entries of join material: id + name, plus key + epoch for a
  // private channel (a public one derives from the root, so nothing to carry).
  // Every entry carries key + epoch on the wire (CORD-05 §1 `{id, key, epoch,
  // name}`): a public channel's key IS the community_root at the base epoch.
  // Vector's parser has no default for either field, so an entry without them
  // fails its whole bundle — which is why our invite links never opened there.
  const channelList = (b) => (b.channels || []).slice(0, 256).map((c) =>
    channelIsPrivate(b, c) ? { id: c.id, name: c.name, key: c.key, epoch: c.epoch || 0 }
      : { id: c.id, name: c.name, key: b.community_root, epoch: b.root_epoch || 0 });

  // Join material subset (never the icon, never link fields). We don't
  // Refound ourselves, 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,
    ...(jm.control_pk ? { control_pk: jm.control_pk } : {}),
    channels: channelList(jm),
    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 (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;
      const have = s.communities.find((c) => c.community_id === e.community_id);
      if (have) {
        // Same community, fresher keys: a device that saw a Refounding holds
        // a higher root epoch; one that joined via a newer invite holds the
        // control_pk and channel keys this entry predates. Adopt, keep ours
        // otherwise — never step an epoch backwards.
        const newer = (jm.root_epoch || 0) > (have.root_epoch || 0);
        const fill = !newer && jm.community_root === have.community_root
          && ((jm.control_pk && !have.control_pk) || channelList(jm).some((c) => c.key && !(have.channels || []).some((h) => h.id === c.id && h.key)));
        if (!newer && !fill) continue;
        Object.assign(have, jmSubset(jm), { name: have.name || jm.name, relays: have.relays && have.relays.length ? have.relays : jm.relays });
        const stale = rooms.get(have.community_id); // rebuilt with the new keys on next open
        if (stale) {
          for (const u of stale.unsubs || []) { try { u(); } catch {} }
          for (const id of stale.wrapIds || []) seenWraps.delete(id);
          rooms.delete(have.community_id);
        }
        changed = true;
        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;
  }

  // The list writers remember what they last sent and when. A relay that
  // refuses a copy (rate limit, ban) leaves the remote copy stale, and the
  // next sync would ask for the same write again — and again, every couple
  // of seconds, forever: that storm filled relay.coinos.io's per-IP budget
  // for a whole household, and a phone behind the same IP could no longer
  // reach its remote signer (every NIP-46 request refused as rate-limited),
  // so its DMs stopped decrypting. An unchanged document is re-sent at most
  // once per LIST_REPUBLISH_MS; a real local change is a new document and
  // goes out at once. Our own writes echoing back on the live subscription
  // are not news either.
  const LIST_REPUBLISH_MS = 5 * 60_000;
  const lastListWrite = new Map(); // 'lists' | 'frags' -> { key, at }
  const ownListIds = new Set();
  function listWriteDue(what, key) {
    const prev = lastListWrite.get(what);
    if (prev && prev.key === key && Date.now() - prev.at < LIST_REPUBLISH_MS) return false;
    lastListWrite.set(what, { key, at: Date.now() });
    return true;
  }
  async function publishLists() {
    const ids = await selfCryptors();
    const s = st();
    publishFragments(ids, fragAt).catch(() => {});
    const docs = [[13302, buildCommunityList(s)], [13303, buildInviteList(s)]];
    if (!listWriteDue('lists', ids.map((i) => i.pk).join() + '|' + docs.map(([k, d]) => k + ':' + d).join('|'))) return;
    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),
          });
          ownListIds.add(evt.id);
          publishOn(DM_RELAYS, evt);
        } catch {}
      }
  }

  // ---- CORD-02 §8 fragmented Community List (kind 33302) ----
  // The form Vector and the other Concord clients write: addressable, one
  // event per fragment (d = index, every fragment declares the total), the
  // content NIP-44-encrypted to self, every 32-byte value unpadded base64url,
  // an entry's embedded join material carrying no community_id (it inherits
  // the entry's) and no seed when it equals current. Reading it is what lets
  // a community joined in Vector under the same key show up here; writing it
  // is what lets Vector see one joined here. The retired single-event 13302
  // is still read and written for older coinos devices.
  const LIST_FRAG_KIND = 33302;
  const STOCK_RELAYS = ['wss://jskitty.com/nostr', 'wss://asia.vectorapp.io/nostr', 'wss://relay.ditto.pub', 'wss://relay.dreamith.to'];
  const LIST_FRAG_BYTES = 48 * 1024;
  const b64of = (v) => (/^[0-9a-f]{64}$/i.test(v || '') ? base64urlnopad.encode(hexToBytes(v.toLowerCase())) : v);
  const hexOf = (v) => {
    if (typeof v !== 'string' || v.length !== 43) return v;
    try { const b = base64urlnopad.decode(v); return b.length === 32 ? bytesToHex(b) : v; } catch { return v; }
  };
  // where a list can live: our relays, the stock CORD set (where Vector's
  // lands when its own relays refuse the kind), and every held community's
  const listRelays = () => [...new Set([...DM_RELAYS, ...STOCK_RELAYS, ...communities().flatMap((jm) => jm.relays || [])])].slice(0, 12);
  const fragMaterial = (jm) => {
    const m = jmSubset(jm);
    return {
      owner: b64of(m.owner), owner_salt: b64of(m.owner_salt), community_root: b64of(m.community_root), root_epoch: m.root_epoch || 0,
      ...(m.control_pk ? { control_pk: b64of(m.control_pk) } : {}),
      channels: (m.channels || []).map((c) => ({ id: b64of(c.id), key: b64of(c.key || m.community_root), epoch: c.epoch || 0, name: c.name })),
      relays: m.relays || [], name: m.name,
    };
  };
  const buildFragments = (s) => {
    const entries = s.communities.filter((jm) => (s.tombstones[jm.community_id] || 0) <= (jm.added_at || 0))
      .map((jm) => ({ community_id: b64of(jm.community_id), current: fragMaterial(jm), added_at: jm.added_at || 0 }));
    const tombstones = Object.entries(s.tombstones).map(([community_id, removed_at]) => ({ community_id: b64of(community_id), removed_at }));
    const frags = [{ frags: 1, entries: [], tombstones: [] }];
    const size = (f) => JSON.stringify(f).length;
    for (const e of entries) {
      const last = frags[frags.length - 1];
      if (!last.entries.length || size(last) + JSON.stringify(e).length < LIST_FRAG_BYTES) last.entries.push(e);
      else frags.push({ frags: 1, entries: [e], tombstones: [] });
    }
    for (const t of tombstones) {
      const last = frags[frags.length - 1];
      if (!last.tombstones.length || size(last) + JSON.stringify(t).length < LIST_FRAG_BYTES) last.tombstones.push(t);
      else frags.push({ frags: 1, entries: [], tombstones: [t] });
    }
    for (const f of frags) f.frags = frags.length;
    return frags;
  };
  const unmaterial = (m, cid) => ({
    community_id: cid, owner: hexOf(m.owner), owner_salt: hexOf(m.owner_salt), community_root: hexOf(m.community_root),
    root_epoch: Number(m.root_epoch) || 0, ...(m.control_pk ? { control_pk: hexOf(m.control_pk) } : {}),
    channels: (m.channels || []).map((c) => ({ id: hexOf(c.id), ...(c.key ? { key: hexOf(c.key) } : {}), epoch: Number(c.epoch) || 0, name: c.name })),
    relays: Array.isArray(m.relays) ? m.relays : [], name: m.name || '',
  });
  // the fragments a reader holds, unioned into the 13302-shaped document
  const defragment = (frags) => {
    const doc = { entries: [], tombstones: [] };
    for (const f of frags) {
      for (const e of f.entries || []) {
        if (!e || !e.current) continue;
        const cid = hexOf(e.community_id);
        const current = unmaterial(e.current, cid);
        doc.entries.push({ community_id: cid, seed: e.seed ? unmaterial(e.seed, cid) : current, current, added_at: Number(e.added_at) || 0 });
      }
      for (const t of f.tombstones || []) doc.tombstones.push({ community_id: hexOf(t.community_id), removed_at: Number(t.removed_at) || 0 });
    }
    return doc;
  };
  // Fetch one identity's fragments: newest per index wins (an age tie falls to
  // the lower id), the newest fragment's declared total governs, and each
  // index's created_at is kept so a rewrite can exceed it.
  async function readFragments(id, evs) {
    const newest = new Map();
    for (const e of evs) {
      if (e.kind !== LIST_FRAG_KIND || e.pubkey !== id.pk) continue;
      const idx = parseInt(e.tags.find((t) => t[0] === 'd')?.[1], 10);
      if (!(idx >= 0)) continue;
      const cur = newest.get(idx);
      if (!cur || e.created_at > cur.created_at || (e.created_at === cur.created_at && e.id < cur.id)) newest.set(idx, e);
    }
    const frags = new Map(); const createdAt = {};
    for (const [idx, e] of newest) {
      try { const f = JSON.parse(await id.dec(e.content)); if (f && typeof f === 'object') { frags.set(idx, f); createdAt[idx] = e.created_at; } } catch {}
    }
    if (!frags.size) return null;
    let top = null; for (const [idx, f] of frags) if (!top || createdAt[idx] > createdAt[top] || (createdAt[idx] === createdAt[top] && (f.frags || 1) > (frags.get(top).frags || 1))) top = idx;
    const declared = Math.max(1, Number(frags.get(top).frags) || 1);
    const live = [...frags.entries()].filter(([idx]) => idx < declared).map(([, f]) => f);
    return { doc: defragment(live), createdAt, declared, complete: live.length === declared };
  }
  async function publishFragments(ids, prevAt = {}) {
    const s = st();
    const frags = buildFragments(s);
    if (!listWriteDue('frags', ids.map((i) => i.pk).join() + '|' + JSON.stringify(frags))) return;
    const now = Math.floor(Date.now() / 1000);
    for (const id of ids)
      for (let i = 0; i < frags.length; i++) {
        try {
          const created_at = Math.max(now, ((prevAt[id.pk] || {})[i] || 0) + 1);
          const evt = await id.sign({ kind: LIST_FRAG_KIND, tags: [['d', String(i)]], content: await id.enc(JSON.stringify(frags[i])), created_at });
          ownListIds.add(evt.id);
          publishOn(listRelays(), evt);
        } catch {}
      }
  }

  let listsSynced = false;
  let listsSyncedAt = 0;
  let listLiveSub = null;
  const fragAt = {}; // pk -> { index: created_at } as last read
  // Re-sync is cheap and a join made in another client should show up soon
  // after: the home view asks again after a minute, and a live subscription
  // on the fragment kind brings a fresh write straight in.
  async function syncLists({ force = false } = {}) {
    if (listsSynced && !force) return;
    const ids = await selfCryptors();
    if (!ids.length) return;
    listsSynced = true; listsSyncedAt = Date.now();
    const authors = ids.map((i) => i.pk);
    const [evs, fragEvs] = await Promise.all([
      queryOn(DM_RELAYS, { kinds: [13302, 13303], authors }, 3500),
      queryOn(listRelays(), { kinds: [LIST_FRAG_KIND], authors }, 4500),
    ]);
    if (!listLiveSub) {
      listLiveSub = subscribeOn(listRelays(), { kinds: [LIST_FRAG_KIND], authors, since: Math.floor(Date.now() / 1000) }, (e) => {
        if (ownListIds.has(e.id)) return; // our own write coming back is not news
        // another device writing: read it soon, but never faster than once
        // every ten seconds — a device stuck rewriting must not drag every
        // other one into a query storm alongside it
        const wait = Math.max(1500, 10_000 - (Date.now() - listsSyncedAt));
        clearTimeout(listLiveSub.t); listLiveSub.t = setTimeout(() => syncLists({ force: true }).catch(() => {}), wait);
      });
      allUnsubs.push(() => { try { listLiveSub(); } catch {} listLiveSub = null; });
    }
    let changed = false;
    const remoteDocs = new Set();
    const remoteLive = new Set(); let anyFrag = false;
    for (const id of ids) {
      const got = await readFragments(id, fragEvs);
      if (!got) continue;
      anyFrag = true; fragAt[id.pk] = got.createdAt;
      for (const e of got.doc.entries) if (!(got.doc.tombstones.find((t) => t.community_id === e.community_id)?.removed_at > e.added_at)) remoteLive.add(e.community_id);
      changed = mergeCommunityList(got.doc) || changed;
    }
    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 {}
      }
    healInviteBundles().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();
    // the fragmented form: write it when no copy exists, or ours knows a
    // membership (or a leave) the relay copy doesn't
    const localLive = s.communities.filter((jm) => (s.tombstones[jm.community_id] || 0) <= (jm.added_at || 0)).map((jm) => jm.community_id);
    const fragStale = !anyFrag || localLive.some((cid) => !remoteLive.has(cid)) || [...remoteLive].some((cid) => !localLive.includes(cid) && s.tombstones[cid]);
    if (fragStale && (localLive.length || Object.keys(s.tombstones).length)) publishFragments(ids, fragAt);
  }

  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, wnId) {
    if (!peer || !rumor.id) return;
    threadOf(peer).set(rumor.id, wnId ? { rumor, mine, wn: wnId } : { 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');
    // an interactive signer (Amber by intent) is a trip through another app
    // per call: never for a wrap that arrives on its own
    if (login && login.signer && login.signer.decryptFrom && !login.signer.interactive) 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.
  //
  // A linked login whose signer is NOT live (a reload before the bunker
  // resumed, or a session selfHealing just dropped) is incomplete, not
  // "nothing to wait for": counting those passes gave every wrap sealed to
  // the login npub up after ~40 s with only the wallet key tried, and the
  // wrap log then hid it from every later session (a phone kept 9 of 186
  // messages). An interactive signer (Amber by intent) never decrypts here
  // either, so it is incomplete too: counted as complete, every wrap sealed
  // to the login npub was given up on the wallet key and logged as opened
  // — an Amber user's threads held only what that device had sent.
  function decryptorsComplete() {
    const login = hook('nostrLoginIdentity');
    return !login || !!(login.signer && !login.signer.interactive && login.signer.decryptFrom);
  }
  // an Amber-by-intent account, whether or not its signer has woken yet:
  // a wallet whose every wrap was already logged never wakes it, and then
  // never said why its messages were missing
  const interactiveLogin = () => {
    const l = hook('nostrLoginIdentity');
    return !!l && (l.signer ? !!l.signer.interactive : l.via === 'amber');
  };
  // Wraps logged while an interactive signer stood in for the login npub
  // may be messages no key here ever tried. Once a signer that can decrypt
  // takes over (Amber reconnected over NIP-46), the heal pass re-opens
  // every wrap the relays still hold.
  function noteSignerGap() {
    const s = st();
    if (interactiveLogin()) { if (!s.dmSignerGap) { s.dmSignerGap = true; save(s); } return; }
    if (!s.dmSignerGap || !decryptorsComplete()) return;
    delete s.dmSignerGap;
    s.dmHeal = 0;
    save(s);
    wrapLog = null; healed.clear(); seenWraps.clear();
    if (dmStarted) resubscribeStreams();
  }

  // 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((e) => { if (SIGNER_SILENT.test(e?.message || '')) throw e; return null; });
  }

  // true: opened. false: not ours. 'later': a remote signer never answered,
  // so nothing is known yet — the wrap must be tried again, uncounted.
  async function openInboxWrap(wrap, heal = false) {
    const g = session;
    for (const d of dmDecryptors()) {
      let got;
      try { got = await unwrapDMAny(wrap, d); } catch { return g === session ? 'later' : 'stale'; }
      if (g !== session) return 'stale'; // opened with the previous account's key
      if (!got) continue;
      if (heal && ![7, 14, 15].includes(got.rumor.kind)) return true;
      if (got.rumor.kind === 14 || got.rumor.kind === 15) {
        // 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);
        // a message that neither comes from nor names this identity isn't
        // this account's conversation, however it reached us
        if (!mine && !(got.rumor.tags || []).some((x) => x[0] === 'p' && isMe(x[1]))) return true;
        const to = got.rumor.tags?.find((x) => x[0] === 'p')?.[1];
        const peer = mine ? (to || got.peer || got.author) : got.author;
        noteEmoji(got.rumor);
        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];
        noteEmoji(got.rumor);
        if (target) {
          const key = target + '|' + got.author;
          const at = got.rumor.created_at * 1000;
          if (at >= (dmReactAt.get(key) || 0)) {
            dmReactAt.set(key, at);
            (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 {}
      } else if (got.rumor.kind === 444 && !isMe(got.author)) {
        // a White Noise invitation: the group itself says who is asking
        whiteNoise().then((c) => c && c.welcome(got.rumor)).catch(() => {});
      } else if (got.rumor.kind === CALL_LOG && isMe(got.author)) {
        // a call, as one of our devices logged it, under the person it was with
        const with_ = got.rumor.tags?.find((x) => x[0] === 'p')?.[1];
        if (with_ && /^[0-9a-f]{64}$/.test(with_)) { noteDM(with_, got.rumor, true); persistDms(); }
      }
      return true;
    }
    return false;
  }

  async function handleInboxWrap(wrap) {
    let heal = false;
    if (seenWraps.has(wrap.id) || seenWraps.has(wrapKey(wrap.id))) {
      noteWrapItem(wrap.id, wrap.created_at); // known by its prefix alone: now held in full
      if (!healing(wrap)) return;
      heal = true;
    }
    seenWraps.add(wrap.id);
    const r = await openInboxWrap(wrap, heal);
    if (r === 'stale') return;
    if (r === true) { rememberWrap(wrap.id, wrap.created_at); return; }
    if (pendingWraps.size >= PENDING_MAX) pendingWraps.delete(pendingWraps.keys().next().value);
    pendingWraps.set(wrap.id, { wrap, heal, tries: r !== 'later' && 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);
      // Still no login signer: a pass would only re-run the wallet key, which
      // already had its try when each wrap arrived. Wait for the signer
      // (nostrSignerLive or the slow retry below) instead.
      const complete = decryptorsComplete();
      if (!complete || !dmDecryptors().length) return;
      // 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;
        const r = await openInboxWrap(p.wrap, p.heal);
        if (r === 'stale') break; // the account changed under this pass
        if (r === true) { pendingWraps.delete(id); rememberWrap(id, p.wrap && p.wrap.created_at); }
        else if (r === 'later') break; // the signer went quiet — nothing learned, try the rest later
        else if (complete && ++p.tries >= PENDING_TRIES) { pendingWraps.delete(id); rememberWrap(id, p.wrap && p.wrap.created_at); }
        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
      // (in finally: an early return above must not end the retries)
      if (pendingWraps.size) scheduleDrain(decryptorsComplete() ? 30_000 : 60_000);
      healDone();
    }
  }

  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;
    if (interactiveLogin()) noteSignerGap();
    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;
      }
      // a row from someone who is neither us nor the peer: another
      // identity's conversation, saved here by an account switch mid-decrypt
      // (fixed — see session). The whole thread goes; ours refetches.
      if (list.some((m) => !isMe(m.from) && m.from !== peer)) {
        delete s.dms[peer];
        swept = true;
        continue;
      }
      for (const m of list) threadOf(peer).set(m.id, { rumor: rumorFromRow(m), mine: isMe(m.from) });
    }
    bumpMsgRev();
    if (swept) save(s);
    const onWrap = (wrap) => { handleInboxWrap(wrap).catch(() => {}); };
    const plainDmSub = (relays) => {
      const u = subscribeOn(relays, { kinds: [1059], '#p': pks, limit: 400 }, onWrap, { onclose: noteSubClosed });
      allUnsubs.push(u); dmUnsubs.push(u);
    };
    // Relay by relay. One that speaks negentropy gets the live subscription
    // with limit 0 — opened first, so nothing slips between — and a
    // reconciliation of the wraps we hold against its newest four hundred,
    // the ones we lack fetched by id. One that doesn't (nos.lol has it
    // disabled; remembered for a day) is asked the old way, its newest
    // wraps re-served and skipped by the prefix log. So is every relay
    // while the one-time heal is running: that pass wants them re-served.
    const dmSub = (relays) => {
      for (const relay of relays) {
        if (healSince || negentropyOff(relay)) { plainDmSub([relay]); continue; }
        const u = subscribeOn([relay], { kinds: [1059], '#p': pks, limit: 0 }, onWrap, { onclose: noteSubClosed });
        allUnsubs.push(u); dmUnsubs.push(u);
        reconcileWraps(relay).then((ok) => {
          if (ok || !dmStarted || !dmUnsubs.includes(u)) return;
          // it doesn't speak it after all: the plain subscription, with its backlog
          try { u(); } catch {}
          allUnsubs = allUnsubs.filter((x) => x !== u); dmUnsubs = dmUnsubs.filter((x) => x !== u);
          plainDmSub([relay]);
        }).catch(() => {});
      }
    };
    async function reconcileWraps(relay) {
      const r = await reconcileOn(relay, { kinds: [1059], '#p': pks, limit: 400 }, wrapItemsHeld());
      if (!r) return false;
      dlog('dm: ' + relay + ' reconciled: ' + r.need.length + ' wraps to fetch, ' + r.have.length + ' held it lacks');
      for (let i = 0; i < Math.min(r.need.length, 600) && dmStarted; i += 100) {
        const evs = await queryOn([relay], { ids: r.need.slice(i, i + 100) }, 6000);
        for (const w of evs) onWrap(w);
      }
      return true;
    }
    dmSub(DM_RELAYS);
    // calls ringing in (ephemeral wraps: only what comes while we listen)
    const callSub = (relays, authed) => {
      const f = { kinds: [CALL_WRAP], '#p': pks, since: Math.floor(Date.now() / 1000) - 20 };
      const on = (w) => { onCallWrap(w).catch(() => {}); };
      const u = authed ? subscribeAuthed(relays, f, on, { onauth: relayAuth, onclose: noteSubClosed }) : subscribeOn(relays, f, on, { onclose: noteSubClosed });
      allUnsubs.push(u); dmUnsubs.push(u);
    };
    callSub(DM_RELAYS, false);
    // 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))
          // every inbox the list names: a sender may deliver to just one of
          // them (crypticCypher's replies reached only primal, the 4th extra
          // in Adam's list, while a cap of three read the first three)
          .slice(0, 8);
        ownInbox = extras;
        if (extras.length && dmStarted) callSub(extras, true);
        // inbox relays are often NIP-42 gated: authenticate as the identity
        if (extras.length && dmStarted) {
          const u = subscribeAuthed(extras, { kinds: [1059], '#p': pks, limit: 400 }, (wrap) => {
            handleInboxWrap(wrap).catch(() => {});
          }, { onauth: relayAuth, onclose: noteSubClosed });
          allUnsubs.push(u); dmUnsubs.push(u);
        }
      } 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; }
    const road = await wnRoute(peer).catch(() => null);
    if (road) return sendWnDirect(peer, road, text);
    // 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;
    ui.emojiAc = null;
    const rumor = makeDMRumor(id.pubkey, peer, text, [...(replyTo ? [['e', replyTo]] : []), ...outboundEmojiTags(text, emojiUrl)]);
    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);
      toOwnInbox(toSelf);
      fetchInboxRelays(peer).then((inbox) => {
        const extra = inbox.slice(0, 4).filter((r) => !DM_RELAYS.includes(r));
        if (extra.length) publishOn(extra, toPeer, { onauth: relayAuth });
      }).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;
    // a reaction travels with the message it answers
    if (m.wn) { const g = findGroup(m.wn); if (g) sendWnReaction(g, m, emoji); return; }
    const rumor = makeDMReaction(id.pubkey, peer, m.rumor.id, emoji, reactEmojiTags(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);
    dmReactAt.set(m.rumor.id + '|' + id.pubkey, rumor.created_at * 1000);
    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);
      toOwnInbox(toSelf);
      fetchInboxRelays(peer).then((inbox) => {
        const extra = inbox.slice(0, 4).filter((x) => !DM_RELAYS.includes(x));
        if (extra.length) publishOn(extra, toPeer, { onauth: relayAuth });
      }).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();
    }
  }

  // A cached DM row. A file message (kind 15) keeps its kind and tags — the
  // url alone is an encrypted blob, and without the key and nonce a reload
  // turned the picture into a bare link.
  function rowOf(rumor) {
    const row = { id: rumor.id, from: rumor.pubkey, text: rumor.content, t: rumor.created_at };
    if (rumor.kind === 15) {
      row.k = 15;
      row.tg = (rumor.tags || []).filter((x) => x[0] !== 'p');
    } else if (rumor.kind === CALL_LOG) {
      // a call: its who, how and how long are all in its tags
      row.k = CALL_LOG;
      row.tg = rumor.tags || [];
    } else {
      // a message's custom emoji ride along, or they'd be text after a reload
      const em = [...emojiTagMap(rumor.tags)];
      if (em.length) row.em = em;
    }
    return row;
  }
  function rumorFromRow(m) {
    return {
      id: m.id, pubkey: m.from, content: m.text, created_at: m.t, kind: m.k || 14,
      tags: m.tg || (m.em || []).map(([c, u]) => ['emoji', c, u]),
    };
  }

  // The cache is shared by every tab of this wallet, and each tab only holds
  // the messages IT has seen: a tab left asleep since yesterday used to
  // rewrite the cache from its own memory and erase what another tab had
  // received meanwhile — while the wrap log still said those were opened, so
  // nothing ever fetched them again. Rows are merged by id with what's
  // stored; the fuller row (the one carrying file fields) wins.
  function persistDms() {
    const s = st();
    const merged = new Map(); // peer -> Map(id -> row)
    for (const [peer, list] of Object.entries(s.dms || {}))
      merged.set(peer, new Map(list.map((r) => [r.id, r])));
    for (const [peer, m] of threads) {
      const rows = merged.get(peer) || merged.set(peer, new Map()).get(peer);
      for (const e of m.values()) {
        if (e.pending || e.wn) continue;
        const row = rowOf(e.rumor);
        const had = rows.get(row.id);
        if (!had || !had.tg || row.tg) rows.set(row.id, row);
      }
    }
    const byRecent = [...merged.entries()]
      .map(([peer, rows]) => [peer, [...rows.values()].sort((a, b) => a.t - b.t)])
      .filter(([, list]) => list.length)
      .sort((a, b) => (b[1].at(-1)?.t || 0) - (a[1].at(-1)?.t || 0))
      .slice(0, 30);
    s.dms = {};
    for (const [peer, list] of byRecent) s.dms[peer] = list.slice(-CACHE_MAX);
    save(s);
  }

  // ---- White Noise (Marmot) -----------------------------------------------
  // The third way a conversation can travel, and the one nobody should have
  // to choose: MLS groups over nostr, the protocol the White Noise app
  // speaks. A two-person group with no name IS a direct message — it lands
  // in the same thread as that person's NIP-17 messages, and a reply goes
  // back the way their last message came. Groups with a name or more people
  // get rows of their own, beside the DMs. The MLS code is a chunk of its
  // own (marmot-client.js), fetched once a wallet is open.

  let wn = null;        // the client for the identity we speak as
  let wnReadied = false; // asked (once a session) to make us invitable
  let wnLoading = null; // { pk, p } while it loads
  const wnReactOf = new Map(); // reaction event id -> { target, pk }: what a later delete undoes

  function whiteNoise() {
    const pk = identityPk();
    if (!pk || !wallet._cacheKey) return Promise.resolve(null);
    if (wn && wn.pubkey === pk) return Promise.resolve(wn);
    if (wnLoading && wnLoading.pk === pk) return wnLoading.p;
    if (wn) { try { wn.stop(); } catch {} wn = null; }
    const p = import('../marmot-client.js').then(async (m) => {
      if (identityPk() !== pk) return null; // the identity changed while the chunk loaded
      // the relays new groups are founded on can be pointed elsewhere (dev and tests)
      let relays = null;
      try { relays = JSON.parse(localStorage.getItem('coinos-group-relays') || 'null'); } catch {}
      const c = m.marmotClient({
        scope: wallet._cacheKey() + ':' + pk, pubkey: pk, identity, on: onWn, subClosed: noteSubClosed,
        ...(Array.isArray(relays) && relays.length ? { relays } : {}),
      });
      wn = c;
      wnLoading = null;
      await c.start();
      return c;
    }).catch((e) => { console.warn('chat: group chats unavailable', e); wnLoading = null; return null; });
    wnLoading = { pk, p };
    return p;
  }

  // Cordn groups (cordn-client.js): MLS again, delivered by a coordinator
  // instead of relays. The same interface as the White Noise client, so the
  // group screens below drive either; gClient(g) says which one a group is.
  let cd = null, cdLoading = null, cdReadied = false;
  function cordnChat() {
    const pk = identityPk();
    if (!pk || !wallet._cacheKey) return Promise.resolve(null);
    if (cd && cd.pubkey === pk) return Promise.resolve(cd);
    if (cdLoading && cdLoading.pk === pk) return cdLoading.p;
    if (cd) { try { cd.stop(); } catch {} cd = null; }
    const p = import('../cordn-client.js').then(async (m) => {
      if (identityPk() !== pk) return null;
      let coordinator = null;
      try { coordinator = JSON.parse(localStorage.getItem('coinos-cordn-coordinator') || 'null'); } catch {}
      const c = m.cordnClient({
        scope: wallet._cacheKey() + ':' + pk, pubkey: pk, identity, on: onCd, subClosed: noteSubClosed,
        ...(coordinator && coordinator.pubkey ? { coordinator } : {}),
      });
      cd = c;
      cdLoading = null;
      await c.start();
      return c;
    }).catch((e) => { console.warn('chat: cordn groups unavailable', e); cdLoading = null; return null; });
    cdLoading = { pk, p };
    return p;
  }
  function onCd(type, g, data) {
    if (!cd) return;
    if (type === 'message') { try { noteEmoji(data); } catch {} }
    wnFolds.delete(g && g.id);
    bumpMsgRev();
    scheduleRepaint();
  }
  const gClient = (g) => (g && g.cordn ? cd : wn);
  const findGroup = (id) => (wn && wn.groups.get(id)) || (cd && cd.groups.get(id)) || null;

  // One delivered event of a direct group, into that person's thread.
  function wnIntoThread(g, peer, m) {
    const th = threadOf(peer);
    const target = (m.tags.find((x) => x[0] === 'e') || [])[1];
    if (m.kind === 7 || m.kind === 9) noteEmoji(m); // a :code: with its picture (NIP-30 tag): learned, so the chip draws it
    if (m.kind === 9) {
      if (!th.has(m.id) || th.get(m.id).pending) th.set(m.id, { rumor: m, mine: isMe(m.pubkey), wn: g.id });
    } else if (m.kind === 7 && target) {
      const key = target + '|' + m.pubkey, at = m.created_at * 1000;
      if (at >= (dmReactAt.get(key) || 0)) {
        dmReactAt.set(key, at);
        (dmReacts.get(target) || dmReacts.set(target, new Map()).get(target)).set(m.pubkey, m.content);
        wnReactOf.set(m.id, { target, pk: m.pubkey });
      }
    } else if (m.kind === 5) {
      // only the author takes a message (or a reaction) back
      for (const [, id] of m.tags.filter((x) => x[0] === 'e')) {
        const hit = th.get(id);
        if (hit && hit.rumor.pubkey === m.pubkey) th.delete(id);
        const r = wnReactOf.get(id);
        if (r && r.pk === m.pubkey) dmReacts.get(r.target)?.delete(r.pk);
      }
    } else if (m.kind === 1009 && target) {
      const hit = th.get(target);
      if (hit && hit.rumor.pubkey === m.pubkey) th.set(target, { ...hit, rumor: { ...hit.rumor, content: m.content }, edited: true });
    }
  }

  function wnReplay() {
    if (!wn) return;
    for (const g of wn.groups.values()) {
      const peer = wn.peer(g);
      if (!peer) continue;
      if (g.fresh) wn.accept(g); // a direct message needs no invitation card
      for (const m of g.log) wnIntoThread(g, peer, m);
    }
  }

  function onWn(type, g, data) {
    if (!wn) return;
    if (type === 'message') {
      const peer = wn.peer(g);
      if (peer) wnIntoThread(g, peer, data);
      try { noteEmoji(data); } catch {}
    } else if (type === 'loaded' || type === 'joined') wnReplay();
    else if (type === 'withdrawn') for (const th of threads.values()) for (const id of data) th.delete(id);
    wnFolds.delete(g && g.id);
    bumpMsgRev();
    scheduleRepaint();
  }

  // The live direct group with this person (the newest, if a chat was remade).
  function wnDirect(peer) {
    if (!wn) return null;
    let best = null;
    for (const g of wn.groups.values())
      if (!g.removed && !g.leaving && wn.peer(g) === peer && (!best || g.at > best.at)) best = g;
    return best;
  }

  // Which way a message to this person travels: a group record, 'new' (found
  // a direct group first), or null for NIP-17. A reply goes back the way
  // their last message came. A first message goes by White Noise only to
  // someone whose KeyPackage was published by another app: a coinos wallet
  // reads NIP-17 on every device it has, where an MLS group reaches just the
  // one device whose KeyPackage was picked. A route pinned by hand in the
  // thread header (st().route) overrides all of that.
  const wnTheirs = (peer) => {
    let theirs = null;
    for (const m of threads.get(peer)?.values() || [])
      if (!m.mine && (!theirs || m.rumor.created_at > theirs.rumor.created_at)) theirs = m;
    return theirs;
  };
  const routePref = (peer) => (st().route || {})[peer] || 'auto';
  async function wnRoute(peer) {
    const c = await whiteNoise();
    if (!c) return null;
    await c.load();
    const pref = routePref(peer);
    if (pref === 'nip17') return null;
    const g = wnDirect(peer);
    const lookup = () => Promise.race([c.lookup(peer), new Promise((r) => setTimeout(() => r(null), 3500))]);
    if (pref === 'wn') return g || ((await lookup()) ? 'new' : null);
    const theirs = wnTheirs(peer);
    if (g) return theirs && !theirs.wn ? null : g;
    if (theirs) return null;
    const cand = await lookup();
    return cand && cand.client !== 'coinos' ? 'new' : null;
  }

  // The same decision without waiting, for the thread header: which way the
  // next message will go and what was pinned — or null when there is nothing
  // to choose (they are not on White Noise, or only through another coinos
  // wallet, where NIP-17 is simply the better road).
  const wnCands = new Map(); // peer -> { at, cand } : their KeyPackage, as last looked up
  function wnKnow(peer) {
    const hit = wnCands.get(peer);
    if (hit && Date.now() - hit.at < 10 * 60_000) return;
    wnCands.set(peer, { at: Date.now(), cand: hit ? hit.cand : undefined });
    whiteNoise().then((c) => (c ? c.lookup(peer) : null)).then((cand) => {
      wnCands.set(peer, { at: Date.now(), cand: cand || null });
      scheduleRepaint();
    }).catch(() => {});
  }
  function routeChoice(peer) {
    if (!wn) return null;
    const g = wnDirect(peer), cand = (wnCands.get(peer) || {}).cand;
    if (!g && !(cand && cand.client !== 'coinos')) return null;
    const pref = routePref(peer), theirs = wnTheirs(peer);
    const auto = g ? (theirs && !theirs.wn ? 'nip17' : 'wn') : (theirs ? 'nip17' : 'wn');
    return { pref, now: pref === 'auto' ? auto : pref };
  }
  function setRoute(peer, pref) {
    const s = st();
    s.route ||= {};
    if (pref === 'auto') delete s.route[peer]; else s.route[peer] = pref;
    save(s);
  }

  async function sendWnDirect(peer, road, text) {
    const c = wn;
    const replyTo = ui.msgReplyTo && threadOf(peer).has(ui.msgReplyTo) ? ui.msgReplyTo : null;
    ui.msgReplyTo = null;
    ui.emojiAc = null;
    const inner = c.event(9, text, [...(replyTo ? [['e', replyTo]] : []), ...outboundEmojiTags(text, emojiUrl)]);
    const entry = { rumor: inner, mine: true, pending: true, wn: true };
    threadOf(peer).set(inner.id, entry);
    clearDraft('dm:' + peer);
    ui.msgStick = true;
    render();
    try {
      const g = road === 'new' ? await c.create({ members: [peer] }) : road;
      entry.wn = g.id;
      if (!(await c.send(g, inner))) throw new Error(t('msgSendFailed'));
      delete entry.pending;
      render();
    } catch (e) {
      threadOf(peer).delete(inner.id);
      toast(e.message === 'no signer' ? t('msgNoIdentity') : (e.message || String(e)));
      render();
    }
  }

  async function sendWnReaction(g, m, emoji) {
    const wn = gClient(g);
    const inner = wn.event(7, emoji, [['e', m.rumor.id], ['p', m.rumor.pubkey], ['k', String(m.rumor.kind)], ...reactEmojiTags(emoji)]);
    const ok = await wn.send(g, inner).catch(() => false);
    if (!ok) { toast(t('msgSendFailed')); return; }
    onWn('message', g, inner);
  }

  // ---- groups ----

  const wnRead = (id) => 'wn:' + id;
  // groups with a screen of their own (a direct group lives in its DM thread)
  const wnGroups = () => [...(wn ? [...wn.groups.values()].filter((g) => !wn.peer(g)) : []), ...(cd ? cd.groups.values() : [])];

  function wnTitle(g) {
    const c = gClient(g);
    const v = c.view(g);
    if (v.name) return v.name;
    const others = c.accounts(g).filter((pk) => !isMe(pk));
    return others.length ? others.slice(0, 3).map(displayName).join(', ') : t('msgGroupUnnamed');
  }

  // A group's log folded for the screen: chat and system rows in time order
  // (edits applied, deletions gone) and who reacted with what.
  const wnFolds = new Map(); // gid -> { n, last, rows, reacts }
  function wnFold(g) {
    const memo = wnFolds.get(g.id), last = g.log.length ? g.log[g.log.length - 1].id : '';
    if (memo && memo.n === g.log.length && memo.last === last) return memo;
    const byId = new Map(), reacts = new Map(), reactOf = new Map();
    const sorted = [...g.log].sort((a, b) => a.created_at - b.created_at);
    for (const m of sorted) if (m.kind === 9 || m.kind === 1210) byId.set(m.id, { rumor: m, mine: isMe(m.pubkey), wn: g.id });
    for (const m of sorted) {
      const target = (m.tags.find((x) => x[0] === 'e') || [])[1];
      if (m.kind === 7 || m.kind === 9) noteEmoji(m); // (a group's :marmot: came as text: its tag was never read)
      if (m.kind === 7 && target) {
        (reacts.get(target) || reacts.set(target, new Map()).get(target)).set(m.pubkey, m.content);
        reactOf.set(m.id, { target, pk: m.pubkey });
      } else if (m.kind === 5) {
        for (const [, id] of m.tags.filter((x) => x[0] === 'e')) {
          const hit = byId.get(id);
          if (hit && hit.rumor.pubkey === m.pubkey && hit.rumor.kind === 9) byId.delete(id);
          const r = reactOf.get(id);
          if (r && r.pk === m.pubkey) reacts.get(r.target)?.delete(r.pk);
        }
      } else if (m.kind === 1009 && target) {
        const hit = byId.get(target);
        if (hit && hit.rumor.pubkey === m.pubkey) byId.set(target, { ...hit, rumor: { ...hit.rumor, content: m.content }, edited: true });
      }
    }
    const fold = { n: g.log.length, last, rows: [...byId.values()], reacts };
    wnFolds.set(g.id, fold);
    return fold;
  }
  const wnChat = (g) => wnFold(g).rows.filter((m) => m.rumor.kind === 9);
  const wnNewest = (g) => newestFrom(wnChat(g), (m) => !m.mine);
  const wnUnread = (g) => !g.fresh && wnNewest(g) > (st().read[wnRead(g.id)] || 0);

  // "Ana added Ben", from a locally derived kind-1210 row
  function wnSystemText(m) {
    let c;
    try { c = JSON.parse(m.content); } catch { return ''; }
    const d = c.data || {};
    const a = d.actor ? displayName(d.actor) : '', b = d.subject ? displayName(d.subject) : '';
    switch (c.system_type) {
      case 'member_added': return d.actor && d.actor !== d.subject ? t('msgSysAdded', { a, b }) : t('msgSysJoined', { b });
      case 'member_removed': return t('msgSysRemoved', { a, b });
      case 'member_left': return t('msgSysLeft', { b });
      case 'admin_added': return t('msgSysAdminAdded', { b });
      case 'admin_removed': return t('msgSysAdminRemoved', { b });
      case 'group_renamed': return t('msgSysRenamed', { a, name: d.name || '' });
      case 'group_disbanded': return t('msgSysDisbanded', { a });
      default: return c.text || '';
    }
  }

  // People being gathered for a group (the New group panel, or Add person):
  // each is checked for a KeyPackage as they are picked.
  const wnReach = new Map(); // pk -> 'checking' | 'ok' | 'no'
  const cdReach = new Map(); // the same, on the Cordn coordinator
  const reachOf = (proto) => (proto === 'cd' ? cdReach : wnReach);
  function wnCheck(pk, proto = 'wn') {
    const reach = reachOf(proto);
    if (reach.get(pk) === 'ok' || reach.get(pk) === 'checking') return;
    reach.set(pk, 'checking');
    (proto === 'cd' ? cordnChat() : whiteNoise()).then((c) => (c ? c.lookup(pk) : null)).then((cand) => { reach.set(pk, cand ? 'ok' : 'no'); scheduleRepaint(); })
      .catch(() => { reach.set(pk, 'no'); scheduleRepaint(); });
  }
  const wnFail = (e) => {
    if (e && e.missing) toast(t('msgGroupSomeCant', { names: e.missing.map(displayName).join(', ') }));
    else if (e && e.message === 'no signer') toast(t('msgNoIdentity'));
    else toast(t('msgGroupFailed'));
    dlog('chat: group', e);
  };

  async function wnCreateGroup() {
    const members = (ui.msgGroupPicks || []).filter((pk) => !isMe(pk));
    if (!members.length) { toast(t('msgGroupNeedPeople')); return; }
    if (ui.msgBusy) return;
    ui.msgBusy = true; render();
    try {
      const cordn = ui.msgGroupProto === 'cd';
      const c = await (cordn ? cordnChat() : whiteNoise());
      if (!c) throw new Error('no signer');
      // a group with no name is still a group once it has a third person;
      // with two it would be a direct chat, so it takes a name
      const name = (ui.msgGroupName || '').trim() || (members.length === 1 || cordn ? t('msgGroupUnnamed') : '');
      const g = await c.create({ name, members });
      ui.msgGroupPicks = []; ui.msgGroupName = ''; ui.msgGroupTo = ''; ui.msgHomePanel = null;
      dmSearcher.clear();
      ui.msgView = 'grp'; ui.msgPeer = g.id; ui.msgStick = true;
    } catch (e) { wnFail(e); } finally { ui.msgBusy = false; render(); }
  }

  async function wnSend(g) {
    const text = draftFor('wn:' + g.id).trim();
    const wn = gClient(g);
    if (!text || !wn) return;
    const replyTo = ui.msgReplyTo && wnFold(g).rows.some((m) => m.rumor.id === ui.msgReplyTo) ? ui.msgReplyTo : null;
    ui.msgReplyTo = null;
    ui.emojiAc = null;
    const inner = wn.event(9, text, [...(replyTo ? [['e', replyTo]] : []), ...outboundEmojiTags(text, emojiUrl)]);
    clearDraft('wn:' + g.id);
    ui.msgStick = true;
    // the engine logs our own event as it encrypts it, so it is on screen at once
    const sent = wn.send(g, inner).catch(() => false);
    wnFolds.delete(g.id);
    render();
    if (!(await sent)) { wnFolds.delete(g.id); toast(t('msgSendFailed')); render(); }
  }

  async function wnAct(fn) {
    if (ui.msgBusy) return;
    ui.msgBusy = true; render();
    try { await fn(); } catch (e) { wnFail(e); } finally { ui.msgBusy = false; render(); }
  }

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

  const timeLabel = (tms) => {
    if (feedPaint?.time.has(tms)) return feedPaint.time.get(tms);
    const d = new Date(tms);
    const today = new Date().toDateString() === d.toDateString();
    const label = 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' });
    feedPaint?.time.set(tms, label);
    return label;
  };

  // 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 FACE_WAIT_MS = 1000;
  const faceAsked = new Map(); // pk -> when its face was first wanted this session
  let faceTimer = null;
  function faceWaiting(pk) {
    let at = faceAsked.get(pk);
    if (at == null) { at = Date.now(); faceAsked.set(pk, at); }
    const left = at + FACE_WAIT_MS - Date.now();
    if (left <= 0) return false;
    // repaint when the wait runs out, so the punk shows without an event
    if (!faceTimer) faceTimer = setTimeout(() => { faceTimer = null; scheduleRepaint(); }, left + 20);
    return true;
  }
  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.
    // Small faces wait at most a second. An unknown payment portrait stays
    // hidden until its lookup settles; suggestions warm the real photo
    // before selection. A name-only search placeholder can retain `loading`
    // after a miss; the request state lets
    // it fall back once we've finished looking.
    const sendFace = cls.includes('send-avatar');
    // A profile page's own face is the same: the one big picture on the
    // page, never punk art while that person's lookup is still running.
    const pageFace = cls.includes('profile-avatar');
    const waiting = (p === null || (p && p.loading && !p.picture))
      && (sendFace || pageFace ? p === null || profQueue.has(pk) || profInFlight.has(pk) || fullInFlight.has(pk) : faceWaiting(pk));
    const node = feedPaint && !p.picture
      ? h('div', { class: cls + ' fallback' }, (p.name || npubOf(pk) || '??').slice(0, 2))
      : waiting && (sendFace || pageFace || p || ui.noteThread || (ui.chatOpen && ui.msgView === 'room'))
        ? h('div', { class: cls + ' fallback loading', style: sendFace ? 'visibility:hidden' : undefined })
      : p && p.loading && !p.picture
        ? fallbackAvatar(h, pk, p.name, cls)
      : 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
        // Larger profile/payment avatars layer 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') || cls.includes('send-avatar')) })
        : fallbackAvatar(h, pk, p.name, cls);
    // A face we keep painting is one worth keeping a thumbnail of.
    if (!feedPaint && 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.
      // As on* properties claimed in _evs, the way h() attaches handlers, so
      // the morph transplants them: a list that re-sorts (a new message
      // lifting a conversation to the top) patches this node into a
      // DIFFERENT person's avatar, and an addEventListener'd handler stayed
      // behind holding the old person — a tap on Bill's row opened someone
      // else's profile, until the next fresh render.
      node.onpointerdown = () => { try { prefetchProfilePage(pk); } catch {} };
      node.onclick = (e) => { e.stopPropagation(); openProfile(pk); };
      (node._evs || (node._evs = new Set())).add('onpointerdown').add('onclick');
    }
    // streaming now: a red ring, and the face opens the stream (the name
    // beside it still opens the profile, which says they're on too)
    let on = null;
    try { on = liveHostNow(pk); } catch {} // (an avatar drawn while the feature is still being built)
    if (on) {
      node.classList.add('live-ring');
      // (on that stream's own page, the face is a way out: to their profile)
      if (clickable) node.onclick = (e) => { e.stopPropagation(); if (ui.liveStream && ui.liveStream.a === liveAddr(on)) openProfile(pk); else openLive(on); };
    }
    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
  const fullInFlight = new Map();
  const fullMisses = new Set();

  // 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, {}) || {};
      // (notes saved before nv 2 were all flattened to kind 1: a boost's
      // JSON, a clip without its imeta — not worth keeping)
      return { full: c.full || {}, notes: c.nv === 2 ? c.notes || {} : {} };
    } catch { return { full: {}, notes: {} }; }
  };
  function persistPage(kind, pk, value) {
    try {
      const c = pageCache();
      c[kind][pk] = { t: Date.now(), v: value };
      c.nv = 2;
      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 {}
  }
  // (an article keeps its kind, its card's tags and, near enough, all of
  // itself: a tap opens it to read)
  const ARTICLE_TAGS = ['d', 'title', 'summary', 'image', 'published_at'];
  // (a note keeps its kind and what draws it: its clips, a poll's options)
  const NOTE_TAGS = ['e', 'p', 'q', 'd', 'imeta', 'title', 'option', 'polltype', 'endsAt', 'relay', 'emoji', 'content-warning'];
  const slimNote = (ev) => ev.kind === 30023 ? {
    id: ev.id, pubkey: ev.pubkey, kind: 30023, created_at: ev.created_at,
    content: String(ev.content || '').slice(0, 30000),
    tags: (ev.tags || []).filter((x) => ARTICLE_TAGS.includes(x[0])),
  } : ev.kind === REPOST ? {
    // a boost whole: the note inside is checked against its signature
    id: ev.id, pubkey: ev.pubkey, kind: REPOST, created_at: ev.created_at,
    content: String(ev.content || ''), tags: (ev.tags || []).filter((x) => x[0] === 'e' || x[0] === 'p'),
  } : {
    id: ev.id, pubkey: ev.pubkey, kind: ev.kind, created_at: ev.created_at,
    content: String(ev.content || '').slice(0, 3000),
    tags: (ev.tags || []).filter((x) => NOTE_TAGS.includes(x[0])),
  };

  function fetchFullProfile(pk) {
    if (!fullProfiles.has(pk)) {
      const cached = pageCache().full[pk];
      if (cached) fullProfiles.set(pk, cached.v);
    }
    if (fullFetched.has(pk)) return Promise.resolve();
    if (fullInFlight.has(pk)) return fullInFlight.get(pk);
    fullMisses.delete(pk);
    // Use the same index-relay + author's-relay fallbacks as feed avatars.
    // Only a real kind-0 response marks a page fetched; relay silence is
    // retryable and leaves cached profile details intact.
    const pending = fetchProfiles([pk]).catch(() => {}).finally(() => {
      fullInFlight.delete(pk);
      if (!fullFetched.has(pk)) fullMisses.add(pk);
      if (ui.profilePk === pk) render();
      else scheduleRepaint();
    });
    fullInFlight.set(pk, pending);
    return pending;
  }

  // A person's profile the way their profile page finds it: index relays and
  // their own relays, not just ours. The zap path asks here — a lightning
  // address on a kind 0 that our relays have long since pruned is still
  // somebody's lightning address.
  wallet.deepProfile = async (pk) => {
    await fetchFullProfile(pk);
    const m = fullProfiles.get(pk);
    if (!m || typeof m !== 'object') return null;
    const str = (v) => (typeof v === 'string' && v.trim() ? v.trim() : null);
    return {
      name: str(m.display_name) || str(m.name), picture: str(m.picture), about: str(m.about), nip05: str(m.nip05),
      lud16: str(m.lud16), lud06: str(m.lud06),
    };
  };

  // 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;
  const bannerOf = (pk) => {
    const full = fullProfiles.get(pk), lp = profiles.get(pk) || {};
    const b = (full && full.banner) || lp.banner;
    return typeof b === 'string' && /^https?:\/\//i.test(b.trim()) ? b.trim() : null;
  };
  function warmBanner(pk) {
    const b = bannerOf(pk);
    if (b && !mediaReady.has(b)) return warmMedia(b, { thumb: true }).then(() => scheduleRepaint());
  }
  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([
        // the cover photo as a column-sized copy, ready before the page opens
        Promise.resolve(fetchFullProfile(pk)).then(() => warmBanner(pk)),
        Promise.resolve(notesFor(pk)),
      ]).finally(() => { prefetching--; drainPrefetch(); });
    }
  }

  // A profile opens at its top: keeping the feed's scroll offset landed the
  // reader deep in that person's posts, which read as a thread. Back (a
  // popstate) puts them where they were on the page they left.
  // The same for a post opened into its thread: Back lands on the row the
  // reader tapped, not the top of the feed.
  const pageReturn = []; // [{ key, y }] per profile/thread opened, newest last
  const pageKey = () => ui.liveStream ? 'live' : ui.noteThread && !(ui.profilePk && ui.profOverThread) ? 'thread'
    : ui.profilePk ? 'p:' + ui.profilePk : '';
  function rememberPlace(key) {
    if (pageKey() === key) return;
    let y = 0; try { y = window.scrollY || 0; } catch {}
    pageReturn.push({ key, y });
    if (pageReturn.length > 20) pageReturn.shift();
  }
  // Only Back OUT OF a profile or thread puts the reader back. Any other
  // pop — a full-screen picture closing, a sheet — leaves the page where it
  // is. It used to restore the newest remembered place on every pop, and a
  // place goes stale whenever its page is left some other way (the Feed
  // button from a thread): a photo's × then jumped the feed to wherever an
  // earlier thread had been opened from, or to its top.
  let pageLeft = ''; // the page a pop is leaving, read before the app restores the entry under it
  if (typeof window !== 'undefined') {
    window.addEventListener('popstate', () => { pageLeft = pageKey(); }, true); // capture: before the app's own handler re-renders
    window.addEventListener('popstate', () => {
      const left = pageLeft; pageLeft = '';
      if (!left || pageKey() === left) return;
      const i = pageReturn.map((e) => e.key).lastIndexOf(left);
      if (i < 0) return;
      const y = pageReturn[i].y;
      pageReturn.length = i; // this entry, and anything stale above it
      // twice: the page under it may paint its rows a frame late
      requestAnimationFrame(() => { try { window.scrollTo(0, y); } catch {}
        requestAnimationFrame(() => { try { if (Math.abs(window.scrollY - y) > 2) window.scrollTo(0, y); } catch {} }); });
    });
  }
  function openProfile(pk) {
    rememberPlace('p:' + pk);
    ui.liveStream = null;
    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;
    ui.profPeople = null; ui.npubShown = null;
    render();
    try { window.scrollTo(0, 0); } catch {}
    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];
  // Replies (kind 1, and NIP-22 comments) so the reply button can say how
  // many — asked separately: relays cap a REQ's answer, and a busy post's
  // replies must not crowd its likes and zaps out of it.
  const REPLY_KINDS = [1, 1111];
  const replyIds = new Map(); // note id -> Map(reply id -> author pubkey)
  // The replies themselves, as the count fetch brought them — a thread's
  // first page, in hand before it is opened: every post on screen has its
  // replies asked for (watchZaps), so opening it paints the conversation at
  // once and the relays only add to it. Bounded: the targets most recently
  // heard from, a few dozen replies each.
  const replyEvents = new Map(); // note id -> Map(reply id -> event)
  const REPLY_KEEP_TARGETS = 400, REPLY_KEEP_EACH = 60;
  function keepReply(target, ev) {
    let m = replyEvents.get(target);
    if (m) replyEvents.delete(target); else m = new Map(); // re-set: most recent last
    if (!m.has(ev.id)) { if (m.size >= REPLY_KEEP_EACH) return; m.set(ev.id, ev); }
    replyEvents.set(target, m);
    while (replyEvents.size > REPLY_KEEP_TARGETS) replyEvents.delete(replyEvents.keys().next().value);
  }
  // The replies in hand for a thread: those naming the root, and those
  // naming only the reply they answer (one hop down), oldest first.
  function repliesInHand(rootId) {
    const out = new Map();
    const take = (id) => { for (const [rid, ev] of replyEvents.get(id) || []) if (rid !== rootId && !out.has(rid)) out.set(rid, ev); };
    take(rootId);
    for (const rid of [...out.keys()]) take(rid);
    return [...out.values()].sort((a, b) => a.created_at - b.created_at);
  }
  // …into a thread's cache entry: on opening it, and again when the count
  // fetch answers for a thread fetched ahead before the answer came
  function adoptRepliesInHand(c) {
    const have = new Set(c.replies.map((e) => e.id));
    let added = [];
    for (const e of repliesInHand(c.rootId)) if (!have.has(e.id) && e.id !== c.rootId) { have.add(e.id); c.replies.push(e); noteForSpam(e); added.push(e); }
    if (added.length) { c.replies.sort((a, b) => a.created_at - b.created_at); warmThread(added); }
    return added.length;
  }
  // A thread's rows painted in their final shape: the faces, pictures,
  // previews and quotes of what is in hand are fetched ahead (noteReady, as
  // the feed does per row), so an opened thread doesn't shift as they land.
  const threadWarmed = new WeakSet();
  const THREAD_ROW_MS = 1500; // a reply arriving from a relay waits this long at most for its face
  function warmThread(evs, deadline = Date.now() + READY_MS) {
    const fresh = evs.filter((e) => e && !threadWarmed.has(e));
    for (const e of fresh) threadWarmed.add(e);
    return Promise.all(fresh.map((e) => noteReady(e, deadline).catch(() => {})));
  }
  const reacts = new Map();  // note id -> Map([emoji, url] -> { emoji, url, who: Set<pubkey> })
  // Resolve from this reaction's own tag: packs can reuse the same shortcode
  // for different pictures, and an unrelated event must not change its face.
  const postReactNode = ({ emoji, url }) => url ? reactImg(shortcodeOf(emoji), url) : emoji;
  const boosts = new Map();  // note id -> Set<pubkey>
  const noteCountsReady = new Set(); // a relay batch is complete for this note
  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 zapWho = new Map();    // id -> Map(receipt id -> { pk, sats, ts, text }) — the tally, by person
  const zapAsked = new Set();
  let zapQueue = new Set(), zapTimer = null, zapLiveUnsub = null, zapRecent = [];
  // Scrolling brings new ids every few hundred ms; asking (two queries) and
  // swapping the live sub (CLOSE + REQ) per batch put ~4 REQs a second on
  // every zap relay. Flush at most every 2 s, swap the live sub at most
  // every 10 s — the tallies still land within a couple of seconds.
  let zapLastFlush = 0, zapLiveAt = 0, zapLiveTimer = null;
  const ZAP_FLUSH_MS = 2000, ZAP_LIVE_MS = 10_000;
  const zapRelays = () => [...new Set([...NOTE_RELAYS, ...((wallet.nostrRelays && wallet.nostrRelays()) || [])])];
  function noteCountSnapshot(id) {
    const rm = reacts.get(id);
    return { likes: rm ? [...rm.values()].reduce((n, { who }) => n + visiblePks(who).length, 0) : 0,
      boosts: visiblePks(boosts.get(id) || new Set()).length,
      sats: zapTotals.get(id)?.sats || 0 };
  }
  function refreshThreadCount(id, persist = true) {
    if (!noteCountsReady.has(id)) return;
    const c = ui.noteThread && threadCache.get(ui.noteThread.rootId);
    if (!c?.root || !(c.root.id === id || c.replies.some((e) => e.id === id))) return;
    const live = noteCountSnapshot(id), old = c.counts[id];
    // Relay answers can be incomplete. A short/empty answer must not erase
    // numbers that were already visible when this conversation opened.
    c.counts[id] = old ? { likes: Math.max(old.likes, live.likes), boosts: Math.max(old.boosts, live.boosts),
      sats: Math.max(old.sats, live.sats) } : live;
    if (persist) persistThread(c);
  }
  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; }
  }
  // The note the zapper typed with it, if any (it rides inside the zap
  // request the receipt carries).
  function zapText(ev) {
    if (ev.kind === 9737) return String(ev.content || '').slice(0, 200);
    try { return String((JSON.parse(tagOf(ev, 'description') || 'null') || {}).content || '').slice(0, 200); } catch { return ''; }
  }
  function zapperOf(ev) {
    if (ev.kind === 9737) {
      // Signed by the wallet key; the sender tag names the person behind it.
      // Older receipts of ours have no such tag — read them as us all the same.
      const sender = tagOf(ev, 'P') || ev.pubkey;
      const id = hook('nostrLoginIdentity');
      return id && wallet.nostr && sender === wallet.nostr.pk ? id.pubkey : sender;
    }
    if (tagOf(ev, 'P')) return tagOf(ev, 'P');
    try { return (JSON.parse(tagOf(ev, 'description') || 'null') || {}).pubkey || null; } catch { return null; }
  }
  // ---- edits and deletions of posts ----------------------------------------
  // A deletion is NIP-09 (kind 5 naming the post); an edit is kind 1010 — the
  // draft NIP-41 Amethyst reads and writes: the new text, e-tagging the post
  // it replaces. Either counts only when the post's own author signed it (the
  // pair is filed by id AND pubkey, since the post may not be here yet when
  // its edit arrives). Remembered between sessions so a deleted post never
  // flashes back in from a cached feed before the relays have answered.
  const EDIT = 1010;
  const EDIT_KINDS = [5, EDIT];
  const POST_EDITS = 'postEdits';
  let postEditsCache = null;
  function postEdits() {
    if (!postEditsCache) {
      let s = null;
      try { s = wallet.loadFeatureState(POST_EDITS, null); } catch {}
      postEditsCache = { del: new Set((s && s.del) || []), ed: new Map(Object.entries((s && s.ed) || {})) };
    }
    return postEditsCache;
  }
  let postEditsTimer = null;
  function savePostEdits() {
    if (postEditsTimer) return;
    postEditsTimer = setTimeout(() => {
      postEditsTimer = null;
      const p = postEdits();
      try { wallet.saveFeatureState(POST_EDITS, { del: [...p.del].slice(-2000), ed: Object.fromEntries([...p.ed].slice(-1000)) }); } catch {}
    }, 500);
  }
  const editKey = (id, pk) => id + ':' + pk;
  const isDeleted = (ev) => !!(ev && ev.id && ev.pubkey && postEdits().del.has(editKey(ev.id, ev.pubkey)));
  // the newest edit by the post's author: { at, c, tags } or undefined
  const editOf = (ev) => (ev && ev.id && ev.pubkey && (ev.kind === 1 || ev.kind === 1111)
    ? postEdits().ed.get(editKey(ev.id, ev.pubkey)) : undefined);
  // what a post says now, and the emoji its words may use
  const noteText = (ev) => { if (isVideoEvent(ev)) return videoEventText(ev); const e = editOf(ev); return e ? e.c : ev.content; };
  const noteEmojiTags = (ev) => { const e = editOf(ev); return emojiTagMap(e ? [...ev.tags, ...e.tags] : ev.tags); };
  function notePostEdit(ev) {
    const ids = (ev.tags || []).filter((x) => x[0] === 'e' && /^[0-9a-f]{64}$/.test(x[1] || '')).map((x) => x[1]);
    if (!ids.length) return;
    const p = postEdits();
    let changed = false;
    if (ev.kind === 5) {
      for (const id of ids) {
        const k = editKey(id, ev.pubkey);
        if (!p.del.has(k)) { p.del.add(k); changed = true; }
      }
    } else if (ev.kind === EDIT) {
      const k = editKey(ids[0], ev.pubkey);
      const cur = p.ed.get(k);
      if (!cur || cur.at < ev.created_at) {
        p.ed.delete(k); // re-inserted last: the newest are the ones kept
        p.ed.set(k, { at: ev.created_at, c: String(ev.content || ''), tags: (ev.tags || []).filter((x) => x[0] === 'emoji' || x[0] === 'imeta') });
        changed = true;
      }
    }
    if (changed) { savePostEdits(); scheduleRepaint(); }
  }
  // Sign as the post's author: the login identity, or the wallet's own key
  // for what it posted before a nostr login was linked.
  async function signAs(pk, partial) {
    const id = await requireIdentity();
    if (id.pubkey === pk) return id.signer instanceof Uint8Array ? finalizeEvent(partial, id.signer) : id.signer.signEvent(partial);
    if (wallet.nostr && wallet.nostr.sk && wallet.nostr.pk === pk) return finalizeEvent(partial, wallet.nostr.sk);
    throw new Error(t('postNotYours'));
  }
  const editRelays = async (ev) => [...new Set([
    ...(await noteRelaysFor(ev).catch(() => [])), ...(await notesRelays(ev.pubkey).catch(() => [])), ...wallet.nostrRelays(),
  ])];
  async function deletePost(ev) {
    const partial = { kind: 5, content: '', created_at: Math.floor(Date.now() / 1000),
      tags: [['e', ev.id], ['k', String(ev.kind)]] };
    const del = await signAs(ev.pubkey, partial);
    notePostEdit(del); // gone from every list at once
    render();
    const ok = await publishOn(await editRelays(ev), del);
    if (!ok) throw new Error(t('msgSendFailed'));
  }
  async function editPost(ev, text) {
    const emojis = [...emojiTagMap(ev.tags)].filter(([code]) => text.includes(':' + code + ':')).map(([code, url]) => ['emoji', code, url]);
    const partial = { kind: EDIT, content: text, created_at: Math.max(Math.floor(Date.now() / 1000), (editOf(ev)?.at || 0) + 1),
      tags: [['e', ev.id], ['p', ev.pubkey], ...emojis, ['alt', 'Edit of a post: ' + text.slice(0, 200)], CLIENT_TAG] };
    const evt = await signAs(ev.pubkey, partial);
    const prev = editOf(ev);
    notePostEdit(evt);
    render();
    const ok = await publishOn(await editRelays(ev), evt);
    if (!ok) {
      const p = postEdits(), k = editKey(ev.id, ev.pubkey);
      if (prev) p.ed.set(k, prev); else p.ed.delete(k);
      savePostEdits(); render();
      throw new Error(t('msgSendFailed'));
    }
  }

  // ---- translation ----------------------------------------------------------
  // A post in a language other than the app's is shown in the app's, the way
  // Amethyst does it: "Translated from Spanish · Show original". The
  // browser's own on-device translator does it when it has the language pair
  // ready (desktop Chrome); otherwise the registrar's LibreTranslate, cached
  // there by text. Automatic for posts we can tell are foreign (a Settings
  // switch); Translate in ⋯ for the ones the guess misses.
  const TRANSLATE_API = 'https://names.coinos.io/translate';
  const TRANSLATE_KEEP = 300;
  const AUTO_TRANSLATE_KEY = 'coinos-auto-translate';
  let deeplWarned = false;
  const autoTranslateOn = () => { try { return localStorage.getItem(AUTO_TRANSLATE_KEY) !== '0'; } catch { return true; } };
  const translations = new Map(); // key -> { text, source } (done) — remembered
  const translating = new Map(); // key -> 'loading' | 'fail'
  const transOriginal = new Set(); // keys the reader flipped back to the original
  const transAsked = new Set(); // keys the reader asked for by hand (shown even with auto off)
  const loadTranslations = () => mergeStored(translations, 'coinos-translations');
  loadTranslations();
  let transFlush = null;
  const saveTranslations = () => {
    if (transFlush) return;
    transFlush = setTimeout(() => {
      transFlush = null;
      try { cacheStorage.setItem('coinos-translations', JSON.stringify([...translations].slice(-TRANSLATE_KEEP))); } catch {}
    }, 1000);
  };
  // LibreTranslate has no Swahili, Marathi, Tamil or Telugu models: readers
  // in those get no offer rather than one that always fails
  const TRANSLATE_NO = new Set(['sw', 'mr', 'ta', 'te']);
  const canTranslateTo = (lang) => !!lang && !TRANSLATE_NO.has(lang);
  // The language posts are translated INTO: the reader's choice (Settings),
  // else the phone's own language when the app has no such UI language
  // (an Italian phone reads coinos in English, but wants posts in Italian),
  // else the app's.
  const TRANSLATE_TO_KEY = 'coinos-translate-to';
  const TRANSLATE_TARGETS = ['ar', 'bn', 'cs', 'da', 'de', 'el', 'en', 'es', 'fa', 'fi', 'fr', 'he', 'hi', 'hu', 'id', 'it', 'ja', 'ko', 'nl', 'pl', 'pt', 'ro', 'ru', 'sk', 'sv', 'th', 'tr', 'uk', 'ur', 'vi', 'zh'];
  const APP_LANGS = new Set(LANGS.map(([c]) => c));
  function transLang() {
    try { const v = localStorage.getItem(TRANSLATE_TO_KEY); if (v) return v; } catch {}
    const phone = (typeof navigator !== 'undefined' && (navigator.languages || [navigator.language])[0] || '').toLowerCase().split(/[-_]/)[0];
    if (phone && !APP_LANGS.has(phone) && TRANSLATE_TARGETS.includes(phone)) return phone;
    return getLang();
  }
  // A DeepL API key of the reader's own (Jumble offers the same): kept on
  // this device, sent with each request — DeepL won't answer a browser, so
  // the registrar passes it on, never storing or logging it.
  const DEEPL_KEY = 'coinos-deepl-key';
  const deeplKey = () => { try { return (localStorage.getItem(DEEPL_KEY) || '').trim(); } catch { return ''; } };
  const transKey = (ev) => ev.id + '|' + transLang() + (deeplKey() ? '|d' : '') + '|' + (editOf(ev)?.at || 0);
  const translatable = (ev) => !!ev && !ev.pending && (ev.kind === 1 || ev.kind === COMMENT);
  // foreign as far as the cheap guess can tell (a script, or a clear other
  // language); unknown is never translated unasked
  // A post that is only hashtags is judged by them: its tags in a script
  // the reader can't read are what wants translating (as glosses).
  // Asked per row per render; the guess reads the whole text, and a post's
  // text and the target language don't change, so remember it.
  const foreignMemo = new Map();
  const looksForeign = (ev) => {
    const to = transLang();
    if (!translatable(ev) || !(deeplKey() || canTranslateTo(to))) return false;
    const mk = transKey(ev) + '|' + to;
    if (foreignMemo.has(mk)) return foreignMemo.get(mk);
    const text = noteText(ev), { prose, tags } = transParts(text, to);
    const v = prose.length ? !inLanguage(text, to) : tags.length > 0;
    if (foreignMemo.size > 3000) foreignMemo.clear();
    foreignMemo.set(mk, v);
    return v;
  };
  const langName = (code) => { try { return new Intl.DisplayNames([getLang()], { type: 'language' }).of(code) || code; } catch { return code; } };
  // the translation to SHOW for this post now, or null
  function shownTranslation(ev) {
    if (!translatable(ev)) return null;
    const k = transKey(ev);
    if (transOriginal.has(k)) return null;
    const tr = translations.get(k);
    if (!tr) return null;
    return transAsked.has(k) || (autoTranslateOn() && looksForeign(ev)) ? tr : null;
  }
  const browserTranslators = new Map(); // 'es>en' -> Promise(translator | null)
  async function browserTranslate(text, from, to) {
    const T = typeof self !== 'undefined' ? self.Translator : null;
    if (!T || !from || from === to) return null;
    const pair = from + '>' + to;
    if (!browserTranslators.has(pair)) {
      browserTranslators.set(pair, (async () => {
        // only a pair already on the device: a download needs a user gesture
        // and minutes; the registrar answers in a second meanwhile
        if ((await T.availability({ sourceLanguage: from, targetLanguage: to })) !== 'available') return null;
        return T.create({ sourceLanguage: from, targetLanguage: to });
      })().catch(() => null));
    }
    const tr = await browserTranslators.get(pair);
    if (!tr) return null;
    return translatePieces(text, (qs) => Promise.all(qs.map((q) => tr.translate(q))), to);
  }
  async function translateNote(ev, { asked = false } = {}) {
    const k = transKey(ev);
    if (asked) { transAsked.add(k); transOriginal.delete(k); }
    if (translations.has(k) || translating.get(k) === 'loading') { scheduleRepaint(); return; }
    if (!asked && translating.get(k) === 'fail') return;
    translating.set(k, 'loading');
    scheduleRepaint();
    const text = noteText(ev);
    const to = transLang();
    const dk = deeplKey();
    try {
      let out = null;
      const guess = guessLang(text);
      // with a DeepL key, DeepL is what the reader chose: not the browser's
      if (!dk) { try { const t2 = await browserTranslate(text, guess, to); if (t2) out = { text: t2, source: guess }; } catch {} }
      if (!out) {
        const r = await fetch(TRANSLATE_API, {
          method: 'POST', headers: { 'content-type': 'application/json', ...(dk ? { 'x-deepl-key': dk } : {}) },
          body: JSON.stringify({ text, target: to }), signal: AbortSignal.timeout(20_000),
        });
        const j = await r.json().catch(() => ({}));
        if (!r.ok) {
          // a key DeepL refused, or out of quota: say so once, not "couldn't translate" on every post
          if (dk && (r.status === 401 || r.status === 402) && !deeplWarned) { deeplWarned = true; toast(t(r.status === 401 ? 'deeplBadKey' : 'deeplQuota')); }
          throw new Error(j.error || 'translate ' + r.status);
        }
        out = { text: String(j.text || ''), source: j.source || null, nothing: !!j.nothing };
      }
      // already in the reader's language after all: nothing to show, and
      // nothing to offer again
      if (!out.text || out.source === to || out.text.trim() === text.trim()) {
        translating.set(k, 'same');
        if (asked) toast(t(out.nothing ? 'translateNothing' : 'translateSame'));
      } else {
        translations.set(k, out);
        translating.delete(k);
        saveTranslations();
      }
    } catch {
      translating.set(k, 'fail');
      if (asked) toast(t('translateFailed'));
    }
    scheduleRepaint();
  }
  // Under the post's words: where it was translated from, and the way back —
  // or, for a post that reads foreign with auto off, the offer.
  function translateLine(ev) {
    if (!translatable(ev)) return null;
    const k = transKey(ev);
    const tr = shownTranslation(ev);
    const state = translating.get(k);
    const btn = (label, onClick) => h('button', { type: 'button', class: 'note-translate-btn', onClick: (e) => { e.stopPropagation(); onClick(); } }, label);
    if (tr) {
      return h('div', { class: 'note-translate small faint' },
        h('span', {}, tr.source ? t('translatedFrom', { lang: langName(tr.source) }) : t('translated')), ' · ',
        btn(t('translateShowOriginal'), () => { transOriginal.add(k); transAsked.delete(k); render(); }));
    }
    if (state === 'loading' && (transAsked.has(k) || (autoTranslateOn() && looksForeign(ev)))) {
      return h('div', { class: 'note-translate small faint' }, t('translating'));
    }
    if (!looksForeign(ev) || state === 'same') return null;
    if (autoTranslateOn() && !transOriginal.has(k) && state !== 'fail') { translateNote(ev); return null; }
    return h('div', { class: 'note-translate small faint' }, btn(t('translateBtn'), () => translateNote(ev, { asked: true })));
  }

  // 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.
  const timedActivity = new Map();
  function rememberMoment(ev) {
    const moment = readMoment(ev);
    if (!moment || ![1, 1111, 7, 9735, 9737].includes(ev.kind)) return;
    const target = ev.tags.filter(x => x[0] === 'e' && x[3] !== 'mention').at(-1)?.[1];
    if (!target) return;
    if (!timedActivity.has(target)) timedActivity.set(target, new Map());
    const items = timedActivity.get(target);
    if (items.has(ev.id)) return;
    items.set(ev.id, { id: ev.id, ev, moment,
      icon: ev.kind === 7 ? ev.content || '♡' : [9735, 9737].includes(ev.kind) ? '⚡' : '↩',
      text: [9735, 9737].includes(ev.kind) ? zapText(ev) : ev.content });
    if (items.size > 300) items.delete(items.keys().next().value);
    if (timedActivity.size > 200) timedActivity.delete(timedActivity.keys().next().value);
    queueMicrotask(() => document.querySelectorAll('audio, video').forEach(v => { if (v._momentUrl) v.dispatchEvent(new Event('mediaactivity')); }));
  }
  // a post's timed activity on one of its clips, in order, each with who and what
  const momentsOn = (id, file) => [...(timedActivity.get(id)?.values() || [])]
    .filter(x => x.moment.url === mediaMoment(file, 0)?.url && !hiddenPk(x.ev.pubkey) && !isDeleted(x.ev))
    .sort((a, b) => a.moment.seconds - b.moment.seconds)
    .map(x => ({ ...x, text: displayName(x.ev.kind === 9735 || x.ev.kind === 9737 ? zapperOf(x.ev) || x.ev.pubkey : x.ev.pubkey) + ' · ' + String(x.text || x.icon).slice(0, 240) }));
  // how a moment shows on a bar: a reaction as its emoji (a :code: as its
  // picture, from the reaction's own tag), a zap ⚡, a reply ↩
  function momentGlyph(x) {
    if (x.ev.kind !== 7) return x.icon;
    const code = shortcodeOf(x.ev.content);
    const tag = code && x.ev.tags.find(t => t[0] === 'emoji' && t[1] === code && t[2]);
    return tag ? reactImg(code, tag[2]) : reactNode(x.ev.content === '+' || !x.ev.content ? '❤️' : x.ev.content);
  }
  // Where a post's clip is up to, if it has been played: a reply, reaction or
  // zap made then is about that moment. (No buttons of their own for it: the
  // usual ones carry the time.)
  function momentOf(ev) {
    if (!ev) return null;
    const cur = pager && pager.cur;
    const players = cur && cur._ev && cur._ev.id === ev.id
      ? [cur.querySelector('.mp-media')]
      : [...document.querySelectorAll('[data-zap-post="' + CSS.escape(ev.id) + '"] :is(video, audio)')];
    for (const v of players) {
      if (v && v._momentUrl && v.currentTime > 0 && Number.isFinite(v.duration)) return mediaMoment(v._momentUrl, v.currentTime);
    }
    return null;
  }
  const withMoment = (ev) => { const m = momentOf(ev); return m ? { ...ev, mediaMoment: m } : ev; };
  function attachMediaTimeline(player, url, explicitEvent) {
    if (player._timeline) return;
    player._timeline = true;
    player._momentUrl = url;
    const event = () => {
      const ev = explicitEvent || noteInHand(player.closest('[data-zap-post]')?.getAttribute('data-zap-post'));
      return ev && (String(ev.content || '').includes(url) || ev.tags.some(tag => tag.includes('url ' + url) || tag[1] === url)) ? ev : null;
    };
    const box = player.parentElement;
    box._skipMorph = true;
    box.append(mediaTimeline(player, url, { h, event, label: t, moments: momentsOn, glyph: momentGlyph }));
    player.dispatchEvent(new Event('timeupdate'));
  }
  function noteEvent(ev) {
    rememberMoment(ev);
    if (ev.kind === 1 || ev.kind === 1111) { noteReply(ev); return; }
    if (EDIT_KINDS.includes(ev.kind)) { notePostEdit(ev); return; }
    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 code = shortcodeOf(ev.content);
        const emoji = !ev.content || ev.content === '+' ? '\u2764\ufe0f' : code ? ev.content : ev.content.slice(0, 12);
        const url = code ? emojiTagMap(ev.tags).get(code) || null : null;
        const key = JSON.stringify([emoji, url]);
        noteEmoji(ev);
        if (!reacts.has(id)) reacts.set(id, new Map());
        const m = reacts.get(id);
        if (!m.has(key)) m.set(key, { emoji, url, who: new Set() });
        m.get(key).who.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);
      }
      refreshThreadCount(id);
      scheduleRepaint();
      return;
    }
    noteReceipt(ev);
  }

  // A reply counts under every post of the conversation it names: NIP-10's
  // root and reply (or the bare positional e tags of older clients), NIP-22's
  // E and e. A 'mention' e tag is a quote, not a reply.
  function noteReply(ev) {
    rememberMoment(ev);
    let changed = false;
    for (const x of ev.tags || []) {
      if (!x[1] || x[1] === ev.id) continue;
      if (!(x[0] === 'e' || (ev.kind === 1111 && x[0] === 'E')) || x[3] === 'mention') continue;
      let m = replyIds.get(x[1]);
      if (!m) replyIds.set(x[1], m = new Map());
      if (!m.has(ev.id)) { m.set(ev.id, ev.pubkey); changed = true; }
      keepReply(x[1], ev);
    }
    if (changed) scheduleRepaint();
  }
  function replyCount(id) {
    const m = replyIds.get(id);
    if (!m) return 0;
    let n = 0;
    for (const pk of m.values()) if (!hiddenPk(pk)) n++;
    return n;
  }

  function noteReceipt(ev) {
    rememberMoment(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;
      if (from) {
        if (!zapWho.has(x[1])) zapWho.set(x[1], new Map());
        zapWho.get(x[1]).set(ev.id, { pk: from, sats, ts: ev.created_at, text: zapText(ev) });
      }
      // 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, sats); }
      changed = true;
      refreshThreadCount(x[1]);
    }
    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;
      zapLastFlush = Date.now();
      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);
        // replies, tallies and the author's edits in one REQ, not one each
        queryManyOn(relays, [{ kinds: REPLY_KINDS, '#e': slice }, { kinds: NOTE_KINDS, '#e': slice }, { kinds: EDIT_KINDS, '#e': slice }], 4000)
          .then((all) => {
            for (const e of all) if (REPLY_KINDS.includes(e.kind)) noteReply(e); else noteEvent(e);
            // 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);
            const c = ui.noteThread && threadCache.get(ui.noteThread.rootId);
            for (const id of slice) {
              noteCountsReady.add(id);
              if (c && (c.root?.id === id || c.replies.some((e) => e.id === id))) refreshThreadCount(id, false);
            }
            // the open thread takes the replies this answer brought
            if (c && slice.includes(c.rootId) && adoptRepliesInHand(c)) renderThreadStable();
            if (c?.root) persistThread(c);
            saveZapTotals();
            scheduleRepaint();
          }).catch(() => {});
      }
      zapRecent = [...batch.reverse(), ...zapRecent.filter((x) => !batch.includes(x))].slice(0, 200);
      if (!zapLiveTimer) zapLiveTimer = setTimeout(() => {
        zapLiveTimer = null;
        zapLiveAt = Date.now();
        if (zapLiveUnsub) { try { zapLiveUnsub(); } catch {} }
        zapLiveUnsub = subscribeOn(zapRelays(), { kinds: [...NOTE_KINDS, ...REPLY_KINDS, ...EDIT_KINDS], '#e': zapRecent, since: Math.floor(Date.now() / 1000) - 60 }, noteEvent);
      }, Math.max(0, zapLiveAt + ZAP_LIVE_MS - Date.now()));
    }, Math.max(250, zapLastFlush + ZAP_FLUSH_MS - Date.now()));
  }
  // 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 }], oldest first: one entry per zap of ours on
  // that id, so tapping again while the first is still in the air stacks a
  // second zap on top instead of being refused. 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 zap, so its 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.
  // Reports and receipts name the id, never the tap, so each is matched to
  // the oldest entry it can describe (same amount first). Two default-amount
  // zaps are told apart by order alone, which is all the chip needs: it shows
  // the sum, and pulses while any is in the air.
  const zapPending = new Map();
  const pendTtl = (p) => (p.state === 'flying' ? ZAP_FLIGHT_MS : ZAP_PAID_MS);
  // Everything still alive for this id, and what the chip makes of it.
  function pendingOf(id) {
    const all = zapPending.get(id);
    if (!all) return null;
    const now = Date.now();
    const list = all.filter((p) => now - p.at <= pendTtl(p));
    if (!list.length) { zapPending.delete(id); return null; }
    zapPending.set(id, list); // the array handed back is the one stored: splices land
    let sats = 0, flying = false;
    for (const p of list) if (p.state !== 'void') { sats += p.sats; flying = flying || p.state === 'flying'; }
    return { sats, flying, list };
  }
  const pickPending = (list, sats, pred) =>
    (sats && list.find((p) => pred(p) && p.sats === sats)) || list.find(pred) || null;
  const dropPending = (id, list, p) => {
    list.splice(list.indexOf(p), 1);
    if (!list.length) zapPending.delete(id);
  };
  function markZapPending(id, sats, origin) {
    if (!id || !sats) return;
    const list = pendingOf(id)?.list || [];
    zapPending.set(id, [...list, { sats, at: Date.now(), state: 'flying' }]);
    animateZap(sats, origin, id, zapSoundOn());
    render();
    // 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 list = pendingOf(id)?.list || [];
    if (!ok) {
      const p = pickPending(list, sats, (x) => x.state === 'flying') || pickPending(list, sats, (x) => x.state === 'paid');
      if (p) { dropPending(id, list, p); scheduleRepaint(); }
      return;
    }
    const p = pickPending(list, sats, (x) => x.state === 'flying');
    if (p) { p.state = 'paid'; p.at = Date.now(); scheduleRepaint(); return; }
    // nothing in the air: the receipt already beat this report (its marker
    // stays, so a repeated confirmation can't count it either), or a form
    // zap paid without a tap — count that one until its receipt lands
    if (pickPending(list, sats, (x) => x.state === 'void')) return;
    zapPending.set(id, [...list, { sats: sats || 0, at: Date.now(), state: 'paid' }]);
    scheduleRepaint();
  }
  // One of our own receipts has been counted for this id: the real total
  // speaks for that zap now, so its optimistic amount stands down.
  function voidPending(id, evMs, sats) {
    const list = pendingOf(id)?.list || [];
    // ...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 zaps currently in the air.
    const fresh = (p) => p.state !== 'void' && !(evMs && evMs < p.at - 120_000);
    const p = pickPending(list, sats, fresh);
    if (p) { p.state = 'void'; p.at = Date.now(); return; }
    if (evMs && evMs < Date.now() - 120_000) return; // old: no report is coming for it
    zapPending.set(id, [...list, { sats: 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.
  const zapSoundOn = () => (ctx.zapSound ? ctx.zapSound() : true);
  function zapChip(id, { onClick, onHold, cls = '' } = {}) {
    if (onClick && zapSoundOn()) warmZapSound();
    const z = zapTotals.get(id) || zapSeeds().get(id);
    const p = pendingOf(id);
    const optimistic = p ? p.sats : 0;
    const sats = (z ? z.sats : 0) + optimistic;
    if (!sats) return null;
    const flying = !!p && p.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 ? holdable(onHold, (e) => { e.stopPropagation(); onClick(); }) : {}),
    }, h('span', { style: 'display:flex', html: BOLT_SVG }), fmtSats(sats));
  }
  // Hold the ⚡ to change the one-tap amount instead of paying it. The
  // press's state lives on the element, not in this closure: a background
  // repaint swaps handlers mid-press, and the lift must still find the timer
  // the press set, or a finger already gone would count as a hold.
  const HOLD_MS = 500;
  function holdable(onHold, onTap) {
    const clear = (e) => { const el = e.currentTarget; if (el._hold) { clearTimeout(el._hold); el._hold = 0; } };
    if (!onHold) return { onClick: onTap };
    return {
      onPointerdown: (e) => {
        const el = e.currentTarget;
        clear(e); el._held = false;
        if (e.button) return; // right button has its own menu
        el._hold = setTimeout(() => {
          el._hold = 0; el._held = true;
          try { navigator.vibrate?.(12); } catch {}
          onHold(el);
        }, HOLD_MS);
      },
      onPointerup: clear, onPointercancel: clear, onPointerleave: clear,
      onContextmenu: (e) => { e.preventDefault(); },
      onClick: (e) => { const el = e.currentTarget; if (el._held) { el._held = false; e.stopPropagation(); return; } onTap(e); },
    };
  }
  // 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, origin) {
    zapNote(pk, { id }, origin);
    recheckZap(id);
  }
  // The one-tap ⚡ beside someone else's bubble: zap without opening the
  // message sheet first (tap pays the default, hold sets the amount).
  function msgZapBtn(pk, id) {
    if (!canZapPk(pk) || isMe(pk)) return null;
    if (zapSoundOn()) warmZapSound();
    return h('button', {
      class: 'chat-zap', title: t('msgZap'), 'aria-label': t('msgZap'),
      ...holdable((el) => openZapSettings(pk, id, el.getBoundingClientRect()),
        (e) => { e.stopPropagation(); zapMessage(pk, id, e.currentTarget.getBoundingClientRect()); }),
    }, h('span', { style: 'display:flex', html: BOLT_SVG }));
  }
  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;
  }
  // Plus relays that keep history: the big ones prune within days, and an
  // author without a NIP-65 list (Joe Nakamoto, 2026-10-01) otherwise shows
  // only whatever primal still holds — 2 posts of 22.
  const PROFILE_ARCHIVE_RELAYS = ['wss://relay.ditto.pub', 'wss://nostr21.com', 'wss://offchain.pub'];
  const notesRelays = async (pk) => [...new Set([...NOTE_RELAYS, ...(await relaysOf(pk)), ...PROFILE_ARCHIVE_RELAYS])];

  // 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);
  }

  // Asked again when the page is reopened after this long: one bad answer
  // (a relay down, the phone just back from sleep) must not freeze a
  // profile at two posts for the rest of the session.
  const NOTES_REFRESH_MS = 60_000;
  // A profile's Posts / Replies tab (Posts unless chosen on this profile).
  const profTab = (pk) => (ui.profTab && ui.profTab.pk === pk ? ui.profTab.tab : 'posts');
  // what goes under Replies: a note answering another (NIP-10), or a NIP-22 comment
  const replyish = (e) => e.kind === 1111 || (e.kind === 1 && isReply(e));
  // A conversations feed (Amethyst's "Conversations" beside its "New
  // Threads"): the replies these people write, each under the post it
  // answers, instead of their posts. Asked for as notes and NIP-22 comments;
  // reposts have no place in it. (REPLY_KINDS, above: a note or a comment.)
  const feedKinds = (def) => (def && def.replies ? REPLY_KINDS : FEED_KINDS);
  const feedKeeps = (def, e) => (def && def.replies ? replyish(e) : FEED_KINDS.includes(e.kind) && !isReply(e));
  // What a reply answers: the e tag marked 'reply' (NIP-10), else 'root'
  // (a reply straight to the root), else — the deprecated positional form —
  // the last e tag; a NIP-22 comment's lowercase e (its parent), else its E.
  function parentRefOf(ev) {
    if (!ev || !replyish(ev)) return null;
    const es = (ev.tags || []).filter((x) => x[0] === 'e' && x[1]);
    let tag;
    if (ev.kind === 1111) tag = es[0] || (ev.tags || []).find((x) => x[0] === 'E' && x[1]);
    else tag = es.find((x) => x[3] === 'reply') || es.find((x) => x[3] === 'root') || es[es.length - 1];
    if (!tag) return null;
    const ref = { type: 'event', id: tag[1], relays: tag[2] ? [tag[2]] : [] };
    // the parent's author: NIP-22 carries it at [3], NIP-10 at [4] (read at
    // [4] only, every comment's parent lost its author, and its outbox went
    // unasked: fiatjaf's comment on Kieran's, 2026-10-20). Without one, the
    // people the reply is addressed to: their outboxes are where it was written.
    const hex = (x) => (/^[0-9a-f]{64}$/i.test(x || '') ? x.toLowerCase() : null);
    ref.author = hex(ev.kind === 1111 ? tag[3] : tag[4]) || hex(tag[3]);
    if (!ref.author) ref.authors = [...new Set((ev.tags || []).filter((x) => x[0] === 'p').map((x) => hex(x[1])).filter((p) => p && p !== ev.pubkey))].slice(0, 3);
    return ref;
  }
  // A note already in hand — in a feed, a thread, someone's page — before
  // asking any relay for it: the post a reply answers is usually right
  // there in the Following feed.
  // a reply whose parent every lookup came back without
  const orphaned = (ev) => { const p = parentRefOf(ev); const q = p && quoted.get(p.id); return !!q && q.status === 'missing' && !q.ev; };
  function noteInHand(id) {
    for (const c of feedStates.values()) for (const e of c.notes) {
      if (e.id === id) return e;
      if (e.kind === REPOST) { const inner = repostInner(e); if (inner && inner.id === id) return inner; }
    }
    for (const c of threadCache.values()) {
      if (c.root && c.root.id === id) return c.root;
      for (const e of c.replies || []) if (e.id === id) return e;
    }
    for (const c of notesCache.values()) for (const e of c.notes || []) if (e.id === id) return e;
    return noteOnDisk(id);
  }
  // ...or on disk with the feed it was read in: a Conversations view opened
  // straight after a reload has the posts its replies answer in Following's
  // cache, not in any feed state yet (and without them, those replies were
  // taken for replies to nothing and left out)
  const diskHeld = new Map(); // feed id -> Map(note id -> note), read once a session
  function noteOnDisk(id) {
    for (const f of new Set([FOLLOWING, curFeedId])) {
      let m = diskHeld.get(f);
      if (!m) {
        let notes = null;
        try { notes = feedDisk()?.peekNotes(f) || wallet.loadFeatureState(feedCacheKey(f), []); } catch {}
        m = new Map((Array.isArray(notes) ? notes : []).filter((e) => e && e.id).map((e) => [e.id, e]));
        diskHeld.set(f, m);
      }
      if (m.has(id)) return m.get(id);
    }
    return null;
  }
  function notesFor(pk) {
    let c = notesCache.get(pk);
    if (c) {
      if (!c.fetching && Date.now() - (c.fetchedAt || 0) > NOTES_REFRESH_MS) fetchNotes(pk, 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 there is something to read while
    // the real answer comes.
    c = stored
      ? { status: 'ready', notes: stored.v }
      : { status: 'loading', notes: seed };
    notesCache.set(pk, c);
    fetchNotes(pk, c);
    return c;
  }
  function fetchNotes(pk, c) {
    c.fetching = true;
    (async () => {
      const evs = await queryOn(await notesRelays(pk), { kinds: PROFILE_KINDS, authors: [pk], limit: 30 }, 4500);
      // Merged with what's already on the page, never swapped for it: the
      // relays answer unevenly (primal held 2 of Joe Nakamoto's posts, ours
      // 18, the archives 30), and a thin answer used to erase a full page.
      const byId = new Map(c.notes.map((e) => [e.id, e]));
      let added = 0;
      for (const e of evs || []) if (!byId.has(e.id)) { byId.set(e.id, e); added++; }
      if (!added && c.notes.length) return;
      const merged = newestArticles([...byId.values()]).sort((a, b) => b.created_at - a.created_at);
      await notesReady(merged.slice(0, FEED_PAGE)); // the first screen arrives whole
      c.notes = merged;
      c.end = false;
      persistPage('notes', pk, merged.slice(0, 20).map(slimNote)); // cache stays bounded
    })().catch(() => {}).finally(() => {
      c.status = 'ready';
      c.fetching = false;
      c.fetchedAt = Date.now();
      if (ui.profilePk === pk) render();
    });
  }

  // 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.
  let lastFeedY = 0, pillFrame = 0;
  // When the reader last moved the page themselves (a wheel notch coasts for
  // a while after the last one), and when it last scrolled at all: a batch of
  // arriving posts waits for a quiet moment (see queueAdmit).
  let lastInputAt = 0, lastScrollAt = 0;
  if (typeof window !== 'undefined') {
    for (const n of ['wheel', 'touchstart', 'touchmove', 'keydown', 'pointerdown']) window.addEventListener(n, () => { lastInputAt = Date.now(); }, { passive: true, capture: true });
    window.addEventListener('scroll', () => {
      lastScrollAt = Date.now();
      if (!ui.profilePk && (!(ui.chatOpen && ui.msgView === 'feed') || ui.noteThread)) return;
      windowScrolled(ui.profilePk ? notesCache.get(ui.profilePk) : feed);
      // Starting to scroll up dismisses the notice: the reader is already
      // heading toward the new posts. Keyed rows keep their positions.
      // Upward only: holding the page still as posts go in above scrolls it
      // DOWN, and that must not count as having gone up to look at them.
      const y = window.scrollY || 0, up = y < lastFeedY;
      lastFeedY = y;
      if (!ui.profilePk && Date.now() - lastInputAt < 2500) noteScrollTrail(y); // the reader's own travel (not a held-still insert)
      // Keep tracking which posts are ahead, even after hiding the pill.
      if (!ui.profilePk && feed && feed.ahead?.size && up && !pillFrame) pillFrame = requestAnimationFrame(() => {
        pillFrame = 0;
        if (!feed) return;
        markReached(feed);
        if (!feed.unseen) return;
        feed.unseen = 0;
        render();
      });
      if (!ui.profilePk && feed?.deferred?.length) admitFeed(feed.deferred, feed);
      if (window.innerHeight + window.scrollY < (document.documentElement.scrollHeight || 0) - (ui.profilePk ? 600 : feedLead())) 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: PROFILE_KINDS, 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) { await notesReady(older); c.notes = newestArticles([...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);

  // Everywhere someone's follow list might be: our relays, the profile
  // indexes, the archives, their own outbox relays, and Primal's cache (its
  // copy is the signed event, checked here like any other). A kind 3 is
  // REPLACEABLE: publishing one built on a list we failed to find wipes the
  // real one everywhere it lands. 2026-10-02: an Amethyst user's 398 follows,
  // kept only on her own relays, became our two starter follows the first
  // time she signed in here. Returns the newest list (or null) and whether
  // this key has any nostr life at all (a list or a profile).
  async function deepContactList(pk) {
    const relays = [...new Set([...zapRelays(), ...PROFILE_INDEX_RELAYS, ...PROFILE_ARCHIVE_RELAYS,
      ...(await relaysOf(pk).catch(() => []))])];
    const [relayEvs, primalEvs] = await Promise.all([
      queryOn(relays, { kinds: [0, 3], authors: [pk] }, 7000).catch(() => []),
      primalCache('contact_list', { pubkey: pk }, 7000)
        .then((evs) => verifiedPrimal((evs || []).filter((e) => e.pubkey === pk), [0, 3])).catch(() => []),
    ]);
    const all = [...(relayEvs || []), ...primalEvs].filter((e) => e.pubkey === pk);
    const list = all.filter((e) => e.kind === 3).sort((a, b) => b.created_at - a.created_at)[0] || null;
    return { list, existing: all.length > 0 };
  }

  // 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.
  // `deep` widens the search to everywhere above — required before
  // publishing on top of a list we have never seen.
  async function syncFollows({ force = false, deep = false } = {}) {
    const me = mePk();
    if (!me) return followsNow();
    if (!force && Date.now() - followsAt < 10 * 60_000) return followsNow();
    followsAt = Date.now();
    try {
      const evs = deep
        ? [(await deepContactList(me)).list].filter(Boolean)
        : 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.
  // A brand-new identity starts with something to read: the people behind
  // coinos, a Bitcoin feed, and one topic as an example of what a feed can
  // be. Once per identity; a person who unfollows stays unfollowed.
  const STARTER_FOLLOWS = [
    '98ae4da926c471c23fd12d1ebdd5839ba82917baa618e184e0c9916d93dcf4f7', // Adam
    '72bdbc57bdd6dfc4e62685051de8041d148c3c68fe42bf301f71aa6cf53e52fb', // coinos
  ];
  // The Bitcoin feed's follow pack (NIP-51 kind 39089): { pk, d, relays, title }.
  // Until one is chosen there is no Bitcoin feed — a #bitcoin topic feed was
  // too noisy to hand a newcomer.
  const STARTER_BITCOIN_PACK = null;
  async function seedNewIdentity({ onlyIfNoFollows = false } = {}) {
    const s = st();
    if (s.seeded) return;
    s.seeded = Date.now();
    const at = Date.now();
    const feeds = [
      STARTER_BITCOIN_PACK ? { id: 'starter-bitcoin', name: 'Bitcoin', follows: false, authors: [], packs: [STARTER_BITCOIN_PACK], topics: [], at } : null,
      { id: 'starter-gardenstr', name: '#gardenstr', follows: false, authors: [], packs: [], topics: ['gardenstr'], at },
    ].filter(Boolean);
    for (const f of feeds) if (!s.feeds.some((x) => x.id === f.id) && !(s.feedsGone || {})[f.id]) s.feeds.push(f);
    save(s);
    if (onlyIfNoFollows) {
      // "New" here means new to coinos, not new to nostr: anyone with a
      // profile or a follow list anywhere already has a following, and a
      // starter list would replace it. Only a key with no trace gets one.
      const me = mePk();
      if (!me) return;
      let found;
      try { found = await deepContactList(me); } catch { return; }
      if (found.existing || followsNow().set.size) { syncFollows({ force: true, deep: true }).catch(() => {}); return; }
    }
    followMany(STARTER_FOLLOWS).catch(() => {});
  }
  // Follow several people in one kind-3 update (toggleFollow is one at a time
  // and locks while it publishes).
  async function followMany(pks) {
    if (followsPub) return;
    const id = await requireIdentity();
    const want = pks.filter((pk) => pk && pk !== id.pubkey);
    if (!want.length) return;
    followsPub = true;
    const before = followsNow();
    try {
      // never seen this person's list: look everywhere before writing one
      await syncFollows({ force: true, deep: !before.at }).catch(() => {});
      const fetched = followsNow();
      const base = fetched.at > before.at ? fetched : before;
      const add = want.filter((pk) => !base.set.has(pk));
      if (!add.length) return;
      const tags = [...base.tags, ...add.map((pk) => ['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);
      saveFollows({ set: new Set(pTags(tags).map((x) => x[1])), tags, content: base.content || '', at: created_at });
      feedAuthorsChanged();
      publishOn(zapRelays(), evt).catch(() => {});
      syncInbox({ force: true }).catch(() => {});
    } finally {
      followsPub = false;
      render();
    }
  }
  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 {
      // never seen this person's list: look everywhere before writing one
      await syncFollows({ force: true, deep: !before.at });
      // 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;
        // The socket is open either way, so it's asked about EVERYONE who
        // writes there, not just the people it was picked to cover. Covering
        // each author once read a five-relay author on nos.lol alone, and his
        // posts that only reached damus and primal — both in the plan, both
        // open — never showed, while Amethyst had them.
        const take = [...byRelay.get(best)];
        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.
  // Cached events avoid waiting for relays; their presentation is prepared
  // before the reading surface is shown.
  const FEED_CACHE = 'feedNotes';
  const FEED_LIMIT = 30;
  const FEED_PAGE = 10;    // posts on screen at once, grown as you scroll
  const FEED_KEEP = 80;   // memory target; retain rows already being read
  const FEED_STORE = FEED_CACHE_POSTS;   // ...and on disk
  let feed = null;         // the feed on screen: { id, status, notes, shown, end, loadingMore, at }
  let feedUnsubs = [];
  // ---- many feeds ----------------------------------------------------------
  // "Following" is one feed among any number the user defines: a set of
  // people (or everyone they follow), a set of topics (hashtags, any of
  // them), or both at once — people AND topics, the way a nostr filter
  // composes them. Definitions live in the synced messages state, so a feed
  // made on the phone is on the laptop too; each feed keeps its own notes,
  // clock and disk cache. A topic opened from search or a #tag in a post is
  // a feed too, until saved just a session one.
  const FOLLOWING = 'following';
  // The feed last on screen, remembered per wallet on this device. It used to
  // be one device-wide key, so a brand-new account opened on whatever the
  // last one was reading (its #gardenstr starter feed has the same id in
  // every account). Nothing remembered: Popular.
  const FEED_LS = 'btc-wallet-feed';
  const feedLsKey = () => FEED_LS + ':' + (wallet._cacheKey ? wallet._cacheKey() : '');
  const storedFeedId = () => { try { return localStorage.getItem(feedLsKey()) || null; } catch { return null; } };
  const feedStates = new Map(); // id -> state
  const adhocFeeds = new Map(); // id -> definition, this session only
  // the feed of your own you last had on (never a session one)
  const homeFeedId = () => { const id = storedFeedId() || EVERYTHING; return feedDef(id) && !adhocFeeds.has(id) ? id : EVERYTHING; };
  let curFeedId = storedFeedId() || 'all'; // EVERYTHING, declared just below (re-read per wallet in init)
  // Two feeds everyone has: the people you follow, and everything the coinos
  // relay carries. Each remembers its own relay choice in the state.
  const EVERYTHING = 'all';
  // The Conversations view of a feed (the chip beside Notes / Images /
  // Videos / Articles): the same people, their replies — a feed state of
  // its own under the feed's id with this suffix, its definition derived
  // from the feed's (replies: true, see feedKeeps). Nothing is stored
  // under it but its notes cache.
  const VIEW_SUFFIX = '~replies';
  const viewId = (id = curFeedId) => (mediaMode === 'replies' ? id + VIEW_SUFFIX : id);
  // Amethyst's feed model, for the people who asked: everyone you follow plus
  // everyone on your lists, and on top of that posts from anyone on a
  // hashtag you follow — your topic feeds' tags and your NIP-51 interests
  // (kind 10015). Not chips of their own: a custom feed ticks "everyone on
  // my lists" (f.lists) and/or "hashtags I follow" (f.interests), and is
  // expanded from your other feeds each time it's read, never stored so.
  const INTERESTS_KIND = 10015;
  const INTERESTS = 'interests'; // feature state: { tags, at } from your kind 10015
  function listsUnion() {
    const authors = new Set(), priv = new Set(), packs = new Map();
    for (const f of st().feeds) {
      for (const pk of f.authors || []) authors.add(pk);
      for (const pk of f.priv || []) priv.add(pk);
      for (const p of f.packs || []) packs.set(packKey(p), p);
    }
    return { authors: [...authors], priv: [...priv], packs: [...packs.values()] };
  }
  function followedTopics() {
    const out = new Set();
    try { for (const x of (wallet.loadFeatureState(INTERESTS, {}) || {}).tags || []) out.add(normTopic(x)); } catch {}
    for (const f of st().feeds) {
      if (f.follows || (f.authors || []).length || (f.packs || []).length || (f.priv || []).length) continue;
      for (const x of f.topics || []) out.add(normTopic(x));
    }
    out.delete('');
    return [...out].slice(0, 30);
  }
  const expands = (f) => !!f && (!!f.lists || !!f.interests);
  function expandFeed(f) {
    if (!expands(f) || f.all) return f;
    const out = { ...f };
    if (f.lists) {
      const u = listsUnion();
      out.authors = [...new Set([...(f.authors || []), ...u.authors])];
      out.priv = [...new Set([...(f.priv || []), ...u.priv])];
      const packs = new Map((f.packs || []).map((p) => [packKey(p), p]));
      for (const p of u.packs) packs.set(packKey(p), p);
      out.packs = [...packs.values()];
    }
    if (f.interests) {
      const tags = followedTopics();
      // nobody to read: the hashtags ARE the feed (posts from anyone on them)
      const people = out.follows || (out.authors || []).length || (out.priv || []).length || (out.packs || []).length;
      if (people) out.orTopics = tags;
      else out.topics = [...new Set([...(f.topics || []), ...tags])];
    }
    return out;
  }
  const feedList = () => {
    const br = st().builtinRelays || {};
    return [
      { id: FOLLOWING, name: t('feedFollowingName'), follows: true, builtin: true, relays: br[FOLLOWING] || [] },
      { id: EVERYTHING, name: t('feedPopular'), follows: false, authors: [], packs: [], topics: [], all: true, curated: true, builtin: true, relays: oldPopularDefault(br[EVERYTHING]) ? [] : br[EVERYTHING] || [] },
      ...st().feeds.map(expandFeed)];
  };
  function feedDef(id = curFeedId) {
    if (typeof id === 'string' && id.endsWith(VIEW_SUFFIX)) {
      const base = feedDef(id.slice(0, -VIEW_SUFFIX.length));
      return base ? { ...base, id, replies: true, view: true } : null;
    }
    if (id === FOLLOWING || id === EVERYTHING) return feedList().find((f) => f.id === id) || null;
    const own = st().feeds.find((f) => f.id === id);
    return own ? expandFeed(own) : adhocFeeds.get(id) || null;
  }
  const normTopic = (x) => String(x || '').trim().replace(/^#/, '').toLowerCase();
  // ---- follow packs (NIP-51 kind 39089, what following.space publishes) ---
  // A feed can name packs instead of (or as well as) people: the pack's
  // current members are its authors, read from the pack event itself, so
  // a curator adding someone reaches your feed without you doing anything.
  // Members are cached on disk so a cold boot paints the feed at once, and
  // refreshed from the relays when a feed that uses them is opened.
  const PACK_KIND = 39089;
  const PACK_CACHE = 'followPacks';
  const PACK_RELAYS = [...new Set([...PROFILE_RELAYS, 'wss://relay.nostr.band'])];
  const packKey = (p) => p.pk + ':' + p.d + (p.kind && p.kind !== PACK_KIND ? ':' + p.kind : '');
  let packMembers = null; // key -> { pks, title, at }
  const packsNow = () => {
    if (!packMembers) { try { packMembers = wallet.loadFeatureState(PACK_CACHE, {}) || {}; } catch { packMembers = {}; } }
    return packMembers;
  };
  const packOf = (p) => packsNow()[packKey(p)] || null;
  // A pasted following.space link (/d/<id>?p=<pubkey>), a bare naddr, or
  // nostr:naddr — the pack it names.
  function parsePackLink(input) {
    const s = String(input || '').trim();
    const link = /\/d\/([^/?#\s]+)[^?\s]*\?(?:[^#\s]*&)?p=([0-9a-f]{64})/i.exec(s);
    if (link) return { pk: link[2].toLowerCase(), d: decodeURIComponent(link[1]), relays: [] };
    const m = /naddr1[a-z0-9]+/i.exec(s);
    if (!m) return null;
    const ref = parseNostrRef(m[0].toLowerCase());
    if (!ref || ref.type !== 'addr') return null;
    if (ref.kind === PACK_KIND) return { pk: ref.pk, d: ref.d, relays: ref.relays || [] };
    // someone's follow set (kind 30000) is a pack by another name
    if (ref.kind === LIST_KIND) return { pk: ref.pk, d: ref.d, relays: ref.relays || [], kind: LIST_KIND };
    return null;
  }
  // Draftable (mutable.top) links name a pack by its id and only the first
  // eight hex of its author: /draftable/d/<id>?p=<prefix>. The id is asked
  // for and the author matched by that prefix.
  const PACK_INDEX_RELAYS = () => [...new Set([...PACK_RELAYS, 'wss://relay.damus.io', 'wss://nos.lol', 'wss://nostr.oxtr.dev'])];
  async function resolveShortPackLink(input) {
    const m = /\/d\/([^/?#\s]+)[^?\s]*\?(?:[^#\s]*&)?p=([0-9a-f]{4,63})(?![0-9a-f])/i.exec(String(input || ''));
    if (!m) return null;
    const d = decodeURIComponent(m[1]), prefix = m[2].toLowerCase();
    const evs = await queryOn(PACK_INDEX_RELAYS(), { kinds: [PACK_KIND], '#d': [d], limit: 50 }, 5000).catch(() => []);
    const ev = evs.filter((e) => e.kind === PACK_KIND && e.pubkey.startsWith(prefix)).sort((a, b) => b.created_at - a.created_at)[0];
    return ev ? { pk: ev.pubkey, d, relays: [] } : null;
  }
  // Every pack the wide relays hold, once per session: the way to find one
  // by a few letters of its title — NIP-50 search only knows the packs the
  // search relay happens to carry, and most live on damus / nos.lol.
  let packIndex = null;
  function loadPackIndex() {
    if (packIndex) return packIndex;
    packIndex = (async () => {
      const relays = PACK_INDEX_RELAYS();
      const all = await Promise.all(relays.map((r) => queryOn([r], { kinds: [PACK_KIND], limit: 500 }, 6000).catch(() => [])));
      const newest = new Map();
      for (const ev of all.flat()) {
        const p = packFromEvent(ev);
        if (!p.pks.length) continue;
        const cur = newest.get(packKey(p));
        if (!cur || p.at > cur.at) newest.set(packKey(p), { ...p, desc: (ev.tags.find((x) => x[0] === 'description') || [])[1] || '' });
      }
      return [...newest.values()];
    })();
    packIndex.catch(() => { packIndex = null; });
    return packIndex;
  }
  const packFromEvent = (ev) => ({
    pk: ev.pubkey, d: (ev.tags.find((x) => x[0] === 'd') || [])[1] || '',
    title: (ev.tags.find((x) => x[0] === 'title') || [])[1] || '',
    pks: [...new Set(ev.tags.filter((x) => x[0] === 'p' && /^[0-9a-f]{64}$/i.test(x[1] || '')).map((x) => x[1].toLowerCase()))],
    at: ev.created_at,
  });
  const packFetching = new Map();
  async function fetchPack(p) {
    const key = packKey(p);
    if (packFetching.has(key)) return packFetching.get(key);
    const job = (async () => {
      const relays = [...new Set([...(p.relays || []), ...PACK_RELAYS])];
      const evs = await queryOn(relays, { kinds: [p.kind || PACK_KIND], authors: [p.pk], '#d': [p.d] }, 4500).catch(() => []);
      const newest = (evs || []).sort((a, b) => b.created_at - a.created_at)[0];
      if (!newest) return packOf(p);
      const got = packFromEvent(newest);
      const cur = packOf(p);
      if (cur && cur.at >= got.at) return cur;
      packsNow()[key] = { pks: got.pks, title: got.title, at: got.at };
      try { wallet.saveFeatureState(PACK_CACHE, packsNow()); } catch {}
      return packsNow()[key];
    })().finally(() => packFetching.delete(key));
    packFetching.set(key, job);
    return job;
  }
  // Make sure a feed's packs are read (or re-read: once an hour is plenty
  // for a curated list), and rebuild the feed when its authors grew.
  const PACK_TTL = 60 * 60_000;
  const packRefreshed = new Map(); // key -> ms
  function resolvePacks(def) {
    const packs = (def && def.packs) || [];
    if (!packs.length) return;
    const due = packs.filter((p) => !packOf(p) || Date.now() - (packRefreshed.get(packKey(p)) || 0) > PACK_TTL);
    if (!due.length) return;
    for (const p of due) packRefreshed.set(packKey(p), Date.now());
    Promise.all(due.map((p) => fetchPack(p).catch(() => null))).then(() => {
      const c = feedStates.get(def.id);
      if (!c) return;
      c.at = 0;
      if (c === feed) refreshFeed({ live: false }, c); else feedStates.delete(def.id);
      scheduleRepaint();
    });
  }
  // The packs' members, from cache; asks the relays on the side when stale.
  function packAuthors(def) {
    const out = new Set();
    for (const p of (def && def.packs) || []) for (const pk of (packOf(p) || {}).pks || []) out.add(pk);
    resolvePacks(def);
    return out;
  }
  // posts from anyone on these tags, as well as the feed's people (Everything)
  const orTopicsOf = (def) => [...new Set(((def && def.orTopics) || []).map(normTopic).filter(Boolean))];
  const feedTopics = (def = feedDef()) => [...new Set(((def && def.topics) || []).map(normTopic).filter(Boolean))].slice(0, 20);
  const feedHasQuery = (def = feedDef()) => !!def && (!!def.all || feedAuthors(def).length > 0 || feedTopics(def).length > 0);
  // A feed's own relay list, when it has one, replaces the usual choice
  // (the authors' outboxes, or the wide relays for a topic) everywhere the
  // feed reads. Independent of what the feed asks for.
  // Popular relays that answer a bare "everything" query (probed 2026-09-27;
  // paid/search relays like nostr.wine and nostr.band answer nothing and are
  // left out). The firehose reads a few of them by default.
  const RELAY_PICKS = ['wss://relay.coinos.io', 'wss://relay.ditto.pub', 'wss://relay.damus.io', 'wss://nos.lol', 'wss://relay.primal.net', 'wss://relay.snort.social',
    'wss://nostr.mom', 'wss://nostr.bitcoiner.social', 'wss://eden.nostr.land', 'wss://nostr.land', 'wss://nostr.oxtr.dev',
    'wss://relay.nostrplebs.com', 'wss://offchain.pub', 'wss://nostr21.com', 'wss://relay.nostr.net', 'wss://nostr-pub.wellorder.net'];
  const normRelay = (u) => {
    let x = String(u || '').trim();
    if (!x) return null;
    if (!/^wss?:\/\//i.test(x)) x = 'wss://' + x;
    try { const url = new URL(x); if (!/^wss?:$/.test(url.protocol) || !url.hostname) return null; return url.href.replace(/\/$/, ''); } catch { return null; }
  };
  const feedRelays = (def) => (def && Array.isArray(def.relays) && def.relays.length ? def.relays : null);
  // ---- curation for the public firehose --------------------------------
  // Everything a relay carries is mostly noise: machine output, every
  // language at once, posts nobody read. Popular keeps a post when it reads
  // as prose in the reader's language and at least two people reacted,
  // replied, reposted or zapped it — one batch ask per page, remembered.
  // A brand-new post has no reactions yet (of 73 fresh English posts on the
  // four relays, one had two), so Popular starts from the other end: the
  // latest reactions, reposts and zaps, counted per post by distinct
  // people, then the posts enough people touched. Older pages walk the
  // reactions back in time. The prose and language tests run at the door.
  const POPULAR_ASK = 600; // reactions per round
  const curateFeed = (evs) => { const lang = getLang(); return evs.filter((e) => !isMachinePost(e.content) && inLanguage(e.content, lang) && !notForPublic(e)); };
  async function popularPass(extra, merge, c, def) {
    // Only the default public feed shares a snapshot. Custom relays and older
    // pages keep their own queries. A static/offline install falls back quickly;
    // the single file opened from a disk has no server to ask at all.
    if (extra.until == null && !feedRelays(def) && /^https?:$/.test(location.protocol)) {
      try {
        const response = await fetch('/api/feed', { signal: AbortSignal.timeout(1500) });
        if (!response.ok || !response.headers.get('content-type')?.includes('application/json')) throw new Error('No feed cache');
        const data = await response.json();
        if (data.version !== 1 || !Number.isFinite(data.generatedAt) || Date.now() - data.generatedAt > 86400_000
          || !Array.isArray(data.notes) || data.notes.length > 240 || !Array.isArray(data.profiles) || data.profiles.length > 240
          || !Number.isFinite(data.popUntil)) throw new Error('Invalid feed cache');
        const events = [...data.notes, ...data.profiles];
        // HTTP is another untrusted source: retain the relay signature checks.
        const valid = await verifyEventsAsync(events);
        if (c.stopped) return false;
        const posts = data.notes.filter((e, i) => valid[i] && e.kind === 1);
        const usable = curateFeed(posts).filter((e) => !isReply(e) && !hidden(e));
        if (usable.length) {
          warmProfiles();
          for (let i = 0; i < data.profiles.length; i++) {
            const e = data.profiles[i];
            if (valid[data.notes.length + i] && e.kind === 0) applyProfile(e.pubkey, e);
          }
          c.popUntil = c.popUntil || data.popUntil;
          const got = await mergeFeed(posts, { ...merge, immediate: true }, c);
          if (got) scheduleRepaint();
          return got; // already-known posts also count as a successful cache hit
        }
      } catch {} // relay path also covers snapshots with no posts in this language
    }
    const relays = feedRelaysOr(def, POPULAR_RELAYS);
    const wide = [...new Set([...relays, ...NOTE_RELAYS])];
    let until = extra.until != null && c.popUntil ? c.popUntil - 1 : undefined;
    let got = false;
    for (let round = 0; round < 3 && !c.stopped; round++) {
      const re = await queryOn(wide, { kinds: [6, 7, 9735], limit: POPULAR_ASK, ...(until ? { until } : {}) }, 4500).catch(() => []);
      if (!re.length) break;
      const candidates = popularCandidates(re);
      const oldest = Math.min(...re.map((r) => r.created_at));
      c.popUntil = c.popUntil && until ? Math.min(c.popUntil, oldest) : (c.popUntil || oldest);
      until = oldest - 1;
      const ids = candidates.ids;
      if (!ids.length) continue;
      const asks = [];
      for (let i = 0; i < ids.length; i += 40) asks.push(queryFeed(wide, { ids: ids.slice(i, i + 40) }, merge, c, 4500, candidates.qualifies)
        .then((ok) => { if (ok) got = true; }));
      await Promise.all(asks);
      if (c.stopped) return got;
      if (got && round >= 0 && (c.notes.length >= FEED_PAGE || extra.until != null)) break;
    }
    return got;
  }
  const feedRelaysOr = (def, usual) => feedRelays(def) || usual;
  const feedCacheKey = (id) => (id === FOLLOWING ? FEED_CACHE : FEED_CACHE + ':' + id);
  const feedDisk = () => typeof wallet.featureStateKey === 'function'
    ? createFeedCache(localStorage, wallet.featureStateKey(FEED_CACHE)) : null;
  const saveFeedCache = (c) => {
    if (adhocFeeds.has(c.id) || isVisitor()) return; // a session feed leaves nothing behind
    try {
      const notes = c.notes.slice(0, FEED_STORE);
      const disk = feedDisk();
      if (disk) disk.save(c.id, notes);
      else wallet.saveFeatureState(feedCacheKey(c.id), notes);
    } catch {}
  };
  // posts on a topic come from the big public relays as well as ours: a
  // hashtag has no author whose outbox we could read
  // A topic has no authors whose relays to read, and the big relays prune:
  // #gardenstr was 5 posts across damus/primal/nos.lol/ours, 774 once these
  // archive-keeping relays were asked too (ditto 500+, nostr.mom 448,
  // oxtr 247, nostrplebs 175, nostr21 102, offchain 74 — 2026-09-30).
  const TOPIC_ARCHIVE_RELAYS = ['wss://relay.ditto.pub', 'wss://nostr.mom', 'wss://nostr.oxtr.dev',
    'wss://relay.nostrplebs.com', 'wss://nostr21.com', 'wss://offchain.pub'];
  const TOPIC_RELAYS = [...new Set([...NOTE_RELAYS, 'wss://relay.damus.io', 'wss://relay.primal.net', 'wss://nos.lol', ...TOPIC_ARCHIVE_RELAYS])];

  // ---- lists (NIP-51 follow sets, kind 30000) ------------------------------
  // A feed of hand-picked people IS a nostr list. Saved here it is published
  // under your key as a follow set, so Coracle, Nostria, Amethyst and the
  // rest show the same list; a list made in one of them turns up here as a
  // feed. The relays' copy wins when it is newer than ours (edited over
  // there); ours goes out on top of whatever they hold, carrying the
  // encrypted content other clients keep their private members in — those
  // are read (nip44 to yourself) and followed, never rewritten.
  const LIST_KIND = 30000;
  const LIST_SYNC_MS = 10 * 60_000;
  let listsAt = 0;
  let listsJob = null;
  const dTagOf = (ev) => (ev.tags.find((x) => x[0] === 'd') || [])[1];
  const listTopics = (ev) => [...new Set(ev.tags.filter((x) => x[0] === 't' && x[1]).map((x) => normTopic(x[1])).filter(Boolean))].slice(0, 20);
  async function privateMembers(ev) {
    if (!ev.content) return [];
    const c = (await selfCryptors()).find((x) => x.pk === ev.pubkey);
    if (!c) return [];
    try {
      const tags = JSON.parse(await c.dec(ev.content));
      return Array.isArray(tags) ? [...new Set(pTags(tags).map((x) => x[1].toLowerCase()))] : [];
    } catch { return []; } // nip04 from an older client, or not ours to read
  }
  // Your lists as the relays hold them, folded into the feeds: a new list
  // becomes a feed, a newer copy of a known one brings its members over.
  function syncFollowSets({ force = false } = {}) {
    const me = mePk();
    if (!me) return Promise.resolve();
    if (listsJob) return listsJob;
    if (!force && Date.now() - listsAt < LIST_SYNC_MS) return Promise.resolve();
    listsAt = Date.now();
    listsJob = (async () => {
      const mine = await Promise.resolve(relaysOf(me)).catch(() => []);
      const relays = [...new Set([...zapRelays(), ...(mine || []), ...PACK_RELAYS])];
      let evs;
      try { evs = await queryOn(relays, { kinds: [LIST_KIND, INTERESTS_KIND], authors: [me] }, 5000); } catch { listsAt = 0; return; }
      // your followed hashtags (NIP-51 interests): Everything reads them
      const interest = (evs || []).filter((e) => e.kind === INTERESTS_KIND).sort((a, b) => b.created_at - a.created_at)[0];
      if (interest) {
        const prev = wallet.loadFeatureState(INTERESTS, {}) || {};
        if (!(prev.at >= interest.created_at)) {
          wallet.saveFeatureState(INTERESTS, { tags: interest.tags.filter((x) => x[0] === 't' && x[1]).map((x) => normTopic(x[1])), at: interest.created_at });
          for (const f of st().feeds) if (f.interests && feedStates.get(f.id) !== feed) feedStates.delete(f.id);
          scheduleRepaint();
        }
      }
      evs = (evs || []).filter((e) => e.kind === LIST_KIND);
      const newest = new Map();
      for (const ev of evs || []) {
        const d = dTagOf(ev);
        if (d == null) continue;
        const cur = newest.get(d);
        if (!cur || ev.created_at > cur.created_at) newest.set(d, ev);
      }
      const s = st();
      let changed = false;
      for (const [d, ev] of newest) {
        const gone = (s.listsGone || {})[d];
        if (gone && ev.created_at <= gone) continue; // deleted here; a relay still serving it
        // a feed synced from another device before its list link did is that list
        const cur = s.feeds.find((f) => f.d === d) || s.feeds.find((f) => !f.d && f.id === d);
        if (cur && (cur.listAt || 0) >= ev.created_at) continue;
        const got = packFromEvent(ev);
        const priv = await privateMembers(ev);
        const pub = got.pks.filter((pk) => !priv.includes(pk));
        const topics = listTopics(ev);
        if (!cur && !pub.length && !priv.length && !topics.length) continue; // an empty list is not a feed
        const patch = { name: got.title || (cur && cur.name) || d, authors: pub.slice(0, FEED_AUTHORS_MAX), priv, topics, d, listAt: ev.created_at, listContent: ev.content || '', at: Date.now() };
        if (cur) Object.assign(cur, patch);
        else s.feeds.push({ id: 'list:' + d, follows: false, packs: [], ...patch });
        feedStates.delete(cur ? cur.id : 'list:' + d); // its query changed
        changed = true;
      }
      if (changed) { save(s); feedsChanged(); scheduleRepaint(); }
    })().finally(() => { listsJob = null; });
    return listsJob;
  }
  // Publish a feed as a follow set: its people as public p tags (a list's
  // private members stay in the content, untouched), its topics as t tags.
  async function publishFollowSet(def) {
    const id = await requireIdentity();
    const d = def.d || def.id;
    const tags = [['d', d], ['title', def.name || d],
      ...(def.authors || []).map((pk) => ['p', pk]),
      ...feedTopics(def).map((x) => ['t', x])];
    const created_at = Math.max(Math.floor(Date.now() / 1000), (def.listAt || 0) + 1);
    const partial = { kind: LIST_KIND, content: def.listContent || '', 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'));
    const s = st();
    const cur = s.feeds.find((f) => f.id === def.id);
    if (cur) { cur.d = d; cur.listAt = created_at; cur.at = Date.now(); save(s); feedsChanged(); }
    return d;
  }
  // NIP-09: ask the relays to drop the list — and remember that we did, so
  // a relay that keeps it anyway doesn't bring it back as a feed.
  async function deleteFollowSet(def) {
    if (!def || !def.d) return;
    const s = st();
    const created_at = Math.floor(Date.now() / 1000);
    const gone = Object.entries(s.listsGone || {}).sort((a, b) => b[1] - a[1]).slice(0, 99);
    s.listsGone = Object.fromEntries([[def.d, created_at], ...gone]);
    save(s);
    const id = await requireIdentity();
    const partial = { kind: 5, content: '', created_at, tags: [['a', LIST_KIND + ':' + id.pubkey + ':' + def.d], ['k', String(LIST_KIND)]] };
    const evt = id.signer instanceof Uint8Array ? finalizeEvent(partial, id.signer) : await id.signer.signEvent(partial);
    await publishOn(zapRelays(), evt);
  }
  // Someone's lists — follow sets and packs — for their profile page; the
  // members are cached as packs, so a tapped list opens as a feed at once.
  const profileLists = new Map(); // pk -> { at, status, items: [{ pk, d, kind, title, n }] }
  const LISTS_TTL = 60 * 60_000;
  function listsFor(pk) {
    let c = profileLists.get(pk);
    if (c && Date.now() - c.at < LISTS_TTL) return c;
    c = { at: Date.now(), status: 'loading', items: c ? c.items : [] };
    profileLists.set(pk, c);
    (async () => {
      const own = await Promise.resolve(relaysOf(pk)).catch(() => []);
      const relays = [...new Set([...PACK_RELAYS, ...(own || [])])];
      const evs = await queryOn(relays, { kinds: [LIST_KIND, PACK_KIND], authors: [pk] }, 5000).catch(() => []);
      const newest = new Map();
      for (const ev of evs || []) {
        const p = { ...packFromEvent(ev), kind: ev.kind };
        const key = packKey(p);
        const cur = newest.get(key);
        if (!cur || p.at > cur.at) newest.set(key, p);
      }
      const items = [...newest.values()].filter((p) => p.pks.length).sort((a, b) => b.at - a.at);
      for (const p of items) {
        const cur = packOf(p);
        if (!cur || cur.at < p.at) packsNow()[packKey(p)] = { pks: p.pks, title: p.title, at: p.at };
      }
      if (items.length) { try { wallet.saveFeatureState(PACK_CACHE, packsNow()); } catch {} }
      c.items = items.map((p) => ({ pk: p.pk, d: p.d, kind: p.kind, title: p.title || p.d, n: p.pks.length }));
      c.status = 'ready';
      scheduleRepaint();
    })().catch(() => { c.status = 'ready'; });
    return c;
  }
  // Open someone's list as a feed: yours is the saved feed it already is;
  // anyone else's a session feed built on it as a pack, savable from there.
  function openListFeed(p) {
    const own = p.pk === mePk() ? st().feeds.find((f) => f.d === p.d) : null;
    const id = own ? own.id : 'list:' + packKey(p);
    if (!own) adhocFeeds.set(id, { id, name: p.title || p.d, packs: [{ pk: p.pk, d: p.d, kind: p.kind === PACK_KIND ? undefined : p.kind, relays: [], title: p.title || '' }] });
    ui.userSearch = null; ui.profilePk = null; ui.noteThread = null; ui.liveStream = null; ui.goLive = null; ui.feedEdit = null; ui.profOverThread = false;
    ui.chatOpen = true; ui.msgView = 'feed';
    switchFeed(id);
  }
  // Which of your feeds someone is in — and a tap to put them in another.
  function listPickSheet() {
    if (!ui.listPick) return null;
    const pk = ui.listPick;
    const close = () => { ui.listPick = null; render(); };
    const feeds = st().feeds.filter((f) => !f.of); // a timeline is someone, not a list
    const toggle = (f) => {
      const s = st();
      const def = s.feeds.find((x) => x.id === f.id);
      if (!def || (def.priv || []).includes(pk)) return;
      const had = (def.authors || []).includes(pk);
      def.authors = had ? def.authors.filter((x) => x !== pk) : [...(def.authors || []), pk].slice(0, FEED_AUTHORS_MAX);
      def.at = Date.now();
      save(s);
      feedsChanged();
      feedStates.delete(def.id);
      render();
      if (def.d) publishFollowSet(def).catch((e) => { if (!(e instanceof NoIdentity)) toast(e.message || String(e)); });
    };
    return h('div', {
      class: 'confirm-pop-backdrop',
      onClick: (e) => { if (e.target === e.currentTarget) close(); },
    },
      h('div', { class: 'card col confirm-pop list-pick', style: 'gap:8px' },
        h('div', { class: 'row gap6', style: 'align-items:center' },
          avatar(pk, 'chat-avatar', false),
          h('div', { class: 'col', style: 'min-width:0' },
            h('div', { class: 'chat-name' }, displayName(pk)),
            h('div', { class: 'small muted' }, t('listPickTitle')))),
        feeds.length ? null : h('div', { class: 'small faint' }, t('listPickEmpty')),
        ...feeds.map((f) => {
          const on = (f.authors || []).includes(pk) || (f.priv || []).includes(pk);
          return h('button', {
            class: 'btn-block list-pick-row' + (on ? ' on' : ''), style: 'text-align:left', type: 'button',
            'aria-pressed': on ? 'true' : 'false',
            onClick: () => toggle(f),
          }, (on ? '\u2611' : '\u2610') + '  ' + f.name);
        }),
        h('button', {
          class: 'btn-block', style: 'text-align:left', type: 'button',
          onClick: () => {
            ui.listPick = null;
            // the editor lives on the feed screen; the profile gives way to it
            ui.profilePk = null; ui.profOverThread = false; ui.noteThread = null; ui.liveStream = null; ui.goLive = null; ui.userSearch = null;
            ui.chatOpen = true; ui.msgView = 'feed';
            openFeedEditor(null);
            ui.feedEdit.authors = [pk];
            render();
          },
        }, '+  ' + t('listNew')),
        h('button', { class: 'btn-ghost btn-block', onClick: close }, t('back'))));
  }

  // 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 authorChunks = (authors) => { const out = []; for (let i = 0; i < authors.length; i += REQ_AUTHORS) out.push(authors.slice(i, i + REQ_AUTHORS)); return out; };
  const feedAuthors = (def = feedDef()) => {
    if (!def) return [];
    // your own posts belong in the feed of the people you follow, as in
    // every other client — not only for the moment after posting. Yours
    // first: a feed's opening ask takes the authors in chunks of REQ_AUTHORS,
    // and with 898 follows a key added last sat in the third chunk — the
    // feed opened without your newest post until a later refresh.
    const set = new Set(def.follows && mePk() ? [mePk()] : []);
    if (def.follows) for (const pk of followsNow().set) set.add(pk);
    for (const pk of def.authors || []) if (pk) set.add(pk);
    for (const pk of def.priv || []) if (pk) set.add(pk); // a list's private members
    for (const pk of packAuthors(def)) set.add(pk);
    if (def.of) for (const pk of ofFollows.get(def.of)?.authors || []) set.add(pk);
    return [...set].slice(0, FEED_AUTHORS_MAX);
  };
  // Someone's timeline is their follow list, read from the relays when the
  // feed is opened (and again after ten minutes) — never copied into the
  // feed itself, so a saved one stays small in sync and follows them.
  const ofFollows = new Map(); // pk -> { authors, at, loading }
  const ofLoaded = (def) => !!ofFollows.get(def.of)?.at;
  function loadOfFollows(def) {
    const pk = def.of;
    let f = ofFollows.get(pk);
    if (!f) { f = { authors: [], at: 0, loading: false }; ofFollows.set(pk, f); }
    if (f.loading || (f.at && Date.now() - f.at < 600_000)) return;
    f.loading = true;
    liveProfileOf(pk); // their name and face for the title
    // Their relays and Primal's cache at once: a list kept only on their own
    // outbox relays reads as nobody followed. Primal's copy is the signed
    // event itself, with the follows' profiles beside it; both are checked
    // before anything is believed.
    Promise.all([
      queryOn([...new Set([...(def.relays || []), ...PROFILE_RELAYS, ...NOTE_RELAYS])], { kinds: [3], authors: [pk] }, 6000).catch(() => []),
      primalCache('contact_list', { pubkey: pk }, 6000).then((evs) => verifiedPrimal(evs, [0, 3])).catch(() => []),
    ])
      .then(([relayEvs, primalEvs]) => {
        const evs = [...(relayEvs || []), ...primalEvs.filter((e) => e.kind === 3 && e.pubkey === pk)];
        const newest = evs.sort((a, b) => b.created_at - a.created_at)[0];
        const had = f.at;
        if (newest || !had) f.authors = newest ? hexList(newest.tags.filter((x) => x[0] === 'p').map((x) => x[1])) : [];
        f.at = Date.now(); f.loading = false;
        // whatever was built before the list was known
        for (const id of [...feedStates.keys()]) {
          if (feedDef(id)?.of !== pk || id === curFeedId) continue;
          dropFeedState(id);
        }
        if (feedDef(curFeedId)?.of === pk) { dropFeedState(curFeedId); selectFeed(curFeedId); }
        scheduleRepaint();
      });
  }

  // ---- follows & followers -------------------------------------------------
  // Whom someone follows is their own kind 3 (ofFollows, above). Who follows
  // THEM is everyone else's kind 3 — no relay will count that — so the
  // number and the list come from Primal's cache, which indexes the network
  // for exactly this. Only pubkeys are taken from it: names and faces still
  // come from the relays, as everywhere else.
  const socialCounts = new Map(); // pk -> { follows, followers, at, loading }
  function loadSocial(pk) {
    const cur = socialCounts.get(pk);
    if (cur && (cur.loading || Date.now() - (cur.at || 0) < 600_000)) return cur;
    socialCounts.set(pk, { ...(cur || {}), loading: true });
    primalCache('user_profile', { pubkey: pk }, 6000).then((evs) => {
      let c = {};
      try { c = JSON.parse(evs.find((e) => e.kind === 10000105)?.content || '{}'); } catch {}
      const num = (n) => (Number.isFinite(n) && n >= 0 ? n : null);
      socialCounts.set(pk, { follows: num(c.follows_count), followers: num(c.followers_count), at: Date.now() });
    }).catch(() => socialCounts.set(pk, { ...(cur || {}), at: Date.now() })).finally(scheduleRepaint);
    return socialCounts.get(pk);
  }
  // Primal's events, signature-checked off the main thread; the profiles
  // among them fill names and faces the relays didn't have.
  async function verifiedPrimal(evs, kinds) {
    const want = (evs || []).filter((e) => kinds.includes(e.kind) && e.sig && /^[0-9a-f]{64}$/.test(e.pubkey || ''));
    const ok = await verifyEventsAsync(want);
    const good = want.filter((e, i) => ok[i]);
    let applied = 0;
    for (const e of good) if (e.kind === 0 && applyProfile(e.pubkey, e)) applied++;
    if (applied) scheduleRepaint();
    return good;
  }
  const followersOf = new Map(); // pk -> { pks, at, loading }
  function loadFollowers(pk) {
    const cur = followersOf.get(pk);
    if (cur && (cur.loading || Date.now() - (cur.at || 0) < 600_000)) return cur;
    followersOf.set(pk, { pks: cur?.pks || [], loading: true });
    const ask = (limit) => primalCache('user_followers', { pubkey: pk, limit }, 8000)
      .then((evs) => verifiedPrimal(evs, [0])).then((evs) => [...new Set(evs.map((e) => e.pubkey))]);
    // a first screenful fast, then the long list behind it
    ask(60).then((pks) => {
      const now = followersOf.get(pk);
      if (now?.loading && pks.length > (now.pks || []).length) { followersOf.set(pk, { pks, loading: true }); scheduleRepaint(); }
    }).catch(() => {});
    ask(500).then((pks) => {
      const now = followersOf.get(pk);
      // the people already on screen keep their places; the rest go after
      const shown = now?.pks || [];
      const seen = new Set(shown);
      followersOf.set(pk, { pks: [...shown, ...pks.filter((x) => !seen.has(x))], at: Date.now() });
    }).catch(() => followersOf.set(pk, { pks: followersOf.get(pk)?.pks || [], at: Date.now() })).finally(scheduleRepaint);
    return followersOf.get(pk);
  }
  const compactNum = (n) => { try { return new Intl.NumberFormat(getLang(), { notation: 'compact', maximumFractionDigits: 1 }).format(n); } catch { return String(n); } };
  // "116 Following · 572 Followers" under the bio; each opens its list
  // right below, on the same page.
  function socialLine(pk) {
    const c = loadSocial(pk);
    const f = ofFollows.get(pk);
    const follows = f?.at ? f.authors.length : c?.follows;
    const pick = (which) => {
      ui.profPeople = ui.profPeople === which ? null : which;
      ui.profPeopleN = 50;
      if (which === 'following') loadOfFollows({ of: pk });
      else loadFollowers(pk);
      render();
    };
    // not known yet: an invisible stand-in holds the place, and the number
    // fades in over it (no dash flashing first)
    const btn = (which, n, label) => h('button', {
      type: 'button', class: 'social-count' + (ui.profPeople === which ? ' on' : ''), 'aria-expanded': String(ui.profPeople === which),
      onClick: () => pick(which),
    }, h('b', { class: 'social-n' + (n == null ? ' pending' : '') }, n == null ? '0' : compactNum(n)), ' ', label);
    const shown = ui.npubShown === pk;
    return h('div', { class: 'row social-line' },
      btn('following', follows, t('profFollowing')),
      btn('followers', c?.followers, t('profFollowers')),
      h('button', {
        type: 'button', class: 'social-count npub-toggle' + (shown ? ' on' : ''), style: 'margin-left:auto', 'aria-expanded': String(shown),
        onClick: () => { ui.npubShown = shown ? null : pk; render(); },
      }, t('profKeyLink')));
  }
  function socialList(pk) {
    const which = ui.profPeople;
    if (!which) return null;
    const src = which === 'following' ? ofFollows.get(pk) : followersOf.get(pk);
    const all = which === 'following' ? (src?.authors || []) : (src?.pks || []);
    const pks = all.filter((x) => !hiddenPk(x));
    const n = ui.profPeopleN || 50;
    const loading = !src || src.loading || (which === 'following' && !src.at);
    const total = which === 'followers' ? socialCounts.get(pk)?.followers : null;
    return h('div', { class: 'col social-list', style: 'gap:6px' },
      loading && !pks.length ? h('div', { class: 'row', style: 'justify-content:center;padding:10px' }, h('span', { class: 'spinner sm' })) : null,
      !loading && !pks.length ? h('div', { class: 'small faint', style: 'text-align:center;padding:8px' }, t(which === 'following' ? 'profFollowsNone' : 'profFollowersNone')) : null,
      pks.length ? h('div', { class: 'list' }, ...pks.slice(0, n).map((x) => {
        const p = profileOf(x) || {};
        const sub = p.nip05 ? String(p.nip05).replace(/^_@/, '') : (npubOf(x) || '').slice(0, 20) + '…';
        return h('div', { class: 'item chat-thread-row', 'data-key': 'sp:' + x, onClick: () => openProfile(x) },
          avatar(x, 'chat-avatar', false),
          h('div', { class: 'col grow', style: 'min-width:0;gap:1px' },
            h('div', { class: 'chat-name' }, displayName(x)),
            h('div', { class: 'muted small chat-preview' }, sub)));
      })) : null,
      pks.length > n ? h('button', { class: 'btn-ghost btn-block', onClick: () => { ui.profPeopleN = n + 50; render(); } }, t('showMore')) : null,
      // Primal hands back the followers it knows best, not always all of them
      which === 'followers' && !loading && total && pks.length < total && pks.length <= n
        ? h('div', { class: 'small faint', style: 'text-align:center' }, t('profFollowersPartial', { n: compactNum(pks.length), total: compactNum(total) }))
        : null);
  }

  function feedNow() {
    if (!feedDef(curFeedId)) curFeedId = EVERYTHING; // a feed deleted on another device
    const id = viewId(); // the feed, or its Conversations view
    let c = feedStates.get(id);
    if (!c) {
      let stored = [];
      try { stored = feedDisk()?.read(id) || wallet.loadFeatureState(feedCacheKey(id), []) || []; } catch {}
      if (!Array.isArray(stored)) stored = [];
      if (!stored.length) stored = borrowedNotes(feedDef(id));
      stored = stored.slice(0, FEED_STORE);
      c = { id, status: 'loading', notes: stored, shown: FEED_PAGE, at: 0, booting: true, presentations: new Map() };
      feedStates.set(id, c);
      while (feedStates.size > 4) {
        const oldest = feedStates.keys().next().value;
        feedStates.get(oldest).stopped = true;
        feedStates.delete(oldest);
      }
      feed = c;
      // Only the opening page gates first paint. The next page warms on the
      // side, so an offscreen image cannot delay the whole feed.
      c.boot = notesReady(stored.slice(0, FEED_PAGE), { parent: feedReplies(c) }).finally(() => {
        c.booting = false;
        c.prepared = null;
        if (!c.stopped && ui.chatOpen && ui.msgView === 'feed' && c === feed) scheduleRepaint();
      });
      c.boot.then(() => {
        if (c.stopped) return;
        notesReady(stored.slice(FEED_PAGE, FEED_PAGE * 2), { parent: feedReplies(c) });
      });
      prefetchFeed(c);
    }
    feed = c;
    return c;
  }
  let feedWarmTimer = null, feedWarmSession = 0;
  async function prefetchFeed(c) {
    const def = feedDef(c.id);
    const authors = feedAuthors(def), topics = feedTopics(def);
    if (!authors.length && !topics.length && !(def && def.all)) { c.status = 'ready'; return; }
    c.at = Date.now();
    const merge = { newerThan: c.notes.length ? c.notes[0].created_at : Infinity };
    if (def && def.curated) {
      try { await popularPass({}, merge, c, def); } catch {} finally {
        if (!c.stopped) { c.status = 'ready'; if (c === feed && ui.chatOpen && ui.msgView === 'feed') { scheduleRepaint(); watchFeed(); } }
      }
      return;
    }
    try {
      const orT = orTopicsOf(def);
      await Promise.all([
        // people's reposts with their posts (a topic or firehose ask: posts only);
        // every author, a chunk of them per ask
        ...(authors.length ? authorChunks(authors) : [null]).map((chunk) =>
          queryFeed(feedRelaysOr(def, def && def.all ? FIREHOSE_RELAYS : NOTE_RELAYS), { kinds: chunk && !topics.length ? [...FEED_KINDS, REPOST] : FEED_KINDS, limit: FEED_PAGE,
            ...(chunk ? { authors: chunk } : {}), ...(topics.length ? { '#t': topics } : {}) }, merge, c, 3000)),
        orT.length ? queryFeed(feedRelaysOr(def, TOPIC_RELAYS), { kinds: FEED_KINDS, limit: FEED_PAGE, '#t': orT }, merge, c, 3000) : null]);
    } catch {} finally {
      if (!c.stopped) {
        c.status = 'ready';
        if (c === feed && ui.chatOpen && ui.msgView === 'feed') { scheduleRepaint(); watchFeed(); seedOtherFeeds(); }
      }
    }
  }
  // A feed never opened on this device (or pushed out of the disk cache)
  // would open on a bare spinner. Posts another open feed already holds —
  // by its people, on its topics — stand in until the relays answer.
  function borrowedNotes(def) {
    if (!def || def.all) return [];
    const authors = new Set(feedAuthors(def)), topics = new Set(feedTopics(def)), orT = new Set(orTopicsOf(def));
    if (!authors.size && !topics.size) return [];
    const tagged = (e, set) => (e.tags || []).some((x) => x[0] === 't' && set.has(normTopic(x[1])));
    const fits = (e) => feedKeeps(def, e) && (((!authors.size || authors.has(e.pubkey))
      && (!topics.size || tagged(e, topics))) || (orT.size && tagged(e, orT)));
    const seen = new Set(), out = [];
    for (const o of feedStates.values()) {
      for (const e of o.notes) if (!seen.has(e.id) && fits(e) && !hidden(e)) { seen.add(e.id); out.push(e); }
    }
    return out.sort((a, b) => b.created_at - a.created_at).slice(0, FEED_PAGE);
  }
  // And once the feed on screen has settled, the other feeds' first few
  // posts are fetched ahead into the disk cache, one feed at a time, so
  // switching to any of them paints at once.
  const SEED_EVERY = 15 * 60_000;
  let feedsSeededAt = 0;
  async function seedOtherFeeds() {
    const disk = feedDisk();
    if (!disk || isVisitor() || Date.now() - feedsSeededAt < SEED_EVERY) return;
    feedsSeededAt = Date.now();
    for (const def of feedList()) {
      if (def.curated || def.of || feedStates.has(def.id) || disk.has(def.id)) continue;
      const authors = feedAuthors(def), topics = feedTopics(def);
      if (!authors.length && !topics.length) continue;
      try {
        const events = (await Promise.all((authors.length ? authorChunks(authors) : [null]).map((chunk) =>
          queryOn(feedRelaysOr(def, NOTE_RELAYS), { kinds: feedKinds(def), limit: FEED_SEED_POSTS * 2,
            ...(chunk ? { authors: chunk } : {}), ...(topics.length ? { '#t': topics } : {}) }, 3000)))).flat();
        if (feedStates.has(def.id)) continue; // opened while we were asking
        disk.seed(def.id, events.filter((e) => feedKeeps(def, e) && !hidden(e)));
      } catch {}
    }
  }
  // Make a feed the current one (no paint): Back/Forward through the
  // history restores ui.feedId and the view catches up from here.
  function selectFeed(id) {
    if (!feedDef(id)) return;
    if (feedDef(id).of) loadOfFollows(feedDef(id));
    if (id !== curFeedId) {
      curFeedId = id;
      if (!adhocFeeds.has(id)) { try { localStorage.setItem(feedLsKey(), id); } catch {} }
    }
    ui.feedId = id;
    stopFeedWatch();
    const c = feedNow();
    c.unseen = 0; c.fresh = null; c.ahead = null; c.shown = FEED_PAGE;
    admitFeed(c.deferred || [], c, true);
    // An already warmed feed can paint synchronously on entry.
    if (!c.booting) c.presentations.clear();
    watchFeed();
    refreshFeed({}, c);
  }
  function switchFeed(id) {
    if (!feedDef(id)) return;
    selectFeed(id);
    try { window.scrollTo({ top: 0 }); } catch {}
    render();
  }
  // ---- feeds anyone can open --------------------------------------------
  // Every kind of feed has a URL, and a visitor with no wallet can read it.
  const isVisitor = () => !wallet.mnemonic && !wallet.xpub && !wallet.xprv;
  const showFeed = (id) => {
    ui.userSearch = null; ui.profilePk = null; ui.profOverThread = false; ui.noteThread = null; ui.liveStream = null; ui.goLive = null; ui.feedEdit = null;
    ui.chatOpen = true; ui.msgView = 'feed';
    if (ui.screen === 'wallet') ui.pubProf = null; // the wallet's chrome owns it
    switchFeed(id);
  };
  const hexList = (pks) => [...new Set(pks.filter((pk) => /^[0-9a-f]{64}$/i.test(pk || '')).map((pk) => pk.toLowerCase()))];
  // The timeline someone else sees: their follow list, read from the relays,
  // becomes the authors of a feed for this session.
  function openFeedOf(pk, relays = [], readFrom = []) {
    const id = 'of:' + pk + (readFrom.length ? '@' + readFrom.join(',') : '');
    let def = adhocFeeds.get(id);
    if (!def) {
      def = { id, name: '', follows: false, authors: [], packs: [], topics: [], of: pk, relays: readFrom };
      adhocFeeds.set(id, def);
      loadOfFollows({ ...def, relays: [...relays, ...readFrom] });
    }
    showFeed(id);
  }
  // A follow pack (or someone's follow set: a pack by another name).
  function openPackFeed(p, readFrom = []) {
    const id = 'pack:' + packKey(p) + (readFrom.length ? '@' + readFrom.join(',') : '');
    if (!adhocFeeds.has(id)) adhocFeeds.set(id, { id, name: (packOf(p) || {}).title || t('feedPackName'), follows: false, authors: [], packs: [p], topics: [], relays: readFrom });
    const def = adhocFeeds.get(id);
    fetchPack(p).then((got) => {
      if (got && got.title) def.name = got.title;
      const c = feedStates.get(id);
      if (c) { c.at = 0; if (c === feed) refreshFeed({ live: false }, c); else dropFeedState(id); }
      scheduleRepaint();
    }).catch(() => {});
    showFeed(id);
  }
  // Any mix of people, packs and topics, carried in the URL itself.
  const urlRelays = (q) => [...new Set((q.get('r') || '').split(',').map(normRelay).filter(Boolean))].slice(0, 12);
  // Plain /feed: every post the coinos relay carries (or the relays named).
  // /feed is Popular: everything the relays carry, curated (no machine
  // posts, the reader's language, and only what someone reacted to).
  // /feed/all is the same relays raw.
  function openFirehose(readFrom = [], { raw = false } = {}) {
    if (!raw && !readFrom.length && !isVisitor()) { showFeed(EVERYTHING); return; }
    const id = (raw ? 'raw' : 'all') + (readFrom.length ? '@' + readFrom.join(',') : ':visitor');
    if (!adhocFeeds.has(id)) adhocFeeds.set(id, { id, name: raw ? t('feedFirehose') : t('feedPopular'), follows: false, authors: [], packs: [], topics: [], all: true, curated: !raw, relays: readFrom });
    showFeed(id);
  }
  function openQueryFeed(q) {
    const authors = hexList((q.get('p') || '').split(',').map((x) => parseNostrPubkey(x.trim()) || ''));
    const topics = [...new Set((q.get('t') || '').split(',').map(normTopic).filter(Boolean))];
    const packs = (q.get('pack') || '').split(',').map((x) => parsePackLink(x.trim())).filter(Boolean);
    const relays = urlRelays(q);
    if (!authors.length && !topics.length && !packs.length) { openFirehose(relays); return true; }
    const sig = JSON.stringify([authors, topics, packs.map(packKey), relays]);
    let hsh = 5381; for (let i = 0; i < sig.length; i++) hsh = ((hsh * 33) ^ sig.charCodeAt(i)) >>> 0;
    const id = 'url:' + hsh.toString(36);
    if (!adhocFeeds.has(id)) adhocFeeds.set(id, { id, name: (q.get('name') || '').trim().slice(0, 40) || t('feedSharedName'), follows: false, authors, packs, topics, relays });
    showFeed(id);
    return true;
  }
  function openFeedUrl(path, search) {
    let q; try { q = new URLSearchParams(search || ''); } catch { q = new URLSearchParams(); }
    const readFrom = urlRelays(q);
    for (const r of readFrom) { try { resetRelay(r); } catch {} } // named in the link: tried even if it was sick
    if (!path) return openQueryFeed(q);
    if (/^all$/i.test(path)) { openFirehose(readFrom, { raw: true }); return true; }
    if (/^t\//i.test(path)) { const tag = normTopic(decodeURIComponent(path.slice(2))); if (!tag) return false; openTopicFeed(tag, readFrom); return true; }
    const pk = parseNostrPubkey(path);
    if (pk) { let relays = []; try { relays = parseNostrRef(path.toLowerCase())?.relays || []; } catch {} openFeedOf(pk, relays, readFrom); return true; }
    const pack = /^naddr1/i.test(path) ? parsePackLink(path) : null;
    if (pack) { openPackFeed(pack, readFrom); return true; }
    return false;
  }
  // The URL a feed answers to. `share` also names the built-in Following
  // feed (as this person's timeline); the address bar shows only feeds that
  // came from a URL, so a saved feed is never doubled by its own link.
  function feedPath(def, { share = false } = {}) {
    if (!def) return null;
    const r = feedRelays(def) ? '?r=' + encodeURIComponent(feedRelays(def).join(',')) : '';
    if (def.all) return (def.curated ? '/feed' : '/feed/all') + r;
    if (def.builtin) return share && mePk() && !def.replies ? '/feed/' + npubOf(mePk()) + r : null;
    if (def.of) return '/feed/' + npubOf(def.of) + r;
    const authors = def.authors || [], topics = feedTopics(def), packs = def.packs || [];
    if (!authors.length && !packs.length && topics.length === 1) return '/feed/t/' + encodeURIComponent(topics[0]) + r;
    if (!authors.length && !topics.length && packs.length === 1) {
      const p = packs[0];
      const n = packNaddr(`${p.kind || PACK_KIND}:${p.pk}:${p.d}`);
      if (n) return '/feed/' + n + r;
    }
    if (!authors.length && !packs.length && !topics.length) return null;
    const q = new URLSearchParams();
    if (feedRelays(def)) q.set('r', feedRelays(def).join(','));
    if (authors.length) q.set('p', authors.map((pk) => npubOf(pk)).join(','));
    if (topics.length) q.set('t', topics.join(','));
    if (packs.length) q.set('pack', packs.map((p) => packNaddr(`${p.kind || PACK_KIND}:${p.pk}:${p.d}`)).filter(Boolean).join(','));
    if (def.name && !def.builtin) q.set('name', def.name);
    return '/feed?' + q.toString();
  }
  // The relays a feed reads from: a list to add to and take from, kept on
  // the feed (a session feed in memory, a saved one in the state, Following
  // beside it). Changing it rebuilds the feed from those relays.
  // Forget a feed's state so it is rebuilt; a fetch still in flight for the
  // old one lands nowhere (it would otherwise fill the orphan, not the new).
  const dropFeedState = (id) => {
    for (const k of [id, id + VIEW_SUFFIX]) { const c = feedStates.get(k); if (c) c.stopped = true; feedStates.delete(k); }
  };
  // Popular's defaults before 2026-10-04: a list saved that matches them
  // exactly was the defaults, kept by an edit, and follows the new ones.
  function oldPopularDefault(list) {
    const OLD_POPULAR = ['wss://relay.coinos.io', 'wss://relay.damus.io', 'wss://nos.lol', 'wss://relay.primal.net'];
    return Array.isArray(list) && list.length === OLD_POPULAR.length && OLD_POPULAR.every((r) => list.includes(r));
  }
  function setFeedRelays(def, relays) {
    relays = [...new Set(relays.map(normRelay).filter(Boolean))].slice(0, 12);
    // the usual list, picked by hand, is no list of one's own
    const usual = usualRelays(def);
    if (usual && relays.length === usual.length && usual.every((r) => relays.includes(r))) relays = [];
    for (const r of relays) { try { resetRelay(r); } catch {} } // chosen by hand: tried again even if it was sick
    if (def.builtin) { const s = st(); s.builtinRelays = { ...(s.builtinRelays || {}), [def.id]: relays }; save(s); }
    else if (adhocFeeds.has(def.id)) def.relays = relays;
    else { const s = st(); s.feeds = s.feeds.map((f) => (f.id === def.id ? { ...f, relays, at: Date.now() } : f)); save(s); feedsChanged(); }
    dropFeedState(def.id);
    try { wallet.saveFeatureState(feedCacheKey(def.id), []); } catch {}
    if (curFeedId === def.id) selectFeed(def.id);
    // the address bar carries the relays of a feed that came from a URL
    if (adhocFeeds.has(def.id) && ui.chatOpen && ui.msgView === 'feed') { try { history.replaceState(history.state, '', feedPath(def) || '/'); } catch {} }
  }
  const usualRelays = (def) => (def.curated ? POPULAR_RELAYS : def.all ? FIREHOSE_RELAYS : (feedAuthors(def).length ? null : TOPIC_RELAYS));
  function relayPanel(def) {
    const e = ui.feedRelayEdit;
    const custom = feedRelays(def);
    const usual = usualRelays(def);
    const list = custom || usual || [];
    const host = (u) => u.replace(/^wss?:\/\//, '');
    const commit = (next) => { setFeedRelays(def, next); e.other = null; e.input = ''; render(); };
    // each relay is a pick from the popular list (the one in place stays
    // offered even when it isn't popular), or Other… for one typed in
    const rowSelect = (u, i) => h('select', { class: 'grow', style: 'min-width:0', onChange: (ev) => {
        const v = ev.target.value;
        if (v === '__other') { e.other = u; e.input = ''; render(); return; }
        const next = list.slice(); next[i] = v; commit(next);
      } },
      ...[...new Set([u, ...RELAY_PICKS])].filter((x) => x === u || !list.includes(x)).map((x) => h('option', { value: x, selected: x === u ? 'selected' : undefined }, host(x))),
      h('option', { value: '__other' }, t('feedRelayOther')));
    const inputRow = (onSave) => h('div', { class: 'row gap6' },
      h('input', { type: 'text', class: 'grow', placeholder: t('feedRelayPh'), value: e.input, autocapitalize: 'none', autocomplete: 'off', spellcheck: 'false', autofocus: true,
        onInput: (ev) => { e.input = ev.target.value; }, onKeyDown: (ev) => { if (ev.key === 'Enter') { ev.preventDefault(); onSave(); } } }),
      h('button', { class: 'btn-sm', type: 'button', onClick: onSave }, t('feedRelayAdd')),
      h('button', { class: 'btn-sm', type: 'button', 'aria-label': t('back'), onClick: () => { e.other = null; render(); } }, '\u00d7'));
    const saveOther = (i) => () => {
      const r = normRelay(e.input);
      if (!r) { toast(t('feedRelayBad')); return; }
      const next = list.slice(); if (i == null) next.push(r); else next[i] = r;
      commit(next);
    };
    return h('div', { class: 'card col', style: 'gap:8px;padding:10px 12px;background:var(--surface2)' },
      h('div', { class: 'small muted' }, t('feedRelaysHint')),
      ...list.map((u, i) => e.other === u
        ? inputRow(saveOther(i))
        : h('div', { class: 'row gap6', style: 'align-items:center' },
            rowSelect(u, i),
            h('button', { class: 'btn-sm', type: 'button', 'aria-label': t('remove'), onClick: () => commit(list.filter((_, j) => j !== i)) }, '\u00d7'))),
      !list.length && !usual ? h('div', { class: 'small faint' }, t('feedRelaysOutbox')) : null,
      e.other === '__new'
        ? inputRow(saveOther(null))
        : h('select', { 'aria-label': t('feedRelayPick'), onChange: (ev) => {
            const v = ev.target.value; ev.target.value = '';
            if (!v) return;
            if (v === '__other') { e.other = '__new'; e.input = ''; render(); return; }
            commit([...list, v]);
          } },
            h('option', { value: '', selected: 'selected' }, t('feedRelayPick')),
            ...RELAY_PICKS.filter((x) => !list.includes(x)).map((x) => h('option', { value: x }, host(x))),
            h('option', { value: '__other' }, t('feedRelayOther'))),
      h('div', { class: 'row gap6' },
        custom ? h('button', { class: 'btn-ghost btn-sm', type: 'button', onClick: () => commit([]) }, t('feedRelaysDefault')) : null,
        h('button', { class: 'btn-sm', type: 'button', style: 'margin-left:auto', onClick: () => { ui.feedRelayEdit = null; render(); } }, t('feedRelaysDone'))));
  }
  async function shareFeed(def) {
    const path = feedPath(def, { share: true });
    if (!path) return;
    const url = location.origin + path;
    try {
      if (navigator.share) await navigator.share({ url });
      else { await navigator.clipboard.writeText(url); toast(t('copied')); }
    } catch {}
  }
  // A follow list that changed means every feed built on it has the wrong
  // authors — the one on screen is rebuilt in place, not offered behind the
  // pill; the others are simply forgotten and rebuilt when next opened.
  function feedAuthorsChanged() {
    for (const c of [...feedStates.values()]) {
      const def = feedDef(c.id);
      if (!def || !def.follows) continue;
      if (c === feed) { c.at = 0; refreshFeed({ live: false }, c); } else feedStates.delete(c.id);
    }
  }
  // A topic straight from search or a #tag in a post: a feed for this
  // session (a saved single-topic feed with the same tag is reused).
  function openTopicFeed(tag, relays = []) {
    tag = normTopic(tag);
    if (!tag) return;
    const saved = relays.length ? null : st().feeds.find((f) => !f.follows && !(f.authors || []).length && feedTopics(f).length === 1 && feedTopics(f)[0] === tag);
    const id = saved ? saved.id : 'topic:' + tag + (relays.length ? '@' + relays.join(',') : '');
    if (!saved && !adhocFeeds.has(id)) adhocFeeds.set(id, { id, name: '#' + tag, topics: [tag], relays });
    ui.userSearch = null; ui.profilePk = null; ui.noteThread = null; ui.liveStream = null; ui.goLive = null; ui.feedEdit = null;
    ui.chatOpen = true; ui.msgView = 'feed';
    switchFeed(id);
  }
  // Something above the posts is in use — a post being written, the relay
  // panel, a focused field — so new posts wait behind the pill rather than
  // push it off the screen.
  const headBusy = () => {
    if (ui.profCompose != null || ui.feedRelayEdit) return true;
    try {
      const a = document.activeElement;
      // a field, not a button: a tapped chip keeps the focus afterwards
      return !!a && !!a.closest('input, textarea, select, [contenteditable], coinos-text')
        && !!a.closest('.feed-page') && !a.closest('.notes-feed');
    } catch { return false; }
  };

  // Resolve the whole first presentation before admitting a row. The
  // deadline leaves unavailable resources as stable, clickable fallbacks;
  // a late response is useful on the next visit, not a mid-read replacement.
  const READY_MS = 8000;
  const mediaReady = new Map(); // URL -> decoded dimensions
  const mediaFailed = new Set(); // URLs whose picture refused to load (not merely slow)
  const corsRefused = new Set(); // pictures whose host wouldn't hand over the bytes (this session)
  const mediaWarming = new Map();
  // A post's photo is often the camera's original — 3024px wide, twelve
  // megapixels — painted into a column a sixth of that. Chrome decodes it
  // again whenever the page that holds it is rebuilt (its decoded copy is
  // long evicted by then), and until it has, the picture is a blank box: the
  // feed came back from a profile with every post's text in place and its
  // photo 200ms behind. So a big picture is painted from a copy the size the
  // column can actually show, made once and kept on disk; it decodes in a few
  // milliseconds, inside the same frame as the text. The original is still
  // what the lightbox opens. A host that won't hand over its bytes (no CORS)
  // keeps the old way.
  const MEDIA_THUMB_W = 1100; // the 560px column at 2x
  const MEDIA_THUMB_CACHE = 'coinos-media-thumbs-v1';
  const MEDIA_THUMB_MAX = 400; // copies kept on disk, oldest out first
  const thumbStore = () => (typeof caches !== 'undefined' ? caches.open(MEDIA_THUMB_CACHE) : Promise.reject(new Error('no cache')));
  async function storedMediaThumb(url) {
    try {
      const r = await (await thumbStore()).match(url);
      if (!r) return null;
      const dims = JSON.parse(r.headers.get('x-dims') || 'null');
      if (!dims || !dims.width) return null;
      const src = r.headers.get('x-original') === '1' ? null : URL.createObjectURL(await r.blob());
      return { ...dims, thumb: src };
    } catch { return null; }
  }
  async function makeMediaThumb(url) {
    if (noCorsHost(url) || typeof createImageBitmap === 'undefined' || typeof OffscreenCanvas === 'undefined') return null;
    let blob;
    try {
      const res = await corsFetch(url, AbortSignal.timeout(READY_MS));
      if (!res.ok) return null;
      blob = await res.blob();
    } catch (e) {
      if (e && e.corsRefused) { noteNoCors(url); corsRefused.add(url); } // refused, as corsFetch confirmed
      return null;
    }
    const result = await makeImageThumbnails(blob, {
      width: MEDIA_THUMB_W, tileSize: tileThumbs.has(url) ? 0 : TILE_PX,
    });
    if (!result) return null;
    const dims = { width: result.width, height: result.height }, out = result.media;
    // Both sizes share one decode in the worker; only cache writes and object
    // URLs come back to the page. The lightbox still uses the original.
    if (result.tile) await saveTileThumb(url, result.tile).catch(() => {});
    try {
      const store = await thumbStore();
      await store.put(url, new Response(out || new Blob(), { headers: { 'x-dims': JSON.stringify(dims), 'x-original': out ? '0' : '1' } }));
      const keys = await store.keys();
      for (const k of keys.slice(0, Math.max(0, keys.length - MEDIA_THUMB_MAX))) store.delete(k);
    } catch {}
    return { ...dims, thumb: out ? URL.createObjectURL(out) : null };
  }
  // Decode a copy ahead, so the <img> that paints it finds it ready.
  const decodeAhead = (src) => new Promise((resolve) => {
    const img = new Image();
    img.onload = () => (img.decode ? img.decode() : Promise.resolve()).then(resolve, resolve);
    img.onerror = resolve;
    img.src = src;
  });
  const warmMedia = (url, { thumb = false } = {}) => {
    if (!url || mediaReady.has(url) || typeof Image === 'undefined') return Promise.resolve();
    if (mediaWarming.has(url)) return mediaWarming.get(url);
    if (thumb && /^https?:/i.test(url)) {
      const task = (async () => {
        let got = (await storedMediaThumb(url)) || (await makeMediaThumb(url).catch(() => null));
        // no copy to be made here (the host keeps its bytes, or no worker to
        // make it): the server makes one
        if (!got && (noCorsHost(url) || corsRefused.has(url) || typeof OffscreenCanvas === 'undefined')) got = await serverMediaThumb(url).catch(() => null);
        if (got) {
          // no copy (small already, or a GIF): the original is what paints,
          // so it's the one decoded ahead — the row mustn't decode it on sight
          await decodeAhead(got.thumb || url);
          mediaReady.set(url, got);
          return;
        }
        await plainWarm(url);
      })().finally(() => mediaWarming.delete(url));
      mediaWarming.set(url, task);
      return task;
    }
    return plainWarm(url);
  };
  const plainWarm = (url) => {
    if (mediaWarming.has(url) && mediaWarming.get(url).plain) return mediaWarming.get(url);
    const task = new Promise((resolve) => {
      const img = new Image();
      const timer = setTimeout(() => done(false), READY_MS);
      const done = (ok) => {
        clearTimeout(timer);
        img.onload = img.onerror = null;
        if (ok) { mediaReady.set(url, { width: img.naturalWidth, height: img.naturalHeight }); mediaFailed.delete(url); }
        resolve();
      };
      img.onload = () => { (img.decode ? img.decode() : Promise.resolve()).then(() => done(true), () => done(false)); };
      img.onerror = () => { mediaFailed.add(url); done(false); };
      img.src = url;
    }).finally(() => { if (mediaWarming.get(url) === task) mediaWarming.delete(url); });
    task.plain = true;
    if (!mediaWarming.has(url)) mediaWarming.set(url, task);
    return task;
  };
  // What an <img> for this picture should load: the column-sized copy when
  // there is one.
  const mediaSrc = (url, d = feedMedia(url)) => (d && d.thumb) || url;
  // A video's shape, so the feed paints its box at the clip's own aspect
  // instead of a 16:9 frame with black bands either side of a portrait clip.
  // The post's imeta `dim` says it for free (Amethyst, Primal and others
  // publish it); otherwise the metadata alone is fetched — a few KB for a
  // moov-first file — with a short cap, since it gates the row. Remembered
  // on disk so a clip seen once is never probed again.
  const VIDEO_RE = /\.(mp4|webm|mov|m4v|m3u8)(\?[^\s]*)?$/i; // (an .m3u8 is an HLS stream: a long clip, posted the way jb55 does)
  // files known to be clips without saying so in their name (divine.video's
  // have no extension): an imeta tag's video/* type, or a video event's file
  const videoUrls = new Set();
  const isVideoUrl = (url) => VIDEO_RE.test(url) || videoUrls.has(url);
  const imetaFields = (tag) => { const f = {}; for (const p of tag.slice(1)) { const i = typeof p === 'string' ? p.indexOf(' ') : -1; if (i > 0) f[p.slice(0, i)] = p.slice(i + 1); } return f; };
  // A video event's file: its HLS stream where the browser plays one (the
  // player picks the rendition); else of the versions its imeta tags
  // offer, the one nearest 1080 on its short side (a phone's screen; not the
  // 4K original); else its url tag.
  function videoEventFile(ev) {
    let best = null, stream = null;
    for (const tag of ev.tags || []) {
      if (tag[0] !== 'imeta') continue;
      const f = imetaFields(tag);
      if (/^https?:\/\//.test(f.url || '') && (/mpegurl/i.test(f.m || '') || /\.m3u8(\?|$)/i.test(f.url))) { stream = stream || { url: f.url, image: f.image }; continue; }
      if (!/^https?:\/\//.test(f.url || '')) continue;
      if (f.m && !/^video\//.test(f.m)) continue;
      const dm = /^(\d+)(?:\.0+)?x(\d+)/.exec(f.dim || '');
      const edge = dm ? Math.min(+dm[1], +dm[2]) : 0;
      const score = !edge ? -400 : -Math.abs(edge - 1080) - (edge > 1080 ? 1 : 0); // nearest 1080; the smaller on a tie
      if (!best || score > best.score) best = { url: f.url, image: f.image, score };
    }
    if (!best) { const u = (ev.tags.find((x) => x[0] === 'url') || [])[1]; if (/^https?:\/\//.test(u || '')) best = { url: u }; }
    if (stream && canHls()) best = { ...stream, image: stream.image || (best && best.image) };
    if (best) videoUrls.add(best.url);
    return best;
  }
  // what a video event reads as: its title, its words, and its file (drawn
  // as the clip it is)
  function videoEventText(ev) {
    learnVideoMeta(ev);
    const f = videoEventFile(ev);
    const title = String((ev.tags.find((x) => x[0] === 'title') || [])[1] || '').trim();
    const words = String(ev.content || '').trim();
    const parts = [];
    if (title && title !== words && !words.startsWith(title)) parts.push(title);
    if (words) parts.push(words);
    if (f && !words.includes(f.url)) parts.push(f.url);
    return parts.join('\n\n');
  }
  const AUDIO_RE = /\.(mp3|m4a|aac|ogg|oga|opus|wav|flac)(\?[^\s]*)?$/i;
  const VIDEO_PROBE_MS = 3000, VIDEO_DIMS_KEEP = 400, VIDEO_DIMS_KEY = 'coinos-video-dims-v2'; // v2: turned clips stand upright
  const videoDims = new Map(); // url -> { width, height }
  const videoUnknown = new Set(); // probed this session and no answer: paint 16:9, don't ask again
  const loadVideoDims = () => mergeStored(videoDims, VIDEO_DIMS_KEY);
  loadVideoDims();
  // the v1 caches held upright phone clips as landscape
  onCacheReady(() => { for (const k of ['coinos-video-dims', 'coinos-video-info']) try { cacheStorage.removeItem(k); } catch {} });
  let videoDimsFlush = null;
  const rememberVideo = (url, width, height) => {
    if (!(width > 0 && height > 0)) return;
    const d = { width, height };
    mediaReady.set(url, d);
    if (videoDims.get(url)?.width === width && videoDims.get(url)?.height === height) return;
    videoDims.delete(url); videoDims.set(url, d);
    if (videoDimsFlush) return;
    videoDimsFlush = setTimeout(() => {
      videoDimsFlush = null;
      try { cacheStorage.setItem(VIDEO_DIMS_KEY, JSON.stringify([...videoDims].slice(-VIDEO_DIMS_KEEP))); } catch {}
    }, 1000);
  };
  const imetaDim = (ev, url) => {
    for (const tag of ev?.tags || []) {
      if (tag[0] !== 'imeta' || !tag.includes('url ' + url)) continue;
      const m = /^dim (\d+)x(\d+)$/.exec(tag.find((x) => /^dim /.test(x)) || '');
      if (m) return { width: +m[1], height: +m[2] };
    }
    return null;
  };
  // ---- what a clip costs, before it's downloaded --------------------------
  // A post's imeta often says (size in bytes, dim, a still); otherwise one
  // 64 KB ranged request does: the total from Content-Range, whether the
  // server takes ranges at all, and the file's layout — an MP4 whose index
  // (moov) sits behind its data can't start until the whole file is in when
  // the server won't serve ranges. Its track header gives the size on screen
  // too. Clips over the budget, above 1080p, or that we couldn't measure
  // wait for a tap — unless the reader asked for large clips to play.
  const VIDEO_INFO_KEY = 'coinos-video-info-v2', VIDEO_INFO_KEEP = 2000, VIDEO_PROBE_BYTES = 65536;
  const VIDEO_LARGE_KEY = 'coinos-video-large';
  const videoInfo = new Map(); // url -> { size, w, h, image, faststart, ranges, moovEnd, probed, failedAt }
  const loadVideoInfo = () => mergeStored(videoInfo, VIDEO_INFO_KEY);
  loadVideoInfo();
  let videoInfoFlush = null;
  const saveVideoInfo = () => {
    if (videoInfoFlush) return;
    videoInfoFlush = setTimeout(() => {
      videoInfoFlush = null;
      try { cacheStorage.setItem(VIDEO_INFO_KEY, JSON.stringify([...videoInfo].slice(-VIDEO_INFO_KEEP))); } catch {}
    }, 1000);
  };
  const noteVideoInfo = (url, d) => { videoInfo.set(url, { ...(videoInfo.get(url) || {}), ...d }); saveVideoInfo(); };
  // what the post itself says about its clips (NIP-92)
  function learnVideoMeta(ev) {
    for (const tag of ev?.tags || []) {
      if (tag[0] !== 'imeta') continue;
      const f = imetaFields(tag);
      if (!f.url || !(VIDEO_RE.test(f.url) || /^video\//.test(f.m || '') || (isVideoEvent(ev) && !f.m))) continue;
      if (!VIDEO_RE.test(f.url)) videoUrls.add(f.url);
      const have = videoInfo.get(f.url) || {};
      const d = {};
      if (!have.size && +f.size > 0) d.size = +f.size;
      // no size, but a bitrate (bits/s) and a duration (Primal posts these): near enough
      else if (!have.size && +f.bitrate > 0 && +f.duration > 0) d.size = Math.round(+f.bitrate * +f.duration / 8);
      if (!have.dur && +f.duration > 0) d.dur = +f.duration;
      const m = /^(\d+)(?:\.0+)?x(\d+)(?:\.0+)?$/.exec(f.dim || '');
      if (!have.w && m) { d.w = +m[1]; d.h = +m[2]; }
      if (!have.image && /^https?:\/\//.test(f.image || '')) d.image = f.image;
      if (Object.keys(d).length) noteVideoInfo(f.url, d);
    }
  }
  // the top-level boxes of an MP4's first bytes: is moov ahead of mdat, and
  // how big is the picture (a video track's tkhd ends in its width/height)
  function readMp4Head(b) {
    const u32 = (i) => ((b[i] << 24) | (b[i + 1] << 16) | (b[i + 2] << 8) | b[i + 3]) >>> 0;
    const type = (i) => String.fromCharCode(b[i], b[i + 1], b[i + 2], b[i + 3]);
    if (b.length >= 4 && u32(0) === 0x1a45dfa3) return { faststart: true }; // WebM/Matroska streams from the start
    let faststart, moovEnd = 0, i = 0;
    while (i + 8 <= b.length) {
      let size = u32(i);
      const tp = type(i + 4);
      if (tp === 'moov') { faststart = true; moovEnd = i + size; break; }
      if (tp === 'mdat') { faststart = false; break; }
      if (size === 1) size = i + 16 <= b.length ? u32(i + 8) * 2 ** 32 + u32(i + 12) : 0;
      if (size < 8) break;
      i += size;
    }
    let w = 0, h = 0;
    for (let j = 4; j + 4 <= b.length && !w; j++) {
      if (b[j] !== 0x74 || type(j) !== 'tkhd') continue; // 't'
      const end = j - 4 + u32(j - 4);
      if (end > b.length || end < j + 8) continue;
      const tw = u32(end - 8) >>> 16, th = u32(end - 4) >>> 16;
      // a phone held upright stores its picture sideways with a quarter-turn
      // matrix (the 36 bytes before width/height): a = 0 and b ≠ 0 there
      const a = u32(end - 44), b2 = u32(end - 40);
      const turned = end - 44 >= j + 8 && a === 0 && b2 !== 0;
      if (tw && th) { w = turned ? th : tw; h = turned ? tw : th; }
    }
    // an iPhone's HEVC (hvc1/hev1 in the sample description)
    let hevc = false;
    for (let j = 0; j + 4 <= b.length && !hevc; j++) if (b[j] === 0x68 && (type(j) === 'hvc1' || type(j) === 'hev1')) hevc = true;
    // its length, from the movie header (a long clip plays as HLS: playSrc)
    let dur = 0;
    for (let j = 4; j + 32 <= b.length && !dur; j++) {
      if (b[j] !== 0x6d || type(j) !== 'mvhd') continue; // 'm'
      const v1 = b[j + 4] === 1, scale = u32(j + (v1 ? 24 : 16));
      const units = v1 ? u32(j + 28) * 2 ** 32 + u32(j + 32) : u32(j + 20);
      if (scale && units && units !== 0xffffffff) dur = units / scale;
    }
    return { faststart, ...(moovEnd ? { moovEnd } : {}), ...(w ? { w, h } : {}), ...(hevc ? { hevc } : {}), ...(dur ? { dur } : {}) };
  }
  const videoProbes = new Map();
  let videoProbing = 0;
  const videoProbeQueue = [];
  const clipGone = (url) => { const d = videoInfo.get(url); return !!d && typeof d.goneAt === 'number' && Date.now() - d.goneAt < 86_400_000; };
  const probeFailedLately = (d) => !!d && typeof d.failedAt === 'number' && Date.now() - d.failedAt < 3_600_000;
  function probeVideo(url, layout = false) {
    const have = videoInfo.get(url);
    // a post that states size and shape is taken at its word: no request at
    // all — unless the file's layout is wanted (a thumbnail)
    // a host that didn't answer is asked again after an hour (a phone on
    // a bad connection must not mark a clip unmeasurable for good)
    if (have && (have.probed || probeFailedLately(have) || (!layout && have.size && have.w))) return Promise.resolve(have);
    if (videoProbes.has(url)) return videoProbes.get(url);
    const task = new Promise((resolve) => videoProbeQueue.push({ url, resolve })).finally(() => videoProbes.delete(url));
    videoProbes.set(url, task);
    pumpVideoProbes();
    return task;
  }
  function pumpVideoProbes() {
    while (videoProbing < 3 && videoProbeQueue.length) {
      const { url, resolve } = videoProbeQueue.shift();
      videoProbing++;
      runVideoProbe(url).then(resolve, () => resolve(videoInfo.get(url) || {}))
        .finally(() => { videoProbing--; pumpVideoProbes(); });
    }
  }
  async function runVideoProbe(url) {
    if (isHls(url)) return probeStream(url);
    const ctrl = new AbortController();
    const timer = setTimeout(() => ctrl.abort(), 10_000);
    try {
      // Past the browser's cache (no-store), always: some hosts (Primal's R2
      // bucket) send CORS headers only to a request that has an Origin, and
      // say nothing of it in Vary — so the copy the cache kept from a
      // player's plain load answers this request without them, and it fails.
      // Any clip that had played in the feed was "unmeasurable" that way.
      const r = await fetch(url, { headers: { Range: 'bytes=0-' + (VIDEO_PROBE_BYTES - 1) }, cache: 'no-store', signal: ctrl.signal });
      if (!r.ok) throw Object.assign(new Error('HTTP ' + r.status), { status: r.status });
      const ranges = r.status === 206;
      const total = ranges ? +(/\/(\d+)\s*$/.exec(r.headers.get('content-range') || '') || [])[1] : +r.headers.get('content-length');
      // never more than the first bytes, even from a server that ignored the range
      const reader = r.body.getReader();
      const parts = [];
      let got = 0;
      while (got < VIDEO_PROBE_BYTES) {
        const { done, value } = await reader.read();
        if (done) break;
        parts.push(value); got += value.length;
      }
      try { reader.cancel(); } catch {}
      const buf = new Uint8Array(Math.min(got, VIDEO_PROBE_BYTES));
      let o = 0;
      for (const p of parts) { if (o >= buf.length) break; buf.set(p.subarray(0, buf.length - o), o); o += p.length; }
      const head = readMp4Head(buf);
      const d = { probed: true, ranges, faststart: head.faststart === true, failedAt: undefined, goneAt: undefined, ...(head.moovEnd ? { moovEnd: head.moovEnd } : {}), ...(head.hevc ? { hevc: true } : {}), ...(head.dur && !(videoInfo.get(url) || {}).dur ? { dur: head.dur } : {}) };
      if (total > 0) d.size = total;
      else {
        // a server that hides Content-Range from scripts (Primal's) still
        // says Content-Length to a HEAD, which any page may read
        try {
          const hr = await fetch(url, { method: 'HEAD', cache: 'no-store', signal: AbortSignal.timeout(5000) });
          const n = +hr.headers.get('content-length');
          if (hr.ok && n > 0) d.size = n;
        } catch {}
      }
      if (head.w && !(videoInfo.get(url) || {}).w) { d.w = head.w; d.h = head.h; }
      if (head.w) rememberVideo(url, head.w, head.h);
      noteVideoInfo(url, d);
    } catch (e) {
      // a host that won't say (no CORS, down, slow): asked again in an hour.
      // One that says the file is gone (deleted: a 404 or 410) is believed
      // for a day, and the grid leaves the clip out (clipGone).
      const gone = e && (e.status === 404 || e.status === 410);
      noteVideoInfo(url, { failedAt: Date.now(), ...(gone ? { goneAt: Date.now() } : {}) });
      if (gone && mediaMode === 'videos') scheduleRepaint();
    } finally { clearTimeout(timer); }
    return videoInfo.get(url);
  }
  // A stream is measured by a player: its playlist says nothing of the
  // picture's size. Where HLS doesn't play, it can't be measured either.
  async function probeStream(url) {
    if (!canHls()) { noteVideoInfo(url, { failedAt: Date.now() }); return videoInfo.get(url); }
    const v = document.createElement('video');
    v.muted = true; v.preload = 'metadata';
    const ok = await new Promise((resolve) => {
      const timer = setTimeout(() => resolve(false), 15_000);
      v.onloadedmetadata = () => { clearTimeout(timer); resolve(!!v.videoWidth); };
      v.onerror = () => { clearTimeout(timer); resolve(false); };
      v.src = url;
    });
    if (ok) {
      noteVideoInfo(url, { probed: true, stream: true, failedAt: undefined, ...(Number.isFinite(v.duration) ? { dur: v.duration } : {}) });
      rememberVideo(url, v.videoWidth, v.videoHeight);
    } else noteVideoInfo(url, { failedAt: Date.now() });
    v.removeAttribute('src'); v.load();
    return videoInfo.get(url);
  }
  // How much a clip may cost before it waits for a tap: less on a slow or
  // metered connection.
  const largeVideosOk = () => { try { return localStorage.getItem(VIDEO_LARGE_KEY) === '1'; } catch { return false; } };
  function videoBudget() {
    try {
      const c = navigator.connection;
      if (c && c.saveData) return 3e6;
      if (c && /(^|-)2g$|^3g$/.test(c.effectiveType || '')) return 8e6;
    } catch {}
    return 25e6;
  }
  // Data Saver on, or a slow link: the connection to be careful with
  const frugalData = () => { try { const c = navigator.connection; return !!(c && (c.saveData || /(^|-)2g$|^3g$/.test(c.effectiveType || ''))); } catch { return false; } };
  const tappedClips = new Set(); // asked for by hand this session: plays, whatever it costs
  // A clip too big to play as it is: over the budget, past 1080p, its index
  // at the end of a big file — or (known) unmeasurable. Such a clip plays as
  // an HLS stream where it can (playSrc); else it waits for a tap.
  function bigClip(url, known = false) {
    const d = videoInfo.get(url) || {};
    if (d.w && d.h && Math.min(d.w, d.h) > 1080) return true;
    if (!d.size) return !known || d.probed || probeFailedLately(d); // nothing known: don't spend data blind
    if (d.size > videoBudget()) return true;
    // the whole file before the first frame: only worth it for a small one
    if (d.probed && !d.faststart && !d.ranges && d.size > 8e6) return true;
    return false;
  }
  function videoHeavy(url) {
    if (tappedClips.has(url) || largeVideosOk()) return false;
    const d = videoInfo.get(url) || {};
    if (d.stream) return false; // a stream takes the rendition the connection carries
    // one that streams costs what the connection carries: it plays like any
    // other (Adam, 2026-10-18) — but not over Data Saver or a slow link,
    // where even a stream is the reader's call
    if (streamsHere(url) && !frugalData()) return false;
    return bigClip(url);
  }
  const fmtBytes = (n) => n >= 1e9 ? (n / 1e9).toFixed(1) + ' GB' : n >= 1e6 ? Math.round(n / 1e6) + ' MB' : Math.max(1, Math.round(n / 1e3)) + ' KB';
  function heavyLabel(url) {
    const d = videoInfo.get(url) || {};
    const edge = d.w && d.h ? Math.min(d.w, d.h) : 0;
    const res = edge >= 2160 ? '4K' : edge > 1080 ? edge + 'p' : '';
    return [d.size ? fmtBytes(d.size) : '', res].filter(Boolean).join(' · ') || t('videoTapToPlay');
  }
  const warmVideo = (url, dim) => {
    if (!url || mediaReady.has(url)) return Promise.resolve();
    const known = videoDims.get(url) || dim;
    if (known) { rememberVideo(url, known.width, known.height); return Promise.resolve(); }
    if (typeof document === 'undefined' || videoUnknown.has(url)) return Promise.resolve();
    if (mediaWarming.has(url)) return mediaWarming.get(url);
    // the 64 KB probe first: it reads the shape from the file's own header
    // and costs nothing like a player's metadata load of an index-last file
    const task = probeVideo(url).then(() => {
      if (mediaReady.has(url)) return;
      const d = videoInfo.get(url) || {};
      if (d.probed) { videoUnknown.add(url); return; }
      return playerShape(url);
    }).finally(() => mediaWarming.delete(url));
    mediaWarming.set(url, task);
    return task;
  };
  // a host that wouldn't answer the probe: ask a player for the shape, briefly
  const playerShape = (url) => {
    const task = new Promise((resolve) => {
      const v = document.createElement('video');
      const done = () => {
        clearTimeout(timer);
        v.onloadedmetadata = v.onerror = null;
        if (v.videoWidth && v.videoHeight) rememberVideo(url, v.videoWidth, v.videoHeight);
        else videoUnknown.add(url);
        v.removeAttribute('src'); try { v.load(); } catch {} // let go of the connection
        resolve();
      };
      const timer = setTimeout(done, VIDEO_PROBE_MS);
      v.onloadedmetadata = done; v.onerror = done;
      v.muted = true; v.preload = 'metadata'; v.src = url;
    });
    return task;
  };
  // ---- link previews --------------------------------------------------
  // A plain link in a post becomes the card its page describes (Open Graph:
  // title, a line, a picture), fetched through the registrar because a
  // browser can't read another site's HTML. Warmed with the rest of a post
  // so the row arrives whole; remembered across sessions, a few hundred at
  // a time, so a feed you've seen paints its cards at once.
  const PREVIEW_API = 'https://names.coinos.io/preview?url=';
  const PREVIEW_KEEP = 400;
  const previews = new Map(); // url -> { title, description, image, site } | null (nothing there)
  const previewWarming = new Map();
  const loadPreviews = () => mergeStored(previews, 'coinos-link-previews');
  loadPreviews();
  let previewFlush = null;
  const savePreviews = () => {
    if (previewFlush) return;
    previewFlush = setTimeout(() => {
      previewFlush = null;
      const rows = [...previews].filter(([, m]) => m).slice(-PREVIEW_KEEP);
      try { cacheStorage.setItem('coinos-link-previews', JSON.stringify(rows)); } catch {}
    }, 1000);
  };
  const previewable = (url) => /^https?:\/\//i.test(url) && !youtubeId(url)
    && !/\.(png|jpe?g|gif|webp|avif|mp4|webm|mov|m4v|mp3|m4a|ogg|wav|pdf|zip)(\?[^\s]*)?$/i.test(url);
  const warmPreview = (url) => {
    if (!url || previews.has(url) || typeof fetch === 'undefined') return Promise.resolve();
    if (previewWarming.has(url)) return previewWarming.get(url);
    const task = (async () => {
      let meta = null;
      try {
        const r = await fetch(PREVIEW_API + encodeURIComponent(url), { signal: AbortSignal.timeout(READY_MS) });
        const j = r.ok ? await r.json() : null;
        if (j && (j.title || j.image)) meta = { title: j.title || '', description: j.description || '', image: j.image || '', site: j.site || '' };
      } catch { return; } // asked again another time: the registrar was away, not the page
      previews.set(url, meta);
      if (meta) { savePreviews(); if (meta.image) await warmMedia(meta.image); }
    })().finally(() => previewWarming.delete(url));
    previewWarming.set(url, task);
    return task;
  };
  // the first two plain links of a post (a wall of links is a list, not cards)
  function notePreviewUrls(content) {
    const urls = [];
    for (const part of String(content || '').split(NOTE_SPLIT)) {
      if (!part || urls.length >= 2) continue;
      const md = MD_PARTS.exec(part);
      const url = md ? md[3] : (/^https?:\/\//i.test(part) ? part : null);
      if (url && !(md && md[1]) && previewable(url) && !PACK_LINK_RE.test(url)) urls.push(url);
    }
    return urls;
  }
  function linkCard(url, pv) {
    let host = '';
    try { host = new URL(url).hostname.replace(/^www\./, ''); } catch {}
    const size = pv.image ? (feedPaint ? feedMedia(pv.image) : mediaReady.get(pv.image)) : null;
    return h('a', {
      class: 'link-card', href: url, target: '_blank', rel: 'noopener noreferrer',
      onClick: (e) => e.stopPropagation(),
    },
      pv.image ? h('img', {
        class: 'link-thumb', src: pv.image, alt: '', loading: 'lazy',
        width: size?.width, height: size?.height,
        style: size && size.width && size.height ? 'aspect-ratio:' + size.width + '/' + size.height : undefined,
        onError: (e) => { e.target.style.display = 'none'; },
      }) : null,
      h('div', { class: 'link-meta' },
        h('div', { class: 'link-title' }, pv.title || host),
        pv.description ? h('div', { class: 'link-desc small muted' }, pv.description) : null,
        h('div', { class: 'link-site small faint' }, pv.site || host)));
  }
  function noteMediaUrls(content) {
    const urls = [];
    for (const part of String(content || '').split(NOTE_SPLIT)) {
      if (!part) continue;
      const md = MD_PARTS.exec(part);
      const url = md ? md[3] : (/^https?:\/\//i.test(part) ? part : null);
      if (!url) continue;
      if ((md && md[1]) || /\.(png|jpe?g|gif|webp|avif)(\?[^\s]*)?$/i.test(url)) urls.push(url);
      else if (youtubeId(url)) urls.push('https://i.ytimg.com/vi/' + youtubeId(url) + '/hqdefault.jpg');
    }
    return urls;
  }
  function noteVideoUrls(content) {
    const urls = [];
    for (const part of String(content || '').split(NOTE_SPLIT)) {
      const md = part && MD_PARTS.exec(part);
      const url = md ? md[3] : (/^https?:\/\//i.test(part || '') ? part : null);
      if (url && !(md && md[1]) && isVideoUrl(url)) urls.push(url);
    }
    return urls;
  }
  const avatarUrl = (p, pk) => p?.picture
    ? localPunk(p.picture) || (p.thumbFor === p.picture && p.thumb) || p.picture
    : punkSmallUrl(pk);
  async function warmAvatar(pk, deadline) {
    let p = liveProfileOf(pk);
    while ((p === null || (p && p.loading && !p.picture)) && Date.now() < deadline) {
      await new Promise((r) => setTimeout(r, 100));
      p = profiles.get(pk);
    }
    await warmMedia(avatarUrl(p, pk));
    if (p?.picture) makeThumb(pk, p);
  }
  // parent: the post a reply answers is part of the row (a conversations
  // feed), so it arrives with the row; elsewhere a reply's parent is fetched
  // only where it is shown (a profile's Replies tab fills its cards in).
  async function noteReady(ev, deadline = Date.now() + READY_MS, depth = 0, { parent: withParent = false } = {}) {
    if (ev && ev.kind === REPOST) { const inner = repostInner(ev); if (!inner) return; ev = inner; }
    const tasks = [warmAvatar(ev.pubkey, deadline), ...noteMediaUrls(ev.content).map((u) => warmMedia(u, { thumb: true })),
      ...(learnVideoMeta(ev), noteVideoUrls(ev.content).map((u) => warmVideo(u, imetaDim(ev, u)))),
      ...notePreviewUrls(ev.content).map(warmPreview),
      ...[...emojiTagMap(ev.tags).values()].map(warmMedia)];
    // a reply's parent, shown above it where replies are shown with context
    const parent = withParent && !depth ? parentRefOf(ev) : null;
    if (parent) {
      const quote = quotedNote(parent);
      tasks.push(Promise.resolve(quote.promise).then(() => quote.ev && noteReady(quote.ev, deadline, depth + 1)));
    }
    for (const part of String(ev.content || '').split(NOTE_SPLIT)) {
      if (/^(nostr:|@?)(npub|nprofile)1/i.test(part)) {
        const ref = parseNostrRef(part.replace(/^(nostr:|@)/i, ''));
        if (ref?.pk) tasks.push(warmAvatar(ref.pk, deadline));
      } else if (!depth && /^nostr:(note|nevent)1/i.test(part)) {
        const ref = parseNostrRef(part.slice(6));
        if (ref?.type === 'event') {
          const quote = quotedNote(ref);
          tasks.push(Promise.resolve(quote.promise).then(() => quote.ev && noteReady(quote.ev, deadline, depth + 1)));
        }
      }
    }
    let timer;
    try {
      await Promise.race([Promise.all(tasks), new Promise((r) => { timer = setTimeout(r, Math.max(0, deadline - Date.now())); })]);
    } catch {} finally { clearTimeout(timer); }
  }
  const notesReady = (evs, opts) => { const deadline = Date.now() + READY_MS; return Promise.all(evs.map((e) => noteReady(e, deadline, 0, opts))); };
  const keyed = (node, key) => { node.setAttribute('data-key', key); return node; };
  // Keep only the resources this row actually uses. Copying the entire
  // session media cache into every row grows quadratically as you scroll.
  function feedMedia(url) {
    if (!feedPaint) return mediaReady.get(url);
    if (!feedPaint.media.has(url)) feedPaint.media.set(url, mediaReady.get(url) || null);
    return feedPaint.media.get(url);
  }
  // a conversations feed: each reply under the post it answers (remembered
  // on the feed's state; a changed definition rebuilds the state)
  const feedReplies = (c) => (c.replies ??= !!(feedDef(c.id) || {}).replies);
  function feedRow(c, ev) {
    let presentation = c.presentations.get(ev.id);
    if (!presentation) {
      presentation = { profiles: new Map(), media: new Map(), quotes: new Map(), time: new Map() };
      c.presentations.set(ev.id, presentation);
    }
    const prev = feedPaint;
    feedPaint = presentation;
    try {
      const row = keyed(noteRow(ev.pubkey, ev, displayName(ev.pubkey), { context: feedReplies(c) }), ev.id);
      if (c.fresh && c.fresh.has(ev.id)) { row.classList.add('note-fresh'); watchFresh(c); }
      return row;
    }
    finally { feedPaint = prev; }
  }

  // ---- read posts: a boost doesn't bring them back -----------------------
  // A post you've read (its row held on screen for a moment, or shown in the
  // media pager) is remembered on this device, by the row it was read in:
  // the post itself, or the repost it came under. A later repost of it —
  // someone boosting it again, hours on — would put it back at the top of
  // the feed as if it were new; it stays out. The row you read keeps its
  // place, so scrolling back down still finds it. Your own reposts show.
  const SEEN_LS = 'coinos-seen';
  const SEEN_MAX = 5000, SEEN_DAYS = 14;
  const seenLsKey = () => SEEN_LS + ':' + (wallet._cacheKey ? wallet._cacheKey() : '');
  let seenNotes = null, seenKey = null, seenSave = 0; // note id -> [row id, seen at (s)]
  function seenMap() {
    const k = seenLsKey();
    if (seenNotes && seenKey === k) return seenNotes;
    seenKey = k; seenNotes = new Map();
    try {
      const cut = Date.now() / 1000 - SEEN_DAYS * 86400;
      for (const [id, row, t] of JSON.parse(localStorage.getItem(k) || '[]')) if (t > cut) seenNotes.set(id, [row, t]);
    } catch {}
    return seenNotes;
  }
  function markSeen(row) {
    const note = row && (row.kind === REPOST ? repostInner(row) : row);
    if (!note) return;
    const m = seenMap();
    if (m.has(note.id)) return;
    m.set(note.id, [row.id, Math.floor(Date.now() / 1000)]);
    if (m.size > SEEN_MAX) for (const id of [...m.keys()].slice(0, m.size - SEEN_MAX)) m.delete(id);
    const k = seenKey;
    clearTimeout(seenSave);
    seenSave = setTimeout(() => {
      try { localStorage.setItem(k, JSON.stringify([...seenMap()].map(([id, [r, t]]) => [id, r, t]))); } catch {}
    }, 1000);
  }
  // a repost of a post already read under another row (the post itself, or
  // someone else's repost of it)
  function reboosted(e) {
    if (!e || e.kind !== REPOST || isMe(e.pubkey)) return false;
    const note = repostInner(e);
    const was = note && seenMap().get(note.id);
    return !!was && was[0] !== e.id;
  }
  // Read: at least half the row (or half the screen, for a tall one) in view
  // for a second without a break.
  const SEEN_MS = 1000;
  let seenObserver = null;
  const seenTimers = new Map(); // row element -> timer
  const seenWatched = new WeakSet();
  function watchSeen() {
    if (typeof IntersectionObserver === 'undefined') return;
    seenObserver ||= new IntersectionObserver((entries) => {
      for (const en of entries) {
        const el = en.target;
        const enough = en.isIntersecting && en.intersectionRect.height >= Math.min(en.boundingClientRect.height, window.innerHeight) * 0.5;
        if (!enough) { clearTimeout(seenTimers.get(el)); seenTimers.delete(el); if (!el.isConnected) seenObserver.unobserve(el); continue; }
        if (seenTimers.has(el)) continue;
        seenTimers.set(el, setTimeout(() => {
          seenTimers.delete(el);
          if (!el.isConnected) return;
          const id = el.getAttribute('data-key');
          const ev = feed && feed.notes.find((x) => x.id === id);
          if (ev) markSeen(ev);
          seenObserver.unobserve(el);
        }, SEEN_MS));
      }
    }, { threshold: [0, 0.25, 0.5, 0.75, 1] });
    requestAnimationFrame(() => {
      for (const el of document.querySelectorAll('.notes-feed > .row[data-key]')) {
        if (seenWatched.has(el)) continue;
        seenWatched.add(el);
        seenObserver.observe(el);
      }
    });
  }

  // A new post wears its tint until any of it reaches the screen; from that
  // moment it fades out (the row's 3s background transition, in the CSS)
  // whether you stay or scroll on. It used to wait for half the row to sit
  // in view for two seconds, with the clock reset by every scroll and lost
  // when the row's node was replaced, so a tall post read in passing, or one
  // the window remounted, could stay green for good.
  let freshObserver = null;
  function watchFresh(c) {
    if (typeof IntersectionObserver === 'undefined') return;
    freshObserver ||= new IntersectionObserver((entries) => {
      for (const en of entries) {
        if (!en.isIntersecting) continue;
        const el = en.target, id = el.getAttribute('data-key');
        feed?.fresh?.delete(id); // by id: the row may be re-rendered mid-fade
        el.classList.remove('note-fresh');
        freshObserver.unobserve(el);
      }
    }, { threshold: 0 });
    // after the paint, when the row nodes are the mounted ones
    requestAnimationFrame(() => {
      for (const el of document.querySelectorAll('.notes-feed > .row.note-fresh')) freshObserver.observe(el);
    });
  }

  // Posts at the door: filtered in synchronously, so the same note from a
  // second relay is dropped while the first copy is still warming.
  const feedStaged = new WeakMap();
  async function mergeFeed(evs, opts = {}, c = feedNow()) {
    let staged = feedStaged.get(c);
    if (!staged) feedStaged.set(c, staged = new Set());
    // (with those waiting a moment to go in together — admitQueues — or a
    // copy from a second relay, or another version of a clip, slips in)
    const held = [...c.notes, ...(c.deferred || []), ...((admitQueues.get(c) || {}).evs || [])];
    const known = new Set(held.map((e) => e.id));
    for (const e of evs || []) noteForSpam(e);
    // A note shows once: as itself, or under the first repost of it to
    // arrive — counting the ones still warming at the door.
    // (`staged` holds the note's id too, for a repost)
    const noteOf = (e) => (e.kind === REPOST ? repostInner(e) : e);
    const notesIn = new Set(held.map((e) => noteOf(e)?.id).filter(Boolean));
    // an addressable post (a 34235/34236 clip) once, however many versions of it come
    for (const e of held) { const a = noteOf(e) && addrOf(noteOf(e)); if (a) notesIn.add(a); }
    const addrNew = (e) => { const n = noteOf(e); const a = n && addrOf(n); return !a || (!notesIn.has(a) && !staged.has(a) && !!staged.add(a)); };
    const fresh = (e) => { const n = noteOf(e); return !!n && !notesIn.has(n.id) && !staged.has(n.id); };
    const unstage = (e) => { staged.delete(e.id); const n = noteOf(e); if (n) { staged.delete(n.id); const a = addrOf(n); if (a) staged.delete(a); } };
    const def = feedDef(c.id);
    let add = (evs || []).filter((e) => (e.kind === REPOST ? !(def && def.replies) && !!repostInner(e) && !hidden(repostInner(e)) && !reboosted(e) : feedKeeps(def, e)) && !hidden(e)
      && fresh(e) && !known.has(e.id) && !staged.has(e.id) && addrNew(e) && known.add(e.id) && staged.add(e.id) && staged.add(noteOf(e).id));
    if (!add.length) return false;
    if (def && def.curated) {
      const kept = curateFeed(add);
      for (const e of add) if (!kept.includes(e)) unstage(e);
      add = kept;
      if (!add.length) return false;
    }
    if (c.stopped) return false;
    if (opts.immediate && !c.notes.length && !opts.catchup) {
      // The public snapshot already contains verified posts and profiles.
      // Paint text now using the same progressive rows as the local cache;
      // slow media/quotes must not hold the whole first page behind a spinner.
      c.booting = true;
      for (const e of add) unstage(e);
      admitFeed(add, c);
      c.boot = notesReady(c.notes.slice(0, FEED_PAGE), { parent: feedReplies(c) }).finally(() => {
        c.booting = false;
        c.prepared = null;
        if (!c.stopped && c === feed) scheduleRepaint();
      });
      scheduleRepaint();
      return true;
    }
    // Each row waits only for its own presentation. A slow photo or quote
    // cannot hold ready text posts (or their new-post notice) behind it.
    const ready = await Promise.all(add.map(async (e) => {
      await noteReady(e, undefined, 0, { parent: feedReplies(c) });
      unstage(e);
      if (c.stopped) return false;
      if (feedReplies(c) && orphaned(e)) return false; // a reply to nothing anyone can find
      // Cached rows can still be warming. This new row is already prepared
      // and can take its stable presentation without waiting for that page.
      if (c.booting) { c.prepared ||= new Set(); c.prepared.add(e.id); }
      queueAdmit(e, c, opts.newerThan);
      return true;
    }));
    return ready.some(Boolean);
  }
  // Ready posts go in together: one admission — one render with the reader's
  // row held still — per short interval, not one per post. A Popular switch
  // used to run dozens of full renders in a few seconds, 200–450 ms each,
  // and a wheel scroll through them stuttered on a laptop (the wheel coast
  // is driven from the main thread, so every long render froze it). While
  // the reader is moving the page the batch waits for a quiet moment, up to
  // a cap, so nothing much changes under a coasting scroll.
  const ADMIT_MS = 120, ADMIT_QUIET_MS = 160, ADMIT_INPUT_MS = 2500, ADMIT_MAX_WAIT_MS = 1500;
  const admitQueues = new Map(); // c → { evs, newerThan, since, timer }
  function queueAdmit(e, c, newerThan) {
    let q = admitQueues.get(c);
    if (!q) admitQueues.set(c, q = { evs: [], newerThan, since: Date.now(), timer: 0 });
    q.evs.push(e);
    if (!q.timer) q.timer = setTimeout(() => flushAdmit(c), ADMIT_MS);
  }
  const readerMoving = () => Date.now() - lastScrollAt < ADMIT_QUIET_MS && Date.now() - lastInputAt < ADMIT_INPUT_MS;
  function flushAdmit(c) {
    const q = admitQueues.get(c);
    if (!q) return;
    q.timer = 0;
    if (c === feed && readerMoving() && Date.now() - q.since < ADMIT_MAX_WAIT_MS) { q.timer = setTimeout(() => flushAdmit(c), ADMIT_QUIET_MS); return; }
    admitQueues.delete(c);
    if (c.stopped) return;
    admitFeed([...(c.deferred || []), ...q.evs], c, false, q.newerThan);
    scheduleRepaint();
  }

  // Never insert between the rows currently under the reader's eyes. Gap
  // fills wait until that part of the feed is offscreen; new posts above
  // the reading position can be inserted immediately with an anchor.
  function admitFeed(add, c, explicit = false, newerThan = c.notes[0]?.created_at || 0) {
    const onScreen = c === feed && ui.chatOpen && ui.msgView === 'feed' && !ui.profilePk && !ui.noteThread;
    const rows = onScreen && !explicit ? [...document.querySelectorAll('.notes-feed > .row[data-key]')] : [];
    // An empty feed has no original head. Once its first row paints, a
    // newer row arriving later still needs a notice if it must wait.
    if (newerThan === Infinity) newerThan = c.notes[0]?.created_at ?? Infinity;
    // Count against the head when the query began, so posts arriving out of
    // order still count. Include deferred prepends: the notice can reveal
    // them explicitly without moving the header out from under the reader.
    let noticed = false;
    if (rows.length) {
      c.fresh ||= new Set();
      const known = new Set(c.notes.map((e) => e.id));
      for (const e of add) if (e.created_at > newerThan && !known.has(e.id) && !c.fresh.has(e.id)) {
        c.fresh.add(e.id);
        (c.ahead ||= new Set()).add(e.id);
        c.unseen = (c.unseen || 0) + 1;
        noticed = true;
      }
    }
    const result = mergeFeedWindow(c.notes, c.shown, add, {
      rows: rows.map((r) => ({ id: r.getAttribute('data-key'), top: r.getBoundingClientRect().top, bottom: r.getBoundingClientRect().bottom })),
      height: typeof window === 'undefined' ? 0 : window.innerHeight, keep: FEED_KEEP, page: FEED_PAGE * (1 + APPETITE_MAX), // room for the pass fetched ahead
      holdHead: headBusy(),
    });
    c.deferred = result.deferred;
    if (!result.added.length) { if (noticed) scheduleRepaint(); return; }
    c.shown = c.opened ? result.shown : FEED_PAGE;
    c.notes = result.notes;
    const retained = new Set(c.notes.map((e) => e.id));
    for (const id of c.presentations.keys()) if (!retained.has(id)) c.presentations.delete(id);
    if (c.prepared) {
      const waiting = new Set(c.deferred.map((e) => e.id));
      for (const id of c.prepared) if (!retained.has(id) && !waiting.has(id)) c.prepared.delete(id);
    }
    saveFeedCache(c);
    if (rows.length) {
      holdScroll(render);
    }
  }

  // The pill's tap: the posts are already in, so this just goes up to them —
  // to the OLDEST of them, the one right above where you were reading, so
  // you read on upward through the rest. Starting to scroll up by yourself clears
  // the pill too (see the scroll listener).
  // Drag the new-posts pill any way but up and let go past a short
  // distance: it flies off that way and onDismiss runs. A short drag springs
  // back, and the click a drag ends in is swallowed.
  function pillSwipe(onDismiss) {
    let d = null;
    const move = (el, dx, dy) => {
      el.style.transition = 'none';
      el.style.transform = `translate(calc(-50% + ${dx}px), ${dy}px)`;
      el.style.opacity = String(Math.max(0.2, 1 - Math.hypot(dx, dy) / 160));
    };
    return {
      onPointerdown: (e) => {
        d = { x: e.clientX, y: e.clientY, id: e.pointerId, dx: 0, dy: 0, moved: false };
      },
      onPointermove: (e) => {
        if (!d || e.pointerId !== d.id) return;
        const el = e.currentTarget;
        d.dx = e.clientX - d.x; d.dy = Math.max(0, e.clientY - d.y); // down or sideways
        // a repaint mid-drag would wipe the inline transform: hold the morph off
        if (!d.moved && Math.hypot(d.dx, d.dy) > 6) { d.moved = true; el._skipMorph = true; try { el.setPointerCapture(d.id); } catch {} }
        if (d.moved) move(el, d.dx, d.dy);
      },
      onPointerup: (e) => {
        if (!d || e.pointerId !== d.id) return;
        const el = e.currentTarget, { dx, dy, moved } = d;
        d = null;
        if (!moved) return;
        el._skipMorph = false;
        el._swiped = true;
        setTimeout(() => { el._swiped = false; }, 400);
        el.style.transition = 'transform .18s ease-out, opacity .18s ease-out';
        if (Math.hypot(dx, dy) > 60) {
          const k = 400 / Math.max(1, Math.hypot(dx, dy));
          el.style.transform = `translate(calc(-50% + ${dx * k}px), ${dy * k}px)`;
          el.style.opacity = '0';
          setTimeout(onDismiss, 180);
        } else {
          el.style.transform = ''; el.style.opacity = '';
        }
      },
      onPointercancel: (e) => {
        if (!d) return;
        d = null;
        const el = e.currentTarget;
        el._skipMorph = false;
        el.style.transition = 'transform .18s ease-out, opacity .18s ease-out';
        el.style.transform = ''; el.style.opacity = '';
      },
    };
  }
  // Where you are in the feed: the rows on screen, top first, as indexes
  // into the list (none when the feed isn't showing).
  function feedRowsOnScreen() {
    if (!(ui.chatOpen && ui.msgView === 'feed') || ui.profilePk || ui.noteThread) return [];
    const out = [];
    for (const r of document.querySelectorAll('.notes-feed > .row[data-key]')) {
      const b = r.getBoundingClientRect();
      if (b.bottom > 8) out.push({ id: r.getAttribute('data-key'), top: b.top });
    }
    return out;
  }
  // c.ahead: new posts you haven't scrolled up to yet. The pill counts
  // them; going up to one (or past it) takes it, and everything below it,
  // off. The tint (c.fresh) is separate — it fades on first sight, and a
  // post that went in above you shows a sliver of itself without you
  // having gone up there.
  function markReached(c) {
    if (!c || !c.ahead || !c.ahead.size) return;
    const top = feedRowsOnScreen().find((r) => r.top >= -8);
    if (!top) return;
    const list = c.winList ? c.winList() : [];
    const k = list.findIndex((ev) => ev.id === top.id);
    if (k >= 0) for (let j = k; j < list.length; j++) c.ahead.delete(list[j].id);
  }
  function pillCount(c) {
    if (!c || !c.unseen || !c.ahead || !c.ahead.size) return 0;
    let n = 0;
    for (const ev of c.notes) if (c.ahead.has(ev.id) && !hidden(ev)) n++;
    for (const ev of c.deferred || []) if (c.ahead.has(ev.id)) n++;
    return n;
  }
  // Only ever up: to the nearest new post above the one you're reading.
  // New posts below it are already behind you.
  function jumpToNew() {
    const c = feed;
    if (!c) return;
    // the first row whose top is on screen, as markReached reads it: one
    // peeking in above that is still up there to go to
    const at = feedRowsOnScreen().find((r) => r.top >= -8)?.id;
    admitFeed(c.deferred || [], c, true);
    c.unseen = 0;
    render();
    const list = c.winList ? c.winList() : [];
    let r = at ? list.findIndex((ev) => ev.id === at) : -1;
    if (r < 0) r = list.length;
    let i = -1;
    for (let j = r - 1; j >= 0; j--) if (c.ahead && c.ahead.has(list[j].id)) { i = j; break; }
    if (i < 0) { if (r === list.length || !at) glideToTop(); return; }
    glideToPost(c, list, i);
  }
  // Scroll so post i's top sits just under the top of the window. A row
  // outside the rendered window is placed from the height cache first, then
  // corrected once it's mounted.
  function glideToPost(c, list, i) {
    const id = list[i].id, MARGIN = 8;
    const find = () => document.querySelector('.notes-feed > [data-key="' + CSS.escape(id) + '"]');
    try {
      const H = window.innerHeight || 800;
      if (!find() && c.heights) {
        let sum = 0, n = 0;
        for (const v of c.heights.values()) { sum += v; n++; }
        const avg = n ? sum / n : 200;
        let y = 0;
        for (let j = 0; j < i; j++) y += (c.heights.get(list[j].id) || avg) + ROW_GAP;
        window.scrollTo(0, Math.max(0, (c.listTop || 0) + y - MARGIN));
        render();
      }
      const el = find();
      if (!el) { glideToTop(); return; }
      const target = Math.max(0, window.scrollY + el.getBoundingClientRect().top - MARGIN);
      const reduce = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
      if (reduce) { window.scrollTo({ top: target }); return; }
      // a long way off: close most of the distance in one step, glide the rest
      if (Math.abs(window.scrollY - target) > H * 2) window.scrollTo({ top: target + Math.sign(window.scrollY - target) * H * 2 });
      requestAnimationFrame(() => { try { window.scrollTo({ top: target, behavior: 'smooth' }); } catch { window.scrollTo(0, target); } });
    } catch { glideToTop(); }
  }
  // Up to the new posts as a glide, not a cut: an instant scrollTo read as a
  // page refresh. A long way down, most of the distance is closed in one
  // step first — so the glide is short, and the rows it passes are the
  // ones the window has mounted — and the last couple of screens roll by.
  function glideToTop() {
    try {
      const H = window.innerHeight || 800;
      const reduce = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
      if (reduce) { window.scrollTo({ top: 0 }); return; }
      if (window.scrollY > H * 2) window.scrollTo({ top: H * 2 });
      requestAnimationFrame(() => { try { window.scrollTo({ top: 0, behavior: 'smooth' }); } catch { window.scrollTo(0, 0); } });
    } catch { try { window.scrollTo(0, 0); } catch {} }
  }
  // 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.
  // The oldest event the relays handed back, admitted or not: a page of
  // replies, muted or spam posts is not the end of the feed — the next ask
  // goes on from there.
  function sawBack(c, evs) {
    for (const e of evs || []) if (e && e.created_at && !(c.seenBack <= e.created_at)) c.seenBack = e.created_at;
    c.sawAny = (c.sawAny || 0) + ((evs || []).length);
  }
  async function queryFeed(relays, filter, merge, c, maxWait = 5000, qualifies = () => true) {
    let got = false;
    await queryStreamOn(relays, filter, async (ev) => {
      if (c.stopped) return;
      if (merge && merge.sink) { if (qualifies(ev)) { merge.sink(ev); got = true; } return; } // the media crawl's: into the index, not the page
      sawBack(c, [ev]);
      if (qualifies(ev) && await mergeFeed([ev], merge, c)) got = true;
    }, maxWait);
    return got;
  }
  // (relays: asked in place of the feed's own — the archives, for history
  // the feed's relays have let go)
  async function feedPass(extra = {}, merge = {}, c = feedNow(), kinds = FEED_KINDS, limit = FEED_LIMIT, relays = null) {
    const def = feedDef(c.id);
    if (!def) return false;
    if (kinds === FEED_KINDS) kinds = feedKinds(def); // a conversations feed asks for replies
    const authors = feedAuthors(def), topics = feedTopics(def);
    const tag = topics.length ? { '#t': topics } : {};
    let got = false;
    if (def.curated) return popularPass(extra, merge, c, def);
    const orT = orTopicsOf(def);
    const orPass = orT.length
      ? queryFeed(relays || feedRelaysOr(def, TOPIC_RELAYS), { kinds, '#t': orT, limit, ...extra }, merge, c).then((x) => { if (x) got = true; })
      : null;
    if (!authors.length) {
      // topics alone: nobody's outbox to read, so the wide relays, one ask;
      // the firehose asks its relays for everything
      if (!topics.length && !def.all) return false;
      return queryFeed(relays || feedRelaysOr(def, def.all ? FIREHOSE_RELAYS : TOPIC_RELAYS), { kinds, ...tag, limit, ...extra }, merge, c);
    }
    const readPlan = async (plan) => {
      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) => {
          // the people's reposts too, unless this pass asks for particular kinds
          const ks = kinds === FEED_KINDS && !topics.length ? [...kinds, REPOST] : kinds;
          if (await queryFeed(relays, { kinds: ks, authors: chunk, ...tag, limit, ...extra }, merge, c)) got = true;
        });
      }));
    };
    if (relays || feedRelays(def)) await readPlan([{ relays: relays || feedRelays(def), authors }]);
    else {
      const initial = outboxPlan(authors);
      const reading = readPlan(initial);
      // Read known/default relays now. Discovery can add coverage later,
      // without holding every post behind a sequence of relay-list queries.
      await Promise.all([reading, (async () => {
        await fetchRelayLists(authors);
        if (c.stopped) return;
        const asked = new Map();
        for (const p of initial) for (const relay of p.relays) {
          const key = normRelay(relay);
          if (!asked.has(key)) asked.set(key, new Set());
          for (const pk of p.authors) asked.get(key).add(pk);
        }
        const additional = outboxPlan(authors).flatMap((p) => p.relays.map((relay) => ({ relays: [relay],
          authors: p.authors.filter((pk) => !asked.get(normRelay(relay))?.has(pk)),
        })).filter((p) => p.authors.length));
        await readPlan(additional);
      })()]);
    }
    await orPass;
    return got;
  }
  // Whatever a refresh finds goes behind the pill whenever posts are already
  // on screen — the cached page at boot included. Posts used to slide in a
  // beat after the page painted, moving what you had started reading. Only
  // a first load (nothing to disturb) or a rebuilt follow list goes straight in.
  async function refreshFeed(opts = {}, c = feedNow()) {
    // Ask at once; each answer prepares its own row at the door (mergeFeed).
    if (!feedHasQuery(feedDef(c.id))) { c.status = 'ready'; return; }
    if (!opts.force && Date.now() - c.at < 30_000) return;
    c.at = Date.now();
    const catchup = opts.live != null ? !!opts.live : !!c.notes.length;
    const newerThan = c.notes.length ? c.notes[0].created_at : Infinity;
    try { await feedPass({}, { catchup, newerThan }, c); } catch {} finally {
      c.status = 'ready';
      scheduleRepaint();
    }
    if (c === feed) watchFeed();
  }
  // Repaint with the page held still: the post at the top of the viewport
  // stays where it was, however much was inserted above it. Measured after
  // the paint, so a browser that anchored the scroll itself isn't corrected
  // twice.
  // ---- windowing: only the rows near the viewport are in the DOM ----------
  // A long scroll used to leave hundreds of rows mounted, and every repaint
  // (a zap count landing, the thirty-second sync) rebuilt and diffed all of
  // them — the slowdown you feel deep in the feed. Now a spacer stands in
  // for the rows above and below the window at their measured heights, so
  // the page keeps its length (scrollbar, Back, anchoring all behave), while
  // a repaint touches a few dozen rows however far you have scrolled. The
  // shape is svelte-virtual-list's: measure after paint, put unmeasured rows
  // in at the running average, and hold the reader's row still when a
  // measurement corrects an estimate.
  const WINDOW_AHEAD = 2.5; // screens kept rendered beyond the viewport, each way
  const WINDOW_MIN = 30; // below this many rows, no windowing at all
  const ROW_GAP = 1; // the hairline between rows
  function listWindow(c, list) {
    const H = typeof window === 'undefined' ? 0 : window.innerHeight;
    if (!H || list.length <= WINDOW_MIN) return { start: 0, end: list.length, top: 0, bottom: 0 };
    const heights = c.heights || (c.heights = new Map());
    let sum = 0, n = 0;
    for (const v of heights.values()) { sum += v; n++; }
    const avg = n ? sum / n : 200;
    const y0 = (window.scrollY || 0) - (c.listTop || 0); // viewport top, relative to the list
    const lo = y0 - WINDOW_AHEAD * H, hi = y0 + (1 + WINDOW_AHEAD) * H;
    let y = 0, start = 0, end = list.length, top = 0, bottom = 0;
    for (let i = 0; i < list.length; i++) {
      const rowH = (heights.get(list[i].id) || avg) + ROW_GAP;
      if (y + rowH <= lo) { top += rowH; start = i + 1; }
      else if (y >= hi) { bottom += rowH; if (end === list.length) end = i; }
      y += rowH;
    }
    return { start, end, top, bottom };
  }
  // The rows for a windowed list: hairline + row for what is in the window,
  // a spacer either side. Every child keyed, so the morph moves by key.
  function windowedRows(c, list, rowOf) {
    const win = listWindow(c, list);
    c.win = win;
    const hr = (ev) => h('div', { 'data-key': 'hr:' + ev.id, style: 'height:1px;background:var(--border,rgba(128,128,128,.18));margin:0 -14px' });
    const out = [];
    if (win.top) out.push(h('div', { 'data-key': 'win-top', class: 'feed-spacer', style: 'height:' + Math.round(win.top) + 'px' }));
    for (let i = win.start; i < win.end; i++) {
      if (i) out.push(hr(list[i]));
      out.push(rowOf(list[i]));
    }
    if (win.bottom) out.push(h('div', { 'data-key': 'win-bottom', class: 'feed-spacer', style: 'height:' + Math.round(win.bottom) + 'px' }));
    measureRows(c);
    return out;
  }
  // After the paint: remember each mounted row's height and where the list
  // starts. A spacer that was built on estimates gets its real numbers on a
  // repaint that holds the reader's row still.
  function measureRows(c, { repaint = true } = {}) {
    if (c._measuring || typeof requestAnimationFrame === 'undefined') return;
    c._measuring = true;
    requestAnimationFrame(() => {
      c._measuring = false;
      const changed = measureNow(c);
      if (changed && repaint && c.win && (c.win.top || c.win.bottom)) holdScroll(render);
    });
  }
  // A row changes height after it was measured — a picture lands in a row
  // that painted before its size was known, a clip learns its shape, a link
  // card arrives. The stale number is what the spacer uses when the row
  // leaves the window: the page then shrinks or grows by the difference,
  // the browser's scroll anchoring pulls the reader back by as much, and a
  // coasting wheel scroll stalled or even reversed right as the media
  // appeared. Keep the measurements live instead (no layout forced: the
  // observer runs after layout).
  const rowSizer = typeof ResizeObserver === 'undefined' ? null : new ResizeObserver((entries) => {
    for (const en of entries) {
      const r = en.target, c = r.parentElement && r.parentElement._winC;
      if (!c || !r.isConnected) continue;
      const hgt = r.getBoundingClientRect().height, key = r.getAttribute('data-key');
      if (hgt > 0 && key) (c.heights || (c.heights = new Map())).set(key, hgt);
    }
  });
  function measureNow(c) {
    const list = document.querySelector('.notes-feed');
    if (!list) return false;
    c.listTop = list.getBoundingClientRect().top + (window.scrollY || 0);
    list._winC = c;
    const heights = c.heights || (c.heights = new Map());
    let changed = false;
    const seen = new Set();
    for (const r of list.querySelectorAll(':scope > .row[data-key]')) {
      const hgt = r.getBoundingClientRect().height;
      const key = r.getAttribute('data-key');
      if (hgt > 0 && Math.abs((heights.get(key) || 0) - hgt) > 0.5) { heights.set(key, hgt); changed = true; }
      if (rowSizer) { seen.add(r); if (!(list._sized ||= new Set()).has(r)) { list._sized.add(r); rowSizer.observe(r); } }
    }
    if (rowSizer && list._sized) for (const r of list._sized) if (!seen.has(r)) { list._sized.delete(r); rowSizer.unobserve(r); }
    return changed;
  }
  // On scroll: replenish the buffer before the reader reaches its edge,
  // holding their row still. Coalesce scroll events into one check per frame.
  let windowRaf = 0;
  function windowScrolled(c) {
    if (!c || !c.win || windowRaf) return;
    windowRaf = requestAnimationFrame(() => {
      windowRaf = 0;
      const list = c.winList ? c.winList() : null;
      if (!list || !c.win || (!c.win.start && c.win.end >= list.length)) return;
      // Keep using the 2.5-screen overscan until only one screen remains.
      // Recentring it every time an offscreen row crossed the ideal boundary
      // rebuilt the whole pane repeatedly during a coast. Two edge reads
      // suffice here; measure all rows only when the window actually moves.
      const rows = document.querySelectorAll('.notes-feed > .row[data-key]');
      const first = rows[0], last = rows[rows.length - 1], H = window.innerHeight;
      if (!first || !last) return;
      const nearTop = c.win.start > 0 && first.getBoundingClientRect().top > -H;
      const nearBottom = c.win.end < list.length && last.getBoundingClientRect().bottom < 2 * H;
      if (!nearTop && !nearBottom) return;
      measureNow(c);
      holdScroll(render, c);
    });
  }

  function holdScroll(paint, c = feed) {
    let key = null, top = 0;
    try {
      for (const r of document.querySelectorAll('.notes-feed > .row[data-key]')) {
        const b = r.getBoundingClientRect();
        if (b.bottom > 0 && b.top < window.innerHeight) { key = r.getAttribute('data-key'); top = b.top; break; }
      }
    } catch {}
    paint();
    if (!key) return;
    const find = () => document.querySelector('.notes-feed > [data-key="' + CSS.escape(key) + '"]');
    try {
      let r = find();
      // Not mounted any more: a batch went in above (a catch-up of thirty
      // posts, say) and the window, computed for the old scroll offset, now
      // holds the newcomers instead of the reader's row. Estimate where the
      // row went from the height cache, scroll there, and paint once more
      // so the window catches up — then the usual correction lands it.
      if (!r && c && c.heights && c.winList) {
        const list = c.winList();
        const i = list.findIndex((ev) => ev.id === key);
        if (i >= 0) {
          let sum = 0, n = 0;
          for (const v of c.heights.values()) { sum += v; n++; }
          const avg = n ? sum / n : 200;
          let y = 0;
          for (let j = 0; j < i; j++) y += (c.heights.get(list[j].id) || avg) + ROW_GAP;
          window.scrollTo(0, Math.max(0, (c.listTop || 0) + y - top));
          paint();
          r = find();
        }
      }
      const d = r ? r.getBoundingClientRect().top - top : 0;
      if (Math.abs(d) > 1) window.scrollBy(0, d);
    } catch {}
  }
  // 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();
    const c = feedNow();
    const def = feedDef(c.id); // the Conversations view has its own
    if (!feedHasQuery(def) || !ui.chatOpen || ui.msgView !== 'feed') return;
    const newerThan = c.notes.length ? c.notes[0].created_at : Infinity;
    const since = Math.floor(Date.now() / 1000) - 60;
    const topics = feedTopics(def), tag = topics.length ? { '#t': topics } : {};
    const kinds = feedKinds(def);
    const on = (ev) => { mergeFeed([ev], { live: true, newerThan }, c).then((ok) => { if (ok) scheduleRepaint(); }).catch(() => {}); };
    const authors = feedAuthors(def);
    if (def.curated) { const iv = setInterval(() => { if (c === feed && ui.chatOpen && ui.msgView === 'feed') refreshFeed({ force: true, live: true }, c).catch(() => {}); }, 120_000); feedUnsubs.push(() => clearInterval(iv)); return; }
    if (!authors.length) { feedUnsubs.push(subscribeOn(feedRelaysOr(def, def.all ? FIREHOSE_RELAYS : TOPIC_RELAYS), { kinds, ...tag, since }, on)); return; }
    const orT = orTopicsOf(def);
    if (orT.length) feedUnsubs.push(subscribeOn(feedRelaysOr(def, TOPIC_RELAYS), { kinds, '#t': orT, since }, on));
    const plan = feedRelays(def) ? [{ relays: feedRelays(def), authors }] : outboxPlan(authors);
    for (const { relays, authors: a } of plan)
      for (let i = 0; i < a.length; i += REQ_AUTHORS)
        feedUnsubs.push(subscribeOn(relays, { kinds: topics.length || def.replies ? kinds : [...kinds, REPOST], authors: a.slice(i, i + REQ_AUTHORS), ...tag, since }, on));
  }
  function stopFeedWatch() {
    for (const u of feedUnsubs) { try { u(); } catch {} }
    feedUnsubs = [];
  }
  // Prepare older pages several screens ahead of the reader. A scroll while
  // preparation is underway shares the same work instead of exposing it early.
  let feedAheadTimer = null;
  function prepareFeedAhead(c) {
    if (feedAheadTimer || c.booting || c.loadingMore || (c.shown >= c.notes.length && (c.end || c.status !== 'ready'))) return;
    feedAheadTimer = setTimeout(() => {
      feedAheadTimer = null;
      if (c !== feed || !ui.chatOpen || ui.msgView !== 'feed' || ui.profilePk || ui.noteThread) return;
      if (mediaMode === 'live') return;
      if (!listView()) {
        // a grid holds only the posts with media: keep fetching while its
        // foot is near (within reason — a firehose has no end)
        const g = document.querySelector(mediaMode === 'articles' ? '.article-list' : '.media-grid');
        if (!g || g.getBoundingClientRect().bottom < window.innerHeight * 3) (mediaMode === 'articles' ? crawlArticles : crawlMedia)(c).catch(() => {});
        return;
      }
      fetchOlderAhead(c); // the relays, meanwhile, if what we hold beyond the rows is thin
      if (c.win && c.win.bottom) return; // rows below are held back by the window, not by paging
      const rows = document.querySelectorAll('.notes-feed > .row[data-key]');
      const last = rows[rows.length - 1];
      if (last && last.getBoundingClientRect().bottom < feedLead()) loadOlderFeed().catch(() => {});
    }, 100);
  }
  // ---- the reader's appetite -------------------------------------------
  // How hungrily the feed is being scrolled: the screens travelled, by the
  // reader's own hand, over the last ten seconds. A page of posts is read
  // at a screen or two in that time; five screens in it is someone flying
  // through, and the feed answers by paging more posts at a time and
  // asking for them from further up — up to four pages and four times the
  // lead at once. (Adam, 2026-10-16: "could we load posts faster if it
  // seems like the user is scrolling a lot? … try always loading more
  // posts and loading them sooner when we're further away from the
  // bottom".) The trail counts only scrolls within a moment of an input,
  // so a page held still under an insert above doesn't look like travel.
  const APPETITE_MAX = 4, APPETITE_MS = 10_000, APPETITE_SCREENS = 5;
  const scrollTrail = []; // [at, scrollY]
  function noteScrollTrail(y) {
    const now = Date.now();
    scrollTrail.push([now, y]);
    while (scrollTrail.length && now - scrollTrail[0][0] > APPETITE_MS) scrollTrail.shift();
  }
  function appetite() {
    const now = Date.now();
    while (scrollTrail.length && now - scrollTrail[0][0] > APPETITE_MS) scrollTrail.shift();
    if (scrollTrail.length < 2) return 1;
    const H = (typeof window !== 'undefined' && window.innerHeight) || 800;
    const down = scrollTrail[scrollTrail.length - 1][1] - scrollTrail[0][1];
    return Math.max(1, Math.min(APPETITE_MAX, 1 + Math.floor(down / (APPETITE_SCREENS * H))));
  }
  // how far above the foot of the feed the next page is asked for
  const feedLead = () => Math.max(3000, ((typeof window !== 'undefined' && window.innerHeight) || 800) * 4) * appetite();
  // The relays run AHEAD of the rows. The older page used to be asked for
  // only once every post in hand was on screen, and shown only once the
  // whole pass had answered — so the reader who reached the end of what we
  // held waited a relay round trip, up to the five seconds the slowest
  // relay in the pass is given. Now a pass for older posts starts as soon
  // as what we hold beyond the shown rows thins to a page or two (more
  // with the appetite), its rows warming at the door while the reader is
  // still on the posts before them; the showing step takes from hand.
  function fetchOlderAhead(c) {
    if (c.fetching) return c.fetching;
    if (c.end || c.booting || c.stopped || c.status !== 'ready') return null;
    if (c.notes.length - c.shown >= FEED_PAGE * (1 + appetite())) return null;
    const oldest = c.notes.at(-1);
    if (!oldest || !feedHasQuery(feedDef(c.id))) { c.end = true; return null; }
    c.fetching = (async () => {
      let until = oldest.created_at - 1;
      const limit = Math.min(100, FEED_LIMIT * appetite()); // a hungrier reader is fetched more per round trip
      for (let tries = 0; tries < 3; tries++) {
        c.sawAny = 0;
        if (await feedPass({ until }, {}, c, FEED_KINDS, limit)) return true;
        // nothing older at all (or no step back): that really is the end
        if (!c.sawAny || !(c.seenBack <= until)) { c.end = true; return false; }
        until = c.seenBack - 1;
      }
      return false;
    })().catch(() => false).finally(() => {
      c.fetching = null;
      if (c === feed && !c.stopped) { scheduleRepaint(); prepareFeedAhead(c); }
    });
    return c.fetching;
  }
  async function loadOlderFeed() {
    const c = feedNow();
    if (c.booting || c.loadingMore || (c.shown >= c.notes.length && (c.end || c.status !== 'ready'))) return;
    c.loadingMore = true;
    if (c === feed) render(); // the footer says so while it happens
    try {
      fetchOlderAhead(c);
      if (c.shown >= c.notes.length) {
        // nothing in hand: the pass underway (started just now, if need be) brings the next page
        if (!c.fetching) return;
        await c.fetching;
        if (c.shown >= c.notes.length) return;
      }
      const page = FEED_PAGE * appetite();
      const end = Math.min(c.shown + page, c.notes.length);
      const boundary = c.notes[end - 1].id;
      await notesReady(c.notes.slice(c.shown, Math.min(end + page, c.notes.length)), { parent: feedReplies(c) });
      c.shown = Math.max(c.shown, c.notes.findIndex((e) => e.id === boundary) + 1);
      fetchOlderAhead(c); // and the relays, if that thinned what we hold
    } finally {
      c.loadingMore = false;
      if (c === feed) 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}\\)';
  // A bare @handle ("Founder of @MusiKnow") names a person without a key.
  // Nothing can resolve it for certain, so it becomes a tap that opens the
  // people search with that name filled in. Not the @ inside an email or a
  // nip05 (a word character sits before those), and never inside a URL
  // (the URL token starts earlier and swallows it).
  const MENTION = '(?<![\\w.@/])@[A-Za-z0-9_]{2,32}(?![\\w@])';
  const HASHTAG = '(?<![\\w#/&])#[A-Za-z0-9_\\u00C0-\\uFFFF]{2,64}(?![\\w])';
  // A bare npub/nprofile — with or without an @ in front, no nostr: prefix —
  // is how Vector (and people) write a mention; it resolves to the name too.
  const BARE_KEY = '(?<![\\w/])@?(?:npub|nprofile)1[a-z0-9]{20,}(?![\\w])';
  const NOTE_SPLIT = new RegExp('(' + MD_LINK + '|https?:\\/\\/[^\\s]+|wss?:\\/\\/[^\\s]+|nostr:(?:npub|nprofile|note|nevent|naddr)1[a-z0-9]+|' + BARE_KEY + '|' + MENTION + '|' + HASHTAG + ')', '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;
  };

  // ---- autoplay: a video plays, muted, while it is on screen --------------
  // The way a timeline does it: a video starts by itself as it scrolls into
  // view — muted, the only way a browser lets a page start one — pauses as
  // it leaves, and a corner button turns the sound on. YouTube gets the same
  // treatment: the player loads muted once its box is in view, and the
  // button asks it to unmute over the iframe API. Data Saver keeps the old
  // tap-to-play. One observer watches every player.
  const autoplayOk = () => { try { return !(navigator.connection && navigator.connection.saveData); } catch { return true; } };
  let playerWatch = null;
  function watchPlayer(el, onIn, onOut) {
    if (typeof IntersectionObserver === 'undefined' || !autoplayOk()) return;
    if (!playerWatch) playerWatch = new IntersectionObserver((entries) => {
      for (const en of entries) {
        const el2 = en.target;
        if (!el2.isConnected) { playerWatch.unobserve(el2); continue; }
        // under the media pager nothing starts: the page laid out again
        // beneath it (a turn of the phone) "showed" a clip — the pager's own,
        // as often as not — and a second copy played behind it
        if (ui.mediaPager && en.isIntersecting) continue;
        if (en.isIntersecting && en.intersectionRatio >= 0.5) { if (el2._onIn) el2._onIn(); } else if (el2._onOut) el2._onOut();
      }
    }, { threshold: [0, 0.5] });
    el._onIn = onIn; el._onOut = onOut;
    playerWatch.observe(el);
  }
  // The corner button: what it says is the state it would switch to.
  function soundBtn(onClick) {
    const btn = h('button', { class: 'vid-sound', type: 'button', onClick: (e) => { e.stopPropagation(); e.preventDefault(); onClick(e.currentTarget); } });
    btn.setSound = (on) => {
      btn.classList.toggle('on', !!on);
      btn.textContent = (on ? '\u{1F50A} ' : '\u{1F507} ') + (on ? t('videoMute') : t('videoUnmute'));
      btn.setAttribute('aria-label', on ? t('videoMute') : t('videoUnmute'));
      btn.title = on ? t('videoMute') : t('videoUnmute');
    };
    btn.setSound(false);
    return btn;
  }
  // An inline video, in a box with the sound button; plays on its own while
  // on screen. Once it has played, the box is the viewer's (no morph).
  // A clip the reader turned the sound on for stays that way for the session,
  // however its box is rebuilt: a repaint pairing children differently, the
  // window unmounting the row and mounting it again, a quoted note loading.
  // Pinning the box alone left every one of those a muted restart.
  const unmutedClips = new Set();
  const wokeClips = new Set(); // played, or tried to: the player's controls show

  // A feed box spans the column and takes the clip's own shape when it's
  // known, never taller than the screen; only a clip taller than that sits
  // in a black frame, rather than in a strip at the left.
  const videoBoxStyle = (d) => d && d.width && d.height
    ? `width:100%;aspect-ratio:${d.width}/${d.height};max-height:100vh;object-fit:contain`
    : 'width:100%;aspect-ratio:16/9;object-fit:contain';
  // Over a clip that waits for a tap: what it costs, and the tap that plays
  // it (with sound — the reader asked for this one). The box is left alone
  // by the morph from here, or a repaint would take the cover off.
  function heavyCover(box, url, onPlay) {
    if (box.querySelector('.vid-heavy')) return;
    box._skipMorph = true;
    const cover = h('button', { class: 'vid-heavy', type: 'button', 'aria-label': t('videoTapToPlay'),
      onClick: (e) => {
        e.stopPropagation(); e.preventDefault();
        tappedClips.add(url);
        cover.remove();
        onPlay && onPlay();
        const v = box.querySelector('video');
        if (v) {
          if (v.getAttribute('src') !== playSrc(url)) v.setAttribute('src', playSrc(url));
          v.preload = 'auto';
          v.play().catch(() => { wokeClips.add(url); box.classList.remove('idle'); v.controls = true; });
        }
      } }, h('span', { class: 'vid-heavy-play', 'aria-hidden': 'true' }, '\u25b6'), h('span', {}, heavyLabel(url)));
    box.append(cover);
  }
  // ---- clips this browser can't picture, posters a post didn't give -------
  // The server (vmedia/server.js) makes a still for a clip that came without
  // one — a clip waiting for a tap was a black box — and an H.264 copy of
  // one whose picture this browser can't decode: an iPhone's HEVC on Chrome
  // for Linux plays its sound over black.
  const VMEDIA = APP_BASE + '/vmedia/';
  const vmediaOk = (url) => /^https:\/\//i.test(url || '');
  // v=4: stills past a dark opening frame (a new URL, so the CDN's old black ones aren't served)
  const serverThumb = (url) => (vmediaOk(url) ? VMEDIA + 'thumb.jpg?v=4&u=' + encodeURIComponent(url) : undefined);
  // the clip's very first frame at full size (the pager's slides ahead hold it)
  const serverFirst = (url) => (vmediaOk(url) ? VMEDIA + 'first.jpg?u=' + encodeURIComponent(url) : undefined);
  const serverFirstFailed = new Set(); // clips the server had no first frame for (this session)
  const h264Of = (url) => VMEDIA + 'h264.mp4?u=' + encodeURIComponent(url);
  const noPicture = new Set(), h264Failed = new Set();
  const serverThumbFailed = new Set(); // clips vmedia had no picture for (this session)
  // A picture from a host that won't hand over its bytes (no CORS: primal's
  // blossom, nostrcheck, most personal sites) can't have its column copy made
  // here, so the server makes it (pic.webp: 1100px wide, or a 360px square
  // for the grid; libvips, cached for everyone at the CDN). Without this the
  // <img> painted the original, and a 9528×6328 camera file froze a wheel
  // scroll for 400 ms on its texture upload. The copy is kept in the same
  // cache as the ones made here, so the next visit paints it at once.
  const serverPic = (url, shape) => (vmediaOk(url) && !/\.gif(\?|$)/i.test(url) ? VMEDIA + 'pic.webp?s=' + shape + '&u=' + encodeURIComponent(url) : null);
  const serverPicFailed = new Set(); // pictures the server had no copy for (this session)
  const picDims = (src) => new Promise((resolve) => {
    const img = new Image();
    img.onload = () => (img.decode ? img.decode() : Promise.resolve()).then(() => resolve({ width: img.naturalWidth, height: img.naturalHeight }), () => resolve(null));
    img.onerror = () => resolve(null);
    img.src = src;
  });
  async function serverPicBlob(url, shape) {
    const src = serverPic(url, shape);
    if (!src || serverPicFailed.has(shape + '|' + url)) return null;
    let res;
    try { res = await fetch(src, { signal: AbortSignal.timeout(READY_MS) }); } catch { return null; }
    if (!res.ok) {
      if (res.status !== 429 && res.status !== 503) serverPicFailed.add(shape + '|' + url); // busy is tried again
      return null;
    }
    const blob = await res.blob();
    return /^image\//.test(blob.type) && blob.size ? blob : null;
  }
  async function serverMediaThumb(url) {
    const blob = await serverPicBlob(url, 'col');
    if (!blob) return null;
    const thumb = URL.createObjectURL(blob);
    const dims = await picDims(thumb);
    if (!dims || !dims.width) { URL.revokeObjectURL(thumb); serverPicFailed.add('col|' + url); return null; }
    try {
      const store = await thumbStore();
      await store.put(url, new Response(blob, { headers: { 'x-dims': JSON.stringify(dims), 'x-original': '0' } }));
      const keys = await store.keys();
      for (const k of keys.slice(0, Math.max(0, keys.length - MEDIA_THUMB_MAX))) store.delete(k);
    } catch {}
    return { ...dims, thumb };
  }
  let hevcPlays;
  const canHevc = () => hevcPlays ??= (() => {
    try { return !!document.createElement('video').canPlayType('video/mp4; codecs="hvc1.1.6.L93.B0"'); } catch { return true; }
  })();
  // A long clip (or a big one whose length isn't known) plays as HLS from
  // vmedia: a 360p and a 720p rendition, the player taking the one the
  // connection carries, in 4-second pieces made as they're watched — not a
  // whole file streamed at its own bitrate (Adam, 2026-10-18; jb55: "you
  // should use hls (m3u8 ext) for long videos"). Where the browser plays HLS
  // itself (Chrome since 2025, Safari, Android); elsewhere (Firefox) the
  // original as before.
  const HLS_MIN_S = 90, HLS_MIN_BYTES = 60e6;
  const hlsOf = (url) => VMEDIA + 'hls.m3u8?u=' + encodeURIComponent(url);
  const isHls = (src) => (src || '').startsWith(VMEDIA + 'hls') || /\.m3u8(\?|#|$)/i.test(src || '');
  const hlsFailed = new Set();
  let hlsPlays;
  const canHls = () => hlsPlays ??= (() => {
    try { return !!document.createElement('video').canPlayType('application/vnd.apple.mpegurl'); } catch { return false; }
  })();
  const longClip = (url) => { const d = videoInfo.get(url) || {}; return d.dur ? d.dur >= HLS_MIN_S : (d.size || 0) >= HLS_MIN_BYTES; };
  // Long, or too big to play as it is (a 4K clip, a 140 MB one: these
  // waited for a tap with their cost on them) — streamed at a rendition the
  // connection carries instead. A small short clip plays as it is: one
  // request, its own quality, no work for the server.
  const streamsHere = (url) => vmediaOk(url) && !isHls(url) && canHls() && !hlsFailed.has(url) && (longClip(url) || bigClip(url, true));
  // what a player for this clip loads: the stream for a long or big one;
  // the copy, once the original is known not to show here
  const playSrc = (url) => !vmediaOk(url) || isHls(url) ? url
    : streamsHere(url) ? hlsOf(url)
    : !h264Failed.has(url) && (noPicture.has(url) || ((videoInfo.get(url) || {}).hevc && !canHevc())) ? h264Of(url) : url;
  // A player whose clip turns out to have no picture it can show (its
  // metadata says zero width) switches to the copy; if the copy fails too,
  // the original's sound plays under a line saying why, with the file.
  function guardPicture(v, url) {
    if (!vmediaOk(url)) return;
    const onCopy = () => (v.getAttribute('src') || '').startsWith(VMEDIA);
    v.addEventListener('loadedmetadata', () => {
      if (v.videoWidth || onCopy() || h264Failed.has(url)) return;
      noPicture.add(url);
      const want = !v.paused;
      v.setAttribute('src', h264Of(url));
      if (want) v.play().catch(() => {});
    });
    v.addEventListener('error', () => {
      if (!onCopy()) return;
      // the stream failed: the copy or the original, as it would have been
      if (isHls(v.getAttribute('src'))) {
        hlsFailed.add(url);
        const want = !v.paused;
        v.setAttribute('src', playSrc(url));
        if (want) v.play().catch(() => {});
        return;
      }
      h264Failed.add(url);
      const want = !v.paused;
      v.setAttribute('src', url);
      if (want) v.play().catch(() => {});
      const box = v.parentElement;
      if (box && !box.querySelector('.vid-nopic')) {
        box._skipMorph = true;
        box.append(h('div', { class: 'vid-nopic' }, h('span', {}, t('videoNoPicture')),
          h('a', { href: url, target: '_blank', rel: 'noopener noreferrer', onClick: (e) => e.stopPropagation() }, t('videoOpenFile'))));
      }
    });
  }
  // A tap on the picture itself (not the player's own play button or its
  // control bar): inline, it goes full screen — the corner button is a
  // reach on a phone. Full screen, it pauses a playing clip, and a tap on a
  // paused one comes back out. The player's controls are inside the video
  // element, so where they sit is judged from the tap's position.
  const fsElement = () => (typeof document !== 'undefined' && (document.fullscreenElement || document.webkitFullscreenElement)) || null;
  let videoTapAt = 0; // a touch's tap on a clip, taken at pointerup: the click after it lands on whatever opened
  function videoTap(e, url) {
    const v = e.currentTarget;
    if (!v || v.tagName !== 'VIDEO') return false;
    const r = v.getBoundingClientRect();
    const x = e.clientX - r.left, y = e.clientY - r.top;
    // a video's taps are its own: never the post's (which opened the thread
    // and, full screen, took the player out from under the reader)
    e.stopPropagation();
    const fs = fsElement() === v;
    // full screen, the video's box is the screen; its controls sit along the bottom
    const H = fs ? window.innerHeight : r.height, W = fs ? window.innerWidth : r.width;
    if (v.controls && y > H - 64) return false; // the control bar
    if (v.controls && v.paused && Math.hypot(x - W / 2, y - H / 2) < 48) return false; // the big play button
    e.preventDefault();
    if (fs) {
      if (!v.paused) v.pause();
      else (document.exitFullscreen || document.webkitExitFullscreen || (() => {})).call(document)?.catch?.(() => {});
      return true;
    }
    if (openClip(v, url)) return true;
    // a clip still idle (autoplaying, no controls) becomes the reader's
    wokeClips.add(url);
    const box = v.closest('.note-video-box');
    if (box) { box.classList.remove('idle'); box._skipMorph = true; }
    v.controls = true;
    const go = v.requestFullscreen || v.webkitRequestFullscreen || v.webkitEnterFullscreen;
    if (!go) return true;
    // (the screen isn't turned for it: a wide clip plays with bars, and the
    // reader turns the phone if they want it bigger)
    Promise.resolve(go.call(v)).catch(() => {});
    return true;
  }
  if (typeof document !== 'undefined') document.addEventListener('fullscreenchange', () => {
    const el = fsElement();
    // The player's own full-screen button on a feed clip: the pager, not
    // Chrome's full screen (no next clip there). The button stays on the bar
    // (left off, Chrome greys it out) and is taken over here.
    // (only a clip the pager has: taken out of full screen for a pager that
    // then wouldn't open, a quoted post's clip went nowhere at all)
    if (el && !pager && el.matches && el.matches('.notes-feed video.note-video') && el.dataset.clip && clipItem(el, el.dataset.clip)) {
      const url = el.dataset.clip;
      Promise.resolve((document.exitFullscreen || document.webkitExitFullscreen || (() => {})).call(document)).catch(() => {})
        .then(() => { if (!pager && document.contains(el)) openClip(el, url); });
      return;
    }
    if (el) return;
    // out of the pager's full screen some other way (Back on Android, Escape
    // on a computer): out of the pager too, in the one step
    if (pagerFs) { pagerFs = false; if (pager) dismissPager(); }
  });
  function videoNode(url, { stable = false } = {}) {
    const loud = unmutedClips.has(url);
    // Nothing is fetched until the clip is about to play (preload none): a
    // window of rows used to pull every clip's metadata, which for a file
    // with its index at the end can be most of the file.
    // Until it plays, a clip is its picture (filling the box) and at most a
    // play button: no seek bar, no sound button. Without autoplay the
    // player's own controls are the way in, so they stay.
    const idle = autoplayOk() && !wokeClips.has(url);
    // (data-clip: which clip it is, for the full-screen button's pager)
    const v = h('video', { src: playSrc(url), class: 'note-video', controls: idle ? undefined : true, 'data-clip': url, poster: videoThumbs.get(url) || (videoInfo.get(url) || {}).image || serverThumb(url),
      preload: 'none', playsinline: true, muted: loud ? undefined : true,
      style: stable ? videoBoxStyle(feedMedia(url)) : undefined,
      // learned now, used by the next paint of any row with this clip
      onLoadedmetadata: (e) => { rememberVideo(url, e.target.videoWidth, e.target.videoHeight); attachMediaTimeline(e.target, url); },
      // a touch's tap was taken at pointerup (below): its click, if one comes, is spent
      onClick: (e) => { if (Date.now() - (e.currentTarget._tapAt || 0) < 800) { e.stopPropagation(); e.preventDefault(); return; } videoTap(e, url); },
      onError: (e) => { if (!stable && !(e.target.getAttribute('src') || '').startsWith(VMEDIA)) { const b = e.target.parentElement; if (b) b.style.display = 'none'; } } });
    guardPicture(v, url);
    // With its own controls up, Chrome on Android keeps a tap on the clip for
    // them (it shows or hides the bar) and the page never gets the click — so
    // a full-screen tap on a clip that had been played did nothing. The
    // pointer events still arrive: a touch that lifts where it went down,
    // quickly, is the tap.
    v.addEventListener('pointerdown', (e) => {
      if (e.pointerType === 'mouse') return;
      e.currentTarget._touch = { x: e.clientX, y: e.clientY, t: Date.now(), id: e.pointerId };
    });
    v.addEventListener('pointercancel', (e) => { e.currentTarget._touch = null; });
    v.addEventListener('pointerup', (e) => {
      const el = e.currentTarget, d = el._touch;
      el._touch = null;
      if (!d || d.id !== e.pointerId || Date.now() - d.t > 500 || Math.hypot(e.clientX - d.x, e.clientY - d.y) > 12) return;
      if (videoTap(e, url)) el._tapAt = videoTapAt = Date.now();
    });
    v.muted = !loud; // the property, not just the attribute: a script-made element autoplays only muted
    const box = h('div', { class: 'note-video-box' + (idle ? ' idle' : '') }, v);
    if (loud) box._skipMorph = true;
    // remembered by clip, so a repaint draws the box as it now stands
    const wake = () => {
      wokeClips.add(url);
      box.classList.remove('idle');
      v.controls = true;
    };
    v.addEventListener('playing', wake);
    const btn = loud ? null : soundBtn((button) => {
      // Morphing copies handlers from a fresh tree onto the live button.
      // Resolve its player at tap time instead of changing a detached video.
      const liveBox = button.closest('.note-video-box');
      const player = liveBox?.querySelector('video');
      if (!player) return;
      player.muted = false;
      unmutedClips.add(url);
      liveBox._skipMorph = true; // the box is the viewer's now: no repaint rebuilds it muted
      if (player.paused) player.play().catch(() => {});
      button.remove(); // the player's own controls carry mute from here
    });
    v.onvolumechange = () => {
      if (!v.muted) { unmutedClips.add(url); if (btn && btn.isConnected) btn.remove(); } // unmuted from the native control: same
      else unmutedClips.delete(url); // muted again from the control: the next box starts quiet
    };
    if (btn) box.append(btn);
    // Off screen, a muted preview lets go of its media entirely (a paused
    // player keeps buffering the whole file — a scroll past ten clips
    // streamed seventy megabytes); back in view it reattaches and plays
    // from the start. A clip the reader unmuted keeps its place instead.
    watchPlayer(v,
      () => {
        box._inView = true;
        clearTimeout(box._release);
        if (!v.getAttribute('src') && !v.getAttribute('data-lazy-src')) {
          v.setAttribute('src', playSrc(url));
          v.addEventListener('loadedmetadata', () => { v.style.minHeight = ''; }, { once: true });
        }
        // a clip over the budget waits for a tap, with what it costs on it
        probeVideo(url).then(() => {
          if (!box._inView || !v.isConnected) return;
          // known by now not to show here: the copy, before a byte of the original
          if (v.paused && v.getAttribute('src') && v.getAttribute('src') !== playSrc(url)) v.setAttribute('src', playSrc(url));
          if (videoHeavy(url)) { heavyCover(box, url, () => { v.muted = false; unmutedClips.add(url); if (btn && btn.isConnected) btn.remove(); }); return; }
          if (v.paused) v.play().then(() => { box._skipMorph = true; }).catch(wake);
        });
      },
      () => {
        box._inView = false;
        if (!v.paused) v.pause();
        if (!(v.muted && box._skipMorph)) return;
        // Let go a moment later, and hold the box at its height meanwhile:
        // an instant release collapsed a tall clip the reader had just
        // scrolled past, and the page jumped under their thumb.
        clearTimeout(box._release);
        box._release = setTimeout(() => {
          if (box._inView || !v.isConnected) return;
          const hgt = v.getBoundingClientRect().height;
          if (hgt > 0) v.style.minHeight = hgt + 'px';
          try { v.removeAttribute('src'); v.load(); } catch {}
        }, 2500);
      });
    return box;
  }

  // The still, with a play button over it, and the player itself only once
  // it's tapped — or, with autoplay, once the box scrolls into view, muted.
  // A feed of ten videos would otherwise load ten YouTube players at once,
  // every one of them telling Google what you're scrolling past; loading on
  // view (and never with sound uninvited) keeps that to what you look at.
  function youtubeEmbed(url, vid) {
    const start = ytStart(url);
    const embedSrc = (muted) => 'https://www.youtube-nocookie.com/embed/' + vid
      + '?autoplay=1&rel=0&playsinline=1&enablejsapi=1' + (muted ? '&mute=1' : '') + (start ? '&start=' + start : '')
      + (typeof location !== 'undefined' ? '&origin=' + encodeURIComponent(location.origin) : '');
    const src = embedSrc(false);
    // the iframe API listens for commands once told someone is listening
    const post = (box, func) => {
      const f = box.querySelector('iframe');
      try { if (f && f.contentWindow) f.contentWindow.postMessage(JSON.stringify({ event: 'command', func, args: [] }), '*'); } catch {}
    };
    const load = (box, muted) => {
      if (!box || box.dataset.playing) return;
      box.dataset.playing = '1';
      // The page repaints in the background all the time (a zap count,
      // a profile landing, the thirty-second sync), and every repaint
      // rebuilds this box as poster + play button and patches the live
      // one into that shape — which threw the playing iframe out a few
      // seconds into every video. Once playing, the box is the viewer's
      // and the morph leaves it exactly as it stands.
      box._skipMorph = true;
      box.textContent = '';
      const f = document.createElement('iframe');
      f.src = muted ? embedSrc(true) : 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;
      f.onload = () => { try { f.contentWindow.postMessage(JSON.stringify({ event: 'listening', id: vid }), '*'); } catch {} };
      box.append(f);
      // a tap on the picture is ours, not the player's (whose taps the page
      // never sees): it takes the clip full screen — YouTube's own control
      // bar along the bottom stays YouTube's. Full screen, this steps aside.
      box.append(h('div', { class: 'yt-shield', 'aria-hidden': 'true' }));
      if (muted) {
        let on = false;
        const btn = soundBtn(() => { on = !on; btn.setSound(on); post(box, on ? 'unMute' : 'mute'); if (on) post(box, 'playVideo'); });
        box._soundOn = () => { on = true; btn.setSound(true); };
        box.append(btn);
      }
    };
    // One tap, as with any clip in a post: it plays, with sound, full screen
    // (the screen not turned: the reader turns the phone if they like). The
    // still loads the player first; a player already going (autoplayed,
    // muted) is unmuted and carried on.
    const full = (box) => {
      const go = box.requestFullscreen || box.webkitRequestFullscreen;
      if (!go) return;
      Promise.resolve(go.call(box, { navigationUI: 'hide' })).catch(() => {});
    };
    const tapped = (e) => {
      if (e.target.closest('.yt-open, .vid-sound, iframe')) return;
      e.stopPropagation(); e.preventDefault();
      const box = e.currentTarget;
      if (!box.dataset.playing) load(box, false); // a tap means sound
      else { post(box, 'unMute'); post(box, 'playVideo'); if (box._soundOn) box._soundOn(); }
      full(box);
    };
    const frame = h('div', { class: 'yt-embed', onClick: tapped },
      h('img', {
        class: 'yt-poster', loading: 'lazy', alt: '',
        src: !feedPaint || feedMedia('https://i.ytimg.com/vi/' + vid + '/hqdefault.jpg')
          ? 'https://i.ytimg.com/vi/' + vid + '/hqdefault.jpg' : undefined,
        onError: (e) => { e.target.style.display = 'none'; },
      }),
      // (its tap is the box's: play, full screen)
      h('button', {
        class: 'yt-play', type: 'button', 'aria-label': t('playVideo'), title: t('playVideo'),
      }, 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'));
    // in view: load muted the first time, resume after; out of view: pause
    watchPlayer(frame,
      () => { if (!frame.dataset.playing) load(frame, true); else if (frame._pausedByUs) { frame._pausedByUs = false; post(frame, 'playVideo'); } },
      () => { if (frame.dataset.playing) { frame._pausedByUs = true; post(frame, 'pauseVideo'); } });
    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.
  // A miss is not final: a relay that was down when we asked (ours was, for
  // an evening) answered nothing, and the note sat "not on your relays"
  // until a reload. A missing note is asked for again the next time it is
  // wanted, half a minute on, with any relay hints the reference carried.
  const QUOTE_RETRY_MS = 30_000;
  const ARTICLE = 30023; // NIP-23 long-form
  const quoted = new Map(); // id -> { status, ev, at }
  // Where a referenced note may be: the reference's hints, its author's own
  // relays, ours — and when none of those has it, a wider net of big public
  // relays (a quoted note in the wild sat only on nostr.mom, which neither
  // the reference nor its author's relay list named).
  // (the archive-keeping ones hold what the big relays have pruned — a poll
  // two days old was only on ditto and nostrplebs by 2026-09-30)
  const WIDE_RELAYS = ['wss://nostr.mom', 'wss://relay.ditto.pub', 'wss://relay.nostrplebs.com', 'wss://nostr21.com',
    'wss://nostr.wine', 'wss://relay.snort.social', 'wss://offchain.pub', 'wss://nostr.oxtr.dev',
    'wss://relay.damus.io', 'wss://nos.lol', 'wss://relay.primal.net'];
  // Lookups wait 150 ms and go out together: one REQ per relay carrying
  // every id wanted there, not one per quoted note (a scrolled feed sent a
  // dozen relays a fresh REQ for each quote it met).
  const findQ = new Map(); // relay -> Map(id -> waiters)
  let findTimer = null;
  function askNote(relays, id, hints = []) {
    // (a relay the reference itself names is asked even when this device has
    // marked it sick: it's the strongest clue there is to where the note lives)
    relays = [...new Set([...readRelayList(relays), ...hints.filter((r) => /^wss:\/\/[^\s]+$/.test(r || '')).map(normRelay)])];
    if (!relays.length) return Promise.resolve(null);
    return new Promise((resolve) => {
      const w = { left: relays.length, resolve, done: false };
      for (const r of relays) {
        let q = findQ.get(r);
        if (!q) findQ.set(r, (q = new Map()));
        if (!q.has(id)) q.set(id, []);
        q.get(id).push(w);
      }
      if (!findTimer) findTimer = setTimeout(flushFind, 150);
    });
  }
  function flushFind() {
    findTimer = null;
    const batch = [...findQ]; findQ.clear();
    for (const [relay, wanted] of batch) {
      const ids = [...wanted.keys()];
      for (let i = 0; i < ids.length; i += 100) {
        const slice = ids.slice(i, i + 100);
        queryOn([relay], { ids: slice }, 4500).catch(() => []).then((evs) => {
          const got = new Map(evs.map((e) => [e.id, e]));
          for (const id of slice) for (const w of wanted.get(id)) {
            if (w.done) continue;
            const ev = got.get(id);
            if (ev) { w.done = true; w.resolve(ev); }
            else if (--w.left === 0) { w.done = true; w.resolve(null); }
          }
        });
      }
    }
  }
  // All at once, first answer wins: asked in turn, a note on a far relay
  // took longer than the feed waits for a row.
  function findNote(ref) {
    const ask = (relays) => askNote(relays, ref.id);
    const near = [...new Set([...(ref.relays || []), ...zapRelays()])];
    const authors = [...new Set([ref.author, ...(ref.authors || [])].filter(Boolean))];
    const asks = [
      askNote(near, ref.id, ref.relays || []),
      ...authors.map((a) => relaysOf(a).catch(() => []).then((rs) => ask(rs.filter((r) => !near.includes(r))))),
      ask(WIDE_RELAYS.filter((r) => !near.includes(r))),
    ];
    return new Promise((resolve) => {
      let left = asks.length;
      for (const a of asks) a.then((ev) => { if (ev) resolve(ev); else if (--left === 0) resolve(null); });
    });
  }
  function quotedNote(ref) {
    let c = quoted.get(ref.id);
    if (c && (c.status !== 'missing' || Date.now() - (c.at || 0) < QUOTE_RETRY_MS)) return c;
    if (!c) {
      const have = noteInHand(ref.id);
      if (have) { c = { status: 'ready', ev: have, at: Date.now(), promise: Promise.resolve() }; quoted.set(ref.id, c); return c; }
      c = { status: 'loading', ev: null, at: 0 }; quoted.set(ref.id, c);
    }
    c.at = Date.now();
    c.promise = (async () => {
      c.ev = (await findNote(ref).catch(() => null)) || c.ev || null;
      c.status = c.ev ? 'ready' : 'missing';
      if (c.ev) cacheNotifNotes([c.ev]);
      // the open thread quotes it: keep it with the thread for the next reload
      const th = c.ev && ui.noteThread && threadCache.get(ui.noteThread.rootId);
      if (th && th.root) persistThread(th);
      scheduleRepaint();
    })();
    return c;
  }

  // A feed row that froze before its quote arrived showed a link — and
  // nothing asked for the note again. Keep asking, and once the note and its
  // own faces/pictures are in, the row takes the card.
  function quoteWarm(ref) {
    const c = quotedNote(ref);
    if (c.ev && !c.warm && !c.warming) {
      c.warming = noteReady(c.ev, Date.now() + READY_MS, 1).catch(() => {})
        .then(() => { c.warm = true; c.warming = null; 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) {
    if (feedPaint && !feedPaint.quotes.has(ref.id)) feedPaint.quotes.set(ref.id, { ...quoted.get(ref.id) });
    let c = feedPaint ? feedPaint.quotes.get(ref.id) : quotedNote(ref);
    if (feedPaint && !c?.ev) {
      const live = quoteWarm(ref);
      // not (yet) found: the card says so where the quote will be — never a
      // bare "view note" link that only leads to the same answer
      if (!(live.ev && live.warm)) return h('div', { class: 'quote-card' },
        h('span', { class: 'small faint' }, t(live.status === 'missing' ? 'noteRefNotFound' : 'noteRefLoading')));
      c = { ...live };
      feedPaint.quotes.set(ref.id, c);
    }
    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;
    if (hidden(ev)) return h('div', { class: 'quote-card' }, h('span', { class: 'small faint' }, t('quoteHidden')));
    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(shownTranslation(ev)?.text ?? noteText(ev), depth + 1, noteEmojiTags(ev))),
      ev.kind === POLL ? pollBox(ev, { interactive: false }) : null);
  }

  // A nostr:naddr: a replaceable thing by its address (kind:author:d) — an
  // article, a list. Its newest copy, from the hint relays, the author's,
  // ours, and the wide net at once; the newest answer within the wait wins.
  const addrKey = (ref) => 'a:' + ref.kind + ':' + ref.pk + ':' + ref.d;
  async function findAddr(ref) {
    const filter = { kinds: [ref.kind], authors: [ref.pk], '#d': [ref.d] };
    const near = [...new Set([...(ref.relays || []), ...zapRelays()])];
    const theirs = await Promise.resolve(relaysOf(ref.pk)).catch(() => []);
    const relays = [...new Set([...near, ...(theirs || []), ...WIDE_RELAYS])];
    const evs = await queryOn(relays, filter, 4500).catch(() => []);
    return (evs || []).filter((e) => e.kind === ref.kind && e.pubkey === ref.pk)
      .sort((a, b) => b.created_at - a.created_at)[0] || null;
  }
  function addrNote(ref) {
    const key = addrKey(ref);
    let c = quoted.get(key);
    if (c && (c.status !== 'missing' || Date.now() - (c.at || 0) < QUOTE_RETRY_MS)) return c;
    if (!c) { c = { status: 'loading', ev: null, at: 0 }; quoted.set(key, c); }
    c.at = Date.now();
    profileOf(ref.pk);
    findAddr(ref).catch(() => null).then((ev) => {
      c.ev = ev || c.ev || null;
      c.status = c.ev ? 'ready' : 'missing';
      scheduleRepaint();
    });
    return c;
  }
  const tagStr = (ev, k) => (ev.tags.find((x) => x[0] === k) || [])[1] || '';
  // The card for it. An article shows its cover, title and summary and opens
  // to read; a list or pack opens as a feed; anything else says what it is.
  function addrCard(ref) {
    const key = addrKey(ref);
    let c = feedPaint ? feedPaint.quotes.get(key) : null;
    if (!c?.ev) {
      c = addrNote(ref);
      if (feedPaint && c.ev) feedPaint.quotes.set(key, { ...c });
    }
    const isList = ref.kind === LIST_KIND || ref.kind === PACK_KIND;
    if (c.ev && ref.kind === LIVE_KIND && !hiddenPk(liveHost(c.ev))) return liveCard(c.ev);
    if (!c.ev && isList) {
      // a list needs nothing fetched to open: the feed resolves its members
      return h('div', { class: 'quote-card clickable', onClick: (e) => { e.stopPropagation(); openListFeed({ pk: ref.pk, d: ref.d, kind: ref.kind, title: '' }); } },
        h('span', { class: 'quote-name' }, '\u{1F465} ' + t('addrList', { name: displayName(ref.pk) })));
    }
    if (!c.ev) return h('div', { class: 'quote-card' + (c.status === 'loading' ? ' quote-loading' : '') },
      c.status === 'loading' ? h('span', { class: 'spinner sm' }) : null,
      h('span', { class: 'small faint' }, t(c.status === 'loading' ? 'addrLoading' : 'addrNotFound')));
    const ev = c.ev;
    if (hidden(ev)) return h('div', { class: 'quote-card' }, h('span', { class: 'small faint' }, t('quoteHidden')));
    const title = tagStr(ev, 'title') || tagStr(ev, 'name');
    const byline = 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((+tagStr(ev, 'published_at') || ev.created_at) * 1000)));
    if (isList) {
      const n = ev.tags.filter((x) => x[0] === 'p').length;
      return h('div', { class: 'quote-card clickable', onClick: (e) => { e.stopPropagation(); openListFeed({ pk: ref.pk, d: ref.d, kind: ref.kind, title }); } },
        byline, h('div', { class: 'addr-title' }, '\u{1F465} ' + (title || ref.d)),
        n ? h('span', { class: 'small muted' }, t('feedPackMembers', { n })) : null);
    }
    if (ref.kind === ARTICLE) return articleCard(ev);
    const alt = tagStr(ev, 'alt');
    return h('div', { class: 'quote-card' }, byline,
      h('div', { class: 'small muted' }, title || alt || t('noteForeignKind', { kind: ev.kind })));
  }
  // An article as a card: its cover, title and summary; a tap opens it to read.
  // Its cover: the image tag, else the first pictures in its body. Covers
  // die (a Blossom host drops the file and no other server has it): a dead
  // one is remembered for the session and the next candidate takes its
  // place, or the card goes without — never a grey box with a broken icon.
  const deadCovers = new Set();
  function articleCover(ev) {
    const cands = [tagStr(ev, 'image').trim(), ...noteMediaUrls(ev.content).slice(0, 3)];
    return cands.find((u) => /^https:\/\/\S+$/.test(u) && !deadCovers.has(u)) || null;
  }
  function articleCard(ev) {
    const img = articleCover(ev);
    const summary = tagStr(ev, 'summary');
    return h('div', { class: 'quote-card clickable addr-article', onClick: (e) => { e.stopPropagation(); openNoteThread(ev); } },
      img ? h('img', {
        class: 'addr-cover', src: img, alt: '', loading: 'lazy', 'data-key': 'cover:' + img,
        onError: (e) => { deadCovers.add(img); e.target.style.display = 'none'; scheduleRepaint(); },
      }) : null,
      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((+tagStr(ev, 'published_at') || ev.created_at) * 1000))),
      h('div', { class: 'addr-title' }, tagStr(ev, 'title') || t('addrArticle')),
      summary ? h('div', { class: 'small muted addr-summary' }, summary) : null,
      h('span', { class: 'small faint' }, t('addrRead', { min: Math.max(1, Math.round(ev.content.split(/\s+/).length / 230)) })));
  }
  // An article's body: its markdown headings as headings, the rest as any post.
  function articleBody(ev) {
    const out = [];
    const title = tagStr(ev, 'title');
    let text = ev.content;
    // most clients repeat the title as the first heading
    if (title) text = text.replace(new RegExp('^\\s*#\\s+' + title.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '\\s*\n'), '');
    if (title) out.push(h('div', { class: 'article-title' }, title));
    const em = emojiTagMap(ev.tags);
    for (const chunk of text.split(/^(#{1,6} .*)$/m)) {
      const hd = /^(#{1,6}) (.*)$/.exec(chunk);
      if (hd) out.push(h('div', { class: 'article-h' + Math.min(hd[1].length, 3) }, hd[2].trim()));
      else if (chunk.trim()) out.push(...noteBody(chunk.replace(/^\n+|\n+$/g, ''), 0, em));
    }
    return out;
  }

  // ---- live streams (NIP-53) -----------------------------------------------
  // What's on now, newest copy of each stream by its address: asked of the
  // relays streams are announced on every couple of minutes while a feed or
  // profile wants it. A feed shows the ones its people are in (Following:
  // your follows; Everything and Popular: all of them) in a row above its
  // posts; a profile says when its person is on; a post linking a stream
  // shows it as a card. Any of them opens the stream's own screen.
  const liveSeen = new Map(); // addr -> newest 30311
  let liveAt = 0, liveAsking = null;
  const liveAskedOf = new Map(); // pk -> when their own streams were asked for
  function takeLive(evs) {
    let changed = false;
    for (const [a, ev] of newestByAddr(evs)) {
      const cur = liveSeen.get(a);
      if (!cur || cur.created_at < ev.created_at) { liveSeen.set(a, ev); changed = true; }
    }
    if (changed) liveHostsAt = 0;
    return changed;
  }
  // who is on now (host -> their stream), for the rings round faces: worked
  // out again when a stream changes and every half minute (one goes stale)
  let liveHostsAt = 0, liveHosts = new Map();
  // Our own live server knows better than an announcement: a stream it
  // carries that it says is over (or taken down) is over, whatever its last
  // 30311 claims — an app closed mid-stream never says `ended`, and the
  // announcement reads live for an hour. Asked at most every 20 s a stream.
  const OUR_LIVE = /^(https:\/\/v3\.coinos\.io|http:\/\/(localhost|127\.0\.0\.1)(:\d+)?)\/live\/[0-9a-f]{16}\/live\.m3u8$/;
  const liveServerSays = new Map(); // stats url -> { state, seconds, at, asking }
  function liveServerState(ev) {
    const url = liveStream(ev) || '';
    if (!OUR_LIVE.test(url)) return null;
    const u = url.replace(/live\.m3u8$/, 'stats');
    let k = liveServerSays.get(u);
    if (!k) liveServerSays.set(u, k = { state: null, at: 0, asking: false });
    if (!k.asking && Date.now() - k.at > 20_000) {
      k.asking = true;
      fetch(u, { cache: 'no-store' })
        .then((r) => (r.status === 404 ? { state: 'ended' } : r.json()))
        .then((j) => { const was = k.state; k.state = j.state || null; k.seconds = j.seconds; if (was !== k.state) { liveHostsAt = 0; scheduleRepaint(); } })
        .catch(() => {}).finally(() => { k.asking = false; k.at = Date.now(); });
    }
    return k.state;
  }
  // taken down by an admin, or deleted by its streamer: nothing to play
  const serverGone = (ev) => { const st = liveServerState(ev); return st === 'removed' || st === 'deleted'; };
  const serverOver = (ev) => liveServerState(ev) === 'ended' || serverGone(ev);
  const liveStatus = (ev, now) => { const st = announcedStatus(ev, now); return st === 'live' && serverOver(ev) ? 'ended' : st; };
  const isLiveNow = (ev, now) => isLiveAnnounced(ev, now) && !serverOver(ev);
  // Your own stream announced live that this tab isn't sending (the app was
  // closed, reloaded, or lost it): end the announcement, its recording kept.
  async function endAnnounced(ev) {
    if (!confirm(t('goLiveEndAsk'))) return;
    try {
      const id = await requireIdentity();
      if (id.pubkey !== ev.pubkey) { toast(t('liveNotYours')); return; }
      const now = Math.floor(Date.now() / 1000);
      const tags = ev.tags.filter((x) => !['status', 'current_participants', 'ends', 'recording', 'client'].includes(x[0]))
        .concat([['status', 'ended'], ['ends', String(now)], CLIENT_TAG]);
      const k = liveServerSays.get((liveStream(ev) || '').replace(/live\.m3u8$/, 'stats'));
      if (OUR_LIVE.test(liveStream(ev)) && k && k.state !== 'removed' && k.state !== 'deleted' && (k.seconds || 0) >= 6) tags.push(['recording', liveStream(ev).replace(/live\.m3u8$/, 'index.m3u8')]);
      const partial = { kind: LIVE_KIND, content: ev.content || '', created_at: Math.max(now, ev.created_at + 1), tags };
      const evt = id.signer instanceof Uint8Array ? finalizeEvent(partial, id.signer) : await id.signer.signEvent(partial);
      takeLive([evt]);
      liveHostsAt = 0;
      render();
      await publishOn([...new Set([...LIVE_RELAYS, ...liveRelays(ev), ...wallet.nostrRelays()])], evt);
    } catch (e) { toast(e.message || String(e)); }
  }
  // ---- moderation: a viewer reports a stream we carry; an admin takes it
  // down (the server ends it and keeps it from everyone, for reporting)
  const LIVE_ADMIN = '98ae4da926c471c23fd12d1ebdd5839ba82917baa618e184e0c9916d93dcf4f7';
  const ourStreamId = (ev) => { const m = OUR_LIVE.test(liveStream(ev) || '') && /\/live\/([0-9a-f]{16})\/live\.m3u8$/.exec(liveStream(ev)); return m ? m[1] : null; };
  async function livePost(path, body) {
    const auth = await signAsMe({ kind: 27235, created_at: Math.floor(Date.now() / 1000), content: '', tags: [['u', APP_BASE + path], ['method', 'POST']] });
    const r = await fetch(liveBase() + path, { method: 'POST', headers: { authorization: 'Nostr ' + btoa(JSON.stringify(auth)), 'content-type': 'application/json' }, body: JSON.stringify(body || {}), signal: AbortSignal.timeout(10000) });
    const j = await r.json().catch(() => ({}));
    if (!r.ok) throw new Error(j.error || 'HTTP ' + r.status);
    return j;
  }
  const REPORT_REASONS = ['csam', 'sexual', 'violence', 'illegal', 'spam', 'other'];
  async function sendLiveReport(ev) {
    const r = ui.liveReport;
    if (!r || !r.reason) return;
    r.busy = true; render();
    try {
      await livePost('/live/' + ourStreamId(ev) + '/report', { reason: r.reason, text: (r.text || '').trim() });
      ui.liveReport = null;
      toast(t('liveReported'));
    } catch (e) { r.busy = false; toast(e.message || String(e)); }
    render();
  }
  function liveReportPanel(ev) {
    const r = ui.liveReport;
    return h('div', { class: 'card col live-report', style: 'gap:8px', 'data-key': 'live-report' },
      h('strong', {}, t('liveReportTitle')),
      h('div', { class: 'small muted' }, t('liveReportDesc')),
      ...REPORT_REASONS.map((x) => h('label', { class: 'row gap6', style: 'align-items:center' },
        h('input', { type: 'radio', name: 'live-report-reason', value: x, checked: r.reason === x, onChange: () => { r.reason = x; render(); } }),
        h('span', {}, t('liveReason_' + x)))),
      h('textarea', { class: 'live-report-text', rows: '2', maxlength: '500', placeholder: t('liveReportTextPh'), value: r.text || '', onInput: (e) => { r.text = e.target.value; } }),
      h('div', { class: 'row gap6' },
        h('button', { class: 'btn-primary btn-sm live-report-send', disabled: !r.reason || !!r.busy, onClick: () => sendLiveReport(ev) }, r.busy ? h('span', { class: 'spinner sm' }) : t('liveReportSend')),
        h('button', { class: 'btn-sm', onClick: () => { ui.liveReport = null; render(); } }, t('cancel'))));
  }
  async function takeDown(ev) {
    if (!confirm(t('liveTakeDownAsk'))) return;
    const ban = confirm(t('liveBanAsk'));
    try {
      await livePost('/live/' + ourStreamId(ev) + '/remove', { ban });
      const k = liveServerSays.get(liveStream(ev).replace(/live\.m3u8$/, 'stats'));
      if (k) { k.state = 'removed'; k.at = Date.now(); }
      toast(t(ban ? 'liveTakenDownBanned' : 'liveTakenDown'));
      render();
    } catch (e) { toast(e.message || String(e)); }
  }
  // Your own stream's recording, deleted: the server lets its files go, and the
  // announcement is said again without it (other apps drop the link too).
  async function deleteRecording(ev) {
    if (!confirm(t('liveDeleteAsk'))) return;
    try {
      const id = await requireIdentity();
      if (id.pubkey !== ev.pubkey) { toast(t('liveNotYours')); return; }
      await livePost('/live/' + ourStreamId(ev) + '/delete', {});
      const k = liveServerSays.get(liveStream(ev).replace(/live\.m3u8$/, 'stats'));
      if (k) { k.state = 'deleted'; k.at = Date.now(); }
      const now = Math.floor(Date.now() / 1000);
      const tags = ev.tags.filter((x) => !['status', 'current_participants', 'recording', 'client'].includes(x[0]))
        .concat([['status', 'ended'], CLIENT_TAG]);
      if (!tags.some((x) => x[0] === 'ends')) tags.push(['ends', String(now)]);
      const evt = await signAsMe({ kind: LIVE_KIND, content: ev.content || '', created_at: Math.max(now, ev.created_at + 1), tags });
      takeLive([evt]);
      liveHostsAt = 0;
      publishOn([...new Set([...liveRelays(ev), ...LIVE_RELAYS, ...wallet.nostrRelays()])], evt).catch(() => {});
      toast(t('liveDeleted'));
      render();
    } catch (e) { if (!(e instanceof NoIdentity)) toast(e.message || String(e)); }
  }
  function liveHostNow(pk) {
    if (!liveSeen.size) return null;
    if (Date.now() - liveHostsAt > 30_000) {
      liveHostsAt = Date.now();
      const now = Date.now() / 1000;
      liveHosts = new Map();
      for (const ev of liveSeen.values()) {
        if (!isLiveNow(ev, now) || !liveShowable(ev)) continue;
        const h = liveHost(ev), cur = liveHosts.get(h);
        if (!cur || cur.created_at < ev.created_at) liveHosts.set(h, ev);
      }
    }
    return liveHosts.get(pk) || null;
  }
  const liveSince = () => Math.floor(Date.now() / 1000) - 6 * 3600;
  function refreshLive() {
    if (liveAsking || Date.now() - liveAt < 120_000) return;
    liveAt = Date.now();
    liveAsking = queryOn(LIVE_RELAYS, { kinds: [LIVE_KIND], since: liveSince(), limit: 300 }, 4000)
      .then((evs) => { if (takeLive(evs)) scheduleRepaint(); })
      .catch(() => {}).finally(() => { liveAsking = null; });
  }
  // the streams someone is in, asked of their own relays as well (a
  // streamer's on a relay we don't otherwise read)
  function askLiveOf(pk) {
    if (Date.now() - (liveAskedOf.get(pk) || 0) < 120_000) return;
    liveAskedOf.set(pk, Date.now());
    Promise.resolve(relaysOf(pk)).catch(() => []).then((theirs) => {
      const relays = [...new Set([...LIVE_RELAYS, ...(theirs || []).slice(0, 4)])];
      return Promise.all([
        queryOn(relays, { kinds: [LIVE_KIND], '#p': [pk], since: pastSince(), limit: 30 }, 4000),
        queryOn(relays, { kinds: [LIVE_KIND], authors: [pk], since: pastSince(), limit: 30 }, 4000),
      ]);
    }).then(([a, b]) => { if (takeLive([...a, ...b])) scheduleRepaint(); }).catch(() => {});
  }
  // Past streams: ended ones that left a recording, the last month of them.
  // A feed asks for its people's (all of them for Everything), a profile for
  // its person's; opening one plays the recording (livePlayable).
  const PAST_DAYS = 30;
  const pastSince = () => Math.floor(Date.now() / 1000) - PAST_DAYS * 86400;
  const pastAsked = new Map(); // what was asked -> when
  let pastAsking = 0;
  function askPast(key, filters) {
    if (Date.now() - (pastAsked.get(key) || 0) < 300_000) return;
    pastAsked.set(key, Date.now());
    pastAsking++;
    Promise.all(filters.map((f) => queryOn(LIVE_RELAYS, { kinds: [LIVE_KIND], since: pastSince(), ...f }, 5000).catch(() => [])))
      .then((rs) => { if (takeLive(rs.flat())) scheduleRepaint(); })
      .finally(() => { pastAsking--; scheduleRepaint(); });
  }
  const isPast = (ev) => liveStatus(ev) === 'ended' && !!liveRecording(ev) && !serverGone(ev);
  const liveEndedAt = (ev) => +(ev.tags.find((x) => x[0] === 'ends') || [])[1] || ev.created_at;
  const pastPeople = (def) => {
    const fol = followsNow().set;
    const people = def.all ? null : [...new Set([...feedAuthors(def), ...(def.follows ? fol : [])])];
    return people && people.slice(0, 400);
  };
  const pastFilters = (ps, limit) => (ps ? [{ authors: ps, limit }, { '#p': ps, limit }] : [{ limit }]);
  function pastForFeed(def) {
    const ps = pastPeople(def);
    if (ps && !ps.length) return [];
    askPast('feed:' + def.id, pastFilters(ps, ps ? 200 : 300));
    const set = ps && new Set(ps);
    return [...liveSeen.values()]
      .filter((ev) => isPast(ev) && liveShowable(ev) && !liveNsfw(ev) && (!set || set.has(liveHost(ev)) || set.has(ev.pubkey)))
      .sort((a, b) => liveEndedAt(b) - liveEndedAt(a));
  }
  const pastOf = (pk) => [...liveSeen.values()].filter((ev) => liveHost(ev) === pk && isPast(ev) && liveShowable(ev))
    .sort((a, b) => liveEndedAt(b) - liveEndedAt(a));
  const liveNsfw = (ev) => ev.tags.some((x) => x[0] === 'content-warning' || (x[0] === 't' && /^nsfw$/i.test(x[1] || '')));
  const liveShowable = (ev) => !hiddenPk(liveHost(ev)) && !hiddenPk(ev.pubkey);
  function liveNowOf(pk) {
    const now = Date.now() / 1000;
    return [...liveSeen.values()].filter((ev) => liveHost(ev) === pk && isLiveNow(ev, now) && liveShowable(ev))
      .sort((a, b) => b.created_at - a.created_at)[0] || null;
  }
  function liveForFeed(def) {
    const now = Date.now() / 1000;
    const fol = followsNow().set;
    const people = def.all ? null : new Set([...feedAuthors(def), ...(def.follows ? fol : [])]);
    if (people && !people.size) return [];
    return [...liveSeen.values()]
      .filter((ev) => isLiveNow(ev, now) && liveShowable(ev) && !liveNsfw(ev) && (!people || people.has(liveHost(ev)) || people.has(ev.pubkey)))
      .sort((a, b) => (fol.has(liveHost(b)) - fol.has(liveHost(a))) || ((liveViewers(b) || 0) - (liveViewers(a) || 0)));
  }
  const liveCoverStyle = (ev) => { const img = liveImage(ev); return img ? 'background-image:url(' + JSON.stringify(img) + ')' : undefined; };
  function liveBadge(ev) {
    const s = liveStatus(ev);
    return h('span', { class: 'live-badge ' + s }, t(s === 'live' ? 'liveBadge' : s === 'planned' ? 'livePlanned' : 'liveEnded'));
  }
  // Past streams scroll on: more tiles as the grid's foot comes near, and
  // once those we hold run out, older ones from the relays (before the oldest
  // asked so far) until a page brings nothing back.
  const PAST_STEP = 24;
  const pastPages = new Map(); // feed id -> { shown, until, end, busy }
  const pastPage = (def) => { let p = pastPages.get(def.id); if (!p) pastPages.set(def.id, p = { shown: PAST_STEP, until: null, end: false, busy: false }); return p; };
  function morePast() {
    if (mediaMode !== 'live' || !ui.chatOpen || ui.msgView !== 'feed' || ui.profilePk || ui.noteThread || ui.liveStream) return;
    const g = document.querySelector('.live-past') || document.querySelector('[data-key="live-past-wait"]');
    if (!g || g.getBoundingClientRect().bottom > window.innerHeight * 2) return;
    const def = feedDef(), p = pastPage(def), all = pastForFeed(def);
    if (p.shown < all.length) { p.shown += PAST_STEP; scheduleRepaint(); return; }
    if (p.end || p.busy || pastAsking) return;
    const ps = pastPeople(def);
    if (ps && !ps.length) { p.end = true; return; }
    // older than the oldest we hold (the first ask's page may stop short of its month)
    if (p.until == null) p.until = Math.min(Math.floor(Date.now() / 1000), ...all.map((e) => e.created_at));
    p.busy = true;
    scheduleRepaint();
    Promise.all(pastFilters(ps, 100).map((f) => queryOn(LIVE_RELAYS, { kinds: [LIVE_KIND], until: p.until - 1, ...f }, 5000).catch(() => [])))
      .then((rs) => {
        const evs = rs.flat();
        if (!evs.length) { p.end = true; return; }
        p.until = Math.min(...evs.map((e) => e.created_at));
        takeLive(evs);
        p.shown += PAST_STEP;
      })
      .finally(() => { p.busy = false; scheduleRepaint(); setTimeout(morePast, 300); }); // still short of the screen: on
  }
  let pastScrollQueued = false;
  if (typeof document !== 'undefined') document.addEventListener('scroll', () => {
    if (pastScrollQueued || mediaMode !== 'live') return;
    pastScrollQueued = true;
    requestAnimationFrame(() => { pastScrollQueued = false; morePast(); });
  }, { capture: true, passive: true });
  // the feed's Live chip: its streams on now, as a grid of tiles
  function liveGrid(def) {
    const evs = liveForFeed(def).slice(0, 60);
    const pp = pastPage(def);
    const past = pastForFeed(def).slice(0, pp.shown);
    setTimeout(morePast, 0); // a short grid fills the screen without a scroll
    return h('div', { class: 'col', style: 'gap:12px', 'data-key': 'live-view' },
      evs.length ? h('div', { class: 'live-grid', 'data-key': 'live-grid' }, ...evs.map(liveTile))
      : liveAsking ? h('div', { class: 'row gap6', 'data-key': 'live-empty', style: 'justify-content:center;padding:12px 0' }, h('span', { class: 'spinner sm' }))
      : h('div', { class: 'small faint', 'data-key': 'live-empty', style: 'text-align:center;padding:12px 0' }, t('mediaNoLive')),
      past.length ? h('h4', { class: 'live-past-title', 'data-key': 'live-past-title' }, t('livePast')) : null,
      past.length ? h('div', { class: 'live-grid live-past', 'data-key': 'live-past' }, ...past.map(liveTile)) : null,
      pastAsking || pp.busy ? h('div', { class: 'row gap6', 'data-key': 'live-past-wait', style: 'justify-content:center;padding:8px 0' }, h('span', { class: 'spinner sm' })) : null);
  }
  // a stream's tile: on now (how many watch) or past (when it ended)
  function liveTile(ev) {
    const host = liveHost(ev), n = liveViewers(ev), now = isLiveNow(ev);
    return h('button', { type: 'button', class: 'live-tile', 'data-key': 'live:' + liveAddr(ev), onClick: (e) => { e.stopPropagation(); openLive(ev); } },
      h('div', { class: 'live-cover', style: liveCoverStyle(ev) },
        now ? liveBadge(ev) : h('span', { class: 'live-badge' }, t('liveRecordingBadge')),
        now ? (n != null ? h('span', { class: 'live-viewers' }, t('liveWatching', { n })) : null)
          : h('span', { class: 'live-viewers' }, timeLabel(liveEndedAt(ev) * 1000))),
      h('div', { class: 'live-tile-title' }, liveTitle(ev) || t('liveUntitled')),
      h('div', { class: 'row gap6 live-tile-host' }, avatar(host, 'chat-avatar mini', false), h('span', { class: 'small muted' }, displayName(host))));
  }
  // a profile's Streams tab: their past streams, as the Live chip's tiles
  function pastStreams(pk) {
    return h('div', { class: 'live-grid live-past', 'data-key': 'live-past-of:' + pk }, ...pastOf(pk).slice(0, 60).map(liveTile));
  }
  // a profile's "on now" line
  function liveBanner(pk) {
    askLiveOf(pk);
    const ev = liveNowOf(pk);
    if (!ev) {
      // yours, still announced live, but nothing's going out: say so, and End it
      const stale = pk === mePk() && !(bc && bc.phase === 'live') && [...liveSeen.values()]
        .find((x) => x.pubkey === pk && liveHost(x) === pk && isLiveAnnounced(x) && serverOver(x));
      return stale ? h('div', { class: 'live-banner', 'data-key': 'live-stale:' + liveAddr(stale) },
        h('span', { class: 'live-banner-title' }, t('liveStaleMine', { title: liveTitle(stale) || t('liveUntitled') })),
        h('button', { class: 'btn-sm live-end-stale', onClick: () => endAnnounced(stale) }, t('goLiveEnd'))) : null;
    }
    return h('button', { type: 'button', class: 'live-banner', 'data-key': 'live-banner:' + liveAddr(ev), onClick: () => openLive(ev) },
      h('span', { class: 'live-badge live' }, t('liveBadge')),
      h('span', { class: 'live-banner-title' }, liveTitle(ev) || t('liveUntitled')),
      h('span', { class: 'small muted' }, t('liveWatch')));
  }
  // a post linking a stream (nostr:naddr of a 30311)
  function liveCard(ev) {
    const host = liveHost(ev);
    return h('div', { class: 'quote-card clickable live-card', onClick: (e) => { e.stopPropagation(); openLive(ev); } },
      h('div', { class: 'live-cover', style: liveCoverStyle(ev) }, liveBadge(ev)),
      h('div', { class: 'col', style: 'gap:4px;min-width:0' },
        h('div', { class: 'addr-title' }, liveTitle(ev) || t('liveUntitled')),
        h('div', { class: 'row gap6', style: 'align-items:center;min-width:0' },
          avatar(host, 'chat-avatar mini', false), h('span', { class: 'quote-name' }, displayName(host)))));
  }

  function openLive(ev) {
    rememberPlace('live');
    const a = liveAddr(ev);
    takeLive([ev]);
    setZapAddr(ev.id, a);
    ui.liveStream = { a, seed: ev };
    ui.noteThread = null; ui.profilePk = null; ui.profOverThread = false; ui.userSearch = null;
    render();
  }
  // a link to a stream (/naddr1…, nostr:naddr in a post we couldn't show)
  async function openLiveRef(ref) {
    const ev = liveSeen.get(LIVE_KIND + ':' + ref.pk + ':' + ref.d) || await findAddr(ref).catch(() => null);
    if (ev) openLive(ev);
    else toast(t('liveNotFound'));
  }

  // The open stream: its chat (1311) and zaps (9735, and coinos's Ark
  // receipts) as they come, and the stream event itself as it's refreshed
  // (the viewer count, `ended`).
  let liveWatch = null;
  function watchLive(s) {
    if (liveWatch && liveWatch.a === s.a) return liveWatch;
    stopLiveWatch();
    const [, pk, ...rest] = s.a.split(':');
    const d = rest.join(':');
    takeLive([s.seed]);
    const w = liveWatch = { a: s.a, lines: new Map(), stops: [], video: null, hls: null, err: null, actions: new Map(), actionTimer: null, actionStop: null, actionKey: '', sheet: null, reply: null, reacting: new Set() };
    let mine = []; try { mine = wallet.nostrRelays(); } catch {}
    const relays = w.relays = [...new Set([...liveRelays(s.seed), ...mine])];
    const add = (e) => {
      if (liveWatch !== w || w.lines.has(e.id)) return;
      if (e.kind === 7 || e.kind === 5) { takeLiveAction(w, e); return; }
      w.lines.set(e.id, e);
      if (w.lines.size > 200) {
        const oldest = [...w.lines.values()].sort((a, b) => a.created_at - b.created_at)[0];
        w.lines.delete(oldest.id);
      }
      if (e.kind === LIVE_CHAT_KIND) { setZapAddr(e.id, w.a); watchLiveActions(w); }
      else noteReceipt(e);
      scheduleRepaint();
    };
    w.stops.push(subscribeOn(relays, { kinds: [LIVE_CHAT_KIND, 9735, 9737], '#a': [s.a], limit: 200 }, add));
    w.stops.push(subscribeOn(relays, { kinds: [7, 5], '#a': [s.a], limit: 1000 }, e => takeLiveAction(w, e)));
    w.stops.push(subscribeOn(relays, { kinds: [LIVE_KIND], authors: [pk], '#d': [d] }, (e) => { if (takeLive([e])) scheduleRepaint(); }));
    // who's here: NIP-53 presence (kind 10312, the stream in its a tag) —
    // Shosho, zap.stream and others say it, and so do we while it's open
    w.here = new Map(); // pubkey -> when they last said so
    w.stops.push(subscribeOn(relays, { kinds: [PRESENCE_KIND], '#a': [s.a], since: Math.floor(Date.now() / 1000) - PRESENCE_FRESH }, (e) => {
      if (liveWatch !== w || (w.here.get(e.pubkey) || 0) >= e.created_at) return;
      w.here.set(e.pubkey, e.created_at);
      scheduleRepaint();
    }));
    sayHere(w);
    return w;
  }
  // Presence counts for half an hour (some clients say it once, on joining);
  // ours is said again every five minutes while the stream is open, and
  // taken back (an empty one) on leaving. Only with a key held here: a
  // signer app would be asked to sign every five minutes.
  const PRESENCE_KIND = 10312, PRESENCE_FRESH = 1800;
  async function presence(w, here) {
    const id = await identity().catch(() => null);
    if (!id || !(id.signer instanceof Uint8Array) || isVisitor()) return;
    const ev = liveSeen.get(w.a);
    if (here && (!ev || liveHost(ev) === id.pubkey || !isLiveNow(ev))) return; // not for your own, nor one that's over
    const evt = finalizeEvent({ kind: PRESENCE_KIND, created_at: Math.floor(Date.now() / 1000), content: '',
      tags: here ? [['a', w.a, w.relays[0] || '', 'root'], CLIENT_TAG] : [CLIENT_TAG] }, id.signer);
    if (here) { w.here.set(evt.pubkey, evt.created_at); scheduleRepaint(); w.said = true; }
    publishOn(w.relays, evt).catch(() => {});
  }
  function sayHere(w) {
    presence(w, true);
    w.hereTimer = setInterval(() => { if (liveWatch === w) presence(w, true); }, 5 * 60_000);
  }
  // the people known to be watching (fresh presence), newest first
  const watchersOf = (w) => {
    const since = Date.now() / 1000 - PRESENCE_FRESH;
    return w && w.here ? [...w.here].filter(([, at]) => at >= since).sort((a, b) => b[1] - a[1]).map(([pk]) => pk) : [];
  };
  // "4 watching": hover names who (as many as are known), a tap shows their faces
  function watchingLine(w, n, cls = 'small muted') {
    const who = watchersOf(w);
    const names = who.slice(0, 30).map((pk) => displayName(pk)).join(', ') + (who.length > 30 ? '…' : '');
    return h('span', { class: cls + (who.length ? ' live-watching has-who' : ' live-watching'), title: who.length ? names : undefined,
      role: who.length ? 'button' : undefined,
      onClick: who.length ? (e) => { e.stopPropagation(); w.showWho = !w.showWho; render(); } : undefined },
      t('liveWatching', { n: Math.max(n || 0, who.length) }));
  }
  function watchersRow(w) {
    const who = watchersOf(w);
    if (!w || !w.showWho || !who.length) return null;
    return h('div', { class: 'live-who', 'data-key': 'live-who' },
      ...who.slice(0, 60).map((pk) => h('button', { type: 'button', class: 'live-who-p', 'data-key': 'who:' + pk, title: displayName(pk), onClick: () => openProfile(pk) },
        avatar(pk, 'chat-avatar mini', false), h('span', { class: 'small' }, displayName(pk)))));
  }
  // Include reactions/receipts from clients that only tag the comment's e,
  // plus deletions of known reactions. Batch changes into one subscription.
  function watchLiveActions(w) {
    if (w.actionTimer || liveWatch !== w) return;
    w.actionTimer = setTimeout(() => {
      w.actionTimer = null;
      if (liveWatch !== w) return;
      const ids = [...w.lines.values()].filter(e => e.kind === LIVE_CHAT_KIND).map(e => e.id);
      const reactions = [...w.actions.values()].filter(e => e.kind === 7 && ids.includes(e.tags.filter(t => t[0] === 'e').at(-1)?.[1])).slice(-400).map(e => e.id);
      const all = [...ids, ...reactions];
      const key = all.join(',');
      if (key === w.actionKey) return;
      w.actionKey = key;
      if (w.actionStop) w.actionStop();
      w.actionStop = all.length ? subscribeOn(w.relays, { kinds: [7, 5, 9735, 9737], '#e': all, limit: 1000 }, e => takeLiveAction(w, e)) : null;
    }, 1000);
  }
  function takeLiveAction(w, ev) {
    if (liveWatch !== w) return;
    if (ev.kind === 9735 || ev.kind === 9737) { noteReceipt(ev); return; }
    if (w.actions.has(ev.id)) return;
    w.actions.set(ev.id, ev);
    while (w.actions.size > 2000) w.actions.delete(w.actions.keys().next().value);
    noteEmoji(ev);
    watchLiveActions(w);
    scheduleRepaint();
  }
  async function sendLiveReaction(w, ev, emoji) {
    if (w.reacting.has(ev.id)) return;
    w.reacting.add(ev.id);
    try {
      const id = await requireIdentity();
      const current = liveReactions([...w.actions.values()]).get(ev.id)?.get(id.pubkey);
      const old = [...w.actions.values()].filter(e => e.kind === 7 && e.pubkey === id.pubkey && e.tags.filter(t => t[0] === 'e').at(-1)?.[1] === ev.id);
      const sign = partial => id.signer instanceof Uint8Array ? finalizeEvent(partial, id.signer) : id.signer.signEvent(partial);
      const events = [];
      const now = old.reduce((n, e) => Math.max(n, e.created_at + 1), Math.floor(Date.now() / 1000));
      if (old.length) events.push(await sign({ kind: 5, content: '', created_at: now,
        tags: [['a', w.a], ['k', '7'], ...old.map(e => ['e', e.id])] }));
      const currentEmoji = current && (!current.content || current.content === '+' ? '❤️' : current.content);
      if (currentEmoji !== emoji) events.push(await sign({ kind: 7, content: emoji, created_at: now,
        tags: [['a', w.a], ['e', ev.id, w.relays[0] || ''], ['p', ev.pubkey], ['k', String(LIVE_CHAT_KIND)], ...reactEmojiTags(emoji), CLIENT_TAG] }));
      if (liveWatch !== w) return;
      const added = new Set(events.filter(e => !w.actions.has(e.id)).map(e => e.id));
      for (const e of events) takeLiveAction(w, e);
      render();
      const results = await Promise.all(events.map(e => publishOn(w.relays, e).catch(() => false)));
      // what no relay took is taken back off the screen
      results.forEach((ok, i) => { if (!ok && added.has(events[i].id)) w.actions.delete(events[i].id); });
      if (results.some(ok => !ok)) { toast(t('msgSendFailed')); render(); }
    } catch (e) { if (!(e instanceof NoIdentity)) toast(t('msgSendFailed')); }
    finally { w.reacting.delete(ev.id); scheduleRepaint(); }
  }
  function stopLivePlayer(w = liveWatch) {
    if (!w) return;
    if (w.hls) { try { w.hls.destroy(); } catch {} w.hls = null; }
    if (w.pc) { try { w.pc.close(); } catch {} w.pc = null; }
    clearInterval(w.rtcBeat);
    const v = w.video;
    w.video = null;
    if (v) { try { v.pause(); v.srcObject = null; v.removeAttribute('src'); v.load(); } catch {} }
  }
  // A stream of ours as WebRTC: the live server gets Cloudflare's SFU to offer
  // the sender's tracks, we answer. Resolves once connected (rejects after
  // 8 s, or if there's no WebRTC for it); after that, a lost connection or a
  // new publish (the sender reconnected) mounts the player again.
  async function rtcWatch(w, el, src, go) {
    const base = src.replace(/live\.m3u8$/, '');
    const pc = w.pc = new RTCPeerConnection({ iceServers: [{ urls: 'stun:stun.cloudflare.com:3478' }], bundlePolicy: 'max-bundle' });
    const media = new MediaStream();
    pc.ontrack = (e) => {
      media.addTrack(e.track);
      if (w.video === el && el.srcObject !== media) { el.srcObject = media; go(); }
    };
    const r = await fetch(base + 'rtc/watch', { method: 'POST', signal: AbortSignal.timeout(8000) });
    if (!r.ok) throw new Error('watch ' + r.status);
    const j = await r.json();
    if (w.pc !== pc) return;
    await pc.setRemoteDescription({ type: 'offer', sdp: j.sdp });
    await pc.setLocalDescription(await pc.createAnswer());
    const r2 = await fetch(base + 'rtc/answer', { method: 'POST', headers: { 'content-type': 'application/json' },
      body: JSON.stringify({ session: j.session, sdp: pc.localDescription.sdp }), signal: AbortSignal.timeout(8000) });
    if (!r2.ok) throw new Error('answer ' + r2.status);
    await new Promise((resolve, reject) => {
      const t = setTimeout(() => reject(new Error('rtc timeout')), 8000);
      const on = () => {
        if (pc.connectionState === 'connected') { clearTimeout(t); resolve(); }
        else if (pc.connectionState === 'failed' || pc.connectionState === 'closed') { clearTimeout(t); reject(new Error('rtc ' + pc.connectionState)); }
      };
      pc.addEventListener('connectionstatechange', on);
      on();
    });
    if (w.pc !== pc) return;
    w.rtcFails = 0;
    const again = (giveUp) => {
      if (w.pc !== pc || w.video !== el) return;
      if (giveUp || ++w.rtcFails > 3) w.noRtc = true;
      stopLivePlayer(w);
      scheduleRepaint();
    };
    pc.addEventListener('connectionstatechange', () => { if (pc.connectionState === 'failed') again(); });
    // counted as watching (no playlist is asked for), and told of a new publish
    w.rtcBeat = setInterval(() => {
      fetch(base + 'stats?watching=1', { cache: 'no-store' }).then((x) => x.json())
        .then((st) => { if (st.state === 'live' && st.rtc !== j.gen) again(st.rtc == null); }).catch(() => {});
    }, 10_000);
  }
  function stopLiveWatch() {
    const w = liveWatch;
    if (!w) return;
    liveWatch = null;
    clearTimeout(w.actionTimer);
    if (w.actionStop) w.actionStop();
    if (w.sheet) ui.emojiPick = null;
    for (const stop of w.stops) { try { stop(); } catch {} }
    clearInterval(w.hereTimer);
    if (w.said) presence(w, false); // gone
    stopLivePlayer(w);
  }
  // What to play: the stream while it's on, its recording once it's over.
  // A recording is played here only when it's video (HLS, MP4, WebM); some
  // services name a web page instead (zap.stream streams kept on Rumble), and
  // that gets a link out — a player can't play a page.
  const videoFile = (u) => /\.(m3u8|mp4|m4v|webm|mov)(\?|#|$)/i.test(u || '');
  const liveRecordingPage = (ev) => { const u = liveRecording(ev); return u && !videoFile(u) ? u : ''; };
  const livePlayable = (ev) => (serverGone(ev) ? '' : isLiveNow(ev) ? liveStream(ev) : liveStatus(ev) === 'ended' && videoFile(liveRecording(ev)) ? liveRecording(ev) : '');
  // The <video> is the page's own once it plays: Chrome takes the playlist as
  // its src; anywhere without HLS of its own, hls.js feeds it. The morph
  // leaves it alone from then on (it would strip the src hls.js set).
  function mountLivePlayer() {
    const w = liveWatch;
    const el = document.querySelector('video.live-video:not(.bc-preview)');
    if (!w || !el || el === w.video) return;
    stopLivePlayer(w);
    const ev = liveSeen.get(w.a);
    const src = ev && livePlayable(ev);
    if (!src) return;
    w.video = el;
    el._skipMorph = true;
    w.err = null;
    // a stream that drops (the streamer's link, a restart) is tried again
    const fail = () => {
      if (w.video !== el) return;
      stopLivePlayer(w);
      w.err = 'offline';
      scheduleRepaint();
      setTimeout(() => { if (liveWatch === w && w.err === 'offline') { w.err = null; scheduleRepaint(); } }, 10_000);
    };
    el.addEventListener('error', fail);
    el.addEventListener('hlsfatal', fail);
    el.addEventListener('playing', () => { if (w.err) { w.err = null; scheduleRepaint(); } });
    const go = () => el.play().catch(() => { el.muted = true; el.play().catch(() => {}); });
    // A stream that's on plays through hls.js wherever it runs: it keeps the
    // viewer near the live edge (starts 1.5 s back, speeds up when it falls
    // behind). Chrome's own HLS player starts three segments back, never
    // catches up, and fails outright if a page changes its speed. Its player
    // still takes recordings, and live streams where hls.js can't run (iOS).
    // Measured (go-live-test LATENCY=1, one machine): 2 s segments on
    // Chrome's player 8.6 s behind the broadcaster; 1 s segments 4.5 s.
    // Ours, on: WebRTC first (a fraction of a second behind), HLS if it
    // can't be had — no WebRTC for the stream, or no connection in 8 s
    if (src === liveStream(ev) && OUR_LIVE.test(src) && typeof RTCPeerConnection !== 'undefined' && !w.noRtc) {
      rtcWatch(w, el, src, go).catch(() => {
        if (w.video !== el) return;
        w.noRtc = true;
        stopLivePlayer(w);
        scheduleRepaint(); // mounted again, as HLS
      });
      return;
    }
    const live = src === liveStream(ev) && isHls(src) && typeof MediaSource !== 'undefined';
    if (!isHls(src) || (canHls() && !live)) { el.src = src; go(); return; }
    import('../hls-player.js').then((m) => m.attachHls(el, src, { live })).then((hls) => {
      if (w.video !== el) { try { hls && hls.destroy(); } catch {} return; }
      if (!hls) { w.err = 'noplayer'; scheduleRepaint(); return; }
      w.hls = hls; go();
    }).catch(() => { w.err = 'noplayer'; scheduleRepaint(); });
  }
  // after every render: a stream screen gone takes its player and watch with
  // it (a <video> taken out of the page plays on, unheard and unseen)
  let liveShown = false;
  function liveAfterRender() {
    // the camera shown before going live: let go of it once that screen is left
    if (!ui.goLive && bc && bc.phase === 'setup') { bcStopMedia(); bc = null; }
    const pv = document.querySelector('video.bc-preview');
    if (pv && bc && bc.media && pv.srcObject !== bc.media) { pv._skipMorph = true; pv.srcObject = bc.media; pv.play().catch(() => {}); }
    if (!ui.liveStream) { stopLiveWatch(); return; }
    if (!liveShown) { stopLivePlayer(); return; }
    mountLivePlayer();
    const box = document.querySelector('.live-chat');
    if (box && box._stick !== false) box.scrollTop = box.scrollHeight;
  }

  async function sendLiveChat(w, text, reply) {
    const id = await requireIdentity();
    const ev = liveSeen.get(w.a);
    const relays = [...new Set([...liveRelays(ev), ...wallet.nostrRelays()])];
    const partial = { kind: LIVE_CHAT_KIND, content: text, created_at: Math.floor(Date.now() / 1000),
      tags: [['a', w.a, relays[0] || '', 'root'], ...(reply ? [['e', reply.id, relays[0] || '', 'reply'], ['p', reply.pubkey]] : []), ...outboundEmojiTags(text), CLIENT_TAG] };
    const evt = id.signer instanceof Uint8Array ? finalizeEvent(partial, id.signer) : await id.signer.signEvent(partial);
    w.lines.set(evt.id, evt);
    setZapAddr(evt.id, w.a); watchLiveActions(w);
    render();
    if (!(await publishOn(relays, evt))) {
      w.lines.delete(evt.id);
      throw new Error(t('msgSendFailed'));
    }
  }

  function liveMessageSheet(w) {
    const ev = w.lines.get(w.sheet);
    if (!ev || ev.kind !== LIVE_CHAT_KIND) return null;
    const mine = liveReactions([...w.actions.values()]).get(ev.id)?.get(identityPk());
    const close = () => { w.sheet = null; ui.emojiPick = 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' },
        reactRow(mine?.content, emoji => { close(); sendLiveReaction(w, ev, emoji); }),
        ui.emojiPick ? null : item('↩', t('msgReply'), () => { w.reply = ev.id; close(); setTimeout(() => document.getElementById('msg-draft')?.focus(), 50); }),
        !ui.emojiPick && canZapPk(ev.pubkey) && !isMe(ev.pubkey) ? item('⚡', t('msgZap'), () => { close(); zapMessage(ev.pubkey, ev.id); }) : null,
        ui.emojiPick ? null : item('⧉', t('copy'), async () => { try { await navigator.clipboard.writeText(ev.content); toast(t('copied')); } catch {} close(); })));
  }
  function liveLine(ev, w, reactions) {
    if (ev.kind === LIVE_CHAT_KIND) {
      if (hiddenPk(ev.pubkey)) return null;
      const em = noteEmojiTags(ev), mine = isMe(ev.pubkey);
      const counts = new Map();
      for (const r of reactions.get(ev.id)?.values() || []) {
        if (hiddenPk(r.pubkey)) continue;
        const emoji = !r.content || r.content === '+' ? '❤️' : r.content;
        const url = emojiTagMap(r.tags).get(shortcodeOf(emoji)) || null;
        const key = JSON.stringify([emoji, url]);
        const c = counts.get(key) || { emoji, url, n: 0, mine: false };
        c.n++; c.mine ||= isMe(r.pubkey); counts.set(key, c);
      }
      const canZap = canZapPk(ev.pubkey) && !mine;
      const zc = zapChip(ev.id, { cls: 'chat-react', onClick: canZap ? () => zapMessage(ev.pubkey, ev.id) : null, onHold: () => openZapSettings(ev.pubkey, ev.id) });
      const reply = w.lines.get(ev.tags.find(t => t[0] === 'e')?.[1]);
      return keyed(h('div', { class: 'chat-row live-message' + (mine ? ' mine' : '') },
        avatar(ev.pubkey),
        h('div', { class: 'chat-body' },
          h('div', { class: 'chat-meta' },
            h('span', { class: 'chat-name clickable', onClick: () => openProfile(ev.pubkey) }, displayName(ev.pubkey)),
            h('span', { class: 'chat-time' }, timeLabel(ev.created_at * 1000))),
          h('div', { class: 'chat-line' },
            h('div', { class: 'chat-bubble clickable' + (emojiJumbo(ev.content, em) ? ' jumbo' : ''),
              onClick: chatBubbleClick(() => { if (!isVisitor()) { w.sheet = ev.id; ui.emojiPick = null; syncEmoji().catch(() => {}); render(); } }),
            },
              reply && !hiddenPk(reply.pubkey) ? h('div', { class: 'chat-quote' },
                h('span', { class: 'chat-quote-name' }, displayName(reply.pubkey)),
                h('span', { class: 'chat-quote-text' }, reply.content.slice(0, 160))) : null,
              ...noteBody(ev.content, 0, em),
              zc || counts.size ? h('div', { class: 'chat-reacts' }, zc,
                [...counts.values()].map(c => h('button', { type: 'button', class: 'chat-react' + (c.mine ? ' on' : ''), title: t('msgReact'), disabled: isVisitor(),
                  onClick: e => { e.stopPropagation(); sendLiveReaction(w, ev, c.emoji); },
                }, postReactNode(c), c.n > 1 ? ' ' + c.n : ''))) : null),
            msgZapBtn(ev.pubkey, ev.id)))), ev.id);
    }
    const z = zapLine(ev, decodeBolt11);
    if (!z.sats || (z.pk && hiddenPk(z.pk))) return null;
    return keyed(h('div', { class: 'live-line live-zap' },
      z.pk ? avatar(z.pk, 'chat-avatar mini') : h('span', {}, '⚡'),
      h('div', { class: 'live-line-body' },
        h('span', { class: 'quote-name' }, z.pk ? displayName(z.pk) : t('liveSomeone')), ' ',
        h('b', {}, t('liveZapped', { n: z.sats.toLocaleString() })),
        z.text ? h('span', {}, ' ' + z.text.slice(0, 280)) : null)), ev.id);
  }

  function liveScreen() {
    const s = ui.liveStream;
    const w = watchLive(s);
    liveShown = true;
    // your own stream, going out: the camera itself, not the stream seconds behind it
    const mine = !!bc && bc.phase === 'live' && bc.a === s.a;
    if (mine) setTimeout(scheduleRepaint, 1000); // the clock
    const ev = liveSeen.get(s.a) || s.seed;
    const host = liveHost(ev), status = liveStatus(ev), n = liveViewers(ev);
    const src = livePlayable(ev);
    const reactions = liveReactions([...w.actions.values()]);
    const lines = [...w.lines.values()].sort((a, b) => a.created_at - b.created_at).slice(-200).map(e => liveLine(e, w, reactions)).filter(Boolean);
    const draftKey = 'live:' + w.a;
    const reply = w.lines.get(w.reply);
    const say = liveServerState(ev) === 'removed' ? t('liveRemoved') : liveServerState(ev) === 'deleted' ? t('liveDeletedSay') : w.err === 'offline' ? t('liveOffline') : w.err === 'noplayer' ? t('liveNoPlayer')
      : !src ? (status === 'planned' ? t('liveStartsAt', { when: timeLabel(liveStarts(ev) * 1000) }) : t('liveOver')) : null;
    const send = () => {
      const text = draftFor(draftKey).trim();
      if (!text || w.sending) return;
      w.sending = true;
      setDraft(draftKey, '');
      w.reply = null;
      const inp = document.getElementById('msg-draft');
      if (inp) inp.value = '';
      sendLiveChat(w, text, reply).catch(e => {
        setDraft(draftKey, text + (draftFor(draftKey) ? '\n' + draftFor(draftKey) : ''));
        if (!w.reply) w.reply = reply?.id || null;
        if (!(e instanceof NoIdentity)) toast(t('msgSendFailed'));
      }).finally(() => { w.sending = false; render(); });
    };
    return h('div', { class: 'col live-page', style: 'gap:12px' },
      ctx.brandHeader(!ui.pubProf && wallet.loaded),
      h('div', { class: 'card col', style: 'gap:10px' },
        h('div', { class: 'row gap6', style: 'align-items:center' },
          mine ? h('button', { class: 'iconbtn chat-back', onClick: () => { if (confirm(t('goLiveEndAsk'))) endBroadcast(); } }, '‹')
            : backBtn(() => { ui.liveStream = null; }),
          h('h3', { class: 'live-title' }, liveTitle(ev) || t('liveUntitled')),
          // yours, said to be on, but not going out from here: End it
          !mine && ev.pubkey === mePk() && announcedStatus(ev) === 'live'
            ? h('button', { class: 'btn-sm live-end-stale', onClick: () => endAnnounced(ev) }, t('goLiveEnd')) : null,
          liveBadge(ev)),
        mine ? h('div', { class: 'row gap6 bc-bar', style: 'align-items:center' },
          h('span', { class: 'bc-clock' }, clockOf(Date.now() / 1000 - bc.starts)),
          watchingLine(w, bc.viewers || 0),
          bc.reconnecting ? h('span', { class: 'small', style: 'color:var(--red)' }, t('goLiveReconnecting'))
            : bc.behind ? h('span', { class: 'small', style: 'color:var(--red)' }, t('goLiveBehind')) : null,
          // camera ⇄ screen, without stopping the stream
          navigator.mediaDevices?.getDisplayMedia ? h('button', { class: 'btn-sm bc-switch', style: 'margin-left:auto', onClick: () => { bc.source = bc.source === 'screen' ? 'camera' : 'screen'; bcPreview(); } },
            t(bc.source === 'screen' ? 'goLiveToCamera' : 'callShare')) : null,
          h('button', { class: 'btn-sm bc-end', style: navigator.mediaDevices?.getDisplayMedia ? undefined : 'margin-left:auto', onClick: () => { if (confirm(t('goLiveEndAsk'))) endBroadcast(); } }, t('goLiveEnd'))) : null,
        mine ? h('div', { class: 'live-player', 'data-key': 'bc-player:' + s.a },
          h('div', { class: 'live-frame', 'data-key': 'bc-frame:' + (bc.media ? bc.media.id : '') },
            h('video', { class: 'live-video bc-preview' + (bc.source === 'camera' && bc.facing === 'user' ? ' mirror' : ''), muted: '', playsinline: '', autoplay: '' })))
        : h('div', { class: 'live-player', 'data-key': 'live-player:' + s.a },
          // the frame is keyed by what plays in it: the <video> itself is
          // never morphed, so a stream that ends or drops swaps the frame
          src && !w.err
            ? h('div', { class: 'live-frame', 'data-key': 'live-frame:' + src },
                h('video', { class: 'live-video', controls: '', playsinline: '', autoplay: '', poster: liveImage(ev) || undefined }))
            : h('div', { class: 'live-cover live-still', 'data-key': 'live-still', style: liveCoverStyle(ev) },
                h('span', { class: 'live-say' }, say),
                !src && liveRecordingPage(ev) ? h('a', { class: 'btn-sm live-rec-link', href: liveRecordingPage(ev), target: '_blank', rel: 'noopener noreferrer' }, t('liveWatchRecording')) : null)),
        h('div', { class: 'row gap6', style: 'align-items:center;flex-wrap:wrap' },
          avatar(host, 'chat-avatar mini'),
          h('a', { href: '#', class: 'quote-name', onClick: (e) => { e.preventDefault(); openProfile(host); } }, displayName(host)),
          n != null && status === 'live' ? watchingLine(w, n) : null,
          h('span', { style: 'margin-left:auto' }),
          canZapPk(host) ? h('button', { class: 'btn-sm', onClick: (e) => { setZapAddr(ev.id, s.a); zapNote(host, ev, e.currentTarget.getBoundingClientRect()); } }, '⚡ ' + t('liveZap')) : null,
          // ours to answer for: anyone signed in can report it, an admin can take it down
          ourStreamId(ev) && !mine && !isVisitor() && host !== mePk() && !serverGone(ev)
            ? h('button', { class: 'btn-sm live-report-btn', title: t('liveReport'), 'aria-label': t('liveReport'), onClick: () => { ui.liveReport = ui.liveReport ? null : { a: s.a, reason: null, text: '' }; render(); } }, '⚑') : null,
          ourStreamId(ev) && mePk() === LIVE_ADMIN && host !== mePk() && !serverGone(ev)
            ? h('button', { class: 'btn-sm live-takedown', style: 'color:var(--red)', onClick: () => takeDown(ev) }, t('liveTakeDown')) : null,
          // your own, over: its recording is yours to delete
          ourStreamId(ev) && !mine && ev.pubkey === mePk() && status === 'ended' && !serverGone(ev)
            ? h('button', { class: 'btn-sm live-delete', style: 'color:var(--red)', title: t('liveDelete'), 'aria-label': t('liveDelete'), onClick: () => deleteRecording(ev) },
                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="M3 6h18M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6M10 11v6M14 11v6"/></svg>' })) : null,
          h('button', { class: 'btn-sm', title: t('postShare'), 'aria-label': t('postShare'), onClick: async () => {
            const url = location.origin + '/' + packNaddr(s.a);
            try { if (navigator.share) await navigator.share({ url }); else { await navigator.clipboard.writeText(url); toast(t('copied')); } } catch {}
          } }, 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"><circle cx="18" cy="5" r="3"/><circle cx="6" cy="12" r="3"/><circle cx="18" cy="19" r="3"/><path d="m8.6 13.5 6.8 4M15.4 6.5l-6.8 4"/></svg>' }))),
        watchersRow(w),
        liveSummary(ev) ? h('div', { class: 'small muted', style: 'white-space:pre-wrap;overflow-wrap:anywhere' }, liveSummary(ev).slice(0, 600)) : null,
        ui.liveReport && ui.liveReport.a === s.a ? liveReportPanel(ev) : null),
      h('div', { class: 'card col', style: 'gap:8px' },
        h('div', { class: 'small muted' }, t('liveChat')),
        h('div', {
          class: 'live-chat', 'data-key': 'live-chat:' + s.a,
          onScroll: (e) => { const b = e.currentTarget; b._stick = b.scrollHeight - b.scrollTop - b.clientHeight < 40; },
        }, ...(lines.length ? lines : [keyed(h('div', { class: 'small faint' }, t('liveChatEmpty')), 'empty')])),
        reply ? h('div', { class: 'reply-bar' },
          h('div', { class: 'col grow', style: 'min-width:0' },
            h('span', { class: 'small' }, '↩ ', displayName(reply.pubkey)),
            h('span', { class: 'small muted chat-quote-text' }, reply.content.slice(0, 160))),
          h('button', { class: 'btn-ghost', onClick: () => { w.reply = null; render(); } }, '×')) : null,
        isVisitor() ? null : composer(t('liveChatHint'), send, null, draftKey)),
      w.sheet ? liveMessageSheet(w) : null,
      ...noteOverlays());
  }

  // ---- going live -----------------------------------------------------------
  // The camera (or the screen) recorded in half-second chunks and sent over a
  // WebSocket to coinos's live server (coinosv3-server live/), which makes HLS
  // of it; the stream is announced as your kind 30311, refreshed every minute
  // with how many watch, and ended with its recording. A coinos name's owner
  // only: the server asks the registrar. One at a time.
  const liveIngest = () => {
    const local = typeof location !== 'undefined' && /^(localhost|127\.0\.0\.1)$/.test(location.hostname);
    return (local ? location.origin : APP_BASE).replace(/^http/, 'ws') + '/live/ingest';
  };
  const recType = () => {
    if (typeof MediaRecorder === 'undefined') return null;
    return ['video/webm;codecs=h264,opus', 'video/webm;codecs=vp8,opus', 'video/webm', 'video/mp4'].find((m) => { try { return MediaRecorder.isTypeSupported(m); } catch { return false; } }) || null;
  };
  const canGoLive = () => !isVisitor() && typeof navigator !== 'undefined' && !!navigator.mediaDevices?.getUserMedia && !!recType();
  const clockOf = (sec) => { sec = Math.max(0, Math.floor(sec)); const hh = Math.floor(sec / 3600), mm = Math.floor(sec / 60) % 60, ss = sec % 60; return (hh ? hh + ':' + String(mm).padStart(2, '0') : String(mm)) + ':' + String(ss).padStart(2, '0'); };
  let bc = null; // the broadcast: { phase, title, source, facing, media, rec, ws, id, a, ev, err, ... }
  function openGoLive() {
    if (bc && bc.a && bc.phase === 'live') { openLive(bc.ev); return; }
    bc = { phase: 'setup', title: '', source: 'camera', facing: 'user', media: null, err: null };
    ui.goLive = true;
    ui.liveStream = null;
    render();
    bcPreview().catch(() => {});
  }
  function bcStopMedia() {
    if (bc && bc.media) for (const tr of bc.media.getTracks()) { try { tr.stop(); } catch {} }
    if (bc) bc.media = null;
  }
  // the picture to send: the camera (with its microphone), or the screen
  // (with the microphone beside it, and the tab's sound when shared)
  async function bcPreview() {
    const b = bc;
    if (!b) return;
    // live, the old picture keeps going out until the new one is there (a
    // cancelled screen picker mustn't leave the stream with nothing)
    const live = b.phase === 'live', was = b.source === 'screen' ? 'camera' : 'screen';
    if (!live) bcStopMedia();
    b.err = null;
    try {
      let media;
      if (b.source === 'screen') {
        media = await navigator.mediaDevices.getDisplayMedia({ video: { frameRate: 30 }, audio: true });
        const mic = await navigator.mediaDevices.getUserMedia({ audio: true }).catch(() => null);
        if (mic && !media.getAudioTracks().length) for (const tr of mic.getAudioTracks()) media.addTrack(tr);
        // the browser's own "Stop sharing", live: back to the camera
        media.getVideoTracks()[0]?.addEventListener('ended', () => { if (bc === b && b.phase === 'live' && b.media === media) { b.source = 'camera'; bcPreview(); } });
      } else {
        media = await navigator.mediaDevices.getUserMedia({
          video: { facingMode: b.facing, width: { ideal: 1280 }, height: { ideal: 720 }, frameRate: { ideal: 30 } },
          audio: { echoCancellation: true, noiseSuppression: true },
        });
      }
      if (bc !== b) { for (const tr of media.getTracks()) tr.stop(); return; }
      if (live) bcStopMedia();
      b.media = media;
      // a switch mid-stream: the recorder carries on with the new picture,
      // and the WebRTC copy swaps it in where it is
      if (b.phase === 'live') { bcRecord(b, true); bcRtcSwap(b); }
    } catch (e) {
      if (bc !== b) return;
      if (live) b.source = was; // no screen after all: the camera goes on
      else b.err = t(b.source === 'screen' ? 'goLiveNoScreen' : 'goLiveNoCamera');
    }
    render();
  }
  async function liveAuth(b) {
    const id = await requireIdentity();
    const partial = { kind: 27235, created_at: Math.floor(Date.now() / 1000), content: '',
      tags: [['u', APP_BASE + '/live/ingest'], ['method', 'GET']] };
    const evt = id.signer instanceof Uint8Array ? finalizeEvent(partial, id.signer) : await id.signer.signEvent(partial);
    b.pk = id.pubkey;
    return btoa(JSON.stringify(evt));
  }
  // one connection to the server: its first word is where the stream is
  function bcConnect(b, resume) {
    return liveAuth(b).then((auth) => new Promise((resolve, reject) => {
      const name = (hook('namesAddress') || '').split('@')[0];
      const ws = new WebSocket(liveIngest() + '?auth=' + encodeURIComponent(auth) + '&name=' + encodeURIComponent(name) + (resume ? '&resume=' + resume : ''));
      ws.binaryType = 'arraybuffer';
      let hello = false;
      ws.onmessage = (e) => {
        if (hello || typeof e.data !== 'string') return;
        hello = true;
        try { resolve({ ws, info: JSON.parse(e.data) }); } catch (err) { reject(err); }
      };
      ws.onerror = () => { if (!hello) reject(new Error(t('goLiveRefused'))); };
      ws.onclose = () => {
        if (!hello) { reject(new Error(t('goLiveRefused'))); return; }
        if (bc === b && b.ws === ws && b.phase === 'live') bcReconnect(b);
      };
    }));
  }
  // a recorder over the current picture, its chunks to the server; a new one
  // (a new connection, a new camera) starts a fresh recording, header and all
  function bcRecord(b, again = false) {
    if (b.rec) { try { b.rec.ondataavailable = null; b.rec.stop(); } catch {} }
    if (again && b.ws) { try { b.ws.close(1000, 'switch'); } catch {} return; } // the reconnect brings the new recording
    const rec = new MediaRecorder(b.media, { mimeType: recType(), videoBitsPerSecond: 2_500_000, audioBitsPerSecond: 128_000 });
    rec.ondataavailable = (e) => {
      if (!e.data || !e.data.size || bc !== b || !b.ws || b.ws.readyState !== 1) return;
      // more than a few seconds unsent: the link can't keep up
      b.behind = b.ws.bufferedAmount > 4_000_000;
      e.data.arrayBuffer().then((buf) => { if (b.ws && b.ws.readyState === 1) b.ws.send(buf); });
    };
    rec.start(500);
    b.rec = rec;
  }
  async function bcReconnect(b) {
    if (b.reconnecting) return;
    b.reconnecting = true;
    b.ws = null;
    render();
    for (let i = 0; i < 10 && bc === b && b.phase === 'live'; i++) {
      try {
        const { ws, info } = await bcConnect(b, b.id);
        if (bc !== b || b.phase !== 'live') { ws.close(); break; }
        b.ws = ws;
        bcRecord(b);
        b.reconnecting = false;
        // The server couldn't take us back (it restarted, or we were gone
        // too long): this is a new stream at a new address. The old one is
        // over — said so, with no recording (there's next to nothing in
        // it) — and the new one is announced as soon as it plays.
        if (info.id !== b.id) {
          toast(t('goLiveRestarted'));
          const old = { ...b, recording: null };
          Object.assign(b, { id: info.id, liveUrl: info.live, recording: info.recording, a: LIVE_KIND + ':' + b.pk + ':' + info.id });
          bcRtc(b).catch(() => {});
          bcAnnounce(old, 'ended').catch(() => {});
          bcPlaying(b).then(() => (bc === b && b.phase === 'live' ? bcAnnounce(b, 'live') : null)).then(() => {
            // the streamer's own view of it follows to the new address
            if (bc === b && b.ev && ui.liveStream && ui.liveStream.a === old.a) { ui.liveStream = { a: b.a, seed: b.ev }; render(); }
          }).catch(() => {});
        }
        render();
        return;
      } catch {}
      await new Promise((r) => setTimeout(r, 3000));
    }
    b.reconnecting = false;
    if (bc === b && b.phase === 'live') { toast(t('goLiveLost')); endBroadcast(); }
  }
  // The stream as WebRTC, for the app's own viewers: the picture also goes to
  // Cloudflare's SFU (the live server brokers it), and a viewer pulls it from
  // there a fraction of a second behind — HLS is seconds behind. Best effort:
  // the HLS above is the stream either way, and the recording.
  async function bcRtc(b, tries = 0) {
    if (typeof RTCPeerConnection === 'undefined' || bc !== b || b.phase !== 'live' || !b.id || !b.media) return;
    bcRtcStop(b);
    const id = b.id;
    const pc = b.pc = new RTCPeerConnection({ iceServers: [{ urls: 'stun:stun.cloudflare.com:3478' }], bundlePolicy: 'max-bundle' });
    const again = () => {
      if (bc !== b || b.pc !== pc || b.phase !== 'live' || tries >= 5) return;
      bcRtcStop(b);
      setTimeout(() => bcRtc(b, tries + 1).catch(() => {}), 3000 * (tries + 1));
    };
    pc.onconnectionstatechange = () => { if (pc.connectionState === 'failed') again(); else if (pc.connectionState === 'connected') tries = 0; };
    try {
      const vt = b.media.getVideoTracks()[0], at = b.media.getAudioTracks()[0];
      const tv = pc.addTransceiver(vt || 'video', { direction: 'sendonly', sendEncodings: [{ maxBitrate: 2_500_000 }] });
      const ta = pc.addTransceiver(at || 'audio', { direction: 'sendonly' });
      await pc.setLocalDescription(await pc.createOffer());
      const u = liveBase() + '/live/' + id + '/rtc/publish';
      const auth = await signAsMe({ kind: 27235, created_at: Math.floor(Date.now() / 1000), content: '', tags: [['u', APP_BASE + '/live/' + id + '/rtc/publish'], ['method', 'POST']] });
      const r = await fetch(u, { method: 'POST', headers: { authorization: 'Nostr ' + btoa(JSON.stringify(auth)), 'content-type': 'application/json' },
        body: JSON.stringify({ sdp: pc.localDescription.sdp, tracks: [{ mid: tv.mid, trackName: 'video' }, { mid: ta.mid, trackName: 'audio' }] }) });
      if (r.status === 501 || r.status === 403) { bcRtcStop(b); return; } // no WebRTC on this server
      if (!r.ok) throw new Error('publish ' + r.status);
      const j = await r.json();
      if (b.pc !== pc) return;
      await pc.setRemoteDescription({ type: 'answer', sdp: j.sdp });
    } catch { again(); }
  }
  function bcRtcSwap(b) {
    if (!b.pc || !b.media) return;
    for (const tr of b.pc.getTransceivers()) {
      const kind = tr.receiver && tr.receiver.track && tr.receiver.track.kind;
      const next = kind === 'video' ? b.media.getVideoTracks()[0] : kind === 'audio' ? b.media.getAudioTracks()[0] : null;
      if (kind) tr.sender.replaceTrack(next || null).catch(() => {});
    }
  }
  function bcRtcStop(b) {
    if (b && b.pc) { try { b.pc.close(); } catch {} b.pc = null; }
  }
  // the announcement: your 30311, and its copies as the stream goes on
  async function bcAnnounce(b, status) {
    const id = await requireIdentity();
    const relays = [...new Set([...LIVE_RELAYS, ...wallet.nostrRelays()])];
    const me = profileOf(id.pubkey) || {};
    const tags = [['d', b.id], ['title', b.title || t('goLiveDefaultTitle', { name: displayName(id.pubkey) })],
      ['status', status], ['streaming', b.liveUrl], ['starts', String(b.starts)],
      ['p', id.pubkey, '', 'Host'], ['relays', ...relays.slice(0, 6)], CLIENT_TAG];
    if (me.picture) tags.push(['image', me.picture]);
    if (status === 'live' && b.viewers != null) tags.push(['current_participants', String(b.viewers)]);
    if (status === 'ended') tags.push(['ends', String(Math.floor(Date.now() / 1000))]);
    if (status === 'ended' && b.recording) tags.push(['recording', b.recording]);
    // each copy newer than the last, to the second: an `ended` stamped the
    // same second as the `live` before it lost to it (relays keep the lower
    // id on a tie) and the stream read live for good
    const prev = liveSeen.get(LIVE_KIND + ':' + id.pubkey + ':' + b.id);
    const partial = { kind: LIVE_KIND, content: '', created_at: Math.max(Math.floor(Date.now() / 1000), prev ? prev.created_at + 1 : 0), tags };
    const evt = id.signer instanceof Uint8Array ? finalizeEvent(partial, id.signer) : await id.signer.signEvent(partial);
    takeLive([evt]);
    if (bc === b) b.ev = evt;
    scheduleRepaint();
    return publishOn(relays, evt);
  }
  async function bcPlaying(b) {
    const url = b.liveUrl;
    for (let i = 0; i < 40 && bc === b && b.phase === 'live' && b.liveUrl === url; i++) {
      await new Promise((r) => setTimeout(r, 500));
      const pl = await fetch(url, { cache: 'no-store' }).then((r) => r.text()).catch(() => '');
      if ((pl.match(/\.ts\s*$/gm) || []).length >= 3) break;
    }
  }
  async function startBroadcast() {
    const b = bc;
    if (!b || b.phase !== 'setup' || !b.media) return;
    b.phase = 'starting'; b.err = null;
    render();
    try {
      const { ws, info } = await bcConnect(b, null);
      if (bc !== b) { ws.close(); return; }
      Object.assign(b, { ws, id: info.id, liveUrl: info.live, recording: info.recording, starts: Math.floor(Date.now() / 1000), viewers: 0 });
      b.phase = 'live';
      b.a = LIVE_KIND + ':' + b.pk + ':' + b.id;
      bcRecord(b);
      bcRtc(b).catch(() => {});
      try { b.lock = await navigator.wakeLock?.request('screen'); } catch {}
      // the stream is a few seconds behind the camera: announced once it has
      // three segments — Chrome's own player won't start a live playlist with
      // fewer (it fails to parse it), so a viewer who comes at once would get
      // an error, not the stream
      await bcPlaying(b);
      if (bc !== b || b.phase !== 'live') return;
      await bcAnnounce(b, 'live');
      b.tick = setInterval(() => bcTick(b), 60_000);
      ui.goLive = null;
      openLive(b.ev);
    } catch (e) {
      if (bc !== b) return;
      b.phase = 'setup';
      b.err = (e && e.message) || t('goLiveRefused');
      try { b.ws && b.ws.close(); } catch {}
      render();
    }
  }
  // every minute: how many watch, into a fresh copy of the announcement
  async function bcTick(b) {
    if (bc !== b || b.phase !== 'live') return;
    try {
      const st = await (await fetch(b.liveUrl.replace(/live\.m3u8$/, 'stats'))).json();
      b.viewers = st.viewers;
    } catch {}
    bcAnnounce(b, 'live').catch(() => {});
  }
  async function endBroadcast() {
    const b = bc;
    if (!b || b.phase === 'ended') return;
    const was = b.phase;
    b.phase = 'ended';
    clearInterval(b.tick);
    try { b.rec && b.rec.stop(); } catch {}
    bcRtcStop(b);
    try { if (b.ws && b.ws.readyState === 1) b.ws.send('end'); } catch {}
    setTimeout(() => { try { b.ws && b.ws.close(1000, 'ended'); } catch {} }, 500);
    bcStopMedia();
    try { b.lock && b.lock.release(); } catch {}
    bc = null;
    ui.goLive = null;
    render();
    if (was === 'live' && b.id) {
      await bcAnnounce(b, 'ended').catch(() => {});
      toast(t('goLiveEnded'));
    }
  }
  // the screen before going live: what to send, a title, the picture itself
  function goLiveScreen() {
    if (!bc) { bc = { phase: 'setup', title: '', source: 'camera', facing: 'user', media: null, err: null }; queueMicrotask(() => bcPreview().catch(() => {})); } // (a reload, back on this screen)
    const b = bc;
    const name = hook('namesAddress');
    const screenOk = !!navigator.mediaDevices?.getDisplayMedia;
    queueMicrotask(() => {
      const v = document.querySelector('video.bc-preview');
      if (v && b.media && v.srcObject !== b.media) { v._skipMorph = true; v.srcObject = b.media; v.play().catch(() => {}); }
    });
    const pick = (src) => { if (b.source === src) return; b.source = src; render(); bcPreview(); };
    // the server's say first (a name a day old, not barred), so Start doesn't just fail
    if (name && b.allowed === undefined) {
      b.allowed = null;
      signAsMe({ kind: 27235, created_at: Math.floor(Date.now() / 1000), content: '', tags: [['u', APP_BASE + '/live/allowed'], ['method', 'GET']] })
        .then((auth) => fetch(liveBase() + '/live/allowed?name=' + encodeURIComponent(name.split('@')[0]), { headers: { authorization: 'Nostr ' + btoa(JSON.stringify(auth)) }, signal: AbortSignal.timeout(8000) }))
        .then((r) => r.json()).then((j) => { b.allowed = j; render(); })
        .catch(() => { b.allowed = { ok: true }; render(); }); // unasked: the server still decides at Start
    }
    const refused = b.allowed && b.allowed.ok === false ? b.allowed : null;
    return h('div', { class: 'col live-page', style: 'gap:12px' },
      ctx.brandHeader(true),
      h('div', { class: 'card col', style: 'gap:12px' },
        h('div', { class: 'row gap6', style: 'align-items:center' },
          backBtn(() => { bcStopMedia(); bc = null; ui.goLive = null; }),
          h('h3', { style: 'margin:0' }, t('goLive'))),
        !name ? h('div', { class: 'notice small' }, t('goLiveNeedsName')) : null,
        refused ? h('div', { class: 'notice small go-live-refused' }, refused.reason === 'new-name' && refused.until
          ? t('goLiveNewName', { when: timeLabel(refused.until) }) : refused.reason === 'banned' ? t('goLiveBanned') : t('goLiveNeedsName')) : null,
        h('div', { class: 'live-player', 'data-key': 'bc-player:' + b.source },
          b.media
            ? h('div', { class: 'live-frame', 'data-key': 'bc-frame:' + b.media.id }, h('video', { class: 'live-video bc-preview' + (b.source === 'camera' && b.facing === 'user' ? ' mirror' : ''), muted: '', playsinline: '', autoplay: '' }))
            : h('div', { class: 'live-cover live-still', 'data-key': 'bc-still' }, h('span', { class: 'live-say' }, b.err || t('goLiveAsking')))),
        h('div', { class: 'row gap6 wrap' },
          h('button', { class: 'btn-sm' + (b.source === 'camera' ? ' on' : ''), onClick: () => pick('camera') }, t('goLiveCamera')),
          screenOk ? h('button', { class: 'btn-sm' + (b.source === 'screen' ? ' on' : ''), onClick: () => pick('screen') }, t('goLiveScreen')) : null,
          b.source === 'camera' ? h('button', { class: 'btn-sm', title: t('goLiveFlip'), onClick: () => { b.facing = b.facing === 'user' ? 'environment' : 'user'; bcPreview(); } }, '⇄ ' + t('goLiveFlip')) : null),
        h('input', { type: 'text', class: 'go-live-title', placeholder: t('goLiveTitlePh'), value: b.title, maxlength: '120',
          onInput: (e) => { b.title = e.target.value; } }),
        b.err && b.media ? h('div', { class: 'notice err small' }, b.err) : null,
        h('button', { class: 'btn-primary btn-block go-live-start', disabled: !name || !b.media || b.phase !== 'setup' || !!refused, onClick: startBroadcast },
          b.phase === 'starting' ? h('span', { class: 'spinner sm' }) : null, ' ', t(b.phase === 'starting' ? 'goLiveStarting' : 'goLiveStart')),
        h('div', { class: 'small faint' }, t('goLiveHint'))));
  }

  // ---- calls (NIP-AC: src/calls.js) ------------------------------------------
  // A 📞 or 🎥 in a conversation's header calls that person; a call from
  // someone you follow (or talk to) rings over whatever page is up. The setup
  // goes as ephemeral gift wraps to their DM inboxes and ours; TURN comes from
  // coinos's live server (Cloudflare's), for the connections that can't go direct.
  const liveBase = () => {
    const local = typeof location !== 'undefined' && /^(localhost|127\.0\.0\.1)$/.test(location.hostname);
    return local ? location.origin : APP_BASE;
  };
  let calls = null;
  const callInbox = new Map(); // peer -> their inbox relays, for this session
  // Relays that turned a call message away are left out of the next ones: a
  // relay that won't take the kind (nip17.com: "only kind 1059") for a day,
  // one rate-limiting or banning us for ten minutes. Kept on this device.
  const CALL_SHUN_KEY = 'coinos-call-shun';
  let callShun = (() => { try { return JSON.parse(localStorage.getItem(CALL_SHUN_KEY) || '{}'); } catch { return {}; } })(); // relay -> until
  function callRefused(url, msg) {
    const kindRule = /only kind|not (accepted|allowed)|blocked|unsupported|restricted|kind \d+/i.test(msg) && !/rate|too many|banned|slow down/i.test(msg);
    callShun[url] = Date.now() + (kindRule ? 86400_000 : 600_000);
    try { localStorage.setItem(CALL_SHUN_KEY, JSON.stringify(callShun)); } catch {}
  }
  function callRelaysOf(relays) {
    const now = Date.now();
    const ok = relays.filter((r) => !(callShun[r] > now));
    return ok.length ? ok : relays; // all of them shunned: try them anyway
  }
  async function inboxFor(pk) {
    if (callInbox.has(pk)) return callInbox.get(pk);
    const p = (isMe(pk) ? Promise.resolve(ownInbox) : fetchInboxRelays(pk).catch(() => []))
      .then((l) => [...new Set([...DM_RELAYS, ...(l || []).filter((r) => /^wss:\/\//i.test(r)).slice(0, 4)])]);
    callInbox.set(pk, p);
    return p;
  }
  async function signAsMe(tmpl) {
    const id = await requireIdentity();
    return id.signer instanceof Uint8Array ? finalizeEvent(tmpl, id.signer) : id.signer.signEvent(tmpl);
  }
  let iceCache = null; // { servers, until }
  async function callIce() {
    if (iceCache && Date.now() < iceCache.until) return iceCache.servers;
    const STUN = [{ urls: ['stun:stun.cloudflare.com:3478', 'stun:stun.l.google.com:19302'] }];
    try {
      const auth = await signAsMe({ kind: 27235, created_at: Math.floor(Date.now() / 1000), content: '', tags: [['u', APP_BASE + '/live/turn'], ['method', 'GET']] });
      const r = await fetch(liveBase() + '/live/turn', { headers: { authorization: 'Nostr ' + btoa(JSON.stringify(auth)) }, signal: AbortSignal.timeout(8000) });
      const j = await r.json();
      if (!Array.isArray(j.iceServers) || !j.iceServers.length) return STUN;
      iceCache = { servers: j.iceServers, until: Date.now() + Math.max(60, (j.ttl || 600) - 600) * 1000 };
      return j.iceServers;
    } catch { return STUN; }
  }
  function callMedia(type, facing = 'user') {
    const video = { facingMode: facing, width: { ideal: 1280 }, height: { ideal: 720 } };
    const audio = { echoCancellation: true, noiseSuppression: true, autoGainControl: true };
    if (type === 'video-only') return navigator.mediaDevices.getUserMedia({ video });
    if (type === 'screen') return navigator.mediaDevices.getDisplayMedia({ video: { frameRate: { ideal: 15 } }, audio: false });
    return navigator.mediaDevices.getUserMedia(type === 'video' ? { audio, video } : { audio });
  }
  // who may ring: someone you follow, or someone you've written to
  // who may ring: someone you follow, or someone you've written to. Anyone
  // else's call doesn't ring but is told of, as a missed call that didn't
  // ring (a wife's call must not vanish because you never followed her);
  // a muted person's leaves nothing.
  const mayRing = (pk) => hiddenPk(pk) ? null
    : followsNow().set.has(pk) || wroteTo(pk) ? 'ring' : 'quiet';
  // a message of ours in the conversation — not a call logged there (a
  // stranger's unrung call would otherwise let their next one ring)
  function wroteTo(pk) {
    for (const m of (threads.get(pk) || new Map()).values()) if (m.mine && m.rumor.kind !== CALL_LOG) return true;
    return false;
  }
  function callsNow() {
    if (calls) return calls;
    calls = createCalls({
      me: () => dmSubKeys()[0],
      sign: signAsMe,
      // An offer, answer, hang-up or decline nobody took is tried again for a
      // while (a relay's per-minute limit, a socket reconnecting): a lost
      // answer left the caller ringing on and the callee "Connecting…".
      // A late route isn't worth the wait.
      send: async (pk, signed) => {
        const tries = signed.kind === CALL.ICE ? 1 : 4;
        for (let i = 0; i < tries; i++) {
          if (i) await new Promise((r) => setTimeout(r, 1500 * 2 ** (i - 1)));
          const relays = callRelaysOf(await inboxFor(pk));
          if (await publishOn(relays, wrapCall(signed, pk), { onauth: relayAuth, onrefused: callRefused })) return;
        }
        throw new Error('not delivered');
      },
      iceServers: callIce,
      media: callMedia,
      mayRing: async (pk) => mayRing(pk),
      changed: () => { callRing(); render(); },
      ended: (rec) => { logCall(rec).catch(() => {}); },
      warm: (pk) => callWarm(pk),
      // a key of our own signs each candidate at once; a remote signer gets
      // them all inside the offer or answer instead
      trickle: () => { try { if (localStorage.getItem('coinos-call-trickle') === '0') return false; } catch {} const id = hook('nostrLoginIdentity'); return !id || id.signer instanceof Uint8Array; },
    });
    return calls;
  }
  // a wrap addressed to us: opened by whichever of our keys it's for
  async function onCallWrap(wrap) {
    for (const d of dmDecryptors()) {
      const dec = d instanceof Uint8Array ? async (pk, ct) => nip44.decrypt(ct, nip44.getConversationKey(d, pk)) : (pk, ct) => d.decryptFrom(pk, ct);
      const inner = await openCall(wrap, dec).catch(() => null);
      if (inner) { profileOf(inner.pubkey); await callsNow().handle(inner); return; }
    }
  }
  // The call log: each call a row in its conversation ("Outgoing video call
  // 4:12", "Missed voice call"), kept like a message and sent to our own
  // inbox (kind 1405 in a gift wrap, to us alone — a kind the NIP-AC
  // discussion uses for logs, which other clients pass over) so our other
  // devices list it too. A call rung on two of our devices is logged by
  // both; the conversation shows it once, by its call-id.
  const callStatus = (rec) => rec.connected ? 'answered'
    : rec.reason === 'missed' || rec.reason === 'unrung' ? 'missed'
    : rec.reason === 'declined' || rec.reason === 'peer-declined' ? 'declined'
    : rec.reason === 'no-answer' ? 'no-answer'
    : rec.reason === 'busy' ? 'busy'
    : rec.reason === 'hung-up' ? 'cancelled'
    : 'failed';
  const CALL_RANK = { answered: 5, declined: 4, busy: 3, 'no-answer': 2, cancelled: 2, failed: 1, missed: 0 };
  function callLogText(dir, type, status, seconds) {
    const video = type === 'video';
    const key = status === 'answered' ? (dir === 'out' ? 'callLogOut' : 'callLogIn')
      : status === 'missed' ? 'callLogMissed'
      : status === 'declined' ? (dir === 'out' ? 'callLogTheyDeclined' : 'callLogDeclined')
      : status === 'no-answer' ? 'callLogNoAnswer'
      : status === 'cancelled' ? 'callLogCancelled'
      : status === 'busy' ? 'callLogBusy' : 'callLogFailed';
    const what = t(key, { what: t(video ? 'callLogVideo' : 'callLogVoice') });
    return status === 'answered' && seconds ? what + ' · ' + clockOf(seconds) : what;
  }
  async function logCall(rec) {
    if (!rec || !rec.peer || /elsewhere$/.test(rec.reason || '')) return; // the device that took it logs it
    // (a missed call found as the app opens may come before its keys do)
    let id = await identity();
    for (let i = 0; !id && i < 15; i++) { await new Promise((r) => setTimeout(r, 1000)); id = await identity(); }
    if (!id) return;
    const status = callStatus(rec);
    const rumor = rumorWithId({
      kind: CALL_LOG, pubkey: id.pubkey, created_at: Math.floor((rec.at || Date.now()) / 1000),
      content: callLogText(rec.dir, rec.type, status, rec.seconds),
      tags: [['p', rec.peer], ['call-id', rec.id], ['call-type', rec.type], ['direction', rec.dir], ['status', status],
        ['duration', String(rec.seconds || 0)], ...(rec.reason === 'unrung' ? [['rang', 'no']] : []), ['alt', 'Call log']],
    });
    noteDM(rec.peer, rumor, true);
    persistDms();
    // to our other devices — not through Amber, a prompt per call for a log line
    if (!(id.signer instanceof Uint8Array) && (id.signer.interactive || !id.signer.encryptTo)) return;
    const toSelf = await wrapDM(id.signer, id.pubkey, rumor);
    publishOn(DM_RELAYS, toSelf);
    toOwnInbox(toSelf);
  }
  // A conversation's rows with each call once: its most telling log (one
  // device answered it while another only saw it ring)
  function foldCallLogs(msgs) {
    const best = new Map();
    for (const m of msgs) {
      if (m.rumor.kind !== CALL_LOG) continue;
      const cid = (m.rumor.tags.find((x) => x[0] === 'call-id') || [])[1] || m.rumor.id;
      const st2 = (x) => CALL_RANK[(x.rumor.tags.find((y) => y[0] === 'status') || [])[1]] ?? 0;
      const cur = best.get(cid);
      if (!cur || st2(m) > st2(cur)) best.set(cid, m);
    }
    return msgs.filter((m) => m.rumor.kind !== CALL_LOG || best.get((m.rumor.tags.find((x) => x[0] === 'call-id') || [])[1] || m.rumor.id) === m);
  }
  function callLogRow(m, peer) {
    const tag = (k) => (m.rumor.tags.find((x) => x[0] === k) || [])[1];
    const type = tag('call-type') === 'video' ? 'video' : 'voice', status = tag('status') || 'failed', dir = tag('direction') || 'out';
    const missed = status === 'missed' || (dir === 'in' && status === 'declined');
    // a call that didn't ring (someone you don't follow), saying so — and,
    // while that's still so, how to have them ring next time
    const unrung = tag('rang') === 'no';
    return h('div', { class: 'chat-row call-log' + (missed ? ' missed' : ''), 'data-call-log': tag('call-id') || '' },
      h('button', { type: 'button', class: 'call-log-pill', title: t(type === 'video' ? 'callVideo' : 'callVoice'), onClick: () => startCall(peer, type) },
        callIcon(type === 'video' ? 'video' : 'phone'),
        h('span', {}, callLogText(dir, type, status, +tag('duration') || 0)),
        h('span', { class: 'chat-time' }, timeLabel(m.rumor.created_at * 1000))),
      unrung ? h('div', { class: 'small faint call-log-why' }, t(mayRing(peer) === 'ring' ? 'callLogUnrungWas' : 'callLogUnrung')) : null);
  }

  // the call offer a push brought (sw-nwc.js keeps it): rung now, once
  async function pendingCall() {
    try {
      if (typeof caches === 'undefined') return;
      const cache = await caches.open('coinos-call');
      // calls the worker saw from people who don't ring us: logged, unrung
      const quiet = await cache.match('/__quiet-calls');
      if (quiet) {
        await cache.delete('/__quiet-calls');
        for (const offer of (await quiet.json()) || []) {
          if (!offer || !offer.pubkey || !mayRing(offer.pubkey)) continue;
          const id = (offer.tags.find((x) => x[0] === 'call-id') || [])[1];
          const type = (offer.tags.find((x) => x[0] === 'call-type') || [])[1] === 'video' ? 'video' : 'voice';
          if (id) logCall({ id, peer: offer.pubkey, type, dir: 'in', reason: 'unrung', seconds: 0, at: offer.created_at * 1000 }).catch(() => {});
        }
      }
      const r = await cache.match('/__pending-call');
      if (!r) return;
      await cache.delete('/__pending-call');
      const { offer, at } = await r.json();
      if (!offer) return;
      if (Date.now() - at < RING_S * 1000) { await callsNow().handle(offer, { maxAge: RING_S }); return; }
      // rang while the app was shut, and nobody came: a missed call in the conversation
      if (mayRing(offer.pubkey)) {
        const type = (offer.tags.find((x) => x[0] === 'call-type') || [])[1] === 'video' ? 'video' : 'voice';
        const id = (offer.tags.find((x) => x[0] === 'call-id') || [])[1];
        if (id) logCall({ id, peer: offer.pubkey, type, dir: 'in', reason: 'missed', seconds: 0, at: offer.created_at * 1000 }).catch(() => {});
      }
    } catch {}
  }
  // A call with them may be coming (it rings, or their conversation is open):
  // their relays looked up, TURN fetched — the seconds the first send or
  // answer used to spend on it. Not through Amber: a prompt to open a chat.
  const warmed = new Set();
  function callWarm(pk) {
    if (!pk || warmed.has(pk)) return;
    warmed.add(pk);
    inboxFor(pk).catch(() => {});
    const login = hook('nostrLoginIdentity');
    if (!(login && login.signer && login.signer.interactive)) callIce().catch(() => {});
  }
  function startCall(peer, type) {
    if (typeof RTCPeerConnection === 'undefined' || !navigator.mediaDevices?.getUserMedia) { toast(t('callUnsupported')); return; }
    const cur = callsNow().call;
    if (cur && cur.state !== 'ended') { ui.callMin = false; render(); return; }
    ui.callMin = false;
    callsNow().start(peer, type).catch(() => {});
  }

  // The ring: a tone (two short bursts every few seconds) and the phone's
  // buzz for a call coming in, a softer one while ours rings them; and, with
  // the app out of sight, a notification.
  let ringCtx = null, ringTimer = null, ringFor = null;
  function tone(ctx, freqs, at, len, vol) {
    for (const f of freqs) {
      const o = ctx.createOscillator(), g = ctx.createGain();
      o.frequency.value = f; o.connect(g); g.connect(ctx.destination);
      g.gain.setValueAtTime(0, at); g.gain.linearRampToValueAtTime(vol, at + 0.02); g.gain.setValueAtTime(vol, at + len - 0.05); g.gain.linearRampToValueAtTime(0, at + len);
      o.start(at); o.stop(at + len + 0.05);
    }
  }
  function callRing() {
    const c = calls && calls.call;
    const want = c && (c.state === 'incoming' || c.state === 'offering') ? c.id + ':' + c.state : null;
    if (want === ringFor) return;
    ringFor = want;
    clearInterval(ringTimer); ringTimer = null;
    try { navigator.vibrate && navigator.vibrate(0); } catch {}
    // answered, declined or over: its "is calling" notification goes too
    if (!want || want.endsWith(':offering')) {
      try { navigator.serviceWorker?.ready.then((r) => r.getNotifications({ tag: 'call' })).then((ns) => { for (const n of ns || []) n.close(); }).catch(() => {}); } catch {}
    }
    if (!want) return;
    const incoming = c.state === 'incoming';
    const beat = () => {
      try {
        ringCtx = ringCtx || new (window.AudioContext || window.webkitAudioContext)();
        if (ringCtx.state === 'suspended') ringCtx.resume().catch(() => {});
        const t0 = ringCtx.currentTime + 0.05;
        if (incoming) { tone(ringCtx, [440, 480], t0, 0.4, 0.12); tone(ringCtx, [440, 480], t0 + 0.6, 0.4, 0.12); }
        else tone(ringCtx, [440, 480], t0, 1.2, 0.05); // the ringback, heard by the caller
      } catch {}
      if (incoming) { try { navigator.vibrate && navigator.vibrate([400, 200, 400]); } catch {} }
    };
    beat();
    ringTimer = setInterval(beat, incoming ? 3000 : 4000);
    if (incoming && typeof document !== 'undefined' && document.hidden) {
      try {
        if (Notification.permission === 'granted') navigator.serviceWorker?.ready.then((r) => r.showNotification(t('callIncomingFrom', { name: displayName(c.peer) }), {
          body: t(c.type === 'video' ? 'callIncomingVideo' : 'callIncomingVoice'), tag: 'call', renotify: true, requireInteraction: true,
        })).catch(() => {});
      } catch {}
    }
  }

  // the call's sound and pictures into their elements, after each paint
  function mountCallMedia() {
    const c = calls && calls.call;
    const put = (sel, stream) => {
      const el = document.querySelector(sel);
      if (el && stream && el.srcObject !== stream) { el.srcObject = stream; el.play().catch(() => {}); }
    };
    if (!c) return;
    put('audio.call-audio', c.remote);
    put('video.call-remote', c.remote);
    put('video.call-local', c.local);
  }
  const callReason = (r) => t({ 'no-answer': 'callNoAnswer', 'peer-declined': 'callDeclined', busy: 'callBusy', failed: 'callFailed', error: 'callFailed',
    'no-permission': 'callNoPermission', missed: 'callMissed', 'answered-elsewhere': 'callAnsweredElsewhere', 'declined-elsewhere': 'callDeclinedElsewhere' }[r] || 'callEnded');
  const CALL_ICONS = {
    phone: '<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 16.9v3a2 2 0 0 1-2.2 2 19.8 19.8 0 0 1-8.6-3.1 19.5 19.5 0 0 1-6-6A19.8 19.8 0 0 1 2.1 4.2 2 2 0 0 1 4.1 2h3a2 2 0 0 1 2 1.7c.1.9.4 1.8.7 2.7a2 2 0 0 1-.5 2.1L8 9.8a16 16 0 0 0 6 6l1.3-1.3a2 2 0 0 1 2.1-.4c.9.3 1.8.6 2.7.7a2 2 0 0 1 1.7 2z"/></svg>',
    video: '<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m22 8-6 4 6 4V8z"/><rect x="2" y="6" width="14" height="12" rx="2"/></svg>',
    mic: '<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="2" width="6" height="12" rx="3"/><path d="M5 10a7 7 0 0 0 14 0M12 17v5"/></svg>',
    micOff: '<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m2 2 20 20M9 9v1a3 3 0 0 0 5.1 2.1M15 9.3V5a3 3 0 0 0-5.9-.6M17 16.9A7 7 0 0 1 5 10M19 10a7 7 0 0 1-.3 2M12 17v5"/></svg>',
    camOff: '<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m2 2 20 20M16 16v1a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V7a2 2 0 0 1 2-2h2m4 0h4a2 2 0 0 1 2 2v3.3l1 1 5-3.3v8"/></svg>',
    flip: '<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 7h-3l-2-3H9L7 7H4a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2z"/><path d="m14 11 2 2-2 2M10 15l-2-2 2-2M8 13h8"/></svg>',
    screen: '<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="3" width="20" height="14" rx="2"/><path d="M8 21h8M12 17v4M9 10l3-3 3 3M12 7v6"/></svg>',
    hang: '<svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor"><path d="M12 9c-1.6 0-3.2.3-4.6.7v3.1c0 .4-.2.7-.6.9-1 .5-1.9 1.1-2.7 1.8-.2.2-.4.3-.7.3s-.5-.1-.7-.3L.3 13.1c-.2-.2-.3-.4-.3-.7s.1-.5.3-.7C3.3 8.9 7.4 7 12 7s8.7 1.9 11.7 4.7c.2.2.3.4.3.7s-.1.5-.3.7l-2.4 2.4c-.2.2-.4.3-.7.3s-.5-.1-.7-.3c-.8-.7-1.7-1.3-2.7-1.8-.3-.2-.6-.5-.6-.9V9.7C15.2 9.3 13.6 9 12 9z"/></svg>',
    min: '<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m4 14 6 0 0 6M20 10l-6 0 0-6M14 10l7-7M3 21l7-7"/></svg>',
  };
  const callIcon = (k) => h('span', { style: 'display:flex', html: CALL_ICONS[k] });
  // The call, over any page: who, how it's going, and its buttons; minimized,
  // a bar across the top to come back by.
  function callOverlay() {
    const c = calls && calls.call;
    if (!c) return null;
    queueMicrotask(mountCallMedia);
    if (c.state === 'connected') setTimeout(scheduleRepaint, 1000); // the clock
    const video = c.type === 'video';
    // a picture that's coming (a muted track: they stopped their camera or share)
    const remoteVideo = video && c.remote && c.remote.getVideoTracks().some((x) => x.readyState === 'live' && !x.muted);
    const camOn = !!c.local && c.local.getVideoTracks().length > 0;
    const sound = h('audio', { class: 'call-audio', 'data-key': 'call-audio:' + c.id, autoplay: '' });
    const status = c.state === 'incoming' ? t(video ? 'callIncomingVideo' : 'callIncomingVoice')
      : c.state === 'starting' || c.state === 'offering' ? t('callCalling')
      : c.state === 'connecting' ? t('callConnecting')
      : c.state === 'connected' ? clockOf((Date.now() - c.connectedAt) / 1000)
      : callReason(c.reason);
    if (ui.callMin && c.state !== 'incoming' && c.state !== 'ended') {
      return h('div', { class: 'call-overlay call-min', 'data-key': 'call-overlay' }, sound,
        h('button', { class: 'call-min-bar', onClick: () => { ui.callMin = false; render(); } },
          h('span', { class: 'go-live-dot' }), h('span', { class: 'call-min-name' }, displayName(c.peer)), h('span', { class: 'call-min-status' }, status)));
    }
    const btn = (cls, icon, label, onClick, on = false) => h('button', { class: 'call-btn ' + cls + (on ? ' on' : ''), title: label, 'aria-label': label, onClick }, callIcon(icon));
    return h('div', { class: 'call-overlay' + (remoteVideo && c.state === 'connected' ? ' has-video' : ''), 'data-key': 'call-overlay' },
      sound,
      video ? h('video', { class: 'call-remote', 'data-key': 'call-remote:' + c.id, autoplay: '', playsinline: '', muted: '' }) : null,
      h('div', { class: 'call-who' },
        avatar(c.peer, 'chat-avatar profile-avatar call-avatar', false),
        h('div', { class: 'call-name' }, displayName(c.peer)),
        h('div', { class: 'call-status' }, status)),
      video && c.local && c.local.getVideoTracks().length ? h('video', { class: 'call-local' + (c.facing === 'user' && !c.sharing ? ' mirror' : '') + (c.sharing ? ' sharing' : ''), 'data-key': 'call-local:' + c.id, autoplay: '', playsinline: '', muted: '' }) : null,
      c.state === 'incoming'
        ? h('div', { class: 'call-bar' },
            btn('call-decline', 'hang', t('callDecline'), () => callsNow().reject()),
            btn('call-accept', video ? 'video' : 'phone', t('callAccept'), () => callsNow().accept()))
        : c.state === 'ended' ? null
        : h('div', { class: 'call-bar' },
            btn('', c.muted ? 'micOff' : 'mic', t(c.muted ? 'callUnmute' : 'callMute'), () => callsNow().setMuted(!c.muted), c.muted),
            // a camera in the call: off/on and flip; none yet (a voice call, or
            // theirs came on first): one tap puts ours in
            camOn ? btn('', c.camOff ? 'camOff' : 'video', t(c.camOff ? 'callCamOn' : 'callCamOff'), () => callsNow().setCamOff(!c.camOff), c.camOff) : null,
            camOn && !c.sharing ? btn('', 'flip', t('callFlip'), () => callsNow().flip()) : null,
            !camOn && c.state === 'connected' ? btn('call-add-video', 'video', t('callAddVideo'), () => callsNow().addVideo()) : null,
            // a browser that can share its screen (desktops; not phones' Chrome)
            c.state === 'connected' && navigator.mediaDevices?.getDisplayMedia
              ? btn('call-share', 'screen', t(c.sharing ? 'callStopShare' : 'callShare'), () => (c.sharing ? callsNow().stopShare() : callsNow().shareScreen()), !!c.sharing) : null,
            btn('', 'min', t('callMinimize'), () => { ui.callMin = true; render(); }),
            btn('call-hang', 'hang', t('callHangUp'), () => callsNow().hangup())));
  }

  // A quote inside a quote: one line of who and what, never a third level
  // of cards (a bare "view note" link said nothing about where it leads).
  function quoteMini(ref) {
    let c = feedPaint ? feedPaint.quotes.get(ref.id) : null;
    if (!c?.ev) {
      c = quotedNote(ref);
      if (feedPaint && c.ev) feedPaint.quotes.set(ref.id, { ...c });
    }
    const open = (e) => { e.preventDefault(); e.stopPropagation(); if (c.ev) openNoteThread(c.ev); else openNoteRef(ref); };
    if (!c.ev || hidden(c.ev)) return h('a', { href: '#', class: 'quote-mini small', onClick: open },
      t(c.status === 'loading' ? 'noteRefLoading' : 'noteRefLink'));
    const words = plainExcerpt(c.ev.content.replace(/https?:\/\/\S+|nostr:(note|nevent|naddr)1[a-z0-9]+/gi, ' '));
    return h('div', { class: 'quote-mini clickable', onClick: open },
      avatar(c.ev.pubkey, 'chat-avatar mini', false),
      h('span', { class: 'quote-name' }, displayName(c.ev.pubkey)),
      h('span', { class: 'small muted quote-mini-text' }, words || '\u2026'));
  }

  // 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.
  // A picture is fitted inside its box (object-fit: contain), so a tall one
  // leaves blank bands either side. A tap there is a tap on the post — it
  // opens the thread — not on the picture.
  function onPicture(e) {
    const el = e.currentTarget;
    const r = el.getBoundingClientRect();
    const nw = el.naturalWidth, nh = el.naturalHeight;
    if (!nw || !nh || !r.width || !r.height) return true;
    const k = Math.min(r.width / nw, r.height / nh);
    const w = nw * k, hh = nh * k;
    const x = e.clientX - (r.left + (r.width - w) / 2), y = e.clientY - (r.top + (r.height - hh) / 2);
    return x >= 0 && x <= w && y >= 0 && y <= hh;
  }
  function urlNode(url, { label = null, isImage = false } = {}) {
    if (isVideoUrl(url)) {
      return videoNode(url, { stable: !!feedPaint });
    }
    if (AUDIO_RE.test(url)) return audioNode(url, label);
    if (isImage || /\.(png|jpe?g|gif|webp|avif)(\?[^\s]*)?$/i.test(url)) {
      const size = feedPaint ? feedMedia(url) : null;
      if (feedPaint && !size) {
        // a picture that refused to load is a link; one that was merely
        // slow (a 3.5 MB PNG on a phone outran the row's deadline) keeps
        // loading inside a box of fixed shape, so nothing moves when it lands
        if (mediaFailed.has(url)) return h('a', { href: url, target: '_blank', rel: 'noopener noreferrer' }, label || url);
        return h('img', {
          src: url, class: 'note-img note-img-late clickable', loading: 'lazy', decoding: 'async', alt: label || '',
          onClick: (e) => { if (!onPicture(e)) return; e.stopPropagation(); openPicture(url, e); },
          onError: (e) => { e.target.style.display = 'none'; },
        });
      }
      // tap it to see it full size (the feed shows it uncropped, but
      // height-capped: see .note-img)
      const known = size || mediaReady.get(url);
      return h('img', {
        src: mediaSrc(url, known), class: 'note-img clickable', loading: feedPaint || known ? 'eager' : 'lazy', alt: label || '',
        // a few-ms decode of the copy paints with the page; an original never holds the page for its decode
        decoding: known && known.thumb ? 'sync' : 'async',
        width: size?.width, height: size?.height,
        style: size ? 'height:auto;aspect-ratio:' + size.width + '/' + size.height + ';--ar:' + (size.width / size.height).toFixed(4) : undefined,
        onClick: (e) => { if (!onPicture(e)) return; e.stopPropagation(); openPicture(url, e); },
        // 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) => { if (!size) e.target.style.display = 'none'; },
      });
    }
    if (youtubeId(url)) return youtubeEmbed(url, youtubeId(url));
    if (!label && previewable(url)) {
      // a frozen feed row keeps the card (or the bare link) it first painted
      let pv = previews.get(url) || null;
      if (feedPaint) {
        if (!feedPaint.media.has('pv:' + url)) feedPaint.media.set('pv:' + url, pv);
        pv = feedPaint.media.get('pv:' + url);
      }
      if (pv) return linkCard(url, pv);
    }
    const shown = label || (url.length > 64 ? url.slice(0, 61) + '…' : url);
    return h('a', { href: url, target: '_blank', rel: 'noopener noreferrer' }, shown);
  }

  // An audio file (a podcast episode on Blossom, a voice note) as a player,
  // the way Amethyst shows one. Nothing is fetched until play; once playing
  // the box is the listener's and no repaint touches it.
  function audioNode(url, label) {
    let name = label;
    if (!name) {
      try {
        const u = new URL(url);
        const file = decodeURIComponent(u.pathname.split('/').pop() || '');
        // a Blossom name is the file's hash: the host says more than that does
        name = /^[0-9a-f]{64}\./i.test(file) ? u.hostname : file || u.hostname;
      } catch { name = url; }
    }
    return h('div', { class: 'note-audio', onClick: (e) => e.stopPropagation() },
      h('div', { class: 'note-audio-head' },
        h('span', { class: 'note-audio-ico', 'aria-hidden': 'true' }, '\u{1F3A7}'),
        h('a', { href: url, target: '_blank', rel: 'noopener noreferrer', class: 'small muted note-audio-name' }, name)),
      h('audio', {
        onLoadedmetadata: e => attachMediaTimeline(e.target, url),
        controls: true, preload: 'none', src: url,
        onPlay: (e) => { const box = e.target.closest('.note-audio'); if (box) box._skipMorph = true; },
      }));
  }

  // ---- encrypted attachments (NIP-92 imeta + NIP-17 file fields) ----
  // A picture in a Concord channel never reaches the media server in the
  // clear: the sender encrypts it under a one-off key, uploads the blob to
  // Blossom, and puts the pointer in an imeta tag — url, mime, aes-gcm key
  // and nonce, the plaintext's sha256 (ox), a size and dimensions. The bubble
  // used to show nothing for such a message (its content is empty). Now the
  // blob is fetched, decrypted here, checked against the hash, and shown
  // from an object URL. A blob that fails the check fails closed.
  const ATTACH_MAX = 25 * 1024 * 1024;
  const attachCache = new Map(); // url -> { state: 'loading'|'ready'|'error', src, blob }
  const parseImeta = (tag) => {
    const a = { fallback: [] };
    for (const f of tag.slice(1)) {
      const i = f.indexOf(' ');
      if (i < 0) continue;
      const k = f.slice(0, i), v = f.slice(i + 1);
      if (k === 'fallback') a.fallback.push(v); else a[k] = v;
    }
    return a.url ? a : null;
  };
  const attachmentsOf = (rumor) => {
    const out = (rumor.tags || []).filter((t) => t[0] === 'imeta').map(parseImeta).filter(Boolean);
    // a NIP-17 file message: the same fields as flat tags, the url as content
    if (rumor.kind === 15 && /^https?:\/\//.test(rumor.content || '')) {
      const a = { url: rumor.content.trim(), fallback: [] };
      for (const [k, v] of rumor.tags || []) {
        if (k === 'file-type') a.m = v;
        else if (k === 'fallback') a.fallback.push(v);
        else if (['encryption-algorithm', 'decryption-key', 'decryption-nonce', 'ox', 'x', 'size', 'dim', 'name'].includes(k)) a[k] = v;
      }
      out.push(a);
    }
    return out;
  };
  async function loadAttachment(a) {
    const entry = { state: 'loading' };
    attachCache.set(a.key || a.url, entry);
    try {
      if (+a.size > ATTACH_MAX) throw new Error('too big');
      let buf = null;
      for (const url of [a.url, ...a.fallback]) {
        try {
          const res = await fetch(url, { mode: 'cors', signal: AbortSignal.timeout(30_000) });
          if (!res.ok) continue;
          buf = await res.arrayBuffer();
          if (buf.byteLength > ATTACH_MAX) throw new Error('too big');
          break;
        } catch (e) { if (String(e.message).includes('too big')) throw e; }
      }
      if (!buf) throw new Error('unreachable');
      let bytes = new Uint8Array(buf);
      const alg = (a['encryption-algorithm'] || '').toLowerCase();
      if (a.wn) {
        // White Noise: the key is the group's, for the epoch the message came in
        const g = wn && wn.groups.get(a.wn.gid);
        if (!g) throw new Error('group gone');
        bytes = wn.media.open(g, a.wn.epoch, bytes, a.wn.ref);
      } else if (alg) {
        if (alg !== 'aes-gcm' || !a['decryption-key'] || !a['decryption-nonce']) throw new Error('unsupported');
        const key = await crypto.subtle.importKey('raw', hexToBytes(a['decryption-key']), 'AES-GCM', false, ['decrypt']);
        bytes = new Uint8Array(await crypto.subtle.decrypt({ name: 'AES-GCM', iv: hexToBytes(a['decryption-nonce']) }, key, bytes));
      }
      if (a.ox) {
        const digest = bytesToHex(new Uint8Array(await crypto.subtle.digest('SHA-256', bytes)));
        if (digest !== a.ox.toLowerCase()) throw new Error('hash mismatch');
      }
      const blob = new Blob([bytes], { type: a.m || 'application/octet-stream' });
      Object.assign(entry, { state: 'ready', blob, src: URL.createObjectURL(blob) });
    } catch (e) {
      entry.state = 'error';
      console.warn('attachment:', a.url, e.message);
    }
    scheduleRepaint();
  }
  // The nodes for a rumor's attachments: a picture inline (tap to view),
  // any other file as a download by name, a grey box the picture's shape
  // while it loads, and a quiet note when it can't be had.
  // A White Noise message's attachments (encrypted-media-v2): the blob is
  // found by its locators, then by its hash on the usual Blossom hosts.
  const WN_BLOB_HOSTS = ['https://blossom.ditto.pub', 'https://nostr.download', 'https://blossom.primal.net', 'https://blossom.divine.video', 'https://cdn.hzrd149.com'];
  const wnAttachmentsOf = (rumor, gid) => (wn ? (rumor.tags || []).map(wn.media.read).filter(Boolean) : []).map((x) => ({
    key: 'wn:' + x.ref.cipher,
    url: x.urls[0] || WN_BLOB_HOSTS[0] + '/' + x.ref.cipher,
    fallback: [...x.urls.slice(1), ...WN_BLOB_HOSTS.map((u) => u + '/' + x.ref.cipher)].filter((u) => u !== x.urls[0]),
    m: x.ref.m, name: x.ref.name, dim: x.dim,
    wn: { gid, epoch: rumor.epoch, ref: x.ref },
  }));
  // `gid`: the White Noise group the message came through, if it did
  function attachmentNodes(rumor, gid) {
    return (gid ? wnAttachmentsOf(rumor, gid) : attachmentsOf(rumor)).map((a) => {
      const isImg = /^image\//i.test(a.m || '') || /\.(png|jpe?g|gif|webp|avif)$/i.test(a.name || a.url.split('?')[0]);
      const encrypted = !!a['encryption-algorithm'] || !!a.wn;
      if (!encrypted && isImg) return urlNode(a.url, { isImage: true });
      const ck = a.key || a.url;
      let entry = attachCache.get(ck);
      if (!entry && isImg) { loadAttachment(a); entry = attachCache.get(ck); }
      const [w, hgt] = String(a.dim || '').split('x').map(Number);
      const ratio = w > 0 && hgt > 0 ? `${w}/${hgt}` : '4/3';
      if (entry && entry.state === 'ready') {
        if (isImg) return h('img', {
          src: entry.src, class: 'note-img clickable', alt: a.name || '',
          onClick: (e) => { e.stopPropagation(); ctx.openImage && ctx.openImage(entry.src); },
        });
        return h('a', { class: 'chat-attach', href: entry.src, download: a.name || 'file', onClick: (e) => e.stopPropagation() },
          '📎 ' + (a.name || 'file') + (a.size ? ` · ${Math.round(+a.size / 1024)} KB` : ''));
      }
      if (entry && entry.state === 'error') return h('div', { class: 'small muted' }, t('msgAttachFailed'));
      if (!isImg) return h('button', {
        class: 'chat-attach linklike', onClick: (e) => { e.stopPropagation(); if (!attachCache.has(ck)) loadAttachment(a); },
      }, '📎 ' + (a.name || 'file') + (a.size ? ` · ${Math.round(+a.size / 1024)} KB` : ''));
      return h('div', { class: 'chat-attach-ph', style: `aspect-ratio:${ratio}` });
    });
  }

  // ---- sending a picture: encrypt it, put the blob on Blossom, post the
  // pointer. Vector's shape exactly, so its users see it: a fresh AES-GCM
  // key and 16-byte nonce per file, the ciphertext uploaded as an opaque
  // blob, the key riding inside the (already encrypted) message. The media
  // host never sees a picture. coinos's own Blossom server stores only sync
  // envelopes, so these go to the configured media hosts or public defaults.
  const MEDIA_SERVERS = ['https://blossom.ditto.pub', 'https://nostr.download', 'https://blossom.yakihonne.com'];
  const MEDIA_MAX = 20 * 1024 * 1024;
  async function encryptFile(file) {
    if (file.size > MEDIA_MAX) throw new Error(t('msgAttachTooBig'));
    const plain = new Uint8Array(await file.arrayBuffer());
    const key = crypto.getRandomValues(new Uint8Array(32));
    const nonce = crypto.getRandomValues(new Uint8Array(16));
    const k = await crypto.subtle.importKey('raw', key, 'AES-GCM', false, ['encrypt']);
    const cipher = new Uint8Array(await crypto.subtle.encrypt({ name: 'AES-GCM', iv: nonce }, k, plain));
    let dim = '';
    if (/^image\//.test(file.type)) {
      try { const bmp = await createImageBitmap(file); dim = `${bmp.width}x${bmp.height}`; bmp.close(); } catch {}
    }
    return {
      cipher, key: bytesToHex(key), nonce: bytesToHex(nonce), ox: bytesToHex(sha256(plain)), x: bytesToHex(sha256(cipher)),
      m: file.type || 'application/octet-stream', name: file.name || 'file', size: String(cipher.length), dim,
    };
  }
  // BUD-01 upload with a kind-24242 auth signed by whoever is sending.
  async function uploadEncrypted(id, enc) {
    const now = Math.floor(Date.now() / 1000);
    const evt = { kind: 24242, pubkey: id.pubkey, created_at: now - 5, content: 'upload',
      tags: [['t', 'upload'], ['x', enc.x], ['expiration', String(now + 600)]] };
    const auth = id.signer instanceof Uint8Array ? finalizeEvent(evt, id.signer) : await id.signer.signEvent(evt);
    const header = 'Nostr ' + btoa(JSON.stringify(auth));
    const urls = [];
    for (const server of mediaServers(MEDIA_SERVERS)) {
      try {
        const r = await fetch(server + '/upload', {
          method: 'PUT', body: enc.cipher, signal: AbortSignal.timeout(60_000),
          headers: { authorization: header, 'content-type': 'application/octet-stream', 'x-sha-256': enc.x },
        });
        if (!r.ok) continue;
        const j = await r.json();
        if (j && j.url) urls.push(j.url);
      } catch {}
      // one copy is enough for a big file, two for a small one — later hosts are fallbacks
      if (urls.length >= (enc.cipher.length > 4 * 1024 * 1024 ? 1 : 2)) break;
    }
    if (!urls.length) throw new Error(t('msgUploadFailed'));
    return urls;
  }
  const imetaTag = (enc, urls) => ['imeta',
    'url ' + urls[0], 'm ' + enc.m, 'encryption-algorithm aes-gcm', 'decryption-key ' + enc.key, 'decryption-nonce ' + enc.nonce,
    'size ' + enc.size, 'ox ' + enc.ox, 'x ' + enc.x, 'name ' + enc.name, ...(enc.dim ? ['dim ' + enc.dim] : []),
    ...urls.slice(1).map((u) => 'fallback ' + u)];
  // the local copy shows at once, from the plaintext we still hold
  const cacheLocal = (enc, urls, file) => {
    const blob = new Blob([file], { type: enc.m });
    for (const u of urls) attachCache.set(u, { state: 'ready', blob, src: URL.createObjectURL(blob) });
  };
  async function sendAttachment(room, chId, file) {
    const id = await identity();
    if (!id) { noIdToast(); return; }
    ui.msgUploading = true; render();
    try {
      const enc = await encryptFile(file);
      const urls = await uploadEncrypted(id, enc);
      cacheLocal(enc, urls, file);
      const { created_at, ms } = msTags(Date.now());
      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: '',
        tags: [['channel', chId], ['epoch', String(room.chEpoch(chId))], imetaTag(enc, urls), ...(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);
      ui.msgStick = true; ui.msgUploading = false; render();
      const wrap = await wrapRumor(rumor, id.signer, room.chStream(chId));
      seenWraps.add(wrap.id);
      const ok = await publishOn(room.relays, wrap);
      if (!ok) { msgs.delete(rumor.id); toast(t('msgSendFailed')); render(); return; }
      delete entry.pending;
      ensureJoined(room, id).catch(() => {});
      persistCache(room);
    } catch (e) { toast(e.message || String(e)); }
    ui.msgUploading = false; render();
  }
  // A file into a White Noise group (encrypted-media-v2): sealed under the
  // group's media secret for the epoch it goes out in, uploaded, and sent as
  // a kind 9 with an imeta tag. A commit landing during the upload moves the
  // epoch and would leave the key behind it — then it is sealed again.
  // `road`: a group record, or 'new' (a direct chat with `peer` to found).
  async function wnSendFile(road, file, peer) {
    const id = await identity();
    if (!id) { noIdToast(); return; }
    if (file.size > MEDIA_MAX) { toast(t('msgAttachTooBig')); return; }
    ui.msgUploading = true; render();
    try {
      const plain = new Uint8Array(await file.arrayBuffer());
      let dim = '';
      if (/^image\//.test(file.type)) {
        try { const bmp = await createImageBitmap(file); dim = `${bmp.width}x${bmp.height}`; bmp.close(); } catch {}
      }
      const g = road === 'new' ? await wn.create({ members: [peer] }) : road;
      const thread = peer ? threadOf(peer) : null;
      const replyTo = ui.msgReplyTo && (thread ? thread.has(ui.msgReplyTo) : wnFold(g).rows.some((m) => m.rumor.id === ui.msgReplyTo)) ? ui.msgReplyTo : null;
      for (let tries = 0; ; tries++) {
        const sealed = wn.media.seal(g, plain, { type: file.type, name: file.name });
        const urls = await uploadEncrypted(id, { cipher: sealed.cipher, x: sealed.ref.cipher });
        if (g.tip.epoch !== sealed.epoch && tries < 2) continue;
        // the local copy shows at once, from the plaintext we still hold
        const blob = new Blob([file], { type: sealed.ref.m });
        attachCache.set('wn:' + sealed.ref.cipher, { state: 'ready', blob, src: URL.createObjectURL(blob) });
        const inner = wn.event(9, '', [wn.media.tag(sealed.ref, urls, dim), ...(replyTo ? [['e', replyTo]] : [])]);
        ui.msgReplyTo = null;
        if (!(await wn.send(g, inner))) throw new Error(t('msgSendFailed'));
        if (thread) thread.set(inner.id, { rumor: g.log.find((m) => m.id === inner.id) || inner, mine: true, wn: g.id });
        wnFolds.delete(g.id);
        break;
      }
      ui.msgStick = true;
    } catch (e) { toast(e.message === 'no signer' ? t('msgNoIdentity') : (e.message || String(e))); }
    ui.msgUploading = false; render();
  }

  // A DM picture is a NIP-17 kind-15 file message: url as content, the
  // same fields as flat tags, wrapped to the peer and to ourselves.
  async function sendDMFile(peer, file) {
    const id = await identity();
    if (!id) { noIdToast(); return; }
    if (!(id.signer instanceof Uint8Array) && !id.signer.encryptTo) { toast(t('msgSignerNoDm')); return; }
    const road = await wnRoute(peer).catch(() => null);
    if (road) return wnSendFile(road, file, peer);
    ui.msgUploading = true; render();
    try {
      const enc = await encryptFile(file);
      const urls = await uploadEncrypted(id, enc);
      cacheLocal(enc, urls, file);
      const replyTo = ui.msgReplyTo && threadOf(peer).has(ui.msgReplyTo) ? ui.msgReplyTo : null;
      ui.msgReplyTo = null;
      const rumor = rumorWithId({
        kind: 15, pubkey: id.pubkey, content: urls[0], created_at: Math.floor(Date.now() / 1000),
        tags: [['p', peer], ...(replyTo ? [['e', replyTo]] : []),
          ['file-type', enc.m], ['encryption-algorithm', 'aes-gcm'], ['decryption-key', enc.key], ['decryption-nonce', enc.nonce],
          ['x', enc.x], ['ox', enc.ox], ['size', enc.size], ['name', enc.name], ...(enc.dim ? [['dim', enc.dim]] : []),
          ...urls.slice(1).map((u) => ['fallback', u])],
      });
      const entry = { rumor, mine: true, pending: true };
      threadOf(peer).set(rumor.id, entry);
      ui.msgStick = true; ui.msgUploading = false; render();
      const toPeer = await wrapDM(id.signer, peer, rumor);
      const toSelf = await wrapDM(id.signer, id.pubkey, rumor);
      const ok = await publishOn(DM_RELAYS, toPeer);
      publishOn(DM_RELAYS, toSelf);
      toOwnInbox(toSelf);
      fetchInboxRelays(peer).then((inbox) => {
        const extra = inbox.slice(0, 4).filter((r) => !DM_RELAYS.includes(r));
        if (extra.length) publishOn(extra, toPeer, { onauth: relayAuth });
      }).catch(() => {});
      if (!ok) { threadOf(peer).delete(rumor.id); toast(t('msgSendFailed')); render(); return; }
      delete entry.pending;
      persistDms();
    } catch (e) { toast(e.message || String(e)); }
    ui.msgUploading = false; render();
  }

  // `em` is the event's own ["emoji", code, url] map (NIP-30): a :code: it
  // names becomes its picture, any other :code: stays text — a message
  // never borrows pictures from packs the READER happens to hold.
  // Inline markdown in a post's plain text, the subset people actually type
  // and Amethyst already shows: **bold** / __bold__, *italic* / _italic_,
  // ~~struck~~ and `code`. Strict about edges so snake_case, 2*3*4 and a lone
  // asterisk stay as typed; markers never reach across a link, mention or
  // hashtag (those are split out first). No headings or lists in posts —
  // "#" at a line's start is a hashtag here, and articles have their own.
  const MD_INLINE = /(`[^`\n]+`)|(\*\*\*(?=\S)[^\n]*?\S\*\*\*)|(\*\*(?=\S)[^\n]*?\S\*\*)|((?<![\p{L}\p{N}_])__(?=\S)[^\n]*?\S__(?![\p{L}\p{N}_]))|(~~(?=\S)[^\n]*?\S~~)|((?<![\p{L}\p{N}*])\*(?=[^\s*])[^*\n]*?[^\s*]\*(?![\p{L}\p{N}*]))|((?<![\p{L}\p{N}_])_(?=[^\s_])[^_\n]*?[^\s_]_(?![\p{L}\p{N}_]))/u;
  function mdInline(str) {
    const out = [];
    let rest = String(str);
    for (let guard = 0; rest && guard < 200; guard++) {
      const m = MD_INLINE.exec(rest);
      if (!m) { out.push(rest); break; }
      if (m.index) out.push(rest.slice(0, m.index));
      const tok = m[0];
      if (m[1]) out.push(h('code', { class: 'md-code' }, tok.slice(1, -1)));
      else if (m[2]) out.push(h('strong', {}, h('em', {}, ...mdInline(tok.slice(3, -3)))));
      else if (m[3] || m[4]) out.push(h('strong', {}, ...mdInline(tok.slice(2, -2))));
      else if (m[5]) out.push(h('s', {}, ...mdInline(tok.slice(2, -2))));
      else out.push(h('em', {}, ...mdInline(tok.slice(1, -1))));
      rest = rest.slice(m.index + tok.length);
    }
    return out;
  }
  function noteBody(text, depth = 0, em = null) {
    const out = [];
    const emojiAt = em && em.size ? (c) => em.get(c) : null;
    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)) {
        const pack = PACK_LINK_RE.exec(part);
        out.push(pack ? packLinkNode(part, pack[1]) : urlNode(part));
      } else if (/^wss?:\/\//i.test(part)) {
        // a relay named in a post opens what's on it (the raw firehose)
        const [, addr, tail] = /^(.*?)([.,;:!?)\]'"]*)$/.exec(part);
        const relay = normRelay(addr);
        out.push(relay ? h('a', {
          href: '/feed/all?r=' + encodeURIComponent(relay), title: t('relayLinkOpen'),
          onClick: (e) => { e.preventDefault(); e.stopPropagation(); openFeedUrl('all', '?r=' + encodeURIComponent(relay)); },
        }, addr) : addr, tail);
      } else if (/^(nostr:|@?)(npub|nprofile)1/i.test(part)) {
        const bare = part.replace(/^(nostr:|@)/i, '');
        const ref = parseNostrRef(bare);
        if (ref && ref.type === 'pubkey') out.push(h('a', { href: '#', onClick: (e) => { e.preventDefault(); e.stopPropagation(); openProfile(ref.pk); } }, '@' + displayName(ref.pk)));
        else out.push(h('span', { class: 'faint' }, bare.slice(0, 12) + '…'));
      } 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 === 1 ? quoteMini(ref) : 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:naddr1/i.test(part)) {
        const ref = parseNostrRef(part.slice(6));
        if (ref && ref.type === 'addr' && !depth) out.push(addrCard(ref));
        else if (ref && ref.type === 'addr') out.push(h('a', {
          href: '#', onClick: (e) => { e.preventDefault(); e.stopPropagation(); if (ref.kind === LIVE_KIND) { openLiveRef(ref); return; } const c = addrNote(ref); if (c.ev) openNoteThread(c.ev); },
        }, t('noteRefLink')));
        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 if (/^@[A-Za-z0-9_]{2,32}$/.test(part)) {
        out.push(h('a', {
          href: '#', title: t('searchPeopleFor', { q: part.slice(1) }),
          onClick: (e) => { e.preventDefault(); e.stopPropagation(); openPeopleSearch(part.slice(1)); },
        }, part));
      } else if (/^#[A-Za-z0-9_\u00C0-\uFFFF]{2,64}$/.test(part)) {
        out.push(h('a', {
          href: '#', title: t('searchTopicFor', { q: part.slice(1) }),
          onClick: (e) => { e.preventDefault(); e.stopPropagation(); openTopicFeed(part.slice(1)); },
        }, part));
      } else if (emojiAt && part.includes(':')) {
        for (const p of splitEmoji(part, emojiAt)) out.push(...(typeof p === 'string' ? mdInline(p) : [emojiImg(p.code, p.url)]));
      } else out.push(...mdInline(part));
    }
    return out;
  }

  // The header magnifier's search, opened with a name already typed.
  function openPeopleSearch(q) {
    ui.chatOpen = false; ui.profilePk = null; ui.noteThread = null; ui.liveStream = null; ui.goLive = null;
    ui.userSearch = { q, rows: null };
    warmSearch();
    userSearcher.update(q);
    render();
  }

  // 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.
  // Your own posts and messages too: a zap to yourself is a harmless
  // round-trip, and one bar that behaves the same everywhere beats a special case.
  const canZapPk = (pk) => !!pk && !isVisitor() && !!(hook('arkReady') || hook('canLnZap')); // a visitor's tap asks them in instead
  // A locked wallet — the watch-only view of a sealed vault, or an identity
  // signed in over one — has no keys to pay with. The tap says so and opens
  // the Accounts page (the padlock, and the way to add the wallet, are
  // there); the feed is remembered for the way back. It used to do nothing
  // at all: the button pressed, the cursor an arrow.
  function zapLockedAsk() {
    toast('\u{1F512} ' + t('zapLocked'), 4000);
    // the open feed, for the way back: by its URL when it has one, by its
    // id otherwise (Following lives at no address)
    const def = ui.chatOpen && ui.msgView === 'feed' ? feedDef() : null;
    const back = def ? feedPath(def) || 'feed:' + def.id : null;
    try { sessionStorage.setItem(RETURN_KEY, back || location.pathname + location.search); } catch {}
    ui.screen = 'accounts';
    render();
  }
  function zapNote(pk, ev, origin, moment = null) {
    const npubStr = npubOf(pk);
    const def = ctx.zapDefaultSat ? ctx.zapDefaultSat() : 0;
    if (!def) { // the first tap ever sets the amount; the reader's place is kept for the way back
      let scrollY = 0; try { scrollY = window.scrollY || 0; } catch {}
      ui.zapSetup = { pk, npub: npubStr, eventId: ev.id, amount: '21', origin, scrollY, moment }; render(); return;
    }
    markZapPending(ev.id, def, origin); // strike now; settlement only corrects the tally
    if (!hook('zapNpub', pk, npubStr, ev.id, def, moment) && !hook('lnZapNpub', pk, npubStr, ev.id, def, moment)) {
      settleZap(ev.id, false);
      toast('⚡ ' + t('lnZapFailed'), 4000);
    }
  }

  // Held ⚡: the same screen, opened to change the amount — saving alone is
  // the main action, zapping this note with the new amount the second.
  function openZapSettings(pk, id, origin) {
    const cur = ctx.zapDefaultSat ? ctx.zapDefaultSat() : 0;
    let scrollY = 0; try { scrollY = window.scrollY || 0; } catch {}
    // the reader's place in the feed, to return to: the settings screen
    // replaces the page, and the page comes back at its top otherwise
    ui.zapSetup = { pk, npub: npubOf(pk), eventId: id, amount: String(cur || 21), origin, edit: true, sound: zapSoundOn(), scrollY };
    render();
  }
  // Leave the zap settings the way they were opened: the page repaints,
  // then the window is put back where the reader was (the feed's windowing
  // mounts the rows for that place on the scroll).
  function closeZapSetup() {
    const y = ui.zapSetup && ui.zapSetup.scrollY;
    ui.zapSetup = null;
    render();
    if (y) { try { window.scrollTo(0, y); } catch {} }
  }

  // First ⚡ tap ever: pick the amount one time, then every zap is one tap.
  function zapSetupScreen() {
    const s = ui.zapSetup;
    const saved = () => {
      const n = parseInt(s.amount, 10);
      if (!n || n <= 0) { toast(t('enterValidAmtForN', { n: 1 })); return 0; }
      ctx.setZapDefaultSat(n);
      if (s.edit && ctx.setZapSound && s.sound !== zapSoundOn()) ctx.setZapSound(s.sound);
      return n;
    };
    const saveAndZap = () => {
      const n = saved();
      if (!n) return;
      const { pk, npub, eventId } = s;
      closeZapSetup();
      markZapPending(eventId, n, s.origin);
      if (!hook('zapNpub', pk, npub, eventId, n, s.moment) && !hook('lnZapNpub', pk, npub, eventId, n, s.moment)) {
        settleZap(eventId, false);
        toast('⚡ ' + t('lnZapFailed'), 4000);
      }
      recheckZap(eventId);
    };
    const saveOnly = () => {
      const n = saved();
      if (!n) return;
      toast('⚡ ' + t('zapAmountSaved', { n: n.toLocaleString() }));
      closeZapSetup();
    };
    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(s.edit ? 'zapSettingsDesc' : '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')),
        s.edit ? h('label', { class: 'row gap6', style: 'align-items:center;cursor:pointer' },
          h('input', { type: 'checkbox', checked: s.sound, style: 'width:18px;height:18px;accent-color:var(--accent);margin:0', onChange: (e) => { s.sound = e.target.checked; } }),
          h('span', { class: 'small' }, t('zapSoundToggle'))) : null,
        s.edit
          ? [h('button', { class: 'btn-primary btn-block', onClick: saveOnly }, t('save')),
            h('button', { class: 'btn-ghost btn-block', onClick: saveAndZap }, t('zapSetupSave'))]
          : h('button', { class: 'btn-primary btn-block', onClick: saveAndZap }, t('zapSetupSave'))),
      h('button', { class: 'btn-ghost btn-block', onClick: closeZapSetup }, 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 reaction of m.values()) for (const pk of mine) if (reaction.who.has(pk)) return reaction;
    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, moment = null) {
    // the post opened from a clip as it played: a reply to it is about that moment
    const offered = ui.noteThread && ui.noteThread.momentFor;
    if (!moment && offered && offered.id === ev.id) moment = offered.moment;
    if (ui.noteThread && ui.noteThread.rootId === rootIdOf(ev)) {
      ui.noteThread.focusId = ev.id;
      ui.noteThread.seed = ev;
    } else ui.noteThread = { rootId: rootIdOf(ev), focusId: ev.id, seed: ev };
    const s = ui.noteThread;
    ui.profOverThread = false;
    s.mediaMoment = moment;
    s.replying = true; // the box appears under this note
    s.scrollPending = false; // focus the composer, without a competing note scroll
    s.refocus = true;
    render();
    // Focus in the tap handler so mobile browsers can open the keyboard.
    focusThreadReply(s);
  }
  function focusThreadReply(s) {
    if (ui.noteThread !== s || ui.profOverThread) return;
    const input = document.querySelector('.thread-reply-input');
    if (!input) return;
    input.focus({ preventScroll: true });
    input.scrollIntoView({ block: 'nearest' });
  }

  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 [key, { who }] of [...m]) { for (const pk of myPubkeys()) who.delete(pk); if (!who.size) m.delete(key); }
      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).
  // ---- polls (NIP-88) -------------------------------------------------------
  // A kind 1068 poll is its question (content) plus ["option", id, label]
  // tags; votes are kind 1018 events e-tagging it with ["response", id].
  // Each person's LATEST vote counts (one option unless the poll says
  // "multiplechoice"), and nothing cast after its endsAt.
  const POLL = 1068, POLL_VOTE = 1018;
  const pollOptions = (ev) => ev.tags.filter((x) => x[0] === 'option' && x[1] != null && x[2])
    .map((x) => ({ id: String(x[1]), label: String(x[2]) }));
  const pollMulti = (ev) => (ev.tags.find((x) => x[0] === 'polltype') || [])[1] === 'multiplechoice';
  const pollEnds = (ev) => { const v = Number((ev.tags.find((x) => x[0] === 'endsAt') || [])[1]); return Number.isFinite(v) && v > 0 ? v : 0; };
  const pollEnded = (ev) => !!pollEnds(ev) && Date.now() / 1000 > pollEnds(ev);
  const pollRelays = async (ev) => [...new Set([
    ...ev.tags.filter((x) => x[0] === 'relay' && /^wss?:\/\//i.test(x[1] || '')).map((x) => x[1]),
    ...(await noteRelaysFor(ev).catch(() => zapRelays())),
  ])].slice(0, 12);
  const pollVotes = new Map(); // poll id -> { at, loaded, loading, by: Map(pk -> { t, ids }) }
  function pollState(ev) {
    let st = pollVotes.get(ev.id);
    if (!st) { st = { at: 0, loaded: false, loading: false, by: new Map() }; pollVotes.set(ev.id, st); }
    return st;
  }
  function pollCount(poll, v) {
    const st = pollState(poll);
    const ends = pollEnds(poll);
    if (ends && v.created_at > ends) return;
    const prev = st.by.get(v.pubkey);
    if (prev && prev.t >= v.created_at) return;
    const valid = new Set(pollOptions(poll).map((o) => o.id));
    let ids = [...new Set(v.tags.filter((x) => x[0] === 'response').map((x) => String(x[1])))].filter((id) => valid.has(id));
    if (!pollMulti(poll)) ids = ids.slice(0, 1);
    st.by.set(v.pubkey, { t: v.created_at, ids });
  }
  // Votes are asked for when a poll is painted, and again a minute on.
  function pollTally(ev) {
    const st = pollState(ev);
    if (!st.loading && Date.now() - st.at > 60_000) {
      st.loading = true; st.at = Date.now();
      (async () => {
        const evs = await queryOn(await pollRelays(ev), { kinds: [POLL_VOTE], '#e': [ev.id], limit: 1000 }, 5000).catch(() => []);
        for (const v of evs || []) if (v.kind === POLL_VOTE) pollCount(ev, v);
      })().finally(() => { st.loading = false; st.loaded = true; scheduleRepaint(); });
    }
    return st;
  }
  async function votePoll(poll, optId) {
    if (pollEnded(poll)) return;
    const id = await requireIdentity();
    const st = pollState(poll);
    const prev = st.by.get(id.pubkey);
    const mine = prev?.ids || [];
    const ids = pollMulti(poll) ? (mine.includes(optId) ? mine.filter((x) => x !== optId) : [...mine, optId]) : [optId];
    if (!pollMulti(poll) && mine[0] === optId) return;
    const partial = {
      kind: POLL_VOTE, content: '',
      // strictly newer than our last vote, or relays and counters keep the old one
      created_at: Math.max(Math.floor(Date.now() / 1000), (prev?.t || 0) + 1),
      tags: [['e', poll.id], ['p', poll.pubkey], ...ids.map((x) => ['response', x]), CLIENT_TAG],
    };
    const evt = id.signer instanceof Uint8Array ? finalizeEvent(partial, id.signer) : await id.signer.signEvent(partial);
    pollCount(poll, evt); // counted on screen before the relays answer
    render();
    const ok = await publishOn(await pollRelays(poll), evt).catch(() => false);
    if (!ok) toast(t('msgSendFailed'));
  }
  // The options as rows with their share of the vote. In a quote card
  // (`interactive` off) they are a picture of the poll — the tap opens it.
  function pollBox(ev, { interactive = true } = {}) {
    const opts = pollOptions(ev);
    if (!opts.length) return null;
    const st = pollTally(ev);
    const counts = new Map(opts.map((o) => [o.id, 0]));
    let voters = 0;
    for (const v of st.by.values()) {
      if (!v.ids.length) continue;
      voters++;
      for (const x of v.ids) counts.set(x, (counts.get(x) || 0) + 1);
    }
    const mine = new Set(myPubkeys().flatMap((pk) => st.by.get(pk)?.ids || []));
    const ended = pollEnded(ev);
    const canVote = interactive && !ended;
    const shown = st.loaded || voters > 0;
    const foot = [
      shown ? t(voters === 1 ? 'pollVoter' : 'pollVoters', { n: voters }) : null,
      pollMulti(ev) ? t('pollMulti') : null,
      ended ? t('pollEnded') : pollEnds(ev) ? t('pollEndsAt', { when: new Date(pollEnds(ev) * 1000).toLocaleString([], { dateStyle: 'medium', timeStyle: 'short' }) }) : null,
    ].filter(Boolean).join(' \u00b7 ');
    return h('div', { class: 'poll' },
      ...opts.map((o) => {
        const n = counts.get(o.id) || 0;
        const pct = voters ? Math.round((n / voters) * 100) : 0;
        return h(canVote ? 'button' : 'div', {
          class: 'poll-opt' + (mine.has(o.id) ? ' mine' : '') + (canVote ? '' : ' static'),
          type: canVote ? 'button' : undefined,
          onClick: canVote ? (e) => { e.stopPropagation(); votePoll(ev, o.id).catch(() => {}); } : undefined,
        },
          h('span', { class: 'poll-bar', style: 'width:' + (shown ? pct : 0) + '%' }),
          h('span', { class: 'poll-label' }, (mine.has(o.id) ? '\u2713 ' : '') + o.label),
          shown ? h('span', { class: 'poll-pct' }, pct + '%') : null);
      }),
      foot ? h('div', { class: 'small faint poll-foot' }, foot) : null);
  }

  async function reactTo(ev, emoji) {
    const id = await requireIdentity();
    const partial = {
      kind: 7, content: emoji || '❤️', created_at: Math.floor(Date.now() / 1000),
      tags: [['e', ev.id], ['p', ev.pubkey], ...momentTags(ev.mediaMoment), ...reactEmojiTags(emoji), 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();
    // (the author's relay list can take seconds to find: it isn't needed to paint)
    publishOn(await noteRelaysFor(ev), 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.liveStream = null; ui.goLive = null;
    ui.profilePk = null;
    ui.chatOpen = true;
    ui.msgView = 'feed';
    feedNow();
    render();
    setTimeout(() => { const el = document.querySelector('.chat-page coinos-text'); 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, words, hashtags, threads, tags, priv, content, at }
  let mutesAt = 0;
  // Everything a mute list holds (NIP-51): people, words, hashtags, whole
  // threads — public tags and the private half (nip44 to yourself) alike.
  const muteSets = (tags) => ({
    set: new Set(pTags(tags).map((x) => x[1])),
    words: [...new Set(tags.filter((x) => x[0] === 'word' && x[1]).map((x) => String(x[1]).toLowerCase().trim()).filter(Boolean))],
    hashtags: new Set(tags.filter((x) => x[0] === 't' && x[1]).map((x) => normTopic(x[1])).filter(Boolean)),
    threads: new Set(tags.filter((x) => x[0] === 'e' && /^[0-9a-f]{64}$/.test(x[1] || '')).map((x) => x[1])),
  });
  const withSets = (m) => ({ ...m, priv: m.priv || [], ...muteSets([...(m.tags || []), ...(m.priv || [])]) });
  function mutesNow() {
    if (!mutes) {
      let st2 = null;
      try { st2 = wallet.loadFeatureState(MUTES, null); } catch {}
      mutes = withSets({ tags: (st2 && st2.tags) || [], priv: (st2 && st2.priv) || [], content: (st2 && st2.c) || '', at: (st2 && st2.at) || 0 });
    }
    return mutes;
  }
  const isMuted = (pk) => mutesNow().set.has(pk);
  function saveMutes(m) {
    mutes = withSets(m);
    try { wallet.saveFeatureState(MUTES, { tags: mutes.tags, priv: mutes.priv, c: mutes.content, at: mutes.at }); } catch {}
  }
  // The private half of a list: nip44 to yourself, a JSON array of tags.
  async function privateTagsOf(ev) {
    if (!ev || !ev.content) return [];
    const c = (await selfCryptors()).find((x) => x.pk === ev.pubkey);
    if (!c) return [];
    try {
      const tags = JSON.parse(await c.dec(ev.content));
      return Array.isArray(tags) ? tags.filter((x) => Array.isArray(x) && x[0] && x[1]) : [];
    } catch { return []; } // nip04 from an older client, or not ours to read
  }
  async function syncMutes({ force = false, deep = false } = {}) {
    const me = mePk();
    if (!me) return mutesNow();
    if (!force && Date.now() - mutesAt < 10 * 60_000) return mutesNow();
    mutesAt = Date.now();
    try {
      // replaceable like the follow list: never written over one we haven't
      // looked for everywhere (see deepContactList)
      const relays = deep
        ? [...new Set([...zapRelays(), ...PROFILE_INDEX_RELAYS, ...PROFILE_ARCHIVE_RELAYS, ...(await relaysOf(me).catch(() => []))])]
        : zapRelays();
      const evs = await queryOn(relays, { kinds: [10000], authors: [me] }, deep ? 7000 : 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({ tags: newest.tags || [], priv: await privateTagsOf(newest), content: newest.content || '', at: newest.created_at });
        scheduleRepaint();
      }
    } catch { mutesAt = 0; }
    return mutesNow();
  }
  // Same care as the follow list: a change is applied to the freshest copy
  // the relays will give us (the note in toggleFollow), never to our own
  // optimistic paint. The private half is re-encrypted only when the change
  // touched it and we hold the key; otherwise it rides along untouched.
  async function updateMutes(change) {
    const id = await requireIdentity();
    const before = mutesNow();
    const paint = change(before);
    if (!paint) return;
    saveMutes({ ...before, ...paint });
    render();
    try {
      await syncMutes({ force: true, deep: !before.at });
      const fetched = mutesNow();
      const base = fetched.at > before.at ? fetched : before;
      const next = change(base) || {};
      const tags = next.tags || base.tags;
      const priv = next.priv || base.priv || [];
      let content = base.content || '';
      if (next.priv && JSON.stringify(next.priv) !== JSON.stringify(base.priv || [])) {
        const c = (await selfCryptors()).find((x) => x.pk === id.pubkey);
        if (c) content = priv.length ? await c.enc(JSON.stringify(priv)) : '';
      }
      const created_at = Math.max(Math.floor(Date.now() / 1000), base.at + 1);
      const partial = { kind: 10000, 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({ tags, priv, content, at: created_at });
      render();
    } catch (e) {
      saveMutes(before);
      if (!(e instanceof NoIdentity)) toast(e.message || String(e));
      render();
      throw e;
    }
  }
  const tagIn = (tags, k, v) => (tags || []).some((x) => x[0] === k && x[1] === v);
  const tagOut = (tags, k, v) => (tags || []).filter((x) => !(x[0] === k && x[1] === v));
  // One entry in or out (want: true/false, or null to flip), both halves.
  const muteToggle = (k, v, want = null) => (m) => {
    const has = tagIn(m.tags, k, v) || tagIn(m.priv, k, v);
    const on = want == null ? !has : want;
    if (on === has) return null;
    return on ? { tags: [...m.tags, [k, v]] } : { tags: tagOut(m.tags, k, v), priv: tagOut(m.priv, k, v) };
  };
  async function toggleMute(pk, { block = false } = {}) {
    const id = await requireIdentity();
    if (pk === id.pubkey) return;
    const had = isMuted(pk);
    try {
      await updateMutes(muteToggle('p', pk));
      if (block && !had && isFollowing(pk)) await toggleFollow(pk);
      toast(had ? t('postUnmuted') : block ? t('postBlocked') : t('postMuted'));
    } catch {}
  }
  const toggleMuteThread = (rootId) => updateMutes(muteToggle('e', rootId)).catch(() => {});
  const toggleMuteWord = (word, want = null) => updateMutes(muteToggle('word', String(word || '').trim().toLowerCase(), want)).catch(() => {});
  const toggleMuteTag = (tag, want = null) => updateMutes(muteToggle('t', normTopic(tag), want)).catch(() => {});

  // ---- moderation: one door for everything that shows a post --------------
  // hiddenWhy(ev) says why a post is not shown (or null); hiddenPk(pk) the
  // same for a person (their zaps, reactions, DMs, chat). Every list in this
  // file asks here: the feed, threads, notifications, the who-reacted panel,
  // rooms, DMs, quote cards. Two rules are Amethyst's, and are what makes
  // its feeds feel clean: repeated content from strangers is spam, and a
  // post your follows reported is folded (not hidden) behind who said so.
  // Per row per check; the cached copy serves (a Settings toggle writes
  // through save(), which refreshes it) rather than re-parsing the blob
  // every 50 ms through a long render.
  const modOn = (k) => ((stCache || st()).mod || {})[k] !== false;
  // ---- sensitive posts (NIP-36 content warnings, NSFW accounts) -------------
  // A post its author marked sensitive carries a content-warning tag — what a
  // Misskey artist's "sensitive" media becomes on the mostr bridge, and what
  // Amethyst and Damus put on a CW'd note. Popular, shown to anyone, leaves
  // such posts out, and the posts of accounts whose own profile says they're
  // adult or NSFW (":role_nsfw:", "🔞", "R18", "成人向け"…); elsewhere a marked
  // post is folded behind its warning with a Show, as NIP-36 asks.
  const NSFW_TAG = /^(nsfw|porn|porno|r18|r-18|18\+|nude|nudes|nudity|hentai|lewd|onlyfans|xxx|adult|エロ|成人向け|r18g)$/i;
  const NSFW_TEXT = /:nsfw:|:role_nsfw:|🔞|(^|\s)#(nsfw|porn|r18|hentai|lewd)\b/i;
  const NSFW_PROFILE = /(^|[^a-z])nsfw([^a-z]|$)|:role_nsfw:|🔞|(^|[^a-z0-9])r-?18(g)?([^0-9]|$)|(^|[^0-9])18\+|成人向け|アダルト|エロ|porn|onlyfans|fansly|hentai|(^|[^a-z])lewd/i;
  // the post's own warning: its reason (possibly ''), or null when unmarked
  function sensitiveWhy(ev) {
    if (!ev || !ev.tags) return null;
    const cw = ev.tags.find((x) => x[0] === 'content-warning');
    if (cw) return cw[1] || '';
    // NIP-32 labels in the content-warning namespace, and NSFW topics
    if (ev.tags.some((x) => (x[0] === 'l' && /^(content-warning|nsfw)$/i.test(x[2] || '')) || (x[0] === 't' && NSFW_TAG.test(x[1] || '')))) return '';
    if (NSFW_TEXT.test(String(ev.content || ''))) return '';
    return null;
  }
  const nsfwAuthor = (pk) => { const p = profiles.get(pk); return !!p && NSFW_PROFILE.test((p.name || '') + ' ' + (p.about || '')); };
  // left out of the public feed (and of every media grid): marked, or by an
  // account that says it posts adult work
  const notForPublic = (ev) => !isMe(ev.pubkey) && (sensitiveWhy(ev) !== null || nsfwAuthor(ev.pubkey));
  function sensitiveFold(ev, why) {
    return h('div', { class: 'row note-folded', style: 'gap:10px;align-items:center;padding:10px 0;opacity:.75' },
      avatar(ev.pubkey, 'chat-avatar note-avatar', false),
      h('div', { class: 'grow small muted', style: 'min-width:0' }, '\u26a0 ' + (why ? t('foldSensitiveWhy', { why: why.slice(0, 80) }) : t('foldSensitive'))),
      h('button', {
        class: 'btn-sm', type: 'button', style: 'flex-shrink:0',
        onClick: (e) => { e.stopPropagation(); (ui.revealed ||= new Set()).add(ev.id); render(); },
      }, t('foldShow')));
  }
  const setMod = (k, v) => { const s = st(); (s.mod ||= {})[k] = v; save(s); render(); };
  // A post of 60+ characters seen again under another id is a duplicate;
  // five duplicates and the author is hidden for the session. Short posts
  // ("GM") and nostr:-mention commands are exempt. Session memory only.
  const spamSeen = new Map(); // content+tags -> first id
  const spamDup = new Set(); // ids that were repeats
  const spamBy = new Map(); // pk -> Set of repeated ids
  function noteForSpam(ev) {
    if (!ev || ev.kind !== 1 || !ev.id || ev.pending) return;
    const c = String(ev.content || '');
    if (c.length < 60) return;
    if (c.length < 180 && c.startsWith('nostr:')) return;
    const key = c + '\u0000' + JSON.stringify(ev.tags || []);
    const first = spamSeen.get(key);
    if (!first) {
      spamSeen.set(key, ev.id);
      if (spamSeen.size > 3000) spamSeen.delete(spamSeen.keys().next().value);
      return;
    }
    if (first === ev.id) return;
    spamDup.add(ev.id);
    const s = spamBy.get(ev.pubkey) || spamBy.set(ev.pubkey, new Set()).get(ev.pubkey);
    s.add(first); s.add(ev.id);
  }
  const SPAM_DUPES = 5;
  const isSpammer = (pk) => modOn('spam') && (spamBy.get(pk) || { size: 0 }).size >= SPAM_DUPES && !trusted(pk) && !isMe(pk);
  const HASHTAG_MAX = 10;
  const hashtagSpam = (ev) => ev.kind === 1 && modOn('spam') && !isFollowing(ev.pubkey)
    && ((ev.tags || []).filter((x) => x[0] === 't').length > HASHTAG_MAX
      || (String(ev.content || '').match(/(^|\s)#[\p{L}\p{N}_]{2,}/gu) || []).length > HASHTAG_MAX);
  function hiddenWhy(ev) {
    if (isDeleted(ev)) return 'deleted'; // by its author, yours included
    if (!ev || !ev.pubkey || isMe(ev.pubkey)) return null;
    const bm = baselineMutes();
    for (const m of bm ? [mutesNow(), bm] : [mutesNow()]) {
      if (m.set.has(ev.pubkey)) return 'muted';
      if (ev.kind !== 1) continue;
      if (m.threads.size && m.threads.has(rootIdOf(ev))) return 'thread';
      const text = String(ev.content || '').toLowerCase();
      if (m.words.length && m.words.some((w) => text.includes(w))) return 'word';
      if (m.hashtags.size) {
        if ((ev.tags || []).some((x) => x[0] === 't' && m.hashtags.has(normTopic(x[1])))) return 'hashtag';
        for (const mm of text.matchAll(/#([\p{L}\p{N}_]+)/gu)) if (m.hashtags.has(normTopic(mm[1]))) return 'hashtag';
      }
    }
    if (reportsNow().mine.has(ev.id)) return 'reported';
    if (!trusted(ev.pubkey)) {
      if (isSpammer(ev.pubkey) || (modOn('spam') && spamDup.has(ev.id))) return 'spam';
      if (hashtagSpam(ev)) return 'hashtags';
    }
    return null;
  }
  const hidden = (ev) => !!hiddenWhy(ev);
  const hiddenPk = (pk) => !!pk && !isMe(pk) && (isMuted(pk) || (baselineMutes() || { set: new Set() }).set.has(pk) || isSpammer(pk) || reportsNow().mine.has(pk));
  const visiblePks = (pks) => [...(pks || [])].filter((pk) => !hiddenPk(pk));

  // ---- reports (NIP-56 kind 1984) from the people you follow --------------
  // The web-of-trust piece — not a score from a provider, just your follows'
  // own flags, read from their outbox relays and ours once every half hour,
  // indexed by post and by person. A post (or its author) flagged by anyone
  // you follow is folded; anything you flagged yourself is hidden.
  const REPORTS = 'reports';
  let reportsCache = null; // { ev: Map id -> Set reporter, pk: Map pk -> Set reporter, mine: Set, at }
  let reportsAt = 0;
  function reportsNow() {
    if (!reportsCache) {
      let s = null;
      try { s = wallet.loadFeatureState(REPORTS, null); } catch {}
      const toMap = (o) => new Map(Object.entries(o || {}).map(([k, v]) => [k, new Set(v)]));
      reportsCache = { ev: toMap(s && s.ev), pk: toMap(s && s.pk), mine: new Set((s && s.mine) || []), at: (s && s.at) || 0 };
    }
    return reportsCache;
  }
  function saveReports() {
    const r = reportsNow();
    const toObj = (m) => Object.fromEntries([...m.entries()].slice(-1500).map(([k, v]) => [k, [...v].slice(0, 50)]));
    try { wallet.saveFeatureState(REPORTS, { ev: toObj(r.ev), pk: toObj(r.pk), mine: [...r.mine].slice(-500), at: r.at }); } catch {}
  }
  // A report typed 'other' says nothing anyone can act on and is ignored.
  function noteReport(ev) { indexReport(reportsNow(), ev, myPubkeys().includes(ev.pubkey)); }
  function indexReport(r, ev, mine) {
    const hex = (v) => /^[0-9a-f]{64}$/.test(v || '');
    let es = 0;
    for (const x of ev.tags || []) {
      if (x[0] !== 'e' || !hex(x[1]) || x[2] === 'other') continue;
      es++;
      (r.ev.get(x[1]) || r.ev.set(x[1], new Set()).get(x[1])).add(ev.pubkey);
      if (mine) r.mine.add(x[1]);
    }
    for (const x of ev.tags || []) {
      // a PERSON is reported when the p tag carries a reason, or when the
      // report names no post at all; a post report's p tag merely credits
      // the author and is not held against them
      if (x[0] !== 'p' || !hex(x[1]) || x[1] === ev.pubkey || (es && !x[2]) || x[2] === 'other') continue;
      (r.pk.get(x[1]) || r.pk.set(x[1], new Set()).get(x[1])).add(ev.pubkey);
      if (mine) r.mine.add(x[1]);
    }
  }
  const REPORTS_MS = 30 * 60_000;
  async function syncReports({ force = false } = {}) {
    if (!modOn('reports') || !myPubkeys().length) return;
    if (!force && Date.now() - reportsAt < REPORTS_MS) return;
    reportsAt = Date.now();
    const authors = [...new Set([...myPubkeys(), ...followsNow().set])].slice(0, FEED_AUTHORS_MAX);
    const from = new Set(authors);
    try {
      await fetchRelayLists(authors);
      const plan = outboxPlan(authors);
      const got = 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((chunk) => queryOn(relays, { kinds: [1984], authors: chunk, limit: 500 }, 5000).catch(() => []));
      }));
      for (const ev of got.flat()) if (ev && ev.kind === 1984 && from.has(ev.pubkey)) noteReport(ev);
      reportsNow().at = Date.now();
      saveReports();
      scheduleRepaint();
    } catch { reportsAt = 0; }
  }
  // Who among your follows flagged this post or its author.
  // A flag on THIS post from one follow folds it. A flag on the PERSON
  // folds everything they write, so it takes two follows to agree — one
  // mis-tapped "impersonation" on a well-known key used to fold their whole
  // timeline for everyone who followed the tapper.
  // ---- a reader with no web of trust borrows coinos's -------------------
  // A visitor, or a wallet that follows almost nobody yet, has no follows
  // whose flags could fold anything (and a visitor no mute list at all), so
  // the public feeds would show the relays raw. They get the moderation the
  // coinos account gets: its mute list (visitors) and its follows' reports,
  // read from the relays every few hours and kept on the device for every
  // wallet. A wallet's own mutes always count too.
  const CURATOR_PK = '98ae4da926c471c23fd12d1ebdd5839ba82917baa618e184e0c9916d93dcf4f7';
  const BASELINE_KEY = 'coinos-mod-baseline';
  const BASELINE_MS = 6 * 3600_000;
  const BASELINE_MIN_FOLLOWS = 5;
  let baseline = null; // { follows: Set, mutes (withSets), ev: Map, pk: Map, mine: Set, at }
  let baselineSync = null;
  function baselineNow() {
    if (!baseline) {
      let b = null;
      try { b = JSON.parse(cacheStorage.getItem(BASELINE_KEY) || 'null'); } catch {}
      const toMap = (o) => new Map(Object.entries(o || {}).map(([k, v]) => [k, new Set(v)]));
      baseline = { follows: new Set((b && b.follows) || []), mutes: withSets({ tags: (b && b.mutes) || [], priv: [], content: '', at: 0 }),
        ev: toMap(b && b.ev), pk: toMap(b && b.pk), mine: new Set(), at: (b && b.at) || 0 };
    }
    return baseline;
  }
  const usingBaseline = () => !mePk() || followsNow().set.size < BASELINE_MIN_FOLLOWS;
  const baselineMutes = () => (mePk() ? null : baselineNow().mutes);
  // someone a web of trust vouches for (the reader's own, or the borrowed
  // one while their own is thin): exempt from the heuristics
  const trusted = (pk) => isFollowing(pk) || (usingBaseline() && baselineNow().follows.has(pk));
  async function syncBaseline() {
    const b = baselineNow();
    if (baselineSync || Date.now() - b.at < BASELINE_MS) return baselineSync;
    baselineSync = (async () => {
      try {
        const evs = await queryOn(zapRelays(), { kinds: [3, 10000], authors: [CURATOR_PK] }, 6000).catch(() => []);
        const newest = (k) => (evs || []).filter((e) => e.kind === k).sort((x, y) => y.created_at - x.created_at)[0];
        const k3 = newest(3), k10 = newest(10000);
        if (!k3) return; // the relays were away: keep what we have, ask again soon
        const follows = hexList(k3.tags.filter((x) => x[0] === 'p').map((x) => x[1]));
        const muteTags = k10 ? (k10.tags || []).filter((x) => ['p', 't', 'word', 'e'].includes(x[0])).slice(0, 2000) : b.mutes.tags;
        const authors = [CURATOR_PK, ...follows].slice(0, FEED_AUTHORS_MAX);
        const from = new Set(authors);
        const r = { ev: new Map(), pk: new Map(), mine: new Set() };
        await fetchRelayLists(authors);
        const got = await Promise.all(outboxPlan(authors).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((chunk) => queryOn(relays, { kinds: [1984], authors: chunk, limit: 500 }, 5000).catch(() => []));
        }));
        for (const ev of got.flat()) if (ev && ev.kind === 1984 && from.has(ev.pubkey)) indexReport(r, ev, false);
        baseline = { follows: new Set(follows), mutes: withSets({ tags: muteTags, priv: [], content: '', at: k10 ? k10.created_at : 0 }), ev: r.ev, pk: r.pk, mine: new Set(), at: Date.now() };
        const toObj = (m) => Object.fromEntries([...m.entries()].slice(-1500).map(([k, v]) => [k, [...v].slice(0, 50)]));
        try { cacheStorage.setItem(BASELINE_KEY, JSON.stringify({ follows, mutes: muteTags, ev: toObj(r.ev), pk: toObj(r.pk), at: baseline.at })); } catch {}
        scheduleRepaint();
      } catch {} finally { baselineSync = null; }
    })();
    return baselineSync;
  }
  const PERSON_REPORTS_MIN = 2;
  function reportsOn(ev) {
    if (!ev || !ev.id || !modOn('reports') || isMe(ev.pubkey)) return null;
    const flagsFrom = (r, f) => {
      const onPost = new Set(), onPerson = new Set();
      for (const pk of r.ev.get(ev.id) || []) if (f.has(pk) && pk !== ev.pubkey) onPost.add(pk);
      for (const pk of r.pk.get(ev.pubkey) || []) if (f.has(pk) && pk !== ev.pubkey) onPerson.add(pk);
      if (!onPost.size && onPerson.size < PERSON_REPORTS_MIN) return null;
      return [...new Set([...onPost, ...onPerson])];
    };
    const own = mePk() ? flagsFrom(reportsNow(), followsNow().set) : null;
    if (own) return own;
    if (!usingBaseline()) return null;
    const b = baselineNow();
    return flagsFrom(b, b.follows);
  }
  // A flagged post, folded: who flagged it, and a tap to see it anyway.
  function foldedRow(ev, by) {
    for (const pk of by.slice(0, 3)) profileOf(pk);
    const who = by.length === 1 ? t('foldReported1', { name: displayName(by[0]) }) : t('foldReportedN', { n: by.length });
    return h('div', { class: 'row note-folded', style: 'gap:10px;align-items:center;padding:10px 0;opacity:.75' },
      avatar(ev.pubkey, 'chat-avatar note-avatar', false),
      h('div', { class: 'grow small muted', style: 'min-width:0' }, '\u26a0 ' + who),
      h('button', {
        class: 'btn-sm', type: 'button', style: 'flex-shrink:0',
        onClick: (e) => { e.stopPropagation(); (ui.revealed ||= new Set()).add(ev.id); render(); },
      }, t('foldShow')));
  }
  // Publish a report (NIP-56): the post with a reason, its author credited.
  async function reportNote(ev, type) {
    const id = await requireIdentity();
    const partial = { kind: 1984, content: '', created_at: Math.floor(Date.now() / 1000), tags: [['e', ev.id, type], ['p', ev.pubkey]] };
    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'));
    noteReport(evt);
    saveReports();
    toast(t('reportSent'));
    render();
  }
  function reportSheet() {
    if (!ui.reportPick) return null;
    const ev = ui.reportPick;
    const close = () => { ui.reportPick = null; render(); };
    const reason = (type, label) => h('button', {
      class: 'btn-block report-reason', style: 'text-align:left', type: 'button', 'data-reason': type,
      onClick: () => { close(); reportNote(ev, type).catch((e) => { if (!(e instanceof NoIdentity)) toast(e.message || String(e)); }); },
    }, label);
    return h('div', { class: 'confirm-pop-backdrop', onClick: (e) => { if (e.target === e.currentTarget) close(); } },
      h('div', { class: 'card col confirm-pop report-pick', style: 'gap:8px' },
        h('div', { class: 'chat-name' }, t('reportTitle')),
        h('div', { class: 'small muted' }, t('reportHelp')),
        reason('spam', t('reportSpam')),
        reason('impersonation', t('reportImpersonation')),
        reason('nudity', t('reportNudity')),
        reason('profanity', t('reportProfanity')),
        reason('illegal', t('reportIllegal')),
        reason('malware', t('reportMalware')),
        reason('other', t('reportOther')),
        h('button', { class: 'btn-ghost btn-block', onClick: close }, t('back'))));
  }
  // Settings → Nostr: the mute list laid out, and the two spam rules.
  // ---- follow list history: undo a client that replaced the list ---------
  // A kind 3 is replaceable, so relays that hold the newest copy have dropped
  // the old one; the archives often haven't. Restoring is a union: everyone
  // in the old copy goes back into the current list, nobody is taken out.
  const FOLLOW_HISTORY_RELAYS = ['wss://nostr21.com', 'wss://relay.ditto.pub', 'wss://offchain.pub', 'wss://nostr.mom',
    'wss://nostr.oxtr.dev', 'wss://relay.nostrplebs.com', 'wss://relay.damus.io', 'wss://nos.lol', 'wss://relay.primal.net',
    'wss://relay.snort.social', 'wss://nostr.wine', 'wss://nostr.bitcoiner.social'];
  async function findFollowHistory() {
    const me = mePk();
    if (!me) return [];
    const relays = [...new Set([...zapRelays(), ...PROFILE_INDEX_RELAYS, ...PROFILE_ARCHIVE_RELAYS, ...FOLLOW_HISTORY_RELAYS,
      ...(await relaysOf(me).catch(() => []))])];
    const evs = await queryOn(relays, { kinds: [3], authors: [me], limit: 50 }, 8000).catch(() => []);
    const byId = new Map();
    for (const e of evs || []) if (e.pubkey === me) byId.set(e.id, e);
    return [...byId.values()].sort((a, b) => b.created_at - a.created_at);
  }
  async function restoreFollows(old) {
    if (followsPub) return;
    const id = await requireIdentity();
    followsPub = true;
    try {
      const before = followsNow();
      await syncFollows({ force: true, deep: true });
      const fetched = followsNow();
      const base = fetched.at > before.at ? fetched : before;
      const have = new Set(pTags(base.tags).map((x) => x[1]));
      const add = pTags(old.tags || []).filter((x) => !have.has(x[1]) && x[1] !== id.pubkey && (have.add(x[1]), true));
      if (!add.length) { toast(t('followHistNothing')); return; }
      const tags = [...base.tags, ...add];
      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([...new Set([...zapRelays(), ...(await relaysOf(id.pubkey).catch(() => []))])], 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(() => {});
      toast(t('followHistRestored', { n: add.length }));
      if (ui.followHist) ui.followHist.done = true;
    } catch (e) {
      if (!(e instanceof NoIdentity)) toast(e.message || String(e));
    } finally {
      followsPub = false;
      render();
    }
  }
  function followHistoryCard() {
    if (!mePk()) return null;
    const cur = followsNow();
    const fh = ui.followHist;
    const look = () => {
      ui.followHist = { loading: true };
      render();
      findFollowHistory().then((vs) => { ui.followHist = { versions: vs }; render(); })
        .catch(() => { ui.followHist = { versions: [] }; render(); });
    };
    const versions = (fh && fh.versions) || [];
    // worth offering: a copy holding people the current list doesn't
    const offers = versions.map((e) => ({ e, extra: pTags(e.tags).filter((x) => !cur.set.has(x[1])).length }))
      .filter((v) => v.extra > 0);
    const clientOf = (e) => (e.tags.find((x) => x[0] === 'client') || [])[1];
    return h('div', { class: 'card col follow-hist-card', style: 'gap:10px' },
      h('h3', {}, t('followHistTitle')),
      h('p', { class: 'small muted', style: 'margin:0' }, t('followHistDesc', { n: cur.set.size })),
      !fh || fh.done
        ? h('button', { class: 'btn-block', onClick: look }, t('followHistLook'))
        : fh.loading
          ? h('div', { class: 'row', style: 'justify-content:center;padding:6px' }, h('span', { class: 'spinner sm' }))
          : offers.length
            ? h('div', { class: 'col', style: 'gap:8px' }, ...offers.slice(0, 6).map(({ e, extra }) => h('div', { class: 'row between gap6', style: 'align-items:center' },
                h('div', { class: 'col', style: 'gap:1px;min-width:0' },
                  h('div', {}, t('followHistPeople', { n: pTags(e.tags).length })),
                  h('div', { class: 'small faint' }, new Date(e.created_at * 1000).toLocaleDateString()
                    + (clientOf(e) ? ' · ' + clientOf(e) : ''))),
                h('button', { class: 'btn-sm', disabled: followsPub, onClick: () => restoreFollows(e) }, t('followHistRestore', { n: extra })))))
            : h('div', { class: 'small faint' }, t('followHistNone')));
  }

  // ---- relay management: your NIP-65 list and your DM inbox (NIP-17) -------
  // Both are replaceable events other clients write too, so the card only
  // ever edits a copy it looked for far and wide first (the follow list was
  // once overwritten from a two-relay lookup), and checks again just before
  // publishing that nobody saved a newer one meanwhile.
  const RELAY_LOOKUP = () => [...new Set([...PROFILE_RELAYS, ...PROFILE_INDEX_RELAYS, ...DM_RELAYS,
    ...PROFILE_ARCHIVE_RELAYS, ...FOLLOW_HISTORY_RELAYS])];
  async function fetchOwnRelayLists(me) {
    const evs = await queryOn(RELAY_LOOKUP(), { kinds: [10002, 10050], authors: [me] }, 6000).catch(() => []);
    const newest = (k) => (evs || []).filter((e) => e.pubkey === me && e.kind === k).sort((a, b) => b.created_at - a.created_at)[0] || null;
    return { r: newest(10002), dm: newest(10050) };
  }
  const rowsOf10002 = (e) => {
    const out = new Map();
    for (const x of (e && e.tags) || []) {
      if (x[0] !== 'r') continue;
      const url = normRelay(x[1]);
      if (!url) continue;
      const row = out.get(url) || { url, read: false, write: false };
      if (!x[2] || x[2] === 'read') row.read = true;
      if (!x[2] || x[2] === 'write') row.write = true;
      out.set(url, row);
    }
    return [...out.values()];
  };
  const urlsOf10050 = (e) => [...new Set(((e && e.tags) || []).filter((x) => x[0] === 'relay').map((x) => normRelay(x[1])).filter(Boolean))];
  const tagsOfRows = (rows) => rows.filter((r) => r.read || r.write)
    .map((r) => (r.read && r.write ? ['r', r.url] : ['r', r.url, r.read ? 'read' : 'write']));
  const sameTags = (a, b) => JSON.stringify(a) === JSON.stringify(b);

  // How long a relay takes to open a socket, measured once per card visit.
  function probeRelayLatency(url) {
    const rm = ui.relayMgr;
    if (!rm || rm.probe[url]) return;
    rm.probe[url] = { state: 'wait' };
    const done = (state, ms) => {
      if (rm.probe[url].state !== 'wait') return;
      rm.probe[url] = { state, ms };
      try { ws.close(); } catch {}
      if (ui.relayMgr === rm) render();
    };
    const t0 = performance.now();
    let ws;
    try { ws = new WebSocket(url); } catch { done('bad'); return; }
    ws.onopen = () => done('ok', Math.round(performance.now() - t0));
    ws.onerror = () => done('bad');
    setTimeout(() => done('bad'), 6000);
  }

  function loadRelayMgr(me, inRender = false) {
    const rm = ui.relayMgr = { me, loading: true, probe: {}, add: '', addDm: '' };
    if (!inRender) render();
    fetchOwnRelayLists(me).then((base) => {
      if (ui.relayMgr !== rm) return;
      rm.base = base;
      rm.rows = base.r ? rowsOf10002(base.r) : PROFILE_RELAYS.map((url) => ({ url, read: true, write: true }));
      rm.dm = base.dm ? urlsOf10050(base.dm) : [...DM_RELAYS];
      rm.loading = false;
      render();
    });
  }

  async function saveRelayMgr() {
    const rm = ui.relayMgr;
    if (!rm || rm.saving || rm.loading) return;
    const tags = tagsOfRows(rm.rows);
    const dmTags = rm.dm.map((u) => ['relay', u]);
    if (!tags.some((x) => !x[2] || x[2] === 'write') || !tags.some((x) => !x[2] || x[2] === 'read')) { toast(t('relaysNeedBoth')); return; }
    if (!dmTags.length) { toast(t('relaysNeedDm')); return; }
    const rChanged = !rm.base.r || !sameTags(tags, tagsOfRows(rowsOf10002(rm.base.r)));
    const dmChanged = !rm.base.dm || !sameTags(rm.dm, urlsOf10050(rm.base.dm));
    if (!rChanged && !dmChanged) { toast(t('relaysUnchanged')); return; }
    if (typeof navigator !== 'undefined' && navigator.onLine === false) { toast(t('msgSendFailed')); return; }
    rm.saving = true;
    render();
    try {
      const id = await requireIdentity();
      if (id.pubkey !== rm.me) throw new Error(t('relaysWrongIdentity'));
      // someone else's client may have saved since this card loaded
      const now = await fetchOwnRelayLists(rm.me);
      const newer = (a, b) => a && (!b || a.created_at > b.created_at);
      if ((rChanged && newer(now.r, rm.base.r)) || (dmChanged && newer(now.dm, rm.base.dm))) {
        toast(t('relaysChangedElsewhere'));
        loadRelayMgr(rm.me);
        return;
      }
      const sign = (partial) => (id.signer instanceof Uint8Array ? finalizeEvent(partial, id.signer) : id.signer.signEvent(partial));
      const stamp = (old) => Math.max(Math.floor(Date.now() / 1000), old ? old.created_at + 1 : 0);
      const writes = tags.filter((x) => !x[2] || x[2] === 'write').map((x) => x[1]);
      // the new list goes to the relays it names, the old ones (so they drop
      // the stale copy) and the indexers other clients look lists up on
      const everywhere = [...new Set([...PROFILE_RELAYS, ...PROFILE_INDEX_RELAYS,
        ...rowsOf10002(rm.base.r).map((r) => r.url), ...tags.map((x) => x[1])])];
      if (rChanged) {
        const evt = await sign({ kind: 10002, content: '', created_at: stamp(rm.base.r), tags });
        if (!(await publishOn(everywhere, evt))) throw new Error(t('msgSendFailed'));
        rm.base.r = evt;
        relayListCache.set(rm.me, Promise.resolve(writes.slice(0, 4)));
        relayListsNow().set(rm.me, { r: writes, t: Date.now() });
        saveRelayLists();
        // wallet sync rides the same write relays (adoptSyncRelays)
        setSyncConfig({ enabled: true, relays: [...new Set([...writes.slice(0, 4), ...DEFAULT_SYNC_RELAYS])].slice(0, 5) });
      }
      if (dmChanged) {
        const evt = await sign({ kind: 10050, content: '', created_at: stamp(rm.base.dm), tags: dmTags });
        const to = [...new Set([...everywhere, ...urlsOf10050(rm.base.dm), ...rm.dm, ...DM_RELAYS])];
        if (!(await publishOn(to, evt))) throw new Error(t('msgSendFailed'));
        rm.base.dm = evt;
        resubscribeStreams(); // read the inbox from the new list now
      }
      toast(t('relaysSaved'));
    } catch (e) {
      if (!(e instanceof NoIdentity)) toast(e.message || String(e));
    } finally {
      rm.saving = false;
      render();
    }
  }

  function relaysCard() {
    const me = mePk();
    if (!me) return null;
    if (!ui.relayMgr || ui.relayMgr.me !== me) loadRelayMgr(me, true);
    const rm = ui.relayMgr;
    const head = [h('h3', {}, t('relaysTitle')), h('p', { class: 'small muted', style: 'margin:0' }, t('relaysDesc'))];
    if (rm.loading) {
      return h('div', { class: 'card col relays-card', style: 'gap:10px' }, ...head,
        h('div', { class: 'row', style: 'justify-content:center;padding:6px' }, h('span', { class: 'spinner sm' })));
    }
    const dot = (url) => {
      probeRelayLatency(url);
      const p = rm.probe[url] || {};
      const color = p.state === 'ok' ? 'var(--green,#2e9d5b)' : p.state === 'bad' ? 'var(--red,#c0392b)' : 'var(--line)';
      return h('span', { title: p.state === 'ok' ? p.ms + ' ms' : p.state === 'bad' ? t('relaysDown') : '',
        style: `flex:0 0 auto;width:8px;height:8px;border-radius:50%;background:${color}` });
    };
    const status = (url) => {
      const p = rm.probe[url] || {};
      // a green dot says it's up (the ms are its tooltip); only trouble is spelled out
      return p.state === 'bad' ? h('span', { class: 'small faint', style: 'white-space:nowrap' }, t('relaysDown')) : null;
    };
    const name = (url) => h('span', { class: 'grow mono', style: 'min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:13px' },
      url.replace(/^wss:\/\//, ''));
    const x = (onClick) => h('button', { class: 'linklike', type: 'button', 'aria-label': t('remove'), style: 'padding:0 4px', onClick }, '×');
    const flag = (row, k, label) => h('button', {
      class: 'feed-chip' + (row[k] ? ' on' : ''), type: 'button', style: 'padding:3px 9px;font-size:12px',
      onClick: () => { row[k] = !row[k]; if (!row.read && !row.write) row[k === 'read' ? 'write' : 'read'] = true; render(); },
    }, label);
    const adder = (key, cls, onAdd) => {
      const go = (ev) => {
        const url = normRelay(rm[key]);
        if (!url || !/^[a-z0-9.-]+(:\d+)?$/i.test(new URL(url).host)) { if (rm[key].trim()) toast(t('relaysBadUrl')); return; }
        rm[key] = '';
        const box = ev && ev.currentTarget && ev.currentTarget.parentNode.querySelector('input');
        if (box) box.value = '';
        onAdd(url);
        render();
      };
      return h('div', { class: 'row gap6' },
        h('input', { type: 'text', class: 'grow ' + cls, placeholder: 'wss://relay.example.com', value: rm[key],
          autocapitalize: 'none', autocomplete: 'off', spellcheck: 'false',
          onInput: (ev) => { rm[key] = ev.target.value; },
          onKeydown: (ev) => { if (ev.key === 'Enter') { ev.preventDefault(); go(ev); } } }),
        h('button', { class: 'btn-sm', type: 'button', onClick: go }, t('modAdd')));
    };
    return h('div', { class: 'card col relays-card', style: 'gap:10px' }, ...head,
      h('div', { class: 'small muted' }, t('relaysPublic')),
      rm.base.r ? null : h('div', { class: 'small faint' }, t('relaysNoneYet')),
      h('div', { class: 'col', style: 'gap:8px' }, ...rm.rows.map((row) => h('div', { class: 'row gap6 relay-row', style: 'align-items:center' },
        dot(row.url), name(row.url), status(row.url),
        flag(row, 'read', t('relaysRead')), flag(row, 'write', t('relaysWrite')),
        x(() => { rm.rows = rm.rows.filter((r) => r !== row); render(); })))),
      adder('add', 'relay-add', (url) => { if (!rm.rows.some((r) => r.url === url)) rm.rows.push({ url, read: true, write: true }); }),
      h('div', { class: 'small muted', style: 'margin-top:6px' }, t('relaysInbox')),
      rm.base.dm ? null : h('div', { class: 'small faint' }, t('relaysNoneYet')),
      h('div', { class: 'col', style: 'gap:8px' }, ...rm.dm.map((url) => h('div', { class: 'row gap6 relay-dm-row', style: 'align-items:center' },
        dot(url), name(url), status(url),
        x(() => { rm.dm = rm.dm.filter((u) => u !== url); render(); })))),
      adder('addDm', 'relay-dm-add', (url) => { if (!rm.dm.includes(url)) rm.dm.push(url); }),
      h('div', { class: 'row gap6', style: 'margin-top:4px' },
        h('button', { class: 'grow relays-save', disabled: rm.saving, onClick: () => saveRelayMgr() }, rm.saving ? t('relaysSaving') : t('relaysSave')),
        h('button', { class: 'btn-ghost', disabled: rm.saving, onClick: () => loadRelayMgr(me) }, t('relaysReload'))));
  }

  // Settings → Nostr: whether clips over the budget play by themselves.
  // Settings → Nostr: which device of yours gets group invitations. A Marmot
  // inviter (White Noise) picks one of your published keys; the group lands
  // on that device alone, and nothing told you which (Adam's invitation sat
  // on the phone while he looked on the laptop).
  function groupDevicesCard() {
    const pk = identityPk();
    let d = ui.wnDevices;
    if (!d || d.pk !== pk) {
      d = ui.wnDevices = { pk, loading: true };
      whiteNoise().then((c) => (c ? c.devices() : null)).then((r) => {
        if (!ui.wnDevices || ui.wnDevices.pk !== pk) return;
        ui.wnDevices = r ? { pk, ...r } : { pk, none: true };
        render();
      }).catch(() => { if (ui.wnDevices && ui.wnDevices.pk === pk) { ui.wnDevices = { pk, none: true }; render(); } });
    }
    const busy = !!ui.wnOnlyHere;
    const state = d.loading ? null : d.none ? t('wnDeviceNone') : d.retired ? t('wnDeviceRetired') : d.published ? t('wnDeviceHere') : t('wnDeviceNone');
    return h('div', { class: 'card col wn-devices-card', style: 'gap:8px' },
      h('h3', {}, t('wnDevicesTitle')),
      h('div', { class: 'small faint' }, t('wnDevicesHelp')),
      state ? h('div', { class: 'small wn-device-state' }, state) : h('div', { class: 'row gap6' }, h('span', { class: 'spinner sm' })),
      !d.loading && d.others ? (d.others.length
        ? h('div', { class: 'col small', style: 'gap:2px' }, h('div', {}, t('wnDevicesOthers', { n: d.others.length })),
            ...d.others.map((o) => h('div', { class: 'faint wn-device' }, (o.client || t('wnDeviceUnknown')) + ' \u00b7 ' + timeLabel(o.created_at * 1000))))
        : h('div', { class: 'small faint wn-no-others' }, t('wnDevicesNoOthers'))) : null,
      h('button', {
        class: 'btn-sm wn-only-here', type: 'button', disabled: busy || d.loading || undefined,
        onClick: () => {
          ui.wnOnlyHere = true; render();
          whiteNoise().then((c) => (c ? c.onlyHere({ interactive: true }) : Promise.reject(new Error('no client'))))
            .then((n) => { toast(t('wnOnlyHereDone', { n })); ui.wnDevices = null; })
            .catch(() => toast(t('wnOnlyHereFail')))
            .finally(() => { ui.wnOnlyHere = false; render(); });
        },
      }, t('wnOnlyHere')));
  }

  function videosCard() {
    const on = largeVideosOk();
    return h('div', { class: 'card col videos-card', style: 'gap:8px' },
      h('h3', {}, t('videoLargeTitle')),
      h('label', { class: 'row gap6', style: 'align-items:center;cursor:pointer' },
        h('input', { type: 'checkbox', class: 'video-large', checked: on, style: 'width:18px;height:18px;accent-color:var(--accent);margin:0',
          onChange: (e) => { try { localStorage.setItem(VIDEO_LARGE_KEY, e.target.checked ? '1' : '0'); } catch {} render(); } }),
        h('span', {}, t('videoLargeToggle'))),
      h('div', { class: 'small faint' }, t('videoLargeHelp', { mb: Math.round(videoBudget() / 1e6) })));
  }

  function translateCard() {
    const to = transLang();
    const e = ui.deeplEdit || (ui.deeplEdit = { key: '' });
    const names = TRANSLATE_TARGETS.map((c) => [c, langName(c)]).sort((a, b) => a[1].localeCompare(b[1]));
    const dk = deeplKey();
    return h('div', { class: 'card col translate-card', style: 'gap:8px' },
      h('h3', {}, t('translateTitle')),
      h('label', { class: 'row gap6', style: 'align-items:center' },
        h('span', { class: 'grow' }, t('translateTo')),
        h('select', { class: 'translate-to', style: 'width:auto',
          onChange: (ev) => { try { localStorage.setItem(TRANSLATE_TO_KEY, ev.target.value); } catch {} render(); } },
          ...names.map(([c, n]) => h('option', { value: c, selected: c === to }, n)))),
      h('label', { class: 'row gap6', style: 'align-items:center;cursor:pointer' },
        h('input', { type: 'checkbox', class: 'auto-translate', checked: autoTranslateOn(), style: 'width:18px;height:18px;accent-color:var(--accent);margin:0',
          onChange: (ev) => { try { localStorage.setItem(AUTO_TRANSLATE_KEY, ev.target.checked ? '1' : '0'); } catch {} render(); } }),
        h('span', {}, t('translateAutoToggle', { lang: langName(to) }))),
      h('div', { class: 'small faint' }, t(dk ? 'translateHelpDeepl' : 'translateHelp')),
      // DeepL, with the reader's own key
      dk
        ? h('div', { class: 'row gap6', style: 'align-items:center' },
            h('span', { class: 'small grow' }, t('deeplOn', { key: '…' + dk.slice(-6) })),
            h('button', { class: 'btn-sm deepl-remove', onClick: () => { try { localStorage.removeItem(DEEPL_KEY); } catch {} deeplWarned = false; render(); } }, t('deeplRemove')))
        : h('div', { class: 'row gap6' },
            h('input', { type: 'password', class: 'grow deepl-key', placeholder: t('deeplKeyPh'), value: e.key, autocomplete: 'off', spellcheck: 'false',
              onInput: (ev) => { e.key = ev.target.value.trim(); } }),
            h('button', { class: 'btn-sm deepl-save', onClick: () => {
              if (!/^[0-9a-f-]{20,}(:fx)?$/i.test(e.key)) { toast(t('deeplBadKey')); return; }
              try { localStorage.setItem(DEEPL_KEY, e.key); } catch {}
              e.key = ''; deeplWarned = false;
              toast(t('deeplSaved'));
              render();
            } }, t('deeplSave'))));
  }

  function moderationCard() {
    const m = mutesNow();
    const e = ui.modEdit || (ui.modEdit = { word: '' });
    const people = [...m.set];
    for (const pk of people.slice(0, 30)) profileOf(pk);
    const add = () => {
      const w = e.word.trim();
      if (!w) return;
      e.word = '';
      if (w.startsWith('#')) toggleMuteTag(w, true); else toggleMuteWord(w, true);
    };
    const chip = (label, onX) => h('span', { class: 'feed-chip on mod-chip', style: 'display:inline-flex;align-items:center;gap:6px' },
      label, h('button', { class: 'linklike', type: 'button', 'aria-label': t('remove'), style: 'padding:0 2px', onClick: onX }, '\u00d7'));
    const toggle = (k, label, help) => h('div', { class: 'col', style: 'gap:4px' },
      h('label', { class: 'row gap6', style: 'align-items:center;cursor:pointer' },
        h('input', { type: 'checkbox', class: 'mod-' + k, checked: modOn(k), style: 'width:18px;height:18px;accent-color:var(--accent);margin:0', onChange: (ev) => setMod(k, ev.target.checked) }),
        h('span', {}, label)),
      h('div', { class: 'small faint' }, help));
    return h('div', { class: 'card col mod-card', style: 'gap:10px' },
      h('h3', {}, t('modTitle')),
      h('p', { class: 'small muted', style: 'margin:0' }, t('modDesc')),
      h('div', { class: 'small muted' }, t('modPeople')),
      people.length
        ? h('div', { class: 'col', style: 'gap:6px' }, ...people.slice(0, 50).map((pk) => h('div', { class: 'row gap6 mod-person', style: 'align-items:center' },
            avatar(pk, 'chat-avatar mini', false),
            h('span', { class: 'grow', style: 'min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap' }, displayName(pk)),
            h('button', { class: 'btn-sm', type: 'button', onClick: () => toggleMute(pk) }, t('postUnmute')))))
        : h('div', { class: 'small faint' }, t('modNoPeople')),
      h('div', { class: 'small muted' }, t('modWords')),
      m.words.length || m.hashtags.size
        ? h('div', { class: 'row wrap', style: 'gap:6px' },
            ...m.words.map((w) => chip(w, () => toggleMuteWord(w, false))),
            ...[...m.hashtags].map((x) => chip('#' + x, () => toggleMuteTag(x, false))))
        : null,
      h('div', { class: 'row gap6' },
        h('input', {
          type: 'text', class: 'grow mod-word', placeholder: t('modWordHint'), value: e.word,
          autocapitalize: 'none', autocomplete: 'off', spellcheck: 'false',
          onInput: (ev) => { e.word = ev.target.value; },
          onKeydown: (ev) => { if (ev.key === 'Enter') { ev.preventDefault(); add(); } },
        }),
        h('button', { class: 'btn-sm', type: 'button', onClick: add }, t('modAdd'))),
      m.threads.size ? h('div', { class: 'small faint' }, t('modThreads', { n: m.threads.size })) : null,
      toggle('spam', t('modSpamToggle'), t('modSpamHelp')),
      toggle('reports', t('modReportsToggle'), t('modReportsHelp')),
      toggle('sensitive', t('modSensitiveToggle'), t('modSensitiveHelp')));
  }

  const noteLink = (ev) => location.origin + '/' + (neventOf(ev.id, ev.pubkey) || ev.id);
  // your own notes and comments; an article or a poll is edited elsewhere
  const canEdit = (ev) => isMe(ev.pubkey) && !ev.pending && (ev.kind === 1 || ev.kind === COMMENT);
  // Editing one of your posts: its words, as they stand now, in a box.
  function editSheet() {
    const e = ui.postEdit;
    if (!e) return null;
    const close = () => { ui.postEdit = null; render(); };
    const save = async () => {
      const text = String(e.text || '').trim();
      if (!text || text === noteText(e.ev).trim()) { close(); return; }
      ui.postEdit = null;
      try { await editPost(e.ev, text); toast(t('postEditedToast')); }
      catch (err) { if (!(err instanceof NoIdentity)) toast(err.message || String(err)); ui.postEdit = { ev: e.ev, text }; render(); }
    };
    return h('div', { class: 'confirm-pop-backdrop', onClick: (x) => { if (x.target === x.currentTarget) close(); } },
      h('div', { class: 'card col confirm-pop', style: 'gap:10px' },
        h('h3', { style: 'margin:0' }, t('postEditTitle')),
        h('coinos-text', {
          class: 'post-edit-input', style: 'font-family:var(--sans);min-height:120px;max-height:50vh',
          value: e.text,
          onInput: (x) => { e.text = x.target.value; updateMentionAc(x.target, '.post-edit-input'); },
          onKeydown: mentionKey,
        }),
        mentionList('.post-edit-input'),
        h('div', { class: 'small faint' }, t('postEditHelp')),
        h('div', { class: 'row gap6' },
          h('button', { class: 'btn-ghost grow', onClick: close }, t('cancel')),
          h('button', { class: 'btn-primary grow', onClick: save }, t('save')))));
  }
  function deleteAskSheet() {
    const ev = ui.postDeleteAsk;
    if (!ev) return null;
    const close = () => { ui.postDeleteAsk = null; render(); };
    const go = async () => {
      close();
      try { await deletePost(ev); toast(t('postDeletedToast')); }
      catch (err) { if (!(err instanceof NoIdentity)) toast(err.message || String(err)); }
    };
    return h('div', { class: 'confirm-pop-backdrop', onClick: (x) => { if (x.target === x.currentTarget) close(); } },
      h('div', { class: 'card col confirm-pop', style: 'gap:10px' },
        h('h3', { style: 'margin:0' }, t('postDeleteTitle')),
        h('div', { class: 'small muted' }, t('postDeleteHelp')),
        h('div', { class: 'row gap6' },
          h('button', { class: 'btn-ghost grow', onClick: close }, t('cancel')),
          h('button', { class: 'btn-danger grow', onClick: go }, t('postDelete')))));
  }
  // 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; ui.emojiPick = 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 {}
        }),
        // the post's own address here — the same path the bar shows while
        // its thread is open, and what njump-style links resolve to
        item('\u{1F517}', t('postCopyLink'), async () => {
          try { await navigator.clipboard.writeText(noteLink(ev)); toast(t('copied')); } catch {}
        }),
        typeof navigator !== 'undefined' && navigator.share
          ? item('\u2197', t('postShare'), () => { navigator.share({ url: noteLink(ev) }).catch(() => {}); })
          : null,
        translatable(ev) && (deeplKey() || canTranslateTo(transLang()))
          ? shownTranslation(ev)
            ? item('\u{1F310}', t('translateShowOriginal'), () => { const k = transKey(ev); transOriginal.add(k); transAsked.delete(k); render(); })
            : item('\u{1F310}', t('translateBtn'), () => translateNote(ev, { asked: true }))
          : null,
        canEdit(ev) ? item('\u270e', t('postEdit'), () => { ui.postEdit = { ev, text: noteText(ev) }; render(); }) : null,
        mine && !ev.pending ? item('\u{1F5D1}', t('postDelete'), () => { ui.postDeleteAsk = ev; render(); }, true) : null,
        mine || !myPubkeys().length ? null : item('\u2630', t('listAddTo'), () => { ui.listPick = ev.pubkey; render(); }),
        mine ? null : item('\u{1F6A9}', t('postReport'), () => { ui.reportPick = ev; render(); }),
        item('\u{1F515}', mutesNow().threads.has(rootIdOf(ev)) ? t('postUnmuteThread') : t('postMuteThread'), () => toggleMuteThread(rootIdOf(ev))),
        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);
  // a person with a plus: add someone to a group or community
  const I_ADD_PERSON = '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M15 21v-1.5a4.5 4.5 0 0 0-4.5-4.5h-5A4.5 4.5 0 0 0 1 19.5V21"/><circle cx="8" cy="7.5" r="4"/><path d="M19.5 8v6"/><path d="M22.5 11h-6"/></svg>';
  const I_ZAP = ICON('<path d="M13 2L4 14h7l-1 8 9-12h-7l1-8z"/>', true);

  function noteActions(pk, ev, { canZap }) {
    if (canZap && zapSoundOn()) warmZapSound(); // the clip is decoded before the first tap
    const mineReact = myReactOn(ev.id);
    const rm = reacts.get(ev.id);
    const cached = ui.noteThread
      ? threadCache.get(ui.noteThread.rootId)?.counts?.[ev.id] : null;
    const likeN = cached ? cached.likes : rm ? [...rm.values()].reduce((n, { who }) => n + visiblePks(who).length, 0) : 0;
    const boostN = cached ? cached.boosts : visiblePks(boosts.get(ev.id) || new Set()).length;
    const btn = (icon, label, count, on, onClick, cls = '', extra = null) => h('button', {
      class: 'note-act' + (on ? ' on' : '') + (cls ? ' ' + cls : ''), title: label, 'aria-label': label,
      'aria-disabled': onClick ? undefined : 'true',
      ...(extra || {}),
      onClick: (e) => { e.stopPropagation(); if (onClick) onClick(e); },
    },
      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);
    // the sats tally rides on the zap button, like the like and boost counts
    // do on theirs — amber once anyone has zapped, breathing while ours flies
    const z = zapTotals.get(ev.id) || zapSeeds().get(ev.id);
    const zp = pendingOf(ev.id);
    const optimistic = zp ? zp.sats : 0;
    const zapSats = (cached ? cached.sats : z ? z.sats : 0) + optimistic;
    const zapFlying = !!zp && zp.flying;
    // tap pays the default amount; hold opens the screen that sets it
    const zapHold = canZap ? holdable((el) => openZapSettings(pk, ev.id, el.getBoundingClientRect()),
      (e) => { zapNote(pk, ev, e.currentTarget.getBoundingClientRect(), momentOf(ev)); recheckZap(ev.id); }) : null;
    const zapMine = !!((z && z.mine) || optimistic);
    const zapLabel = zapFlying ? t('zapSending') : zapSats ? t('zapTallyTitle', { n: zapSats.toLocaleString() }) : t('zapTitle');
    return h('div', { class: 'row note-acts' },
      btn(I_REPLY, t('msgReply'), replyCount(ev.id), false, () => { if (!signinAsk()) replyToNote(ev, momentOf(ev)); }),
      btn(I_BOOST, t('postBoost'), boostN, iBoosted(ev.id), () => boostNote(ev).catch(() => {})),
      btn(I_QUOTE, t('postQuote'), 0, false, () => { if (!signinAsk()) quoteNote(ev); }),
      // tap to choose how you feel about it; tap again to take it back
      btn(mineReact ? postReactNode(mineReact) : I_HEART(false), t('postLike'), likeN, !!mineReact,
        () => { if (signinAsk()) return; if (mineReact) unreact(ev).catch(() => {}); else { ui.reactPick = withMoment(ev); render(); } }),
      // always in the bar — the same row of buttons on every post, so nothing
      // shifts when a wallet comes online; without one it is just the number
      btn(I_ZAP, zapLabel, zapSats ? fmtSats(zapSats) : 0, zapMine,
        (zapHold && zapHold.onClick) || (isVisitor() ? () => signinAsk() : wallet.watchOnly ? zapLockedAsk : null),
        'note-zap' + (zapMine ? ' zapped' : '') + (zapFlying ? ' flying' : ''),
        zapHold && { ...zapHold, onClick: undefined }),
      // who did all that: a small chevron, always in place — dimmed until
      // there is someone to show, so the first reaction doesn't reflow the bar
      (() => {
        const n = whoCount(ev.id), open = n && whoOpen(ev.id);
        return h('button', {
          class: 'note-act note-who-toggle' + (open ? ' on' : ''),
          title: t('postWho'), 'aria-label': t('postWho'), 'aria-expanded': open ? 'true' : 'false',
          'aria-disabled': n ? undefined : 'true',
          onClick: (e) => { e.stopPropagation(); if (n) toggleWho(ev.id); },
        }, h('span', { class: 'note-who-chev' + (open ? ' open' : ''), html: I_CHEV }));
      })());
  }

  // ---- who reacted, boosted and zapped ------------------------------------
  // The counts on the bar say how many; this says who, and with what. Opened
  // per post by the chevron, the way Amethyst does it, and remembered for
  // the session so a repaint doesn't fold it back up.
  const I_CHEV = '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:block"><path d="M6 9l6 6 6-6"/></svg>';
  const whoOpenIds = new Set();
  const whoOpen = (id) => whoOpenIds.has(id);
  const toggleWho = (id) => { if (whoOpenIds.has(id)) whoOpenIds.delete(id); else whoOpenIds.add(id); render(); };
  function whoCount(id) {
    const rm = reacts.get(id);
    let n = rm ? [...rm.values()].reduce((k, { who }) => k + visiblePks(who).length, 0) : 0;
    n += visiblePks(boosts.get(id) || new Set()).length;
    n += [...(zapWho.get(id) || new Map()).values()].filter((z) => !hiddenPk(z.pk)).length;
    return n;
  }
  function whoPanel(ev) {
    const rm = new Map([...(reacts.get(ev.id) || new Map())].map(([k, r]) => [k, { ...r, who: new Set(visiblePks(r.who)) }]).filter(([, r]) => r.who.size));
    const bs = new Set(visiblePks(boosts.get(ev.id) || new Set()));
    const zs = [...(zapWho.get(ev.id) || new Map()).values()].filter((z) => !hiddenPk(z.pk)).sort((a, b) => b.sats - a.sats || b.ts - a.ts);
    const person = (pk, extra) => h('button', {
      class: 'note-who-person',
      onClick: (e) => { e.stopPropagation(); openProfile(pk); },
    }, avatar(pk, 'chat-avatar mini', false), h('span', { class: 'note-who-name' }, displayName(pk)), extra || null);
    const people = (pks) => {
      for (const pk of pks) profileOf(pk); // names and faces, one batch
      return h('div', { class: 'row wrap note-who-people' },
        ...pks.slice(0, 24).map((pk) => person(pk)),
        pks.length > 24 ? h('span', { class: 'small faint' }, '+' + (pks.length - 24)) : null);
    };
    const line = (lead, body) => h('div', { class: 'row note-who-line' }, h('span', { class: 'note-who-lead' }, lead), body);
    const lines = [];
    // biggest zaps first, each with its own line (the amount is the point)
    if (zs.length) {
      for (const z of zs) profileOf(z.pk);
      lines.push(line(h('span', { style: 'display:flex', html: I_ZAP }),
        h('div', { class: 'col', style: 'gap:4px;min-width:0' }, ...zs.slice(0, 24).map((z) =>
          person(z.pk, h('span', { class: 'note-who-sats' }, fmtSats(z.sats) + ' sats'
            + (z.text ? ' · ' + z.text : '')))))));
    }
    for (const reaction of [...rm.values()].sort((a, b) => b.who.size - a.who.size)) {
      lines.push(line(h('span', { class: 'note-act-emoji' }, postReactNode(reaction)), people([...reaction.who])));
    }
    if (bs.size) lines.push(line(h('span', { style: 'display:flex', html: I_BOOST }), people([...bs])));
    if (!lines.length) return null;
    return h('div', { class: 'col note-who', onClick: (e) => e.stopPropagation() }, ...lines);
  }

  // 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(); };
    // over the media pager (a reaction from a slide): above it, and its
    // like button hears the pick
    const after = () => { if (pager && pager.cur) pagerCounts(pager.cur); };
    return h('div', {
      class: 'confirm-pop-backdrop' + (pager ? ' over-pager' : ''),
      onClick: (e) => { if (e.target === e.currentTarget) close(); },
    },
      h('div', { class: 'card col msg-sheet' },
        reactRow(null, (e2) => { close(); reactTo(ev, e2).catch(() => {}).finally(after); setTimeout(after, 50); }),
        h('button', { class: 'btn-ghost btn-block', onClick: close }, t('back'))));
  }

  // context: a reply shows the post it answers above itself (the
  // Conversations feed, a profile's Replies tab) — a quote card, which opens
  // that post; the reply's own tap opens the thread at the reply.
  function noteRow(pk, ev, name, { open = true, focus = false, joined = false, context = false } = {}) {
    if (ev.kind === REPOST) {
      const inner = repostInner(ev);
      if (!inner) return h('div', { class: 'row note-post', style: 'display:none' });
      const prev = repostBy;
      repostBy = ev.pubkey;
      try { return noteRow(inner.pubkey, inner, displayName(inner.pubkey), { open, focus, joined, context }); }
      finally { repostBy = prev; }
    }
    // who reposted this, for its header line (only this row: a quote inside draws none)
    const reposter = repostBy;
    repostBy = null;
    // A zap receipt (9735, or coinos's 9737) reached as a reply or through a
    // reaction to it — some clients let you react to a zap — is the zap, not
    // a post by the lightning server that signed it: the zapper's face and
    // name, what they sent, what they said with it.
    const zapRec = ev.kind === 9735 || ev.kind === 9737;
    if (zapRec) { const z = zapperOf(ev); if (z) { pk = z; name = displayName(z); } }
    // 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);
    // An event of a kind this app has no renderer for (a chess game, kind
    // 64, reached through a reaction to it) is shown as what its author's
    // client said it is (NIP-31 alt), never as raw content dressed as a post.
    const foreign = ev.kind !== 1 && ev.kind !== ARTICLE && ev.kind !== POLL && ev.kind !== COMMENT && !isVideoEvent(ev) && !zapRec;
    const altText = foreign ? ((ev.tags.find((x) => x[0] === 'alt') || [])[1] || t('noteForeignKind', { kind: ev.kind })) : null;
    const isReply = ev.kind === COMMENT || (!foreign && !zapRec && ev.tags.some((x) => x[0] === 'e'));
    const parent = context && !foreign && !zapRec ? parentRefOf(ev) : null;
    const canZap = canZapPk(pk);
    // 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;
    // flagged by people you follow: folded behind a line that says who
    const flagged = !pending && !(ui.revealed && ui.revealed.has(ev.id)) ? reportsOn(ev) : null;
    if (flagged) return foldedRow(ev, flagged);
    const warned = !pending && modOn('sensitive') && !isMe(ev.pubkey) && !(ui.revealed && ui.revealed.has(ev.id)) ? sensitiveWhy(ev) : null;
    if (warned !== null) return sensitiveFold(ev, warned);
    // deleted by its author: a thread's root or a reply in view keeps its
    // place (the conversation around it still reads), saying only that
    if (isDeleted(ev)) return h('div', { class: 'note-post small faint', 'data-zap-post': ev.id, style: 'padding:10px 0' }, t('postDeletedNote'));
    const edited = editOf(ev);
    const openable = open && !pending;
    if (openable) threadPrefetch.watch(ev);
    if (!pending) watchZaps([ev.id]);
    return h('div', {
      class: 'row note-post',
      'data-zap-post': ev.id,
      'data-thread-prefetch': openable ? ev.id : undefined,
      'data-focus-note': focus ? '1' : undefined,
      style: 'padding:10px 0'
        + (openable ? ';cursor:pointer' : '')
        + (pending ? ';opacity:.55' : '')
        // joined: the reply box continues this highlight below, so the
        // bottom corners stay square and the two read as one panel
        + (focus ? ';background:var(--accent-soft,rgba(128,128,128,.08));border-radius:' + (joined ? '8px 8px 0 0' : '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
      // nor a link in it: a mention opens the person, a URL its page — the
      // thread opening underneath as well buried the profile under the post
      onClick: openable ? (e) => { if (e.target && e.target.closest && e.target.closest('button, a')) 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: 'note-content' },
        reposter ? h('div', { class: 'small faint note-reposted', onClick: (e) => { e.stopPropagation(); openProfile(reposter); } },
          h('span', { 'aria-hidden': 'true' }, '\u{1F501} '), t('postRepostedBy', { name: displayName(reposter) })) : null,
        parent ? h('div', { class: 'note-context', 'data-context-of': parent.id },
          h('div', { class: 'small faint note-context-label' }, '\u21a9 ' + t('noteReplyingTo')),
          quoteCard(parent, 0)) : null,
        h('div', { class: 'row between note-header', 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 && !parent ? '↩ ' + t('profReplyTag') + ' · ' : '') + timeLabel(ev.created_at * 1000)
              + (edited ? ' · ' + t('postEditedTag') : ''))),
          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')),
        zapRec
          ? h('div', { class: 'note-text', style: 'white-space:pre-wrap;overflow-wrap:anywhere' },
              h('span', { class: 'note-zap-line' }, '\u26a1 ' + t('zapRowText', { n: receiptSats(ev).toLocaleString() })),
              zapText(ev) ? h('div', {}, ...noteBody(zapText(ev))) : null)
        : foreign
          ? h('div', { class: 'note-text small muted', style: 'white-space:pre-wrap;overflow-wrap:anywhere' }, (ev.kind === 64 ? '\u265f ' : '') + altText)
          : h('div', { class: 'note-text', style: 'white-space:pre-wrap;overflow-wrap:anywhere' }, ...(ev.kind === ARTICLE ? (open ? [articleCard(ev)] : articleBody(ev)) : noteBody(shownTranslation(ev)?.text ?? noteText(ev), 0, noteEmojiTags(ev)))),
        readMoment(ev) ? h('a', { class: 'small media-time-link', href: readMoment(ev).url + '#t=' + readMoment(ev).seconds, target: '_blank', rel: 'noopener noreferrer', onClick: e => {
          e.stopPropagation();
          const m = readMoment(ev);
          const player = [...document.querySelectorAll('audio, video')].find(v => mediaMoment(v.dataset.clip || v.getAttribute('src'), 0)?.url === m.url);
          if (player) { e.preventDefault(); const seek = () => { player.currentTime = Math.min(m.seconds, Number.isFinite(player.duration) ? player.duration : m.seconds); }; if (player.readyState) seek(); else player.addEventListener('loadedmetadata', seek, { once: true }); player.play().catch(() => {}); player.scrollIntoView({ block: 'center' }); }
        } }, '▶ ' + mediaClock(readMoment(ev).seconds)) : null,
        foreign || pending ? null : translateLine(ev),
        ev.kind === POLL ? pollBox(ev) : null,
        pending ? null : noteActions(pk, ev, { canZap }),
        !pending && whoOpen(ev.id) ? whoPanel(ev) : null));
  }

  // ---- thread view: a note in its conversation ----------------------------
  const threadCache = new Map(); // root id -> { status, root, replies }
  const threadStore = createThreadStore();
  const threadPrefetch = createThreadPrefetch({
    key: rootIdOf,
    cached: (ev) => threadCache.has(rootIdOf(ev)),
    load: (ev) => threadFor(ev, true).loading,
  });
  function trimPrefetchedThreads() {
    const idle = [...new Set(threadCache.values())].filter((c) => c.prefetched
      && c.status === 'ready' && ui.noteThread?.rootId !== c.rootId);
    for (const c of idle.slice(0, Math.max(0, idle.length - 12))) {
      for (const [id, entry] of threadCache) if (entry === c) threadCache.delete(id);
    }
  }
  const persistThread = (c) => {
    if (!c.root) return;
    const faces = {};
    for (const ev of [c.root, ...c.replies]) {
      const p = profiles.get(ev.pubkey);
      if (p && (p.name || p.picture)) faces[ev.pubkey] = p;
    }
    // quoted posts inside the thread ride along, so a reload paints them
    // instead of a "Fetching note…" spinner
    const quotes = [];
    for (const ev of [c.root, ...c.replies]) {
      for (const m of (ev.content || '').matchAll(/nostr:((?:note|nevent)1[a-z0-9]+)/gi)) {
        const ref = parseNostrRef(m[1].toLowerCase());
        const q = ref && ref.type === 'event' && quoted.get(ref.id);
        if (q && q.ev) {
          quotes.push(q.ev);
          const p = profiles.get(q.ev.pubkey);
          if (p && (p.name || p.picture)) faces[q.ev.pubkey] = p;
        }
      }
    }
    threadStore.save(c, c.focusId, faces, c.counts, quotes);
  };
  function persistThreadProfile(pk) {
    const c = ui.noteThread && threadCache.get(ui.noteThread.rootId);
    if (c?.root && [c.root, ...c.replies].some((ev) => ev.pubkey === pk)) persistThread(c);
  }
  const noteSep = () => h('div', { style: 'height:1px;background:var(--border,rgba(128,128,128,.18));margin:0 -14px' });
  function renderThreadStable() {
    if (!ui.noteThread || ui.noteThread.scrollPending || typeof document === 'undefined') { render(); return; }
    // At the very top the HEADER is the anchor. Pinning the first post instead
    // turns a late header/control row into an unwanted downward scroll.
    if (window.scrollY <= 1) {
      render();
      if (window.scrollY) window.scrollTo(0, 0);
      requestAnimationFrame(() => {
        if (ui.noteThread && window.scrollY <= 80) window.scrollTo(0, 0);
      });
      return;
    }
    const rows = [...document.querySelectorAll('.thread-page [data-zap-post]')];
    const anchor = rows.find((el) => el.getAttribute('data-focus-note') === '1'
      && el.getBoundingClientRect().top >= 0 && el.getBoundingClientRect().top < innerHeight)
      || rows.find((el) => { const r = el.getBoundingClientRect(); return r.bottom > 0 && r.top < innerHeight; });
    if (!anchor) { render(); return; }
    const id = anchor.getAttribute('data-zap-post');
    const top = anchor.getBoundingClientRect().top;
    render();
    const settle = () => {
      if (!ui.noteThread || ui.noteThread.scrollPending) return;
      const next = [...document.querySelectorAll('.thread-page [data-zap-post]')]
        .find((el) => el.getAttribute('data-zap-post') === id);
      if (next) window.scrollBy(0, next.getBoundingClientRect().top - top);
    };
    settle();
    requestAnimationFrame(settle);
  }
  // ---- NIP-22 comments (kind 1111) ----
  // The reply format for everything that isn't a kind 1 note — a poll, an
  // article, a picture. Uppercase tags name the ROOT (E/A + K + P),
  // lowercase the PARENT it answers (e/a + k + p). A kind 1 note is never
  // answered with one (NIP-22), and never answers anything but a kind 1.
  const COMMENT = 1111;
  const tagVal = (ev, name) => (ev.tags.find((x) => x[0] === name && x[1]) || [])[1] || null;
  const addrOf = (ev) => ev.kind >= 30000 && ev.kind < 40000 ? ev.kind + ':' + ev.pubkey + ':' + (tagVal(ev, 'd') || '') : null;
  function rootIdOf(ev) {
    if (ev.kind === COMMENT) return tagVal(ev, 'E') || tagVal(ev, 'e') || ev.id;
    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, prefetch = false) {
    const requestedRootId = rootIdOf(seed);
    let c = threadCache.get(requestedRootId) || [...new Set(threadCache.values())]
      .find((c) => c.replies.some((e) => e.id === seed.id || e.id === requestedRootId));
    if (c) {
      threadCache.set(requestedRootId, c);
      if (adoptRepliesInHand(c) && c.status === 'ready' && !c.prefetched) persistThread(c);
      if (!prefetch) {
        c.focusId = seed.id;
        const wasPrefetched = c.prefetched;
        c.prefetched = false;
        if (wasPrefetched && c.status === 'ready') persistThread(c);
      }
      if (seed.id === c.rootId) c.root ||= seed;
      else if (!c.replies.some((ev) => ev.id === seed.id)) {
        c.replies = [...c.replies, seed].sort((a, b) => a.created_at - b.created_at);
        persistThread(c);
      }
      if (ui.noteThread?.focusId === seed.id) ui.noteThread.rootId = c.rootId;
      return c;
    }
    // Browser history restores only the selected event. Recover the full
    // conversation synchronously, including the canonical root discovered
    // by climbing a reply-only chain on the previous visit.
    const stored = threadStore.find(seed.id) || threadStore.find(requestedRootId);
    // The event cache is public and survives profile-cache eviction. Restore
    // its author faces before the first thread row is painted on refresh.
    if (stored?.profiles) {
      warmProfiles();
      for (const [pk, face] of Object.entries(stored.profiles)) {
        const current = profiles.get(pk);
        if (!current || (current.eventAt || 0) < (face.eventAt || 0)
          || (current.eventAt === face.eventAt && !current.thumb && face.thumb)) {
          profiles.set(pk, { ...current, ...face });
        }
      }
    }
    for (const q of stored?.quotes || []) if (!quoted.get(q.id)?.ev) quoted.set(q.id, { status: 'ready', ev: q, at: Date.now() });
    const rootId = stored?.rootId || requestedRootId;
    c = { status: stored ? 'ready' : 'loading', rootId, focusId: seed.id, prefetched: prefetch,
      // a root already in hand (the post a conversation row answers sits in
      // the Following feed) paints at once; the relays only fill the replies
      root: stored?.root || (seed.id === rootId ? seed : noteInHand(rootId)), replies: stored?.replies || [], counts: stored?.counts || {} };
    // the replies the feed already fetched for the count go in now: the
    // thread opens whole for any post that has been on screen
    adoptRepliesInHand(c);
    if (seed.id !== rootId && !c.replies.some((e) => e.id === seed.id)) c.replies.push(seed);
    c.replies.sort((a, b) => a.created_at - b.created_at);
    warmThread([c.root, ...c.replies]);
    threadCache.set(requestedRootId, c);
    threadCache.set(rootId, c);
    if (ui.noteThread?.focusId === seed.id) ui.noteThread.rootId = rootId;
    c.loading = (async () => {
      // Where a thread lives: the reply's author, the people it tags (the
      // root's author is usually first among them), the relay hints on its
      // e tags, and ours. The reply author's relays alone missed roots
      // written elsewhere — the thread then opened without its first post.
      const relaysFor = async (ev) => {
        const hints = ev.tags.filter((x) => x[0] === 'e' && /^wss?:\/\//i.test(x[2] || '')).map((x) => x[2]);
        const people = [ev.pubkey, ...ev.tags.filter((x) => x[0] === 'p').map((x) => x[1]).slice(0, 3)];
        const sets = await Promise.all(people.map((pk) => notesRelays(pk).catch(() => [])));
        return [...new Set([...hints, ...sets.flat(), ...NOTE_RELAYS])].slice(0, 12);
      };
      let relays = await relaysFor(c.root || seed);
      // Replies go in as they arrive, the page repainted in place (not
      // after the slowest relay's EOSE, which used to hold the whole
      // thread behind a spinner); the root the moment it is found.
      const onScreen = () => ui.noteThread && (ui.noteThread.rootId === c.rootId || ui.noteThread.rootId === requestedRootId);
      let paintT = null;
      const paint = () => { if (paintT || !onScreen()) return; paintT = setTimeout(() => { paintT = null; if (onScreen()) renderThreadStable(); }, 150); };
      const got = new Set(c.replies.map((e) => e.id));
      const streamed = new Map();
      const take = (e) => {
        if (!e || e.id === c.rootId || got.has(e.id)) return;
        got.add(e.id); noteForSpam(e); streamed.set(e.id, e);
        // painted whole: its face and pictures first (briefly), then the row
        warmThread([e], Date.now() + THREAD_ROW_MS).then(() => {
          if (c.replies.some((x) => x.id === e.id)) return;
          c.replies = [...c.replies, e].sort((a, b) => a.created_at - b.created_at);
          paint();
        });
      };
      await Promise.all([
        c.root ? Promise.resolve() : queryOn(relays, { ids: [rootId] }, 4000).then((roots) => { // a root can be a poll
          if (!c.root && (roots || [])[0]) { c.root = roots[0]; paint(); }
        }),
        // kind 1 replies, and NIP-22 comments naming it as their root
        queryStreamOn(relays, { kinds: [1], '#e': [rootId], limit: 80 }, take, 4500).catch(() => {}),
        queryStreamOn(relays, { kinds: [COMMENT], '#E': [rootId], limit: 120 }, take, 4500).catch(() => {}),
      ]);
      clearTimeout(paintT); paintT = null;
      let all = [...c.replies, ...streamed.values()];
      // A client that tags only the note it answered leaves the root
      // unnamed: what we resolved as the root is itself a reply. Climb —
      // fetch ITS root and re-root the thread there — a few hops at most.
      let top = c.root, topId = rootId;
      for (let hop = 0; top && hop < 4; hop++) {
        const up = rootIdOf(top);
        if (up === top.id) break;
        relays = [...new Set([...relays, ...(await relaysFor(top))])].slice(0, 14);
        const [ups, more] = await Promise.all([
          queryOn(relays, { ids: [up] }, 4000),
          queryOn(relays, { kinds: [1, COMMENT], '#e': [up], limit: 80 }, 4500),
        ]);
        const upNote = (ups || [])[0];
        if (!upNote) break;
        all = [...all, top, ...(more || [])];
        top = upNote; topId = up;
      }
      if (topId !== rootId) {
        c.root = top; c.rootId = topId;
        threadCache.set(topId, c);
        if (ui.noteThread && ui.noteThread.rootId === rootId) ui.noteThread.rootId = topId;
      }
      // an article's comments may name it only by address
      const addr = c.root && addrOf(c.root);
      if (addr) all = [...all, ...(await queryOn(relays, { kinds: [COMMENT], '#A': [addr], limit: 120 }, 4500).catch(() => []) || [])];
      for (const e of all) noteForSpam(e);
      const seen = new Set([c.rootId]);
      c.replies = all
        .filter((e) => e && e.id !== c.rootId && !seen.has(e.id) && seen.add(e.id))
        .sort((a, b) => a.created_at - b.created_at);
      c.status = 'ready';
      if (!c.prefetched) persistThread(c);
      if (ui.noteThread && ui.noteThread.rootId === c.rootId) {
        renderThreadStable();
        // 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;
          const s = ui.noteThread;
          setTimeout(() => focusThreadReply(s), 30);
        }
      }
    })().catch(() => {
      c.status = 'ready';
      if (ui.noteThread && ui.noteThread.rootId === c.rootId) renderThreadStable();
    }).finally(trimPrefetchedThreads);
    return c;
  }
  function openNoteThread(ev) {
    rememberPlace('thread');
    ui.liveStream = null;
    ui.noteThread = { rootId: rootIdOf(ev), focusId: ev.id, seed: ev, scrollPending: true };
    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) {
    const saved = threadStore.find(ref.id);
    const cached = saved && (saved.root.id === ref.id ? saved.root : saved.replies.find((e) => e.id === ref.id));
    if (cached) { openNoteThread(cached); return; }
    if (!ui.pubNotePending) toast(t('noteRefLoading')); // the pending frame says so itself
    const ev = quoted.get(ref.id)?.ev || await findNote(ref).catch(() => null);
    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();
    // the hashtags in the text as t tags (NIP-24), so topic feeds and other
    // clients' searches find the post — up to the count past which a post
    // reads as hashtag spam
    const hashtags = [...new Set([...String(text || '').matchAll(/(^|[^\w#/&])#([\p{L}\p{N}_]{2,64})(?![\w])/gu)].map((m) => normTopic(m[2])))].slice(0, HASHTAG_MAX);
    const temp = {
      id: 'pending:' + Math.random().toString(36).slice(2),
      pubkey: id.pubkey, content: text, created_at: Math.floor(Date.now() / 1000),
      tags: hashtags.map((x) => ['t', x]), 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 the feeds it would reach, before
    // any relay has heard of it: the open feed and Following, when they
    // carry your posts (Following, a people feed with you in it, Everything)
    // or a topic the post wears — not a topic feed open at the time that it
    // doesn't match, where it used to land (and then only there)
    const carries = (def) => !!def && (!!def.all || feedAuthors(def).includes(id.pubkey) || feedTopics(def).some((x) => hashtags.includes(x)));
    const feeds = [...new Set([feed, feedStates.get(FOLLOWING)].filter((c) => c && !c.stopped && carries(feedDef(c.id))))];
    for (const c of feeds) c.notes = [temp, ...c.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(mediaImeta);
      // 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]] : [];
      // the people it mentions are told (NIP-27 p tags)
      const mentions = mentionedPks(text).filter((pk) => pk !== id.pubkey && !q.some((x) => x[0] === 'p' && x[1] === pk)).map((pk) => ['p', pk]);
      const partial = { kind: 1, content: text, created_at: temp.created_at, tags: [...imeta, ...q, ...mentions, ...temp.tags, 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, ...feeds]) c.notes = c.notes.map((e) => (e.id === temp.id ? evt : e));
      render();
      return evt;
    } catch (e) {
      for (const c of [...caches, ...feeds]) c.notes = c.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);
    // and whoever the reply mentions by name (NIP-27), beyond the thread's eight
    for (const pk of mentionedPks(text)) if (pk !== id.pubkey && !pTags.includes(pk)) pTags.push(pk);
    const imeta = (ui.postMedia || []).filter((m) => m && m.url && text.includes(m.url)).map(mediaImeta);
    const root = c.root || (target.id === rootId ? target : null);
    // the root's scope: from the root itself, or — not loaded yet — copied
    // off the comment being answered, which carries it
    const scope = root
      ? [...(addrOf(root) ? [['A', addrOf(root), '']] : []), ['E', root.id, '', root.pubkey], ['K', String(root.kind)], ['P', root.pubkey]]
      : target.kind === COMMENT ? target.tags.filter((x) => ['A', 'E', 'I', 'K', 'P'].includes(x[0])) : [];
    const partial = target.kind === 1 || !scope.length ? null : {
      // NIP-22: a comment on a poll, an article, or on another comment
      kind: COMMENT,
      content: text,
      created_at: Math.floor(Date.now() / 1000),
      tags: [
        ...scope,
        ...(root && target.id === root.id
          ? [...(addrOf(root) ? [['a', addrOf(root), '']] : []), ['e', root.id, '', root.pubkey], ['k', String(root.kind)], ['p', root.pubkey]]
          : [['e', target.id, '', target.pubkey], ['k', String(target.kind)], ['p', target.pubkey]]),
        ...pTags.filter((pk) => pk !== target.pubkey && (!root || pk !== root.pubkey)).map((pk) => ['p', pk]),
        ...imeta,
        CLIENT_TAG,
      ],
    };
    const note = 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,
      ],
    };
    note.tags.push(...momentTags(s.mediaMoment));
    if (s.mediaMoment) note.content = '[' + mediaClock(s.mediaMoment.seconds) + '] ' + note.content;
    const evt = id.signer instanceof Uint8Array ? finalizeEvent(note, id.signer) : await id.signer.signEvent(note);
    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];
    noteReply(evt); // the count under the post goes up at once
    persistThread(c);
    return evt;
  }

  // The thread's replies by parent, each note's answers in the order the
  // page draws them (yours first, then oldest first); an orphan hangs off
  // the root.
  function threadTree(c) {
    const parentOf = (ev) => {
      // a comment's parent is its lowercase e; one answering the root by
      // address (an article) has only an a — the root
      if (ev.kind === COMMENT) return tagVal(ev, 'e') || c.rootId;
      const es = ev.tags.filter((x) => x[0] === 'e');
      const marked = es.find((x) => x[3] === 'reply');
      return (marked || es[es.length - 1] || [])[1] || c.rootId;
    };
    const ids = new Set([c.rootId, ...c.replies.map((e) => e.id)]);
    const children = new Map();
    for (const ev of c.replies) {
      const pid = ids.has(parentOf(ev)) ? parentOf(ev) : c.rootId;
      if (!children.has(pid)) children.set(pid, []);
      children.get(pid).push(ev);
    }
    for (const list of children.values()) list.sort((a, b) => (isMe(b.pubkey) - isMe(a.pubkey)) || (a.created_at - b.created_at));
    return children;
  }
  // The thread's posts in the order the page shows them: the root, then
  // the replies down the tree (a hidden one skipped, its answers kept).
  function threadOrder(c) {
    const children = threadTree(c), out = [];
    if (c.root) out.push(c.root);
    const walk = (pid) => { for (const ev of children.get(pid) || []) { if (!hidden(ev)) out.push(ev); walk(ev.id); } };
    walk(c.rootId);
    return out;
  }
  function threadScreen() {
    const s = ui.noteThread;
    const c = threadFor(s.seed);
    queueMicrotask(syncMediaPager); // a picture of the thread's opened full screen: the pager over its pictures
    // the conversation on screen is the best count of its own replies
    for (const e of c.replies) noteReply(e);
    const boxUnder = (ev) => !!(s.replying || (s.draft || '').trim()) && (ev.id === s.focusId || (!s.focusId && c.root && ev.id === c.root.id));
    const row = (ev) => {
      const focus = ev.id === s.focusId && ev.id !== c.rootId;
      return noteRow(ev.pubkey, ev, displayName(ev.pubkey), { open: false, focus, joined: focus && boxUnder(ev) });
    };
    // 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.
    // The box appears once Reply is tapped (or while a draft is pending) —
    // a thread opened to read used to come with an empty field under its
    // first post. Amethyst's shape: the field across the full width, the
    // tools on a row beneath it.
    // The box takes the width of the note above it and, under a focused
    // note, continues its highlight: same soft background, the bottom
    // corners rounded, the note's squared off — one panel, not a field
    // dropped in beneath a card.
    const replyBox = (joined) => h('div', {
      class: 'col thread-reply' + (joined ? ' joined' : ''),
      style: 'gap:8px;margin:0 -8px;padding:' + (joined ? '2px' : '8px') + ' 8px 10px;background:var(--accent-soft,rgba(128,128,128,.08));border-radius:' + (joined ? '0 0 8px 8px' : '8px'),
    },
      // the moment of the clip this reply is about, and a way to make it about the whole post
      s.mediaMoment ? h('div', { class: 'row small muted', style: 'gap:6px;align-items:center' },
        t('mediaCommentAt') + ' ' + mediaClock(s.mediaMoment.seconds),
        h('button', { type: 'button', class: 'btn-ghost btn-sm', 'aria-label': t('mediaMomentDrop'), title: t('mediaMomentDrop'),
          style: 'padding:0 6px;min-height:0', onClick: () => { s.mediaMoment = null; if (s.momentFor) s.momentFor = null; render(); } }, '×')) : null,
      s.preview ? draftPreview(s.draft) : null,
      mediaBar(),
      // A textarea that grows with the reply, like the chat composer: Enter
      // sends, Shift+Enter (or Ctrl+J) breaks the line — a reply used to be
      // a one-line field with no way to write a paragraph.
      h('div', { class: 'compose-box' },
      h('coinos-text', {
        class: 'thread-reply-input', placeholder: t('threadReplyHint'),
        style: 'font-family:var(--sans);min-height:64px;max-height:160px',
        value: s.draft || '',
        // a keyboard GIF or a pasted picture: attached like the paperclip's
        onMedia: (f) => 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;
        }),
        // 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; growComposer(e.target); updateMentionAc(e.target, '.thread-reply-input'); if (s.preview) render(); },
        onKeyup: (e) => { if (/^Arrow|^Home|^End/.test(e.key)) updateMentionAc(e.target, '.thread-reply-input'); },
        onKeydown: (e) => {
          mentionKey(e);
          if (e.defaultPrevented) return;
          if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); e.target.closest('.col').querySelector('.thread-reply-send')?.click(); 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;
            s.draft = el.value;
            growComposer(el);
          }
        },
      }),
      h('div', { class: 'compose-tools' },
        (ctx.uploadMedia || ctx.uploadImage) ? h('button', {
          type: 'button', class: 'compose-tool', 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,
        gifs.button('reply', 'compose-tool gif-btn'))),
      mentionList('.thread-reply-input'),
      h('div', { class: 'row reply-tools wrap', style: 'gap:8px;align-items:center' },
      // 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.
      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
          });
        },
      }),
      h('span', { class: 'grow' }),
      h('div', { class: 'row gap6 composer-options' },
        previewBtn(!!s.preview, () => { s.preview = !s.preview; render(); }),
        h('button', {
          class: 'btn-ghost btn-sm thread-reply-cancel', type: 'button',
          onClick: () => { s.replying = false; s.preview = false; s.mediaMoment = null; render(); },
        }, t('cancel'))),
      h('button', {
        class: 'btn-primary btn-sm 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 = '';
            s.replying = false; s.preview = false; s.mediaMoment = null; // sent: the box folds away
            toast(t('threadReplied'));
          } catch (e) { if (!e.silent) toast(e.message); }
          s.sending = false; render();
        },
      }, s.sending ? h('span', { class: 'spinner sm' }) : t('threadReplySend'))),
      // a picked GIF lands in the draft like an attachment, with its imeta
      gifs.sheet('reply', (g) => {
        s.draft = ((s.draft || '').replace(/\s+$/, '') + ' ' + g.url).trim();
        (ui.postMedia ||= []).push(gifMedia(g));
        const inp = document.querySelector('.thread-reply-input');
        if (inp) inp.value = s.draft;
        s.preview = true;
        render();
      }));
    // 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 = !(s.replying || (s.draft || '').trim()); // nothing to place until Reply is tapped
    const place = (ev) => {
      if (boxPlaced) return;
      if (ev.id === s.focusId || (!s.focusId && c.root && ev.id === c.root.id)) {
        kids.push(replyBox(ev.id === s.focusId && ev.id !== c.rootId));
        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')));
    }
    // Replies as a tree, not one flat line by time: each note's answers sit
    // under it, a little indented, oldest first — except your own, which go
    // first among a note's answers, so what you just wrote shows right
    // under the post instead of at the bottom of a long thread.
    const children = threadTree(c);
    const walk = (pid, depth) => {
      const list = children.get(pid) || [];
      for (const ev of list) {
        if (hidden(ev)) { walk(ev.id, depth); continue; } // its answers keep their place
        const indent = Math.min(depth, 3) * 14;
        kids.push(noteSep(), indent ? h('div', { style: 'margin-left:' + indent + 'px' }, row(ev)) : row(ev));
        place(ev);
        walk(ev.id, depth + 1);
      }
    };
    walk(c.rootId, 0);
    // No spinner: the post reads at once and its replies come in whole as
    // they arrive (Adam: rather have them pop in than wait to learn there
    // are none); "no replies" only once the relays have spoken.
    if (c.status !== 'loading' && !c.replies.length) kids.push(h('div', { class: 'small faint', style: 'text-align:center;padding:10px 0' }, t('threadNoReplies')));
    if (!boxPlaced) kids.push(replyBox(false));
    // A tapped reply deep in a long thread has to be ON SCREEN when the
    // thread opens — highlighting it somewhere below the fold reads as the
    // thread having missed it. Scroll to it after this paint; if the replies
    // are still loading the row isn't there yet, so the request stays armed
    // for the render that brings it. The root itself means the top.
    if (s.scrollPending) {
      const isRoot = !!c.root && s.focusId === c.root.id;
      setTimeout(() => {
        if (ui.noteThread !== s || !s.scrollPending) return;
        if (isRoot) { s.scrollPending = false; try { window.scrollTo({ top: 0 }); } catch {} return; }
        const el = document.querySelector('[data-focus-note]');
        if (!el) return;
        s.scrollPending = false;
        try { el.scrollIntoView({ block: 'center' }); } catch {}
      }, 60);
    }
    return h('div', { class: 'col thread-page', 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 thread-card', style: 'gap:0;padding:2px 14px' }, ...kids),
      // a real Back: the history entry under the thread restores the feed
      // (or profile) and its scroll place. A thread opened straight from a
      // link has nothing of ours under it, so no button that invents one.
      !ctx.canGoBack || ctx.canGoBack()
        ? h('button', { class: 'btn-ghost btn-block', onClick: () => ctx.goBack(() => { ui.noteThread = null; ui.liveStream = null; ui.goLive = null; }) }, t('back'))
        : null,
      ...noteOverlays());
  }

  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;
    queueMicrotask(syncMediaPager); // a picture of theirs opened full screen: the pager over their timeline
    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')))
        : (() => {
            // With other identities signed in, logging out means THIS one
            // leaves and the rest stay put; logging out of everything is
            // the second, explicit choice. Alone on the device, it's the
            // plain log-out it always was.
            const others = ctx.identities ? ctx.identities().filter((x) => !x.active) : [];
            const one = others.length > 0 && !!ctx.signOutIdentity;
            const leave = (fn) => () => {
              ui.logoutConfirm = null;
              ui.profilePk = null; ui.profEdit = null; ui.profEditFilled = false;
              fn && fn();
            };
            return h('div', { class: 'card col confirm-pop', style: 'gap:10px' },
            h('h3', { style: 'margin:0' }, (one ? t('logoutOne', { name: displayName(pk) }) : t('logout')) + '?'),
            h('p', { class: 'small muted', style: 'margin:0' },
              one ? t(ctx.identityRecoverable && ctx.identityRecoverable() ? 'logoutOneBlurbLogin' : 'logoutOneBlurbSeed') : t('logoutPopBlurb')),
            h('button', { class: 'btn-primary btn-block', onClick: leave(one ? ctx.signOutIdentity : ctx.logout) }, t('logout')),
            one ? h('button', { class: 'btn-block', onClick: leave(ctx.logout) }, t('logoutAll')) : null,
            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);
    if (bannerUrl && !draft && !mediaReady.has(bannerUrl)) warmBanner(pk);
    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),
      fullMisses.has(pk) ? h('div', { class: 'row between gap6 small muted' },
        t(full || lp.eventAt || lp.name || lp.picture ? 'profFetchFailed' : 'profNotFound'),
        h('button', { class: 'btn-sm', onClick: () => { fetchFullProfile(pk); render(); } }, t('retry'))) : null,
      h('div', { class: 'card col', style: 'gap:12px' },
        bannerUrl ? h('div', { class: 'profile-banner', style: `background-image:url(${JSON.stringify(draft ? bannerUrl : mediaSrc(bannerUrl, mediaReady.get(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)})` })
            // a tap shows the picture itself, full size
            : profileOf(pk)?.picture
              ? h('div', { style: 'flex:0 0 auto;cursor:zoom-in', role: 'button', 'aria-label': name,
                  onClick: (e) => { e.stopPropagation(); ctx.openImage && ctx.openImage(profileOf(pk).picture); } },
                  avatar(pk, 'chat-avatar profile-avatar', false))
              : 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)),
        ui.profEdit ? null : liveBanner(pk),
        mine && !ui.profEdit && canGoLive() && !liveNowOf(pk) ? h('button', { class: 'btn-sm go-live-btn', style: 'align-self:flex-start', onClick: openGoLive },
          h('span', { class: 'go-live-dot' }), t('goLive')) : 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,
        ui.profEdit ? null : socialLine(pk),
        ui.profEdit ? null : socialList(pk),
        // The npub in full, monospace, tap to copy — behind the "Public key"
        // link on the line above, so it costs no room until it's asked for.
        // Its QR sits above it: the same key for a phone held up to the
        // screen. The bare npub, lowercase — what every app's scanner takes.
        ui.profEdit || ui.npubShown !== pk || !npub ? null
          : h('div', { class: 'npub-qr', style: 'align-self:center', html: qrSvg(npub) }),
        ui.profEdit || ui.npubShown !== pk ? null : h('button', {
          type: 'button', class: 'addr-box break npub-box', title: t('copy'),
          onClick: async () => { try { await navigator.clipboard.writeText(npub); toast(t('copied')); } catch {} },
        }, h('span', { class: 'npub-text' }, npub),
          h('span', { class: 'npub-copy', 'aria-hidden': 'true', html: '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect width="14" height="14" x="8" y="8" rx="2" ry="2"/><path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"/></svg>' })),
        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 prof-actions' },
                h('button', { class: 'btn-primary grow', onClick: () => {
                  const peer = pk;
                  // leave the thread this profile may sit over too: the
                  // screen router shows an open thread before the chat, so
                  // a reply half-typed under their post used to win here
                  ui.profilePk = null; ui.profOverThread = false;
                  ui.noteThread = null; ui.liveStream = null; ui.goLive = null; ui.userSearch = null; ui.feedEdit = 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.liveStream = null; ui.goLive = null;
                  ui.userSearch = null;
                  ui.chatOpen = false;
                  ctx.showSend({ fresh: true });
                  ui.send.recipients[0].address = npubStr;
                  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')),
              )),
      // The timeline they see: their follows as a feed, with a public URL.
      mine ? null : h('div', { class: 'row gap6' },
        h('button', { class: 'btn-ghost grow', onClick: () => openFeedOf(pk) }, t('profTheirFeed')),
        // ...or into one of your lists (a feed of people)
        myPubkeys().length ? h('button', { class: 'btn-ghost grow', 'aria-label': t('listAddTo'), onClick: () => { ui.listPick = pk; render(); } }, '\u2630 ' + t('listAddTo')) : null),
      // The lists they curate (follow sets and packs): each opens as a feed.
      (() => {
        const c = listsFor(pk);
        if (!c.items.length) return null;
        return h('div', { class: 'col', style: 'gap:6px' },
          h('div', { class: 'small muted', style: 'padding:0 2px' }, t('profLists')),
          h('div', { class: 'row feed-chips prof-lists' },
            ...c.items.map((p) => h('button', {
              class: 'feed-chip', type: 'button', title: t('feedListPeople', { n: p.n }),
              onClick: () => openListFeed(p),
            }, p.title, ' ', h('span', { class: 'faint' }, String(p.n))))));
      })(),
      // muted: say so, with the way back, where their posts still show
      !mine && isMuted(pk)
        ? h('div', { class: 'row gap6 small muted prof-muted', style: 'align-items:center' },
            h('span', { class: 'grow' }, t('profMutedBanner')),
            h('button', { class: 'btn-sm', type: 'button', onClick: () => toggleMute(pk) }, t('postUnmute')))
        : null,
      // 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);
        // Posts | Replies: the replies are their side of other people's
        // conversations, apart from what they posted themselves
        // Streams joins the tabs once they've streamed
        const streamed = pastOf(pk).length > 0;
        const tab = profTab(pk) === 'streams' && !streamed ? 'posts' : profTab(pk);
        const shown = c.notes.filter((e) => (tab === 'replies') === replyish(e));
        // a tab that holds only a few of the pages fetched so far (someone
        // who mostly replies, or mostly posts) asks for older ones by itself:
        // too short to scroll means the scroll that loads more never comes
        // (five pages at most per tab: someone who never replies must not
        // have their whole history paged through looking for one)
        const fill = c.autoFill && c.autoFill.tab === tab ? c.autoFill : (c.autoFill = { tab, n: 0 });
        if (tab !== 'streams' && c.status === 'ready' && shown.length < 12 && !c.end && !c.loadingMore && fill.n < 5) {
          fill.n++;
          queueMicrotask(() => loadOlderNotes(pk).catch(() => {}));
        }
        const tabs = h('div', { class: 'seg prof-tabs', style: 'display:flex;width:100%' },
          ...['posts', 'replies', ...(streamed ? ['streams'] : [])].map((k) => h('button', {
            type: 'button', class: (tab === k ? 'active ' : '') + 'grow', 'data-tab': k,
            onClick: () => { if (tab === k) return; ui.profTab = { pk, tab: k }; c.win = null; render(); },
          }, t(k === 'posts' ? 'profTabPosts' : k === 'replies' ? 'profTabReplies' : 'profTabStreams'))));
        if (tab === 'streams') return h('div', { class: 'col', style: 'gap:8px' }, tabs, pastStreams(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.
        const none = t(tab === 'replies' ? 'profRepliesNone' : 'profNotesNone');
        if (!shown.length) {
          const waiting = c.status === 'loading' || c.loadingMore || (!c.end && c.status === 'ready' && fill.n < 5);
          return h('div', { class: 'col', style: 'gap:8px' }, tabs,
            waiting && c.notes.length
              ? h('div', { class: 'row gap6', style: 'justify-content:center;padding:8px 0' }, h('span', { class: 'spinner sm' }))
              // nothing in hand yet: the empty line holds the height, unseen (no spinner)
              : h('div', { class: 'small faint', style: 'text-align:center' + (waiting ? ';visibility:hidden' : '') }, none));
        }
        return h('div', { class: 'col', style: 'gap:8px' },
          tabs,
          h('div', { class: 'card col notes-feed', style: 'gap:0', 'data-key': 'prof-notes:' + tab },
            ...(c.winList = () => c.notes.filter((e) => (profTab(pk) === 'replies') === replyish(e)), windowedRows(c, shown, (ev) => keyed(noteRow(pk, ev, name, { context: profTab(pk) === 'replies' }), ev.id)))),
          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.profCompose = null; ctx.goBack(() => { ui.profilePk = null; ui.profOverThread = false; ui.pubProf = null; ui.profEdit = null; ui.profEditFilled = false; }); } }, t('back')),
      mine ? logoutPop() : null,
      mine ? switchPop() : null,
      ...noteOverlays());
  }

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

  // ---- 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 || '');
  let postAttachGeneration = 0;
  // Upload, then hand the URL to whichever draft asked for it.
  async function attachTo(file, place) {
    const upload = ctx.uploadMedia || ctx.uploadImage;
    if (!file || !upload) return;
    ui.postUploading = true; render();
    try {
      // (a URL, or what a stream's upload says of it: its type, size, length)
      const got = await upload(file);
      const url = typeof got === 'string' ? got : got.url;
      // A post canceled while its upload was in flight must stay canceled.
      // `false` lets that composer reject the late result without affecting
      // the reply composer, which shares this helper.
      if (place(url) !== false) (ui.postMedia ||= []).push(typeof got === 'string' ? { url, m: file.type || '' } : { m: file.type || '', ...got });
    } catch (e) { toast(e.message || String(e)); }
    ui.postUploading = false; render();
  }
  const attachMedia = (file) => {
    const generation = postAttachGeneration;
    return attachTo(file, (url) => {
      if (generation !== postAttachGeneration) return false;
      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;
      return true;
    });
  };
  function cancelPost() {
    postAttachGeneration++;
    ui.postCancelConfirm = false;
    ui.profCompose = null;
    ui.postMedia = [];
    ui.postPreview = false;
    discardDraft(POST_DRAFT);
    render();
  }
  function requestCancelPost() {
    if (composeText().length > 20 || ui.postUploading || (ui.postMedia || []).length) {
      ui.postCancelConfirm = true;
      render();
      return;
    }
    cancelPost();
  }
  function postCancelWarning() {
    if (!ui.postCancelConfirm) return null;
    const keep = () => { ui.postCancelConfirm = false; render(); };
    return h('div', {
      class: 'confirm-pop-backdrop',
      onClick: (event) => { if (event.target === event.currentTarget) keep(); },
    },
      h('div', { class: 'card col confirm-pop', style: 'gap:10px' },
        h('h3', { style: 'margin:0' }, t('postDiscardTitle')),
        h('div', { class: 'small muted' }, t('postDiscardBody')),
        h('div', { class: 'row gap6' },
          h('button', { class: 'btn-ghost grow', onClick: keep }, t('postKeepEditing')),
          h('button', { class: 'btn-danger grow', onClick: cancelPost }, t('postDiscard')))));
  }
  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>';

  // ---- 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')));
  }
  // Shrinking, then uploading, as a labelled bar with its percentage — the
  // paperclip's spinner said only "busy", however long a video took.
  function mediaBar() {
    const m = ui.mediaProgress;
    if (!m) return null;
    const label = t(m.stage === 'shrink' ? 'mediaShrinking' : 'mediaUploading');
    return h('div', { class: 'media-progress', role: 'progressbar', 'aria-valuemin': '0', 'aria-valuemax': '100', 'aria-valuenow': String(m.pct), 'aria-label': label },
      h('div', { class: 'row between small' }, h('span', { class: 'muted' }, label + '…'), h('span', { class: 'media-progress-pct' }, m.pct + '%')),
      h('div', { class: 'media-progress-track' }, h('div', { class: 'media-progress-fill', style: 'width:' + m.pct + '%' })));
  }
  const previewBtn = (on, toggle) => h('button', {
    type: 'button', class: 'btn-ghost btn-sm compose-preview-toggle',
    title: on ? t('composePreviewHide') : t('composePreview'),
    'aria-label': t('composePreview'),
    'aria-pressed': String(on),
    onClick: toggle,
  }, t('composePreview'));
  function postComposer() {
    if (ui.profCompose == null && !draftFor(POST_DRAFT)) return null;
    const text = composeText();
    return h('div', { class: 'col', style: 'gap:8px' },
      // the attach and GIF buttons sit in the field's corner: the row under
      // it is for what you do with the post (Post, Preview, Cancel)
      h('div', { class: 'compose-box' },
      h('coinos-text', {
        class: 'post-input', placeholder: t('profComposePh'),
        style: 'font-family:var(--sans);min-height:84px;max-height:320px',
        value: text,
        // the field is focused, so the morph leaves it: put the URL in by hand
        onMedia: (f) => attachMedia(f).then(() => { const el = document.querySelector('.post-input'); if (el) el.value = composeText(); }),
        onKeydown: mentionKey,
        onKeyup: (ev) => { if (/^Arrow|^Home|^End/.test(ev.key)) updateMentionAc(ev.target, '.post-input'); },
        onInput: (ev) => {
          ui.profCompose = ev.target.value;
          setDraft(POST_DRAFT, ev.target.value);
          updateMentionAc(ev.target, '.post-input');
          // 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();
        },
      }),
      h('div', { class: 'compose-tools' },
        (ctx.uploadMedia || ctx.uploadImage) ? h('button', {
          type: 'button', class: 'compose-tool', 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,
        gifs.button('post', 'compose-tool gif-btn'),
        canGoLive() ? h('button', { type: 'button', class: 'compose-tool go-live-tool', title: t('goLive'), 'aria-label': t('goLive'), onClick: openGoLive },
          h('span', { class: 'go-live-dot' })) : null)),
      mentionList('.post-input'),
      ui.postPreview ? draftPreview(text) : null,
      mediaBar(),
      h('div', { class: 'row gap6 wrap post-actions' },
        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')),
        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('div', { class: 'row gap6 composer-options' },
          previewBtn(!!ui.postPreview, () => { ui.postPreview = !ui.postPreview; render(); }),
          h('button', { class: 'btn-ghost btn-sm', onClick: requestCancelPost }, t('cancel')))),
      postCancelWarning(),
      gifs.sheet('post', (g) => {
        const cur = composeText().replace(/\s+$/, '');
        const next = (cur ? cur + '\n' : '') + g.url;
        ui.profCompose = next;
        setDraft(POST_DRAFT, next);
        (ui.postMedia ||= []).push(gifMedia(g));
        ui.postPreview = true;
        const el = document.querySelector('.post-input');
        if (el) el.value = next;
        render();
      }));
  }

  // ---- the feed view --------------------------------------------------------
  // One line saying what a feed is made of: who, and on what.
  function feedSummary(f) {
    const n = (f.authors || []).length + (f.priv || []).length;
    const people = f.follows
      ? (n ? t('feedSumFollowsPlus', { n }) : t('feedSumFollows'))
      : n === 1 ? displayName((f.authors || [])[0] || f.priv[0])
        : n ? t('feedSumPeople', { n }) : '';
    const packs = ((f.packs || []).map((p) => (packOf(p) || {}).title || p.title).filter(Boolean)).join(', ');
    const topics = feedTopics(f).map((x) => '#' + x).join(' ');
    return [people, packs, topics].filter(Boolean).join(' \u00b7 ') || t('feedNoQuery');
  }
  // The row of feeds under the title: Following, then yours, then + for
  // a new one. A topic opened for the session sits at the end until saved.
  function feedChips() {
    const items = feedList();
    const cur = feedDef();
    if (cur && adhocFeeds.has(cur.id)) items.push(cur);
    return h('div', { class: 'row feed-chips', 'data-key': 'feed-chips' },
      ...items.map((f) => h('button', {
        class: 'feed-chip' + (f.id === curFeedId ? ' on' : ''), type: 'button', 'data-key': 'chip:' + f.id,
        onClick: () => switchFeed(f.id),
        // someone's timeline carries the person, not a name — an empty
        // label left a blank black pill
      }, f.name || (f.of ? t('feedOfTitle', { name: displayName(f.of) }) : feedSummary(f)))),
      h('button', { class: 'feed-chip add', type: 'button', title: t('feedNew'), 'aria-label': t('feedNew'), onClick: () => openFeedEditor(null) }, '+'));
  }
  // The sheets a post (or a person) can open: the ⋯ menu, the reaction
  // picker, the list picker. Every screen that shows a post draws them —
  // the thread and profile pages once left the ⋯ tap doing nothing.
  const noteOverlays = () => [noteSheet(), editSheet(), deleteAskSheet(), reactPicker(), listPickSheet(), reportSheet(), signinSheet(), feedMenuSheet()];
  // The feed's own menu, behind the ⋯ in its header.
  function feedMenuSheet() {
    if (!ui.feedMenu) return null;
    const def = feedDef();
    const close = () => { ui.feedMenu = null; render(); };
    if (!def) { ui.feedMenu = null; return null; }
    const visitor = isVisitor();
    const item = (icon, label, onClick) => h('button', { class: 'btn-block', style: 'text-align:left', 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 msg-sheet' },
        feedPath(def, { share: true }) ? item('\u{1F517}', t('feedShare'), () => shareFeed(def)) : null,
        item('\u{1F4E1}', t('feedRelays') + (feedRelays(def) ? ' \u00b7 ' + feedRelays(def).length : ''), () => { ui.feedRelayEdit = { id: def.id, input: '' }; }),
        def.builtin || visitor ? null
          : adhocFeeds.has(def.id)
            ? item('\u{1F4BE}', t('feedSaveAdhoc'), () => (def.of ? saveTimelineFeed(def) : openFeedEditor(def)))
            // a saved timeline is the person, nothing to edit — only to drop;
            // the drop sits in the menu for every feed, not behind Edit
            : [def.of ? null : item('\u270e', t('feedEdit'), () => openFeedEditor(def)),
              item('\u{1F5D1}', t('feedDelete'), () => deleteFeed(def.id))],
        h('button', { class: 'btn-ghost btn-block', onClick: close }, t('back'))));
  }
  // ---- a visitor at the action bar ---------------------------------------
  // Reading is free; zapping, replying, reacting and following take a
  // wallet. A visitor who taps one gets the sign-in doors right there, and
  // the page they were on is remembered so a sign-in lands back on it.
  const RETURN_KEY = 'coinos-after-signin';
  const rememberReturn = () => { try { sessionStorage.setItem(RETURN_KEY, location.pathname + location.search); } catch {} };
  function signinAsk() {
    if (!isVisitor()) return false;
    rememberReturn();
    ui.signinAsk = true;
    render();
    return true;
  }
  function toFrontDoor() {
    rememberReturn();
    ui.signinAsk = null; ui.pubProf = null; ui.chatOpen = false; ui.msgView = null;
    ui.userSearch = null; ui.profilePk = null; ui.profOverThread = false; ui.noteThread = null; ui.liveStream = null; ui.goLive = null; ui.feedRelayEdit = null;
    render();
    try { window.scrollTo({ top: 0 }); } catch {}
  }
  function signinSheet() {
    if (!ui.signinAsk) return null;
    const close = () => { ui.signinAsk = null; render(); };
    return h('div', { class: 'confirm-pop-backdrop', onClick: (e) => { if (e.target === e.currentTarget) close(); } },
      h('div', { class: 'card col msg-sheet', style: 'gap:12px' },
        h('h3', { style: 'margin:0' }, t('askSignInTitle')),
        h('div', { class: 'small muted' }, t('askSignInBody')),
        hook('frontDoorSignin') || h('button', { class: 'btn-primary btn-block', onClick: toFrontDoor }, t('nlSignIn')),
        h('button', { class: 'btn-block', onClick: toFrontDoor }, t('askSignInCreate')),
        h('button', { class: 'btn-ghost btn-block', onClick: close }, t('askNotNow'))));
  }
  // Back to where the sign-in was asked for, once a wallet is open.
  function returnAfterSignin() {
    let back = null;
    try { back = sessionStorage.getItem(RETURN_KEY); sessionStorage.removeItem(RETURN_KEY); } catch {}
    if (!back) return;
    setTimeout(() => {
      try {
        if (back.startsWith('feed:')) { showFeed(back.slice(5)); render(); return; }
        const [path, q] = back.split('?');
        if (/^\/feed(\/|$)/i.test(path)) { openFeedUrl(path.replace(/^\/feed\/?/i, ''), q ? '?' + q : ''); return; }
        const pk = parseNostrPubkey(path.replace(/^\//, ''));
        if (pk) { ui.chatOpen = false; openProfile(pk); }
      } catch {}
    }, 0);
  }
  function appBottomNav() {
    const visitor = isVisitor();
    const me = !visitor && ctx.shownPubkey ? ctx.shownPubkey() : null;
    // a stream (or Go live) over the shell is a place of its own: no button
    // is "here", so the one tapped goes there (Feed under a stream thought it
    // was home and only scrolled the hidden feed)
    const active = ui.liveStream || ui.goLive ? 'live' : ui.userSearch ? 'search' : me && ui.profilePk === me && !ui.noteThread ? 'profile' : ui.noteThread || ui.profilePk ? 'feed' : ui.chatOpen
      ? ui.msgView === 'feed' ? 'feed' : ui.msgView === 'notifs' ? 'notifs' : 'messages' : ui.tab === 'settings' ? 'settings' : 'wallet';
    const leavePage = () => {
      stopFeedWatch(); stopNotifWatch();
      // Top-level destinations must leave any feature page covering the shell.
      for (const key of ['profilePk', 'profEdit', 'profEditFilled', 'profOverThread', 'noteThread', 'liveStream', 'goLive', 'liveReport', 'userSearch',
        'zapSetup', 'hatShop', 'feedEdit', 'feedMenu', 'feedRelayEdit', 'noteSheet', 'reactPick', 'reportSheet',
        'msgReplyTo', 'msgSheet', 'arkCoinsPage', 'arkExitPage', 'nameEditOpen', 'nostrReconnect', 'nostrLoginOpen',
        'pos', 'lockedGift', 'viewGift', 'claimChoose', 'signinAsk']) ui[key] = null;
      if (!visitor) { ui.screen = 'wallet'; ui.pubProf = null; }
    };
    // The chat list used to carry the notifications row and its count; the
    // nav's bell carries the dot now.
    const notifsWaiting = () => {
      if (!myPubkeys().length) return 0;
      refreshNotifs(); // throttled inside; keeps the count honest
      return notifUnread();
    };
    const icon = (paths) => '<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">' + paths + '</svg>';
    const button = (id, label, paths, onClick, cls = '') => h('button', {
      type: 'button', class: 'app-nav-button' + cls + (!visitor && (id === 'messages' ? hook('unreadMessages') : id === 'notifs' && notifsWaiting()) ? ' unread' : ''),
      'aria-label': label, 'aria-current': active === id ? 'page' : undefined,
      onClick: (e) => {
        // An open composer doesn't follow you around: back on the feed it sat
        // at the top, out of sight, and hid the Post button. Its words are
        // already the saved draft (it still shows, and Post reopens it).
        ui.profCompose = null;
        onClick(e);
      },
    }, h('span', { html: icon(paths) }), h('span', {}, label));
    // Your profile heads the desktop rail: a bigger face and your name, where
    // the header's avatar sits on a phone.
    const profileItem = me ? h('button', {
      type: 'button', class: 'app-nav-button app-nav-wide app-nav-profile',
      'aria-label': t('profYourProfile'), 'aria-current': active === 'profile' ? 'page' : undefined,
      onClick: () => { ui.profCompose = null; leavePage(); openProfile(me); render(); window.scrollTo({ top: 0 }); },
    }, avatar(me, 'chat-avatar app-nav-ava', false), h('span', { class: 'app-nav-name' }, displayName(me))) : null;
    return h('nav', {
      class: 'app-bottom-nav', 'data-key': 'app-bottom-nav',
    },
      profileItem,
      button('feed', t('feedTitle'), '<path d="M4 22h16a2 2 0 0 0 2-2V4a2 2 0 0 0-2-2H8a2 2 0 0 0-2 2v16a2 2 0 0 1-2 2m0 0a2 2 0 0 1-2-2v-9c0-1.1.9-2 2-2h2"/><path d="M18 14h-8M15 18h-5M10 6h8v4h-8z"/>', () => {
        // A destination tab is a destination: tapping Feed while already
        // there always returns to its top. Only the explicit "x new posts"
        // pill jumps to the first unread arrival.
        // (someone's timeline or a #tag opened from a post isn't the Feed
        // tab — the tab is your own feeds, the one you last had on)
        const own = adhocFeeds.has(curFeedId) ? homeFeedId() : curFeedId;
        if (active === 'feed' && ui.msgView === 'feed' && !ui.profilePk && !ui.noteThread && !ui.feedEdit && own === curFeedId) { glideToTop(); return; }
        leavePage();
        if (visitor) { ui.pubProf = true; openFirehose(); } else showFeed(own);
        window.scrollTo({ top: 0 });
      }),
      button('messages', t('msgDmsTitle'), '<path d="M21 11.5a8.4 8.4 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.4 8.4 0 0 1-3.8-.9L3 21l1.9-5.7a8.4 8.4 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.4 8.4 0 0 1 3.8-.9h.5a8.5 8.5 0 0 1 8 8z"/>', () => {
        if (visitor) { toFrontDoor(); return; }
        leavePage(); ui.chatOpen = true; ui.msgView = 'home'; render();
        window.scrollTo({ top: 0 });
      }),
      button('notifs', t('alertsTitle'), '<path d="M18 8a6 6 0 0 0-12 0c0 7-3 7-3 9h18c0-2-3-2-3-9M10 21h4"/>', () => {
        if (visitor) { toFrontDoor(); return; }
        leavePage(); openNotifs();
        window.scrollTo({ top: 0 });
      }),
      button('wallet', t('settingsWallet'), '<path d="M20 8V5H5a2 2 0 0 0 0 4h16v11H5a2 2 0 0 1-2-2V7"/><path d="M21 12h-5v5h5"/><path d="M17 14.5h.01"/>', () => {
        if (isVisitor()) { toFrontDoor(); return; }
        leavePage();
        ui.txDetail = null; ui.arkMoveDetail = null; ui.arkReconDetail = null; ui.arkExitDetail = null; ui.giftDetail = null;
        ui.chatOpen = false; ui.msgView = null; ui.tab = 'receive';
        render(); window.scrollTo({ top: 0 });
      }),
      // Settings joins the nav where it's the desktop rail (the header's own
      // gear steps aside there); a phone's bar keeps four.
      ctx.openSettingsPage ? button('settings', t('tabSettings'), '<circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09a1.65 1.65 0 0 0-1-1.51 1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09a1.65 1.65 0 0 0 1.51-1 1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33h.09a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82v.09a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/>', () => {
        if (visitor) { toFrontDoor(); return; }
        leavePage(); ctx.openSettingsPage(null);
      }, ' app-nav-wide') : null);
  }
  // ---- media views: a feed's pictures as a grid, its videos to flip through --
  // All / Images / Videos sits under the feed chips. Images lays the feed's
  // pictures out as a grid; Videos opens straight into a full-screen pager,
  // one clip per screen, the next a flick away. The pager shows nothing but
  // the picture or clip until it's tapped: then the author, the post's words
  // as a caption, and its likes and sats. The pager is a place (Back closes
  // it), built outside the morph so a repaint never restarts a playing clip.
  const MEDIA_MODE_KEY = 'coinos-feed-media';
  let mediaMode = 'all';
  try { const m = localStorage.getItem(MEDIA_MODE_KEY); if (m === 'replies' || m === 'images' || m === 'videos' || m === 'live' || m === 'articles') mediaMode = m; } catch {}
  // Notes and Conversations are lists of posts (the feed's own state, or its
  // Conversations view); the rest are grids read from the media index.
  const listView = () => mediaMode === 'all' || mediaMode === 'replies';
  const mediaKey = (it) => it.ev.id + '|' + it.url;
  // the picture an imeta tag names for a clip (NIP-92 `image`), if any
  const posterOf = (ev, url) => {
    for (const x of ev.tags || []) {
      if (x[0] !== 'imeta' || !x.includes('url ' + url)) continue;
      const img = x.find((p) => typeof p === 'string' && p.startsWith('image '));
      if (img) return img.slice(6);
    }
    return null;
  };
  // ---- the media index: each feed's pictures and clips, kept apart -------
  // (src/media-cache.js) The grid reads from here, not from the feed's page
  // of posts: a reload paints what was found before, at once, and the crawl
  // for more picks up where it stopped instead of re-reading the relays.
  const mediaIdx = new Map(); // key -> { key, images: Map, videos: Map, checked: Set, until, end, loaded }
  const mediaIdxKey = (feedId) => (mePk() || 'visitor') + '|' + feedId;
  // a post's clips: a video event's file, or the clips linked in a note
  const clipUrlsOf = (ev) => (isVideoEvent(ev) ? [videoEventFile(ev)?.url].filter(Boolean) : noteVideoUrls(ev.content));
  const hasMediaOf = (ev, kind) => ev.kind === REPOST ? false : kind === 'videos' ? clipUrlsOf(ev).length > 0
    : noteMediaUrls(ev.content).some((u) => !u.startsWith('https://i.ytimg.com/'));
  function mediaIndex(feedId) {
    const key = mediaIdxKey(feedId);
    let r = mediaIdx.get(key);
    if (r) return r;
    r = { key, replies: !!(feedDef(feedId) || {}).replies, images: new Map(), videos: new Map(), articles: new Map(), art: { until: 0, end: 0, empty: 0, head: 0 }, checked: new Set(), until: 0, end: false, empty: 0, loaded: false };
    mediaIdx.set(key, r);
    loadMediaIndex(key).then(async (rec) => {
      if (rec) {
        for (const kind of ['images', 'videos']) for (const e of rec[kind] || []) if (!r[kind].has(e.id)) r[kind].set(e.id, e);
        if (rec.until && (!r.until || rec.until < r.until)) r.until = rec.until;
        for (const e of rec.articles || []) fileArticle(r, e);
        if (rec.art) {
          if (rec.art.until && (!r.art.until || rec.art.until < r.art.until)) r.art.until = rec.art.until;
          if (rec.art.end && Date.now() - rec.art.end < 86_400_000) r.art.end = r.art.end || rec.art.end;
        }
        // (the bottom of a feed isn't kept: see crawlMedia)
      }
      // kept frames first, so the first paint of the grid is pictures
      await Promise.all([warmVideoThumbs([...r.videos.values()]),
        warmTileThumbs([...r.images.values()].flatMap((e) => noteMediaUrls(e.content)))]);
      r.loaded = true;
      if (!listView()) scheduleRepaint();
    });
    return r;
  }
  function saveMediaIdx(r) {
    clearTimeout(r.saveT);
    r.saveT = setTimeout(() => {
      const list = (m) => [...m.values()].sort((a, b) => b.created_at - a.created_at);
      saveMediaIndex(r.key, { images: list(r.images), videos: list(r.videos), articles: list(r.articles),
        art: { until: r.art.until, end: r.art.end }, until: r.until });
    }, 1500);
  }
  // file the posts that carry media; each post is looked at once
  function indexMedia(r, evs) {
    let n = 0;
    for (const e of evs) {
      if (r.checked.has(e.id)) continue;
      r.checked.add(e.id);
      if (r.replies ? !replyish(e) : !FEED_KINDS.includes(e.kind) || isReply(e)) continue;
      for (const kind of ['images', 'videos']) if (!r[kind].has(e.id) && hasMediaOf(e, kind)) { r[kind].set(e.id, e); n++; }
    }
    if (n) saveMediaIdx(r);
    return n;
  }
  // Older posts for the grid, read straight into the index: a hundred a
  // time, no waiting on avatars, pictures and link cards (the grid shows
  // none of that), and the feed's own page of posts left as it was.
  let mediaCrawling = null;
  function crawlMedia(c = feedNow(), kind = mediaMode === 'videos' ? 'videos' : 'images') {
    const def = feedDef(c.id);
    if (!def || !feedHasQuery(def)) return Promise.resolve();
    if (def.curated) return loadOlderFeed(); // a curated feed pages its own way
    const r = mediaIndex(c.id);
    // A grid is never at its end (Adam, 2026-10-17: "I should never be all
    // caught up"): the bottom it found — the relays answering empty — is
    // looked past again a few minutes on.
    if (r.end && Date.now() - r.end > 300_000) { r.end = false; r.empty = 0; }
    if (!r.loaded || r.end || mediaCrawling) return mediaCrawling || Promise.resolve();
    mediaCrawling = (async () => {
      scheduleRepaint();
      // Clips are rare (one post in a hundred, on a busy relay), so a crawl
      // keeps reading pages until it has found a few, or read several.
      const had = r[kind].size;
      for (let pass = 0; pass < 5 && r[kind].size - had < 6; pass++) {
        const from = [r.until, c.notes.at(-1)?.created_at].filter(Boolean);
        const until = (from.length ? Math.min(...from) : Math.floor(Date.now() / 1000) + 1) - 1;
        let oldest = Infinity, saw = 0;
        const sink = (ev) => {
          saw++;
          if (ev.created_at < oldest) oldest = ev.created_at;
          noteForSpam(ev);
          indexMedia(r, [ev]);
        };
        try { await feedPass({ until, limit: 100 }, { sink }, c, FEED_KINDS, FEED_LIMIT, r.deep ? TOPIC_ARCHIVE_RELAYS : null); } catch {}
        if (c.stopped) break;
        if (saw) { r.empty = 0; r.until = Math.min(oldest, until); continue; }
        // Nothing older on the feed's relays: the big ones keep days, so
        // the history goes on on the archive relays, which keep years (the
        // grid stopped at five clips, "all caught up")
        if (!r.deep) { r.deep = true; pass--; continue; }
        // an empty answer is the bottom only when it repeats: a relay that
        // timed out, or a socket the phone froze, answers empty too
        if (++r.empty >= 3) { r.end = Date.now(); break; }
        await new Promise((ok) => setTimeout(ok, 1500 * r.empty));
      }
      saveMediaIdx(r);
    })().finally(() => { mediaCrawling = null; scheduleRepaint(); });
    return mediaCrawling;
  }

  // ---- Articles: the feed's long-form posts (NIP-23) ----------------------
  // The feed itself reads notes and polls; articles are asked for apart, from
  // the same people, topics and relays, with a cursor of their own (they're
  // sparse: a page of notes back is not a page of articles back). Kept by
  // address, so an edited article replaces its old copy.
  const ARTICLE_PAGE = 50;
  function fileArticle(r, e) {
    if (!e || e.kind !== ARTICLE) return false;
    const k = e.pubkey + ':' + ((e.tags || []).find((x) => x[0] === 'd') || [])[1];
    const cur = r.articles.get(k);
    if (cur && cur.created_at >= e.created_at) return false;
    r.articles.set(k, e);
    return true;
  }
  let articlesCrawling = null;
  function crawlArticles(c = feedNow()) {
    const def = feedDef(c.id);
    if (!def || !feedHasQuery(def)) return Promise.resolve();
    const r = mediaIndex(c.id);
    const a = r.art;
    if (!r.loaded || articlesCrawling) return articlesCrawling || Promise.resolve();
    // newer ones first, now and then; older ones while the list's foot is near
    const newest = Math.max(0, ...[...r.articles.values()].map((e) => e.created_at));
    const head = newest && Date.now() - a.head > 5 * 60_000;
    if (!head && a.end) return Promise.resolve();
    articlesCrawling = (async () => {
      scheduleRepaint();
      let saw = 0, oldest = Infinity;
      const sink = (ev) => {
        if (ev.kind !== ARTICLE) return;
        saw++;
        if (ev.created_at < oldest) oldest = ev.created_at;
        if (fileArticle(r, ev)) saveMediaIdx(r);
      };
      const until = (a.until || Math.floor(Date.now() / 1000) + 1) - 1;
      const span = head ? { since: newest + 1 } : { until };
      const filter = { kinds: [ARTICLE], limit: ARTICLE_PAGE, ...span };
      if (def.curated) {
        // Popular's rule for articles too: prose in the reader's language
        // that at least two other people reacted to, reposted, zapped or
        // answered. The relays' raw newest is mostly spam and feed bots.
        const relays = feedRelaysOr(def, POPULAR_RELAYS);
        const wide = [...new Set([...relays, ...NOTE_RELAYS])];
        const evs = (await queryOn(wide, { ...filter, limit: 100 }, 5000).catch(() => [])).filter((e) => e.kind === ARTICLE);
        for (const ev of evs) { saw++; if (ev.created_at < oldest) oldest = ev.created_at; }
        const cands = curateFeed(evs).filter((e) => !hidden(e));
        if (cands.length) {
          const coord = (e) => ARTICLE + ':' + e.pubkey + ':' + ((e.tags.find((x) => x[0] === 'd') || [])[1] || '');
          const byCoord = new Map(cands.map((e) => [coord(e), e])), byId = new Map(cands.map((e) => [e.id, e]));
          const who = new Map(); // article id -> Set(pubkey)
          const kinds = [1, 6, 7, 16, 1111, 9735];
          const [ra, re] = await Promise.all([
            queryOn(wide, { kinds, '#a': [...byCoord.keys()], limit: 2000 }, 4500).catch(() => []),
            queryOn(wide, { kinds, '#e': [...byId.keys()], limit: 2000 }, 4500).catch(() => []),
          ]);
          for (const x of [...ra, ...re]) {
            // a zap receipt's sender is in its description, not its pubkey
            let from = x.pubkey;
            if (x.kind === 9735) { try { from = JSON.parse((x.tags.find((t) => t[0] === 'description') || [])[1] || '{}').pubkey || null; } catch { from = null; } }
            const hits = new Set();
            for (const tg of x.tags) {
              if (tg[0] === 'a' && byCoord.has(tg[1])) hits.add(byCoord.get(tg[1]));
              if (tg[0] === 'e' && byId.has(tg[1])) hits.add(byId.get(tg[1]));
            }
            for (const e of hits) if (from && from !== e.pubkey) { if (!who.has(e.id)) who.set(e.id, new Set()); who.get(e.id).add(from); }
          }
          for (const e of cands) if ((who.get(e.id)?.size || 0) >= 2 && fileArticle(r, e)) saveMediaIdx(r);
        }
      } else {
        try { await feedPass(span, { sink }, c, [ARTICLE], ARTICLE_PAGE); } catch {}
      }
      if (head) a.head = Date.now();
      else if (saw) { a.empty = 0; a.until = Math.min(oldest, until); }
      else if (++a.empty >= 3) a.end = Date.now();
      saveMediaIdx(r);
    })().finally(() => { articlesCrawling = null; scheduleRepaint(); });
    return articlesCrawling;
  }
  function articleList(c) {
    const r = mediaIndex(c.id);
    const items = [...r.articles.values()].filter((e) => !hidden(e))
      .sort((x, y) => (+tagStr(y, 'published_at') || y.created_at) - (+tagStr(x, 'published_at') || x.created_at));
    if (!items.length) {
      return !r.loaded || articlesCrawling || !r.art.end
        ? h('div', { class: 'row gap6', 'data-key': 'media-empty', style: 'justify-content:center;padding:12px 0' }, h('span', { class: 'spinner sm' }))
        : h('div', { class: 'small faint', 'data-key': 'media-empty', style: 'text-align:center;padding:12px 0' }, t('mediaNoArticles'));
    }
    return h('div', { class: 'col article-list', 'data-key': 'article-list' },
      ...items.map((ev) => h('div', { 'data-key': 'art:' + ev.id, style: 'display:contents' }, articleCard(ev))));
  }

  // A clip's first frame, kept: drawn from the tile's player once it has
  // one (when the host allows the pixels to be read), stored small in the
  // Cache API, and painted as a plain picture from then on — in the grid,
  // as the pager's poster and the feed's.
  const VIDEO_THUMB_CACHE = 'coinos-video-thumbs-v1', VIDEO_THUMB_MAX = 600;
  const videoThumbs = new Map(); // url -> object URL
  const thumbKey = (url) => 'https://video-thumb.invalid/?u=' + encodeURIComponent(url);
  async function warmVideoThumbs(evs) {
    if (typeof caches === 'undefined') return;
    let found = 0;
    try {
      const store = await caches.open(VIDEO_THUMB_CACHE);
      for (const e of evs) for (const url of noteVideoUrls(e.content)) {
        if (videoThumbs.has(url)) continue;
        const res = await store.match(thumbKey(url));
        if (res) { videoThumbs.set(url, URL.createObjectURL(await res.blob())); found++; }
      }
    } catch {}
    if (found && !listView()) scheduleRepaint();
  }
  function keepVideoThumb(v, url) {
    if (videoThumbs.has(url)) return Promise.resolve(true);
    if (!v.videoWidth) return Promise.resolve(false);
    return new Promise((resolve) => {
      try {
        const w = Math.min(480, v.videoWidth), hh = Math.round(w * v.videoHeight / v.videoWidth); // sharp in a tile, fair as the pager's poster
        const cv = document.createElement('canvas');
        cv.width = w; cv.height = hh;
        cv.getContext('2d').drawImage(v, 0, 0, w, hh);
        cv.toBlob((blob) => {
          if (!blob) { resolve(false); return; }
          videoThumbs.set(url, URL.createObjectURL(blob));
          if (typeof caches !== 'undefined') caches.open(VIDEO_THUMB_CACHE).then(async (s) => {
            await s.put(thumbKey(url), new Response(blob, { headers: { 'content-type': 'image/jpeg' } }));
            // oldest out first, a batch at a time
            const keys = await s.keys();
            if (keys.length > VIDEO_THUMB_MAX) for (const k of keys.slice(0, keys.length - VIDEO_THUMB_MAX + 50)) s.delete(k);
          }).catch(() => {});
          resolve(true);
        }, 'image/jpeg', 0.75);
      } catch { resolve(false); }
    });
  }
  // Grid tiles from tile-sized copies: a square of the picture's middle,
  // 360px (a 120-180px tile at 2-3x), made once and kept in the Cache API.
  // A flick down the grid used to be a blank screen: every tile was a lazy
  // <img> of the original (or the 1100px column copy) to fetch and decode,
  // and the browser's lazy margin is a screen or two. These are local and a
  // few KB, so every tile loads at once and decodes in no time.
  const TILE_CACHE = 'coinos-tile-thumbs-v1', TILE_PX = 360, TILE_MAX = 1200;
  const tileThumbs = new Map(); // url -> object URL
  const tileKey = (url) => 'https://tile-thumb.invalid/?u=' + encodeURIComponent(url);
  const tileQueue = [], tileTried = new Set(), tileLooked = new Set();
  let tileBusy = 0, tileRepaint = null;
  const tileStore = () => caches.open(TILE_CACHE);
  async function warmTileThumbs(urls) {
    if (typeof caches === 'undefined') return;
    let found = 0;
    try {
      const store = await tileStore();
      await Promise.all(urls.map(async (url) => {
        if (tileThumbs.has(url)) return;
        const res = await store.match(tileKey(url));
        if (res) { tileThumbs.set(url, URL.createObjectURL(await res.blob())); found++; }
      }));
    } catch {}
    if (found && mediaMode === 'images') scheduleRepaint();
  }
  async function makeTileThumb(url) {
    if (typeof createImageBitmap === 'undefined' || typeof OffscreenCanvas === 'undefined' || typeof caches === 'undefined') return;
    // the column copy is already here and smaller than the original
    const kept = mediaReady.get(url)?.thumb;
    if (!kept && (noCorsHost(url) || corsRefused.has(url))) {
      // the host keeps its bytes: the server cuts the tile
      const tile = await serverPicBlob(url, 'tile');
      if (tile) await saveTileThumb(url, tile);
      return;
    }
    let blob;
    try {
      const res = kept ? await fetch(kept) : await corsFetch(url, AbortSignal.timeout(READY_MS));
      if (!res.ok) return;
      blob = await res.blob();
    } catch (e) {
      if (e && e.corsRefused) { corsRefused.add(url); const tile = await serverPicBlob(url, 'tile'); if (tile) await saveTileThumb(url, tile); }
      return;
    }
    if (/gif/i.test(blob.type)) return; // animated: the tile shows the original
    const result = await makeImageThumbnails(blob, { tileSize: TILE_PX });
    if (result?.tile) await saveTileThumb(url, result.tile);
  }
  async function saveTileThumb(url, out) {
    tileThumbs.set(url, URL.createObjectURL(out));
    const store = await tileStore();
    await store.put(tileKey(url), new Response(out, { headers: { 'content-type': out.type } }));
    const keys = await store.keys();
    if (keys.length > TILE_MAX) for (const k of keys.slice(0, keys.length - TILE_MAX + 100)) store.delete(k);
  }
  // newest first, a few at a time; the grid repaints as a batch lands
  function queueTileThumbs(urls) {
    for (const url of urls) if (!tileThumbs.has(url) && !tileTried.has(url)) { tileTried.add(url); tileQueue.push(url); }
    while (tileBusy < 4 && tileQueue.length) {
      const url = tileQueue.shift();
      tileBusy++;
      makeTileThumb(url).catch(() => {}).finally(() => {
        tileBusy--;
        if (tileThumbs.has(url) && !tileRepaint) tileRepaint = setTimeout(() => { tileRepaint = null; if (mediaMode === 'images') scheduleRepaint(); }, 400);
        queueTileThumbs([]);
      });
    }
  }
  // A clip's first frame without a player on the clip itself: the opening
  // of the file (its index and about a megabyte after) is fetched as bytes,
  // past the browser's cache, and decoded from a blob — whose pixels are
  // ours to read whatever the host's player-side CORS and whatever the
  // cache holds (see runVideoProbe). For a file that leads with its index,
  // from a host the probe could read; anything else keeps its player.
  const FRAME_BYTES_AFTER = 1_000_000, FRAME_BYTES_MAX = 4_000_000;
  const frameGrabs = new Map(), frameQueue = [], frameFailed = new Set();
  let frameGrabbing = 0;
  function grabFrame(url) {
    if (videoThumbs.has(url)) return Promise.resolve(true);
    const d = videoInfo.get(url) || {};
    if (!d.probed || !d.faststart || !d.ranges || frameFailed.has(url) || (d.moovEnd || 0) + FRAME_BYTES_AFTER > FRAME_BYTES_MAX) return Promise.resolve(false);
    if (frameGrabs.has(url)) return frameGrabs.get(url);
    const task = new Promise((resolve) => frameQueue.push({ url, resolve })).finally(() => frameGrabs.delete(url));
    frameGrabs.set(url, task);
    pumpFrames();
    return task;
  }
  // ---- the pager's first-frame posters -------------------------------------
  // The clip ahead holds its own first frame — full size, frame 0, drawn
  // from the opening of the file (the bytes headStart put in the cache,
  // read again by range) — so a flick to it glides onto the very picture
  // the player will show first, and the player's frame replaces it with no
  // visible change. (Adam, 2026-10-16: "could we actually have the next
  // image or video scroll in while the previous scrolls out? Right now it
  // goes black before the next one scrolls in.") A dozen are kept, the
  // oldest let go; the tile's kept frame (480px, at 0.1 s) is made from the
  // same decode when the tile has none yet.
  const PAGER_POSTERS = 12, POSTER_W = 1100;
  const pagerPosters = new Map(); // url -> object URL, oldest first
  const posterGrabs = new Map(); // url -> promise
  function pagerPoster(url) {
    if (pagerPosters.has(url)) { const p = pagerPosters.get(url); pagerPosters.delete(url); pagerPosters.set(url, p); return Promise.resolve(p); }
    if (posterGrabs.has(url)) return posterGrabs.get(url);
    const task = probeVideo(url).then(() => grabPoster(url)).catch(() => null).finally(() => posterGrabs.delete(url));
    posterGrabs.set(url, task);
    return task;
  }
  async function grabPoster(url) {
    const d = videoInfo.get(url) || {};
    if (!d.probed || !d.faststart || !d.ranges || frameFailed.has(url) || (d.moovEnd || 0) + FRAME_BYTES_AFTER > FRAME_BYTES_MAX) return null;
    // no more of the file than the head start fetched: the bytes come from the cache
    const last = Math.min((d.moovEnd || 200_000) + FRAME_BYTES_AFTER, Math.max(HEAD_MIN, headStartBytes(url))) - 1;
    let r;
    try { r = await fetch(url, { headers: { Range: 'bytes=0-' + last }, signal: AbortSignal.timeout(20_000) }); }
    catch { r = await fetch(url, { headers: { Range: 'bytes=0-' + last }, cache: 'no-store', signal: AbortSignal.timeout(20_000) }); } // a cached copy without CORS headers (Primal's bucket)
    if (r.status !== 206 && !(r.ok && d.size && d.size <= last + 1)) { try { r.body.cancel(); } catch {} return null; }
    const blob = new Blob([await r.arrayBuffer()], { type: (r.headers.get('content-type') || '').startsWith('video/') ? r.headers.get('content-type') : 'video/mp4' });
    const src = URL.createObjectURL(blob);
    const v = document.createElement('video');
    v.muted = true; v.playsInline = true; v.preload = 'auto';
    try {
      const shown = await new Promise((resolve) => {
        const timer = setTimeout(() => resolve(v.readyState >= 2), 6000);
        v.onloadeddata = () => { clearTimeout(timer); resolve(true); };
        v.onerror = () => { clearTimeout(timer); resolve(false); };
        v.src = src;
      });
      if (!shown || !v.videoWidth) return null;
      const w = Math.min(POSTER_W, v.videoWidth), hh = Math.round(w * v.videoHeight / v.videoWidth);
      const cv = document.createElement('canvas');
      cv.width = w; cv.height = hh;
      cv.getContext('2d').drawImage(v, 0, 0, w, hh);
      const out = await new Promise((resolve) => cv.toBlob(resolve, 'image/jpeg', 0.9));
      if (!out) return null;
      const p = URL.createObjectURL(out);
      pagerPosters.set(url, p);
      while (pagerPosters.size > PAGER_POSTERS) { const k = pagerPosters.keys().next().value; try { URL.revokeObjectURL(pagerPosters.get(k)); } catch {} pagerPosters.delete(k); }
      // the tile's frame too, from the same decode, when it has none
      if (!videoThumbs.has(url)) {
        await new Promise((resolve) => { const t = setTimeout(resolve, 3000); v.onseeked = () => { clearTimeout(t); resolve(); }; try { v.currentTime = 0.1; } catch { clearTimeout(t); resolve(); } });
        await keepVideoThumb(v, url).catch(() => {});
      }
      return p;
    } finally {
      v.onloadeddata = v.onseeked = v.onerror = null;
      try { v.removeAttribute('src'); v.load(); } catch {}
      URL.revokeObjectURL(src);
    }
  }
  function pumpFrames() {
    while (frameGrabbing < 2 && frameQueue.length) {
      const { url, resolve } = frameQueue.shift();
      frameGrabbing++;
      runFrameGrab(url).catch(() => false).then((ok) => { if (!ok) frameFailed.add(url); resolve(!!ok); })
        .finally(() => { frameGrabbing--; pumpFrames(); });
    }
  }
  async function runFrameGrab(url) {
    const d = videoInfo.get(url) || {};
    const last = (d.moovEnd || 200_000) + FRAME_BYTES_AFTER - 1;
    const r = await fetch(url, { headers: { Range: 'bytes=0-' + last }, cache: 'no-store', signal: AbortSignal.timeout(20_000) });
    if (r.status !== 206 && !(r.ok && d.size && d.size <= last + 1)) { try { r.body.cancel(); } catch {} return false; }
    const blob = new Blob([await r.arrayBuffer()], { type: (r.headers.get('content-type') || '').startsWith('video/') ? r.headers.get('content-type') : 'video/mp4' });
    const src = URL.createObjectURL(blob);
    const v = document.createElement('video');
    v.muted = true; v.playsInline = true; v.preload = 'auto';
    try {
      const shown = await new Promise((resolve) => {
        const timer = setTimeout(() => resolve(v.readyState >= 2), 6000);
        const done = (ok) => { clearTimeout(timer); resolve(ok); };
        v.onloadeddata = () => { try { v.currentTime = 0.1; } catch { done(true); } };
        v.onseeked = () => done(true);
        v.onerror = () => done(false);
        v.src = src;
      });
      if (!shown) return false;
      return await keepVideoThumb(v, url);
    } finally {
      v.onloadeddata = v.onseeked = v.onerror = null;
      try { v.removeAttribute('src'); v.load(); } catch {}
      URL.revokeObjectURL(src);
    }
  }

  // Videos is for flipping through phone-shaped clips: only those known to
  // stand taller than they're wide. A clip of unknown shape is measured
  // (the header probe, or a player when the index sits at the end of a
  // file a server serves in ranges) and joins once it's known to qualify.
  // ---- which clips fit the screen -----------------------------------------
  // The Videos view and the pager show the clips the screen's way round: tall
  // ones on a phone held upright, wide ones held sideways (or on a desktop
  // window), a square either way — unless the reader asks for all shapes
  // (remembered on this device). (Adam, 2026-10-16: "only show vertical
  // videos by default on a phone that's in vertical orientation and only
  // horizontal videos if the phone is in landscape but have some kind of
  // control to toggle the ability to see all videos".)
  const CLIPS_FIT_KEY = 'coinos-clips-fit'; // 'all', or unset: the screen's way round
  const clipsAll = () => { try { return localStorage.getItem(CLIPS_FIT_KEY) === 'all'; } catch { return false; } };
  const setClipsAll = (all) => { try { if (all) localStorage.setItem(CLIPS_FIT_KEY, 'all'); else localStorage.removeItem(CLIPS_FIT_KEY); } catch {} };
  const screenTall = () => window.innerHeight >= window.innerWidth;
  const clipShape = (url) => {
    const d = videoInfo.get(url) || {};
    const k = d.w && d.h ? d : videoDims.get(url) || mediaReady.get(url);
    const w = k && (k.w || k.width), hh = k && (k.h || k.height);
    return w && hh ? (hh > w ? 'tall' : hh < w ? 'wide' : 'square') : null;
  };
  // true/false, or null while the clip's shape isn't known
  const clipFits = (url) => { if (clipsAll()) return true; const sh = clipShape(url); return sh === null ? null : sh === 'square' || sh === (screenTall() ? 'tall' : 'wide'); };
  const clipsLabel = () => t(clipsAll() ? 'clipsAll' : screenTall() ? 'clipsTall' : 'clipsWide');
  // the toggle: in the pager's top bar only (over the grid it sat oddly
  // apart from the chips); the grid follows the same setting
  function clipsToggle(cls, after) {
    return h('button', { class: cls, type: 'button', title: t('clipsToggleTitle'), onClick: (e) => {
      e.stopPropagation();
      setClipsAll(!clipsAll());
      for (const b of document.querySelectorAll('.mp-fit')) b.textContent = clipsLabel();
      if (after) after();
      if (mediaMode === 'videos') scheduleRepaint();
    } }, clipsLabel());
  }
  function fitClip(url) {
    const f = clipFits(url);
    if (f !== null) return f;
    const d = videoInfo.get(url) || {};
    if (!probeFailedLately(d) && !(d.probed && (!d.ranges || videoUnknown.has(url)))) measureClip(url);
    return false;
  }
  const measuring = new Set();
  function measureClip(url) {
    if (measuring.has(url)) return;
    measuring.add(url);
    probeVideo(url).then((d) => {
      if (d && d.probed && !d.w && d.ranges && !videoDims.has(url)) return playerShape(url);
    }).finally(() => { if (mediaMode === 'videos') scheduleRepaint(); });
  }
  // One picture or clip shows once in the grid, however many posts carry it
  // (Adam, 2026-10-22: a conference promo filled the Videos view with
  // copies): the same file (a Blossom hash names it wherever it's hosted),
  // or the same words from the same person posted again with another upload.
  const sameFile = (url) => { const m = /\/([0-9a-f]{64})(?:\.\w+)?(?:[?#]|$)/i.exec(url); return m ? m[1].toLowerCase() : url.replace(/[?#].*$/, ''); };
  const saidAgain = (ev) => { const w = String(ev.content || '').replace(/https?:\/\/\S+/g, '').replace(/\s+/g, ' ').trim(); return w.length >= 8 ? ev.pubkey + '|' + w : null; };
  // (anyShape: the pager's list — every clip, the ones the wrong way round
  // for the screen held out of sight by pagerFit, so "All shapes" there has
  // them to show)
  function mediaItems(c, kind, anyShape = false) {
    const out = [], seen = new Set(), said = new Map();
    const r = mediaIndex(c.id);
    indexMedia(r, c.notes);
    const evs = [...r[kind].values()].sort((a, b) => b.created_at - a.created_at);
    const curated = !!(feedDef(c.id) || {}).curated;
    for (const ev of evs) {
      if (hidden(ev)) continue;
      // a grid shows the picture itself — no warning to fold it behind
      if (curated ? notForPublic(ev) : modOn('sensitive') && sensitiveWhy(ev) !== null && !isMe(ev.pubkey)) continue;
      const again = saidAgain(ev);
      if (again && said.has(again) && said.get(again) !== ev.id) continue;
      if (kind === 'videos') learnVideoMeta(ev);
      // (a clip whose host says it's deleted has nothing to show: a blank tile)
      const urls = kind === 'videos' ? clipUrlsOf(ev).filter((u) => !clipGone(u) && (anyShape || fitClip(u)))
        : noteMediaUrls(ev.content).filter((u) => !u.startsWith('https://i.ytimg.com/'));
      // (the words are taken by a post that shows: one whose clip doesn't fit
      // the screen leaves them to the next)
      if (again && urls.length) said.set(again, ev.id);
      for (const url of urls) {
        const f = sameFile(url);
        if (seen.has(f)) continue;
        seen.add(f);
        out.push({ ev, url });
      }
    }
    return out;
  }
  // The feed's pictures (or clips) in reading order — every one of a post
  // before the next post's — for the pager opened from one in the feed: the
  // feed's own list (its order, its moderation), not the media index. Clips
  // of every shape, not only the tall ones the Videos view flips through.
  // The posts a post quotes (drawn inside it), as far as they've been fetched.
  function quotedIn(ev) {
    const out = [];
    for (const m of String(ev.content || '').matchAll(/nostr:((?:note|nevent)1[a-z0-9]+)/gi)) {
      const ref = parseNostrRef(m[1].toLowerCase());
      const q = ref && ref.type === 'event' && quoted.get(ref.id);
      if (q && q.ev && FEED_KINDS.includes(q.ev.kind) && !hidden(q.ev) && !out.includes(q.ev)) out.push(q.ev);
    }
    return out;
  }
  function feedMediaItems(c, kind) {
    const out = [];
    const list = c.winList ? c.winList() : c.notes;
    const sensitive = (e) => modOn('sensitive') && sensitiveWhy(e) !== null && !isMe(e.pubkey);
    const add = (e, row) => {
      if (kind === 'videos') learnVideoMeta(e);
      const urls = kind === 'videos' ? clipUrlsOf(e)
        : noteMediaUrls(e.content).filter((u) => !u.startsWith('https://i.ytimg.com/'));
      for (const url of urls) out.push({ ev: e, url, row });
    };
    for (const row of list) {
      const ev = row.kind === REPOST ? repostInner(row) || row : row;
      if (sensitive(ev)) continue;
      add(ev, row);
      // then the pictures (clips) of the posts it quotes, which are drawn
      // inside it: tapped there, one opened alone, with nothing to swipe to
      for (const q of quotedIn(ev)) if (!sensitive(q)) add(q, row);
    }
    return out;
  }
  // The feed row a tapped picture or clip sits in, when the feed itself is
  // the page (not a thread, a profile or a chat).
  function feedRowOf(el) {
    const inFeed = ui.chatOpen && ui.msgView === 'feed' && !ui.profilePk && !ui.noteThread && feed && !feed.stopped && feed.winList;
    return inFeed && el && el.closest ? el.closest('.notes-feed > [data-key]')?.getAttribute('data-key') || null : null;
  }
  // the page the row is on: the feed, a person's timeline (their profile
  // page) or a thread — the pager runs over that page's pictures (or clips)
  const onProfilePage = () => !!ui.profilePk && (!ui.noteThread || ui.profOverThread);
  const onThreadPage = () => !!ui.noteThread && !onProfilePage();
  // the thread on screen, by its root — the key a thread pager is tied to
  const threadPageId = () => (onThreadPage() && (threadCache.get(ui.noteThread.rootId) || threadCache.get(rootIdOf(ui.noteThread.seed)))?.rootId) || null;
  // a thread as a list the pager can read (feedMediaItems), in the page's order
  const threadNotes = (c) => ({ notes: threadOrder(c), shown: c.replies.length + 1 });
  function pageRowOf(el) {
    if (!el || !el.closest) return null;
    if (onThreadPage()) {
      const rowId = el.closest('.thread-page [data-zap-post]')?.getAttribute('data-zap-post') || null;
      const tid = threadPageId();
      return rowId && tid ? { c: threadNotes(threadCache.get(tid)), rowId, profile: null, thread: tid } : null;
    }
    const rowId = el.closest('.notes-feed > [data-key]')?.getAttribute('data-key') || null;
    if (!rowId) return null;
    if (onProfilePage()) { const c = notesCache.get(ui.profilePk); return c && c.winList ? { c, rowId, profile: ui.profilePk } : null; }
    return feedRowOf(el) ? { c: feed, rowId, profile: null } : null;
  }
  // Where a pager opened from a page gets its pictures: the feed on screen,
  // or a person's timeline — its posts' pictures in its order, more fetched
  // as the reader nears the end. The media grid's pager has no source here.
  function pagerSource(p = pager) {
    if (!p) return null;
    if (p.thread) {
      // a thread's pictures: the root's and its replies', as the page lists
      // them — all here already, nothing more to fetch
      const c = threadCache.get(p.thread);
      return c ? { c: threadNotes(c), thread: p.thread, items: (kind) => feedMediaItems(threadNotes(c), kind), more: async () => {}, done: () => true,
        live: () => threadPageId() === p.thread } : null;
    }
    if (p.profile) {
      const c = notesCache.get(p.profile);
      return c ? { c, profile: p.profile, items: (kind) => feedMediaItems(c, kind), more: () => loadOlderNotes(p.profile), done: () => !!c.end && !c.loadingMore,
        live: () => onProfilePage() && ui.profilePk === p.profile } : null; // (the entry is replaced by a refetch: the page, not the object, says it is still there)
    }
    if (p.fromFeed) { const c = feedNow(); return { c, items: (kind) => feedMediaItems(c, kind), more: () => loadOlderFeed(), done: () => !!c.end && c.shown >= c.notes.length && !c.loadingMore, live: () => c === feed && !onProfilePage() }; }
    return null;
  }
  // A picture tapped in the feed opens in the media pager, on that picture,
  // with the feed's other pictures a swipe (or an arrow) away, the way the
  // media grid's are; on a profile page over that person's pictures, and on
  // a thread over the thread's (Adam, 2026-10-16: the same viewer wherever
  // a picture is opened from — a thread's opened alone and a tap on it
  // closed it, with no caption or controls). Elsewhere — a chat, a face —
  // the picture opens alone.
  function openPicture(url, e) {
    try {
      const at = pageRowOf(e && e.target);
      if (at) {
        const it = feedMediaItems(at.c, 'images').find((x) => (x.row.id === at.rowId || x.ev.id === at.rowId) && x.url === url);
        if (it) { openMediaPager('images', mediaKey(it), { fromFeed: !at.profile && !at.thread, profile: at.profile, thread: at.thread || null }); return; }
      }
    } catch {}
    ctx.openImage && ctx.openImage(url);
  }
  // A clip tapped in the feed opens in the pager the same way, over the
  // feed's clips, picking up where it was. The pager takes the whole screen
  // (what the player's own full screen did). The screen isn't turned for a
  // wide clip — Adam would rather it play with bars and turn the phone
  // himself — so it follows the phone throughout.
  // The pager's item for a clip on the page, if the pager has it: a clip in
  // the post a reply answers (its "Replying to" card) isn't one of the
  // feed's own, and gets the browser's full screen instead.
  function clipItem(v, url) {
    try {
      const on = pageRowOf(v);
      if (!on) return null;
      const it = feedMediaItems(on.c, 'videos').find((x) => (x.row.id === on.rowId || x.ev.id === on.rowId) && x.url === url);
      return it ? { on, it } : null;
    } catch { return null; }
  }
  function openClip(v, url) {
    try {
      const found = clipItem(v, url);
      if (!found) return false;
      const { on, it } = found;
      tappedClips.add(url); // asked for by hand: no tap-to-play cover
      const at = v.currentTime || 0;
      v.pause();
      openMediaPager('videos', mediaKey(it), { fromFeed: !on.profile && !on.thread, profile: on.profile, thread: on.thread || null, at });
      pagerFullscreen();
      return true;
    } catch { return false; }
  }
  let pagerFs = false; // the pager put the page full screen (and so takes it back out)
  // The installed app (the Play/Zapstore build — immersive since 1.13 — or a
  // home-screen install) has no address bar: the pager already fills its
  // window. Going full screen there only hid the system bars, and every time
  // it did Chrome put up its "To exit full screen, drag from the top…"
  // notice, which a page can't turn off. So there it doesn't.
  const installedApp = () => {
    try { return matchMedia('(display-mode: standalone), (display-mode: fullscreen), (display-mode: minimal-ui)').matches || document.referrer.startsWith('android-app://'); } catch { return false; }
  };
  function pagerFullscreen() {
    if (installedApp()) return;
    const d = document.documentElement;
    const go = d.requestFullscreen || d.webkitRequestFullscreen;
    if (!go || fsElement()) return;
    Promise.resolve(go.call(d, { navigationUI: 'hide' })).then(() => {
      if (!ui.mediaPager) { exitFs(); return; }
      pagerFs = true;
    }).catch(() => {});
  }
  const exitFs = () => { try { (document.exitFullscreen || document.webkitExitFullscreen || (() => {})).call(document)?.catch?.(() => {}); } catch {} };
  function pagerUnFullscreen() {
    if (!pagerFs) return;
    pagerFs = false;
    if (fsElement() === document.documentElement) exitFs();
  }
  // The words of the post, without the links to the media it carries.
  function mediaCaption(ev, raw = false) {
    let s = isVideoEvent(ev) ? videoEventText(ev) : String(ev.content || '');
    s = s.replace(new RegExp(MD_LINK, 'gi'), (m) => (MD_PARTS.exec(m)?.[1] ? '' : m));
    for (const u of [...noteMediaUrls(s), ...noteVideoUrls(s)]) s = s.split(u).join('');
    return raw ? s.replace(/\s+/g, ' ').trim() : plainExcerpt(s);
  }
  // The pager's caption: the post's words with their names, tags and links
  // live (a plain excerpt left "@NostrValley" dead — Adam, 2026-10-16). A
  // tap on a name, a tag or a note reference leaves the pager, and the full
  // screen with it, before going where it goes; a link to the web opens in
  // its own tab and the pager stays. A tap anywhere else on the caption
  // leaves the pager and opens the post ("clicking anywhere on the caption
  // that's not a link should take me out of fullscreen and take me to the
  // post"), where the whole of a long caption reads.
  function captionNode(ev, text) {
    const el = h('div', { class: 'mp-caption' }, ...noteBody(text, 2, noteEmojiTags(ev)));
    el.addEventListener('click', (e) => {
      const a = e.target && e.target.closest ? e.target.closest('a') : null;
      if (a && /^https?:/i.test(a.getAttribute('href') || '')) { e.stopPropagation(); return; }
      leavePager();
      if (a) return; // the link's own handler opens the name, the tag, the note
      e.stopPropagation(); e.preventDefault();
      openNoteThread(ev);
    }, true);
    return el;
  }
  function setMediaMode(m) {
    mediaMode = m;
    try { localStorage.setItem(MEDIA_MODE_KEY, m); } catch {}
    // Notes ↔ Conversations: another feed state (the view's), entered like
    // a switch of feed — its watch, its fresh counter — with no change of chip
    if (listView() && feedDef(curFeedId)) selectFeed(curFeedId);
    render();
    try { window.scrollTo({ top: 0 }); } catch {}
  }
  function mediaModes() {
    const b = (m, label) => h('button', {
      class: 'feed-chip media-mode' + (mediaMode === m ? ' on' : ''), type: 'button', 'data-mode': m,
      onClick: () => setMediaMode(m),
    }, label);
    // Live wears a red dot while someone in the feed is streaming
    const def = feedDef(curFeedId);
    const onAir = def && liveForFeed(def).length > 0;
    return h('div', { class: 'row media-modes', 'data-key': 'media-modes' },
      b('all', t('mediaAll')), b('replies', t('mediaConversations')), b('images', t('mediaImages')), b('videos', t('mediaVideos')),
      b('live', onAir ? [h('span', { class: 'live-dot', 'aria-hidden': 'true' }), t('mediaLive')] : t('mediaLive')),
      b('articles', t('mediaArticles')));
  }
  function mediaGrid(c) {
    const items = mediaItems(c, mediaMode);
    if (!items.length) {
      const r = mediaIndex(c.id);
      return !r.loaded || mediaCrawling || (!r.end && feedHasQuery(feedDef(c.id)) && !feedDef(c.id)?.curated) || c.booting || c.status === 'loading' || c.loadingMore
        || (mediaMode === 'videos' && (videoProbes.size || videoProbeQueue.length))
        ? h('div', { class: 'row gap6', 'data-key': 'media-empty', style: 'justify-content:center;padding:12px 0' }, h('span', { class: 'spinner sm' }))
        : h('div', { class: 'small faint', 'data-key': 'media-empty', style: 'text-align:center;padding:12px 0' },
            t(mediaMode === 'videos' ? 'mediaNoVideos' : 'mediaNoImages'));
    }
    if (mediaMode === 'images') {
      const missing = items.filter((it) => !tileThumbs.has(it.url) && !tileTried.has(it.url) && !tileLooked.has(it.url)).map((it) => it.url);
      for (const u of missing) tileLooked.add(u);
      if (missing.length) warmTileThumbs(missing).then(() => queueTileThumbs(missing.filter((u) => !tileThumbs.has(u))));
    }
    if (mediaMode === 'videos') for (const it of items.slice(0, 24)) preconnect(playSrc(it.url));
    // The tiles take the clips' shape (Adam, 2026-10-22): wide clips only (a
    // wide screen) go one to a row, their posters whole, not slivers cut to
    // portrait tiles; every shape ("All shapes") goes three across in
    // squares; tall ones only (a phone held upright) keep the tall tiles.
    const shape = mediaMode !== 'videos' ? '' : clipsAll() ? ' square' : screenTall() ? '' : ' wide';
    return h('div', { class: 'media-grid' + shape, 'data-key': 'media-grid:' + mediaMode },
      ...items.map((it) => {
        const k = mediaKey(it);
        // a video tile shows a still at once: kept, given, or the server's
        // (vmedia, cached at the CDN — about a second the first time anyone
        // asks, instant after). The browser's own frame grab — a probe, then
        // a megabyte of the clip, decoded — is left for clips the server
        // couldn't picture.
        const poster = mediaMode === 'videos' ? videoThumbs.get(it.url) || posterOf(it.ev, it.url) || (videoInfo.get(it.url) || {}).image
          || (serverThumbFailed.has(it.url) ? null : serverThumb(it.url)) : null;
        const fromServer = mediaMode === 'videos' && poster && poster === serverThumb(it.url);
        return h('button', {
          class: 'media-tile' + (mediaMode === 'videos' ? ' video' : ''), type: 'button', 'data-key': 'tile:' + k,
          'aria-label': displayName(it.ev.pubkey), onClick: () => openMediaPager(mediaMode, k),
          onPointerDown: mediaMode === 'videos' ? () => earlyPlayer(it.url) : undefined,
        },
          mediaMode === 'images' || poster
            ? h('img', { src: poster || tileThumbs.get(it.url) || mediaSrc(it.url), alt: '', draggable: 'false',
                loading: poster || tileThumbs.has(it.url) ? 'eager' : 'lazy', decoding: 'async',
                onError: (e) => {
                  if (fromServer) { serverThumbFailed.add(it.url); render(); return; } // the frame grab's turn
                  const b = e.target.closest('.media-tile'); if (b) b.classList.add('broken');
                } })
            // no still to show: the clip's first frame, fetched once the tile is near
            : h('video', { 'data-src': it.url + '#t=0.1', muted: true, playsinline: true, preload: 'metadata' }),
          mediaMode === 'videos' && poster && videoInfo.get(it.url)?.size && videoHeavy(it.url) ? h('span', { class: 'media-tile-badge' }, heavyLabel(it.url)) : null,
          mediaMode === 'videos' ? h('span', { class: 'media-tile-play', 'aria-hidden': 'true' }, '▶') : null);
      }));
  }
  // Video tiles get their src once they come near the screen; the tile is
  // then left alone by the morph, which would otherwise strip the src.
  let tileObs = null;
  function watchMediaTiles() {
    if (typeof IntersectionObserver === 'undefined') return;
    tileObs = tileObs || new IntersectionObserver((entries) => {
      for (const e of entries) {
        if (!e.isIntersecting) continue;
        const v = e.target;
        tileObs.unobserve(v);
        const tile = v.closest('.media-tile');
        if (tile) tile._skipMorph = true;
        // A first frame costs the start of the file when the index leads or
        // the server serves ranges — whatever the clip's size. Only an
        // index-last file without ranges would have to come down whole for
        // it; that one shows what it costs instead. A clip over budget wears
        // its cost as a badge either way.
        const url = v.getAttribute('data-src').replace(/#t=[\d.]+$/, '');
        probeVideo(url, true).then(async (d) => {
          if (!v.isConnected) return;
          const heavy = videoHeavy(url);
          // the frame as a picture, kept for good, when the bytes can be had
          if (await grabFrame(url)) {
            if (!v.isConnected) return;
            const img = document.createElement('img');
            img.alt = ''; img.draggable = false; img.src = videoThumbs.get(url);
            v.replaceWith(img);
            if (heavy && d.size) img.after(h('span', { class: 'media-tile-badge' }, heavyLabel(url)));
            return;
          }
          if (!v.isConnected) return;
          // unmeasured (the probe failed): try for a frame anyway, but give
          // up and let go after eight seconds, so an index-last file can't
          // stream whole into a tile
          const still = d && (d.probed ? d.faststart || d.ranges : true);
          if (still && !(d && d.probed)) {
            const cap = setTimeout(() => {
              if (v.readyState >= 2 || !v.isConnected) return;
              try { v.removeAttribute('src'); v.load(); } catch {}
              v.replaceWith(h('span', { class: 'media-tile-cost' }, ''));
            }, 8000);
            v.addEventListener('loadeddata', () => clearTimeout(cap), { once: true });
          }
          if (still) {
            // (a plain load: shown, not kept — a player's pixels can only be
            // read from a CORS load, and those fail on a cached plain copy)
            v.muted = true;
            v.src = v.getAttribute('data-src');
            if (heavy && d.size) v.after(h('span', { class: 'media-tile-badge' }, heavyLabel(url)));
            return;
          }
          v.replaceWith(h('span', { class: 'media-tile-cost' }, d && d.size ? heavyLabel(url) : ''));
        });
      }
    }, { rootMargin: '400px 0px' });
    for (const v of document.querySelectorAll('.media-tile video[data-src]:not([data-obs])')) {
      v.setAttribute('data-obs', '1');
      tileObs.observe(v);
    }
  }

  // Opening a clip from the grid: on Adam's phone a player made at the tap
  // took ~0.65 s to move (making it ~0.25, its first frame ~0.15, starting
  // its sound ~0.3 — the clip's opening already in the cache saved nothing),
  // and 1.8 s when the host's connection had to be made too. So the grid's
  // clip hosts are connected to ahead (a preconnect: cheap), and the
  // player starts loading when the finger comes down on the tile — the
  // pager adopts that same element (pagerSlide), so the load overlaps the
  // tap and the pager's opening. One the tap doesn't follow (a scroll) is
  // let go.
  const preconnected = new Set();
  function preconnect(url) {
    let origin; try { origin = new URL(url, location.href).origin; } catch { return; }
    if (origin === location.origin || preconnected.has(origin) || preconnected.size > 24 || typeof document === 'undefined') return;
    preconnected.add(origin);
    const l = document.createElement('link');
    l.rel = 'preconnect'; l.href = origin;
    document.head.append(l);
  }
  let early = null; // { url, v, timer }
  function earlyPlayer(url) {
    if (frugalData() || (early && early.url === url)) return;
    dropEarly();
    const v = document.createElement('video');
    v.playsInline = true; v.loop = true; v.preload = 'auto'; v.muted = true;
    v.setAttribute('src', playSrc(url));
    v.dataset.early = '1'; // (the pager's adoption of it, for tests)
    // on the page (out of sight) while it waits: a detached player isn't loaded everywhere
    v.style.cssText = 'position:fixed;left:-9999px;top:0;width:2px;height:2px;opacity:0;pointer-events:none';
    document.body.append(v);
    early = { url, v, timer: setTimeout(dropEarly, 2500) };
  }
  function dropEarly() {
    if (!early) return;
    clearTimeout(early.timer);
    try { early.v.removeAttribute('src'); early.v.load(); early.v.remove(); } catch {}
    early = null;
  }
  function takeEarly(url) {
    if (!early || early.url !== url) return null;
    const { v } = early;
    clearTimeout(early.timer);
    early = null;
    return v;
  }

  // `fromFeed`: opened from a picture or clip in the feed (its pictures or
  // clips, in the feed's order), rather than from the media grid; `at`: where
  // the clip it opened on was, so it carries on from there
  function openMediaPager(kind, start, { fromFeed = false, profile = null, thread = null, at = 0 } = {}) {
    // the page's own players stop: the pager's is the one to hear
    for (const v of document.querySelectorAll('video')) { try { v.pause(); } catch {} }
    for (const f of document.querySelectorAll('.yt-embed[data-playing] iframe')) {
      try { f.contentWindow.postMessage(JSON.stringify({ event: 'command', func: 'pauseVideo', args: [] }), '*'); f.closest('.yt-embed')._pausedByUs = true; } catch {}
    }
    ui.mediaPager = { kind, start, feed: curFeedId, fromFeed, profile, thread, at };
    render();
  }
  const closeMediaPager = () => ctx.closeLayer('mediaPager');
  // still on the picture that opened the pager (nothing swiped to yet)
  const pagerOnStart = () => !pager || !pager.cur || pager.cur.getAttribute('data-k') === pager.start;
  // Dismissing a pager opened from the feed after moving through it lands
  // the feed on the post of the picture last looked at; otherwise (the
  // media grid's pager, or nothing moved) it simply closes.
  function dismissPager() {
    if (pager && pagerSource() && !pagerOnStart() && pager.cur) closePagerTo(pager.cur._rowId);
    else closeMediaPager();
  }
  function closePagerTo(rowId) {
    const src = pagerSource();
    closeMediaPager();
    // the pop that closes it lands on a later turn: the glide waits for the feed
    let tries = 0;
    const go = () => {
      if (src.thread) {
        // a thread's post is drawn already (no window): just bring it on screen if it isn't
        if (ui.mediaPager) { if (++tries < 90) requestAnimationFrame(go); return; }
        if (!src.live()) return;
        const el = document.querySelector('.thread-page [data-zap-post="' + CSS.escape(rowId) + '"]');
        const r = el && el.getBoundingClientRect();
        if (r && (r.top < 0 || r.bottom > window.innerHeight)) window.scrollTo(0, Math.max(0, window.scrollY + r.top - 8));
        return;
      }
      if (ui.mediaPager || !document.querySelector('.notes-feed')) { if (++tries < 90) requestAnimationFrame(go); return; }
      landOnPost(src, rowId);
    };
    requestAnimationFrame(go);
  }
  // Put the feed on a post the reader hasn't been near — one the pager went
  // on to, maybe paged in while it was open and never drawn. Its place is
  // only a guess until it is drawn, and the rows around it settle as they
  // draw (a long post, a picture finding its size), so: jump to the guess,
  // draw, and set the row under the top again each frame — until it has sat
  // still a moment, a couple of seconds have gone, or the reader touches the
  // page. A jump, not a glide: the pager was covering the feed.
  function landOnPost(src, rowId) {
    const MARGIN = 8, t0 = Date.now();
    const find = () => document.querySelector('.notes-feed > [data-key="' + CSS.escape(rowId) + '"]');
    let still = 0, misses = 0, lastY = null;
    const step = () => {
      if (!src.live() || ui.mediaPager || !document.querySelector('.notes-feed') || lastInputAt > t0 || Date.now() - t0 > 2500) return;
      // the list as it is now (a profile's entry is replaced by a refetch)
      const c = src.profile ? notesCache.get(src.profile) || src.c : src.c;
      // the page sent somewhere else meanwhile (not by a finger: a glide, a link)
      if (lastY !== null && Math.abs(window.scrollY - lastY) > window.innerHeight / 2) return;
      const el = find();
      if (!el) {
        const list = c.winList ? c.winList() : c.notes;
        const i = list.findIndex((e) => e.id === rowId);
        if (i < 0 || ++misses > 20) return;
        let sum = 0, n = 0;
        for (const v of (c.heights || new Map()).values()) { sum += v; n++; }
        const avg = n ? sum / n : 200;
        let y = 0;
        for (let j = 0; j < i; j++) y += ((c.heights && c.heights.get(list[j].id)) || avg) + ROW_GAP;
        window.scrollTo(0, Math.max(0, (c.listTop || 0) + y - MARGIN));
        render();
        requestAnimationFrame(step);
        return;
      }
      const off = el.getBoundingClientRect().top - MARGIN;
      if (Math.abs(off) > 2) { window.scrollTo(0, Math.max(0, window.scrollY + off)); still = 0; }
      else if (++still >= 20 && Date.now() - t0 > 600) return;
      lastY = window.scrollY;
      requestAnimationFrame(step);
    };
    step();
  }
  // Leaving the pager for another page (a profile, sign-in, the zap amount):
  // only the feed's own render syncs the pager, and those pages don't paint
  // the feed — so the overlay goes now, not on the next feed render.
  const leavePager = () => { ui.mediaPager = null; if (pager) dropPager(); };
  let pager = null; // the live pager: { el, scroller, kind, keys, cur, loud, io, near, tick }
  let pagerLoud = true; // sound on, unless the browser said no without a tap
  function syncMediaPager() {
    const m = ui.mediaPager;
    const want = m && (m.thread ? threadPageId() === m.thread
      : m.profile ? onProfilePage() && ui.profilePk === m.profile && notesCache.has(m.profile)
      : ui.chatOpen && ui.msgView === 'feed' && !ui.profilePk && !ui.noteThread) ? m : null;
    if (!want) { if (pager) dropPager(); return; }
    if (pager && (pager.kind !== want.kind || pager.fromFeed !== !!want.fromFeed || pager.profile !== (want.profile || null) || pager.thread !== (want.thread || null))) dropPager();
    if (!pager) buildPager(want);
    else growPager();
  }
  function dropPager() {
    const p = pager;
    pager = null;
    try { p.io.disconnect(); p.near.disconnect(); } catch {}
    clearInterval(p.tick);
    cancelAnimationFrame(p.raf);
    window.removeEventListener('resize', p.onResize);
    pagerUnFullscreen();
    for (const v of p.el.querySelectorAll('video')) { try { v.pause(); v.removeAttribute('src'); v.load(); } catch {} }
    p.el.remove();
    document.documentElement.classList.remove('no-scroll');
  }
  function pagerCounts(slide) {
    const ev = slide && slide._ev;
    if (!ev) return;
    const s = noteCountSnapshot(ev.id);
    const zp = pendingOf(ev.id);
    const sats = s.sats + (zp ? zp.sats : 0);
    const like = slide.querySelector('.mp-like'), zap = slide.querySelector('.mp-zap');
    const mine = myReactOn(ev.id);
    like.classList.toggle('on', !!mine);
    if (mine) like.querySelector('.i').replaceChildren(postReactNode(mine)); // the emoji chosen, a picture for a :code:
    else like.querySelector('.i').innerHTML = I_HEART(false);
    like.querySelector('.n').textContent = s.likes ? String(s.likes) : '';
    zap.classList.toggle('on', sats > 0);
    const replies = replyCount(ev.id);
    slide.querySelector('.mp-post .n').textContent = replies ? String(replies) : '';
    zap.querySelector('.n').textContent = sats ? fmtSats(sats) : '';
  }
  function pagerSlide(it) {
    const { ev, url } = it;
    const video = pager.kind === 'videos';
    // A picture flies in as the feed's copy of it (1100px wide, decoded
    // already if the feed painted it; else the server's, cached at the CDN)
    // and is sharpened to the original once it comes to rest (pagerSharpen).
    // Originals as they passed — camera files, several megapixels each —
    // decoded on the main thread and were uploaded as textures mid-flight,
    // and the flight stuttered (Adam, 2026-10-16: "a bit of choppiness as
    // they scroll"). A copy that fails falls back to the original.
    const quick = !video && !/\.gif(\?|$)/i.test(url) ? (mediaReady.get(url) || {}).thumb || serverPic(url, 'col') || url : url;
    // A clip that will play by itself has no poster: every poster there is
    // (the kept frame, a post's imeta picture, the server's) is 480px wide
    // and taken at some moment of the clip, so it showed for a beat, soft
    // and not quite the first frame, and the clip's own first frame
    // replaced it — a flash on every flick (Adam, 2026-10-16: "if we're
    // auto playing let's not show the thumbnail let's just start on the
    // first frame of the video"). The slide is the pager's black until the
    // player, whose opening is in the cache by then (headStart), has its
    // first frame. (Giving the next clip's player its file ahead of time
    // was tried: it pulled the whole file down.) On a connection to be
    // careful with the poster stays: the clip may never load (a heavy one
    // waits for a tap), and the still is what there is.
    // (the clip a grid tile was pressed on: the player already loading since the finger came down)
    const adopted = video && !frugalData() ? takeEarly(url) : null;
    if (adopted) { adopted.removeAttribute('style'); adopted.className = 'mp-media'; adopted.setAttribute('data-src', url); adopted.setAttribute('playsinline', ''); adopted.setAttribute('loop', ''); }
    const media = adopted || (video
      ? h('video', { class: 'mp-media', 'data-src': url, loop: true, playsinline: true, preload: 'none',
          poster: frugalData() ? videoThumbs.get(url) || posterOf(ev, url) || (videoInfo.get(url) || {}).image || serverThumb(url) : undefined })
      : h('img', { class: 'mp-media', 'data-src': quick, 'data-full': url, alt: '', draggable: 'false', decoding: 'async',
          onError: (e) => {
            const m = e.currentTarget;
            if ((m.getAttribute('src') || '') !== url) { m.setAttribute('data-src', url); m.setAttribute('src', url); return; }
            // the original is gone too (its host down, the file deleted): say
            // so, in place of the browser's broken-picture glyph
            let host = ''; try { host = new URL(url).hostname; } catch {}
            m.closest('.mp-slide').classList.add('mp-gone');
            m.insertAdjacentElement('afterend', h('div', { class: 'mp-missing' }, h('div', { class: 'mp-missing-ico' }, '🖼'), h('div', {}, t('mediaPicGone')), host ? h('div', { class: 'small muted' }, host) : null));
          } }));
    if (video) capUpscale(media);
    const caption = mediaCaption(ev, true);
    const stop = (fn) => (e) => { e.stopPropagation(); fn(e); };
    const slide = h('div', { class: 'mp-slide', 'data-k': mediaKey(it) },
      media,
      h('div', { class: 'mp-meta' },
        h('div', { class: 'mp-left' },
          h('button', { class: 'mp-author', type: 'button', onClick: stop(() => { leavePager(); openProfile(ev.pubkey); }) },
            avatar(ev.pubkey, 'chat-avatar mini', false), h('span', {}, displayName(ev.pubkey))),
          caption ? captionNode(ev, caption) : null),
        h('div', { class: 'mp-counts' },
          // as in the feed: a tap picks how you feel about it (the emoji
          // sheet, over the pager), a tap again takes it back
          h('button', { class: 'mp-like', type: 'button', 'aria-label': t('postLike'), onClick: stop(() => {
            if (signinAsk()) { leavePager(); render(); return; }
            if (myReactOn(ev.id)) { unreact(ev).catch(() => {}).finally(() => pagerCounts(slide)); setTimeout(() => pagerCounts(slide), 50); return; }
            ui.reactPick = withMoment(ev); render();
          }) }, h('span', { class: 'i', html: I_HEART(false) }), h('span', { class: 'n' })),
          // the post itself, as the feed would open it: the whole text, the replies
          h('button', { class: 'mp-post', type: 'button', 'aria-label': t('mediaOpenPost'), title: t('mediaOpenPost'), onClick: stop(() => {
            // a reply written there is about where the clip was
            const moment = momentOf(ev);
            leavePager(); openNoteThread(ev);
            if (moment && ui.noteThread) ui.noteThread.momentFor = { id: ev.id, moment };
          }) }, h('span', { class: 'i', html: I_REPLY }), h('span', { class: 'n' })),
          h('button', { class: 'mp-zap', type: 'button', 'aria-label': t('zapTitle'), onClick: stop((e) => {
            if (signinAsk()) { leavePager(); render(); return; }
            // the first zap ever asks for an amount on a page of its own
            const at = e.currentTarget.getBoundingClientRect();
            const moment = momentOf(ev);
            if (!(ctx.zapDefaultSat && ctx.zapDefaultSat())) leavePager();
            zapNote(ev.pubkey, ev, at, moment);
            recheckZap(ev.id);
            setTimeout(() => pagerCounts(slide), 50);
          }) }, h('span', { class: 'i', html: I_ZAP }), h('span', { class: 'n' })))));
    slide._ev = ev;
    slide._rowId = it.row ? it.row.id : ev.id; // the feed row to land on (a repost's wrapper, not its inner post)
    // pinch to zoom a picture (drag pans it zoomed; the wheel is the pager's)
    if (!video && ctx.attachZoom) ctx.attachZoom(slide, media, { wheel: 'ctrl' }); // ctrl+wheel (a pinch) zooms; the plain wheel is the pager's
    if (video) {
      guardPicture(media, url);
      media.muted = !pagerLoud;
      media.addEventListener('click', () => {}); // a tap is the pager's (overlay), not the player's
      media._momentUrl = url;
      slide.append(seekBar(media, () => momentsOn(ev.id, url)));
    }
    return slide;
  }
  // A clip's own seek bar: a thin line along the bottom that fills as it
  // plays, thicker with the details up or under a finger. Dragging it scrubs
  // (the clip holds still meanwhile, and the time shows); the drag is the
  // bar's alone, never the pager's swipe or its tap.
  const clock = (t) => { t = Math.max(0, Math.floor(t || 0)); const m = Math.floor(t / 60), x = t % 60; return m + ':' + String(x).padStart(2, '0'); };
  // A big screen blew a small clip up into blocks (Adam, 2026-10-22: "videos
  // that are low res … so pixellated on my large 1920 monitor"). In a big
  // window (a phone on its side is too short) a clip is drawn at most 1.5×
  // its own pixels,
  // smaller ones sitting in the middle on the pager's black. A phone fills
  // its screen as before.
  const MAX_UPSCALE = 1.5;
  function capUpscale(v) {
    const fit = () => {
      const big = v.videoWidth && matchMedia('(min-width: 1000px) and (min-height: 600px)').matches;
      const k = MAX_UPSCALE / (window.devicePixelRatio || 1);
      v.style.maxWidth = big ? Math.round(v.videoWidth * k) + 'px' : '';
      v.style.maxHeight = big ? Math.round(v.videoHeight * k) + 'px' : '';
    };
    v.addEventListener('loadedmetadata', fit);
    if (v.readyState >= 1) fit();
  }
  // up for a few seconds, and on while a finger is on it
  // (a mouse brings it up by moving, so it goes sooner once the mouse is
  // still, and stays while the pointer rests on the bar itself)
  function revealSeek(bar, ms = 3500) {
    bar.classList.add('reveal');
    clearTimeout(bar._hide);
    bar._hide = setTimeout(() => { if (bar._drag || bar._hover) revealSeek(bar, ms); else bar.classList.remove('reveal'); }, ms);
  }
  // What was said, reacted or zapped at a moment of the clip sits over the
  // bar at that moment (a tap goes there and says who and what), and floats
  // up off it as the clip plays past.
  function seekBar(v, moments = () => []) {
    const fill = h('div', { class: 'mp-seek-fill' });
    const time = h('span', { class: 'mp-seek-time' });
    const marks = h('div', { class: 'mp-marks' });
    const bar = h('div', { class: 'mp-seek' }, marks, h('div', { class: 'mp-seek-track' }, fill), time);
    bar.addEventListener('pointerenter', (e) => { if (e.pointerType === 'mouse') bar._hover = true; });
    bar.addEventListener('pointerleave', () => { bar._hover = false; });
    let items = [], sig = '', checked = 0, last = 0;
    const say = (x) => {
      time.textContent = clock(x.moment.seconds) + '  ' + x.text;
      bar.classList.add('say');
      clearTimeout(bar._say);
      bar._say = setTimeout(() => bar.classList.remove('say'), 3000);
      revealSeek(bar);
    };
    const paintMarks = () => {
      checked = performance.now();
      items = moments();
      const next = items.map((x) => x.id).join(',') + '@' + v.duration;
      if (next === sig) return;
      sig = next;
      marks.replaceChildren(...items.map((x) => h('button', {
        type: 'button', class: 'mp-mark', title: clock(x.moment.seconds) + ' ' + x.text,
        style: 'left:' + markAt(x.moment.seconds, v.duration) + '%',
        onPointerdown: (e) => e.stopPropagation(),
        onClick: (e) => { e.stopPropagation(); try { v.currentTime = x.moment.seconds; } catch {} say(x); },
      }, momentGlyph(x))));
    };
    v.addEventListener('mediaactivity', () => { checked = 0; });
    // a moment the clip just played through floats up from its place
    const pop = (x) => {
      const slide = bar.closest('.mp-slide');
      if (!slide || !pager || pager.cur !== slide) return;
      const el = h('div', { class: 'mp-pop', style: 'left:calc(' + bar.offsetLeft + 'px + ' + (markAt(x.moment.seconds, v.duration) / 100) + ' * ' + bar.offsetWidth + 'px)' }, momentGlyph(x));
      slide.append(el);
      setTimeout(() => el.remove(), 1700);
    };
    const frac = (e) => { const r = bar.getBoundingClientRect(); return Math.min(1, Math.max(0, (e.clientX - r.left) / (r.width || 1))); };
    const show = (f) => {
      fill.style.width = (f * 100).toFixed(2) + '%';
      if (!bar.classList.contains('say')) time.textContent = clock(f * v.duration) + ' / ' + clock(v.duration); // (unless it's saying a moment)
    };
    const to = (f) => { try { v.currentTime = f * v.duration; } catch {} };
    bar.addEventListener('pointerdown', (e) => {
      if (!(v.duration > 0 && isFinite(v.duration))) return;
      e.stopPropagation(); e.preventDefault();
      try { bar.setPointerCapture(e.pointerId); } catch {}
      bar._drag = { playing: !v.paused, id: e.pointerId };
      bar.classList.add('drag');
      bar.classList.remove('say');
      v.pause();
      const f = frac(e); show(f); to(f);
    });
    bar.addEventListener('pointermove', (e) => {
      if (!bar._drag || bar._drag.id !== e.pointerId) return;
      e.stopPropagation();
      const f = frac(e); show(f);
      if (v.fastSeek) { try { v.fastSeek(f * v.duration); } catch { to(f); } } else to(f);
    });
    const end = (e) => {
      const d = bar._drag;
      if (!d || d.id !== e.pointerId) return;
      bar._drag = null;
      bar.classList.remove('drag');
      if (bar.classList.contains('reveal')) revealSeek(bar); // a few seconds more after the drag
      if (e.type === 'pointerup') to(frac(e));
      if (d.playing) v.play().catch(() => {});
    };
    bar.addEventListener('pointerup', end);
    bar.addEventListener('pointercancel', end);
    bar.addEventListener('click', (e) => e.stopPropagation());
    bar._paint = () => {
      if (bar._drag) return;
      const ok = v.duration > 0 && isFinite(v.duration);
      bar.classList.toggle('ready', ok);
      if (!ok) return;
      show(v.currentTime / v.duration);
      if (performance.now() - checked > 1000) paintMarks();
      const now = v.currentTime;
      if (!v.paused && now > last && now - last < 1) for (const x of items) if (x.moment.seconds > last && x.moment.seconds <= now) pop(x);
      last = now;
    };
    return bar;
  }
  // The pager is posts stacked top to bottom (up and down go from post to
  // post), each a row of its pictures or clips — its quotes' too — side by
  // side (left and right go within it). Its slides, in reading order:
  const pagerSlides = () => (pager ? [...pager.scroller.querySelectorAll('.mp-slide')] : []);
  // the posts in the carousel: those on offer (a clip's post waits out of it
  // until it is ready to play, and a clip the wrong way round for the screen
  // is kept out — see pagerReveal, pagerFit), or every one built (all)
  const PAGER_ON = '.mp-group:not(.mp-wait):not(.mp-off)';
  const pagerGroups = (all = false) => (pager ? [...pager.scroller.querySelectorAll(':scope > ' + (all ? '.mp-group' : PAGER_ON))] : []);
  // the posts found: the ready ones and those still warming, not those kept out for their shape
  const pagerFound = () => (pager ? [...pager.scroller.querySelectorAll(':scope > .mp-group:not(.mp-off)')] : []);
  // the slide a post's row rests on
  const rowSlide = (g) => { const row = g && g._row; if (!row || !row.children.length) return null; return row.children[Math.min(row.children.length - 1, Math.round(row.scrollLeft / (row.clientWidth || 1)))]; };
  // bring a slide to the screen: its post, and within it, the slide
  function pagerShow(slide) {
    const g = slide && slide.closest('.mp-group');
    if (!g) return;
    pager.scroller.scrollTop = g.offsetTop;
    g._row.scrollLeft = slide.offsetLeft;
  }
  // what's next from a slide: down (the next post, where its row rests),
  // along (the next in this post), and the post after next
  function pagerAhead(slide) {
    const out = [];
    // (a post kept out for its shape is passed over: nothing to ready there)
    const nextGroup = (g) => { let n = g && g.nextElementSibling; while (n && (!n.classList.contains('mp-group') || n.classList.contains('mp-off'))) n = n.nextElementSibling; return n; };
    const g1 = nextGroup(slide.closest('.mp-group')), g2 = nextGroup(g1);
    const down = g1 && rowSlide(g1);
    if (down) out.push(down);
    if (slide.nextElementSibling) out.push(slide.nextElementSibling);
    const down2 = g2 && rowSlide(g2);
    if (down2) out.push(down2);
    const prevGroup = (g) => { let n = g && g.previousElementSibling; while (n && (!n.classList.contains('mp-group') || n.classList.contains('mp-off'))) n = n.previousElementSibling; return n; };
    const up = prevGroup(slide.closest('.mp-group')), back = up && rowSlide(up);
    if (back) out.push(back); // (the one before: ready again for the swipe back)
    out.back = back || null;
    return out;
  }
  function pagerAttach(slide) {
    const m = slide.querySelector('.mp-media');
    if (m && !m.getAttribute('src')) m.setAttribute('src', m.tagName === 'VIDEO' ? playSrc(m.getAttribute('data-src')) : m.getAttribute('data-src'));
  }
  // The slide at rest gets its picture's original — fetched and decoded
  // aside first, then swapped in (same box, same aspect: nothing moves) —
  // a moment after landing, so a quick page past it costs nothing.
  function pagerSharpen(slide) {
    const m = slide && slide.querySelector('img.mp-media');
    const full = m && m.getAttribute('data-full');
    if (!full || m.getAttribute('src') === full || m._sharp) return;
    m._sharp = setTimeout(() => {
      m._sharp = 0;
      if (!pager || pager.cur !== slide) return;
      const im = new Image();
      im.decoding = 'async';
      im.onload = () => { const go = () => { if (pager && m.isConnected && m.getAttribute('src') !== full) { m.setAttribute('data-src', full); m.setAttribute('src', full); } }; (im.decode ? im.decode().then(go, go) : go()); };
      im.src = full;
    }, 300);
  }
  // A player's first play with sound waits on the phone's audio output to
  // start: on Adam's Android ~250 ms of a still picture, every clip, warm
  // or not (muted, 60 ms; a muted start then unmuted freezes the picture
  // for those 250 ms instead). A player that has played with sound resumes
  // in 20-80 ms, even many seconds later. So a warm player plays at a
  // volume nobody hears until its picture moves (a frame or two in: the
  // audio's start is the wait) and pauses there — not back to 0: a seek
  // undoes it. Only while the pager has sound on, and the browser lets it.
  // Having played, the player no longer stops reading at its first frame —
  // it fetches the rest of the file — so only a clip known to be small
  // enough to be worth that is primed (most are 3-25 MB).
  const PRIME_MAX = 25e6;
  function primeSound(s, v) {
    if (!pagerLoud || v._primed || (navigator.userActivation && !navigator.userActivation.hasBeenActive)) return;
    const d = videoInfo.get(v.getAttribute('data-src')) || {};
    if (!(d.size > 0 && d.size <= PRIME_MAX)) return;
    const go = () => {
      if (!pager || pager.cur === s || !s.isConnected || !v.getAttribute('src') || !v.paused || v._primed) return;
      v._primed = true;
      v.muted = false; v.volume = 0.001;
      const done = () => {
        clearTimeout(v._primeTimer);
        if (pager && pager.cur !== s) { try { v.pause(); } catch {} }
        v.volume = 1;
        if (pager && pager.cur !== s) v.muted = true;
      };
      v._primeTimer = setTimeout(done, 2000);
      const f = () => { if (v.currentTime >= 0.03 || v.paused) done(); else v.requestVideoFrameCallback(f); };
      v.play().then(() => (v.requestVideoFrameCallback ? v.requestVideoFrameCallback(f) : setTimeout(done, 400)), () => { v._primed = false; done(); });
    };
    if (v.readyState >= 3) go(); else v.addEventListener('canplay', go, { once: true });
  }
  function pagerRelease(slide) {
    const m = slide.querySelector('video.mp-media');
    if (m && m.getAttribute('src')) { try { m.pause(); m.removeAttribute('src'); m.load(); m._primed = false; } catch {} }
  }
  // Flipping through clips is asking to watch them: whatever they cost, the
  // one on screen plays at once (streaming the rest as it goes), and the
  // next two get a head start: the opening half megabyte of each fetched
  // ahead into the browser's cache, where the player finds it — but no
  // more, so a big file isn't pulled down for a clip that may be swiped
  // past. (Not a player of their own yet: one given its file, even told to
  // preload only the metadata, takes the whole of it on a fast link.) Unless the connection
  // is one to be careful with (Data Saver, a slow link). Then only the clip on screen
  // loads in full, the next gets its opening if it's within budget, and a
  // clip over budget waits for a tap; sizes are asked for a few slides
  // ahead, so the verdict is in before the reader gets there. Every other
  // clip holds nothing.
  function pagerNeighbours(slide) {
    if (!pager || pager.kind !== 'videos') return;
    const slides = pagerSlides();
    const i = slides.indexOf(slide);
    const eager = !frugalData();
    const ahead = pagerAhead(slide);
    slides.forEach((s, j) => {
      const k = ahead.indexOf(s);
      if (Math.abs(j - i) <= 2 || k >= 0) slidePoster(s);
      // the slides around the reader (and the one landed on) hold their clip's first frame
      if (eager && ((j > i && j - i <= 5) || (j < i && i - j <= 3) || k >= 0) && !(j === i && pager.at && slide.getAttribute('data-k') === pager.start)) slideFrame(s, k);
      if (j === i) return;
      const v = s.querySelector('video.mp-media');
      if (eager && k >= 0) {
        // the next clip and the one before: a player of its own, warm — once
        // its opening is in the cache, given the file to read up to its
        // first frame (preload 'metadata': Chrome reads ~2 s of it and
        // stops) and paused there, so the swipe onto it is only play and
        // sound (TikTok's trick). The one just left keeps the player it
        // played in (a swipe back to it took 0.7 s on a phone, built anew).
        // The others ahead get their opening only.
        const warm = k === 0 || s === ahead.back;
        if (warm && v.getAttribute('src')) return; // warm already
        pagerRelease(s);
        const head = headStart(playSrc(v.getAttribute('data-src')), k === 0 ? 1 : 0.5);
        if (warm) head.then(() => {
          const now = pager && pager.cur && pagerAhead(pager.cur);
          if (!now || !s.isConnected || pager.cur === s || v.getAttribute('src') || (now[0] !== s && now.back !== s)) return;
          v.preload = 'metadata';
          v.muted = true;
          pagerAttach(s);
          primeSound(s, v);
        });
        return;
      }
      if (k === 0) {
        const url = v.getAttribute('data-src');
        probeVideo(url).then(() => {
          if (!pager || pager.cur === s || videoHeavy(url) || pager.cur !== slide) return;
          v.preload = 'metadata';
          pagerAttach(s);
        });
      } else pagerRelease(s);
    });
    for (const s of slides.slice(i + 2, i + 4)) probeVideo(s.querySelector('video.mp-media').getAttribute('data-src'));
  }
  // A slide near the reader holds its clip's first frame as its poster, so
  // a flick glides onto the very picture the player shows first and the
  // player takes over with no visible change — and a slide left behind
  // (its player let go) keeps it for the swipe back. Some slides came up
  // black until the player had its frame: the frame drawn here needed the
  // next clip's cached opening, a file led by its index and a host that
  // allows the read, and only the next clip had one at all — not the one
  // before, not a flight's landing (Adam, 2026-10-16: "i'm still seeing
  // mostly black between some videos and then they suddenly appear when
  // it starts playing"). The server's first frame (vmedia first.jpg: frame
  // 0 at full size, any host, any layout, cached at the CDN) is the first
  // choice, fetched and decoded aside and put on the slide when it is
  // ready; the frame drawn here is the fallback for the next clip. A clip
  // with neither gets no picture at all — and so stays out of the carousel
  // (pagerReveal): the post's own still, put up meanwhile, was often not
  // the clip's first frame, and the swap from one to the other jarred
  // (Adam, 2026-10-17: "i don't want to show posters and then switch to
  // the first frame … could we just always wait until we have a non-black
  // frame before including the video in the pager?").
  function slideFrame(s, k) {
    const v = s.querySelector('video.mp-media');
    if (!v || v._frame === 'first' || v._frameBusy) return;
    const url = v.getAttribute('data-src');
    const put = (p, kind) => {
      if (!p || !pager || !s.isConnected || v._frame === 'first') return false;
      v.setAttribute('poster', p); v._frame = kind;
      pagerReveal();
      return true;
    };
    const first = serverFirst(url);
    if (first && !serverFirstFailed.has(url)) {
      v._frameBusy = true;
      const im = new Image();
      im.decoding = 'async';
      const ok = () => {
        v._frameBusy = false;
        if (im.naturalWidth && im.naturalHeight && !clipShape(url)) { rememberVideo(url, im.naturalWidth, im.naturalHeight); pagerFit(); } // its shape, from the frame
        put(first, 'first');
      };
      im.onload = () => (im.decode ? im.decode().then(ok, ok) : ok());
      im.onerror = () => { v._frameBusy = false; serverFirstFailed.add(url); slideFrame(s, k); };
      im.src = first;
      return;
    }
    if (k === 0 && !v._grabbed) { // the next clip: its opening is in the cache, the frame comes from there
      v._grabbed = true;
      v._frameBusy = true;
      pagerPoster(playSrc(url)).then((p) => { v._frameBusy = false; put(p, 'first'); });
    }
  }
  // The opening of a clip about to be reached, fetched into the browser's
  // HTTP cache with a range request: the player's own request for the file
  // is answered from there as far as it goes, and streams on from the host.
  // A host that ignores the range sends the whole file: the opening is
  // read, the rest cancelled. A host that doesn't allow the request (no
  // CORS) gets none.
  //
  // How much: enough seconds of the clip that it starts at once and the
  // stream stays ahead of it — few when the link is well ahead of the clip's
  // bitrate, more when it's only just, and when it's behind, enough to cover
  // the shortfall over the clip's length. The bitrate is the file's size over
  // its length when a post says both (else guessed from its picture size, or
  // a phone clip's); the link's speed is measured off these fetches
  // themselves — until there's a measure, a couple of seconds' worth (the
  // browser's own guess at the speed runs low, and would have had every
  // first head start at the cap). A reader who swipes on within seconds gets
  // just the opening; a small clip comes whole.
  const HEAD_MIN = 256 * 1024, HEAD_MAX = 4 * 1024 * 1024;
  let netRate = 0; // bytes/s, from the head starts (a moving average)
  let dwell = 0; // seconds a clip is watched before the swipe on (a moving average)
  function headStartBytes(url) {
    const d = videoInfo.get(url) || {};
    const dur = d.dur > 0 ? d.dur : 0;
    const B = d.size && dur ? d.size / dur // bytes/s
      : d.w && d.h ? Math.max(150e3, d.w * d.h * 30 * 0.1 / 8) : 500e3;
    const D = netRate;
    let lead = !D || D >= 1.5 * B ? 2 : D >= B ? 4 : 2 + (dur || 20) * (1 - D / B);
    if (dwell && dwell < 4) lead = Math.min(lead, 2);
    let n = B * lead;
    if (d.size && d.size <= 3e6 && d.size <= 2 * n) n = d.size;
    return Math.round(Math.min(Math.max(n, HEAD_MIN), HEAD_MAX, d.size || Infinity));
  }
  const headStarted = new Map(); // url -> its promise
  const headDone = new Set(); // head starts finished (or given up: a host that won't allow the read)
  function headStart(url, share = 1) {
    if (!url || url.startsWith('blob:') || frugalData()) return Promise.resolve();
    if (headStarted.has(url)) return headStarted.get(url);
    if (isHls(url)) { // a stream's head start: its playlists and its first piece, the smaller rendition's
      const task = hlsHead(url).catch(() => {}).finally(() => { headDone.add(url); pagerReveal(); });
      headStarted.set(url, task);
      return task;
    }
    const want = Math.max(HEAD_MIN, Math.round(headStartBytes(url) * share));
    const t0 = performance.now();
    const task = fetch(url, { headers: { Range: 'bytes=0-' + (want - 1) } }).then(async (r) => {
      const reader = r.ok && r.body ? r.body.getReader() : null;
      if (!reader) return;
      let got = 0;
      for (;;) {
        const { done, value } = await reader.read();
        if (done) break;
        got += value.length;
        if (got >= want) { reader.cancel().catch(() => {}); break; }
      }
      const secs = (performance.now() - t0) / 1000;
      if (got >= 128 * 1024 && secs > 0) { const rate = got / secs; netRate = netRate ? netRate * 0.6 + rate * 0.4 : rate; }
    }).catch(() => {}).finally(() => { headDone.add(url); pagerReveal(); });
    headStarted.set(url, task);
    if (headStarted.size > 300) { const k = headStarted.keys().next().value; headStarted.delete(k); headDone.delete(k); }
    return task;
  }
  async function hlsHead(url) {
    const get = async (u) => { const r = await fetch(u, { signal: AbortSignal.timeout(20_000) }); if (!r.ok) throw new Error('HTTP ' + r.status); return r; };
    const uri = (text, base) => { const l = text.split('\n').map((x) => x.trim()).find((x) => x && !x.startsWith('#')); return l && new URL(l, base).href; };
    const master = await get(url), text = await master.text();
    // a master playlist's first rendition (vmedia lists the smaller first), or a media playlist itself
    let list = text, at = master.url || url;
    if (/#EXT-X-STREAM-INF/.test(text)) { at = uri(text, at); list = await (await get(at)).text(); }
    const seg = uri(list, at);
    if (seg) await (await get(seg)).arrayBuffer();
  }
  function playSlide(slide) {
    const v = slide.querySelector('video.mp-media');
    if (!v) return;
    pagerNeighbours(slide);
    const url = v.getAttribute('data-src');
    if (!frugalData()) { startSlide(slide); return; } // no waiting on its size: it plays
    probeVideo(url).then(() => {
      if (!pager || pager.cur !== slide) return;
      if (videoHeavy(url)) {
        // under the cover, a picture of what it is: the kept frame, else the
        // first frame itself (only the start of the file, when it leads with
        // its index or is served in ranges) — again on every return, since
        // a slide left behind lets go of its file
        slidePoster(slide, true);
        if (videoThumbs.has(url)) pagerRelease(slide);
        else grabFrame(url).then((kept) => {
          if (!pager || !slide.isConnected) return;
          if (kept) { slidePoster(slide, true); return; }
          // no frame to keep (the host's bytes can't be read, or the index
          // trails): the player shows its own first frame under the cover
          const d = videoInfo.get(url) || {};
          if (pager.cur !== slide || !slide.querySelector('.vid-heavy') || v.getAttribute('src')) return;
          if (!(d.faststart || d.ranges || !d.probed)) return;
          v.preload = 'metadata';
          v.setAttribute('src', url + '#t=0.1');
        });
        if (slide.querySelector('.vid-heavy')) return;
        slide.append(h('button', { class: 'vid-heavy', type: 'button', 'aria-label': t('videoTapToPlay'), onClick: (e) => {
          e.stopPropagation();
          tappedClips.add(url);
          e.currentTarget.remove();
          startSlide(slide);
        } }, h('span', { class: 'vid-heavy-play', 'aria-hidden': 'true' }, '\u25b6'), h('span', {}, heavyLabel(url))));
        return;
      }
      startSlide(slide);
    });
  }
  // the kept frame as the poster, looked up as the slide comes near (it may
  // have been kept after the slide was built) — only where a poster is
  // wanted: a careful connection, or a heavy clip under its cover (force)
  function slidePoster(slide, force = false) {
    if (!force && !frugalData()) return;
    const v = slide.querySelector('video.mp-media');
    const thumb = v && videoThumbs.get(v.getAttribute('data-src'));
    if (thumb && v.getAttribute('poster') !== thumb) v.setAttribute('poster', thumb);
  }
  function startSlide(slide) {
    // only the slide on screen plays (not one a half-way layout — a turn of
    // the phone — passed over), and it alone
    if (!pager || pager.cur !== slide) return;
    const v = slide.querySelector('video.mp-media');
    for (const o of pager.el.querySelectorAll('video.mp-media')) if (o !== v && !o.paused) { try { o.pause(); } catch {} }
    if (/#t=[\d.]+$/.test(v.getAttribute('src') || '')) v.setAttribute('src', playSrc(v.getAttribute('data-src'))); // the still's src: from the start now
    v.preload = 'auto';
    pagerAttach(slide);
    // the clip the pager opened on carries on from where it was in the feed
    if (pager && pager.at && slide.getAttribute('data-k') === pager.start) {
      const at = pager.at;
      pager.at = 0;
      if (v.readyState >= 1) v.currentTime = at;
      else v.addEventListener('loadedmetadata', () => { try { v.currentTime = at; } catch {} }, { once: true });
    }
    v.muted = !pagerLoud;
    v.volume = 1;
    clearTimeout(v._primeTimer);
    clockStart(slide, v);
    v.play().catch((err) => {
      // sound needs a tap the browser counted: play quietly, the button says so
      if (err && err.name === 'NotAllowedError' && !v.muted) {
        pagerLoud = false; v.muted = true;
        pager?.el.classList.add('quiet');
        v.play().catch(() => {});
      }
    });
  }
  // How long from landing on a clip to its picture moving, kept for the
  // last hundred (coinosPagerStarts() in the console, and dlog), with what
  // shape the player was in when the swipe landed (warm: it had its frame).
  const pagerStarts = [];
  function clockStart(slide, v) {
    const t0 = slide._arriveAt;
    slide._arriveAt = 0;
    if (!t0) return;
    const url = v.getAttribute('data-src') || '', warm = v.readyState >= 2, rs = v.readyState;
    const primed = !!v._primed;
    const buf = v.buffered && v.buffered.length ? +v.buffered.end(v.buffered.length - 1).toFixed(1) : 0;
    const d = videoInfo.get(url) || {};
    let host = ''; try { host = new URL(url).hostname; } catch {}
    const done = () => {
      const ms = Math.round(performance.now() - t0);
      pagerStarts.push({ ms, warm, primed, rs, buf, host, mb: d.size ? +(d.size / 1e6).toFixed(1) : null, faststart: d.faststart ?? null, src: (v.getAttribute('src') || '').startsWith(VMEDIA) ? 'copy' : 'original', url });
      if (pagerStarts.length > 100) pagerStarts.shift();
      dlog('pager start', ms + ' ms', warm ? 'warm' : 'cold', host);
    };
    const tick = () => {
      if (!v.isConnected || performance.now() - t0 > 20000) return;
      if (v.currentTime > 0 && !v.paused) { done(); return; }
      if (v.requestVideoFrameCallback) v.requestVideoFrameCallback(tick); else requestAnimationFrame(tick);
    };
    tick();
  }
  if (typeof window !== 'undefined') window.coinosPagerStarts = () => {
    const ms = pagerStarts.map((x) => x.ms).sort((a, b) => a - b);
    const q = (f) => ms.length ? ms[Math.min(ms.length - 1, Math.floor(f * ms.length))] : null;
    return { n: ms.length, median: q(0.5), p90: q(0.9), max: ms.at(-1) ?? null, warm: pagerStarts.filter((x) => x.warm).length, starts: pagerStarts.slice() };
  };
  function pagerSound(on) {
    pagerLoud = on;
    if (!pager) return;
    pager.el.classList.toggle('quiet', !on);
    for (const v of pager.el.querySelectorAll('video.mp-media')) v.muted = !on;
    const cur = pager.cur && pager.cur.querySelector('video.mp-media');
    if (cur && cur.paused) cur.play().catch(() => {});
  }
  // The pager's own glide from slide to slide: the browser's smooth scroll
  // dawdles (half a second and more on Android). Quick and eased out, faster
  // still after a fast flick; snapping stays off until it lands.
  // A longer glide (a flight past several posts) says how long it takes;
  // onDone hears the landing, or the interruption (true) that caught it.
  function pagerGlide(box, axis, to, vel = 0, { ms: want = 0, onDone = null, ease = 3 } = {}) {
    pagerHold(box); // a glide under way is caught where it is
    const y = axis === 'y', from = y ? box.scrollTop : box.scrollLeft, dist = to - from;
    box.style.scrollSnapType = 'none';
    box._onDone = onDone;
    const done = (cut) => { box._glide = 0; box.style.scrollSnapType = ''; const f = box._onDone; box._onDone = null; if (f) f(!!cut); };
    if (Math.abs(dist) < 1) { done(); return; }
    const ms = want || Math.max(60, Math.min(130, Math.abs(dist) / Math.max(5, Math.abs(vel) * 1.5)));
    // timed from its first frame: a frame's time can be a little before now,
    // and a glide timed from now began by stepping back
    let t0 = 0;
    const step = (now) => {
      if (!t0) t0 = now - 8; // (a frame's worth in already: no frame stands still)
      const k = Math.max(0, Math.min(1, (now - t0) / ms)), e = 1 - Math.pow(1 - k, ease);
      if (y) box.scrollTop = from + dist * e; else box.scrollLeft = from + dist * e;
      if (k < 1) box._glide = requestAnimationFrame(step); else done();
    };
    box._glide = requestAnimationFrame(step);
  }
  // Where a slide (or post) sits in its scroller — measured, not counted in
  // screens: a post is 100dvh, a hair off the scroller's height, and n
  // screens down landed past it for the snap to yank back.
  const pagerAt = (box, el, y) => {
    const b = box.getBoundingClientRect(), r = el.getBoundingClientRect();
    return y ? box.scrollTop + r.top - b.top : box.scrollLeft + r.left - b.left;
  };
  const pagerHold = (box) => {
    if (!box || !box._glide) return;
    cancelAnimationFrame(box._glide); box._glide = 0; box.style.scrollSnapType = '';
    const f = box._onDone; box._onDone = null; if (f) f(true);
  };
  // the slide on screen — named, not "a screen further", which from a
  // scroll still settling landed short
  const pagerHere = () => pager && (pagerSlides().find((x) => { const r = x.getBoundingClientRect(); return Math.abs(r.left) < r.width / 2 && Math.abs(r.top) < r.height / 2; }) || pager.cur);
  // A step: v up or down the posts (-1/1), hz along the post's pictures.
  // The keys, the wheel and the desktop arrows all come here.
  function pagerStep(v, hz) {
    if (!pager) return false;
    const here = pagerHere();
    if (v) {
      const groups = pagerGroups();
      const from = here && here.closest('.mp-group');
      // the ends are ends: no going round to the other (Adam, 2026-10-18)
      const to = groups[groups.indexOf(from) + v];
      if (to) pagerGlide(pager.scroller, 'y', pagerAt(pager.scroller, to, true));
      return !!to;
    }
    if (hz) {
      const to = here && (hz > 0 ? here.nextElementSibling : here.previousElementSibling);
      if (to) pagerGlide(here.parentElement, 'x', pagerAt(here.parentElement, to, false));
      return !!to;
    }
    return false;
  }
  // A spin of the wheel flies. Each notch adds a post to go — the third and
  // later notches of a quick run add two, so a flick of the wheel is a few
  // posts and a spin a dozen — and the pager glides through them, the
  // pictures passing, to land snapped on the last. The posts passed are not
  // arrived at (no clip starts, nothing is marked seen): only the landing
  // is (pagerArrive). A notch back against a flight catches it on the post
  // it is passing and steps back from there; a touch or a key catches it
  // too (pagerHold → onDone). A notch from rest is the single step it was.
  let fly = null; // { to: the post flown to, n: notches in this run, at, dir }
  // A pager flies only once ten posts are ready (in the carousel: clips
  // ready to play, pictures decoded): before that a fling outran the
  // warming, landing on whatever was ready and fighting the posts joining
  // (Adam, 2026-10-17: "let's not allow flying/coasting until we have at
  // least 10 videos fully warmed up"; the picture pager the same: "image
  // pager should work similar"). Until then a flick or a spin of the wheel
  // is one post at a time.
  const PAGER_FLY_READY = 10;
  const pagerCanFly = () => !pager || (pager.kind === 'videos' && frugalData()) || pagerGroups().length >= PAGER_FLY_READY;
  function pagerFly(dir, now) {
    if (!pager) return;
    const stops = pagerGroups();
    if (!stops.length) return;
    const live = fly && now - fly.at < 400 && pager.scroller._glide;
    let from, n = 1;
    if (live && fly.dir === dir) { from = fly.to; n = fly.n + 1; }
    else if (live) { // against the flight: the post it is passing
      const y = pager.scroller.scrollTop;
      from = stops.reduce((b, g) => (Math.abs(g.offsetTop - y) < Math.abs(b.offsetTop - y) ? g : b));
    } else {
      const here = pagerHere();
      from = here && here.closest('.mp-group');
    }
    // a flight stops at the end it reaches
    const i = Math.min(stops.length - 1, Math.max(0, stops.indexOf(from) + dir * (n <= 2 || !pagerCanFly() ? 1 : 2)));
    const to = stops[i];
    if (to === from && !live) return;
    fly = { to, n, at: now, dir };
    if (live) pager.scroller._onDone = null; // the flight goes on: not a landing
    pagerFlyTo(to);
  }
  // The flight itself: a glide to the post, the pictures passing, landing
  // snapped on it — only the landing is arrived at. A flick of a finger
  // (pace: a little slower per screen than the wheel's) comes here too.
  function pagerFlyTo(to, { vel = 0, pace = 110, most = 1200 } = {}) {
    const dest = pagerAt(pager.scroller, to, true);
    const screens = Math.abs(dest - pager.scroller.scrollTop) / Math.max(1, pager.scroller.clientHeight);
    pager.flying = true;
    pager.flyDir = Math.sign(dest - pager.scroller.scrollTop);
    const land = pager.kind === 'videos' && !frugalData() && rowSlide(to); // the landing's first frame, fetched on the way
    if (land) slideFrame(land, -1);
    // A flight eases out on a square, not a cube: on a cube a long one
    // spent its last 400 ms creeping under 3 px a frame (Adam's phone, a
    // nine-post flight), and the picture coming to rest stepped a pixel
    // at a time — the stutter "towards the end of the fly as it's
    // snapping" (Adam, 2026-10-17); and it set off at three times its
    // average speed, faster than the finger that flung it.
    pagerGlide(pager.scroller, 'y', dest, vel, {
      ease: screens > 1.05 ? 2 : 3,
      ms: screens > 1.05 ? Math.min(most, 100 + pace * screens) : 0,
      onDone: () => { if (!pager) return; pager.flying = false; const s = pagerHere(); if (s && s !== pager.cur) pagerArrive(s); pagerPosition(); },
    });
  }
  const pagerArrive = (slide) => { if (pager && pager.arrive) pager.arrive(slide); };
  // A finger down on a flight stops it there and then, settling on the post
  // most on screen (Adam, 2026-10-17: "Tapping … should instantly stop the
  // flying … and snap to the video that's most on screen").
  function pagerCatch() {
    pagerHold(pager.scroller); // the flight's onDone: no longer flying, arrived at the post most on screen
    const here = pagerHere(), g = here && here.closest('.mp-group');
    if (g) pagerGlide(pager.scroller, 'y', pagerAt(pager.scroller, g, true));
  }
  // the sideways arrows show only where the post has a picture that way
  function pagerArrows(slide) {
    if (!pager || !slide) return;
    pager.el.classList.toggle('has-left', !!slide.previousElementSibling);
    pager.el.classList.toggle('has-right', !!slide.nextElementSibling);
  }

  // Counted: the posts in the carousel — the ones that can be reached. (All
  // the posts found, the waiting ones too, was tried and undone: a count
  // that can't be scrolled to confused — Adam, 2026-10-17.)
  function pagerPosition() {
    if (!pager) return;
    const groups = pagerGroups();
    const slide = pager.cur || pager.anchor;
    let index = groups.indexOf(slide && slide.closest('.mp-group'));
    // in a flight, the post passing under the reader: the count runs with
    // the slides rather than jumping on landing (Adam, 2026-10-17: "the
    // counter should animate as we fly")
    if (pager.flying && groups.length) {
      const y = pager.scroller.scrollTop + pager.scroller.clientHeight / 2;
      let lo = 0, hi = groups.length - 1; // the last post whose top is above the middle of the screen
      while (lo < hi) { const m = (lo + hi + 1) >> 1; if (groups[m].offsetTop <= y) lo = m; else hi = m - 1; }
      index = lo;
    }
    const text = (index < 0 ? 0 : index + 1) + ' / ' + groups.length, el = pager.el.querySelector('.mp-position');
    if (el.textContent !== text) el.textContent = text;
    // a video pager shows no count until it can fly: ten clips ready (Adam,
    // 2026-10-17: "let's also not show the position/total counter until we have 10")
    // (one with fewer posts than that, every one of them ready, counts them)
    pager.el.classList.toggle('few', !pagerCanFly() && !!pager.scroller.querySelector(':scope > .mp-group.mp-wait:not(.mp-off)'));
  }

  function buildPager(want) {
    const video = want.kind === 'videos';
    const scroller = h('div', { class: 'mp-scroll' });
    scroller.addEventListener('scroll', () => { if (pager && pager.flying) pagerPosition(); }, { passive: true });
    const el = h('div', { class: 'media-pager' + (video ? ' videos' : '') + (pagerLoud ? '' : ' quiet'), role: 'dialog', 'aria-modal': 'true' },
      scroller,
      h('div', { class: 'mp-position', role: 'status' }, '0 / 0'),
      h('div', { class: 'mp-top' },
        h('button', { class: 'mp-x', type: 'button', 'aria-label': t('close'), onClick: (e) => { e.stopPropagation(); dismissPager(); } }, '×'),
        h('div', { class: 'mp-top-r' },
          clipsToggle('mp-fit', () => { pagerFit(); pagerWarmPics(); }),
          video ? h('button', { class: 'mp-sound', type: 'button', onClick: (e) => { e.stopPropagation(); pagerSound(!pagerLoud); } },
            h('span', { class: 'on' }, '\u{1F50A}'), h('span', { class: 'off' }, '\u{1F507} ' + t('videoUnmute'))) : null)),
      // a mouse's way through (shown where there is a pointer to hover with,
      // style.css): up and down the posts at the right edge, left and right
      // along a post's pictures when it has more than one (has-left/right)
      h('div', { class: 'mp-arrows' }, ...[['mp-up', 'pagerPrevPost', 'M6 15l6-6 6 6', -1, 0], ['mp-down', 'pagerNextPost', 'M6 9l6 6 6-6', 1, 0],
        ['mp-ar-left', 'pagerPrevPic', 'M15 6l-6 6 6 6', 0, -1], ['mp-ar-right', 'pagerNextPic', 'M9 6l6 6-6 6', 0, 1]].map(([cls, label, d, v, hz]) =>
        h('button', { class: 'mp-arrow ' + cls, type: 'button', 'aria-label': t(label), title: t(label), onClick: (e) => { e.stopPropagation(); pagerStep(v, hz); } },
          h('span', { style: 'display:flex', html: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="' + d + '"/></svg>' })))));
    // A mouse wheel pages: a notch down is the next post, a notch up the one
    // before, and a spin of notches is a flight past that many (pagerFly),
    // landing snapped on a post. A trackpad's run of small deltas is one
    // step per run (its first 40px; the rest of the run, until a pause, is
    // spent), and a sideways run — or shift+wheel — walks along the post's
    // pictures, a breath between steps. Ctrl+wheel (a
    // trackpad's pinch comes the same way) zooms the picture and the wheel
    // pans it while zoomed: attachZoom takes those first (defaultPrevented).
    // Left to the browser, a notch scrolled the snap container a hundred
    // pixels and the glide's snap put it straight back: the wheel did nothing.
    let wheelStepAt = 0, run = null;
    el.addEventListener('wheel', (e) => {
      if (!pager || e.defaultPrevented || e.ctrlKey || e.metaKey) return;
      if (e.target.closest && e.target.closest('.mp-caption.open, .mp-seek')) return;
      e.preventDefault();
      const k = e.deltaMode === 1 ? 40 : 1;
      let dx = e.deltaX * k, dy = e.deltaY * k;
      if (e.shiftKey && !dx) { dx = dy; dy = 0; }
      const hz = Math.abs(dx) > Math.abs(dy), d = hz ? dx : dy;
      if (!d) return;
      const notch = e.deltaMode === 1 || (hz ? e.wheelDeltaX && e.wheelDeltaX % 120 === 0 : e.wheelDeltaY && e.wheelDeltaY % 120 === 0);
      const now = e.timeStamp;
      if (notch && !hz) { pagerFly(Math.sign(d), now); return; } // up and down the posts: a notch, or a spin, flies
      if (notch) {
        if (now - wheelStepAt < 220) return;
      } else {
        if (!run || now - run.at > 150) run = { at: now, acc: 0, done: false };
        run.at = now;
        if (run.done) return;
        run.acc += d;
        if (Math.abs(run.acc) < 40) return;
        run.done = true;
      }
      wheelStepAt = now;
      pagerStep(hz ? 0 : Math.sign(d), hz ? Math.sign(d) : 0);
    }, { passive: false });
    // A touch is the pager's to judge, not the browser's. Left to native
    // scrolling, a tap whose finger moved a few pixels was taken for a
    // scroll (no click: a tap meant to pause a clip did nothing), and a quick
    // one flung the pager on to the next slide. So the slides follow the
    // finger once it has gone FOLLOW, along the way it set off — up and down
    // post to post, across within a post — and on letting go go on to the
    // next if the finger went a little way or flicked, else back. A touch
    // that came and went within TAP_SLOP is a tap all the same (done here if
    // the browser sent no click): a tap meant to pause a clip drifts.
    const FOLLOW = 10, TAP_SLOP = 24, TAP_MS = 350; // px; px; ms
    const SWIPE_X = 0.1, SWIPE_Y = 0.12, FLICK = 0.2, FLICK_MIN = 24; // of the screen; px/ms; px
    // A fast flick up or down flies past several posts, the way a spin of
    // the wheel does, and lands snapped on one (Adam, 2026-10-16: "make
    // images coast on the phone too when I swipe"): as many posts as the
    // fling would have coasted — the speed times FLY_TAU, in screens — from
    // FLY_V up; a slower swipe is the one post it was. The ends are not
    // flown past: a fling that would, lands on the last (or first) post.
    // (3 px/ms and a 500 ms coast took a hard flick to fly at all — Adam,
    // 2026-10-16: "too hard to get it to fly"; then 800 ms and six posts:
    // "make it fly longer before it settles down… I can slow it down by
    // touching again when I see something I like".) So a long coast, taken
    // slowly enough to watch and to catch: a finger down holds it.
    const FLY_V = 1.6, FLY_TAU = 1600, FLY_MAX = 14; // px/ms; ms; posts
    const TRACK_MS = 80; // the speed is the finger's over its last moment, not its last few samples
    let touch = null, pendingTap = 0, tapDoneAt = 0;
    el.addEventListener('touchstart', (e) => {
      const t = e.touches[0];
      // caught in flight: stopped where it is (a two-finger touch, a touch
      // on the seek bar too); a swipe back from there is the post before it
      // however hard (Adam, 2026-10-17: "reverse swiping should go to the
      // previous video"), one on the way it was flying takes it on
      const caught = !!pager && pager.flying && !!pager.scroller._glide ? pager.flyDir || 0 : 0;
      if (caught) pagerCatch();
      const img = e.target.closest && e.target.closest('img.mp-media');
      // not a touch on the seek bar, in an opened caption, or on a picture zoomed in (each its own)
      touch = e.touches.length === 1 && pager && !e.target.closest('.mp-seek, .mp-caption.open') && !(img && img.style.touchAction === 'none')
        ? { x: t.clientX, y: t.clientY, at: Date.now(), slide: pager.cur, target: e.target, caught } : null;
    }, { passive: true });
    el.addEventListener('touchmove', (e) => {
      const d = touch;
      if (!d || e.touches.length !== 1) { if (d && d.box) settle(d, 0); touch = null; return; }
      if (e.cancelable) e.preventDefault();
      const t = e.touches[0], dx = t.clientX - d.x, dy = t.clientY - d.y;
      if (!d.axis) {
        if (Math.hypot(dx, dy) < FOLLOW) return;
        d.axis = Math.abs(dx) > Math.abs(dy) ? 'x' : 'y';
        d.box = d.axis === 'y' ? pager.scroller : d.slide && d.slide.parentElement;
        if (!d.box) { touch = null; return; }
        pagerHold(d.box); // caught mid-glide: from where it is
        d.start = d.axis === 'y' ? d.box.scrollTop : d.box.scrollLeft;
        d.box.style.scrollSnapType = 'none'; // following the finger: no snapping under it
        d.track = [];
      }
      const delta = d.axis === 'y' ? dy : dx;
      d.far = Math.max(d.far || 0, Math.hypot(dx, dy));
      if (d.axis === 'y') d.box.scrollTop = d.start - delta; else d.box.scrollLeft = d.start - delta;
      // Timed when the finger moved (the event's timeStamp), not when the
      // move was handled: right after a refresh, with clips warming, moves
      // queue behind other work and arrive in bursts — timed on handling, a
      // burst after a stall read as a fling (a short flick flew) and a
      // stall at the end as a crawl (a long flick took one step) (Adam,
      // 2026-10-17: "sometimes a quick long flick only proceeds to the next
      // video … sometimes … a short flick does fly"). The handling time is
      // kept for moves that share a timeStamp (synthetic ones can).
      d.track.push({ t: e.timeStamp, h: performance.now(), v: delta });
      while (d.track.length > 2 && d.track[d.track.length - 1].t - d.track[1].t >= TRACK_MS) d.track.shift();
    }, { passive: false });
    // let go of a drag: on to the next (or the one before), or back
    function settle(d, step, vel = 0) {
      const box = d.box, y = d.axis === 'y';
      const stops = [...box.children].filter((c) => c.matches(y ? PAGER_ON : '.mp-slide')).map((c) => pagerAt(box, c, y));
      if (!stops.length) return;
      // the stop it set off from, then one along (or back) — or, flung, several
      const from = stops.reduce((bi, p, i) => (Math.abs(p - d.start) < Math.abs(stops[bi] - d.start) ? i : bi), 0);
      const posts = y && step && Math.abs(vel) >= FLY_V && pagerCanFly() && !(d.caught && step !== d.caught) ? Math.min(FLY_MAX, Math.max(1, Math.round(Math.abs(vel) * FLY_TAU / Math.max(1, box.clientHeight)))) : 1;
      // past either end, it stops at the end: going round to the other end
      // was tried and undone (Adam, 2026-10-18: "let's not make the media
      // pager circle around to the start anymore")
      const next = from + step * posts;
      if (y && posts > 1) {
        const i = Math.min(stops.length - 1, Math.max(0, next));
        if (i !== from) { pagerFlyTo(pagerGroups()[i], { vel, pace: 260, most: 4000 }); return; }
      }
      pagerGlide(box, d.axis, stops[Math.min(stops.length - 1, Math.max(0, next))], vel);
    }
    el.addEventListener('touchend', (e) => {
      const d = touch;
      touch = null;
      if (!d || e.touches.length || !pager) return;
      const t = e.changedTouches[0];
      if (d.box) {
        const delta = d.axis === 'y' ? t.clientY - d.y : t.clientX - d.x;
        const size = d.axis === 'y' ? d.box.clientHeight : d.box.clientWidth;
        const a = d.track[0], b = d.track[d.track.length - 1];
        const dt = a && b ? (b.t - a.t >= 8 ? b.t - a.t : b.h - a.h) : 0;
        const vel = dt > 0 ? (b.v - a.v) / dt : 0;
        const tap = d.far < TAP_SLOP && Date.now() - d.at < TAP_MS;
        const go = !tap && (Math.abs(delta) > size * (d.axis === 'y' ? SWIPE_Y : SWIPE_X) || (Math.abs(delta) >= FLICK_MIN && Math.abs(vel) > FLICK && Math.sign(vel) === Math.sign(delta)));
        settle(d, go ? (delta < 0 ? 1 : -1) : 0, go ? vel : 0);
        if (!tap) return;
      }
      // the tap that caught a flight only stopped it (the buttons still work)
      if (d.caught && !(d.target.closest && d.target.closest('button, a'))) { tapDoneAt = Date.now(); return; }
      if (Date.now() - d.at > 500) return; // a press, not a tap
      clearTimeout(pendingTap);
      pendingTap = setTimeout(() => {
        pendingTap = 0;
        const btn = d.target.closest && d.target.closest('button, a');
        if (btn) btn.click(); else pagerTap(d.target, t.clientY); // (the click here is before tapDoneAt: not swallowed)
        tapDoneAt = Date.now();
      }, 120);
    }, { passive: true });
    el.addEventListener('touchcancel', () => { if (touch && touch.box) settle(touch, 0); touch = null; }, { passive: true });
    // The browser's click for a touch: it IS the tap, so the pending one
    // stands down — judged on the way down (capture), before a button's own
    // handler stops the bubble: the sound button's click never reached this
    // listener, the pending tap clicked it again 120 ms later, and a clip
    // could not be muted (Adam, 2026-10-16). A click after the pending tap
    // has already been done is swallowed before it reaches anything.
    el.addEventListener('click', (e) => {
      if (pendingTap) { clearTimeout(pendingTap); pendingTap = 0; }
      else if (Date.now() - tapDoneAt < 700) { e.stopPropagation(); e.preventDefault(); }
    }, true);
    el.addEventListener('click', (e) => pagerTap(e.target, e.clientY));
    // On a desktop the bar comes up while the mouse moves over a playing
    // clip and fades once it's been still a moment (Adam, 2026-10-22).
    el.addEventListener('pointermove', (e) => {
      if (e.pointerType !== 'mouse' || !pager || !video) return;
      const bar = pager.cur && pager.cur.querySelector('.mp-seek.ready');
      if (bar) revealSeek(bar, 2000);
    });
    // a tap shows (or hides) who posted it and what they said
    function pagerTap(target, y) {
      if (target.closest('button, a, .mp-caption, .mp-seek')) return;
      if (Date.now() - videoTapAt < 800) return; // the click of the touch that opened it
      // The seek bar is out of sight while a clip plays (Adam, 2026-10-19:
      // only when someone goes for it, or pauses): a tap near the foot of
      // the screen, where it sits, brings it up without pausing.
      const bar = pager && video && pager.cur && pager.cur.querySelector('.mp-seek.ready');
      if (bar && y != null && !el.classList.contains('show') && y >= bar.getBoundingClientRect().top - 72) { revealSeek(bar); return; }
      if (pager && video) {
        // A clip (from the feed or the media grid): a tap anywhere but the
        // seek bar and the buttons pauses it and brings up who posted it,
        // the ×, the seek bar to grab; another plays it on.
        const v = pager.cur && pager.cur.querySelector('video.mp-media');
        if (v && !v.paused) { v.pause(); el.classList.add('show'); pagerCounts(pager.cur); return; }
        el.classList.remove('show');
        if (v && v.getAttribute('src')) v.play().catch(() => {});
        else if (pager.cur) playSlide(pager.cur);
        return;
      }
      if (pager && pagerSource()) {
        // Opened from a post on a page (the feed, a profile, a thread): the
        // first tap shows the post's details — its caption and controls —
        // and the next closes the pager onto that post. (A tap on the
        // picture that opened it used to close it outright, as a full-screen
        // picture had; Adam, 2026-10-16: a tap should bring the details up
        // wherever the picture was opened from.)
        if (!el.classList.contains('show')) { el.classList.add('show'); pagerCounts(pager.cur); return; }
        dismissPager();
        return;
      }
      el.classList.toggle('show');
      if (el.classList.contains('show')) pagerCounts(pager && pager.cur);
    }
    pager = { el, scroller, kind: want.kind, keys: new Set(), cur: null, feed: want.feed, fromFeed: !!want.fromFeed, profile: want.profile || null, thread: want.thread || null, start: want.start, at: want.at || 0 };
    pager.near = new IntersectionObserver((entries) => {
      for (const e of entries) {
        if (!e.isIntersecting) continue;
        watchZaps([e.target._ev.id]);
        // pictures are cheap — a post's all at once, the ones along its row
        // too (out of sight sideways, they'd load only on arrival); clips
        // are pagerNeighbours' call
        if (pager.kind === 'images') for (const x of e.target.closest('.mp-group').querySelectorAll('.mp-slide')) {
          pagerAttach(x);
          const im = x.querySelector('img.mp-media'); // decoded before the flick lands: it glides in as a picture, not a blank
          if (im && im.decode) im.decode().catch(() => {});
        }
      }
    }, { root: scroller, rootMargin: '250% 0px' });
    // a slide has come to rest on screen (or a flight has landed on it)
    pager.arrive = (slide) => {
      if (!pager) return;
      if (pager.cur && pager.cur !== slide) {
        const v = pager.cur.querySelector('video.mp-media'); if (v) v.pause();
        // how long a clip held the reader (the head start's measure of them)
        if (v && pager.curAt) { const secs = (Date.now() - pager.curAt) / 1000; dwell = dwell ? dwell * 0.7 + secs * 0.3 : secs; }
        if (pagerSource() && video) el.classList.remove('show');
      }
      if (pager.cur) pager.cur.classList.remove('mp-cur');
      slide.classList.add('mp-cur'); // (the one with the layer for a pinch: style.css)
      pager.cur = slide;
      pager.anchor = slide;
      pager.curAt = Date.now();
      slide._arriveAt = performance.now();
      pagerSharpen(slide);
      pagerArrows(slide);
      pagerPosition();
      if (pager.fromFeed) { const row = feedNow().notes.find((x) => x.id === slide._rowId); markSeen(row || slide._ev); }
      else if (pager.profile || pager.thread) markSeen(slide._ev);
      playSlide(slide);
      pagerCounts(slide);
      pagerLoadAhead();
      pagerWarmPics();
    };
    pager.io = new IntersectionObserver((entries) => {
      for (const e of entries) {
        if (!e.isIntersecting || e.intersectionRatio < 0.6 || !pager) continue;
        if (pager.flying) continue; // passing, not arriving: the landing is pagerFly's
        // a slide the screen's new size put there, not the reader: the anchor goes back
        if (pager.screenH && scroller.clientHeight !== pager.screenH) { pager.onResize(); continue; }
        pager.arrive(e.target);
      }
    }, { root: scroller, threshold: [0.6] });
    growPager();
    document.body.append(el);
    document.documentElement.classList.add('no-scroll');
    const first = pagerSlides().find((s) => s.getAttribute('data-k') === want.start) || pagerSlides()[0];
    if (first) pagerShow(first);
    pager.anchor = first; // the slide meant to be on screen, from the first moment
    pager.screenH = scroller.clientHeight;
    pagerLoadAhead();
    // the clip on screen's seek bar, every frame (timeupdate comes a few
    // times a second). While the pager is in motion — under a finger, in a
    // glide or a flight, snapping back — no seek bar shows at all: the
    // clip's slide is off its mark, and the bar rode along with it, a
    // white line sliding up the screen (Adam, 2026-10-16: "i don't want to
    // see the seek bar while i'm transitioning to the next video"). It
    // fades back in once the clip is square on the screen. (The motion flag
    // is a picture pager's too: its counter shows while it moves.)
    {
      const p = pager;
      const frame = () => {
        if (pager !== p) return;
        const bar = p.cur?.querySelector('.mp-seek');
        if (bar) bar._paint();
        const r = p.cur && p.cur.getBoundingClientRect();
        p.el.classList.toggle('moving', !!r && (Math.abs(r.top) > 2 || Math.abs(r.left) > 2));
        if (p.later && p.later.length && !pagerMoving()) { const l = p.later; p.later = []; for (const [g, cls, on] of l) pagerToggleGroup(g, cls, on); }
        p.raf = requestAnimationFrame(frame);
      };
      p.raf = requestAnimationFrame(frame);
    }
    // turned on its side (or back), the slides change height: stay on this one
    // The screen changed size — a turn of the phone, or the page going full
    // screen for the pager (the address bar and tabs gone: a taller window).
    // The posts are a screen tall each, so a scroll position in pixels
    // deep in the pager now sits in a different post: put the one meant
    // back on screen. The slide meant is the anchor, set the moment the
    // pager opens (cur is set by the observer a frame later, and the full
    // screen's resize beat it: Adam's full-screen button on a clip 23 posts
    // down landed him on another post's picture) and on each arrival.
    pager.onResize = () => {
      if (!pager) return;
      pager.screenH = pager.scroller.clientHeight;
      if (pager.anchor) pagerShow(pager.anchor);
      for (const b of el.querySelectorAll('.mp-fit')) b.textContent = clipsLabel();
      pagerFit();
    };
    window.addEventListener('resize', pager.onResize);
    // new posts land in the feed while the pager is open; counts move
    pager.tick = setInterval(() => { if (pager) { growPager(); pagerLoadAhead(); if (el.classList.contains('show')) pagerCounts(pager.cur); } }, 1500);
  }
  // All media pagers build the same buffer, retaining the source's ordering
  // and filters. The furthest post reached never moves back when we wrap,
  // so pending refills continue while the reader circles through older items.
  const PAGER_INITIAL = 30, PAGER_AHEAD = 20;
  function pagerLoadSource(p) {
    const src = pagerSource(p);
    if (src) return {
      more: src.more, done: src.done,
      progress: () => src.c.shown + ':' + src.c.notes.length,
    };
    // A profile cache can be replaced while refreshing; never fall back
    // to another source in that gap. The next timer tick will try again.
    if (p.profile || p.fromFeed) return { more: async () => {}, done: () => true, progress: () => '' };
    const c = feedNow(), r = mediaIndex(c.id);
    const curated = feedDef(c.id)?.curated;
    return {
      more: () => crawlMedia(c, p.kind),
      done: () => c.stopped || (curated ? c.end && c.shown >= c.notes.length : !!r.end),
      progress: () => [r.until, r[p.kind].size, c.shown, c.notes.length].join(':'),
    };
  }
  async function pagerLoadAhead() {
    const p = pager;
    if (!p) return;
    const groups = pagerGroups(true);
    const slide = p.cur || p.anchor;
    p.furthest = Math.max(p.furthest ?? -1, groups.indexOf(slide && slide.closest('.mp-group')));
    if (p.loadingAhead || Date.now() < (p.retryAheadAt || 0)) return;
    p.loadingAhead = true;
    let stalled = false;
    try {
      // Bound each run; the timer resumes if sparse media needs more pages.
      for (let pages = 0; pages < 8 && pager === p; pages++) {
        // (the posts found, waiting ones too: ready ones come only as fast as they warm)
        if (pagerFound().length >= Math.max(PAGER_INITIAL, p.furthest + 1 + PAGER_AHEAD)) break;
        const src = pagerLoadSource(p);
        if (src.done()) break;
        const before = src.progress();
        await src.more();
        if (pager !== p) return;
        growPager();
        if (src.progress() === before) { stalled = true; break; }
      }
    } catch { stalled = true; } finally {
      p.loadingAhead = false;
      // An empty or busy source gets a breather, never concurrent requests.
      p.retryAheadAt = Date.now() + (stalled ? 10000 : 1500);
    }
  }
  // Slides for feed items the pager doesn't have yet: into their post's row
  // (a quote fetched late joins its post), a new post appended below (never
  // inserted above the one on screen).
  function growPager() {
    if (!pager) return;
    const c = feedNow();
    pager.groups ||= new Map();
    const src = pagerSource();
    for (const it of (src ? src.items(pager.kind) : mediaItems(c, pager.kind, true))) {
      const k = mediaKey(it);
      if (pager.keys.has(k)) continue;
      pager.keys.add(k);
      const s = pagerSlide(it);
      const gk = it.row ? it.row.id : it.ev.id;
      let g = pager.groups.get(gk);
      if (!g) {
        g = pagerGroup();
        // out of the carousel until it's ready: a clip to play, a picture decoded
        if (pager.kind === 'images' || !frugalData()) g.classList.add('mp-wait');
        pager.groups.set(gk, g);
        pager.scroller.append(g);
      }
      if (k === pager.start) { g.classList.remove('mp-wait'); g._opened = true; } // the clip tapped: in, whatever its state
      g._row.append(s);
      pagerDots(g);
      pager.near.observe(s);
      pager.io.observe(s);
    }
    pagerFit();
    pagerPosition();
    pagerWarmPics();
  }
  // A picture post is ready once its picture is decoded: only then does it
  // join the carousel, so a flight passes over pictures already in hand.
  // They were fetched and decoded as the flight came near them, and the
  // flight stuttered — dropped frames with no script running, the decoding
  // (Adam, 2026-10-17: "some stutter/choppiness when flying images"; seen
  // on his phone: 66 ms frames mid-flight as pictures arrived). A few at a
  // time are decoded ahead of the reader (and a few behind, for the way
  // back), out of sight; its size learned, a picture the wrong way round
  // for the screen stays out like a clip (pagerFit). One that can't be had
  // at all — copy and original both gone — stays out.
  const PIC_WARM_AT_ONCE = 4, PIC_READY_AHEAD = 16, PIC_WARM_BEHIND = 3;
  function pagerWarmPics() {
    if (!pager || pager.kind !== 'images') return;
    const all = pagerFound();
    const cur = pager.cur || pager.anchor, ci = Math.max(0, all.indexOf(cur && cur.closest('.mp-group')));
    let busy = all.filter((g) => g._warming).length;
    const want = (g) => g.classList.contains('mp-wait') && !g._warming && !g._failed;
    for (let j = ci + 1, ready = 0; j < all.length && busy < PIC_WARM_AT_ONCE && ready < PIC_READY_AHEAD; j++) {
      if (!all[j].classList.contains('mp-wait')) { ready++; continue; }
      if (want(all[j])) { warmPic(all[j]); busy++; }
    }
    for (let j = ci - 1; j >= Math.max(0, ci - PIC_WARM_BEHIND) && busy < PIC_WARM_AT_ONCE; j--) if (want(all[j])) { warmPic(all[j]); busy++; }
  }
  function warmPic(g) {
    const p = pager;
    g._warming = true;
    for (const x of g._row.children) pagerAttach(x);
    const m = g._row.firstElementChild && g._row.firstElementChild.querySelector('img.mp-media');
    // the copy failing falls back to the original (its onError): decoded again
    const decode = (n) => {
      const src = m.getAttribute('src');
      return m.decode().then(() => true, () => new Promise((r) => setTimeout(r, 60)).then(() =>
        n < 2 && m.getAttribute('src') !== src && !m.closest('.mp-slide').classList.contains('mp-gone') ? decode(n + 1) : false));
    };
    const timeout = new Promise((r) => setTimeout(() => r(false), 20000));
    Promise.race([m ? decode(0) : Promise.resolve(true), timeout]).then((ok) => {
      g._warming = false;
      if (pager !== p || !g.isConnected) return;
      if (!ok) { g._failed = true; pagerWarmPics(); return; }
      const url = m && m.getAttribute('data-full');
      if (url && m.naturalWidth && !mediaReady.has(url)) mediaReady.set(url, { width: m.naturalWidth, height: m.naturalHeight }); // its shape
      pagerFit();
      pagerToggleGroup(g, 'mp-wait', false);
      pagerWarmPics();
    });
  }
  // A post's clip is ready to play when its first frame is on the slide and
  // its opening is in the cache (the head start done): only then does the
  // post join the carousel, so the reader never lands on a black slide
  // (Adam, 2026-10-16: "i never want to land on a black screen i'd rather
  // just not have a video in carousel yet if it's not ready to play"). A
  // post joining above the one on screen would push it down: the scroll
  // moves by the post's height in the same frame, snapping off meanwhile,
  // and not while the pager is in motion (then, once it has settled).
  function pagerReveal() {
    if (!pager || pager.kind !== 'videos') return;
    const eager = !frugalData();
    for (const g of pager.scroller.querySelectorAll(':scope > .mp-group.mp-wait')) {
      const v = g._row.firstElementChild && g._row.firstElementChild.querySelector('video.mp-media');
      if (!v) continue;
      const url = v.getAttribute('data-src');
      // the frame is asked of a clip that can have one (the server's: an https
      // clip); a local http clip (a dev setup) waits only for its opening
      if ((serverFirst(url) && !v._frame) || (eager && !headDone.has(playSrc(url)))) continue;
      pagerToggleGroup(g, 'mp-wait', false);
    }
  }
  // the posts whose clips are the wrong way round for the screen stay out
  // (not the one opened on; a shape not yet known is let in)
  function pagerFit() {
    if (!pager) return;
    const cur = pager.cur || pager.anchor, cg = cur && cur.closest('.mp-group');
    for (const g of pagerGroups(true)) {
      const fits = g._opened || g === cg || [...g._row.children].some((s) => { const m = s.querySelector('.mp-media'); return !m || clipFits(m.getAttribute('data-full') || m.getAttribute('data-src')) !== false; });
      pagerToggleGroup(g, 'mp-off', !fits);
    }
  }
  function pagerToggleGroup(g, cls, on) {
    if (!pager || g.classList.contains(cls) === on) return;
    const cur = pager.cur || pager.anchor, cg = cur && cur.closest('.mp-group');
    const above = !!cg && cg !== g && !!(g.compareDocumentPosition(cg) & Node.DOCUMENT_POSITION_FOLLOWING);
    if (above && pagerMoving()) { (pager.later ||= []).push([g, cls, on]); return; } // once it has settled (the frame loop)
    const box = pager.scroller;
    const shown = g.offsetParent !== null; // (a group hidden the other way stays hidden: no height to count)
    const h0 = shown ? g.offsetHeight : 0;
    box.style.scrollSnapType = 'none';
    g.classList.toggle(cls, on);
    if (above) box.scrollTop += (g.offsetParent !== null ? g.offsetHeight : 0) - h0;
    requestAnimationFrame(() => { if (pager && !box._glide) box.style.scrollSnapType = ''; });
    pagerPosition();
    if (cg === g && on) { const s = pagerHere(); if (s && s !== pager.cur) pagerArrive(s); } // the one on screen went out (turned the phone): whoever is there now
  }
  const pagerMoving = () => !!pager && (pager.flying || !!pager.scroller._glide || pager.el.classList.contains('moving'));
  // A post in the pager: its row of slides, side by side, and — with more
  // than one — dots saying how many and which.
  function pagerGroup() {
    const row = h('div', { class: 'mp-row' });
    const dots = h('div', { class: 'mp-dots', 'aria-hidden': 'true' });
    const g = h('div', { class: 'mp-group' }, row, dots);
    g._row = row; g._dots = dots;
    row.addEventListener('scroll', () => pagerDots(g), { passive: true });
    return g;
  }
  function pagerDots(g) {
    const n = g._row.children.length;
    if (g._dots.children.length !== (n > 1 ? n : 0)) g._dots.replaceChildren(...(n > 1 ? Array.from({ length: n }, () => h('i')) : []));
    const at = rowSlide(g);
    [...g._dots.children].forEach((d, i) => d.classList.toggle('on', g._row.children[i] === at));
  }
  if (typeof window !== 'undefined') {
    window.addEventListener('keydown', (e) => {
      if (!pager || e.defaultPrevented) return;
      if (ui.reactPick) { if (e.key === 'Escape') { e.preventDefault(); ui.reactPick = null; ui.emojiPick = null; render(); } return; } // the emoji sheet's
      if (e.key === 'Escape') { e.preventDefault(); dismissPager(); return; }
      // up and down: the next post, or the one before; left and right: along this post's row
      const v = ['ArrowDown', 'j', 'PageDown'].includes(e.key) ? 1 : ['ArrowUp', 'k', 'PageUp'].includes(e.key) ? -1 : 0;
      const hz = ['ArrowRight', 'l'].includes(e.key) ? 1 : ['ArrowLeft', 'h'].includes(e.key) ? -1 : 0;
      if (v || hz) { e.preventDefault(); pagerStep(v, hz); return; }
      if (e.key === ' ' && pager.cur) {
        const v = pager.cur.querySelector('video.mp-media');
        if (v) { e.preventDefault(); if (v.paused) v.play().catch(() => {}); else v.pause(); }
      }
    });
    window.addEventListener('popstate', () => setTimeout(syncMediaPager, 0));
  }

  function feedView() {
    syncFollowSets().catch(() => {}); // throttled inside
    syncReports().catch(() => {}); // likewise
    if (usingBaseline()) syncBaseline()?.catch?.(() => {}); // a reader without a web of trust borrows one
    // Back/Forward restored another feed's id: catch up before painting
    if (ui.feedId && ui.feedId !== curFeedId && feedDef(ui.feedId)) selectFeed(ui.feedId);
    const c = feedNow();
    c.opened = true;
    const def = feedDef();
    const visitor = isVisitor();
    queueMicrotask(() => {
      syncMediaPager();
      if (listView()) watchSeen();
      else watchMediaTiles();
    });
    const authors = feedAuthors(def);
    const hasQuery = feedHasQuery(def);
    // the follows feed of someone who follows nobody: only their own posts
    const noFollows = !!def.follows && !followsNow().set.size && !(def.authors || []).length && !(def.priv || []).length && !feedTopics(def).length;
    prepareFeedAhead(c);
    // Never a bare spinner over posts we already hold: while the opening
    // page's faces and pictures are still being decoded, the cached rows
    // paint as they are (live profiles, pictures as they load) and take
    // their settled presentation once the warm-up lands. The spinner is
    // for a feed with nothing cached at all.
    const curatedFeed = !!(feedDef(c.id) || {}).curated;
    // (a reply whose post every lookup came back without isn't shown: a
    // "Couldn't find that note" over it told nobody anything — Adam, 2026-10-20)
    const repliesHere = feedReplies(c);
    const shownHere = (ev) => !hidden(ev) && !(curatedFeed && notForPublic(ev)) && !(repliesHere && orphaned(ev));
    const visible = c.notes.filter(shownHere);
    // Every child keyed by its post, hairlines included, so the morph
    // reconciles the list by post: a new one at the top is inserted as its
    // own node; the rest keep theirs.
    const list = visible.slice(0, c.shown || FEED_PAGE);
    // The window's list getter runs on every scroll frame and inside
    // holdScroll; filtering every note through the mute/spam/report checks
    // each time was the main thread's single largest cost while a feed
    // loaded. Anything that changes who is shown goes through render(), which
    // lands here again; between renders the same notes give the same list.
    const visNotes = c.notes, visShown = c.shown;
    c.winList = () => (c.notes === visNotes && c.shown === visShown ? list : c.notes.filter(shownHere).slice(0, c.shown || FEED_PAGE));
    const rows = windowedRows(c, list, (ev) => (c.booting && !c.prepared?.has(ev.id)
      ? keyed(noteRow(ev.pubkey, ev, displayName(ev.pubkey), { context: feedReplies(c) }), ev.id) : feedRow(c, ev)));
    // Posts that went in above you while you were reading. A floating pill
    // that says how many are up there; the tap takes you up to them.
    // Keyed, so the morph keeps this very node while the count changes —
    // the count itself is a fresh node each time, which is what replays its
    // bump. The tap is the pill's alone (no bubbling into the page).
    // A swipe sends it away until more posts arrive than it was showing.
    const waiting = c.pillN = pillCount(c);
    if (!c.unseen) c.pillDismissed = 0;
    const pill = waiting && (c.unseen || 0) > (c.pillDismissed || 0)
      ? h('button', {
          class: 'feed-new-pill', 'data-key': 'feed-pill', type: 'button',
          onClick: (e) => {
            e.preventDefault(); e.stopPropagation();
            if (e.currentTarget._swiped) { e.currentTarget._swiped = false; return; }
            jumpToNew();
          },
          ...pillSwipe(() => { c.pillDismissed = c.unseen || 0; render(); }),
        }, '↑ ', h('span', { class: 'n', 'data-key': 'n:' + waiting }, String(waiting)), ' ',
          waiting === 1 ? t('feedOneNewWord') : t('feedNNewWord'))
      : null;
    // the chat shell draws the brand header; this is just the page under it
    return h('div', { class: 'card col chat-page feed-page', style: 'gap:10px' },
        h('div', { 'data-key': 'feed-notice', style: 'display:contents' }, pill),
        h('div', { class: 'row gap6', style: 'align-items:center' },
          backBtn(() => {
            stopFeedWatch();
            // a feed opened from somewhere (a profile's timeline, a #tag, a
            // pack link) goes back there — or, reached directly, to yours
            if (!visitor && adhocFeeds.has(def.id)) { ctx.goBack(() => { ui.chatOpen = true; ui.msgView = 'feed'; selectFeed(homeFeedId()); }); return; }
            if (visitor) { ui.chatOpen = false; ui.msgView = null; ui.pubProf = null; } else ui.msgView = 'home';
            render();
          }),
          def.of ? avatar(def.of, 'chat-avatar mini', true) : null,
          h('h3', { style: 'margin:0;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap' },
            def.builtin && !def.all ? t('feedTitle') : def.of && !def.name ? t('feedOfTitle', { name: displayName(def.of) }) : def.name),
          // one ⋯ for the feed itself (share, relays, save or edit) and one
          // pencil for a new post: the title keeps the room a phone has
          h('button', {
            class: 'btn-sm' + (feedRelays(def) ? ' on' : ''), title: t('feedMenu'), 'aria-label': t('feedMenu'), style: 'margin-left:auto;flex-shrink:0',
            onClick: () => { ui.feedMenu = true; render(); },
          }, '\u22ef'),
          ),
        ui.feedRelayEdit && ui.feedRelayEdit.id === def.id ? relayPanel(def) : null,
        visitor ? null : feedChips(),
        (refreshLive(), mediaModes()),
        // floating bottom right, wherever the reader is in the feed: the
        // composer opens at the top and takes the focus
        visitor || ui.profCompose != null ? null : h('button', {
          class: 'btn-primary feed-post-fab', 'data-key': 'feed-post-fab', type: 'button', title: t('profNewPost'), 'aria-label': t('profNewPost'),
          onClick: () => {
            ui.profCompose = draftFor(POST_DRAFT) || '';
            render();
            try { window.scrollTo({ top: 0, behavior: 'smooth' }); } catch { window.scrollTo(0, 0); }
            setTimeout(() => document.querySelector('.post-input')?.focus(), 60);
          },
        }, h('span', { class: 'feed-compose-icon', 'aria-hidden': 'true', html:
          '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path stroke="currentColor" d="M12 4H6a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-6"/><path stroke="currentColor" opacity=".5" d="M8 17h5"/><path class="compose-pen-fill" d="m16.5 3.5 3 3-8 8-4 1 1-4Z"/><path class="compose-pen" d="M16.5 3.5a2.1 2.1 0 0 1 3 3l-8 8-4 1 1-4Z"/><path class="compose-pen" d="m14.5 5.5 3 3"/></svg>' }), h('span', {}, t('feedPostFab'))),
        visitor ? null : postComposer(),
        def.of && !ofLoaded(def)
          ? h('div', { class: 'row gap6', style: 'justify-content:center;align-items:center;padding:12px 0' },
              h('span', { class: 'spinner sm' }), h('span', { class: 'small muted' }, t('feedOfLoading')))
        : def.of && !hasQuery
          ? h('div', { class: 'small muted', style: 'text-align:center;padding:12px 0' }, t('feedNoFollowsOf'))
        : !hasQuery || noFollows
          ? def.builtin
            ? 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')),
                // your own posts, under the invitation
                noFollows && visible.length && listView() ? h('div', { class: 'card col notes-feed', style: 'gap:0' }, ...rows) : null)
            : h('div', { class: 'col', style: 'gap:8px' },
                h('div', { class: 'small muted' }, t('feedNoQuery')),
                h('button', { class: 'btn-sm', onClick: () => openFeedEditor(def) }, t('feedEdit')))
          : mediaMode === 'live' ? liveGrid(def)
          : (c.booting || 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'))
              : mediaMode === 'articles' ? articleList(c)
              : !listView() ? mediaGrid(c)
              : h('div', { class: 'card col notes-feed', style: 'gap:0', 'data-booting': c.booting ? '1' : undefined, 'data-shown': c.shown, 'data-held': c.notes.length }, ...rows),
        // The foot of the feed says what is happening down there: older
        // posts on their way, or nothing older left to fetch. (Older pages
        // prepare offscreen, so the line is mostly seen by a reader who
        // outruns them.)
        mediaMode === 'live' ? null
        : c.loadingMore || (mediaMode === 'articles' ? articlesCrawling && mediaIndex(c.id).articles.size : !listView() && mediaCrawling)
          ? h('div', { class: 'row gap6 feed-foot', style: 'justify-content:center;align-items:center;padding:10px 0' },
              h('span', { class: 'spinner sm' }), h('span', { class: 'small muted' }, t('feedLoadingMore')))
          : !listView() ? (mediaMode === 'articles' && mediaIndex(c.id).art.end ? h('div', { class: 'small faint feed-foot', style: 'text-align:center;padding:10px 0' }, t('feedEnd')) : null)
          : c.end && visible.length && !(c.win && c.win.bottom) && c.shown >= visible.length
            ? h('div', { class: 'small faint feed-foot', style: 'text-align:center;padding:10px 0' }, t('feedEnd'))
            : null,
        // the reader's language, right where a curated feed is judged by it
        ctx.languagePicker ? h('div', { class: 'row gap6 feed-lang', 'data-key': 'feed-lang', style: 'justify-content:center;align-items:center;padding:6px 0 2px' },
          h('span', { class: 'small muted' }, t('feedLangLabel')), ctx.languagePicker()) : null,
        ...noteOverlays());
  }


  // ---- defining a feed ----------------------------------------------------
  // Name, the people (everyone you follow and/or a hand-picked few) and the
  // topics. People AND topics narrows to their posts on those topics; either
  // alone is the whole of it. Saved into the synced state, so every device
  // has the same feeds.
  function openFeedEditor(def) {
    syncFollowSets().catch(() => {});
    // a new feed of people is a list from the start; a feed made before
    // lists existed stays private until its owner says otherwise
    const isNew = !def || adhocFeeds.has(def.id);
    def = (def && st().feeds.find((f) => f.id === def.id)) || def; // as saved, not expanded
    ui.feedEdit = def
      ? { id: def.id, name: def.name || '', follows: !!def.follows, lists: !!def.lists, interests: !!def.interests, authors: [...(def.authors || [])], priv: [...(def.priv || [])], packs: [...(def.packs || [])],
          topics: feedTopics(def).map((x) => '#' + x).join(' '), q: '', rows: null, pq: '', packRows: null, isNew, d: def.d || null, publish: isNew || !!def.d,
          relays: (def.relays || []).map((r) => r.replace(/^wss:\/\//, '')).join(' '), all: !!def.all && !def.builtin, curated: !!def.curated }
      : { id: null, name: '', follows: false, lists: false, interests: false, authors: [], priv: [], packs: [], topics: '', q: '', rows: null, pq: '', packRows: null, isNew: true, d: null, publish: true,
          relays: '', all: false, curated: false };
    render();
  }
  const feedPeopleSearcher = makeSearcher((q, rows) => {
    const e = ui.feedEdit;
    if (e && e.q === q) { e.rows = rows; render(); }
    for (const r of rows || []) if (r.pk) prefetchProfilePage(r.pk);
  });
  function saveFeedEditor() {
    const e = ui.feedEdit;
    if (!e) return;
    const topics = [...new Set(e.topics.split(/[\s,]+/).map(normTopic).filter(Boolean))].slice(0, 20);
    const words = String(e.relays || '').split(/[\s,]+/).filter(Boolean);
    const relays = [...new Set(words.map(normRelay).filter(Boolean))].slice(0, 12);
    if (relays.length < words.length) { toast(t('feedRelayBad')); return; }
    // every post on its relays: a firehose needs the relays, nothing else
    if (e.all && !relays.length) { toast(t('feedAllNeedsRelays')); return; }
    if (!e.all && !e.follows && !e.lists && !e.interests && !e.authors.length && !e.packs.length && !topics.length) { toast(t('feedNoQuery')); return; }
    const name = e.name.trim().slice(0, 40) || (e.all ? relays[0].replace(/^wss:\/\//, '') : topics.length ? '#' + topics[0] : t('feedNewName'));
    const s = st();
    const keep = e.id && !adhocFeeds.has(e.id) && s.feeds.some((f) => f.id === e.id);
    const id = keep ? e.id : 'f' + Date.now().toString(36) + Math.random().toString(36).slice(2, 6);
    const def = e.all
      ? { id, name, follows: false, authors: [], packs: [], topics: [], all: true, curated: !!e.curated, relays, at: Date.now() }
      : { id, name, follows: e.follows, lists: !!e.lists, interests: !!e.interests, authors: e.authors.slice(0, FEED_AUTHORS_MAX), packs: e.packs.slice(0, 20), topics, relays, all: false, curated: false, at: Date.now() };
    if (!relays.length) delete def.relays;
    if (!def.lists) delete def.lists;
    if (!def.interests) delete def.interests;
    const prev = keep ? s.feeds.find((f) => f.id === id) : null;
    // d, listAt, listContent and priv ride along from the previous copy
    if (keep) s.feeds = s.feeds.map((f) => (f.id === id ? { ...f, ...def } : f)); else s.feeds.push(def);
    save(s);
    feedsChanged();
    if (e.id && adhocFeeds.has(e.id)) adhocFeeds.delete(e.id);
    dropFeedState(id); // its query changed: rebuild from scratch
    ui.feedEdit = null;
    switchFeed(id);
    // the list side: a feed of people goes out as a follow set (or, unticked,
    // comes off the relays)
    const saved = s.feeds.find((f) => f.id === id);
    const isList = !!e.publish && (def.authors.length > 0 || (saved.priv || []).length > 0);
    if (isList) publishFollowSet(saved).then(() => render()).catch((err) => { if (!(err instanceof NoIdentity)) toast(err.message || String(err)); });
    else if (prev && prev.d) {
      // ours first: the deletion re-reads the state to note the list as gone
      delete saved.d; delete saved.listAt; delete saved.listContent; saved.priv = [];
      save(s);
      deleteFollowSet(prev).catch(() => {});
    }
  }
  // "Save feed" on someone's timeline: into the chips at once. The editor
  // would have copied their whole follow list in, one row per person.
  function saveTimelineFeed(adhoc) {
    const s = st();
    const have = s.feeds.find((f) => f.of === adhoc.of && JSON.stringify(f.relays || []) === JSON.stringify(adhoc.relays || []));
    const id = have ? have.id : 'f' + Date.now().toString(36) + Math.random().toString(36).slice(2, 6);
    if (!have) {
      s.feeds.push({ id, name: '', follows: false, authors: [], packs: [], topics: [], of: adhoc.of,
        ...(adhoc.relays && adhoc.relays.length ? { relays: adhoc.relays } : {}), at: Date.now() });
      save(s);
      feedsChanged();
    }
    adhocFeeds.delete(adhoc.id);
    feedStates.delete(adhoc.id);
    switchFeed(id);
    toast(t('feedSaved'));
  }
  function deleteFeed(id) {
    const s = st();
    const def = s.feeds.find((f) => f.id === id);
    s.feeds = s.feeds.filter((f) => f.id !== id);
    const gone = Object.entries(s.feedsGone || {}).sort((a, b) => b[1] - a[1]).slice(0, 199);
    s.feedsGone = Object.fromEntries([[id, Date.now()], ...gone]);
    save(s);
    feedsChanged();
    if (def && def.d) deleteFollowSet(def).catch(() => {}); // after ours: it re-reads the state
    dropFeedState(id);
    try { wallet.saveFeatureState(feedCacheKey(id), []); } catch {}
    ui.feedEdit = null;
    if (curFeedId === id) switchFeed(FOLLOWING); else render();
  }
  // Packs by title, NIP-50 search on a relay that indexes them; a pasted
  // link or naddr is looked up directly.
  let packSearchSeq = 0;
  async function searchPacks(q) {
    const e = ui.feedEdit;
    const seq = ++packSearchSeq;
    q = String(q || '').trim();
    if (!e || q.length < 2) { if (e) e.packRows = null; render(); return; }
    const link = parsePackLink(q) || await resolveShortPackLink(q);
    if (seq !== packSearchSeq) return;
    let rows = [];
    if (link) {
      const got = await fetchPack(link).catch(() => null);
      rows = got ? [{ ...link, title: got.title, n: got.pks.length }] : [];
    } else {
      const words = q.toLowerCase().split(/\s+/).filter(Boolean);
      const index = await loadPackIndex().catch(() => []);
      const hits = index.filter((p) => { const hay = (p.title + ' ' + p.desc).toLowerCase(); return words.every((w) => hay.includes(w)); })
        .sort((a, b) => b.pks.length - a.pks.length).slice(0, 12);
      for (const p of hits) {
        packsNow()[packKey(p)] ||= { pks: p.pks, title: p.title, at: p.at };
        rows.push({ pk: p.pk, d: p.d, relays: [], title: p.title, n: p.pks.length });
      }
      if (hits.length) { try { wallet.saveFeatureState(PACK_CACHE, packsNow()); } catch {} }
    }
    if (seq !== packSearchSeq || !ui.feedEdit) return;
    ui.feedEdit.packRows = rows;
    render();
  }
  function feedEditView() {
    const e = ui.feedEdit;
    const packRow = (p, onTap, extra) => h('div', { class: 'row gap6', style: 'align-items:center' + (onTap ? ';cursor:pointer' : ''), onClick: onTap },
      h('div', { class: 'chat-avatar fallback mini' }, '\u2605'),
      h('div', { class: 'col grow', style: 'min-width:0' },
        h('span', { style: 'overflow:hidden;text-overflow:ellipsis;white-space:nowrap' }, (packOf(p) || {}).title || p.title || t('feedPackUntitled')),
        h('span', { class: 'small muted' }, t('feedPackMembers', { n: (packOf(p) || {}).pks?.length ?? p.n ?? 0 }))),
      extra || null);
    const person = (pk) => h('div', { class: 'row gap6', style: 'align-items:center' },
      avatar(pk, 'chat-avatar mini', false),
      h('span', { class: 'grow', style: 'min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap' }, displayName(pk)),
      h('button', { class: 'btn-sm', type: 'button', 'aria-label': t('remove'), onClick: () => { e.authors = e.authors.filter((x) => x !== pk); render(); } }, '\u00d7'));
    const picks = (e.rows || []).filter((r) => r.pk && !e.authors.includes(r.pk)).slice(0, 8);
    return h('div', { class: 'card col chat-page', style: 'gap:14px' },
      h('div', { class: 'row gap6', style: 'align-items:center' },
        backBtn(() => { ui.feedEdit = null; render(); }),
        h('h3', { style: 'margin:0' }, e.isNew ? t('feedNew') : t('feedEdit'))),
      h('label', { class: 'col', style: 'gap:4px' },
        h('span', { class: 'small muted' }, t('feedName')),
        h('input', { type: 'text', value: e.name, placeholder: t('feedNameHint'), maxlength: '40', onInput: (ev) => { e.name = ev.target.value; } })),
      // where the feed reads, and whether it takes everything there
      h('div', { class: 'col', style: 'gap:6px' },
        h('span', { class: 'small muted' }, t('feedRelays')),
        h('input', { type: 'text', class: 'feed-relays-input', value: e.relays || '', placeholder: 'nos.lol relay.damus.io',
          autocapitalize: 'none', autocomplete: 'off', spellcheck: 'false', onInput: (ev) => { e.relays = ev.target.value; } }),
        h('div', { class: 'small faint' }, t('feedRelaysFormHelp')),
        h('label', { class: 'row gap6', style: 'align-items:center;cursor:pointer' },
          h('input', { type: 'checkbox', class: 'feed-all-toggle', checked: !!e.all, style: 'width:18px;height:18px;accent-color:var(--accent);margin:0', onChange: (ev) => { e.all = ev.target.checked; render(); } }),
          h('span', {}, t('feedAllToggle'))),
        e.all ? h('label', { class: 'row gap6', style: 'align-items:center;cursor:pointer;margin-left:26px' },
          h('input', { type: 'checkbox', checked: !!e.curated, style: 'width:18px;height:18px;accent-color:var(--accent);margin:0', onChange: (ev) => { e.curated = ev.target.checked; } }),
          h('span', { class: 'small' }, t('feedAllCurated'))) : null),
      e.all ? null : h('div', { class: 'col', style: 'gap:8px' },
        h('span', { class: 'small muted' }, t('feedPeople')),
        h('label', { class: 'row gap6', style: 'align-items:center;cursor:pointer' },
          h('input', { type: 'checkbox', checked: e.follows, style: 'width:18px;height:18px;accent-color:var(--accent);margin:0', onChange: (ev) => { e.follows = ev.target.checked; render(); } }),
          h('span', {}, t('feedFollowsToggle'))),
        h('label', { class: 'row gap6', style: 'align-items:center;cursor:pointer' },
          h('input', { type: 'checkbox', class: 'feed-lists-toggle', checked: !!e.lists, style: 'width:18px;height:18px;accent-color:var(--accent);margin:0', onChange: (ev) => { e.lists = ev.target.checked; } }),
          h('span', {}, t('feedListsToggle'))),
        ...e.authors.map(person),
        // a list's private members, kept where they were made
        ...(e.priv || []).map((pk) => h('div', { class: 'row gap6', style: 'align-items:center', title: t('feedPrivateMember') },
          avatar(pk, 'chat-avatar mini', false),
          h('span', { class: 'grow', style: 'min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap' }, displayName(pk)),
          h('span', { class: 'faint', 'aria-label': t('feedPrivateMember') }, '\u{1F512}'))),
        h('input', {
          type: 'text', class: 'user-search-input', placeholder: t('feedAddPerson'), value: e.q,
          autocapitalize: 'none', autocomplete: 'off', spellcheck: 'false',
          onInput: (ev) => { e.q = ev.target.value; feedPeopleSearcher.update(e.q); },
        }),
        picks.length
          ? h('div', { class: 'list' }, resultRows(h, picks, (r) => {
              if (!r.pk) return;
              e.authors.push(r.pk); e.q = ''; e.rows = null; render();
            }, (pk, node) => hook('wrapAvatar', pk, node)))
          : null),
      e.all ? null : h('div', { class: 'col', style: 'gap:8px' },
        h('span', { class: 'small muted' }, t('feedPacks')),
        ...e.packs.map((p) => packRow(p, null,
          h('button', { class: 'btn-sm', type: 'button', 'aria-label': t('remove'), onClick: () => { e.packs = e.packs.filter((x) => packKey(x) !== packKey(p)); render(); } }, '\u00d7'))),
        h('input', {
          type: 'text', class: 'user-search-input', placeholder: t('feedAddPack'), value: e.pq,
          autocapitalize: 'none', autocomplete: 'off', spellcheck: 'false',
          onInput: (ev) => { e.pq = ev.target.value; clearTimeout(e.pt); e.pt = setTimeout(() => searchPacks(e.pq), 350); },
        }),
        h('div', { class: 'small faint' }, t('feedPacksHelp')),
        ...(e.packRows || []).filter((r) => !e.packs.some((x) => packKey(x) === packKey(r))).map((r) => packRow(r, () => {
          e.packs.push({ pk: r.pk, d: r.d, relays: r.relays || [], title: r.title || '', ...(r.kind && r.kind !== PACK_KIND ? { kind: r.kind } : {}) });
          e.pq = ''; e.packRows = null; render();
        })),
        e.packRows && !e.packRows.length ? h('div', { class: 'small faint' }, t('searchNoResults')) : null),
      e.all ? null : h('label', { class: 'col', style: 'gap:4px' },
        h('span', { class: 'small muted' }, t('feedTopics')),
        h('input', { type: 'text', value: e.topics, placeholder: t('feedTopicsHint'), autocapitalize: 'none', autocomplete: 'off', onInput: (ev) => { e.topics = ev.target.value; } }),
        h('div', { class: 'small faint' }, t('feedTopicsHelp'))),
      e.all ? null : h('div', { class: 'col', style: 'gap:4px' },
        h('label', { class: 'row gap6', style: 'align-items:center;cursor:pointer' },
          h('input', { type: 'checkbox', class: 'feed-interests-toggle', checked: !!e.interests, style: 'width:18px;height:18px;accent-color:var(--accent);margin:0', onChange: (ev) => { e.interests = ev.target.checked; } }),
          h('span', {}, t('feedInterestsToggle'))),
        h('div', { class: 'small faint' }, t('feedInterestsHelp'))),
      // a feed of people is a nostr list (NIP-51 follow set) unless told not to be
      !e.all && (e.authors.length || (e.priv || []).length || e.d)
        ? h('div', { class: 'col', style: 'gap:4px' },
            h('label', { class: 'row gap6', style: 'align-items:center;cursor:pointer' },
              h('input', { type: 'checkbox', class: 'feed-list-toggle', checked: !!e.publish, style: 'width:18px;height:18px;accent-color:var(--accent);margin:0', onChange: (ev) => { e.publish = ev.target.checked; } }),
              h('span', {}, t('feedShareList'))),
            h('div', { class: 'small faint' }, t('feedShareListHelp')))
        : null,
      h('button', { class: 'btn-primary btn-block', onClick: saveFeedEditor }, t('save')),
      e.id && !e.isNew ? h('button', { class: 'btn-ghost btn-block', onClick: () => deleteFeed(e.id) }, t('feedDelete')) : null);
  }

  // ---- 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', { class: 'user-search-main', style: 'margin:0' }, t('searchUsers')),
        h('input', {
          type: 'text', class: 'user-search-input user-search-main', placeholder: t('searchUsersHint'), value: s.q,
          autocapitalize: 'none', autocomplete: 'off', spellcheck: 'false',
          onInput: (e) => { s.q = e.target.value; userSearcher.update(s.q); },
        }),
        // a word is a topic too: posts tagged with it, as a feed
        (() => {
          const m = /^#?([A-Za-z0-9_\u00C0-\uFFFF]{2,64})$/.exec(s.q.trim());
          if (!m) return null;
          const tag = normTopic(m[1]);
          return h('div', { class: 'list' }, h('div', { class: 'item chat-thread-row', onClick: () => openTopicFeed(tag) },
            h('div', { class: 'chat-avatar fallback' }, '#'),
            h('div', { class: 'col grow', style: 'min-width:0;gap:1px' },
              h('span', { class: 'chat-name' }, '#' + tag),
              h('div', { class: 'muted small' }, t('searchTopicRow')))));
        })(),
        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(room.chEpoch(chId))], 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 = () => {
    // Mobile keyboards can resize only the visual viewport, leaving dvh
    // unchanged. Size the conversation to the space above the keyboard.
    const viewport = window.visualViewport;
    const height = viewport && viewport.scale === 1 ? viewport.height : window.innerHeight;
    document.documentElement.style.setProperty('--chat-viewport-height', `${height}px`);
    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')));
  }

  // Amber by intent signs, but each decrypt would be a trip through the app,
  // so nothing sent TO the login npub is opened here — a thread shows only
  // what this device sent. Amber also speaks NIP-46; connected that way it
  // decrypts quietly, and the messages held back open.
  function amberDmNotice() {
    if (wallet.watchOnly || !interactiveLogin()) return null;
    return h('div', { class: 'row gap6 chat-signer-off', style: 'align-items:center' },
      h('span', { class: 'small muted grow' }, t('msgAmberDms')),
      h('button', { class: 'btn-sm', onClick: () => hook('nostrSignerUpgrade') }, t('msgAmberConnect')));
  }

  // 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.
  // The box is border-box, so its height carries the border too: sized to
  // scrollHeight alone it came up two pixels short of its own text, and an
  // empty field grew a scrollbar. It scrolls only once it hits the cap.
  const growComposer = (el) => {
    el.style.height = 'auto';
    const border = el.offsetHeight - el.clientHeight;
    const want = el.scrollHeight + border;
    const cap = parseFloat(getComputedStyle(el).maxHeight) || 120;
    el.style.height = Math.min(want, cap) + 'px';
    el.style.overflowY = want > cap ? 'auto' : 'hidden';
  };
  // ---- :shortcode: autocomplete in the composer -----------------------------
  // A colon and two letters at the caret open a strip of matches above the
  // box: custom emoji first (packs held, then ones seen here), a few
  // standard ones after. Tap, Tab or Enter takes the first; Escape closes.
  function updateEmojiAc(el, key) {
    const upto = el.value.slice(0, el.selectionEnd ?? el.value.length);
    const m = EMOJI_PARTIAL_RE.exec(upto);
    const next = m ? { key, q: m[1], start: upto.length - m[1].length - 1, end: upto.length } : null;
    const was = ui.emojiAc;
    ui.emojiAc = next;
    if (!!was !== !!next || (was && next && (was.q !== next.q || was.key !== next.key))) render();
  }
  function emojiAcHits(q) {
    const ql = q.toLowerCase();
    const custom = customEmojis().filter((x) => x.code.toLowerCase().includes(ql))
      .sort((a, b) => Number(b.code.toLowerCase().startsWith(ql)) - Number(a.code.toLowerCase().startsWith(ql)));
    const std = EMOJI_LIB.filter((x) => x.k.split(' ').some((w) => w.startsWith(ql)));
    return [...custom.slice(0, 8), ...std.slice(0, 4)].slice(0, 8);
  }
  function pickEmojiAc(hit) {
    const ac = ui.emojiAc;
    ui.emojiAc = null;
    const el = document.getElementById('msg-draft');
    if (!ac || !el) { render(); return; }
    const ins = hit.url ? ':' + hit.code + ': ' : hit.e + ' ';
    const v = el.value;
    el.value = v.slice(0, ac.start) + ins + v.slice(ac.end);
    el.selectionStart = el.selectionEnd = ac.start + ins.length;
    setDraft(ac.key, el.value);
    growComposer(el);
    if (hit.url) noteRecent(':' + hit.code + ':');
    render();
    el.focus();
  }
  // Always a node, empty when idle: the strip appearing must not shift the
  // composer's children, or the morph rebuilds the textarea under a
  // typing finger and the keystroke that opened it lands nowhere.
  function emojiAcStrip(draftKey) {
    const ac = ui.emojiAc;
    const hits = ac && ac.key === draftKey ? emojiAcHits(ac.q) : [];
    return h('div', { class: 'emoji-ac' },
      hits.map((x) => h('button', {
        type: 'button', title: x.url ? ':' + x.code + ':' : x.k,
        onMousedown: (e) => e.preventDefault(), // the box keeps focus and its caret
        onClick: () => pickEmojiAc(x),
      }, x.url ? emojiImg(x.code, x.url) : x.e, x.url ? h('span', { class: 'small' }, x.code) : null)));
  }

  // ---- @mentions in posts and replies -----------------------------------------
  // "@" and a few letters at the caret open a list of people under the box:
  // the people you follow whose name matches first (instantly, from what's
  // here), then the same search the header uses. Picking one puts a
  // nostr:npub… in the text (NIP-27; every client shows it as @name) and the
  // post goes out with their p tag, so they're told. Tab or Enter takes the
  // first; Escape closes.
  const MENTION_RE = /(?:^|\s)@([\p{L}\p{N}._-]{0,30})$/u;
  let mentionRows = [];
  const mentionSearcher = makeSearcher((q, rows) => {
    if (!ui.mentionAc || ui.mentionAc.q !== q) return;
    mentionRows = rows || [];
    render();
  });
  function updateMentionAc(el, sel) {
    const upto = el.value.slice(0, el.selectionEnd ?? el.value.length);
    const m = MENTION_RE.exec(upto);
    const next = m ? { sel, q: m[1], start: upto.length - m[1].length - 1, end: upto.length } : null;
    const was = ui.mentionAc;
    ui.mentionAc = next;
    if (next && (!was || was.q !== next.q)) {
      mentionRows = (was && next.q.startsWith(was.q)) ? mentionRows : [];
      if (next.q.length >= 2) mentionSearcher.update(next.q); else mentionSearcher.clear(false);
    }
    if (!next) mentionSearcher.clear(false);
    if (!!was !== !!next || (was && next && (was.q !== next.q || was.sel !== next.sel))) render();
  }
  function mentionHits(q) {
    const ql = q.toLowerCase();
    const mine = [...followsNow().set]
      .filter((pk) => !hiddenPk(pk))
      .map((pk) => ({ pk, name: displayName(pk) }))
      .filter((r) => !ql || r.name.toLowerCase().includes(ql))
      .sort((a, b) => Number(b.name.toLowerCase().startsWith(ql)) - Number(a.name.toLowerCase().startsWith(ql)))
      .slice(0, ql ? 4 : 6)
      .map((r) => { const p = profiles.get(r.pk) || {}; return { pk: r.pk, name: r.name, picture: p.picture || null, known: true }; });
    const seen = new Set(mine.map((r) => r.pk));
    return [...mine, ...mentionRows.filter((r) => !seen.has(r.pk) && !hiddenPk(r.pk))].slice(0, 8);
  }
  function pickMention(r) {
    const ac = ui.mentionAc;
    ui.mentionAc = null;
    mentionSearcher.clear(false);
    const el = ac && document.querySelector(ac.sel);
    if (!el) { render(); return; }
    el.focus();
    el.setSelectionRange(ac.start, ac.end);
    // as the editor would type it: undo history intact, and the box's own
    // input handler stores the draft
    const ins = 'nostr:' + npubOf(r.pk) + ' ';
    if (typeof el._insert === 'function') el._insert(ins);
    else { const v = el.value; el.value = v.slice(0, ac.start) + ins + v.slice(ac.end); el.dispatchEvent(new Event('input', { bubbles: true })); }
    render();
  }
  // Keys while the list is open: Tab / Enter take the first, Escape closes.
  function mentionKey(e) {
    const ac = ui.mentionAc;
    if (!ac) return;
    if (e.key === 'Escape') { ui.mentionAc = null; render(); e.preventDefault(); return; }
    if (e.key !== 'Tab' && e.key !== 'Enter') return;
    const first = mentionHits(ac.q)[0];
    if (!first) return;
    e.preventDefault();
    e.stopPropagation();
    pickMention(first);
  }
  // Always a node, empty when idle (the morph must not rebuild the box
  // under a typing finger when the list appears).
  function mentionList(sel) {
    const ac = ui.mentionAc;
    const hits = ac && ac.sel === sel ? mentionHits(ac.q) : [];
    return h('div', { class: 'mention-ac', onMousedown: (e) => e.preventDefault() }, // the box keeps focus and caret
      ...(hits.length ? resultRows(h, hits, pickMention, (pk, ava) => ava) : []));
  }
  // The people a text mentions (nostr:npub / nprofile), for its p tags.
  const mentionedPks = (text) => [...new Set([...String(text || '').matchAll(/nostr:((?:npub|nprofile)1[a-z0-9]+)/gi)]
    .map((m) => parseNostrRef(m[1].toLowerCase())).filter((r) => r && r.type === 'pubkey').map((r) => r.pk))];

  const composer = (placeholder, onSend, onType, draftKey, onAttach = null) => {
    syncEmoji().catch(() => {}); // throttled inside: your packs, from wherever you added them
    return h('div', { class: 'col', style: 'gap:6px' },
      signerNotice(),
      emojiAcStrip(draftKey),
    h('div', { class: 'chat-compose' },
      onAttach ? h('input', {
        type: 'file', id: 'msg-file', accept: 'image/*,video/*', style: 'display:none',
        onChange: (e) => { const f = e.target.files && e.target.files[0]; e.target.value = ''; if (f) onAttach(f); },
      }) : null,
      // attach + GIF sit inside the field, as in the post composer
      h('div', { class: 'compose-box chat-box' },
        h('coinos-text', {
          class: 'grow', id: 'msg-draft', placeholder,
          value: draftFor(draftKey),
          onMedia: onAttach ? (f) => onAttach(f) : null,
          onInput: (e) => { setDraft(draftKey, e.target.value); growComposer(e.target); updateEmojiAc(e.target, draftKey); if (onType && e.target.value) onType(); },
          onClick: (e) => updateEmojiAc(e.target, draftKey), // the caret moved
          onBlur: () => { if (ui.emojiAc) { ui.emojiAc = null; render(); } },
          onKeydown: (e) => {
            const ac = ui.emojiAc && ui.emojiAc.key === draftKey ? ui.emojiAc : null;
            if (ac && (e.key === 'Tab' || e.key === 'Enter') && !e.shiftKey) {
              const hits = emojiAcHits(ac.q);
              if (hits.length) { e.preventDefault(); pickEmojiAc(hits[0]); return; }
            }
            if (ac && e.key === 'Escape') { e.preventDefault(); ui.emojiAc = null; render(); return; }
            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('div', { class: 'compose-tools' },
          onAttach ? h('button', {
            type: 'button', class: 'compose-tool chat-clip', title: t('msgAttach'), 'aria-label': t('msgAttach'),
            disabled: !!ui.msgUploading,
            onClick: () => document.getElementById('msg-file')?.click(),
          }, ui.msgUploading ? h('span', { class: 'spinner sm' }) : h('span', { style: 'display:flex', html: CLIP })) : null,
          gifs.button('chat:' + draftKey, 'compose-tool gif-btn chat-gif'))),
      h('button', { class: 'btn-primary btn-sm', onClick: onSend }, t('msgSend'))),
    // a picked GIF goes out at once, after whatever was typed
    gifs.sheet('chat:' + draftKey, (g) => {
      const cur = draftFor(draftKey).replace(/\s+$/, '');
      const next = (cur ? cur + ' ' : '') + g.url;
      setDraft(draftKey, next);
      const el = document.getElementById('msg-draft');
      if (el) el.value = next;
      onSend();
    }));
  };

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

  function homeView() {
    if (myPubkeys().length) syncFollowSets().catch(() => {}); // lists made elsewhere join the feeds (throttled inside)
    // The feed is a tap away from here: have it warmed and asked for before
    // the tap, so it opens on the latest posts rather than a spinner.
    if (myPubkeys().length) { try { const c = feedNow(); if (!c.booting) refreshFeed({}, c); } catch {} }
    syncReports().catch(() => {}); // your follows' flags (throttled inside)
    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(() => {});
    if (Date.now() - listsSyncedAt > 60_000) syncLists({ force: true }).catch(() => {});
    for (const jm of communities()) ensureRoom(jm);

    // Cordn groups the same way: a KeyPackage on the coordinator is what
    // makes us invitable there (a seed wallet signs it unasked; a signer
    // login is asked when it first opens a Cordn group or invites someone).
    if (ui.msgView !== 'grp' && cd) cd.focus(null);
    cordnChat().then((c) => { if (c && !cdReadied) { cdReadied = true; c.ready(); } });
    // Group chats ride along: the client loads with the wallet, and standing
    // on this screen is what makes us invitable (a KeyPackage on the relays).
    whiteNoise().then(async (c) => {
      // a profile renamed since boot should reach White Noise's relays too (throttled inside)
      if (c && wnReadied) c.announce();
      if (!c || wnReadied) return;
      wnReadied = true;
      await c.load();
      // A login signer has to sign the device's proof once, and may ask its
      // owner. Unprompted, that question is put at most once a week.
      if (!c.isSetUp() && hook('nostrLoginIdentity')) {
        const s = st();
        if (Date.now() - (s.wnAsked || 0) < 7 * 86400_000) return;
        s.wnAsked = Date.now();
        save(s);
      }
      c.ready().catch(() => {});
    }).catch(() => {});
    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 && !isMuted(x.peer))
      .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)));
      for (const g of wnGroups()) newest = Math.max(newest, wnNewest(g));
      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);
    const amberRow = amberDmNotice();
    if (amberRow) kids.push(amberRow);

    if (pendingLink && pendingLink.where !== 'communities') kids.push(linkInviteCard());
    for (const [rid, inv] of pendingDirect) kids.push(directInviteCard(rid, inv));
    for (const g of wnGroups()) if (g.fresh && !g.removed) kids.push(wnInviteCard(g));

    // 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()));

    // ---- DMs
    kids.push(h('div', { class: 'row between', style: 'align-items:baseline' },
      h('h3', { style: 'margin:0' }, t('msgDmsTitle')),
      h('div', { class: 'row gap6' },
        h('button', { class: 'btn-sm', onClick: () => { dmSearcher.clear(); ui.msgHomePanel = ui.msgHomePanel === 'newgroup' ? null : 'newgroup'; if (ui.msgHomePanel === 'newgroup') warmSearch(); render(); } }, t('msgNewGroup')),
        h('button', { class: 'btn-sm', onClick: () => { dmSearcher.clear(); ui.msgHomePanel = ui.msgHomePanel === 'newdm' ? null : 'newdm'; if (ui.msgHomePanel === 'newdm') warmSearch(); render(); } }, t('msgNewDm')))));
    if (ui.msgHomePanel === 'newgroup') kids.push(wnNewGroupPanel());
    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 four,
    // the rest waits behind "show all". Communities get the same cap.
    const LIST_PREVIEW = 4;
    // one list, newest first: a group chat is a conversation like any other
    const chatRows = [
      ...dmRows.map((x) => ({ at: x.last.rumor.created_at, dm: x })),
      ...wnGroups().filter((g) => !g.fresh).map((g) => ({ at: (wnFold(g).rows.at(-1) || {}).rumor?.created_at || g.at, g })),
    ].sort((a, b) => b.at - a.at);
    const shownDms = ui.msgAllDms ? chatRows : chatRows.slice(0, LIST_PREVIEW);
    kids.push(
      chatRows.length
        ? h('div', { class: 'list' }, shownDms.map((row) => row.g ? wnGroupRow(row.g) : (({ peer, last, unread }) =>
            h('div', {
              class: 'item chat-thread-row' + (unread ? ' unread' : ''),
              // keyed: a new message re-sorts the list, and the row moves
              // with its person instead of being repainted as someone else
              'data-key': 'dm:' + peer,
              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))),
              h('div', { class: 'muted small chat-preview' }, (last.mine ? t('msgYouPrefix') + ' ' : '') + (last.rumor.kind === 15 || (!last.rumor.content && last.wn) ? '📎 ' + t('msgPhoto') : last.rumor.content))),
            // the row's own dot, centred and inset like the communities' below
            unread ? h('i', { class: 'thread-dot' }) : null))(row.dm)))
        : h('div', { class: 'muted small' }, t('msgNoDms')));
    if (shownDms.length < chatRows.length)
      kids.push(h('button', { class: 'linklike small', onClick: () => { ui.msgAllDms = true; render(); } },
        t('msgShowAllDms', { n: chatRows.length })));
    else if (ui.msgAllDms && chatRows.length > LIST_PREVIEW)
      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 (pendingLink && pendingLink.where === 'communities') kids.push(linkInviteCard());
    if (ui.msgHomePanel === 'join') {
      const isLink = !!parseInviteLink(ui.msgJoinText || '');
      kids.push(h('div', { class: 'col', style: 'gap:8px' },
        h('div', { class: 'row gap6' },
          h('input', {
            class: 'grow', type: 'text', placeholder: t('msgInvitePlaceholder'),
            value: ui.msgJoinText || '', onInput: (e) => { ui.msgJoinText = e.target.value; render(); },
            onKeydown: (e) => { if (e.key === 'Enter' && isLink) joinFromText(ui.msgJoinText); },
          }),
          isLink ? h('button', { class: 'btn-sm btn-primary', onClick: () => joinFromText(ui.msgJoinText) }, t('msgJoin')) : null),
        isLink ? null : hubPanel()));
    }
    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'))));
    const allRooms = communities();
    const shownRooms = ui.msgAllRooms ? allRooms : allRooms.slice(0, LIST_PREVIEW);
    // the rooms on the list get their faces while it sits there, so even a
    // tap with no hover before it finds them ready
    setTimeout(() => { for (const jm of shownRooms) if (rooms.has(jm.community_id)) warmRoom(jm); }, 300);
    kids.push(h('div', { class: 'list' }, shownRooms.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' : ''),
        onMouseenter: () => warmRoom(jm),
        onPointerdown: () => warmRoom(jm),
        onClick: () => openRoomWarm(jm, () => { ui.msgView = 'room'; ui.msgCommunity = jm.community_id; ui.msgChannel = null; ui.msgStick = true; }),
      },
      communityAvatar(jm, room, name),
      h('div', { class: 'col grow', style: 'min-width:0;gap:1px' },
        h('span', { class: 'chat-name' }, name),
        h('div', { class: 'muted small' },
          memberCount ? t('msgMembers', { n: memberCount }) : t('msgEncrypted'))),
      // the row's own centring puts the dot mid-height, off the edge
      unread ? h('i', { class: 'thread-dot' }) : null);
    })));
    if (shownRooms.length < allRooms.length)
      kids.push(h('button', { class: 'linklike small', onClick: () => { ui.msgAllRooms = true; render(); } },
        t('msgShowAllCommunities', { n: allRooms.length })));
    else if (ui.msgAllRooms && allRooms.length > LIST_PREVIEW)
      kids.push(h('button', { class: 'linklike small', onClick: () => { ui.msgAllRooms = false; render(); } },
        t('msgShowFewerDms')));

    if (ui.msgHomePanel !== 'join') kids.push(hubPanel({ preview: true }));

    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 ---------------------------------------------------------------

  // ---- a room's faces, before it opens -------------------------------------
  // Opening a community painted everyone as a punk for a beat: their
  // profiles weren't in memory yet. As SvelteKit preloads on hover, a
  // pointer over (or pressing) a room's row starts the faces of its latest
  // messages — profile, then the picture decoded — and the tap waits for
  // them, a moment at most, before the room replaces the list.
  const ROOM_READY_MS = 1500;
  const roomWarm = new Map(); // cid -> { at, promise }
  let roomOpenSeq = 0;
  function roomFaces(jm) {
    const room = ensureRoom(jm);
    const ch = roomChannels(room)[0];
    if (!ch) return [];
    // everyone the channel paints, newest speakers first
    const msgs = [...(room.byChannel.get(ch.id)?.values() || [])]
      .sort((a, b) => eventMs(b.rumor) - eventMs(a.rumor));
    return [...new Set(msgs.map((m) => m.author))].slice(0, 150);
  }
  // A community's face. Vector puts the logo in the vsk-0 metadata as an
  // AES-256-GCM blob ({ url, key, nonce, hash }, 16-byte nonce, tag
  // appended); a plain URL is taken as is. Decrypted once per session.
  // The built-in coinos community wears the coinos logo.
  const roomIcons = new Map();
  function communityIcon(jm, room) {
    const ic = room?.folded?.metadata?.icon;
    if (typeof ic === 'string' && /^(https:|data:image\/)/.test(ic)) return ic;
    if (ic && typeof ic === 'object' && /^https:/.test(ic.url || '')) {
      const k = ic.url + '#' + ic.key;
      if (!roomIcons.has(k)) {
        roomIcons.set(k, null);
        (async () => {
          const key = hexToBytes(ic.key), iv = hexToBytes(ic.nonce);
          if (key.length !== 32 || iv.length !== 16) return;
          const res = await fetch(ic.url, { signal: AbortSignal.timeout(20_000) });
          if (!res.ok || Number(res.headers.get('content-length') || 0) > 10e6) return;
          const ct = await res.arrayBuffer();
          if (ct.byteLength > 10e6) return;
          const ck = await crypto.subtle.importKey('raw', key, { name: 'AES-GCM' }, false, ['decrypt']);
          const plain = new Uint8Array(await crypto.subtle.decrypt({ name: 'AES-GCM', iv }, ck, ct));
          if (ic.hash && bytesToHex(new Uint8Array(await crypto.subtle.digest('SHA-256', plain))) !== String(ic.hash).toLowerCase()) return;
          roomIcons.set(k, URL.createObjectURL(new Blob([plain])));
          scheduleRepaint();
        })().catch(() => {});
      }
      if (roomIcons.get(k)) return roomIcons.get(k);
    }
    return jm.community_id === COMMUNITY.community_id ? assetUrl('icon-192.png') : null;
  }
  const communityAvatar = (jm, room, name, cls = '') => {
    const src = communityIcon(jm, room);
    return src
      ? h('img', { class: 'chat-avatar hub-icon' + cls, src, alt: '' })
      : h('div', { class: 'chat-avatar fallback' + cls }, name.slice(0, 2));
  };
  // Each face is warmed once per half minute; a later call (the history
  // still streaming in when the list first warmed) adds whoever is new.
  function warmRoom(jm) {
    let w = roomWarm.get(jm.community_id);
    if (!w || Date.now() - w.at > 30_000) { w = { at: Date.now(), faces: new Map() }; roomWarm.set(jm.community_id, w); }
    const deadline = Date.now() + 8000;
    try {
      for (const pk of roomFaces(jm)) if (!w.faces.has(pk)) w.faces.set(pk, warmAvatar(pk, deadline).catch(() => {}));
    } catch {}
    return Promise.all(w.faces.values());
  }
  async function openRoomWarm(jm, go) {
    const seq = ++roomOpenSeq;
    const from = ui.msgView;
    await Promise.race([warmRoom(jm), new Promise((r) => setTimeout(r, ROOM_READY_MS))]);
    // another tap, or the reader went elsewhere, while the faces loaded
    if (seq !== roomOpenSeq || ui.msgView !== from || !ui.chatOpen) return;
    go();
    render();
  }

  const chatBubbleClick = (open) => (e) => {
    if (e.target.closest && e.target.closest('a, button, img:not(.cemoji)')) return;
    const sel = window.getSelection && window.getSelection();
    if (sel && String(sel).length) return;
    open();
  };

  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)))
      .filter((m) => !hiddenPk(m.author)) // muted here, or a spammer
      .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);
      // the message's own custom emoji (an edit brings its own set)
      const em = emojiTagMap((edit && edit.author === m.author ? edit.rumor : m.rumor).tags);
      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-line' }, h('div', {
            class: 'chat-bubble clickable' + (emojiJumbo(text, em) ? ' jumbo' : ''),
            // 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.
            // A custom emoji is an <img> too, but tapping it should open the
            // sheet like tapping any other word.
            onClick: chatBubbleClick(() => {
              ui.msgSheet = ui.msgSheet === m.rumor.id ? null : m.rumor.id;
              render();
            }),
          },
            replyQuote(room, chId, m),
            ...noteBody(text, 0, em),
            ...attachmentNodes(m.rumor),
            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); },
                    }, reactNode(emoji), n > 1 ? ' ' + n : '')))
              : null)(zapChip(m.rumor.id, { cls: 'chat-react', onClick: canZapPk(m.author) ? () => zapMessage(m.author, m.rumor.id) : null, onHold: () => openZapSettings(m.author, m.rumor.id) }))),
            msgZapBtn(m.author, m.rumor.id)))
      );
    });
  }

  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(); }),
          communityAvatar(jm, room, name, ' header-ava'),
          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>',
          }),
          // a person with a plus, like the bell and the door beside it: the
          // words wrapped onto two lines in a narrow header
          h('button', {
            class: 'btn-sm' + (ui.msgInvitePanel ? ' on' : ''), title: t('msgInviteTitle'), 'aria-label': t('msgAddPerson'),
            onClick: () => { ui.msgInvitePanel = !ui.msgInvitePanel; render(); },
            html: I_ADD_PERSON,
          }),
          // the door out — in the header where anyone looks for it, not in
          // the invite panel; one tap arms it, the second leaves
          jm.community_id === COMMUNITY.community_id ? null : h('button', {
            class: 'btn-sm' + (ui.msgLeaveArm ? ' btn-danger' : ''), title: t('msgLeave'), 'aria-label': t('msgLeave'),
            onClick: () => { if (ui.msgLeaveArm) leaveCommunity(room); else { ui.msgLeaveArm = true; render(); } },
            html: ui.msgLeaveArm ? null : '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/><path d="M16 17l5-5-5-5"/><path d="M21 12H9"/></svg>',
          }, ui.msgLeaveArm ? t('msgLeaveConfirmShort') : null))),
      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 ? (f) => sendAttachment(room, ch.id, f) : null),
      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
      null);
  }

  // ---- group chats (White Noise) --------------------------------------------

  function wnGroupRow(g) {
    const wn = gClient(g);
    const name = wnTitle(g);
    const last = wnChat(g).at(-1);
    const unread = wnUnread(g);
    for (const pk of wn.accounts(g).slice(0, 12)) profileOf(pk);
    return h('div', {
      class: 'item chat-thread-row' + (unread ? ' unread' : ''),
      'data-key': 'grp:' + g.id,
      onClick: () => { ui.msgView = 'grp'; ui.msgPeer = g.id; ui.msgStick = true; ui.msgMembers = false; 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),
        last ? h('span', { class: 'chat-time thread-when' }, timeLabel(last.rumor.created_at * 1000)) : null),
      h('div', { class: 'muted small chat-preview' },
        g.removed ? t('msgGroupGone')
          : last ? (last.mine ? t('msgYouPrefix') : displayName(last.rumor.pubkey) + ':') + ' ' + (last.rumor.content || '📎 ' + t('msgGroupAttachment'))
          : t('msgMembers', { n: wn.accounts(g).length }))),
    unread ? h('i', { class: 'thread-dot' }) : null);
  }

  function wnInviteCard(g) {
    const wn = gClient(g);
    return h('div', { class: 'notice info col', style: 'gap:8px' },
      h('div', {}, t('msgGroupInvite', { name: displayName(g.inviter), group: wnTitle(g) })),
      h('div', { class: 'row gap6' },
        h('button', {
          class: 'btn-primary btn-sm',
          onClick: () => { wn.accept(g); ui.msgView = 'grp'; ui.msgPeer = g.id; ui.msgStick = true; render(); },
        }, t('msgJoin')),
        h('button', {
          class: 'btn-ghost btn-sm', disabled: ui.msgBusy,
          onClick: () => wnAct(() => wn.leave(g)),
        }, t('msgGroupDecline'))));
  }

  // Search, tap, and the person becomes a chip that says whether they can be
  // reached. Shared by New group and a group's Add person.
  function wnPeoplePicker(picks, onPick, onDrop, proto = 'wn') {
    const wnReach = reachOf(proto);
    for (const pk of picks) { profileOf(pk); wnCheck(pk, proto); }
    const add = (pk) => { if (!isMe(pk) && !picks.includes(pk)) onPick(pk); dmSearcher.clear(); ui.msgGroupTo = ''; render(); };
    return [
      picks.length ? h('div', { class: 'row gap6', style: 'flex-wrap:wrap' }, picks.map((pk) => {
        const state = wnReach.get(pk);
        return h('span', { class: 'chat-react' + (state === 'no' ? ' muted' : ' on'), title: state === 'no' ? t('msgGroupCantJoin') : '' },
          displayName(pk),
          state === 'checking' ? ' · ' + t('msgGroupChecking') : state === 'no' ? ' · ' + t('msgGroupCantJoin') : '',
          ' ', h('button', { class: 'linklike', 'aria-label': t('msgGroupRemove'), onClick: () => { onDrop(pk); render(); } }, '×'));
      })) : null,
      h('input', {
        type: 'text', placeholder: t('msgGroupPeople'), value: ui.msgGroupTo || '',
        onInput: (e) => { ui.msgGroupTo = e.target.value; dmSearcher.update(e.target.value); },
        onKeydown: (e) => { if (e.key === 'Enter') { const pk = parseNostrPubkey(ui.msgGroupTo); if (pk) add(pk); } },
      }),
      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) => add(r.pk), (pk, node) => hook('wrapAvatar', pk, node)))
          : h('div', { class: 'small muted' }, t('msgNoMatches')),
    ];
  }

  function wnNewGroupPanel() {
    const picks = ui.msgGroupPicks || (ui.msgGroupPicks = []);
    const proto = ui.msgGroupProto || 'wn';
    const ready = picks.length && picks.every((pk) => reachOf(proto).get(pk) === 'ok');
    return h('div', { class: 'col gap6' },
      // which protocol the group speaks: White Noise (Marmot) or Cordn
      h('div', { class: 'seg' },
        h('button', { class: proto === 'wn' ? 'active' : '', onClick: () => { ui.msgGroupProto = 'wn'; render(); } }, t('msgGroupProtoWn')),
        h('button', { class: proto === 'cd' ? 'active' : '', onClick: () => { ui.msgGroupProto = 'cd'; render(); } }, t('msgGroupProtoCd'))),
      proto === 'cd' ? h('div', { class: 'small muted' }, t('msgGroupProtoCdHint')) : null,
      h('input', {
        type: 'text', placeholder: t('msgGroupName'), maxlength: '64',
        value: ui.msgGroupName || '', onInput: (e) => { ui.msgGroupName = e.target.value; },
      }),
      ...wnPeoplePicker(picks, (pk) => picks.push(pk), (pk) => picks.splice(picks.indexOf(pk), 1), proto),
      h('div', { class: 'row' },
        h('button', { class: 'btn-primary btn-sm', disabled: !ready || ui.msgBusy, onClick: wnCreateGroup },
          ui.msgBusy ? h('span', { class: 'spinner sm' }) : t('msgGroupCreate'))));
  }

  function wnMemberPanel(g, admin) {
    const wn = gClient(g);
    const proto = g.cordn ? 'cd' : 'wn';
    const v = wn.view(g);
    const accounts = wn.accounts(g);
    const picks = ui.msgGroupAdd || (ui.msgGroupAdd = []);
    return h('div', { class: 'col chat-members' },
      h('div', { class: 'muted small', style: 'padding:8px 12px 2px' }, t(g.cordn ? 'msgCordnInfo' : 'msgGroupInfo')),
      ...accounts.map((pk) => h('div', { class: 'item chat-thread-row', onClick: () => openProfile(pk) },
        avatar(pk),
        h('div', { class: 'row gap6 grow', style: 'align-items:center;min-width:0' },
          h('span', { class: 'chat-name' }, displayName(pk)),
          v.admins.includes(pk) ? h('span', { class: 'chat-badge' }, t('msgAdmin')) : null),
        admin && !isMe(pk)
          ? h('button', {
              class: 'btn-ghost btn-sm', disabled: ui.msgBusy,
              onClick: (e) => { e.stopPropagation(); wnAct(() => wn.kick(g, pk)); },
            }, t('msgGroupRemove'))
          : null)),
      admin ? h('div', { class: 'col gap6 chat-invite' },
        ...wnPeoplePicker(picks, (pk) => picks.push(pk), (pk) => picks.splice(picks.indexOf(pk), 1), proto),
        picks.length ? h('div', { class: 'row' }, h('button', {
          class: 'btn-primary btn-sm', disabled: ui.msgBusy || !picks.every((pk) => reachOf(proto).get(pk) === 'ok'),
          onClick: () => wnAct(async () => { await wn.add(g, [...picks]); ui.msgGroupAdd = []; }),
        }, ui.msgBusy ? h('span', { class: 'spinner sm' }) : t('msgAddPerson'))) : null,
        h('div', { class: 'row gap6' },
          h('input', {
            class: 'grow', type: 'text', placeholder: t('msgGroupName'), maxlength: '64',
            value: ui.msgGroupNewName ?? v.name, onInput: (e) => { ui.msgGroupNewName = e.target.value; },
          }),
          h('button', {
            class: 'btn-sm', disabled: ui.msgBusy,
            onClick: () => {
              const name = (ui.msgGroupNewName ?? v.name).trim();
              if (name && name !== v.name) wnAct(async () => { await wn.rename(g, name); ui.msgGroupNewName = null; });
            },
          }, t('msgGroupRename')))) : null);
  }

  function wnSheet(g) {
    const wn = gClient(g);
    const fold = wnFold(g);
    const m = fold.rows.find((x) => x.rumor.id === ui.msgSheet);
    if (!m) { ui.msgSheet = null; return null; }
    const reacts = fold.reacts.get(m.rumor.id);
    const myReact = reacts && myPubkeys().map((pk) => reacts.get(pk)).find(Boolean);
    const close = () => { ui.msgSheet = null; ui.emojiPick = 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' },
        g.removed ? null : reactRow(myReact, (e2) => { close(); sendWnReaction(g, m, e2); }),
        ui.emojiPick || g.removed ? null : item('↩', t('msgReply'), () => {
          ui.msgReplyTo = m.rumor.id;
          close();
          setTimeout(() => document.getElementById('msg-draft')?.focus(), 50);
        }),
        ui.emojiPick ? null : item('⧉', t('copy'), async () => {
          try { await navigator.clipboard.writeText(m.rumor.content); toast(t('copied')); } catch {}
          close();
        }),
        !ui.emojiPick && m.mine && !g.removed ? item('×', t('msgDelete'), async () => {
          close();
          const del = wn.event(5, '', [['e', m.rumor.id], ['k', '9']]);
          if (await wn.send(g, del).catch(() => false)) (g.cordn ? onCd : onWn)('message', g, del);
        }) : null));
  }

  function wnView() {
    const g = findGroup(ui.msgPeer);
    if (!g) {
      // the groups are still loading (a reload straight into this screen)
      if (!wn || wnLoading || !cd || cdLoading) { Promise.all([whiteNoise(), cordnChat()]).then(() => scheduleRepaint()); return h('div', { class: 'card col chat-card chat-page' }, h('span', { class: 'spinner' })); }
      ui.msgView = 'home';
      return homeView();
    }
    const wn = gClient(g);
    // a Cordn group on screen is read from its coordinator every few seconds
    if (cd) cd.focus(g.cordn ? g.id : null);
    const fold = wnFold(g);
    const v = wn.view(g);
    const my = myPubkeys();
    const accounts = wn.accounts(g);
    const admin = wn.isAdmin(g) && !g.removed && !g.leaving;
    const live = !g.removed && !g.leaving;
    for (const pk of accounts) profileOf(pk);
    markRead(wnRead(g.id), wnNewest(g));
    stickToBottom();
    const byId = new Map(fold.rows.map((m) => [m.rumor.id, m]));
    const back = () => { ui.msgView = 'home'; ui.msgReplyTo = null; ui.msgSheet = null; ui.msgMembers = false; ui.msgLeaveArm = false; ui.msgGroupAdd = []; ui.msgGroupNewName = null; dmSearcher.clear(false); render(); };
    let lastAuthor = null, lastT = 0;
    const rows = fold.rows.map((m) => {
      if (m.rumor.kind === 1210) {
        lastAuthor = null;
        return h('div', { class: 'muted small', style: 'text-align:center;padding:6px 0' }, wnSystemText(m.rumor));
      }
      const tms = m.rumor.created_at * 1000;
      const grouped = m.rumor.pubkey === lastAuthor && tms - lastT < 5 * 60_000;
      lastAuthor = m.rumor.pubkey; lastT = tms;
      const em = emojiTagMap(m.rumor.tags);
      const reacts = fold.reacts.get(m.rumor.id);
      const counts = new Map();
      if (reacts) for (const emoji of reacts.values()) counts.set(emoji, (counts.get(emoji) || 0) + 1);
      const myReact = reacts && my.map((pk) => reacts.get(pk)).find(Boolean);
      const replyId = (m.rumor.tags.find((x) => x[0] === 'e') || [])[1];
      const src = replyId && byId.get(replyId);
      const files = attachmentNodes(m.rumor, g.id);
      const body = [
        ...(m.rumor.content ? noteBody(m.rumor.content, 0, em) : []),
        ...files,
        // an attachment in a shape we can't read (another format, a malformed tag)
        ...(!m.rumor.content && !files.length ? [h('span', { class: 'muted' }, '📎 ' + t('msgGroupAttachment'))] : []),
      ];
      return h('div', { class: 'chat-row' + (m.mine ? ' mine' : '') + (grouped ? ' grouped' : '') },
        grouped ? h('div', { class: 'chat-avatar spacer' }) : avatar(m.rumor.pubkey),
        h('div', { class: 'chat-body' },
          grouped ? null : h('div', { class: 'chat-meta' },
            h('span', { class: 'chat-name clickable', onClick: () => openProfile(m.rumor.pubkey) },
              displayName(m.rumor.pubkey),
              v.admins.includes(m.rumor.pubkey) ? h('span', { class: 'chat-badge' }, t('msgAdmin')) : null),
            h('span', { class: 'chat-time' }, timeLabel(tms))),
          h('div', {
            class: 'chat-bubble clickable' + (emojiJumbo(m.rumor.content, em) ? ' jumbo' : ''),
            onClick: chatBubbleClick(() => {
              ui.msgSheet = ui.msgSheet === m.rumor.id ? null : m.rumor.id;
              render();
            }),
          },
            src ? h('div', { class: 'chat-quote' },
              h('span', { class: 'chat-quote-name' }, displayName(src.rumor.pubkey)),
              h('span', { class: 'chat-quote-text' }, ...snippetNodes(src.rumor))) : null,
            ...body,
            m.edited ? h('span', { class: 'chat-edited' }, ' ', t('msgEdited')) : null,
            counts.size ? h('div', { class: 'chat-reacts' },
              [...counts.entries()].map(([emoji, n]) => h('span', {
                class: 'chat-react clickable' + (emoji === myReact ? ' on' : ''),
                onClick: (e) => { e.stopPropagation(); if (live) sendWnReaction(g, m, emoji); },
              }, reactNode(emoji), n > 1 ? ' ' + n : ''))) : null)));
    });
    const reply = ui.msgReplyTo && byId.get(ui.msgReplyTo);
    if (ui.msgReplyTo && !reply) ui.msgReplyTo = null;
    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(back),
          h('div', {
            class: 'col clickable', style: 'gap:2px;min-width:0',
            onClick: () => { ui.msgMembers = !ui.msgMembers; dmSearcher.clear(false); render(); },
          },
            h('div', { class: 'chat-title' }, wnTitle(g)),
            h('div', { class: 'muted small' }, g.removed ? t('msgGroupGone') : t('msgMembers', { n: accounts.length })))),
        h('div', { class: 'row gap6', style: 'align-items:center' },
          admin ? h('button', {
            class: 'btn-sm' + (ui.msgMembers ? ' on' : ''), title: t('msgAddPerson'), 'aria-label': t('msgAddPerson'),
            onClick: () => { ui.msgMembers = !ui.msgMembers; dmSearcher.clear(false); render(); },
            html: I_ADD_PERSON,
          }) : null,
          // the door out: one tap arms it, the second leaves (same as a community)
          h('button', {
            class: 'btn-sm' + (ui.msgLeaveArm ? ' btn-danger' : ''), title: t('msgGroupLeave'), 'aria-label': t('msgGroupLeave'), disabled: ui.msgBusy,
            onClick: () => {
              if (!ui.msgLeaveArm) { ui.msgLeaveArm = true; render(); return; }
              ui.msgLeaveArm = false;
              wnAct(async () => { await wn.leave(g); ui.msgView = 'home'; });
            },
            html: ui.msgLeaveArm ? null : '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/><path d="M16 17l5-5-5-5"/><path d="M21 12H9"/></svg>',
          }, ui.msgLeaveArm ? t('msgLeaveConfirmShort') : null))),
      ui.msgMembers ? wnMemberPanel(g, admin) : null,
      h('div', {
        class: 'chat-log',
        onScroll: (e) => {
          const el = e.target;
          ui.msgStick = el.scrollHeight - el.scrollTop - el.clientHeight < 60;
        },
      }, ...(rows.length ? rows : [h('div', { class: 'muted small', style: 'text-align:center;padding:24px 0' }, t('msgNoDmsYet'))])),
      reply ? 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(reply.rumor.pubkey)),
          h('span', { class: 'small muted chat-quote-text' }, ...snippetNodes(reply.rumor))),
        h('button', { class: 'chat-del', style: 'position:static;display:flex;flex-shrink:0', onClick: () => { ui.msgReplyTo = null; render(); } }, '×')) : null,
      live
        ? composer(t('msgDmPlaceholder'), () => wnSend(g), null, 'wn:' + g.id, g.cordn ? null : (f) => wnSendFile(g, f))
        : h('div', { class: 'muted small', style: 'text-align:center;padding:12px' }, t('msgGroupGone')),
      ui.msgSheet ? wnSheet(g) : null);
  }

  // ---- 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; ui.emojiPick = 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' },
        reactRow(myReact, (e2) => { close(); sendDmReaction(peer, m, e2); }),
        ui.emojiPick ? null : item('↩', t('msgReply'), () => {
          ui.msgReplyTo = m.rumor.id;
          close();
          setTimeout(() => document.getElementById('msg-draft')?.focus(), 50);
        }),
        !ui.emojiPick && canZapPk(m.rumor.pubkey) ? item('⚡', t('msgZap'), () => { close(); zapMessage(m.rumor.pubkey, m.rumor.id); }) : null,
        ui.emojiPick ? null : item('⧉', t('copy'), async () => {
          try { await navigator.clipboard.writeText(m.rumor.content); toast(t('copied')); } catch {}
          close();
        })));
  }

  // How messages to this person travel: automatic unless pinned.
  function routeSheet(peer, choice) {
    const close = () => { ui.msgRoutePick = false; render(); };
    const item = (pref, label, hint) => h('button', {
      class: 'msg-sheet-item', 'aria-pressed': String(choice.pref === pref),
      onClick: () => { setRoute(peer, pref); close(); },
    },
      h('span', { class: 'msg-sheet-ico' }, choice.pref === pref ? '✓' : ''),
      h('span', { class: 'col', style: 'gap:1px;text-align:left' },
        h('span', {}, label),
        h('span', { class: 'muted small' }, hint)));
    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: 'muted small', style: 'padding:4px 10px 6px' }, t('msgRouteTitle')),
        item('auto', t('msgRouteAuto'), t('msgRouteAutoHint')),
        item('wn', t('msgRouteWn'), t('msgRouteWnHint')),
        item('nip17', t('msgRouteDm'), t('msgRouteDmHint'))));
  }

  function dmView() {
    startDMs();
    const peer = ui.msgPeer;
    if (!peer) { ui.msgView = 'home'; return homeView(); }
    const thread = threads.get(peer) || new Map();
    if (!isMe(peer)) setTimeout(() => callWarm(peer), 1500); // a call may be next
    const msgs = foldCallLogs([...thread.values()].sort((a, b) => a.rumor.created_at - b.rumor.created_at));
    // a first message may go by White Noise: have their KeyPackage looked up before Send
    wnKnow(peer);
    const choice = routeChoice(peer);
    // 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' }, ...snippetNodes(src.rumor)));
    };
    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: canZapPk(m.rumor.pubkey) ? () => zapMessage(m.rumor.pubkey, m.rumor.id) : null, onHold: () => openZapSettings(m.rumor.pubkey, m.rumor.id) });
      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); },
        }, reactNode(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' }, ...snippetNodes(m.rumor))),
        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; ui.msgRoutePick = false; 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: 'row gap6', style: 'margin-left:auto;flex-shrink:0;align-items:center' },
          // a call: voice or video, to this one person
          isMe(peer) ? null : h('button', { class: 'iconbtn call-start', 'data-call': 'voice', title: t('callVoice'), 'aria-label': t('callVoice'), onClick: () => startCall(peer, 'voice') }, callIcon('phone')),
          isMe(peer) ? null : h('button', { class: 'iconbtn call-start', 'data-call': 'video', title: t('callVideo'), 'aria-label': t('callVideo'), onClick: () => startCall(peer, 'video') }, callIcon('video')),
          // Only where there is a choice: this person can be reached two ways.
          // The pill says which way the next message goes; tapping it pins one.
          choice ? h('button', {
            class: 'btn-sm route-pill', style: 'flex-shrink:0', title: t('msgRouteTitle'), 'aria-haspopup': 'true',
            onClick: () => { ui.msgRoutePick = !ui.msgRoutePick; render(); },
          }, t(choice.now === 'wn' ? 'msgRouteWn' : 'msgRouteDm'), ' ▾') : null)),
      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) => m.rumor.kind === CALL_LOG ? callLogRow(m, peer) :
            h('div', { class: 'chat-row dm' + (m.mine ? ' mine' : '') },
              h('div', { class: 'chat-body' },
                h('div', { class: 'chat-line' }, h('div', {
                  class: 'chat-bubble clickable' + (m.mine ? ' me' : '') + (emojiJumbo(m.rumor.content, emojiTagMap(m.rumor.tags)) ? ' jumbo' : ''),
                  // same tap-for-actions as community bubbles
                  onClick: chatBubbleClick(() => {
                    ui.msgSheet = ui.msgSheet === m.rumor.id ? null : m.rumor.id;
                    render();
                  }),
                }, dmQuote(m), ...(m.rumor.kind === 15 ? [] : noteBody(m.rumor.content, 0, emojiTagMap(m.rumor.tags))), ...attachmentNodes(m.rumor, m.wn), dmChips(m)),
                  m.mine ? null : msgZapBtn(m.rumor.pubkey, m.rumor.id)),
                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(),
      amberDmNotice(),
      composer(t('msgDmPlaceholder'), () => sendDM(peer), null, 'dm:' + peer, (f) => sendDMFile(peer, f)),
      ui.msgSheet ? dmSheet(peer) : null,
      choice && ui.msgRoutePick ? routeSheet(peer, choice) : null);
  }

  // ---- notifications: what happened to your posts --------------------------
  // Everything that names you: a like, a boost or a zap on something you
  // wrote, a reply, a mention. One filter (#p = you) on the relays we read,
  // kept as a short list of what-happened rows rather than the raw events —
  // a zap receipt drags its whole request along, and the list rides in the
  // feature state. Painted from the last visit while the relays are asked.
  const NOTIF_KINDS = [1, COMMENT, 6, 7, ...ZAP_KINDS];
  const NOTIF_KEEP = 150;
  let notif = null;      // { status, items }
  const NOTIF_V = 2;
  let notifAt = 0, notifUnsub = null;
  // Every notification event seen, id and time, for reconciliation (NIP-77)
  // with the relays that speak it: a refresh then fetches only what's new,
  // not the newest hundred and twenty again — a hundred kilobytes a visit.
  // All of them, not the rows kept: a zap receipt folded into its twin, or
  // a hidden author's reply, would otherwise come back on every refresh.
  const NOTIF_SEEN_MAX = 300; // the relay reconciles its newest 120
  let notifHeld = null; // id -> created_at, oldest first
  function notifHeldItems() {
    if (!notifHeld) {
      notifHeld = new Map();
      try { const s = st(); if (s.notifHeldPk === identityPk()) for (const [id, ts] of s.notifHeld || []) notifHeld.set(id, ts | 0); } catch {}
      for (const x of notifNow().items) if (x && x.id && x.ts && !notifHeld.has(x.id)) notifHeld.set(x.id, x.ts);
    }
    return [...notifHeld].map(([id, ts]) => [ts, id]);
  }
  function noteNotifHeld(evs) {
    notifHeldItems();
    let grew = false;
    for (const ev of evs || []) if (ev && ev.id && !notifHeld.has(ev.id)) { notifHeld.set(ev.id, ev.created_at | 0); grew = true; }
    while (notifHeld.size > NOTIF_SEEN_MAX) notifHeld.delete(notifHeld.keys().next().value);
    return grew;
  }
  const notifNoteAsking = new Set();
  const notifSeen = () => st().notifSeen || 0;
  // Notifications are about the IDENTITY, not the wallet: the stored list
  // remembers whose it is, and another identity on the same wallet starts
  // empty instead of reading the previous one's.
  const identityPk = () => (hook('nostrLoginIdentity') || {}).pubkey || (wallet.nostr && wallet.nostr.pk) || null;
  function notifNow() {
    if (!notif) {
      const s = st();
      // v2: lists saved before the account-switch fix may hold another
      // identity's rows under this one's key — dropped once, refetched
      const stored = (s.notifsV === NOTIF_V && s.notifsPk === identityPk()) ? (s.notifs || []) : [];
      notif = { status: stored.length ? 'ready' : 'loading', items: stored };
      // Reply events and the notes reactions/zaps point at ride beside their
      // notification rows. Seed the in-memory note caches synchronously, so
      // opening Notifications after a reload never paints "Fetching note…".
      const noteCache = s.notifNotesPk === identityPk() ? (s.notifNoteCache || {}) : {};
      for (const note of Object.values(noteCache)) {
        if (!note || !note.id) continue;
        notifNotes.set(note.id, note);
        quoted.set(note.id, { status: 'ready', ev: note, at: Date.now() });
      }
      warmNotifFaces(stored);
      warmNotifNotes(stored);
      refreshNotifs();
    }
    return notif;
  }
  // The faces the notifications page will paint, fetched and decoded ahead
  // of it: the names in one batch, then each picture through the cache and
  // into a thumbnail. Runs when the list is read from disk or grows (the
  // chat home does both before the page is ever opened), so opening it
  // paints faces rather than quiet circles that fill in one by one.
  const notifWarmed = new Set();
  function warmNotifFaces(items) {
    const pks = [...new Set((items || []).map((x) => x && x.actor).filter((pk) => pk && !notifWarmed.has(pk)))].slice(0, 80);
    if (!pks.length || typeof Image === 'undefined') return;
    for (const pk of pks) { notifWarmed.add(pk); liveProfileOf(pk); }
    const deadline = Date.now() + READY_MS;
    for (const pk of pks) warmAvatar(pk, deadline).catch(() => {});
  }
  // Keep only what rendering and opening a thread need. Signatures and relay
  // metadata make this cache unnecessarily large; the relays remain the
  // source of truth whenever the live notification refresh runs.
  const savedNotifNote = (ev) => ev && ev.id ? ({
    id: ev.id, pubkey: ev.pubkey, kind: ev.kind, created_at: ev.created_at,
    content: ev.content || '', tags: ev.tags || [],
  }) : null;
  function persistNotifs() {
    if (!notif) return;
    const wanted = new Set();
    for (const x of notif.items) {
      const id = x.what === 'reply' || x.what === 'mention' ? x.id : x.target;
      if (id) wanted.add(id);
    }
    const notes = {};
    for (const id of wanted) if (notifNotes.has(id)) notes[id] = savedNotifNote(notifNotes.get(id));
    const s2 = st();
    s2.notifs = notif.items; s2.notifsPk = identityPk(); s2.notifsV = NOTIF_V;
    if (notifHeld) { s2.notifHeld = [...notifHeld]; s2.notifHeldPk = identityPk(); }
    s2.notifNoteCache = notes; s2.notifNotesPk = identityPk();
    save(s2);
  }
  function cacheNotifNotes(evs) {
    if (!notif || !(evs || []).length) return false;
    const byId = new Map((evs || []).filter((ev) => ev && ev.id).map((ev) => [ev.id, savedNotifNote(ev)]));
    let changed = false;
    const wanted = new Set();
    for (const x of notif.items) wanted.add(x.what === 'reply' || x.what === 'mention' ? x.id : x.target);
    for (const [id, note] of byId) {
      if (!wanted.has(id) || notifNotes.has(id)) continue;
      notifNotes.set(id, note);
      quoted.set(id, { status: 'ready', ev: note, at: Date.now() });
      changed = true;
    }
    if (changed) persistNotifs();
    return changed;
  }
  // Old notification rows did not carry their note. Upgrade them in one
  // bounded batch while the bell/chat home is visible, before the user opens
  // the page. New rows take the same path as soon as they arrive.
  function warmNotifNotes(items) {
    const ids = [...new Set((items || [])
      .filter((x) => x && x.target && x.what !== 'reply' && x.what !== 'mention' && !notifNotes.has(x.target))
      .map((x) => x.target).filter((id) => !notifNoteAsking.has(id)))].slice(0, NOTIF_KEEP);
    if (!ids.length) return;
    for (const id of ids) notifNoteAsking.add(id);
    (async () => {
      const got = [];
      for (let i = 0; i < ids.length; i += 60)
        got.push(...await queryOn(zapRelays(), { ids: ids.slice(i, i + 60) }, 4500).catch(() => []));
      if (cacheNotifNotes(got)) scheduleRepaint();
    })().finally(() => { for (const id of ids) notifNoteAsking.delete(id); });
  }
  // What an event says happened, or null if it isn't about you after all.
  function notifItem(ev) {
    const my = myPubkeys();
    if (!ev || !ev.id) return null;
    const eTags = (ev.tags || []).filter((x) => x[0] === 'e' && x[1]);
    const lastE = eTags.map((x) => x[1]).at(-1) || null;
    // the relay hint on that tag: where the reactor says the note is
    const hint = /^wss?:\/\//i.test((eTags.at(-1) || [])[2] || '') ? [eTags.at(-1)[2]] : [];
    if (ZAP_KINDS.includes(ev.kind)) {
      const actor = zapperOf(ev), sats = receiptSats(ev);
      if (!actor || my.includes(actor) || !sats) return null;
      // a zap on a stream names it by address (a 30311), not by an e tag
      const stream = !lastE ? ((ev.tags || []).find((x) => x[0] === 'a' && String(x[1] || '').startsWith(LIVE_KIND + ':')) || [])[1] || null : null;
      return { id: ev.id, what: 'zap', actor, target: lastE, stream, hint, sats, text: zapText(ev), ts: ev.created_at };
    }
    if (my.includes(ev.pubkey)) return null;
    if (ev.kind === 7) {
      if (!lastE) return null;
      // a :shortcode: keeps its whole name and the picture its NIP-30 tag names
      const code = shortcodeOf(ev.content || '');
      const tag = code && (ev.tags || []).find((x) => x[0] === 'emoji' && x[1] === code && /^https?:\/\//.test(x[2] || ''));
      const emoji = !ev.content || ev.content === '+' ? '\u2764\ufe0f' : code ? ev.content.slice(0, 64) : ev.content.slice(0, 12);
      return { id: ev.id, what: 'react', actor: ev.pubkey, target: lastE, hint, emoji, emojiUrl: tag ? tag[2] : undefined, ts: ev.created_at };
    }
    if (ev.kind === 6) return lastE ? { id: ev.id, what: 'boost', actor: ev.pubkey, target: lastE, hint, ts: ev.created_at } : null;
    if (ev.kind === COMMENT) {
      const parent = tagVal(ev, 'e') || tagVal(ev, 'E');
      return { id: ev.id, what: parent ? 'reply' : 'mention', actor: ev.pubkey, target: parent, text: String(ev.content || '').slice(0, 300), ts: ev.created_at, pubkey: ev.pubkey };
    }
    if (ev.kind === 1) {
      const es = (ev.tags || []).filter((x) => x[0] === 'e' && x[1]);
      const replyTo = (es.find((x) => x[3] === 'reply') || es.find((x) => x[3] === 'root') || es.at(-1) || [])[1] || null;
      return { id: ev.id, what: replyTo ? 'reply' : 'mention', actor: ev.pubkey, target: replyTo, text: String(ev.content || '').slice(0, 300), ts: ev.created_at, pubkey: ev.pubkey };
    }
    return null;
  }
  function mergeNotifs(evs) {
    // only what names this identity
    evs = (evs || []).filter((ev) => ev && (ev.tags || []).some((x) => x[0] === 'p' && isMe(x[1])));
    const c = notifNow();
    const known = new Set(c.items.map((x) => x.id));
    for (const ev of evs) noteForSpam(ev);
    const items = evs.map((ev) => ((ev.kind === 1 || ev.kind === COMMENT) && hidden(ev) ? null : notifItem(ev)));
    // a custom-emoji reaction saved before rows kept its picture gets it now
    let healed = false;
    for (const x of items) {
      if (!x || !x.emojiUrl || !known.has(x.id)) continue;
      const old = c.items.find((y) => y.id === x.id);
      if (old && !old.emojiUrl) { old.emojiUrl = x.emojiUrl; old.emoji = x.emoji; healed = true; }
    }
    const add = items.filter((x) => x && !hiddenPk(x.actor) && !known.has(x.id) && known.add(x.id));
    if (!add.length) { if (healed) persistNotifs(); return healed; }
    warmNotifFaces(add);
    // One zap, two receipts: a coinos zap publishes its own (9737) beside the
    // LNURL server's (9735). The same person, post and amount within a few
    // minutes is one row.
    const all = [...c.items, ...add].sort((a, b) => b.ts - a.ts);
    const kept = [];
    for (const x of all) {
      if (x.what === 'zap' && kept.some((y) => y.what === 'zap' && y.actor === x.actor && y.target === x.target
        && y.sats === x.sats && Math.abs(y.ts - x.ts) < 300)) continue;
      kept.push(x);
    }
    c.items = kept.slice(0, NOTIF_KEEP);
    // Keep the small notification rows and one deduplicated copy of each note
    // they show. A reply is also a note we can open straight away.
    for (const ev of evs) if (ev.kind === 1 || ev.kind === COMMENT) notifNotes.set(ev.id, ev);
    cacheNotifNotes(evs);
    warmNotifNotes(c.items);
    persistNotifs();
    return true;
  }
  const notifNotes = new Map(); // reply id -> event, for opening the thread
  async function refreshNotifs(force) {
    const my = myPubkeys();
    if (!my.length) { if (notif) notif.status = 'ready'; return; }
    if (!force && Date.now() - notifAt < 30_000) return;
    notifAt = Date.now();
    const g = session;
    try {
      const evs = await syncOn(zapRelays(), { kinds: NOTIF_KINDS, '#p': my, limit: 120 }, notifHeldItems(), { maxWait: 5000 });
      if (g !== session) return; // asked for the previous account
      const grew = noteNotifHeld(evs);
      if (mergeNotifs(evs)) scheduleRepaint();
      if (grew) persistNotifs();
    } catch {} finally {
      if (g === session) {
        if (notif) notif.status = 'ready';
        scheduleRepaint();
      }
    }
    if (g === session) watchNotifs();
  }
  function watchNotifs() {
    stopNotifWatch();
    const my = myPubkeys();
    if (!my.length || !ui.chatOpen || ui.msgView !== 'notifs') return;
    notifUnsub = subscribeOn(zapRelays(), { kinds: NOTIF_KINDS, '#p': my, since: Math.floor(Date.now() / 1000) - 60 },
      (ev) => { if (mergeNotifs([ev])) scheduleRepaint(); });
  }
  function stopNotifWatch() { if (notifUnsub) { try { notifUnsub(); } catch {} notifUnsub = null; } }
  // Counted as a notification: not from someone hidden, and not something
  // your follows flagged — the page folds that row (notifFoldRow) rather
  // than count it as news.
  const notifShown = (x) => !hiddenPk(x.actor) && !reportsOn({ id: x.id, pubkey: x.actor });
  // Who among your follows flagged this row's author or post, unless you
  // asked to see it: the row is folded, not dropped — a reply from someone
  // two follows reported as spam vanished from the page without a trace
  // (Adam's phone, 2026-10-14), while the thread would have shown a fold.
  const notifFlagged = (x) => (ui.revealed && ui.revealed.has(x.id)) ? null : reportsOn({ id: x.id, pubkey: x.actor });
  function notifFoldRow(x, by) {
    profileOf(x.actor);
    for (const pk of by.slice(0, 3)) profileOf(pk);
    const who = by.length <= 3 ? t('foldReported1', { name: by.map((pk) => displayName(pk)).join(', ') }) : t('foldReportedN', { n: by.length });
    return h('div', { class: 'row alert-row note-folded', style: 'gap:10px;align-items:center;padding:10px 0;opacity:.75' },
      avatar(x.actor, 'chat-avatar note-avatar', false),
      h('div', { class: 'col grow', style: 'min-width:0;gap:3px' },
        h('div', { class: 'row', style: 'gap:7px;align-items:baseline;min-width:0' },
          h('span', { style: 'font-weight:600;font-size:15px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis' }, displayName(x.actor)),
          h('span', { class: 'small', style: 'min-width:0' }, notifLabel(x)),
          h('span', { class: 'small faint', style: 'white-space:nowrap;margin-left:auto' }, timeLabel(x.ts * 1000))),
        h('div', { class: 'small muted' }, '\u26a0 ' + who)),
      // seen here, the reply is seen in its thread too (the same id)
      h('button', {
        class: 'btn-sm', type: 'button', style: 'flex-shrink:0',
        onClick: (e) => { e.stopPropagation(); (ui.revealed ||= new Set()).add(x.id); render(); },
      }, t('foldShow')));
  }
  const notifUnread = () => notifNow().items.filter((x) => x.ts > notifSeen() && notifShown(x)).length;
  function markNotifsSeen() {
    const newest = Math.max(0, ...notifNow().items.map((x) => x.ts));
    if (newest > notifSeen()) { const s2 = st(); s2.notifSeen = newest; save(s2); }
  }
  // The post an item is about, if we have it — ours from the feed or a
  // thread, or fetched once by id (quotedNote remembers and repaints).
  function notifTarget(id, relays = []) {
    if (!id) return null;
    for (const pk of myPubkeys()) { const hit = notesInHand(pk).find((e) => e.id === id); if (hit) return hit; }
    if (notifNotes.has(id)) return notifNotes.get(id);
    const q = quotedNote({ id, relays });
    return q.ev || null;
  }
  // A zap can land on a chat message or a DM rather than a post — the
  // receipt e-tags the rumor's id, which no relay has ever seen as an event,
  // so fetching it by id would spin forever. Look in the rooms and threads
  // we hold first; that is where the text is, and where a tap should go.
  function messageInHand(id) {
    for (const [cid, room] of rooms) {
      for (const [chId, msgs] of room.byChannel) {
        const m = msgs.get(id);
        if (m) return { cid, chId, text: String(m.rumor.content || '') };
      }
    }
    for (const [peer, msgs] of threads) {
      const m = msgs.get(id);
      if (m) return { peer, text: String(m.rumor.content || '') };
    }
    return null;
  }
  const targetGone = (id) => { const q = quoted.get(id); return !!q && q.status === 'missing'; };
  // A one-line excerpt: mentions read as names, not as nostr:nprofile1… keys.
  function plainExcerpt(text) {
    return String(text || '').replace(/nostr:(npub|nprofile)1[a-z0-9]+/gi, (m) => {
      const ref = parseNostrRef(m.slice(6));
      return ref && ref.type === 'pubkey' ? '@' + displayName(ref.pk) : m.slice(6, 18) + '\u2026';
    }).replace(/\s+/g, ' ').trim();
  }
  function notifLabel(x) {
    if (x.what === 'zap') return t('alertZap', { sats: fmtSats(x.sats) + ' sats' });
    if (x.what === 'react') {
      const code = shortcodeOf(x.emoji);
      const url = code && (x.emojiUrl || emojiUrl(code));
      if (!url) return t('alertReact', { emoji: x.emoji });
      const [a, b = ''] = t('alertReact', { emoji: '\u0000' }).split('\u0000');
      return h('span', {}, a, reactImg(code, url), b);
    }
    if (x.what === 'boost') return t('alertBoost');
    if (x.what === 'reply') return t('alertReply');
    return t('alertMention');
  }
  function notifRow(x) {
    profileOf(x.actor);
    const aboutNote = !(x.what === 'reply' || x.what === 'mention');
    const msg = aboutNote ? messageInHand(x.target) : null;
    const target = aboutNote && !msg ? notifTarget(x.target, x.hint || []) : null;
    const excerpt = !aboutNote
      ? plainExcerpt(x.text)
      : msg ? plainExcerpt(msg.text.slice(0, 140))
        : target ? plainExcerpt(String(target.content || '').slice(0, 140)) : null;
    const open = () => {
      if (!aboutNote) {
        const ev = notifNotes.get(x.id);
        if (ev) openNoteThread(ev); else openNoteRef({ id: x.id }).catch(() => {});
      } else if (msg && msg.peer) { ui.msgView = 'dm'; ui.msgPeer = msg.peer; ui.msgStick = true; stopNotifWatch(); render(); }
      else if (msg) { ui.msgView = 'room'; ui.msgCommunity = msg.cid; ui.msgChannel = msg.chId; ui.msgStick = true; stopNotifWatch(); render(); }
      else {
        // a reaction, boost or zap: land on the note with its who-panel
        // already unfolded, so the tap answers "who?" without a second one
        if (x.target) whoOpenIds.add(x.target);
        if (target) openNoteThread(target);
        // a note we couldn't find is asked for again on tap, hints and all
        else if (x.target) openNoteRef({ id: x.target, relays: x.hint || [] }).catch(() => {});
        // a zap on a stream opens the stream; one on your profile (no post
        // at all) opens the zapper's — the tap used to do nothing
        else if (x.stream) { const [, pk, ...d] = x.stream.split(':'); stopNotifWatch(); openLiveRef({ pk, d: d.join(':') }).catch(() => {}); }
        else { stopNotifWatch(); openProfile(x.actor); }
      }
    };
    return h('div', {
      class: 'row alert-row' + (x.ts > notifSeenAtOpen ? ' fresh' : ''),
      style: 'gap:10px;align-items:flex-start;padding:10px 0;cursor:pointer',
      onClick: (e) => { if (e.target && e.target.closest && e.target.closest('button')) return; open(); },
    },
      // the face opens the sender's profile; the rest of the row opens the note
      avatar(x.actor, 'chat-avatar note-avatar'),
      h('div', { class: 'col grow', style: 'min-width:0;gap:3px' },
        h('div', { class: 'row', style: 'gap:7px;align-items:baseline;min-width:0' },
          h('span', { style: 'font-weight:600;font-size:15px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis' },
            displayName(x.actor)),
          h('span', { class: 'small', style: 'min-width:0' }, notifLabel(x)),
          h('span', { class: 'small faint', style: 'white-space:nowrap;margin-left:auto' }, timeLabel(x.ts * 1000))),
        x.what === 'zap' && x.text ? h('div', { class: 'small' }, x.text) : null,
        excerpt != null
          ? h('div', { class: 'small muted alert-excerpt' }, excerpt)
          : x.target ? h('div', { class: 'small faint' }, targetGone(x.target) ? t('alertNoteGone') : t('noteRefLoading')) : null));
  }
  let notifSeenAtOpen = 0; // what counted as new when the list was opened
  function openNotifs() {
    notifSeenAtOpen = notifSeen();
    ui.chatOpen = true;
    ui.msgView = 'notifs';
    warmNotifFaces(notifNow().items);
    refreshNotifs(true).catch(() => {});
    watchNotifs();
    markNotifsSeen();
    render();
  }
  function notifView() {
    const c = notifNow();
    syncReports().catch(() => {}); // the folds below follow your follows' flags (throttled inside)
    markNotifsSeen(); // anything that lands while you look is seen too
    const items = c.items.filter((x) => !hiddenPk(x.actor)); // a mute made later applies to what was kept
    const rows = items.flatMap((x, i) => { const by = notifFlagged(x); return [i ? noteSep() : null, by ? notifFoldRow(x, by) : notifRow(x)]; });
    return h('div', { class: 'card col chat-page', style: 'gap:10px' },
      h('div', { class: 'row gap6', style: 'align-items:center' },
        backBtn(() => { ui.msgView = 'home'; stopNotifWatch(); render(); }),
        h('h3', { style: 'margin:0' }, t('alertsTitle')),
        // which of these also buzz the phone: Settings → Notifications
        ctx.openSettingsPage ? h('button', {
          class: 'btn-sm notif-settings', style: 'margin-left:auto;display:inline-flex;align-items:center;gap:6px',
          title: t('settingsNotifications'), 'aria-label': t('settingsNotifications'),
          onClick: () => { stopNotifWatch(); ctx.openSettingsPage('notifications'); },
        }, h('span', { style: 'display:flex', html: '<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09a1.65 1.65 0 0 0-1-1.51 1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09a1.65 1.65 0 0 0 1.51-1 1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33h.09a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82v.09a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg>' }),
          t('tabSettings')) : null),
      c.status === 'loading' && !items.length
        ? h('div', { class: 'row gap6', style: 'justify-content:center;padding:12px 0' }, h('span', { class: 'spinner sm' }))
        : !items.length
          ? h('div', { class: 'small faint', style: 'text-align:center;padding:12px 0' }, t('alertsEmpty'))
          : h('div', { class: 'card col notes-feed', style: 'gap:0' }, ...rows),
      ...noteOverlays());
  }

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

  function messagesTab() {
    if (ui.feedEdit) return feedEditView();
    if (ui.msgView === 'feed') return feedView();
    if (ui.msgView === 'notifs') return notifView();
    if (ui.msgView === 'room') return roomView();
    if (ui.msgView === 'dm') return dmView();
    if (ui.msgView === 'grp') return wnView();
    return homeView();
  }

  // The caches above live in IndexedDB (cache-store.js), which opens a few
  // milliseconds into boot. Anything read before then came from what was
  // left in localStorage — nothing, once migrated — so re-read it all.
  if (!cacheIsReady()) onCacheReady(() => {
    profBlob = null; facelessBlob = null; relayLists = null; packMembers = null; reportsCache = null; baseline = null;
    profilesWarmed = false; warmProfiles();
    loadHubCache(); loadVideoDims(); loadVideoInfo(); loadPreviews(); loadTranslations();
    scheduleRepaint();
  });

  return {
    id: 'messages',
    // group-chat state is device state in IndexedDB: it goes with the account
    wipeCache(bases) { import('../marmot-store.js').then((m) => { for (const b of bases) m.wipeMarmot(b); }).catch(() => {}); },
    forgetAll() { wipeMediaIndex(); mediaIdx.clear(); try { caches.delete(VIDEO_THUMB_CACHE); } catch {} },
    nostrSettingsCards() { return [relaysCard(), followHistoryCard(), groupDevicesCard(), moderationCard(), translateCard(), videosCard()]; },
    // 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) {
      // a blink between apps didn't kill anything
      if (awayMs && awayMs < 5_000) return;
      resubscribeStreams(); // DMs and rooms, whether or not chat is on screen
      if (!ui.chatOpen || !['feed', 'notifs'].includes(ui.msgView)) return true;
      if (ui.msgView === 'notifs') refreshNotifs(true).catch(() => {});
      else 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);
      setTimeout(seedNewIdentity, 0); // fresh words: something to read from the start
      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();
    },
    bottomNav: appBottomNav,
    notifySettingsCards() { return [notifyCard()]; },
    screenView() {
      liveShown = false;
      queueMicrotask(liveAfterRender);
      // 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.
      // Same for a note deep link while its thread is being found.
      if (ui.pubNotePending && !ui.noteThread && !ui.liveStream) return h('div', { class: 'col', style: 'gap:16px' },
        ctx.brandHeader(false),
        h('div', { class: 'card row gap6', style: 'justify-content:center;align-items:center;padding:16px' },
          h('span', { class: 'spinner sm' }), h('span', { class: 'small faint' }, t('noteRefLoading'))));
      if (ui.pubFeedPending) return h('div', { class: 'col', style: 'gap:16px' }, ctx.brandHeader(false));
      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.zapSetup && ui.liveStream) return zapSetupScreen();
          if (ui.liveStream) return liveScreen();
          if (ui.profOverThread && ui.profilePk) return profileScreen();
          if (ui.noteThread) return threadScreen();
          if (ui.profilePk) return profileScreen();
          if (ui.userSearch) return userSearchScreen();
          if (ui.chatOpen && ui.msgView === 'feed') return h('div', { class: 'col', style: 'gap:16px' }, ctx.brandHeader(false), feedView());
        }
        return null;
      }
      if (ui.zapSetup) return zapSetupScreen();
      if (ui.goLive) return goLiveScreen();
      if (ui.liveStream) return liveScreen();
      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; },
    // the desktop header's search field: typing there IS the search page's query
    userSearchQuery(q) {
      if (!ui.userSearch) { if (!isVisitor()) ui.chatOpen = false; ui.profilePk = null; ui.noteThread = null; ui.liveStream = null; ui.goLive = null; ui.userSearch = { q: '', rows: null }; warmSearch(); }
      ui.userSearch.q = q; userSearcher.update(q); render();
      return true;
    },
    openUserSearch() {
      if (!isVisitor()) ui.chatOpen = false; // a visitor's feed stays underneath, for Back
      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() { noteSignerGap(); 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); },
    // Search results have their own profile cache. Hand the known name and
    // photo to the portrait cache before drawing the suggestions, instead
    // of throwing them away and waiting for another relay lookup on pick.
    warmRecipient(cand) {
      const pk = cand?.pk;
      if (!/^[0-9a-f]{64}$/.test(pk || '')) return;
      warmProfiles();
      const cur = profiles.get(pk);
      const entry = keepThumb(pk, {
        ...(cur || {}), name: cur?.name || cand.name || null,
        picture: cur?.picture || cand.picture || null,
        t: cur?.t || 0,
      });
      if (entry.picture) delete entry.loading;
      else if (!cur || cur.loading) entry.loading = true;
      profiles.set(pk, entry);
      persistProfile(pk, entry);
      preloadPicture(entry, true);
      // Search data is partial: fetch payment metadata in the background
      // while the already-known picture is immediately available.
      profileOf(pk);
      return true;
    },
    // 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(() => {});
    },
    // opens the profile, unless the caller has a step to take first (the
    // Accounts page switches to that identity before showing its profile)
    profileChip(pk, size, onOpen) {
      const big = size === 'lg';
      return h(big ? 'button' : 'span', {
        class: big ? 'send-person' : 'zap-chip',
        type: big ? 'button' : undefined,
        onClick: (e) => { e.stopPropagation(); if (onOpen) onOpen(); else openProfile(pk); },
      }, avatar(pk, 'chat-avatar ' + (big ? 'send-avatar' : 'mini'), false),
        h('span', { class: big ? '' : 'small' }, displayName(pk)));
    },
    // A sign-in (Google, passkey, key) that found no wallet on its identity:
    // the same start, but only the follows of an identity that follows
    // nobody yet — an established nostr user keeps their own list.
    identitySignedInNew() { setTimeout(() => seedNewIdentity({ onlyIfNoFollows: true }), 0); return true; },
    openProfile(pk) { openProfile(pk); return true; },
    openFeedOf(pk) { openFeedOf(pk); return true; },
    // the visitor's header: search, and the way in
    visitorSignIn() { toFrontDoor(); return true; },
    visitorSearch() {
      rememberReturn();
      ui.profilePk = null; ui.noteThread = null; ui.liveStream = null; ui.goLive = null; ui.profOverThread = false;
      ui.userSearch = { q: '', rows: null };
      warmSearch();
      render();
      return true;
    },
    // a new language: the curated feeds were judged in the old one
    langChanged() {
      for (const c of [...feedStates.values()]) { const d = feedDef(c.id); if (d && d.curated) dropFeedState(c.id); }
      if (feedDef(curFeedId)?.curated) selectFeed(curFeedId);
      return true;
    },
    navPath(snap) {
      if (snap && snap.liveStream && snap.liveStream.a) { const n = packNaddr(snap.liveStream.a); if (n) return '/' + n; }
      if (!snap || !snap.chatOpen || snap.msgView !== 'feed' || snap.profilePk || snap.noteThread || snap.userSearch) return null;
      const def = feedDef(snap.feedId || curFeedId);
      return def && adhocFeeds.has(def.id) ? feedPath(def) : null;
    },
    avatarNode(pk, cls) { return avatar(pk, cls || 'chat-avatar mini', false); },
    callOverlay() { return callOverlay(); },
    init() {
      const session = ++feedWarmSession;
      // this wallet's own feed (the feature outlives a sign-out): a feed
      // opened from a link stays put
      if (!adhocFeeds.has(curFeedId)) { curFeedId = homeFeedId(); if (ui.feedId && !adhocFeeds.has(ui.feedId)) ui.feedId = curFeedId; }
      try { localStorage.removeItem(FEED_LS); } catch {} // the old device-wide choice: nobody's in particular
      returnAfterSignin(); // a visitor who signed in from a feed or profile lands back on it
      // /feed opened before the wallet restored made a visitor's session copy
      // of Popular; with the wallet here, the built-in one takes over (two
      // Popular chips otherwise)
      if (adhocFeeds.has('all:visitor')) {
        adhocFeeds.delete('all:visitor'); dropFeedState('all:visitor');
        if (curFeedId === 'all:visitor') { ui.feedId = EVERYTHING; curFeedId = EVERYTHING; }
      }
      // this wallet's cached faces, from its own namespace — the keys are
      // in place now, whatever the header asked for before
      profilesWarmed = false;
      warmProfiles();
      // 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);
      // A tapped "new reply" notification lands here: as ?open=notifs when
      // it had to open a window, or as a worker message when one was open.
      if (OPEN_VIEW === 'notifs') setTimeout(openNotifs, 0);
      // a connection that came back is a connection whose subs may have died
      window.addEventListener('online', () => setTimeout(resubscribeStreams, 1500));
      armWatchdog(); // and, on screen, keep checking the sockets are really there
      try {
        navigator.serviceWorker?.addEventListener('message', (ev) => {
          if (ev.data && ev.data.type === 'open' && ev.data.view === 'notifs') openNotifs();
          // a call the worker was woken for: rung here too (an app in the
          // background may have missed it live), or picked up from the tap
          if (ev.data && ev.data.type === 'call-offer' && ev.data.offer) callsNow().handle(ev.data.offer, { maxAge: RING_S }).catch(() => {});
          if (ev.data && ev.data.type === 'open' && ev.data.view === 'call') pendingCall();
        });
      } catch {}
      // a tapped "is calling" opened the app, or brought it back: the offer the worker kept
      setTimeout(pendingCall, 0);
      document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'visible') pendingCall(); });
      if (urlInvite && !pendingLink) {
        loadLinkInvite(urlInvite);
        setTimeout(() => { ui.chatOpen = true; ui.msgView = 'home'; render(); }, 0);
      }
      if (urlPack) {
        addPack(urlPack).catch(() => {});
        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);
      onViewportResize();
      allUnsubs.push(() => {
        window.removeEventListener('resize', onViewportResize);
        window.visualViewport?.removeEventListener('resize', onViewportResize);
        document.documentElement.style.removeProperty('--chat-viewport-height');
      });
      startDMs();
      // Group chats: load this identity's groups once the boot rush is over.
      // A seed-derived identity signs silently, so it also becomes invitable
      // here; a login signer is only asked when Chat is opened.
      setTimeout(() => {
        whiteNoise().then((c) => { if (c && !hook('nostrLoginIdentity')) { wnReadied = true; c.ready().catch(() => {}); } }).catch(() => {});
      }, 3000);
      // 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(() => {});
      // Warm a small opening page while the wallet is idle, before Feed is
      // opened. This is one bounded query, not a live feed subscription.
      syncFollows().catch(() => {});
      feedWarmTimer = setTimeout(() => {
        feedWarmTimer = null;
        if (session === feedWarmSession) feedNow();
      }, 1500);
      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();
      if (wn) { try { wn.stop(); } catch {} }
      wn = null; wnLoading = null; wnReadied = false;
      wnFolds.clear(); wnReach.clear(); wnReactOf.clear(); wnCands.clear();
      seenWraps.clear(); wrapLog = null; // the next account must decrypt wraps this one couldn't
      clearTimeout(healTimer); healSince = 0;
      clearTimeout(drainTimer);
      pendingWraps.clear();
      dmStarted = false;
      if (calls) { try { calls.stop(); } catch {} calls = null; callInbox.clear(); iceCache = null; warmed.clear(); callRing(); }
      listsSynced = false;
      if (zapLiveUnsub) { try { zapLiveUnsub(); } catch {} zapLiveUnsub = null; }
      clearTimeout(zapTimer); zapTimer = null; zapQueue = new Set(); zapRecent = [];
      clearTimeout(zapLiveTimer); zapLiveTimer = null; zapLiveAt = 0;
      stopFeedWatch();
      ++feedWarmSession;
      clearTimeout(feedWarmTimer); feedWarmTimer = null;
      clearTimeout(feedAheadTimer); feedAheadTimer = null;
      for (const c of feedStates.values()) c.stopped = true;
      feedStates.clear();
      threadPrefetch.stop();
      threadCache.clear();
      follows = null; followsAt = 0; feed = null; relayLists = null;
      mutes = null; mutesAt = 0;
      stCache = null; stAt = 0; // the next account's state, not this one's
      if (profFlush) { clearTimeout(profFlush); flushProfiles(); } // this account's faces, written before the blob is dropped
      profBlob = null;
      timedActivity.clear(); diskHeld.clear(); reacts.clear(); boosts.clear(); seenNoteEv.clear(); myReactEv.clear(); quoted.clear();
      noteCountsReady.clear();
      // what happened to THEIR posts stays with them — the next identity
      // starts its list empty and asks the relays under its own key
      stopNotifWatch(); notif = null; notifHeld = null; notifAt = 0; notifNotes.clear();
      session++;
      zapWho.clear(); whoOpenIds.clear();
      clearTimeout(zapSaveT); zapSaveT = null; zapSeed = null;
      zapTotals.clear(); zapAsked.clear(); zapPending.clear(); // 'mine' is per identity — refetch under the next
    },
  };
}