aboutsummaryrefslogtreecommitdiffstats
path: root/src/params
diff options
context:
space:
mode:
authorAdam Soltys <[email protected]>2022-11-11 20:25:50 -0800
committerAdam Soltys <[email protected]>2022-11-11 20:25:50 -0800
commit801aeaf8175fd043a349addb48ee663986615b9a (patch)
treebbacbc0de60e4c19668a7f7752b8b2c3d00166c3 /src/params
parent20449bd44c6d6deefd357d2cdab6e26645b67afa (diff)
downloadcoinos-ui-801aeaf8175fd043a349addb48ee663986615b9a.tar.gz
coinos-ui-801aeaf8175fd043a349addb48ee663986615b9a.zip
logo scrolls to top
Diffstat (limited to 'src/params')
0 files changed, 0 insertions, 0 deletions
'n173' href='#n173'>173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411
import { momentTags } from '../media-timeline.js';
// Ark feature — off-chain payments via an ASP (Second's bark/captaind
// protocol, spoken natively by ../ark). Receive address + boarding, instant
// sends, history entries, refresh/consolidation, server settings.

import { zapAddrOf } from '../live.js';
import * as btc from '@scure/btc-signer';
import { HDKey } from '@scure/bip32';
import { hex, base32nopad, bech32 } from '@scure/base';
import { sha256 } from '@noble/hashes/sha256';
import { ArkManager, remoteRenewalsInFlight, lnFoldedIds, renewPolicy, CUSTODY_TIERS } from '../ark/manager.js';
export { remoteRenewalsInFlight };

// Coins this device may offer: spendable, and not held by a renewal another
// device has in flight (see ArkManager._remoteBusy).
function freeCoins(st) {
  if (!st) return [];
  const busy = new Set(remoteRenewalsInFlight(st).flatMap((r) => r.inputIds || []));
  return (st.vtxos || []).filter((v) => v.state === 'spendable' && !busy.has(v.id));
}
// The coins a unilateral exit can still take on-chain. Past its timelock a
// coin's tree is the server's to sweep (and it has): only the server can
// honor it now, and it does — but no exit transaction will ever confirm.
function exitableCoins(st, tip) {
  return freeCoins(st).filter((v) => !(tip && v.expiryHeight && v.expiryHeight <= tip));
}
import { loadBg, saveBg, buildBg, disarmSiblingRecords } from '../nwc-bg.js';
import { boardFee, p2trAddress } from '../ark/board.js';
import { maybeBolt11, maybeLnInvoice, lnSendFee, lnShortfall } from '../ark/lightning.js';
import { decodeVtxo, getVtxoStatus, VTXO_STATE_SPENT, concatBytes, vtxoBytesFromStr, vtxoBytesToHex, decodeAddress, arkIdFromServerPubkey, getArkInfo } from '../ark/proto.js';
import { arkStore } from '../ark/store.js';
import { signedExitTxs, exitTxVsizes, buildBumpChild, buildExitClaim, submitPackage } from '../ark/exit.js';
import { utxoId } from '../wallet.js';
import {
  getNetwork, setNetwork, getArkProviderId, getArkConfig, setArkProviderId, arkPresets, getArkCustom, setArkCustom,
} from '../api.js';
import { t } from '../i18n.js';
import { rateNow } from '../rates.js';
import { resolveBip353, parsePaymentName, parseBip21 as parseBip21Uri } from '../bip353.js';
import { parseZapTarget, fetchPayParams, requestInvoice } from '../lnurl.js';
import { shortAddr, shortTxid, timeAgo, fmtSats, fmtBtc, ARK_ICON, ARK_MARK, BITCOIN_ICON } from '../format.js';

// t?ark1… bech32m — an Ark address for this or another ASP.
export function isArkAddress(a) { return /^t?ark1[a-z0-9]{20,}$/i.test((a || '').trim()); }

// Use the funding transaction's actual input selection and P2TR output size
// for both Max and the fee preview. Mining fees are paid from Savings; only
// the ASP service fee comes out of the amount deposited into Spending.
export function previewBoardFunding(wallet, ark, amountSat = 0, sendMax = false) {
  const feeRate = (wallet.feeRates && wallet.feeRates.halfHourFee) || 5;
  const hrp = { bitcoin: 'bc', regtest: 'bcrt' }[ark?.info?.network] || 'tb';
  const dest = ark ? p2trAddress(ark._key(0).pubkey.slice(1), hrp) : wallet.freshChange().address;
  const draft = wallet.buildTx({ recipients: [{ address: dest, amount: amountSat }], feeRate, sendMax, noSort: true });
  const fundingSat = draft.outputs[0].amount;
  const serviceFeeSat = boardFee(fundingSat, ark?.info?.boardFees);
  return { fundingSat, chainFeeSat: draft.fee, serviceFeeSat,
    feeSat: draft.fee + serviceFeeSat, netSat: fundingSat - serviceFeeSat };
}

// Ark movement types that actually touch the chain — each is a real bitcoin
// tx with a txid, so it wears the Bitcoin mark, not the Ark one: board pulls
// coins in from on-chain, offboard and exit push them back out.
const ONCHAIN_ARK = new Set(['board', 'offboard', 'exit']);

// Every live ark manager registers its debounced persist here so a pending
// write is never lost: flushed synchronously when the page hides, and on a
// wallet switch (see stopArk).
const arkPersistFlushers = new Set();
if (typeof document !== 'undefined') {
  const flushAll = () => { for (const f of [...arkPersistFlushers]) { try { f(); } catch {} } };
  addEventListener('pagehide', flushAll);
  document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'hidden') flushAll(); });
}

// Wallet storage/key helpers for this feature, installed onto the core
// wallet instance so a build without the feature ships none of it.
export function installArkWallet(wallet) {
  if (wallet.loadArkState) return; // already installed
  const store = arkStore(); // IndexedDB-backed, memory-fronted; opens now
  Object.assign(wallet, {
    _arkStore: store,
    // ---- Ark support -------------------------------------------------------
    // Persisted ArkManager state (vtxos, in-flight action checkpoints, movement
    // history — no secrets: vtxo keys are re-derived from the seed).
    // Ark state is per WALLET *and* per ASP: vtxos are cosigned by one
    // specific server, so showing another server's coins (or resuming its
    // in-flight board) is meaningless and alarming. Switching providers must
    // therefore switch state, and switching back must restore it.
    _arkNs(url) {
      // short, stable id for an ASP endpoint
      let h = 5381;
      for (const c of String(url || '')) h = ((h * 33) ^ c.charCodeAt(0)) >>> 0;
      return h.toString(36);
    },
    _arkKey(url) { return this._cacheKey() + ':ark:' + this._arkNs(url); },
    _arkLegacyKey() { return this._cacheKey() + ':ark'; },
    // Who really cosigned this state's coins? A vtxo names its server in its
    // own bytes, which is cryptographic fact — unlike the stamp, which is
    // just something we wrote and could have written wrongly.
    _arkVtxoOwner(st) {
      const v = (st?.vtxos || []).find((x) => x.bytes);
      if (!v) return null;
      try { return decodeVtxo(vtxoBytesFromStr(v.bytes)).serverPubkey; } catch { return null; }
    },
    // Park state under the server that actually owns it, until the URL for
    // that server is selected and can adopt it.
    _arkHoldKey(pubkey) { return this._cacheKey() + ':ark:pk:' + String(pubkey).slice(0, 16); },
    loadArkState(url) {
      // NB deliberately no fallback to the legacy key: the UI renders from
      // this before any server is contacted, so returning another ASP's state
      // here is exactly how you get a phantom balance. Pre-namespacing state
      // is claimed via adoptArkState() once we know who cosigned it.
      try {
        const st = store.get(this._arkKey(url));
        if (!st) return null;
        // Self-repair: an earlier build could stamp state with whichever
        // server happened to be connected, filing one ASP's coins under
        // another. The vtxos themselves settle it — if they disagree with the
        // stamp, this state is misfiled. Move it to its real owner and show
        // nothing here.
        const owner = this._arkVtxoOwner(st);
        if (owner && st.serverPubkey && owner !== st.serverPubkey) {
          st.serverPubkey = owner;
          store.set(this._arkHoldKey(owner), st);
          store.remove(this._arkKey(url));
          return null;
        }
        return st;
      } catch { return null; }
    },
    // Offer up pre-namespacing state, but only to the ASP that actually
    // cosigned it. Its owner is read from the state's own stamp, or failing
    // that decoded straight out of a vtxo — the vtxo wire format carries the
    // server pubkey, so this needs no network call and cannot guess wrong.
    adoptArkState(serverPubkey, url) {
      try {
        // state parked by the self-repair above belongs to exactly one server
        const held = store.get(this._arkHoldKey(serverPubkey));
        if (held) {
          this.saveArkState(held, url);
          store.remove(this._arkHoldKey(serverPubkey));
          return held;
        }
        const st = store.get(this._arkLegacyKey());
        if (!st) return null;
        let owner = st.serverPubkey || null;
        if (!owner) {
          const v = (st.vtxos || []).find((x) => x.bytes);
          if (v) { try { owner = decodeVtxo(vtxoBytesFromStr(v.bytes)).serverPubkey; } catch {} }
        }
        if (owner && owner !== serverPubkey) return null; // belongs to another ASP
        if (!owner) return null;                          // can't prove ownership: leave it
        st.serverPubkey = owner;
        this.saveArkState(st, url);
        store.remove(this._arkLegacyKey()); // now safely namespaced
        return st;
      } catch { return null; }
    },
    saveArkState(state, url) {
      store.set(this._arkKey(url), state);
    },
  });
}

// A slim projection of ark state for the sync snapshot. Oversized domains
// now travel as encrypted Blossom blobs, so preserve the complete history
// and spent-coin stubs instead of rebuilding them from the mailbox. Another
// device needs, per vtxo: id/amount/state (+ bytes ONLY for spendable/pending,
// which it might spend/exit); the movement log for ark history; and
// done board/offboard/exit actions (stripped of hex) so on-chain rows still
// label. In-flight actions and their signing material stay device-local.
const RENEW_STEP_RANK = { created: 0, submitted: 1, issued: 2, done: 3, failed: 3 };
// when a renewal began: its action id carries the moment (refresh-<ms>,
// refresh-rescue-<ms>)
const renewalStartedAt = (id) => Number(String(id).split('-').pop()) || 0;

function renewalSliver(a) {
  return {
    id: a.id, step: a.step, superseded: !!a.superseded, manual: !!a.manual,
    // which coins it holds, so other devices don't offer them meanwhile
    inputIds: [...(a.inputIds || [])],
    outAmountSat: a.outAmountSat, feeSat: a.feeSat || 0,
    unlockHash: a.unlockHash || null, fundingTxid: a.fundingTxid || null,
  };
}

// Other devices' renewals, by id: the furthest-along telling wins (a step
// never goes backwards), this device's own actions never count as remote,
// and anything begun more than two days ago is dropped — a renewal finishes
// within hours, and a device that stopped publishing mustn't leave a card
// behind forever.
export function mergeRemoteRenewals(a, b, now = Date.now()) {
  const own = new Set((a.actions || []).map((x) => x.id));
  // b's own renewals are remote to us; a.renewals only exists when a was
  // itself adopted whole from a snapshot
  const byId = new Map();
  for (const r of [...(a.remoteRenewals || []), ...(a.renewals || []), ...(b.remoteRenewals || []), ...(b.renewals || [])]) {
    if (!r || !r.id || own.has(r.id)) continue;
    if (now - renewalStartedAt(r.id) > 2 * 86_400_000) continue;
    const cur = byId.get(r.id);
    if (!cur || (RENEW_STEP_RANK[r.step] ?? 0) > (RENEW_STEP_RANK[cur.step] ?? 0)
      || (!cur.fundingTxid && r.fundingTxid && r.step === cur.step)) byId.set(r.id, { ...r });
  }
  return [...byId.values()].sort((x, y) => renewalStartedAt(x.id) - renewalStartedAt(y.id));
}


export function slimArkForSync(s) {
  if (!s) return null;
  const HEAVY = ['bytes', 'destBytes', 'changeBytes', 'vtxoBytes', 'txHex', 'fundingTxHex', 'outputVtxos'];
  return {
    v: s.v, serverPubkey: s.serverPubkey, mailboxCheckpoint: s.mailboxCheckpoint, nextKeyIndex: s.nextKeyIndex, receiveAckTs: s.receiveAckTs,
    // Spent stubs keep old snapshots/mailbox messages from resurrecting coins.
    vtxos: (() => {
      // On the wire the bytes stay HEX for now: a device still on a build
      // that only reads hex would otherwise fail to decode every coin merged
      // from this one. Flip to base64 once builds before 2026-09-10 are gone.
      const live = (s.vtxos || []).filter((v) => v.state !== 'spent')
        .map((v) => (v.bytes ? { ...v, bytes: vtxoBytesToHex(v.bytes) } : v));
      const stubs = (s.vtxos || []).filter((v) => v.state === 'spent')
        .map((v) => ({ id: v.id, amountSat: v.amountSat, state: 'spent', keyIndex: v.keyIndex, expiryHeight: v.expiryHeight }));
      return [...live, ...stubs];
    })(),
    actions: (() => {
      const done = (s.actions || []).filter((a) => a.step === 'done');
      const core = done.filter((a) => ['board', 'offboard', 'exit'].includes(a.type))
        .map((a) => { const c = { ...a }; for (const k of HEAVY) delete c[k]; return c; });
      // Spends travel as SLIVERS — id, net amount, and which coins they
      // consumed. That last field is what lets ANOTHER device recognize a
      // vanished coin as this send rather than painting a red "spent on
      // another device" row beside the synced Sent movement (one spend was
      // showing twice, at input magnitude the second time).
      const spends = done.filter((a) => ['send', 'ln-pay'].includes(a.type))
        .map((a) => ({
          id: a.id, type: a.type, step: 'done', amountSat: a.amountSat,
          inputIds: [...new Set([...(a.inputIds || []), ...(a.parts || []).map((p) => p.inputId), a.inputId].filter(Boolean))],
        }));
      return [...core, ...spends];
    })(),
    // This device's own renewals, for DISPLAY elsewhere only — a phone that
    // knew nothing showed no "Renewal in progress" while the laptop's round
    // ran and the balance sat locked. No signing material: nothing but the
    // device that started a renewal can ever drive it. Terminal ones ride
    // too, so the finished telling replaces the in-progress one.
    renewals: (s.actions || []).filter((a) => a.type === 'refresh').map(renewalSliver),
    movements: (s.movements || []).map((m, i, arr) =>
      // Older rows only need to render a history line; the bolt11 (~400 chars
      // each) and preimage are what pushed snapshots past relay size limits.
      (arr.length - i <= 50 ? m : (({ invoice, preimage, ...rest }) => rest)(m))),
    gifts: s.gifts,
  };
}

// Merge two ark states so devices can't clobber each other through the sync
// snapshot: additive union of vtxos (a device keeps its own full copy, gains
// ones it lacks), actions/movements/gifts union by id, counters take the max
// (so two devices never reuse a key index).
export function mergeArkStates(a, b) {
  if (!a) return b;
  if (!b) return a;
  // never fuse state from two different ASPs
  if (a.serverPubkey && b.serverPubkey && a.serverPubkey !== b.serverPubkey) return a;
  const out = { ...a };
  // ADDITIVE union only: bring in vtxos this device is missing (the whole
  // point — board/change coins that live only where they were created), but
  // NEVER let a remote snapshot change the state of a vtxo we already track.
  // Spend detection is each device's own job via reconcile() against the
  // server (the authority), so a stale-or-wrong "spent" on one device can't
  // propagate and permanently poison the others. A newly-merged-in vtxo that
  // was actually spent elsewhere gets caught by the reconcile on next connect
  // / send-intent, exactly like any other drift.
  const vtxos = new Map((a.vtxos || []).map((v) => [v.id, { ...v }]));
  for (const rv of b.vtxos || []) if (!vtxos.has(rv.id)) vtxos.set(rv.id, { ...rv });
  out.vtxos = [...vtxos.values()];
  const unionById = (x = [], y = []) => {
    const ids = new Set(x.map((i) => i.id));
    return [...x, ...y.filter((i) => !ids.has(i.id))];
  };
  out.actions = unionById(a.actions, b.actions);
  // Union keeps the local copy of a movement forever — but a movement can be
  // ENRICHED after other devices synced it (the cooney rescue stamped
  // inputIds/unlockHash/fee onto its renewal movement post-hoc, and those
  // fields are what lets history exclude the matching "spent on another
  // device" rows). Adopt fields the local copy lacks; never overwrite ones
  // it has.
  const bM = new Map((b.movements || []).map((m) => [m.id, m]));
  const enriched = (a.movements || []).map((lm) => {
    const rm = bM.get(lm.id);
    if (!rm) return lm;
    const take = {};
    if (rm.inputIds != null && lm.inputIds == null) take.inputIds = rm.inputIds;
    if (rm.unlockHash != null && lm.unlockHash == null) take.unlockHash = rm.unlockHash;
    // a fee learned late (the rescue computed it from inputs − outputs)
    // upgrades a recorded zero — the row only renders when the fee is real
    if ((rm.feeSat || 0) > 0 && !(lm.feeSat > 0)) take.feeSat = rm.feeSat;
    if (rm.chainFeeSat != null && lm.chainFeeSat == null) take.chainFeeSat = rm.chainFeeSat;
    if (rm.serviceFeeSat != null && lm.serviceFeeSat == null) take.serviceFeeSat = rm.serviceFeeSat;
    // an LN-origin tag learned on another device (matched against the
    // registrar's receipts there) rides the snapshot to this one
    if (rm.viaLn && !lm.viaLn) { take.viaLn = true; if (rm.lnHash) take.lnHash = rm.lnHash; }
    return Object.keys(take).length ? { ...lm, ...take } : lm;
  });
  // Two devices (or the push and the poll, pre-guard) can each record the
  // SAME lightning payment under different movement ids — same preimage is
  // the same payment, keep the earliest telling of it.
  const seenPay = new Set();
  out.movements = unionById(enriched, b.movements)
    .sort((m, n) => (m.ts || 0) - (n.ts || 0))
    .filter((m) => {
      if (!m.type || !m.type.startsWith('ln-') || m.status !== 'complete') return true;
      const key = m.type + ':' + (m.paymentHash || m.preimage || m.invoice || m.id);
      if (seenPay.has(key)) return false;
      seenPay.add(key);
      return true;
    });
  const gifts = new Map((a.gifts || []).map((g) => [g.id, { ...g }]));
  for (const rg of b.gifts || []) {
    const lg = gifts.get(rg.id);
    if (!lg) gifts.set(rg.id, { ...rg });
    else { lg.claimed = lg.claimed || rg.claimed; lg.revoked = lg.revoked || rg.revoked; }
  }
  out.gifts = [...gifts.values()];
  // Targeted spend knowledge beats waiting for a reconcile: a completed
  // movement or done action that names its consumed inputs is direct
  // evidence those coins are gone. A device waking cold used to merge in
  // another device's renewal/send OUTPUT while still counting the consumed
  // inputs as spendable — the balance visibly ticked high, then dropped
  // when the reconcile caught up. (This is narrow, evidence-based state —
  // not the blanket remote-state adoption the rule above forbids.)
  const consumed = new Set();
  for (const x of out.actions || []) {
    if (x.step !== 'done') continue;
    for (const id of x.inputIds || []) consumed.add(id);
    for (const part of x.parts || []) if (part.inputId) consumed.add(part.inputId);
  }
  for (const m of out.movements || []) {
    if (m.status !== 'complete') continue;
    for (const id of m.inputIds || []) consumed.add(id);
  }
  for (const v of out.vtxos) if (v.state === 'spendable' && consumed.has(v.id)) v.state = 'spent';
  // The checkpoint is READING PROGRESS, not state: adopting a remote one
  // skips every message this device never processed — balance appears (the
  // vtxo unions in) but its receive movement and celebration never happen.
  // Keep the local checkpoint; re-read messages dedupe harmlessly.
  const pristine = !a.mailboxCheckpoint && !a.vtxos?.length && !a.movements?.length
    && !a.actions?.length && !a.scheduled?.length;
  // A manager's empty shell is not local history. Restore the snapshot's
  // cursor with its coins/history, just as the !a case above does, rather
  // than replaying the entire mailbox on a first login.
  out.mailboxCheckpoint = pristine ? b.mailboxCheckpoint || 0 : a.mailboxCheckpoint || 0;
  out.remoteRenewals = mergeRemoteRenewals(a, b);
  delete out.renewals; // a snapshot's own list, adopted above as remote
  out.nextKeyIndex = Math.max(a.nextKeyIndex || 1, b.nextKeyIndex || 1);
  // standing renewal orders registered on the other side (the worker's, say)
  out.scheduled = ArkManager.mergeScheduled(a.scheduled, b.scheduled);
  out.nextLnRecvIndex = Math.max(a.nextLnRecvIndex || 0, b.nextLnRecvIndex || 0);
  out.receiveAckTs = Math.max(a.receiveAckTs || 0, b.receiveAckTs || 0);
  out.serverPubkey = a.serverPubkey || b.serverPubkey || null;
  return out;
}

// Apply sync to a connected manager without restarting payment ceremonies.
// Drivers retain references across awaits, so preserve the state, coin and
// action objects they already hold while adding/enriching the remote records.
export function adoptArkSnapshot(manager, snapshot) {
  if (!snapshot || !manager.state) return false;
  const state = manager.state;
  const merged = mergeArkStates(state, snapshot);
  if (JSON.stringify(merged) === JSON.stringify(state)) return false;
  for (const field of ['vtxos', 'actions', 'movements', 'gifts']) {
    const existing = new Map((state[field] || []).map(item => [item.id, item]));
    merged[field] = (merged[field] || []).map(item => {
      const current = existing.get(item.id);
      return current ? Object.assign(current, item) : item;
    });
  }
  Object.assign(state, merged);
  manager._save();
  return true;
}

export function arkFeature(ctx) {
  const { h, ui, render, wallet, blankSend, fmtAmount, unitLabel, unitTag, copyBtn, toast, openExternal } = ctx;
  // Auto-pay budgets on offer: round money in the user's currency when that's
  // the unit on screen ($1, $5, $10, $100, kept as sats at today's rate),
  // round sats otherwise.
  const budgetChoices = () => {
    const rate = ctx.getUnit && ctx.getUnit() === 'fiat' && rateNow();
    return rate ? [1, 5, 10, 100].map((f) => Math.ceil((f / rate) * 1e8)) : [1000, 5000, 10000, 100000];
  };
  installArkWallet(wallet); // ark state storage lives outside the core wallet

  // Ride the encrypted sync snapshot so ark funds follow the seed across
  // devices. Board/change vtxo bytes exist only where they were created — a
  // second device can't otherwise see them. All devices share ONE replaceable
  // event slot (same seed -> same nostr key), so a naive publish can clobber
  // another device's coins. Anti-entropy fixes that: on receiving a snapshot,
  // union it with local; if it was missing coins we know (or brought coins we
  // didn't), re-publish the superset. The slot converges to the union no
  // matter who publishes when.
  wallet.registerCacheExtension({
    domain: 'ark', // published as its own sync slot — see splitSnapshotDomains
    mergeAlways: true, // load() is a commutative merge — apply older snapshots too
    syncOnly: true, // ark keeps its own store; the local cache blob needn't carry a copy
    save: () => {
      const cfg = getArkConfig();
      const s = cfg && wallet.loadArkState(cfg.ark);
      // tag the snapshot with the ASP it belongs to (see load())
      return s ? { arkState: slimArkForSync(s), arkServer: wallet._arkNs(cfg.ark) } : {};
    },
    load: (d) => {
      if (!d.arkState) return;
      const cfg = getArkConfig();
      if (!cfg) return;
      if (d.arkServer && d.arkServer !== wallet._arkNs(cfg.ark)) return;
      // A snapshot from an older build carries no tag, so the tag alone can't
      // be trusted — ask the vtxos who cosigned them. If they belong to a
      // different ASP (or we can't yet prove they belong to this one), park
      // the snapshot under its real owner instead of merging it in. Merging
      // blind is exactly how another server's balance appears here.
      const owner = d.arkState.serverPubkey || wallet._arkVtxoOwner(d.arkState);
      const mine = (ark && ark.info && ark.info.serverPubkey)
        || (wallet.loadArkState(cfg.ark) || {}).serverPubkey || null;
      if (owner && owner !== mine) {
        try {
          const key = wallet._arkHoldKey(owner);
          wallet._arkStore.set(key, mergeArkStates(wallet._arkStore.get(key), { ...d.arkState, serverPubkey: owner }));
        } catch {}
        // `mine` is null on a FRESH restore (no local state, not yet
        // connected), so even our own snapshot lands in the hold. Connecting
        // is what resolves it: the manager learns the server's pubkey and
        // adopts the held state if it matches — a seed imported on a new
        // device would otherwise show no ark balance until some manual poke.
        if (!mine) setTimeout(() => maybeInitArk(), 0);
        return;
      }
      const local = wallet.loadArkState(cfg.ark);
      const merged = mergeArkStates(local, d.arkState);
      // Every boot replays the sync slot, and on a converged slot the union
      // brings nothing — not worth rewriting ~1 MB of state or re-adopting
      // it into the manager (profiled at ~200ms per replay, twice per boot).
      // Bytes decide: unchanged means it serializes to what's already stored.
      let changed = true;
      try { changed = JSON.stringify(merged) !== JSON.stringify(local); } catch {}
      if (changed) wallet.saveArkState(merged, cfg.ark);
      const mergedN = (merged.vtxos || []).length;
      const remoteN = (d.arkState.vtxos || []).length;
      // We know vtxos this snapshot lacked — push our superset back up so the
      // sender (and the shared slot) learns them. Guarded by mergedN>remoteN so
      // it can't loop once every device has converged to the union.
      if (mergedN > remoteN) { try { wallet.saveCache(); } catch {} }
      // maybeInitArk deliberately does nothing when connected. Update that
      // manager directly or the newly synced change/history stays invisible
      // until reload, even though storage already contains the right balance.
      if (ark) { if (changed) adoptArkSnapshot(ark, merged); }
      else if (mergedN) setTimeout(() => maybeInitArk(), 0);
    },
  });

  // One manager per open wallet; null when Ark is off in Settings, watch-only,
  // or not yet dialed (lazy: fresh wallets connect on first use).
  let ark = null;
  // The same manager the moment its own init is done (server info, tip,
  // persisted coins) — before the Nostr snapshot restore that `ark` also
  // waits for, which can take ten seconds on a slow relay/Blossom day. For
  // READING only: the pages price and label coins from it; anything that
  // acts (a renewal, an exit) still waits for `ark`.
  let arkInited = null;
  const arkView = () => ark || arkInited;
  // An amount in bitcoin terms whatever the display unit: sats, or BTC when
  // that is the unit chosen — never fiat. A co-operative exit moves coins,
  // and the number on its button is the coins' own.
  const fmtNative = (sat) => (unitLabel() === 'BTC' ? fmtBtc(sat) + ' BTC' : fmtSats(sat) + ' sats');
  // The last server info and chain tip seen, per server, so the first paint
  // after a refresh shows the real renewal price and expiries instead of
  // "free" and "—" for the half second the info call takes.
  const ARK_INFO_KEY = 'btc-wallet-arkinfo:';
  function cachedArkInfo(url) {
    try { return url ? JSON.parse(localStorage.getItem(ARK_INFO_KEY + url) || 'null') : null; } catch { return null; }
  }
  function rememberArkInfo(url, info, tip) {
    try {
      if (!url || !info) return;
      // no tip yet (right after init): keep the last one seen, dated as it was
      const prev = tip ? null : cachedArkInfo(url);
      localStorage.setItem(ARK_INFO_KEY + url, JSON.stringify(tip ? { info, tip, at: Date.now() } : { info, tip: (prev && prev.tip) || 0, at: (prev && prev.at) || Date.now() }));
    } catch {}
  }
  // the tip, live or estimated from the last one seen (a block per ten minutes)
  function arkTipNow(mgr) {
    if (mgr && mgr._tipH) return mgr._tipH;
    const c = cachedArkInfo((getArkConfig() || {}).ark);
    return c && c.tip ? c.tip + Math.floor((Date.now() - (c.at || Date.now())) / 600_000) : 0;
  }
  let arkTimer = null;
  let arkConnectPromise = null;
  let arkInitGen = 0; // guards against a stale init() resolving after a wallet switch

  function stopArk() {
    // land any debounced ark write BEFORE bumping the gen (which would make the
    // old manager's flusher a no-op), then drop the stale flushers
    for (const f of [...arkPersistFlushers]) { try { f(); } catch {} }
    arkPersistFlushers.clear();
    arkInitGen++;
    lastAutoInit = 0;
    if (arkTimer) clearInterval(arkTimer);
    arkTimer = null;
    if (ark) ark.stopMailboxStream();
    stopNwcFunding();
    for (const timer of arkLnTimers.values()) clearInterval(timer);
    arkLnTimers.clear();
    clearTimeout(lnTagT);
    lnTagSeen = -1;
    ark = null;
    arkInited = null;
    arkConnectPromise = null;
    // The renewal warning describes the coins of the wallet we're leaving.
    // Switching accounts used to carry it onto the next one — with the old
    // wallet's amount and deadline, over the new wallet's balance — and the
    // 30-minute throttle then kept it there. Both reset with the manager;
    // the next connect's first tick re-decides for the wallet now open.
    arkRenewWarn = null;
    arkAutoRefreshAt = 0;
    rescuedServers = false;
  }

  function arkAvailable() {
    return !!getArkConfig() && !wallet.watchOnly && !!wallet.account;
  }

  function arkWanted() {
    const cfg = getArkConfig();
    const st = cfg && wallet.loadArkState(cfg.ark);
    return !!(st && ((st.vtxos || []).length || (st.movements || []).length
      || (st.actions || []).some((a) => !['done', 'failed'].includes(a.step))));
  }

  function initArk() {
    stopArk();
    ui.arkError = '';
    // The ark store is IndexedDB — asynchronous to OPEN, synchronous to read
    // once it has. A boot that beats it open reads no state at all: no
    // Spending balance, no Spending history, and nothing here that looks
    // worth connecting for. Wait for it and run again, so what the store
    // holds is on screen the moment it can be.
    const store = wallet._arkStore;
    if (store && !store.ready) {
      store.open().then(() => { ctx.forgetAmountAnim && ctx.forgetAmountAnim(); render(); initArk(); }).catch(() => {});
      return;
    }
    if (arkAvailable() && arkWanted()) { lastAutoInit = Date.now(); connectArk().then(() => rescueOtherServers()).catch(() => {}); }
  }

  // Automatic re-inits (a synced snapshot arriving) must not restart a
  // connection that is already in flight, or retry in a tight loop when the
  // server is unreachable: each one calls stopArk() first, so the settings
  // card's "connecting" indicator flickers on every snapshot. User-driven
  // calls to initArk() stay immediate.
  let lastAutoInit = 0;
  // A payment can land with a server this wallet is NOT connected to: an
  // invoice minted for its coinos name by the background answerer before a
  // switch, or by another device still on the old server. Once per session,
  // every other server this wallet holds state with gets a short visit — its
  // own manager, a receive rescan, a sync to claim — and a toast says what
  // arrived and where. The coins stay with that server until a switch back.
  let rescuedServers = false;
  async function rescueOtherServers() {
    if (rescuedServers || wallet.watchOnly) return;
    rescuedServers = true;
    const cur = getArkConfig();
    if (!cur) return;
    for (const p of arkPresets(getNetwork())) {
      if (!p.ark || p.ark === cur.ark || p.id === 'custom' || p.id === 'off') continue;
      if (!wallet.loadArkState(p.ark)) continue; // never used that server
      try {
        const mgr = new ArkManager({
          account: wallet.account(),
          storage: {
            load: () => wallet.loadArkState(p.ark),
            adopt: (serverPubkey) => wallet.adoptArkState(serverPubkey, p.ark),
            save: (s) => { wallet.saveArkState(mergeArkStates(s, wallet.loadArkState(p.ark)), p.ark); },
          },
          arkUrl: p.ark, esploraUrl: p.esplora, network: getNetwork(), honorsExpired: !!p.honorsExpired,
        });
        await mgr.init();
        const done = () => (mgr.state.movements || []).filter((m) => m.type === 'ln-receive' && m.status === 'complete');
        const before = done().length;
        await mgr.sync(); // rescans receives and drives the claims
        await new Promise((r) => setTimeout(r, 2500));
        await mgr.sync(); // a claim takes more than one step
        const got = done().slice(before).reduce((n, m) => n + (m.amountSat || 0), 0);
        if (got > 0) toast(t('arkOtherServerReceipt', { amount: fmtSats(got), server: p.label.replace(/ \(.*\)$/, '') }), 9000);
      } catch (e) { console.warn('ark: rescue on ' + p.ark + ' failed', e); }
    }
  }
  function maybeInitArk() {
    if (ark || arkConnectPromise) return;
    if (Date.now() - lastAutoInit < 20000) return;
    // A fresh snapshot may be held under its server pubkey, so arkWanted()
    // cannot see it until the handshake identifies the server and adopts it.
    if (arkAvailable()) { lastAutoInit = Date.now(); connectArk().catch(() => {}); }
  }

  // Operator console rescue for a round participation stranded server-side
  // 'unclaimed' (its action lost client-side): arkRescue('<unlockHash>',
  // ['<vtxoId>', ...]) from devtools, ids supplied from the server's DB.
  if (typeof globalThis !== 'undefined') {
    globalThis.arkRescue = async (unlockHash, inputIds) => {
      const mgr = await connectArk();
      return mgr.rescueParticipation(unlockHash, inputIds);
    };
  }

  function connectArk() {
    if (ark) return Promise.resolve(ark);
    if (arkConnectPromise) return arkConnectPromise;
    if (!arkAvailable()) return Promise.reject(new Error(t('arkNotConnected')));
    const cfg = getArkConfig();
    const gen = arkInitGen;
    // Persisting ark state is EXPENSIVE — a JSON.parse of the stored state, a
    // merge over every vtxo + movement, a JSON.stringify, a synchronous
    // localStorage write, then saveCache(). The manager fires _save() on every
    // mutation, and a boot reconcile mutates dozens of times in a burst —
    // that's the main-thread stall that made a mouse drag lurch right after a
    // refresh. The in-memory state is always current and every live READ goes
    // to it (arkStateNow returns ark.state); only the disk copy has to catch
    // up, so coalesce the writes: idle → write now, mid-burst → one write when
    // it quiets (capped so a steady stream still lands). Flushed on hide.
    let persistPending = null, persistT = 0, persistLastAt = 0, persistFirstAt = 0;
    const flushPersist = () => {
      clearTimeout(persistT); persistT = 0; persistFirstAt = 0;
      if (!persistPending || gen !== arkInitGen) { persistPending = null; return; }
      const s = persistPending; persistPending = null; persistLastAt = Date.now();
      wallet.saveArkState(mergeArkStates(s, wallet.loadArkState(cfg.ark)), cfg.ark);
      try { wallet.saveCache(); } catch {}
    };
    arkPersistFlushers.add(flushPersist);
    const mgr = new ArkManager({
      account: wallet.account(),
      storage: {
        load: () => wallet.loadArkState(cfg.ark),
        adopt: (serverPubkey) => wallet.adoptArkState(serverPubkey, cfg.ark),
        // merge-on-save: the MANAGER is authoritative for the state of the
        // vtxos it tracks (its reconcile/spends must persist), so its state
        // is the first arg and wins; storage only contributes vtxos the
        // manager hasn't loaded yet (a snapshot merged in from another device
        // between init and the next reinit). saveCache() then carries ark
        // state into the snapshot -> debounced nostr publish.
        save: (s) => {
          persistPending = s;
          const now = Date.now();
          if (!persistFirstAt) persistFirstAt = now;
          // a lone change after a quiet spell writes immediately; a burst
          // coalesces into one write ~200ms after it settles, but never waits
          // more than ~800ms so a steady stream still lands
          if (now - persistLastAt > 1000 && !persistT) { flushPersist(); return; }
          if (now - persistFirstAt > 800) { flushPersist(); return; }
          clearTimeout(persistT);
          persistT = setTimeout(flushPersist, 200);
        },
      },
      arkUrl: cfg.ark,
      esploraUrl: cfg.esplora,
      network: getNetwork(),
      honorsExpired: !!cfg.honorsExpired,
      // the wallet's own tx table as a second witness for confirmations —
      // its data source is user-configurable and often healthier than the
      // ark preset's esplora from this device
      statusHint: (txid2) => {
        const tx = (wallet.txs || []).find((t2) => t2.txid === txid2);
        return tx && tx.confirmed ? { confirmed: true, block_height: tx.blockHeight || NaN } : null;
      },
      onUpdate: (m) => { if (gen !== arkInitGen) return; maybeAutoSelectSpending(); scheduleLnTag(m); render(); },
    });
    ui.arkError = '';
    // Open the server connection while Nostr restores, but do not replay the
    // mailbox before the snapshot's history and cursor have arrived.
    const restored = Promise.resolve(wallet.nostrRestoreReady || wallet.syncFromNostr?.()).catch(() => false);
    const inited = mgr.init().then(() => {
      if (gen !== arkInitGen) return;
      arkInited = mgr; // readable now; `ark` (and the mailbox) wait for the snapshot
      rememberArkInfo(cfg.ark, mgr.info, mgr._tipH);
      render();
    });
    // The tip: expiries and exit costs are judged against it, and init alone
    // never asks for it (the first sync does, after the snapshot gate). Ask
    // now, off the connect path, and remember it for the next refresh.
    inited.then(() => mgr._tipMemo()).then(() => {
      if (gen !== arkInitGen || !mgr._tipH) return;
      rememberArkInfo(cfg.ark, mgr.info, mgr._tipH);
      render();
    }).catch(() => {});
    arkConnectPromise = Promise.all([inited, restored]).then(() => {
      if (gen !== arkInitGen) throw new Error('superseded'); // wallet switched mid-connect
      ark = mgr;
      // Sync may have arrived while init awaited the server handshake.
      adoptArkSnapshot(mgr, wallet.loadArkState(cfg.ark));
      // Boards that died before funding (a failed tx build, a closed tab)
      // used to linger at 'created' forever — and an in-flight-looking
      // action blocks auto-renewal. Anything unfunded after an hour is a
      // stub, not a plan; the id carries its birth time.
      {
        let swept = false;
        for (const a of mgr.state.actions || []) {
          if (a.type !== 'board' || a.fundingTxid || ['done', 'failed'].includes(a.step)) continue;
          const ts = Number((a.id || '').split('-')[1]) || 0;
          if (ts && Date.now() - ts > 3600_000) { a.step = 'failed'; a.error = a.error || 'never funded'; swept = true; }
        }
        if (swept) mgr._save();
      }
      announceArkAddress(mgr); // ark zaps: tell nostr where our mailbox lives
      startNwcFunding(mgr);    // NWC bridge: honor funding requests within the allowance
      // Publish this device's ark state to its per-device sync slot on connect.
      // Cross-device sync only re-published on a state CHANGE (a send/board), so
      // an idle device never shared its coins — another device would never see
      // them. Publishing on connect guarantees every device's ark balance
      // reaches the relay (and gets merged) without needing a transaction first.
      if (mgr.state && (mgr.state.vtxos || []).length) { try { wallet.saveCache(); } catch {} }
      // A failed mailbox read must not starve the action drives: boards and
      // refreshes progress on chain state alone, so push them even when the
      // sync itself errored.
      let ticking = null;
      const tick = () => ticking || (ticking = mgr.sync().catch(async () => {
        // Even when mailbox catch-up fails, independently check stale coins
        // and advance recoverable local actions.
        await mgr.reconcile().catch(() => {});
        await mgr.resumePending().catch(() => {});
      })
        .then(() => driveExits(mgr)).catch(() => {})
        .then(() => { if (ark === mgr) return maybeAutoRefresh(mgr); }).catch(() => {})
        .then(() => { if (ark === mgr) return maybeAutoWithdraw(mgr); }).catch(() => {})
        .finally(() => { ticking = null; }));
      // sync() already reconciles on its first pass. Start the live stream
      // afterwards, at the caught-up cursor: running both together replayed
      // the backlog one message/render at a time alongside the batch read.
      tick().finally(() => { if (ark === mgr) mgr.startMailboxStream(); });
      mergeBgWorkerState(mgr).catch(() => {}); // absorb what the SW did while we were closed
      // Receives arrive in real time over the mailbox stream; the poll is the
      // fallback and what drives in-flight boards/refreshes forward.
      scheduleLnTag(mgr); // receives that landed while this device was closed
      arkTimer = setInterval(() => { if (ark === mgr) tick(); }, getNetwork() === 'regtest' ? 5000 : 30000);
      render();
      return mgr;
    }).catch((e) => {
      if (gen === arkInitGen) { ui.arkError = e.message; render(); }
      throw e;
    }).finally(() => { if (gen === arkInitGen) arkConnectPromise = null; });
    render();
    return arkConnectPromise;
  }

  // The current ark state for READ-ONLY rendering: the live manager if it's
  // connected, else the persisted state straight from storage. Lets the
  // balance and history icons paint immediately on refresh instead of
  // flickering (empty → populated) while the manager connects asynchronously.
  function arkStateNow() {
    if (ark && ark.state) return ark.state;
    // Read persisted state whenever Ark is configured for this network — even
    // watch-only (seed not loaded this session): the balance/history should
    // show read-only, just like the on-chain balance does. Acting on it
    // (send/exit) still requires the seed and is gated separately.
    const cfg = getArkConfig();
    if (!cfg) return null;
    return wallet.loadArkState(cfg.ark);
  }

  // Which receives actually arrived over Lightning? A payment to the user's
  // [email protected] address settles on the registrar's node and lands here as
  // an ordinary arkoor from its float wallet — the mailbox protocol carries
  // no memo, so the movement alone can't name the rail the sender used. The
  // registrar keeps a receipt per LN settlement it forwarded; matching those
  // against receive movements (exact amount, delivery within a couple of
  // minutes) marks the row viaLn so it wears the ⚡ the sender expects.
  // Best-effort and cosmetic: a rare amount+time collision only mislabels an
  // icon. The receipt's payment hash is stamped on the matched movement so a
  // receipt never claims a second row on later passes.
  let lnTagBusy = false, lnTagT = 0, lnTagSeen = -1;
  async function tagLnReceives(mgr) {
    if (lnTagBusy) return;
    // nothing a receipt could match (the registrar keeps them 7 days) —
    // don't spend a signed fetch on every boot of a quiet wallet
    if (!(mgr.state.movements || []).some((m) => m.type === 'receive' && m.status === 'complete'
        && !m.viaLn && (m.ts || 0) > Date.now() - 7 * 86400_000)) return;
    lnTagBusy = true;
    try {
      const receipts = await Promise.resolve(ctx.hook('namesLnReceipts')).catch(() => null);
      if (!receipts || !receipts.length || ark !== mgr || !mgr.state) return;
      const twins = lnFoldedIds(mgr.state.movements);
      const moves = (mgr.state.movements || [])
        .filter((m) => m.type === 'receive' && m.status === 'complete' && !twins.has(m.id));
      const used = new Set(moves.filter((m) => m.lnHash).map((m) => m.lnHash));
      let changed = false;
      for (const r of receipts) {
        if (r.hash && used.has(r.hash)) continue;
        let best = null;
        for (const m of moves) {
          if (m.viaLn || m.amountSat !== r.sat) continue;
          const dt = Math.abs((m.ts || 0) - r.ts);
          if (dt > 180_000) continue;
          if (!best || dt < Math.abs((best.ts || 0) - r.ts)) best = m;
        }
        if (!best) continue;
        best.viaLn = true;
        if (r.hash) { best.lnHash = r.hash; used.add(r.hash); }
        changed = true;
      }
      if (changed) mgr._save();
    } finally { lnTagBusy = false; }
  }
  // Fires off onUpdate, so gate on the thing that actually warrants a fetch:
  // the count of untagged receives changed (a new receive landed, or a
  // snapshot brought some in). Debounced so a catch-up burst asks once.
  function scheduleLnTag(mgr) {
    const n = (mgr.state.movements || []).reduce((c, m) =>
      c + (m.type === 'receive' && m.status === 'complete' && !m.viaLn ? 1 : 0), 0);
    if (n === lnTagSeen) return;
    lnTagSeen = n;
    clearTimeout(lnTagT);
    lnTagT = setTimeout(() => { if (ark === mgr) tagLnReceives(mgr).catch(() => {}); }, 2000);
  }

  // A wallet that opens onto "Savings: 0" while its money sits in Spending
  // is answering the wrong question — a stale device-global selection (or
  // the default) shouldn't hide the balance. One shot per wallet open; any
  // manual switch afterwards is respected.
  let _autoSelected = false;
  function maybeAutoSelectSpending() {
    if (_autoSelected || wallet.watchOnly) return;
    // The user beat us to it: they've already scrolled/tapped/flicked to an
    // account this session. The "open onto Spending when Savings is empty"
    // convenience only applies to the UNTOUCHED open — arriving late (when
    // the ark balance finally syncs, a second after a refresh) and yanking
    // the card away from the one they just chose is the exact opposite of
    // convenient. Consume the one-shot so it can't fire behind them.
    if (ui.accountUserChosen) { _autoSelected = true; return; }
    const b = arkBalance();
    if (!b || b.spendableSat + b.pendingSat <= 0) return;
    _autoSelected = true;
    if ((wallet.spendable || 0) === 0 && ctx.getAccount() === 'savings') {
      ui.navAnimSkip = true; // a correction at open paints, never slides
      ctx.setAccount('spending'); // renders synchronously; the flip is decided here
      ui.navAnimSkip = false; // don't let the one-shot eat the next real navigation
    }
  }

  function arkBalance() {
    const s = arkStateNow();
    if (!s) return null;
    // coins in another device's renewal count as pending here, as they do there
    const busy = new Set(remoteRenewalsInFlight(s).flatMap((r) => r.inputIds || []));
    const sum = (st) => (s.vtxos || []).filter((v) => !v.expiryRejected && (st === 'spendable'
      ? v.state === 'spendable' && !busy.has(v.id)
      : v.state === st || (st === 'pending' && v.state === 'spendable' && busy.has(v.id)))).reduce((n, v) => n + v.amountSat, 0);
    const boardingSat = (s.actions || [])
      .filter((a) => a.type === 'board' && a.fundingTxid && !['done', 'failed'].includes(a.step))
      .reduce((n, a) => n + (a.amountSat - a.feeSat), 0);
    return { spendableSat: sum('spendable'), pendingSat: sum('pending'), boardingSat };
  }

  function renewingSat() {
    const s = arkStateNow();
    const ids = new Set((s?.actions || []).filter((a) => a.type === 'refresh' && !['done', 'failed'].includes(a.step)).flatMap((a) => a.inputIds || []));
    const remote = new Set(s ? remoteRenewalsInFlight(s).flatMap((r) => r.inputIds || []) : []);
    return (s?.vtxos || []).filter((v) => (v.state === 'pending' && ids.has(v.id)) || (v.state === 'spendable' && remote.has(v.id)))
      .reduce((n, v) => n + v.amountSat, 0);
  }

  // An ark address in the send form signals a send is coming: verify our
  // spendable vtxos against the server now, so a stale one (same seed active
  // elsewhere, restored state) is dropped before coin selection instead of
  // failing at cosign time. Throttled — this fires from the render path.
  let arkReconciledAt = 0;
  function maybeReconcile() {
    if (Date.now() - arkReconciledAt < 30_000) return;
    arkReconciledAt = Date.now();
    connectArk().then((mgr) => mgr.reconcile()).catch(() => {});
  }

  function arkSendReview() {
    if (ui.arkSent) {
      return h(
        'div',
        {
          class: 'card col',
          style: 'align-items:center;text-align:center;gap:14px;cursor:pointer;padding:48px 20px',
          onClick: () => { ui.arkSent = null; ui.send = blankSend(); render(); },
        },
        h('div', { class: 'check-badge' }, '✓'),
        h('h2', { style: 'margin:0' }, t('arkSentTitle')),
        h('div', { class: 'amount-neg', style: 'font-size:18px' }, fmtAmount(ui.arkSent.amountSat) + ' ' + unitLabel()),
        h('div', { class: 'small muted' }, t('tapToProceed'))
      );
    }
    const a = ui.arkSend;
    const row = (k, v) => h('div', { class: 'row between' }, h('span', { class: 'small muted' }, k), h('span', { class: 'small' }, v));
    return h(
      'div',
      { class: 'card col', style: 'gap:12px' },
      h('h3', {}, t('arkSendTitle')),
      row(t('lnPayAmount'), fmtAmount(a.amountSat) + ' ' + unitLabel()),
      row(t('arkPayTo'), a.via
        ? h('span', { class: 'row gap6', style: 'align-items:center' }, a.via.pk ? ctx.hook('avatarNode', a.via.pk) : null, a.via.name)
        : shortAddr(a.address, 14)),
      row(t('networkFee'), t('arkNoFee')),
      ui.sendError ? h('div', { class: 'notice err' }, ui.sendError) : null,
      // An amount Spending can't cover isn't a dead end while Savings can:
      // the Send button becomes the door to the board panel, prefilled with
      // what this payment needs — instead of letting the send run into an
      // "insufficient ark balance" wall.
      h('div', { class: 'row gap6' },
        h('button', { class: 'btn-ghost', onClick: () => { ui.arkSend = null; ui.sendError = ''; render(); } }, t('back')),
        ui.busy
          ? h('button', { class: 'btn-primary grow', disabled: true }, h('span', { class: 'spinner' }))
          : a.amountSat > (arkBalance()?.spendableSat || 0) && wallet.spendable > 0 && !wallet.watchOnly
            ? h('button', { class: 'btn-primary grow', onClick: () => {
                const need = a.amountSat;
                ui.arkSend = null; ui.sendError = '';
                ctx.hook('arkOfferBoard', need);
              } }, t('zapBoardBtn'))
            : h('button', { class: 'btn-primary grow', onClick: doArkSend }, t('arkSendBtn'))
      )
    );
  }

  async function doArkSend() {
    const a = ui.arkSend;
    ui.busy = true; ui.sendError = ''; render();
    try {
      const mgr = await connectArk();
      await mgr.send(a.address, a.amountSat);
      ui.arkSent = { amountSat: a.amountSat };
      ui.arkSend = null;
      ui.send = blankSend(); // the next send starts empty, however this card is left
    } catch (e) {
      ui.sendError = e.message;
    }
    ui.busy = false; render();
  }

  // ---- lightning via the ASP (captaind pays/holds invoices natively) -------
  // One poll timer per in-flight lightning action; cleared on settle.
  const arkLnTimers = new Map();
  function stopArkLnPoll(id) {
    const timer = arkLnTimers.get(id);
    if (timer) { clearInterval(timer); arkLnTimers.delete(id); }
  }
  function pollArkLn(id, onSettle) {
    stopArkLnPoll(id);
    // One held call brings the settlement the moment the server has it;
    // the interval below is the fallback pace if that call breaks.
    if (ark) {
      ark.awaitLnPay(id).then((a) => {
        if (a && ['done', 'failed'].includes(a.step) && arkLnTimers.has(id)) {
          stopArkLnPoll(id);
          onSettle(a);
        }
        render();
      }).catch(() => {});
    }
    arkLnTimers.set(id, setInterval(async () => {
      if (!ark) return;
      const a = await ark.driveLn(id).catch(() => null);
      if (a && ['done', 'failed'].includes(a.step)) {
        stopArkLnPoll(id);
        onSettle(a);
      }
      render();
    }, 2500));
  }

  // ---- background NWC mirror ---------------------------------------------
  // The service worker answers wallet-connect requests while the app is
  // closed, spending the SAME ark balance the app does. The mirror is the
  // full manager state plus the chain-3 keys for its live coins and a window
  // of upcoming change indices (the worker cannot derive). nwc.js decides
  // WHEN to mirror (background answering on) and supplies the connections.
  // connections/offer belong to the nwc feature; when it isn't the caller
  // (an auto-withdraw setting changed, say) carry forward what's mirrored
  // rather than blanking someone's wallet connections.
  async function writeBgMirror(connections, offer, prefs) {
    const cfg = getArkConfig();
    if (!cfg || !ark || !ark.info || !ark.state) return;
    const prev = await loadBg(wallet._cacheKey());
    if (connections === undefined) connections = (prev && prev.connections) || [];
    if (offer === undefined) offer = (prev && prev.offer) || null;
    if (prefs === undefined) prefs = (prev && prev.prefs) || undefined;
    const rec = buildBg({
      ark: { arkUrl: cfg.ark, esploraUrl: cfg.esplora, network: getNetwork(), serverPubkey: ark.info.serverPubkey, honorsExpired: !!cfg.honorsExpired },
      mgrState: ark.state,
      custody: getCustody(),
      keyFor: (chain, i) => hex.encode(ark.account.deriveChild(chain).deriveChild(i).privateKey),
      connections,
      offer,
      autowithdraw: await awMirror(prev),
    });
    if (prev) rec.spends = prev.spends; // the worker's log survives rewrites
    if (prefs) rec.prefs = prefs; // notification choices the worker honours
    await saveBg(wallet._cacheKey(), rec);
    await disarmSiblingRecords(wallet._cacheKey(), rec).catch(() => {});
  }

  // On connect, fold whatever the worker did while we were closed back into
  // the live state: its spent flips and change vtxos merge in (the additive
  // merge never resurrects anything reconcile() disproves), its key
  // allocations advance ours, and its in-flight ln actions become resumable.
  async function mergeBgWorkerState(mgr) {
    const rec = await loadBg(wallet._cacheKey());
    if (!rec) return;
    absorbBgAutoWithdraw(rec);
    if (rec.v < 3) {
      await sweepLegacyPouch(rec).catch((e) => console.warn('ark: pouch sweep failed', e.message));
      return;
    }
    if (!rec.mgr) return;
    const merged = mergeArkStates(mgr.state, rec.mgr);
    // the worker's view of OUR vtxos is newer for anything it spent
    const workerState = new Map((rec.mgr.vtxos || []).map((v) => [v.id, v.state]));
    for (const v of merged.vtxos) {
      if (workerState.get(v.id) === 'spent') v.state = 'spent';
    }
    merged.nextKeyIndex = Math.max(merged.nextKeyIndex || 1, rec.mgr.nextKeyIndex || 1);
    mgr.state = merged;
    mgr._save();
    await mgr.reconcile().catch(() => {});
    await mgr.resumePending().catch(() => {});
  }

  // A leftover chain-6 pouch from before whole-balance background spending:
  // sweep its coins home using the keys stored in the record itself, then
  // let the next mirror write replace it.
  async function sweepLegacyPouch(rec) {
    if (!(rec.vtxos || []).some((v) => (v.state || 'spendable') === 'spendable')) return;
    const cfg = getArkConfig();
    const mgr = await connectArk();
    const shim = { deriveChild: () => ({ deriveChild: (i) => ({ privateKey: hex.decode(rec.keys[String(i)] || rec.keys['0']) }) }) };
    let state = {
      v: 1, serverPubkey: rec.ark?.serverPubkey || null, mailboxCheckpoint: 0,
      nextKeyIndex: rec.nextKeyIndex || 20,
      vtxos: (rec.mgr?.vtxos || rec.vtxos || []).map((v) => ({ ...v, state: v.state || 'spendable' })),
      actions: [], movements: [],
    };
    const pm = await new ArkManager({
      account: shim,
      storage: { load: () => state, save: (s2) => { state = s2; } },
      arkUrl: cfg.ark, esploraUrl: cfg.esplora, network: getNetwork(), honorsExpired: !!cfg.honorsExpired,
    }).init();
    const dest = mgr.address();
    for (let guard = 0; guard < 30; guard++) {
      const v = (pm.state.vtxos || []).find((x) => x.state === 'spendable');
      if (!v) break;
      await pm.send(dest, v.amountSat);
    }
    await saveBg(wallet._cacheKey(), { ...rec, vtxos: [], mgr: state, sweptAt: Date.now() });
  }

  // Pay a bolt11 with no UI at all — used by the NWC wallet service. Same
  // routing as the interactive path: the cheaper bridge first, the ASP's own
  // lightning-send as fallback. Resolves { preimage, feeSat, amountSat }.
  async function payInvoiceHeadless(invoice, { maxAmountSat } = {}) {
    const dec = maybeBolt11(invoice);
    if (!dec) throw new Error('not a bolt11 invoice');
    if (!dec.amountSat) throw new Error('zero-amount invoices are not supported');
    if (maxAmountSat && dec.amountSat > maxAmountSat) {
      throw new Error(`amount ${dec.amountSat} exceeds the limit of ${maxAmountSat} sat`);
    }
    const mgr = await connectArk();
    // The sync merge is additive, so a vtxo spent on another device can sit
    // in local state looking spendable until someone checks. The interactive
    // send path reconciles on intent; this headless path must too, or an NWC
    // payment picks the stale coin and the ASP rejects it ("state: spent").
    await mgr.reconcile().catch(() => {});

    // Up to three attempts: each failure refunds in full, and the next try
    // brings one extra sat of routing budget for liquidity that shifted
    // between the quote and the send.
    let last = null;
    for (let attempt = 0; attempt < 3; attempt++) {
      const routingFeeSat = attempt === 0 ? undefined : (last?.routingFeeSat ?? 0) + 1;
      const id = await mgr.payLnInvoice(invoice, { routingFeeSat });
      await mgr.awaitLnPay(id).catch(() => {});
      for (let i = 0; i < 60; i++) {
        const a = mgr.lnAction(id);
        if (!a || ['done', 'failed'].includes(a.step)) break;
        await new Promise((r) => setTimeout(r, 2000));
        await mgr.driveLn(id).catch(() => {});
      }
      const a = mgr.lnAction(id);
      if (a && a.step === 'done') return { preimage: a.preimage, feeSat: a.feeSat, amountSat: a.amountSat };
      last = a;
      if (a && a.step === 'failed' && !lnRetryable(a)) break;
      if (!a || a.step !== 'failed') break; // still pending after 2 min — don't double-pay
    }
    throw new Error(last?.error || last?.lastError || 'payment did not complete');
  }

  // A bolt11 lands in Send (via the swaps feature's delegation hook, or
  // directly when swaps is absent): take over when the ark balance can
  // plausibly cover it, else decline so the Boltz path handles it.
  // Lightning leaves Spending, whichever balance is on screen. With Savings
  // showing, ask before going on — a person looking at one balance and
  // charged from the other read it as the wrong wallet paying. Autopay
  // (a trusted, budgeted code) never asks: nobody is looking.
  function startArkLnPay(invoice, meta) {
    const dec = maybeLnInvoice(invoice);
    if (!dec || !arkAvailable() || wallet.watchOnly) return false;
    if (ctx.getAccount() === 'savings' && !(meta && meta.autopay) && !ui.arkLnFromSavingsOk) {
      ui.arkLnFromSavings = { invoice, meta: meta || null, amountSat: dec.amountSat };
      ui.sendError = '';
      render();
      return true;
    }
    ui.arkLnFromSavingsOk = false;
    const s = arkStateNow();
    // Coverage by SUM: multi-input pays gather up to 24 coins, so judging by
    // the single largest coin declined invoices the wallet could pay — a
    // tester holding 204+29 sats pasted a ~220-sat invoice and nothing
    // happened at all. Fees are the quote's business, not this gate's.
    const sum = (state) =>
      (s ? (s.vtxos || []) : []).filter((v) => v.state === state).reduce((n, v) => n + v.amountSat, 0);
    // pending funds count for the take-over decision: an in-flight payment or
    // revocation frees them in seconds
    if (sum('spendable') < (dec.amountSat || 1) && sum('pending') < (dec.amountSat || 1)) return false;
    // Will this pay itself (an armed budget that covers it)? Known before the
    // quote — from the invoice amount and the stored budget — so the view can
    // go straight to a paying screen and never flash the review card first.
    const armedBudget = meta && meta.autopay && meta.budgetKey && ctx.lnBudget ? ctx.lnBudget(meta.budgetKey) : 0;
    const autopaying = !!(meta && meta.autopay && dec.amountSat != null && armedBudget > 0 && dec.amountSat <= armedBudget);
    ui.arkLnPay = { invoice, meta: meta || null, amountSat: dec.amountSat, amount: '', feeSat: null, status: 'quote', autopaying };
    ui.sendError = '';
    render();
    // An auto-pay recipient (a budget the user set) pays as soon as the quote
    // lands — no tap. Guarded to the budget and to a single fire; anything
    // off-script (over budget, no amount, a quote error) falls back to the
    // normal review with the Pay button.
    const maybeAutopay = () => {
      const p2 = ui.arkLnPay;
      if (!p2 || p2.invoice !== invoice || p2._autopaid) return;
      if (p2.status !== 'ready' || !p2.meta || !p2.meta.autopay || p2.amountSat == null) return;
      const budget = p2.meta.budgetKey && ctx.lnBudget ? ctx.lnBudget(p2.meta.budgetKey) : 0;
      if (!(budget > 0 && p2.amountSat <= budget)) return;
      p2._autopaid = true;
      doArkLnPay();
    };
    quoteArkLnPay(invoice, meta).then(maybeAutopay).catch(() => {
      // The quote is a nicety — a dead esplora or quote service must not
      // wedge the form at an eternal spinner (it did: "Getting a quote…"
      // above a Failed-to-fetch, Pay unreachable). Price it like the outage
      // fallback and let Pay proceed; the payment path quotes again with
      // its own fallbacks and locks only what the route actually needs.
      const p2 = ui.arkLnPay;
      if (!p2 || p2.invoice !== invoice) return;
      p2.feeSat = p2.amountSat ? Math.max(3, Math.ceil(p2.amountSat / 1000)) : null;
      p2.status = 'ready';
      ui.sendError = '';
      render();
      maybeAutopay();
    });
    return true;
  }

  // Quote (or re-quote) an in-form lightning pay: smallest vtxo that covers
  // amount + its expiry-based fee. Funds locked by a settling action retry
  // themselves free; genuinely insufficient funds hand off to Boltz.
  async function quoteArkLnPay(invoice, meta) {
    const mgr = await connectArk();
    const p = ui.arkLnPay;
    if (!p || p.invoice !== invoice) return;
    if (!p.amountSat) { p.status = 'ready'; render(); return; }
    const tip = await mgr.chain.tipHeight();
    // what the lightning network itself will charge (0 for coinos-to-coinos)
    const routing = await mgr.lnRouteFee(invoice, p.amountSat);
    if (!ui.arkLnPay || ui.arkLnPay !== p || p.invoice !== invoice) return;
    p.routingFeeSat = routing;
    const spendables = freeCoins(mgr.state);
    let fee = null;
    for (const v of [...spendables].sort((a, b) => a.amountSat - b.amountSat)) {
      const f = lnSendFee(p.amountSat, mgr.info.lnSendFees, [v], tip) + routing;
      if (v.amountSat >= p.amountSat + f) { fee = f; break; }
    }
    if (fee == null) {
      // no single coin covers it — the pay path gathers several, so quote for
      // the same largest-first set it will pick
      const picked = [];
      let sum = 0;
      for (const v of [...spendables].sort((a, b) => b.amountSat - a.amountSat)) {
        picked.push(v); sum += v.amountSat;
        const f = lnSendFee(p.amountSat, mgr.info.lnSendFees, picked, tip) + routing;
        if (sum >= p.amountSat + f) { fee = f; break; }
      }
    }
    if (fee == null) {
      const why = lnShortfall(mgr.vtxos(), mgr.state.actions, p.amountSat);
      if (why.kind === 'settling') {
        p.status = 'fundsPending';
        render();
        mgr.resumePending().catch(() => {}); // nudge whatever holds them
        setTimeout(() => {
          if (ui.arkLnPay === p) quoteArkLnPay(invoice, meta).catch(() => {});
        }, 4000);
        return;
      }
      // Say why. A renewal holds its coins until the round confirms on-chain
      // (not seconds: no spinner for that); otherwise there simply isn't
      // enough once the fee is in — and that is not "Payment failed".
      ui.arkLnPay = null;
      ui.sendError = why.kind === 'renewing'
        ? t('arkLnRenewing', { sats: fmtSats(why.renewingSat) })
        : t('arkLnShort', {
            need: fmtSats(p.amountSat + lnSendFee(p.amountSat, mgr.info.lnSendFees, spendables, tip) + routing),
            have: fmtSats(why.spendableSat),
          });
      render();
      return;
    }
    p.feeSat = fee;
    p.status = 'ready';
    render();
  }

  async function doArkLnPay() {
    const p = ui.arkLnPay;
    const sats = p.amountSat || ctx.parseAmount(p.amount, ctx.getUnit());
    if (!sats || sats <= 0) { ui.sendError = t('enterValidAmtForN', { n: 1 }); render(); return; }
    ui.busy = true; ui.sendError = ''; render();
    try {
      const mgr = await connectArk();
      // Routing conditions can shift between quote and send: a failed
      // (and fully refunded) attempt re-tries with one extra sat of routing
      // budget before giving up — askrene fees are exact, liquidity isn't.
      let tries = 0;
      if (p.meta && p.meta.pk) noteZap('inv:' + p.invoice, p.meta.pk);
      const attempt = async (routingFeeSat) => {
        const id = await mgr.payLnInvoice(p.invoice, { amountSat: sats, routingFeeSat });
        const a = mgr.lnAction(id);
        if (['done', 'failed'].includes(a.step)) settle(a);
        else { p.actionId = id; p.status = 'paying'; pollArkLn(id, settle); }
      };
      const settle = (a) => {
        if (a.step === 'done') {
          ui.arkLnPaid = { amountSat: a.amountSat, meta: p.meta, autopaid: !!(p._autopaid || p.autopaying) };
          ui.send = blankSend(); // the next send starts empty, however this card is left
          // the user opted this recipient into auto-pay: remember the chosen
          // budget so future fixed charges from them clear without a tap
          if (p.setBudget && p.meta && p.meta.budgetKey && ctx.setLnBudget)
            ctx.setLnBudget(p.meta.budgetKey, p.setBudget);
          ui.arkLnPay = null;
        } else if (ui.arkLnPay) {
          if (tries < 2 && lnRetryable(a)) {
            tries += 1;
            p.retrying = tries; // the spinner narrates instead of stonewalling
            render();
            attempt((a.routingFeeSat ?? 0) + 1).catch((e) => {
              ui.arkLnPay.status = 'ready'; ui.sendError = e.message; render();
            });
            return;
          }
          ui.arkLnPay.status = 'ready';
          ui.sendError = a.error === 'payment failed' ? t('arkLnRefunded') : (a.error || t('arkLnPayFailed'));
        }
        render();
      };
      await attempt(p.routingFeeSat);
    } catch (e) {
      ui.sendError = e.message;
    }
    ui.busy = false; render();
  }

  // A failed lightning pay is worth re-trying with a bumped routing budget
  // unless the error says the attempt itself was ill-formed.
  function lnRetryable(a) {
    return !a?.error || !/already|invalid|expired|unpayable|insufficient|consolidate|no amount|exceeds/i.test(a.error);
  }

  // The most a Lightning pay can carry: the spendable sum over the 24-input
  // cap, minus the schedule fee and the conservative routing reserve. The
  // real quote at pay time confirms or trims — Max leaves a few sats on the
  // table rather than promising ones the fees will eat.
  function lnMaxSat() {
    const s = arkStateNow();
    const coins = freeCoins(s)
      .sort((a2, b2) => b2.amountSat - a2.amountSat).slice(0, 24);
    const sum = coins.reduce((n, v) => n + v.amountSat, 0);
    if (!sum) return 0;
    const tip = (ark && ark._tipH) || 0;
    const fees = (ark && ark.info && ark.info.lnSendFees) || {};
    let amt = sum;
    for (let i = 0; i < 3; i++) {
      const f = lnSendFee(amt, fees, coins, tip) + Math.max(3, Math.ceil(amt / 1000));
      amt = sum - f;
    }
    return Math.max(0, amt);
  }
  const amountFill = (sat) => ctx.amountField(sat);

  // Auto-pay progress + success as ONE structurally identical card, so the
  // paying → paid step is a class flip (spinner ring settles into the green
  // check, amount and recipient never move) instead of a text/layout swap. No
  // "Paying" wording at all — the badge animation carries the state.
  const autopayCard = (paid, meta, amountSat) =>
    h('div', {
      class: 'card col autopay-card' + (paid ? ' paid' : ''),
      style: 'align-items:center;text-align:center;gap:14px;padding:48px 20px' + (paid ? ';cursor:pointer' : ''),
      onClick: paid ? () => { ui.arkLnPaid = null; ui.send = blankSend(); render(); } : undefined,
    },
      h('div', { class: 'check-badge autopay-badge' }, '⚡'),
      meta && meta.name ? h('div', { class: 'small muted' }, meta.name) : null,
      h('div', { class: 'amount-neg', style: 'font-size:18px' }, fmtAmount(amountSat) + ' ' + unitLabel()),
      h('div', { class: 'small muted autopay-foot' }, paid ? t('tapToProceed') : ''));

  function arkLnPayView() {
    const u = ' ' + unitLabel();
    if (ui.arkLnPaid) {
      const zap = ui.arkLnPaid.meta;
      if (ui.arkLnPaid.autopaid) return autopayCard(true, zap, ui.arkLnPaid.amountSat);
      return h('div', {
        class: 'card col',
        style: 'align-items:center;text-align:center;gap:14px;cursor:pointer;padding:48px 20px',
        onClick: () => { ui.arkLnPaid = null; ui.send = blankSend(); render(); },
      },
        h('div', { class: 'check-badge' }, '⚡'),
        h('h2', { style: 'margin:0' }, zap && zap.social ? t('arkZapSentTitle') : t('arkLnPaidTitle')),
        zap && zap.name ? h('div', { class: 'small muted' }, zap.name) : null,
        h('div', { class: 'amount-neg', style: 'font-size:18px' }, fmtAmount(ui.arkLnPaid.amountSat) + u),
        h('div', { class: 'small muted' }, t('tapToProceed')));
    }
    const p = ui.arkLnPay;
    if (!p) return null;
    const zap = p.meta;
    // Auto-pay in flight: the progress half of the same card (see autopayCard).
    if (p.autopaying) return autopayCard(false, p.meta, p.amountSat);
    const row = (label, sats, bold) => h('div', { class: 'row between' + (bold ? '' : ''), style: bold ? 'font-weight:600' : '' },
      h('span', { class: bold ? '' : 'small muted' }, label), h('span', {}, fmtAmount(sats) + u));
    const total = (p.amountSat || 0) + (p.feeSat || 0);
    return h('div', { class: 'col', style: 'gap:12px' },
      h('div', { class: 'card col', style: 'gap:10px' },
        h('h3', { style: 'margin:0' }, '⚡ ' + (zap && zap.social ? t('lnZapReviewTitle') : t('lnPayTitle'))),
        h('div', { class: 'small muted' }, t('arkLnPayVia')),
        zap && (zap.name || zap.address) ? h('div', { class: 'small muted', style: 'word-break:break-all' }, zap.name || zap.address) : null,
        zap && zap.comment ? h('div', { class: 'small faint', style: 'font-style:italic;word-break:break-word' }, '“' + zap.comment + '”') : null,
        p.status === 'quote'
          ? h('div', { class: 'row gap6', style: 'align-items:center' }, h('span', { class: 'spinner sm' }), h('span', { class: 'small muted' }, t('lnQuoting')))
          : null,
        p.status === 'fundsPending'
          ? h('div', { class: 'row gap6', style: 'align-items:center' }, h('span', { class: 'spinner sm' }), h('span', { class: 'small muted' }, t('arkLnFundsPending')))
          : null,
        p.amountSat == null && p.status !== 'quote'
          ? h('div', { class: 'input-group' },
              h('input', { type: 'number', min: '0', inputmode: 'decimal', placeholder: t('lnPayAmount'), value: p.amount,
                onInput: (e) => { p.amount = e.target.value; } }),
              h('button', { type: 'button', onClick: () => { p.amount = amountFill(lnMaxSat()); render(); } }, t('max')),
              h('div', { style: 'display:flex;align-items:center' }, unitTag()))
          : null,
        p.amountSat != null ? row(t('lnPayAmount'), p.amountSat) : null,
        p.feeSat != null && p.feeSat > 0 ? row(t('arkLnFee'), p.feeSat) : null,
        p.amountSat != null && p.feeSat != null
          ? [h('div', { style: 'border-top:1px solid var(--line, #ddd);margin:2px 0' }), row(t('lnPayTotal'), total, true)]
          : null),
      ui.sendError ? h('div', { class: 'notice err' }, ui.sendError) : null,
      // Offer to skip this confirmation next time: pick a budget and future
      // fixed charges from this recipient up to it auto-pay without this
      // screen. The chosen amount is stored on a successful pay (see settle).
      (zap && zap.budgetKey && zap.fixedSat && !zap.autopay
        && p.status === 'ready'
        && !(ctx.lnBudget && ctx.lnBudget(zap.budgetKey) > 0))
        ? h('div', { class: 'col', style: 'gap:6px' },
            h('span', { class: 'small muted' }, t('lnAutopaySetLabel', { name: zap.name || zap.address || '' })),
            h('div', { class: 'row gap6', style: 'flex-wrap:wrap' },
              ...budgetChoices().map((amt) =>
                h('button', { type: 'button',
                  class: (p.setBudget === amt ? 'btn-primary' : 'btn-ghost') + ' btn-sm',
                  onClick: () => { p.setBudget = p.setBudget === amt ? 0 : amt; render(); } },
                  fmtAmount(amt) + ' ' + unitLabel()))))
        : null,
      p.status === 'paying'
        ? h('div', { class: 'card row gap6', style: 'align-items:center' },
            h('span', { class: 'spinner sm' }),
            h('span', { class: 'small muted' },
              p.retrying ? t('arkLnRetrying', { n: p.retrying + 1, of: 3 }) : t('arkLnPaying')))
        : h('button', { class: 'btn-primary btn-block', disabled: !!ui.busy || p.status !== 'ready', onClick: doArkLnPay },
            ui.busy ? h('span', { class: 'spinner' }) : t('lnPayConfirm')),
      p.status !== 'paying'
        ? h('button', { class: 'btn-ghost btn-block', onClick: () => { ui.arkLnPay = null; ui.sendError = ''; ui.send = blankSend(); render(); } }, t('back'))
        : null);
  }

  async function doArkLnInvoice() {
    const sats = parseInt((ui.arkLnRecvAmt || '').trim(), 10);
    if (!sats) return;
    ui.arkBusy = 'lninvoice'; ui.arkError = ''; render();
    try {
      const mgr = await connectArk();
      const a = await mgr.createLnInvoice(sats);
      ui.arkLnRecvId = a.id;
      pollArkLn(a.id, () => render()); // 'done' -> celebration via unseenReceives
    } catch (e) {
      ui.arkError = e.message;
    }
    ui.arkBusy = null; render();
  }


  // Who a zap went to, keyed by what the movement records (the ark address
  // for direct zaps, the invoice for Lightning ones) — enough to put a face
  // on history rows without touching the manager's movement schema.
  const zapNotes = () => wallet.loadFeatureState('zapnotes', {});
  function noteZap(key, pk) {
    const s = zapNotes();
    s[key] = pk;
    const keys = Object.keys(s);
    if (keys.length > 200) for (const k of keys.slice(0, keys.length - 200)) delete s[k];
    wallet.saveFeatureState('zapnotes', s);
  }
  const zapNoteFor = (m) =>
    m.type === 'send' && m.to ? zapNotes()['to:' + m.to]
    : m.type === 'ln-send' && m.invoice ? zapNotes()['inv:' + m.invoice]
    : null;

  function arkHistoryItem(m) {
    const failed = m.status === 'failed';
    const incoming = !['send', 'offboard', 'exit', 'ln-send', 'refresh'].includes(m.type);
    const label = failed ? t('arkLnPayFailed') : m.type === 'receive' ? t('received') : m.type === 'board' ? t('arkBoarded')
      : m.type === 'ln-send' ? t('arkLnPaidHistory') : m.type === 'ln-receive' ? t('arkLnReceivedHistory')
      : m.type === 'offboard' ? t('arkOffboarded') : m.type === 'exit' ? t('arkExited')
      : m.type === 'refresh' ? t('arkRenewedHistory') : t('sent');
    // A spent input proves neither a payment amount nor its date: it can
    // contain change, an offboard, or a renewal this device has not synced.
    // Show the missing history explicitly until its records arrive.
    if (m.type === 'reconcile') {
      return h('div', {
        class: 'item', style: 'cursor:pointer',
        onClick: () => {
          ui.arkReconDetail = { amountSat: m.amountSat, ts: m.ts, vtxoIds: [...(m.vtxoIds || [])] };
          render();
        },
      },
        h('div', { class: 'ico' }, '↻'),
        h('div', { class: 'grow' },
          h('div', {}, t('arkHistoryIncomplete')),
          h('div', { class: 'small faint' }, t('arkDetailsNotSynced'))),
        h('div', { style: 'text-align:right' },
          h('div', { class: 'small muted' }, fmtAmount(m.amountSat, m.ts / 1000) + ' ' + unitLabel())));
    }
    // a renewal moves nothing anywhere — its history amount is what it COST
    if (m.type === 'refresh') {
      return h('div', { class: 'item', style: 'cursor:pointer', onClick: () => { ui.arkMoveDetail = m.id; render(); } },
        h('div', { class: 'ico' }, '↻'),
        h('div', { class: 'grow' },
          h('div', {}, label),
          h('div', { class: 'small faint' }, timeAgo(m.ts / 1000))),
        h('div', { style: 'text-align:right' },
          m.feeSat > 0
            ? h('div', { class: 'amount-neg' }, fmtAmount(m.feeSat))
            : h('div', { class: 'small faint' }, t('arkDepthFree'))));
    }
    return h(
      'div',
      { class: 'item', style: 'cursor:pointer', onClick: () => { ui.arkMoveDetail = m.id; render(); } },
      // The circle's glyph names the RAIL the money actually rode: ⚡ for
      // Lightning (including a receive the registrar forwarded from an LN
      // settlement — viaLn, matched against its receipts), the Bitcoin mark
      // for the on-chain movements (board pulls coins in from chain;
      // offboard/exit push them back out — each is a real tx with a txid),
      // and the Ark mark for pure off-chain hops.
      // Direction is carried by the tint + signed amount, no text chip.
      m.type.startsWith('ln-') || m.viaLn
        ? h('div', { class: `ico ${incoming ? 'in' : 'out'}` }, '⚡')
        : ONCHAIN_ARK.has(m.type)
          ? h('div', { class: `ico ${incoming ? 'in' : 'out'}`, html: BITCOIN_ICON(20) })
          : h('div', { class: `ico ${incoming ? 'in' : 'out'}`, html: ARK_MARK(15) }),
      h('div', { class: 'grow' },
        h('div', { class: 'row gap6', style: 'align-items:center' },
          (() => {
            const g = giftForMovement(m);
            if (!g) return label;
            return h('span', {}, '🎁 ' + t('giftHistoryTitle'), ' ',
              h('span', { class: g.claimed ? 'tag conf' : 'tag' },
                g.claimed ? t('giftClaimedTag') : g.revoked ? t('giftRevokedTag') : t('giftUnclaimedTag')));
          })(),
          (() => { const pk = zapNoteFor(m); return pk ? ctx.hook('profileChip', pk) : null; })(),
          m.status !== 'complete' && !failed ? h('span', { class: 'tag pending' }, m.status === 'pending' ? t('arkExitPendingTag') : m.status) : null),
        h('div', { class: 'small faint' }, timeAgo(m.ts / 1000))),
      h('div', { style: 'text-align:right' },
        // in fiat this is what the payment was worth when it was made
        h('div', { class: failed ? 'muted' : incoming ? 'amount-pos' : 'amount-neg' }, fmtAmount(m.amountSat, m.ts / 1000)))
    );
  }

  // a movement as a line of the history export (Settings → Wallet): what
  // was paid, the fee beside it, and the change to the balance — a failed
  // payment moved nothing; a renewal moved nothing but its fee
  function arkCsvRow(m) {
    if (m.status === 'failed') return null;
    const out = ['send', 'offboard', 'exit', 'ln-send', 'refresh', 'reconcile'].includes(m.type);
    const fee = m.feeSat != null ? m.feeSat : Number(((m.detail || '').match(/fee (\d+) sat/) || [])[1]) || 0;
    const amount = m.type === 'refresh' ? 0 : m.amountSat || 0;
    const viaLn = m.type.startsWith('ln-') || m.viaLn;
    return {
      ts: m.ts, type: m.type === 'reconcile' ? 'spent-elsewhere' : m.type,
      rail: viaLn ? 'lightning' : ONCHAIN_ARK.has(m.type) ? 'onchain' : 'ark',
      amount: out ? -amount : amount, fee: out ? fee : 0, net: out ? -(amount + fee) : amount,
      status: m.status === 'complete' ? 'complete' : 'pending',
      ref: m.txid || m.paymentHash || m.vtxoId || '', to: m.to || '', invoice: m.invoice || '',
      note: m.type === 'reconcile' ? t('arkDetailsNotSynced') : '',
    };
  }

  const exitStartedTs = (a) => Number((a.id || '').split('-')[1]) || Date.now();
  // A Lightning payment (a zap, mostly) still settling: the money has left
  // the balance, so history shows it now as the Sent row it will become.
  const lnPendingMove = (a) => ({
    id: 'lnpay:' + a.id, type: 'ln-send', status: 'pending', ts: exitStartedTs(a),
    amountSat: a.amountSat, invoice: a.invoice, paymentHash: a.paymentHash,
    detail: a.feeSat ? `fee ${a.feeSat} sat` : undefined,
    inputIds: (a.parts || []).map((p) => p.inputId).concat(a.inputId ? [a.inputId] : []).filter(Boolean),
  });
  // Only link a tx that is KNOWN to be out there: the claim, a confirmed
  // hop, or the finished chain. Guessing from lastError made the link
  // flicker in time with the retry loop.
  const exitWatchTxid = (a) => a.claimTxid
    || (a.step !== 'chain' ? (a.txids || [])[(a.txids || []).length - 1]
      : a.hopsDone > 0 ? (a.txids || [])[Math.min(a.hopsDone, (a.txids || []).length - 1)]
      : null);

  // A renewal in flight, beside the in-progress exits: the tap opens the
  // coins page, where the round's progress is spelled out.
  function arkRefreshActionItem(a) {
    return h('div', { class: 'item', style: 'cursor:pointer', onClick: () => ctx.openWalletSettings('spending') },
      h('div', { class: 'ico' }, '\u21bb'),
      h('div', { class: 'grow' },
        h('div', { class: 'row gap6', style: 'align-items:center' },
          t('arkRenewingHistory'), h('span', { class: 'tag pending' }, t('arkExitPendingTag'))),
        h('div', { class: 'small faint' }, timeAgo(exitStartedTs(a) / 1000))),
      h('div', { style: 'text-align:right' },
        a.feeSat ? h('div', { class: 'amount-neg' }, fmtAmount(a.feeSat)) : h('div', { class: 'small muted' }, fmtAmount(a.inAmountSat || a.outAmountSat) + ' ' + unitLabel())));
  }

  function arkExitActionItem(a) {
    return h('div', { class: 'item', style: 'cursor:pointer', onClick: () => { ui.arkExitDetail = a.id; render(); } },
      h('div', { class: 'ico out', html: ARK_MARK(15) }),
      h('div', { class: 'grow' },
        h('div', { class: 'row gap6', style: 'align-items:center' },
          t('arkExitingHistory'), h('span', { class: 'tag pending' }, t('arkExitPendingTag'))),
        h('div', { class: 'small faint' }, timeAgo(exitStartedTs(a) / 1000))),
      h('div', { style: 'text-align:right' },
        h('div', { class: 'amount-neg' }, fmtAmount(a.amountSat))));
  }

  function arkExitActionDetail(a) {
    const exitDelta = (ark && ark.info && ark.info.vtxoExitDelta) || 144;
    const blocks = a.step === 'chain' ? ((a.txids || []).length - (a.hopsDone || 0)) + exitDelta + 1
      : a.step === 'timelock' ? Math.max(0, a.claimableAt - (a.tipSeen || 0)) + 1 : 1;
    const mins = blocks * 10;
    const eta = getNetwork() === 'regtest' ? t('arkExitSoon')
      : mins >= 2880 ? `${Math.round(mins / 1440)} days`
      : mins >= 120 ? `${Math.round(mins / 60)} hours`
      : `${mins} minutes`;
    const watch = exitWatchTxid(a);
    const url = watch ? wallet.api.explorerTx(watch) : null;
    const cancellable = a.actionable && !(a.hopsDone > 0) && a.step === 'chain';
    const row = (k, v) => h('div', { class: 'row between', style: 'gap:12px' },
      h('span', { class: 'small muted', style: 'flex-shrink:0' }, k), h('span', { class: 'small', style: 'text-align:right;word-break:break-all' }, v));
    return h('div', { class: 'card col', style: 'gap:10px' },
      h('div', { class: 'row gap6', style: 'align-items:center' },
        h('span', { html: ARK_ICON(18) }),
        h('h3', { style: 'margin:0' }, t('arkExitingHistory')),
        h('span', { class: 'tag pending' }, t('arkExitPendingTag'))),
      h('div', { class: 'amount-neg', style: 'font-size:20px' }, fmtAmount(a.amountSat) + ' ' + unitLabel()),
      row(t('dateLabel'), new Date(exitStartedTs(a)).toLocaleString()),
      h('div', { class: 'small muted' }, t('arkExitSummary', { n: fmtSats(a.amountSat), eta })),
      a.lastError ? h('div', { class: a.actionable ? 'small err' : 'small faint' }, a.actionable ? a.lastError : t('arkExitRetrying')) : null,
      url ? h('a', { class: 'btn btn-sm', href: url, target: '_blank', rel: 'noopener' }, t('arkExitViewTx')) : null,
      cancellable ? h('button', { class: 'linklike small', onClick: () => {
        a.step = 'failed';
        const v = ark && ark._vtxo(a.vtxoId);
        if (v && v.state === 'pending') v.state = 'spendable';
        if (ark) ark._save();
        ui.arkExitDetail = null;
        render();
      } }, t('arkExitCancel')) : null,
      h('button', { class: 'btn-ghost btn-block', onClick: () => ctx.goBack(() => { ui.arkExitDetail = null; }) }, t('back')));
  }

  // One label, N monospace coin ids — the send detail's consumed inputs and
  // the reconcile detail's vanished coins share the shape.
  const coinListRows = (label, ids) => !ids || !ids.length ? null
    : h('div', { class: 'col', style: 'gap:4px' },
        ...ids.map((id, i) => h('div', { class: 'row between', style: 'gap:12px' },
          h('span', { class: 'small muted', style: 'flex-shrink:0' }, i === 0 ? label : ''),
          h('span', { class: 'small', style: 'text-align:right;word-break:break-all' }, shortTxid(id)))));

  // Detail for a folded reconcile row: the hard facts only — when this wallet
  // learned of it, the original coin total, and which coins were consumed.
  function arkReconDetailView(d) {
    const row = (k, v) => h('div', { class: 'row between', style: 'gap:12px' },
      h('span', { class: 'small muted', style: 'flex-shrink:0' }, k),
      h('span', { class: 'small', style: 'text-align:right;word-break:break-all' }, v));
    return h('div', { class: 'card col', style: 'gap:10px' },
      h('div', { class: 'row gap6', style: 'align-items:center' },
        h('span', { html: ARK_ICON(18) }),
        h('h3', { style: 'margin:0' }, t('arkHistoryIncomplete'))),
      h('div', { class: 'small muted' }, t('arkHistoryIncompleteHelp')),
      row(t('arkOriginalCoins'), fmtAmount(d.amountSat) + ' ' + unitLabel()),
      row(t('arkDetectedAt'), new Date(d.ts).toLocaleString()),
      coinListRows((d.vtxoIds || []).length > 1 ? t('arkVtxoInputs') : t('arkVtxoId'), d.vtxoIds),
      h('button', { class: 'btn-ghost btn-block', onClick: () => ctx.goBack(() => { ui.arkReconDetail = null; }) }, t('back')));
  }

  function arkMoveDetailView(m) {
    const failed = m.status === 'failed';
    const incoming = m.type === 'refresh' ? false : !['send', 'offboard', 'exit', 'ln-send'].includes(m.type);
    const label = failed ? t('arkLnPayFailed') : m.type === 'receive' ? t('received') : m.type === 'board' ? t('arkBoarded')
      : m.type === 'ln-send' ? t('arkLnPaidHistory') : m.type === 'ln-receive' ? t('arkLnReceivedHistory')
      : m.type === 'offboard' ? t('arkOffboarded') : m.type === 'exit' ? t('arkExited')
      : m.type === 'refresh' ? t('arkRenewedHistory') : t('sent');
    const row = (k, v) => h('div', { class: 'row between', style: 'gap:12px' },
      h('span', { class: 'small muted', style: 'flex-shrink:0' }, k), h('span', { class: 'small', style: 'text-align:right;word-break:break-all' }, v));
    const url = m.txid ? wallet.api.explorerTx(m.txid) : null;
    return h(
      'div',
      { class: 'card col', style: 'gap:10px' },
      h('div', { class: 'row gap6', style: 'align-items:center' },
        // the rail the user chose is the one to show: a payment SENT over
        // Lightning stays Lightning here, however it settled underneath; an
        // on-chain move (board/offboard/exit) wears the Bitcoin mark
        m.type.startsWith('ln-') || m.viaLn ? h('span', { style: 'font-size:18px' }, '⚡')
          : ONCHAIN_ARK.has(m.type) ? h('span', { html: BITCOIN_ICON(18) })
          : h('span', { html: ARK_ICON(18) }),
        h('h3', { style: 'margin:0' }, label),
        m.status !== 'complete' && !failed ? h('span', { class: 'tag pending' }, m.status === 'pending' ? t('arkExitPendingTag') : m.status) : null),
      m.type === 'refresh'
        ? h('div', { class: m.feeSat > 0 ? 'amount-neg' : 'small faint', style: 'font-size:20px' },
            m.feeSat > 0 ? fmtAmount(m.feeSat) + ' ' + unitLabel() : t('arkDepthFree'))
        : h('div', { class: failed ? 'muted' : incoming ? 'amount-pos' : 'amount-neg', style: 'font-size:20px;display:flex;align-items:baseline;gap:6px' },
            fmtAmount(m.amountSat, m.ts / 1000), unitTag()), // the unit toggles, as on the balance
      row(t('dateLabel'), new Date(m.ts).toLocaleString()),
      ctx.worthLine ? ctx.worthLine(m.amountSat, m.ts / 1000, row) : null,
      // a feature that knows more about this movement (the till: bill and tip)
      ctx.hook ? ctx.hook('arkMoveDetailExtra', m, row) : null,
      (() => {
        const pk = zapNoteFor(m);
        const chip = pk ? ctx.hook('profileChip', pk) : null;
        return chip
          ? h('div', { class: 'row between', style: 'gap:12px;align-items:center' },
              h('span', { class: 'small muted' }, t('recipient')),
              chip)
          : null;
      })(),
      m.to ? row(t('arkPayTo'), shortAddr(m.to, 16, 12)) : null,
      m.vtxoId ? row(t('arkVtxoId'), shortTxid(m.vtxoId)) : null,
      // the coins this payment consumed — a send can gather up to 24 inputs
      coinListRows(t('arkVtxoInputs'), m.inputIds),
      // An offboard's fee is two different pockets — the miners' cut for the
      // on-chain weight and the ASP's service charge (base + lifetime ppm) —
      // shown apart so neither reads as the other being overpriced.
      m.chainFeeSat != null && m.serviceFeeSat != null
        ? h('div', { class: 'col', style: 'gap:10px' },
            row(t('arkFeeChain'), fmtAmount(m.chainFeeSat) + ' ' + unitLabel()),
            row(t('arkFeeService'), fmtAmount(m.serviceFeeSat) + ' ' + unitLabel()))
        : m.detail ? row(t('detailsLabel'), m.detail) : null,
      // proof of payment: the preimage is what a merchant asks for (its copy
      // button rides the grouped small-button row below with the others)
      m.preimage ? row(t('preimageLabel'), shortTxid(m.preimage)) : null,
      // A send that funded a bearer gift: show its fate, and while unclaimed
      // the sweep-back — the copy-link lives in the grouped small-button row
      // below, next to the other copy actions.
      (() => {
        const g = giftForMovement(m);
        if (!g) return null;
        refreshArkGiftRecords();
        const open = !g.claimed && !g.revoked;
        return h('div', { class: 'col', style: 'gap:8px;border-top:1px solid var(--border,rgba(128,128,128,.2));padding-top:10px' },
          h('div', { class: 'row gap6', style: 'align-items:center' },
            h('span', {}, '🎁 ' + t('giftHistoryTitle')),
            h('span', { class: g.claimed ? 'tag conf' : 'tag' },
              g.claimed ? t('giftClaimedTag') : g.revoked ? t('giftRevokedTag') : t('giftUnclaimedTag'))),
          open ? (ui.busy && ui.revokeId === g.id
            ? h('button', { class: 'btn-block btn-danger', disabled: true }, h('span', { class: 'spinner sm' }))
            : h('button', { class: 'btn-block btn-danger', onClick: async () => {
                ui.revokeId = g.id; ui.busy = true; render();
                try { await doArkGiftRevoke(g.id); toast(t('giftArkRevoked')); }
                catch (e) { toast(e.message); }
                ui.busy = false; ui.revokeId = null; render();
              } }, t('giftRevoke'))) : null);
      })(),
      m.txid
        ? h('div', { class: 'col', style: 'gap:6px' },
            h('div', { class: 'small muted' }, t('transactionId')),
            h('div', { class: 'addr-box', style: 'width:100%' }, m.txid))
        : null,
      // All the small copy/view actions travel TOGETHER in one wrapping row at
      // their natural width — not each stretched full-width and split apart by
      // the block buttons. The block actions (Revoke above, Back below) own
      // the full width; these are secondary and read as a cluster.
      (() => {
        const g = giftForMovement(m);
        const open = g && !g.claimed && !g.revoked;
        const chips = [
          open ? copyBtn(`${location.origin}/g/${encodeArkGiftCode(getNetwork(), g.amountSat, hex.decode(g.secretHex))}`, t('giftCopyLinkAgain')) : null,
          m.preimage ? copyBtn(m.preimage, t('copyPreimage')) : null,
          m.txid ? copyBtn(m.txid, t('copyTxid')) : null,
          m.txid ? h('a', { class: 'btn btn-sm', href: url, target: '_blank', rel: 'noopener', onClick: (e) => { e.preventDefault(); openExternal(url); } }, t('viewOnMempool')) : null,
          m.to ? copyBtn(m.to, t('copyAddress')) : null,
        ].filter(Boolean);
        return chips.length ? h('div', { class: 'row gap6 wrap' }, ...chips) : null;
      })(),
      h('button', { class: 'btn-ghost btn-block', onClick: () => ctx.goBack(() => { ui.arkMoveDetail = null; }) }, t('back'))
    );
  }

  async function doArkBoard() {
    const sats = parseInt((ui.arkBoardAmt || '').trim(), 10);
    if (!sats) return;
    ui.arkBusy = 'board'; ui.arkError = ''; render();
    let unfunded = null; // the action id, until the funding tx is on the wire
    try {
      const { actionId, fundingAddress, feeSat } = await ark.startBoard(sats);
      unfunded = actionId;
      const feeRate = (wallet.feeRates && wallet.feeRates.halfHourFee) || 5;
      const draft = wallet.buildTx({ recipients: [{ address: fundingAddress, amount: sats }], feeRate, noSort: true });
      const hexTx = wallet.sign(draft.tx);
      const txid = await wallet.broadcast(hexTx);
      unfunded = null; // money moved — this action must live on whatever happens next
      // Like the main send flow: reflect the spend locally and let the
      // poll/watcher reconcile. A scan here would race the explorer's indexing
      // and could resurrect the just-spent coin.
      wallet.applySentTx(draft.tx);
      await ark.completeBoard(actionId, txid);
      ui.arkBoardAmt = '';
      ui.arkBoarded = { txid, netSat: sats - feeSat };
    } catch (e) {
      // A board that never funded is not in flight. Leaving the stub at
      // 'created' looked like an in-flight action forever — which silently
      // blocked auto-renewal (it refuses to start a round beside one).
      if (unfunded && ark && ark.state) {
        const a = (ark.state.actions || []).find((x) => x.id === unfunded);
        if (a && !a.fundingTxid) { a.step = 'failed'; a.error = e.message; try { ark._save(); } catch {} }
      }
      ui.arkError = e.message;
    }
    ui.arkBusy = null; render();
  }

  // ---- ark zaps (draft protocol, NIP-61-shaped) ----------------------------
  // Lightning zaps (NIP-57) are built around LNURL + bolt11; ark needs
  // neither. Mirroring nutzaps (NIP-61): the recipient announces their ark
  // address as a replaceable event, the sender pays with a plain instant
  // arkoor send and publishes a receipt referencing the delivered vtxo.
  // Kinds are provisional until a NIP lands.
  const ARK_INFO_KIND = 10037; // replaceable: ["ark", <address>], ["network", <net>]
  const ARK_ZAP_KIND = 9737;   // receipt: ["p", pk], ["e", note?], ["amount", sats], ["vtxo", id], ["network", net], ["P", sender?]
  // The receipt is signed by the wallet key, which has no profile. When the
  // wallet is linked to a nostr login, name that identity as the sender (the
  // same "P" tag NIP-57 receipts use) so the zap reads as the person, not
  // as an npub nobody recognizes.
  const zapSenderTag = () => {
    const id = ctx.hook('nostrLoginIdentity');
    const me = wallet.nostrPubkey && wallet.nostrPubkey();
    return id && id.pubkey && id.pubkey !== me ? [['P', id.pubkey]] : [];
  };

  // npub decode without importing the nostr stack (keeps ark-only builds lean)
  function npubToHex(s) {
    try {
      const { prefix, words } = bech32.decode(String(s || '').trim(), 200);
      if (prefix !== 'npub') return null;
      return hex.encode(new Uint8Array(bech32.fromWords(words)));
    } catch { return null; }
  }

  // Tell the world where our ark mailbox lives (once per address, and only
  // when the sync/nostr feature is present in this build).
  function announceArkAddress(mgr) {
    if (!wallet.nostrPublish) return;
    const addr = mgr.address();
    if (mgr._zapAnnounced === addr) return;
    mgr._zapAnnounced = addr;
    wallet.nostrPublish({ kind: ARK_INFO_KIND, tags: [['ark', addr], ['network', getNetwork()]] }).catch(() => {});
  }

  // Resolve an npub to a same-network ark address via their announcement.
  // Paying a PERSON (an npub): resolve every way they can be paid and take
  // the best — ark over lightning over on-chain.
  //   1. their ark address: the kind-10037 advert, or an ark= instruction in
  //      BIP-353 (their coinos name via the registrar, or their nip05 name's
  //      own DNS record — a bare domain nip05 is the BIP-353 "_" user)
  //   2. lightning: profile lud16/lud06, via the zap flow
  //   3. an on-chain address from the BIP-353 record
  const NAMES_REGISTRAR = 'https://names.coinos.io';
  function startNpubPay(pk, npub, eventId = null, autoSat = 0, moment = null) {
    const z = { npub, pk, eventId, moment, amount: '', comment: '', status: 'lookup', autoSat };
    // A one-tap post zap has no card: it resolves and pays off-screen, so a
    // second tap — the same post again, or another — never evicts the one
    // already in the air. Everything else takes the send screen's zap slot.
    const instant = !!(autoSat && eventId);
    if (!instant) {
      ui.arkZap = z;
      ui.zap = null; // a stale Lightning-zap card must not resurface behind ours
      ui.sendError = '';
      render();
    }
    const live = () => instant || ui.arkZap === z;
    // The tap already put a pulsing chip on the note being zapped: whichever
    // way this goes, say so, so the chip settles instead of pulsing until it
    // times out. (A handover to the Lightning flow doesn't report — that flow
    // is still carrying the same zap, and reports for itself.)
    const bail = (error) => {
      if (!z.autoSat) return; // a form zap: the card keeps the screen and its own status
      ctx.hook('zapSettled', z.eventId, false);
      z.autoSat = 0;
      if (z.eventId) {
        if (ui.arkZap === z) ui.arkZap = null;
        toast('⚡ ' + (error || t('arkZapNoArk')), 4000);
        return true;
      } else ctx.showSend();
    };
    // an instant zap: resolution succeeded — pay the default amount now, no
    // form. Post zaps settle in place; other payments retain their form.
    const auto = async (label) => {
      try {
        await performArkZap(z, z.autoSat);
        if (ui.arkZap === z) ui.arkZap = null;
        ctx.hook('zapSettled', z.eventId, true, z.autoSat);
        if (!z.eventId) toast('⚡ ' + t('zapSentShort', { n: fmtAmount(z.autoSat) + ' ' + unitLabel() }));
        render();
      } catch (e) {
        if (!bail(e.message)) ui.sendError = e.message;
        render();
      }
    };
    (async () => {
      connectArk().catch(() => {});
      // 1a. ark advert
      const adv = await lookupArkZapTarget(pk).catch(() => ({ status: 'noark' }));
      if (!live()) return;
      if (adv.status === 'ready') { Object.assign(z, adv); if (z.autoSat) return auto(); render(); return; }
      // An advert for another network is no address here: keep looking.
      if (adv.status === 'wrongnet') z.net = adv.net;
      // 1b. BIP-353 with an ark instruction; remember on-chain as last resort
      const uris = [];
      try {
        const j = await (await fetch(`${NAMES_REGISTRAR}/pubkey/${pk}`)).json();
        if (j && j.uri) uris.push(j.uri);
      } catch {}
      const profile = wallet.nostrProfile ? await wallet.nostrProfile(pk).catch(() => null) : null;
      if (!live()) return;
      if (profile && typeof profile.nip05 === 'string' && profile.nip05.trim()) {
        const nip05 = profile.nip05.trim().toLowerCase();
        const parsed = parsePaymentName(nip05.includes('@') ? nip05 : '_@' + nip05);
        if (parsed) {
          try { const uri = await resolveBip353(parsed.name, parsed.domain); if (uri) uris.push(uri); } catch {}
        }
      }
      if (!live()) return;
      let onchain = null;
      for (const uri of uris) {
        const dec = parseBip21Uri(uri);
        if (!dec) continue;
        const arkAddr = dec.params && dec.params.ark;
        if (arkAddr && isArkAddress(arkAddr) && !foreignArkAddr(arkAddr)) {
          Object.assign(z, { status: 'ready', address: arkAddr });
          if (z.autoSat) return auto();
          render();
          return;
        }
        if (dec.onchain && !onchain) onchain = dec.onchain;
      }
      // 2. lightning via the zap flow (connect first — canLnPay needs it)
      if (profile && (profile.lud16 || profile.lud06)) {
        z.lnOk = true;
        await connectArk().catch(() => {});
        if (!live()) return;
        if (ctx.hook('canLnZap')) { if (ui.arkZap === z) ui.arkZap = null; ctx.hook('lnZapNpub', pk, npub, z.eventId, z.autoSat, z.moment); return; }
      }
      // 3. on-chain fallback (a one-tap zap can't take the send form)
      if (onchain && !(z.autoSat && z.eventId)) {
        ui.arkZap = null;
        ui.send.recipients[0].address = onchain;
        bail();
        render();
        return;
      }
      if (!live()) return;
      z.status = z.net ? 'wrongnet' : 'noark';
      // A post's author with no Lightning or Ark address can't be zapped:
      // a gift DM is for paying a person on purpose (Pay, the send form),
      // not something a tap on a post should send.
      // They do have a lightning address — it's paying it that isn't possible right now.
      if (z.eventId) { bail(t(z.lnOk ? 'arkZapLnDown' : 'arkZapNoPostZap')); render(); return; }
      // 4. last resort: an ark gift locked to their nostr key, DMed to them.
      // To the payer it's just a zap.
      if (z.autoSat && zapGiftOk(z.autoSat)) {
        try {
          await performArkZapGift(z, z.autoSat);
          if (ui.arkZap === z) ui.arkZap = null;
          ctx.hook('zapSettled', z.eventId, true, z.autoSat);
          if (!z.eventId) toast('⚡ ' + t('zapSentShort', { n: fmtAmount(z.autoSat) + ' ' + unitLabel() }));
        } catch (e) {
          if (!bail(e.message)) ui.sendError = e.message;
        }
        render();
        return;
      }
      bail(z.net ? t('arkGiftWrongNet', { net: z.net }) : undefined); render();
    })().catch((e) => { if (live()) { z.status = 'noark'; if (!bail(e.message)) ui.sendError = e.message; render(); } });
  }

  // The ask itself: switch and continue, move Savings over first, or not.
  function arkLnFromSavingsView() {
    const p = ui.arkLnFromSavings;
    const have = arkBalance()?.spendableSat || 0;
    const need = p.amountSat || 0;
    const enough = !need || have >= need;
    const proceed = () => {
      ui.arkLnFromSavings = null;
      ctx.setAccount('spending', 'right');
      ui.arkLnFromSavingsOk = true; // this one call is the answer to the ask
      if (startArkLnPay(p.invoice, p.meta)) return;
      ui.arkLnFromSavingsOk = false;
      // Spending can't carry it: the same offer the Spending side makes
      if (need && wallet.spendable > 1000 && ctx.hook('arkOfferBoard', need)) return;
      ui.sendError = t('arkLnExceedsSpending', { need: fmtAmount(need) + ' ' + unitLabel(), have: fmtAmount(have) + ' ' + unitLabel() });
      render();
    };
    return h('div', { class: 'card col', style: 'gap:12px' },
      h('h3', { style: 'margin:0' }, t('arkLnFromSavingsTitle')),
      h('p', { class: 'small muted', style: 'margin:0' }, t('arkLnFromSavingsBody', { have: fmtAmount(have) + ' ' + unitLabel() })),
      need ? h('div', { class: 'row between' }, h('span', { class: 'small muted' }, t('lnPayAmount')), h('span', { class: 'small' }, fmtAmount(need) + ' ' + unitLabel())) : null,
      !enough ? h('div', { class: 'notice info small' }, t('arkLnFromSavingsShort')) : null,
      h('button', { class: 'btn-primary btn-block', onClick: proceed }, enough ? t('arkLnUseSpending') : t('arkLnMoveFirst')),
      enough && wallet.spendable > 1000
        ? h('button', { class: 'btn-block', onClick: () => { ui.arkLnFromSavings = null; ctx.hook('arkOfferBoard', need || 0); } }, t('arkLnMoveFirst'))
        : null,
      h('button', { class: 'btn-ghost btn-block', onClick: () => { ui.arkLnFromSavings = null; ui.sendError = ''; ui.send = blankSend(); render(); } }, t('cancel')));
  }

  // shared by the ark and lightning zap flows (see zaps.js for the twin)
  function zapSkeleton(pk, fallback) {
    return h('div', { class: 'card col', style: 'gap:12px' },
      h('h3', {}, '⚡ ' + t('zapTitle')),
      (pk && ctx.hook('profileChip', pk, 'lg'))
        || h('div', { class: 'small muted break' }, fallback || ''),
      h('div', { class: 'row gap6', style: 'align-items:center;padding:6px 0' },
        h('span', { class: 'spinner sm' }),
        h('span', { class: 'small muted' }, t('zapFinding'))),
      h('button', { class: 'btn-ghost btn-block', onClick: () => {
        ui.arkZap = null; ui.zap = null; ui.sendError = ''; ui.send = blankSend(); render();
      } }, t('back')));
  }

  // An Ark address names its server (the first bytes are a hash of the
  // server key). One on a different server than ours can't take an arkoor
  // send — the pay ladder falls through to Lightning for such a person, and
  // a pasted one is refused with the reason rather than a gRPC error.
  function myArkId() {
    try {
      if (ark && ark.serverPub) return hex.encode(arkIdFromServerPubkey(ark.serverPub));
      const st = arkStateNow();
      if (st && st.serverPubkey) return hex.encode(arkIdFromServerPubkey(hex.decode(st.serverPubkey)));
    } catch {}
    return null;
  }
  function foreignArkAddr(addr) {
    try {
      const mine = myArkId();
      return !!mine && decodeAddress(String(addr).trim()).arkId !== mine;
    } catch { return false; }
  }
  async function lookupArkZapTarget(pk) {
    const events = await wallet.nostrFetch({ kinds: [ARK_INFO_KIND], authors: [pk] }, 6000);
    const ev = (events || []).sort((a, b) => b.created_at - a.created_at)[0];
    if (!ev) return { status: 'noark' };
    const addr = (ev.tags.find((t) => t[0] === 'ark') || [])[1];
    const net = (ev.tags.find((t) => t[0] === 'network') || [])[1];
    if (!addr) return { status: 'noark' };
    if (net && net !== getNetwork()) return { status: 'wrongnet', net };
    if (foreignArkAddr(addr)) return { status: 'noark', foreign: true }; // their server isn't ours: Lightning it is
    return { status: 'ready', address: addr };
  }

  // The zap itself, shared by the form and the one-tap default-amount path.
  async function performArkZap(z, sats) {
    const mgr = await connectArk();
    const actionId = await mgr.send(z.address, sats);
    const action = mgr.state.actions.find((a) => a.id === actionId);
    if (!action || action.step === 'failed') throw new Error(action?.error || t('claimFailed'));
    const vtxoId = decodeVtxo(hex.decode((action.destBytesList || [action.destBytes])[0])).id;
    noteZap('to:' + z.address, z.pk);
    // the receipt is best-effort: the sats are already delivered via mailbox
    await wallet.nostrPublish({
      kind: ARK_ZAP_KIND,
      content: (z.comment || '').slice(0, 280),
      tags: [...momentTags(z.moment), ['p', z.pk], ...(z.eventId ? [['e', z.eventId]] : []), ...(zapAddrOf(z.eventId) ? [['a', zapAddrOf(z.eventId)]] : []),
        ['amount', String(sats)], ['vtxo', vtxoId], ['network', getNetwork()], ...zapSenderTag()],
    }).catch(() => {});
  }

  async function doArkZap() {
    const z = ui.arkZap;
    const sats = ctx.parseAmount(z.amount, ctx.getUnit());
    if (!sats || sats <= 0) { ui.sendError = t('enterValidAmtForN', { n: 1 }); render(); return; }
    ui.busy = true; ui.sendError = ''; render();
    try {
      await performArkZap(z, sats);
      ctx.hook('zapSettled', z.eventId, true, sats); // the tally shows it now, not when the receipt lands
      ui.arkZapped = { amountSat: sats, npub: z.npub };
      ui.arkZap = null;
      ui.send = blankSend();
    } catch (e) {
      ui.sendError = e.message;
    }
    ui.busy = false; render();
  }

  // No ark address published: the zap leaves anyway, as an ark gift locked to
  // their nostr key. The sats move into a bearer vtxo now; the public link is
  // safe to put in the receipt because only the recipient's key — or the
  // claim code we DM them — opens it. Unclaimed, it stays revocable from the
  // gift card like any other ark gift.
  // Can a zap to this person leave as a locked gift (this build carries
  // gifts, the wallet can sign, and Spending covers it)?
  function zapGiftOk(sats = 330) {
    return !wallet.watchOnly && (arkBalance()?.spendableSat || 0) >= Math.max(330, sats) && !!ctx.hook('canLockGift');
  }
  async function performArkZapGift(z, sats) {
    const g = await createArkGift(sats, z.pk);
    const locked = ctx.hook('lockArkGift', g.code, sats, z.pk);
    if (!locked) throw new Error(t('claimFailed')); // no gifts feature in this build
    noteZap('to:' + g.address, z.pk);
    const gift = { url: locked.url, claimCode: locked.claimCode, dm: 'sending' };
    // best-effort receipt; carries the locked link so the recipient can
    // discover the gift from the note even if the DM never lands
    wallet.nostrPublish({
      kind: ARK_ZAP_KIND,
      content: (z.comment || '').slice(0, 280),
      tags: [...momentTags(z.moment), ['p', z.pk], ...(z.eventId ? [['e', z.eventId]] : []), ...(zapAddrOf(z.eventId) ? [['a', zapAddrOf(z.eventId)]] : []),
        ['amount', String(sats)], ['network', getNetwork()], ['gift', locked.url], ...zapSenderTag()],
    }).catch(() => {});
    const dmText = t('giftDmText', { amount: fmtAmount(sats) + ' ' + unitLabel(), link: locked.url, code: locked.claimCode });
    if (wallet.sendNostrDM) {
      wallet.sendNostrDM(z.pk, dmText)
        .then((ok) => { gift.dm = ok ? 'sent' : 'failed'; render(); })
        .catch(() => { gift.dm = 'failed'; render(); });
    } else gift.dm = 'failed';
    return gift;
  }

  async function doArkZapGift() {
    const z = ui.arkZap;
    const sats = ctx.parseAmount(z.amount, ctx.getUnit());
    if (!sats || sats <= 0) { ui.sendError = t('enterValidAmtForN', { n: 1 }); render(); return; }
    if (sats > (arkBalance()?.spendableSat || 0)) { ui.sendError = t('giftExceedsBalance'); render(); return; }
    ui.busy = true; ui.sendError = ''; render();
    try {
      const gift = await performArkZapGift(z, sats);
      ctx.hook('zapSettled', z.eventId, true, sats);
      ui.arkZapped = { amountSat: sats, npub: z.npub, gift };
      ui.arkZap = null;
      ui.send = blankSend();
    } catch (e) {
      ui.sendError = e.message;
    }
    ui.busy = false; render();
  }

  function arkZapView() {
    // While resolving, show the SHAPE of the card that's coming — same
    // title, same recipient portrait, a spinner where the form will be. The
    // screen fills in rather than being replaced.
    if (ui.arkZap && ui.arkZap.status === 'lookup') return zapSkeleton(ui.arkZap.pk, ui.arkZap.npub);
    if (ui.arkZapped) {
      const gift = ui.arkZapped.gift;
      const finish = () => { ui.arkZapped = null; ui.send = blankSend(); render(); };
      // A gift zap looks like any other zap. Only a DM that couldn't be
      // delivered needs the payer: the link and code to pass along by hand.
      if (!gift || gift.dm !== 'failed') {
        return h('div', {
          class: 'card col',
          style: 'align-items:center;text-align:center;gap:14px;cursor:pointer;padding:48px 20px',
          onClick: finish,
        },
          h('div', { class: 'check-badge' }, '⚡'),
          h('h2', { style: 'margin:0' }, t('arkZapSentTitle')),
          h('div', { class: 'amount-neg', style: 'font-size:18px' }, fmtAmount(ui.arkZapped.amountSat) + ' ' + unitLabel()),
          h('div', { class: 'small muted' }, t('tapToProceed')));
      }
      return h('div', { class: 'card col', style: 'align-items:center;text-align:center;gap:12px;padding:28px 16px' },
        h('div', { class: 'check-badge' }, '⚡'),
        h('h2', { style: 'margin:0' }, t('arkZapSentTitle')),
        h('div', { class: 'amount-neg', style: 'font-size:18px' }, fmtAmount(ui.arkZapped.amountSat) + ' ' + unitLabel()),
        h('div', { class: 'notice info', style: 'text-align:left' }, t('giftDmFailed')),
        h('div', { class: 'addr-box break', style: 'width:100%;font-size:11px' }, gift.url),
        h('div', { class: 'row gap6 wrap', style: 'justify-content:center' },
          copyBtn(gift.url, t('copyLink')),
          copyBtn(gift.claimCode, t('giftCopyCode'))),
        h('button', { class: 'btn-primary btn-block', onClick: finish }, t('done')));
    }
    const z = ui.arkZap;
    if (!z) return null;
    const spendable = arkBalance()?.spendableSat || 0;
    // No ark address or Lightning found — the zap still leaves, as an ark
    // gift locked to their nostr key. The payer sees an ordinary zap.
    const noAddr = z.status === 'noark' || z.status === 'wrongnet';
    const giftOk = noAddr && !z.eventId && !wallet.watchOnly && !!ctx.hook('canLockGift');
    const payable = z.status === 'ready' || giftOk;
    const amountInputs = (hint) => h('div', { class: 'col gap6' },
      h('div', { class: 'input-group' },
        h('input', { type: 'number', min: '0', inputmode: 'decimal', placeholder: t('lnPayAmount'), value: z.amount,
          onInput: (e) => { z.amount = e.target.value; } }),
        h('button', { type: 'button', onClick: () => { z.amount = amountFill(lnMaxSat()); render(); } }, t('max')),
        h('div', { style: 'display:flex;align-items:center' }, unitTag())),
      h('input', { type: 'text', class: 'mono-input', placeholder: t('arkZapCommentPh'), value: z.comment,
        onInput: (e) => { z.comment = e.target.value; } }),
      h('div', { class: 'small faint' }, hint));
    return h('div', { class: 'card col', style: 'gap:12px' },
      h('h3', {}, '⚡ ' + t('zapTitle')),
      ctx.hook('profileChip', z.pk, 'lg') || h('div', { class: 'small muted', style: 'word-break:break-all' }, z.npub),
      z.status === 'lookup' ? h('div', { class: 'row gap6', style: 'align-items:center' }, h('span', { class: 'spinner sm' }), h('span', { class: 'small muted' }, t('arkZapLookup'))) : null,
      z.status === 'noark' && !giftOk ? h('div', { class: 'notice err' }, t(z.eventId ? 'arkZapNoPostZap' : 'arkZapNoArk')) : null,
      z.status === 'wrongnet' && !giftOk ? h('div', { class: 'notice err' }, t('arkGiftWrongNet', { net: z.net })) : null,
      // Only someone with a Lightning address gets the Lightning door (the
      // lookup normally hands such a person straight to the zaps feature).
      noAddr && z.lnOk && ctx.hook('canLnZap')
        ? h('button', { class: 'btn-block', disabled: !!ui.busy, onClick: () => { ctx.hook('lnZapNpub', z.pk, z.npub, z.eventId, 0, z.moment); } }, '⚡ ' + t('lnZapFallback'))
        : null,
      payable && spendable < 330
        ? h('div', { class: 'notice info' }, t(spendable + renewingSat() >= 330 ? 'spendingRenewingPayment' : 'zapNoBalance'))
        : payable
        ? amountInputs(t('arkZapHint'))
        : null,
      ui.sendError ? h('div', { class: 'notice err' }, ui.sendError) : null,
      h('div', { class: 'row gap6' },
        h('button', { class: 'btn-ghost', onClick: () => { ui.arkZap = null; ui.sendError = ''; ui.send = blankSend(); render(); } }, t('back')),
        payable && spendable >= 330
          ? (ui.busy
              ? h('button', { class: 'btn-primary grow', disabled: true }, h('span', { class: 'spinner' }))
              : h('button', { class: 'btn-primary grow', onClick: z.status === 'ready' ? doArkZap : doArkZapGift }, t('arkZapBtn')))
          : null));
  }

  // ---- auto-withdraw --------------------------------------------------------
  // Forward Spending onward once it crosses a threshold. Same destinations the
  // send form takes — an ark address, a payment name, a lightning address, an
  // npub, or an on-chain address — resolved through the same paths, just
  // without a human present. Deliberately conservative: one transfer at a
  // time, never while another action is in flight, and a failure backs off
  // instead of retrying in a loop.

  const awState = () => wallet.loadFeatureState('autowithdraw', {});
  const awSave = (v) => wallet.saveFeatureState('autowithdraw', v);

  // What kind of destination is this, and can we pay it at all? Returns
  // { kind, address } or null. Resolution that needs the network (BIP-353,
  // LNURL, npub profiles) happens at send time, not here.
  function awClassify(dest) {
    const d = (dest || '').trim();
    if (!d) return null;
    if (isArkAddress(d)) return { kind: 'ark', address: d };
    if (parsePaymentName(d)) return { kind: 'name', address: d };
    if (npubToHex(d)) return { kind: 'npub', address: d };
    if (/^lnurl1[ac-hj-np-z02-9]+$/i.test(d)) return { kind: 'lnurl', address: d };
    try {
      btc.Address(wallet.netCfg.net).decode(d);
      return { kind: 'onchain', address: d };
    } catch {}
    return null;
  }

  // Turn any destination into something payable right now.
  async function awResolve(dest) {
    const c = awClassify(dest);
    if (!c) throw new Error(t('awBadDest'));
    if (c.kind === 'ark' || c.kind === 'onchain') return c;
    // a payment name may carry an ark instruction (free) or fall back to LNURL
    if (c.kind === 'name') {
      const p = parsePaymentName(c.address);
      const uri = await resolveBip353(p.name, p.domain).catch(() => null);
      const dec = uri ? parseBip21Uri(uri) : null;
      const arkAddr = dec && dec.params && dec.params.ark;
      if (arkAddr && isArkAddress(arkAddr)) return { kind: 'ark', address: arkAddr };
      if (dec && dec.onchain) return { kind: 'onchain', address: dec.onchain };
      return { kind: 'lnaddr', address: c.address };
    }
    if (c.kind === 'npub') {
      const pk = npubToHex(c.address);
      const adv = await lookupArkZapTarget(pk).catch(() => null);
      if (adv && adv.status === 'ready') return { kind: 'ark', address: adv.address };
      const profile = wallet.nostrProfile ? await wallet.nostrProfile(pk).catch(() => null) : null;
      if (profile && profile.lud16) return { kind: 'lnaddr', address: profile.lud16 };
      throw new Error(t('awBadDest'));
    }
    return { kind: c.kind === 'lnurl' ? 'lnurl' : 'lnaddr', address: c.address };
  }

  async function awPay(target, amountSat) {
    const mgr = await connectArk();
    if (target.kind === 'ark') {
      await mgr.send(target.address, amountSat);
      return;
    }
    if (target.kind === 'onchain') {
      const spk = btc.OutScript.encode(btc.Address(wallet.netCfg.net).decode(target.address));
      // Offboarding moves whole vtxos, so carve out the exact amount first
      // when we're not sending everything.
      const spendables = () => freeCoins(mgr.state);
      const total = spendables().reduce((n, v) => n + v.amountSat, 0);
      let ids;
      if (amountSat < total) {
        let exact = spendables().find((v) => v.amountSat === amountSat);
        if (!exact) {
          const before = new Set(spendables().map((v) => v.id));
          await mgr.send(mgr.address(), amountSat);
          for (let i = 0; i < 30 && !exact; i++) {
            await new Promise((r) => setTimeout(r, 2000));
            await mgr.sync().catch(() => {});
            exact = spendables().find((v) => v.amountSat === amountSat && !before.has(v.id));
          }
          if (!exact) throw new Error(t('arkSplitTimeout'));
        }
        ids = [exact.id];
      }
      await mgr.startOffboard(spk, target.address, ids);
      return;
    }
    // lightning: ask their server for an invoice, pay it over ark
    const zt = parseZapTarget(target.address);
    if (!zt || !zt.url) throw new Error(t('awBadDest'));
    const params = await fetchPayParams(zt.url);
    const msat = amountSat * 1000;
    if (msat < params.minSendable || msat > params.maxSendable) throw new Error(t('awOutOfRange'));
    const invoice = await requestInvoice(params, { amountMsat: msat, lnurlBech32: zt.lnurlBech32 });
    await mgr.payLnInvoice(invoice, { amountSat });
  }

  // What the service worker gets: the setting plus a destination it can pay
  // without a relay. Resolution can fail (DNS down, profile missing) — then we
  // keep whatever we mirrored last rather than dropping the feature.
  async function awMirror(prev) {
    const st = awState();
    if (!st.on || !st.dest) return null;
    const prevAw = prev && prev.autowithdraw;
    let target = prevAw && prevAw.dest === st.dest ? prevAw.target : null;
    try {
      const r = await awResolve(st.dest);
      target = { kind: r.kind, address: r.address };
      if (r.kind === 'lnaddr' || r.kind === 'lnurl') {
        const zt = parseZapTarget(r.address);
        if (zt && zt.url) target.url = zt.url; else target = null;
      } else if (r.kind === 'onchain') {
        target.spkHex = hex.encode(btc.OutScript.encode(btc.Address(wallet.netCfg.net).decode(r.address)));
      }
    } catch {}
    if (!target) return null;
    return {
      on: true, dest: st.dest, target,
      threshold: Number(st.threshold) || 0,
      keep: Math.max(0, Number(st.keep) || 0),
      failedAt: st.failedAt || 0,
    };
  }

  // What the worker did while we were closed becomes the app's state again.
  function absorbBgAutoWithdraw(rec) {
    const bg = rec && rec.autowithdraw;
    if (!bg) return;
    const st = awState();
    if (!st.on) return;
    if ((bg.lastAt || 0) > (st.lastAt || 0)) awSave({ ...st, lastAt: bg.lastAt, lastSat: bg.lastSat, failedAt: 0, error: '' });
    else if ((bg.failedAt || 0) > (st.failedAt || 0)) awSave({ ...st, failedAt: bg.failedAt, error: bg.error || '' });
  }

  let awBusy = false;
  async function maybeAutoWithdraw(mgr) {
    const st = awState();
    if (!st.on || !st.dest || wallet.watchOnly || awBusy) return;
    if (Date.now() - (st.failedAt || 0) < 15 * 60_000) return; // backing off
    if ((mgr.state.actions || []).some((a) => !['done', 'failed'].includes(a.step))) return;
    const spendable = freeCoins(mgr.state).reduce((n, v) => n + v.amountSat, 0);
    const threshold = Number(st.threshold) || 0;
    const keep = Math.max(0, Number(st.keep) || 0);
    if (!threshold || spendable < threshold) return;
    const amount = spendable - keep;
    if (amount < 330) return;
    awBusy = true;
    try {
      const target = await awResolve(st.dest);
      await awPay(target, amount);
      const s2 = awState();
      awSave({ ...s2, lastAt: Date.now(), lastSat: amount, failedAt: 0, error: '' });
      toast(t('awSent', { n: fmtAmount(amount) + ' ' + unitLabel() }));
      render();
    } catch (e) {
      const s2 = awState();
      awSave({ ...s2, failedAt: Date.now(), error: e.message || String(e) });
      console.warn('auto-withdraw failed:', e.message);
    } finally {
      awBusy = false;
    }
  }

  // The exit-cost tradeoff, surfaced only when it's real: every off-chain
  // hop a coin accumulates makes its trustless exit one on-chain transaction
  // more expensive; a renewal flattens the history back to a single hop.
  // Most users never need to think about this — the card only appears once
  // coins run deep enough for the difference to matter.
  const EXIT_DEPTH_ADVISORY = 4;
  // Pricing the advisory is EC-heavy: it decodes every spendable coin (for its
  // genesis depth) and builds the exit transactions (estimateExitFeeSat). Doing
  // that synchronously in the render path was the cold cost behind a carousel
  // drag stutter right after a refresh. So the render only READS the cached
  // answer, and the recompute runs in idle time — never competing with input.
  let _depthKey = null, _depthComputing = false;
  function computeDepthAdvisory() {
    if (!ark || !ark.state) return;
    const spend = freeCoins(ark.state);
    const feeRate = Math.max(1, (wallet.feeRates && wallet.feeRates.halfHourFee) || 2);
    const key = feeRate + '|' + spend.map((v) => v.id).join(',');
    if (key === _depthKey || _depthComputing) return; // already priced this exact set
    _depthComputing = true;
    const run = () => {
      try {
        let depth = 0;
        for (const v of spend) { try { depth = Math.max(depth, ark._decoded(v).genesis.length); } catch {} }
        let show = false, exitFee = 0;
        if (spend.length && depth >= EXIT_DEPTH_ADVISORY) {
          try { exitFee = estimateExitFeeSat(ark); } catch {}
          const afterFee = Math.ceil(530 * feeRate); // one coin, one hop post-renewal
          show = afterFee < exitFee; // renewing has to actually help
        }
        _depthKey = key;
        const cached = wallet.loadFeatureState('arkDepth', null);
        if (!cached || cached.show !== show || cached.exitFee !== exitFee) {
          wallet.saveFeatureState('arkDepth', { show, exitFee });
          render();
        }
      } finally { _depthComputing = false; }
    };
    if (typeof requestIdleCallback === 'function') requestIdleCallback(run, { timeout: 2000 });
    else setTimeout(run, 200);
  }
  function exitDepthNotice() {
    if (!arkAvailable() || wallet.watchOnly) return null;
    // Render is cheap: paint the last computed answer immediately (so the line
    // doesn't pop in and shove layout), and kick an idle recompute if the coin
    // set changed. The heavy EC never runs in the render/interaction path.
    if (ark && ark.state) computeDepthAdvisory();
    const cached = wallet.loadFeatureState('arkDepth', null);
    return cached && cached.show ? t('arkDepthNotice', { fee: fmtSats(cached.exitFee) }) : null;
  }

  // The screen behind that notice's Manage link: every spendable coin with
  // its expiry and arkoor depth, what an uncooperative exit costs today, and
  // what a renewal costs and buys.
  function arkCoinsPage({ embedded = false } = {}) {
    // The notice that opens this page reads the persisted state; so must the
    // page, or a tap before the manager has connected (the first seconds
    // after boot) found no coins and closed itself — Manage needed two taps.
    // The manager is dialled meanwhile; what needs it live waits for it.
    const mgr = arkView();
    const st = (mgr && mgr.state) || arkStateNow();
    // another device's renewal holds its coins just the same: greyed here too
    const elsewhere = st ? remoteRenewalsInFlight(st) : [];
    const spend = freeCoins(st);
    // Coins in a renewal round sit 'pending' until the fresh coin is signed
    // (a confirmation of the round's transaction, then a sync). They stay on
    // the page, greyed and unselectable, with the round's progress beside
    // them — the page used to shrink to one line the moment Renew was tapped.
    const renewing = ((st && st.actions) || []).filter((a) => a.type === 'refresh' && !['done', 'failed'].includes(a.step));
    const inRound = new Set([...renewing, ...elsewhere].flatMap((a) => a.inputIds || []));
    const pendingCoins = ((st && st.vtxos) || []).filter((v) => (v.state === 'pending' || v.state === 'spendable') && inRound.has(v.id));
    const tip = arkTipNow(mgr);
    // the coinos servers keep honoring a coin past its timelock: it is held
    // by coinos, not expired — still money, just not exitable on its own
    const honors = !!(mgr && mgr.honorsExpired);
    const exitable = exitableCoins(st, tip);
    const back = embedded
      ? () => { ui.arkCoinsSel = null; ui.arkRenewConfirm = null; ctx.goHome(); }
      : () => ctx.goBack(() => { ui.arkCoinsPage = null; ui.arkCoinsSel = null; ui.arkRenewConfirm = null; }); // the page is a history entry now
    if (!spend.length && !pendingCoins.length) {
      if (embedded) return h('div', { class: 'card col', style: 'gap:6px' }, h('h3', { style: 'margin:0' }, t('arkCoinsTitle')), h('p', { class: 'small muted', style: 'margin:0' }, t('arkCoinsNone')));
      ui.arkCoinsPage = null; return null; // nothing left to manage
    }
    if (!mgr) connectArk().then(() => render()).catch(() => {});
    const totalSat = spend.reduce((n, v) => n + v.amountSat, 0);
    const heldSat = totalSat + pendingCoins.reduce((n, v) => n + v.amountSat, 0);
    const spendableSat = arkBalance()?.spendableSat || 0;
    let exitFee = 0; try { exitFee = estimateExitFeeSat(mgr); } catch {}
    const feeRate = Math.max(1, (wallet.feeRates && wallet.feeRates.halfHourFee) || 2);
    const afterFee = Math.ceil(530 * feeRate);
    // relative and terse — "14d" / "13h" beside the hourglass — a date says
    // less than a countdown, and a coin past its height says so plainly
    // instead of the shifty "0h" (the server still honors it; the wallet's
    // next renewal round sweeps it up).
    const expiresOf = (v) => {
      if (!v.expiryHeight || !tip) return '—';
      const blocks = v.expiryHeight - tip;
      if (blocks <= 0) return honors ? t('arkCoinsHeld') : t('arkCoinsExpired');
      return blocks >= 144 ? Math.round(blocks / 144) + 'd' : Math.max(1, Math.round(blocks / 6)) + 'h';
    };
    // what pulling THIS coin on-chain alone would cost: every hop's fee
    // child plus the claim, at today's rate (the whole-balance figure below
    // is the same sum over all coins)
    const exitFeeOf = (v) => {
      try {
        let f = Math.ceil(150 * feeRate);
        if (mgr) for (const vsize of exitTxVsizes(mgr._decoded(v), mgr.serverPub)) f += Math.ceil((vsize + 130) * feeRate);
        return f;
      } catch { return null; }
    };
    // The server prices a renewal by how much lifetime each coin still
    // carries (its ppm bracket) — waiting IS cheaper, and inside the final
    // bracket the share is zero, where the wallet renews on its own anyway.
    // A flat base fee (the round's on-chain cost, which coinos stopped
    // absorbing in October 2026) rides on top of every bracket.
    const infoNow = (mgr && mgr.info) || (cachedArkInfo((getArkConfig() || {}).ark) || {}).info || {};
    const table = (infoNow.refreshFees || {}).ppmExpiryTable || [];
    const baseSat = (infoNow.refreshFees || {}).baseFeeSat || 0;
    const baseCost = fmtSats(baseSat) + ' sats';
    const roundMins = Math.max(1, Math.round((infoNow.roundIntervalSecs || 120) / 60));
    const roundEvery = roundMins === 1 ? t('arkCoinsRoundEveryOne') : t('arkCoinsRoundEvery', { n: roundMins });
    const ppmFor = (blocks) => (table.filter((e) => e.thresholdBlocks <= blocks).pop()?.ppm) ?? 0;
    // A coin's SHARE of the renewal fee, fractional: the server totals the
    // ppm across every coin in the round and rounds up once (refreshFee), so
    // a 1-sat coin costs a few thousandths of a sat, not the 1 sat a
    // per-coin ceiling used to print — nine such chips summing past the
    // real total made it look as if the page were skipping them.
    const feeNowOf = (v) => (v.amountSat * ppmFor((v.expiryHeight || 0) - tip)) / 1_000_000;
    const renewChip = (share) => share <= 0 ? t('arkDepthFree')
      : share < 1 ? t('arkCoinsChipRenewTiny')
      : fmtAmount(Math.round(share)) + ' ' + unitLabel();
    const span = (blocks) => {
      if (blocks >= 144) {
        const d = Math.round(blocks / 144);
        return d === 1 ? t('arkCoinsSpanDay') : t('arkCoinsSpanDays', { n: d });
      }
      const hs = Math.max(1, Math.round(blocks / 6));
      return hs === 1 ? t('arkCoinsSpanHour') : t('arkCoinsSpanHours', { n: hs });
    };
    const schedule = [...table].sort((a, b) => b.thresholdBlocks - a.thresholdBlocks).map((e, i, arr) => ({
      label: e.ppm === 0
        ? t('arkCoinsSchedFinal', { span: span(arr[i - 1] ? arr[i - 1].thresholdBlocks : 144) })
        : i === 0
          ? t('arkCoinsSchedOver', { span: span(e.thresholdBlocks) })
          : t('arkCoinsSchedBetween', { a: span(e.thresholdBlocks), b: span(arr[i - 1].thresholdBlocks) }),
      cost: e.ppm === 0 ? (baseSat ? baseCost : t('arkDepthFree'))
        : (e.ppm / 10000).toLocaleString(undefined, { maximumFractionDigits: 3 }) + '%' + (baseSat ? ' + ' + baseCost : ''),
      free: e.ppm === 0 && !baseSat,
    }));
    // Which coins ride the renewal: all by default (the one-button behavior),
    // any subset by unticking. Selection is per-visit; ids that vanished
    // (spent meanwhile) drop out silently.
    const ids = new Set(spend.map((v) => v.id));
    if (!(ui.arkCoinsSel instanceof Set)) ui.arkCoinsSel = new Set(ids);
    for (const id of ui.arkCoinsSel) if (!ids.has(id)) ui.arkCoinsSel.delete(id);
    const sel = ui.arkCoinsSel;
    const selCoins = spend.filter((v) => sel.has(v.id));
    let selFee = 0; try { selFee = mgr.refreshFee(selCoins, tip); } catch {}
    const renew = () => {
      if (!selCoins.length || !mgr) return;
      // fire and let the round machinery carry it — rounds can be an hour out
      mgr.refresh(selCoins.map((v) => v.id), { manual: true }).catch((e) => toast(e.message));
      toast(t('arkDepthRenewed'));
      ui.arkCoinsSel = null;
      ui.arkRenewConfirm = null;
      render(); // the page stays: the coins show as renewing
    };
    // "Renew" asks once, with the numbers on the table: the coins it takes
    // can't be spent until the round's transaction confirms, it can't be
    // called back, and by default it takes every coin. (A user renewed their
    // whole balance right after being paid and couldn't pay for an hour.)
    if (ui.arkRenewConfirm && selCoins.length) {
      const selSat = selCoins.reduce((n, v) => n + v.amountSat, 0);
      const leftSat = spend.reduce((n, v) => n + v.amountSat, 0) - selSat;
      const row = (k, v, cls = '') => h('div', { class: 'row between' }, h('span', { class: 'small muted' }, k), h('span', { class: 'small' + (cls ? ' ' + cls : '') }, v));
      return h('div', { class: 'col ark-renew-confirm', style: 'gap:16px' },
        h('div', { class: 'card col', style: 'gap:10px' },
          h('h3', { style: 'margin:0' }, t('arkRenewConfirmTitle')),
          h('p', { class: 'small muted', style: 'margin:0' }, t('arkRenewConfirmBody')),
          h('div', { class: 'col', style: 'gap:4px' },
            row(t('arkExitConfirmCoins'), String(selCoins.length)),
            row(t('arkExitConfirmAmount'), fmtSats(selSat) + ' sats'),
            row(t('arkRenewConfirmFee'), selFee > 0 ? fmtSats(selFee) + ' sats' : t('arkDepthFree')),
            row(t('arkRenewConfirmLeft'), fmtSats(leftSat) + ' sats', leftSat ? '' : 'err')),
          leftSat ? null : h('div', { class: 'notice err small' }, t('arkRenewConfirmAll')),
          h('p', { class: 'small muted', style: 'margin:0' }, t('arkRenewConfirmWait')),
          h('button', { class: 'btn-primary btn-block ark-renew-go', disabled: !!ui.arkBusy || !ark, onClick: renew },
            selFee > 0 ? t('arkCoinsRenewNowFee', { fee: fmtSats(selFee) + ' sats' }) : t('arkDepthRenewBtn'))),
        h('button', { class: 'btn-ghost btn-block', onClick: () => { ui.arkRenewConfirm = null; render(); } }, t('cancel')));
    }
    if (ui.arkRenewConfirm) ui.arkRenewConfirm = null; // nothing selected any more
    const stageOf = (a) => a.step === 'issued' ? t('arkRenewStageFinishing') : a.step === 'submitted' ? t('arkRenewStageRound') : t('arkRenewStageQueued');
    // another device's renewals, shown but never driven from here (it holds
    // their signing material); they lock the balance just the same
    const renewingRows = [...renewing, ...elsewhere.map((r) => ({ ...r, elsewhere: true }))];
    const renewingCard = renewingRows.length ? h('div', { class: 'card col', style: 'gap:8px' },
      h('div', { class: 'row gap6', style: 'align-items:center' },
        h('h4', { style: 'margin:0' }, t('arkRenewingTitle')), h('span', { class: 'tag pending' }, t('arkExitPendingTag'))),
      ...renewingRows.map((a) => h('div', { class: 'col', style: 'gap:2px' },
        h('div', { class: 'small' }, t('arkRenewingLine', { amount: fmtSats(a.inAmountSat || (a.outAmountSat + (a.feeSat || 0))), fee: a.feeSat ? t('arkRenewingFee', { fee: fmtSats(a.feeSat) }) : '' })),
        h('div', { class: 'small muted' }, stageOf(a)),
        a.elsewhere ? h('div', { class: 'small faint' }, t('arkRenewElsewhere')) : null,
        // the round's transaction, once the round has run: the thing the
        // wait is for, there to be looked at
        a.fundingTxid ? (() => {
          const url = wallet.api.explorerTx(a.fundingTxid);
          return h('a', { class: 'linklike small ark-renew-tx', href: url, target: '_blank', rel: 'noopener',
            onClick: (e) => { e.preventDefault(); openExternal(url); } }, t('arkRenewViewTx'));
        })() : null,
        // a check that failed is retried on the next sync; the reason is a
        // server string nobody should have to read
        a.lastError ? h('div', { class: 'small faint' }, t('arkRenewStageRetry')) : null))) : null;
    const tick = (checked, onChange, title) => h('input', {
      type: 'checkbox', checked, title, style: 'flex:0 0 auto;margin:0', onChange,
    });
    // "Exit now" asks once, with the numbers on the table, before anything
    // is published: an exit cannot be called back.
    if (ui.arkExitConfirm) {
      const savings = wallet.spendable || 0;
      const short = savings < exitFee;
      const row = (k, v, cls = '') => h('div', { class: 'row between' }, h('span', { class: 'small muted' }, k), h('span', { class: 'small' + (cls ? ' ' + cls : '') }, v));
      return h('div', { class: 'col', style: 'gap:16px' },
        h('div', { class: 'card col', style: 'gap:10px' },
          h('h3', { style: 'margin:0' }, t('arkExitConfirmTitle')),
          h('p', { class: 'small muted', style: 'margin:0' }, t('arkExitConfirmBody')),
          h('div', { class: 'col', style: 'gap:4px' },
            row(t('arkExitConfirmCoins'), String(exitable.length)),
            row(t('arkExitConfirmAmount'), fmtSats(exitable.reduce((n, v) => n + v.amountSat, 0)) + ' sats'),
            row(t('arkExitConfirmFee'), fmtSats(exitFee) + ' sats'),
            row(t('arkExitConfirmSavings'), fmtSats(savings) + ' sats', short ? 'err' : '')),
          short ? h('div', { class: 'notice err small' }, t('arkExitFeeShort', { need: fmtSats(exitFee), have: fmtSats(savings) })) : null,
          h('p', { class: 'small muted', style: 'margin:0' }, t('arkExitConfirmWait')),
          h('button', { class: 'btn-primary btn-block', disabled: !!ui.arkBusy || short || !exitable.length, onClick: () => {
            ui.arkExitConfirm = null;
            doArkExit();
            ui.arkCoinsSel = null;
            back();
            ui.tab = 'history'; // the exit lives as a pending record there
            render();
          } }, ui.arkBusy === 'exit' ? h('span', { class: 'spinner sm' }) : t('arkExitConfirmGo'))),
        h('button', { class: 'btn-ghost btn-block', onClick: () => { ui.arkExitConfirm = null; render(); } }, t('cancel')));
    }
    // what a unilateral exit costs, which used to sit under the balance (and
    // only when the coins' chains ran deep): here it is always said
    let depth = null;
    if (embedded) {
      const cached = wallet.loadFeatureState('arkDepth', null);
      const fee = exitFee || (cached && cached.exitFee) || 0;
      if (fee > 0) depth = t('arkDepthNotice', { fee: fmtSats(fee) });
    }
    return h('div', { class: 'col', style: 'gap:16px' },
      h('div', { class: 'card col', style: 'gap:8px' },
        h('h3', { style: 'margin:0' }, t('arkCoinsTitle')),
        depth ? h('div', { class: 'notice info small' }, depth) : null,
        h('p', { class: 'small muted', style: 'margin:0' },
          !spend.length
            ? t('arkCoinsIntroRenewing', { total: fmtSats(heldSat) + ' sats' })
            : spend.length === 1
              ? t('arkCoinsIntroOne', { total: fmtSats(totalSat) + ' sats' })
              : t('arkCoinsIntro', { n: spend.length, total: fmtSats(totalSat) + ' sats' })),
        // One coin per row, two lines: the amount (with its renewal price on
        // the right — the number this page's action spends), then a faint
        // meta line. Five flexed columns fit a laptop but wrapped into
        // confetti on a phone; labels riding inline with each value need no
        // header row and no horizontal budget at all. `.coin` brings the
        // on-chain coin-control look — hairlines between rows, big accent
        // checkboxes — so the two coin pages read as siblings.
        // One coin per row in a headed table — the labels live in the header
        // once instead of on every row as chips. It scrolls sideways on a
        // narrow screen (the wrapper, not the page) rather than wrapping.
        // A tap anywhere on a row toggles it.
        h('div', { class: 'coin-scroll' },
          h('table', { class: 'coin-table' },
            h('thead', {}, h('tr', {},
              h('th', {}, spend.length ? tick(sel.size === ids.size, (e) => {
                ui.arkCoinsSel = e.target.checked ? new Set(ids) : new Set();
                render();
              }, t('arkCoinsSelectAll')) : null),
              h('th', { class: 'num' }, t('arkCoinsColAmount')),
              h('th', { class: 'num', title: t('arkCoinsChipExpTitle') }, t('arkCoinsColExpiry')),
              h('th', { class: 'num', title: t('arkCoinsChipExitTitle') }, t('arkCoinsColExit')),
              h('th', { class: 'num', title: t('arkCoinsChipRenewTitle') }, t('arkCoinsColRenew')))),
            h('tbody', {}, ...spend.map((v) => {
              const f = feeNowOf(v);
              const xf = exitFeeOf(v);
              const past = !!(v.expiryHeight && tip && v.expiryHeight - tip <= 0);
              const due = (past && !honors) || !!v.expiryRejected;
              // expired and under the floor: nothing can renew it, so the
              // last column offers to give it up
              const lost = due && v.amountSat < 330;
              const toggle = () => { sel.has(v.id) ? sel.delete(v.id) : sel.add(v.id); render(); };
              return h('tr', {
                class: 'clickable',
                onClick: (e) => { if (e.target.tagName !== 'INPUT') toggle(); },
              },
                h('td', {}, tick(sel.has(v.id), toggle)),
                h('td', { class: 'num' }, fmtSats(v.amountSat), h('span', { class: 'small faint' }, ' sats')),
                h('td', { class: 'num' + (due ? ' warn' : '') }, expiresOf(v)),
                h('td', { class: 'num' }, xf == null ? '—' : fmtSats(xf), xf == null ? null : h('span', { class: 'small faint' }, ' sats')),
                h('td', { class: 'num' }, lost
                  ? h('button', { class: 'btn-sm', title: t('arkCoinForgetTitle'), onClick: (e) => { e.stopPropagation(); if (mgr.forgetVtxo(v.id)) { sel.delete(v.id); toast(t('arkCoinForgotten')); render(); } } }, t('arkCoinForget'))
                  : renewChip(f)));
            }),
            // the coins in a round: greyed, no checkbox, their column says why
            ...pendingCoins.map((v) => h('tr', { class: 'coin-renewing', style: 'opacity:.6' },
              h('td', {}, ''),
              h('td', { class: 'num' }, fmtSats(v.amountSat), h('span', { class: 'small faint' }, ' sats')),
              h('td', { class: 'num' }, expiresOf(v)),
              h('td', { class: 'num' }, '—'),
              h('td', { class: 'num' }, h('span', { class: 'tag pending' }, t('arkCoinsRenewing'))))))))),
      renewingCard,
      embedded ? custodyCard() : null,
      h('div', { class: 'card col', style: 'gap:8px' },
        h('h4', { style: 'margin:0' }, t('arkCoinsRenewTitle')),
        // the round cadence comes from the server (it has been an hour and
        // is two minutes as of September 2026) — never a number baked in here
        h('p', { class: 'small muted', style: 'margin:0' }, getCustody() === 'custodial' && honors
          ? t('arkCoinsRenewDescCustodial', { every: roundEvery, base: baseSat ? baseCost : t('arkDepthFree') })
          : baseSat
            ? t('arkCoinsRenewDescBase', { every: roundEvery, base: baseCost })
            : t('arkCoinsRenewDesc', { every: roundEvery })),
        schedule.length ? h('div', { class: 'col', style: 'gap:2px;margin:2px 0' },
          ...schedule.map((r) => h('div', { class: 'row between' },
            h('span', { class: 'small muted' }, r.label),
            h('span', { class: 'small' + (r.free ? ' faint' : '') }, r.cost)))) : null,
        !spend.length ? null : h('button', { class: 'btn-primary btn-block ark-renew-ask', disabled: !!ui.arkBusy || !selCoins.length || !ark, onClick: () => { ui.arkRenewConfirm = true; render(); try { window.scrollTo({ top: 0 }); } catch {} } },
          !selCoins.length ? t('arkCoinsRenewNone')
            : selCoins.length < spend.length
              ? t('arkCoinsRenewSome', { n: selCoins.length, fee: selFee > 0 ? fmtSats(selFee) + ' sats' : t('arkDepthFree') })
              : selFee > 0 ? t('arkCoinsRenewNowFee', { fee: fmtSats(selFee) + ' sats' }) : t('arkDepthRenewBtn'))),
      // The ticked coins are what leaves: a subset goes on-chain as exactly
      // those coins (no fresh coin split off the whole balance first), all
      // of them — or nothing ticked — means the whole balance as before.
      (() => {
        const subset = selCoins.length > 0 && selCoins.length < spend.length;
        const coopSat = subset ? selCoins.reduce((n, v) => n + v.amountSat, 0) : spendableSat;
        return h('div', { class: 'card col', style: 'gap:8px' },
          h('h4', { style: 'margin:0' }, t('arkCoinsCoopTitle')),
          h('p', { class: 'small muted', style: 'margin:0' }, t('arkCoopDesc')),
          subset ? h('p', { class: 'small muted', style: 'margin:0' }, selCoins.length === 1 ? t('arkCoopSelectedOne') : t('arkCoopSelected', { n: selCoins.length })) : null,
          h('button', { class: 'btn-primary btn-block ark-coop-go', disabled: !!ui.arkBusy || !coopSat || wallet.watchOnly, onClick: () => {
            const address = wallet.freshReceive().address;
            const vtxoIds = subset ? selCoins.map((v) => v.id) : undefined;
            ui.arkCoinsPage = null; ui.arkCoinsSel = null; ui.arkExitPage = null; ui.arkExitConfirm = null; ui.arkRenewConfirm = null;
            ui.arkOffboarded = null; ui.arkError = '';
            ctx.showSend({ fresh: true });
            ui.arkOffboardSend = { address, amount: String(coopSat), fromCoins: true, vtxoIds };
            render();
          } }, t('arkOffboardBtn', { n: fmtNative(coopSat) })));
      })(),
      h('div', { class: 'card col', style: 'gap:8px' },
        h('h4', { style: 'margin:0' }, t('arkCoinsExitTitle')),
        h('p', { class: 'small muted', style: 'margin:0' },
          exitable.length ? t('arkCoinsExitDesc', { fee: fmtSats(exitFee), after: fmtSats(afterFee) }) : t('arkExitNoneExitable')),
        h('button', { class: 'btn-ghost btn-block', disabled: !!ui.arkBusy || !exitable.length || !mgr, onClick: () => { ui.arkExitConfirm = true; render(); } }, t('arkCoinsExitBtn'))),
      embedded ? null : h('button', { class: 'btn-ghost btn-block', onClick: back }, t('back')));
  }

  // Who holds the coins once their timelock runs out — the user's call, made
  // here, with what each option costs in the server's own numbers. The
  // default is coinos: most people come from v2, where coinos held
  // everything, and the server honors a coin past its timelock anyway. The
  // two renewing tiers are the opt-ins, for those who want the exit kept
  // (self) or kept cheap by flattening deep histories early (exit). Only
  // shown on a server that honors expired coins; elsewhere renewal is the
  // only way to keep money.
  function custodyCard() {
    if (!arkAvailable() || wallet.watchOnly) return null;
    const cfg = getArkConfig();
    const view = arkView();
    const info = (view && view.info) || (cachedArkInfo(cfg && cfg.ark) || {}).info || null;
    const honors = !!(cfg && cfg.honorsExpired);
    const cur = honors ? getCustody() : 'self';
    const base = (info && info.refreshFees && info.refreshFees.baseFeeSat) || 0;
    const table = (info && info.refreshFees && info.refreshFees.ppmExpiryTable) || [];
    const ppmAt = (blocks) => (table.filter((e) => e.thresholdBlocks <= blocks).pop()?.ppm) ?? 0;
    const lifeDays = Math.max(1, Math.round(((info && info.vtxoExpiryDelta) || 8640) / 144));
    const baseCost = !info ? '…' : base ? fmtSats(base) + ' sats' : t('arkDepthFree');
    // an early renewal pays the bracket a fresh coin sits in (the top one)
    const earlyPct = pct(ppmAt(((info && info.vtxoExpiryDelta) || 8640) - 1));
    const hops = (renewPolicy('exit', getNetwork()) || {}).maxDepth || 4;
    const tiers = [
      { id: 'custodial', label: t('arkCustodyCustodial'), desc: t('arkCustodyCustodialDesc'), cost: t('arkCustodyCostNone') },
      { id: 'self', label: t('arkCustodySelf'), desc: t('arkCustodySelfDesc', { days: lifeDays }), cost: t('arkCustodyCostSelf', { base: baseCost }) },
      { id: 'exit', label: t('arkCustodyExit'), desc: t('arkCustodyExitDesc', { hops }), cost: t('arkCustodyCostExit', { pct: earlyPct, base: baseCost }) },
    ].filter((x) => honors || x.id !== 'custodial');
    const chosen = tiers.find((x) => x.id === cur) || tiers[0];
    // A drop-down, and only the chosen strategy's description under it: three
    // paragraphs at once read as a wall, and two of them are about choices
    // the reader has not made.
    return h('div', { class: 'card col ark-custody', style: 'gap:10px' },
      h('h4', { style: 'margin:0' }, t('arkCustodyTitle')),
      h('p', { class: 'small muted', style: 'margin:0' }, t('arkCustodyDesc', { days: lifeDays })),
      h('select', { id: 'ark-custody-select', disabled: !honors, onChange: (e) => applyCustody(e.target.value) },
        ...tiers.map((x) => h('option', { value: x.id, selected: x.id === cur }, x.label + ' · ' + x.cost))),
      h('p', { class: 'small muted ark-custody-desc', style: 'margin:0' }, chosen.desc),
      honors ? null : h('p', { class: 'small faint', style: 'margin:0' }, t('arkCustodyNotHere')));
  }

  // What each server charges and promises, from its own published info —
  // laid side by side under the switcher so the choice is an informed one.
  const serverInfos = new Map(); // url -> info | null (failed) | undefined (loading)
  function serverInfo(url) {
    if (!url) return null;
    if (serverInfos.has(url)) return serverInfos.get(url);
    serverInfos.set(url, undefined);
    getArkInfo(url).then((i) => { serverInfos.set(url, i); render(); }).catch(() => { serverInfos.set(url, null); render(); });
    return undefined;
  }
  const pct = (ppm) => (ppm / 10000).toLocaleString(undefined, { maximumFractionDigits: 3 }) + '%';
  const blocksSpan = (b) => (b >= 144 ? Math.round(b / 144) + 'd' : Math.max(1, Math.round(b / 6)) + 'h');
  // an expiry-graded fee: free within N of expiry, else a range
  const gradedFee = (tbl, base = 0, min = 0) => {
    const rows = [...(tbl || [])].sort((a, b) => a.thresholdBlocks - b.thresholdBlocks);
    const paid = rows.filter((r) => r.ppm > 0);
    const parts = [];
    if (base) parts.push(fmtSats(base) + ' sats');
    if (!paid.length) parts.push(t('arkCmpFree'));
    else {
      const lo = Math.min(...paid.map((r) => r.ppm)), hi = Math.max(...paid.map((r) => r.ppm));
      const freeUnder = rows[0].ppm === 0 && paid[0] ? paid[0].thresholdBlocks : 0;
      parts.push((lo === hi ? pct(lo) : pct(lo) + '–' + pct(hi)) + (freeUnder ? ' · ' + t('arkCmpFreeNear', { span: blocksSpan(freeUnder) }) : ''));
    }
    if (min) parts.push(t('arkCmpMin', { n: fmtSats(min) }));
    return parts.join(', ');
  };
  function arkServerCompare(presets) {
    const cols = presets.filter((p) => p.ark && p.id !== 'custom');
    if (cols.length < 2) return null;
    const infos = cols.map((p) => serverInfo(p.ark));
    const cell = (i, f) => (i === undefined ? '…' : i === null ? '—' : f(i));
    const rows = [
      [t('arkCmpRunBy'), cols.map((p) => t(p.id === 'coinos' ? 'arkCmpRunByCoinos' : p.id === 'second' ? 'arkCmpRunBySecond' : 'arkCmpRunByOther'))],
      [t('arkCmpLifetime'), infos.map((i) => cell(i, (x) => blocksSpan(x.vtxoExpiryDelta || 0)))],
      [t('arkCmpRounds'), infos.map((i) => cell(i, (x) => t('arkCmpEvery', { n: Math.max(1, Math.round((x.roundIntervalSecs || 0) / 60)) })))],
      [t('arkCmpRenew'), infos.map((i) => cell(i, (x) => gradedFee((x.refreshFees || {}).ppmExpiryTable, (x.refreshFees || {}).baseFeeSat)))],
      [t('arkCmpLnSend'), infos.map((i) => cell(i, (x) => gradedFee((x.lnSendFees || {}).ppmExpiryTable, (x.lnSendFees || {}).baseFeeSat, (x.lnSendFees || {}).minFeeSat)))],
      [t('arkCmpLnRecv'), infos.map((i) => cell(i, (x) => ((x.lnReceiveFees || {}).ppm || (x.lnReceiveFees || {}).baseFeeSat) ? gradedFee([{ thresholdBlocks: 0, ppm: x.lnReceiveFees.ppm || 0 }], x.lnReceiveFees.baseFeeSat) : t('arkCmpFree')))],
      [t('arkCmpExit'), infos.map((i) => cell(i, (x) => gradedFee((x.offboardFees || {}).ppmExpiryTable, (x.offboardFees || {}).baseFeeSat)))],
      [t('arkCmpBoard'), infos.map((i) => cell(i, (x) => t('arkCmpBoardVal', { min: fmtSats(x.minBoardAmountSat || 0), n: x.requiredBoardConfirmations || 0 })))],
      [t('arkCmpMaxCoin'), infos.map((i) => cell(i, (x) => fmtSats(x.maxVtxoAmountSat || 0) + ' sats'))],
    ];
    return h('div', { class: 'col', style: 'gap:6px' },
      h('table', { class: 'cmp-table' },
        h('thead', {}, h('tr', {}, h('th', {}), ...cols.map((p) => h('th', {}, p.label.replace(/ \(.*\)$/, ''))))),
        h('tbody', {}, ...rows.map(([k, vals]) => h('tr', {}, h('td', { class: 'k' }, k), ...vals.map((v) => h('td', {}, v)))))),
      h('div', { class: 'small faint' }, t('arkCmpNote')));
  }

  // Settings → Advanced: which Ark server. The state is kept per server, so
  // coins held with the old one aren't lost by switching — but they can't be
  // spent from the new one; the card says what's held before it lets go.
  function arkServerCard() {
    if (wallet.watchOnly) return null;
    const net = getNetwork();
    const presets = arkPresets(net);
    const cur = getArkProviderId(net);
    const custom = ui.arkCustomDraft || (ui.arkCustomDraft = getArkCustom(net));
    const held = arkBalance() ? (arkBalance().spendableSat || 0) + (arkBalance().pendingSat || 0) : 0;
    const apply = (id) => {
      if (id === cur && id !== 'custom') return;
      if (id === 'custom' && !(custom.ark && custom.esplora)) { toast(t('arkServerCustomNeeded')); return; }
      if (id === 'custom') setArkCustom(custom, net);
      setArkProviderId(id, net);
      ui.arkSwitchConfirm = null;
      ui.arkRecvAddr = null; // the reusable address belongs to the old server
      stopArk();
      initArk();
      // the payment name's ark= instruction and the nostr advert name the
      // server's address: both follow the switch once the new one answers
      connectArk().then((mgr) => { announceArkAddress(mgr); ctx.hook('namesRefresh'); }).catch(() => {});
      toast(t('arkServerSwitched'));
      render();
    };
    const pick = (id) => {
      if (id === cur) return;
      if (held > 0 && id !== 'custom') { ui.arkSwitchConfirm = id; render(); return; }
      if (id === 'custom') { ui.arkSwitchConfirm = 'custom'; render(); return; }
      apply(id);
    };
    const c = ui.arkSwitchConfirm;
    return h('div', { class: 'card col', style: 'gap:8px' },
      h('h3', {}, t('arkServerTitle')),
      h('p', { class: 'small muted', style: 'margin:0' }, t('arkServerDesc')),
      h('select', { onChange: (e) => pick(e.target.value) },
        ...presets.map((p) => h('option', { value: p.id, selected: p.id === (c || cur) }, p.label))),
      h('button', { class: 'linklike small', style: 'align-self:flex-start', onClick: () => { ui.arkCmpOpen = !ui.arkCmpOpen; render(); } }, ui.arkCmpOpen ? t('arkCmpHide') : t('arkCmpShow')),
      ui.arkCmpOpen ? arkServerCompare(presets) : null,
      (c === 'custom' || cur === 'custom') ? h('div', { class: 'col', style: 'gap:6px' },
        h('input', { type: 'text', placeholder: t('arkServerCustomUrl'), value: custom.ark, autocapitalize: 'none', onInput: (e) => { custom.ark = e.target.value; } }),
        h('input', { type: 'text', placeholder: t('arkServerCustomEsplora'), value: custom.esplora, autocapitalize: 'none', onInput: (e) => { custom.esplora = e.target.value; } })) : null,
      c ? h('div', { class: 'col', style: 'gap:8px' },
        held > 0 ? h('div', { class: 'notice info small' }, t('arkServerSwitchWarn', { amount: fmtSats(held) })) : null,
        h('div', { class: 'row gap6' },
          h('button', { class: 'btn-primary grow', onClick: () => apply(c) }, t('arkServerSwitchGo')),
          h('button', { class: 'btn-ghost grow', onClick: () => { ui.arkSwitchConfirm = null; render(); } }, t('cancel')))) : null);
  }

  function autoWithdrawCard() {
    if (!arkAvailable() || wallet.watchOnly) return null;
    const st = awState();
    const draft = ui.awDraft || (ui.awDraft = { dest: st.dest || '', threshold: String(st.threshold || ''), keep: String(st.keep || '') });
    const save = (on) => {
      const dest = (draft.dest || '').trim();
      const threshold = parseInt(String(draft.threshold).replace(/[^0-9]/g, ''), 10) || 0;
      const keep = parseInt(String(draft.keep).replace(/[^0-9]/g, ''), 10) || 0;
      if (on) {
        if (!awClassify(dest)) { ui.awError = t('awBadDest'); render(); return; }
        if (threshold < 1000) { ui.awError = t('awLowThreshold'); render(); return; }
        if (keep >= threshold) { ui.awError = t('awKeepTooHigh'); render(); return; }
      }
      ui.awError = '';
      awSave({ ...st, on, dest, threshold, keep, failedAt: 0, error: '' });
      writeBgMirror().catch(() => {}); // the worker needs the new destination
      toast(on ? t('awOn') : t('awOff'));
      render();
    };
    return h('div', { class: 'card col' },
      h('h3', {}, t('awTitle')),
      h('p', { class: 'small muted', style: 'margin:0' }, t('awDesc')),
      h('label', { class: 'field' },
        h('span', { class: 'lab' }, t('awDest')),
        h('input', {
          type: 'text', class: 'mono-input', placeholder: t('awDestPh'),
          autocapitalize: 'none', autocomplete: 'off', spellcheck: 'false',
          value: draft.dest,
          onInput: (e) => { draft.dest = e.target.value; },
        })),
      h('div', { class: 'row gap6' },
        h('label', { class: 'field grow' },
          h('span', { class: 'lab' }, t('awThreshold')),
          h('input', {
            type: 'number', inputmode: 'numeric', min: '0', placeholder: '100000',
            value: draft.threshold, onInput: (e) => { draft.threshold = e.target.value; },
          })),
        h('label', { class: 'field grow' },
          h('span', { class: 'lab' }, t('awKeep')),
          h('input', {
            type: 'number', inputmode: 'numeric', min: '0', placeholder: '0',
            value: draft.keep, onInput: (e) => { draft.keep = e.target.value; },
          }))),
      ui.awError ? h('div', { class: 'notice err small' }, ui.awError) : null,
      st.on && st.error ? h('div', { class: 'notice err small' }, t('awLastError', { why: st.error })) : null,
      st.lastAt
        ? h('div', { class: 'small faint' }, t('awLast', { n: fmtAmount(st.lastSat || 0) + ' ' + unitLabel(), when: new Date(st.lastAt).toLocaleString() }))
        : null,
      st.on
        ? h('div', { class: 'row gap6' },
            h('button', { class: 'grow', onClick: () => save(true) }, t('save')),
            h('button', { class: 'btn-ghost', onClick: () => save(false) }, t('awTurnOff')))
        : h('button', { class: 'btn-primary btn-block', onClick: () => save(true) }, t('awTurnOn')));
  }

  // ---- NWC bridge funding (PoC) --------------------------------------------
  // An external NWC wallet service (e.g. coinos) can bridge ark -> lightning:
  // a nostr client asks IT to pay_invoice, it asks US (kind 23196, funding
  // request) to cover the amount over ark, we auto-pay within a user-set
  // allowance and ack (kind 23197). Custody window = seconds in flight.
  // PoC config in localStorage 'btc-wallet-arknwc': { bridgePk, budgetSat }.
  const NWC_FUND_KIND = 23196;
  const NWC_FUND_ACK_KIND = 23197;
  let nwcUnsub = null;
  let nwcSpent = 0;

  function stopNwcFunding() {
    if (nwcUnsub) { try { nwcUnsub(); } catch {} nwcUnsub = null; }
  }

  function startNwcFunding(mgr) {
    if (nwcUnsub || !wallet.nostrSubscribe || !wallet.nostrPubkey || !wallet.nostrPubkey()) return;
    let cfg = null;
    try { cfg = JSON.parse(localStorage.getItem('btc-wallet-arknwc') || 'null'); } catch {}
    if (!cfg || !cfg.bridgePk || !(cfg.budgetSat > 0)) return;
    const seen = new Set();
    nwcUnsub = wallet.nostrSubscribe(
      { kinds: [NWC_FUND_KIND], authors: [cfg.bridgePk], '#p': [wallet.nostrPubkey()] },
      async (ev) => {
        if (seen.has(ev.id)) return;
        seen.add(ev.id);
        let req;
        try { req = JSON.parse(ev.content); } catch { return; }
        const sats = Math.round(req.amountSat || 0);
        if (!sats || !req.address || nwcSpent + sats > cfg.budgetSat) return; // over allowance: bridge times out
        try {
          const actionId = await mgr.send(req.address, sats);
          const action = mgr.state.actions.find((a) => a.id === actionId);
          if (!action || action.step === 'failed') return;
          nwcSpent += sats;
          await wallet.nostrPublish({
            kind: NWC_FUND_ACK_KIND,
            tags: [['p', cfg.bridgePk], ['e', ev.id]],
            content: JSON.stringify({ id: req.id }),
          });
        } catch {}
      });
  }

  // ---- unilateral exit (trustless: no server cooperation) ------------------
  const addrScript = (address) => btc.OutScript.encode(btc.Address(wallet.netCfg.net).decode(address));

  // Smallest confirmed, unreserved coin that can fund a CPFP bump.
  function pickFeeCoin(minSat) {
    return wallet.utxos
      .filter((u) => u.confirmed && !wallet.isReserved(utxoId(u)) && u.value >= minSat)
      .sort((a, b) => a.value - b.value)[0] || null;
  }

  // What a unilateral exit will need from Savings, BEFORE it starts: every
  // chain hop is a zero-fee tx bumped by a ~130 vB CPFP child, plus the
  // final claim. Priced at today's feerate — the driver reprices per hop.
  // Sizes only (exitTxVsizes): building the real signed chain costs several
  // secp256k1 multiplies per hop, and across 27 coins of depth ~13 that was
  // 5+ seconds of main-thread work on every boot (idle callback or not).
  // Fee = size × rate needs none of it. Still memoized on the coin set +
  // feerate, since the advisory asks on every wallet render.
  let _exitFeeMemo = { key: null, val: 0 };
  function estimateExitFeeSat(mgr) {
    const feeRate = Math.max(1, (wallet.feeRates && wallet.feeRates.halfHourFee) || 2);
    const coins = exitableCoins(mgr.state, mgr._tipH || 0);
    const key = feeRate + '|' + coins.map((v) => v.id).join(',');
    if (_exitFeeMemo.key === key) return _exitFeeMemo.val;
    let total = 0;
    for (const v of coins) {
      try {
        for (const vsize of exitTxVsizes(mgr._decoded(v), mgr.serverPub))
          total += Math.ceil((vsize + 130) * feeRate);
        total += Math.ceil(150 * feeRate); // the claim tx
      } catch {}
    }
    _exitFeeMemo = { key, val: total };
    return total;
  }

  async function doArkExit() {
    ui.arkBusy = 'exit'; ui.arkError = ''; render();
    try {
      const mgr = await connectArk();
      const spendables = exitableCoins(mgr.state, mgr._tipH || 0);
      if (!spendables.length) throw new Error(freeCoins(mgr.state).length ? t('arkExitNoneExitable') : t('arkNotConnected'));
      // Fees are paid hop by hop from Savings as the exit unrolls — an exit
      // that can't fund its hops just stalls at step zero. Refuse to start
      // one Savings can't carry, with the number on the table.
      const feeEst = estimateExitFeeSat(mgr);
      if ((wallet.spendable || 0) < feeEst) {
        throw new Error(t('arkExitFeeShort', { need: fmtSats(feeEst), have: fmtSats(wallet.spendable || 0) }));
      }
      for (const v of spendables) mgr.startExit(v.id);
      toast(t('arkExitStarted', { n: spendables.length }));
      driveExits(mgr).catch(() => {});
    } catch (e) {
      ui.arkError = e.message;
    }
    ui.arkBusy = null; render();
  }

  async function driveExits(mgr) {
    const open = mgr.state.actions.filter((a) => a.type === 'exit' && !['done', 'failed'].includes(a.step));
    for (const a of open) {
      try {
        await driveExit(mgr, a);
        if (a.lastError) { delete a.lastError; delete a.actionable; mgr._save(); } // resolved
      } catch (e) {
        a.lastError = e.message;
        a.actionable = !!e.actionable; // user must act (e.g. fund fees) vs. plain retry
        mgr._save();
      }
    }
  }

  // One tick of an exit's state machine: broadcast the next unconfirmed hop
  // (with its fee child) as a package, then wait out the CSV, then claim.
  async function driveExit(mgr, action) {
    const rec = mgr._vtxo(action.vtxoId);
    const decoded = mgr._decoded(rec);
    if (action.step === 'chain') {
      const txs = signedExitTxs(decoded, mgr.serverPub);
      let lastConfirmedHeight = 0;
      let hopsDone = 0;
      for (const txi of txs) {
        const st = await mgr.chain.getTxStatus(txi.txid);
        if (st?.confirmed) { lastConfirmedHeight = st.block_height; hopsDone++; if (action.hopsDone !== hopsDone) { action.hopsDone = hopsDone; mgr._save(); } continue; }
        // /tx/:txid/status answers {confirmed:false} even for UNKNOWN txids
        // (electrs + mempool.space) — only /tx/:txid 404s definitively
        if (await mgr.chain.getTxHex(txi.txid)) return; // in mempool — wait
        // unknown to the chain: submit this hop + CPFP child as a package
        const feeRate = Math.max(1, (wallet.feeRates && wallet.feeRates.halfHourFee) || 2);
        // the child pays for the whole package (the parent is zero-fee)
        const feeSat = Math.ceil((txi.vsize + 130) * feeRate); // child ≈ 130 vB
        const coin = pickFeeCoin(Math.max(294, feeSat - txi.anchorValue + 294));
        if (!coin) {
          // No on-chain coin for the fee child. Try the hop bare — a node
          // that relays zero-fee txs (regtest with minrelaytxfee=0) needs no
          // bump. If it refuses, this is a PRECONDITION the user must fix,
          // not a transient to retry behind a vague message.
          try {
            await submitPackage(mgr.esploraUrl, [txi.hex]);
            mgr._save();
            return;
          } catch {
            const e = new Error(t('arkExitNoFeeCoin', { need: fmtSats(Math.max(294, feeSat)) }));
            e.actionable = true;
            throw e;
          }
        }
        const changeAddr = wallet.freshChange().address;
        const child = buildBumpChild({
          parentTxidInternal: txi.txidInternal, anchorVout: txi.anchorVout, anchorValue: txi.anchorValue,
          coin: {
            txid: coin.txid, vout: coin.vout, value: coin.value,
            pubkey: wallet.derive(coin.chain, coin.index).pubkey,
            privkey: wallet.node(coin.chain, coin.index).privateKey,
          },
          changeScript: addrScript(changeAddr), feeSat,
        });
        await submitPackage(mgr.esploraUrl, [txi.hex, child.hex]);
        // reflect the spent fee coin locally so nothing double-spends it
        wallet.utxos = wallet.utxos.filter((u) => !(u.txid === coin.txid && u.vout === coin.vout));
        const ce = wallet.addrMap.get(changeAddr);
        if (ce) wallet.utxos.push({ txid: child.txid, vout: 0, value: child.changeSat, address: changeAddr, chain: ce.chain, index: ce.index, confirmed: false });
        wallet._recomputeBalanceFromUtxos();
        wallet.saveCache();
        action.bumpTxid = child.txid;
        mgr._save();
        return; // one hop per tick (TRUC: single unconfirmed parent)
      }
      // whole chain confirmed — start the CSV clock from the vtxo tx's height
      action.claimableAt = lastConfirmedHeight + decoded.exitDelta;
      action.step = 'timelock';
      mgr._save();
    }
    if (action.step === 'timelock') {
      const tip = await mgr.chain.tipHeight();
      if (action.tipSeen !== tip) { action.tipSeen = tip; mgr._save(); } // for the blocks-left display
      if (tip < action.claimableAt) return;
      const keys = mgr._keyForVtxo(rec);
      const feeRate = Math.max(1, (wallet.feeRates && wallet.feeRates.halfHourFee) || 2);
      const claim = buildExitClaim({
        vtxo: decoded, keys, serverPub: mgr.serverPub,
        destScript: addrScript(wallet.freshReceive().address), feeRate,
      });
      await mgr.chain.broadcastTx(claim.hex);
      rec.state = 'spent';
      action.claimTxid = claim.txid;
      action.step = 'claiming';
      mgr._movement({ type: 'exit', amountSat: claim.amountSat, status: 'complete', txid: claim.txid, detail: `fee ${claim.feeSat} sat` });
      mgr._save();
      wallet.scan().catch(() => {});
    }
    if (action.step === 'claiming') {
      const st = await mgr.chain.getTxStatus(action.claimTxid);
      if (!st?.confirmed) return;
      action.step = 'done';
      mgr._save();
    }
  }

  // ---- ark gifts: bearer-key vtxos ----------------------------------------
  // Ark can't presign a bearer spend (every arkoor needs a live server cosign),
  // so an ark gift is a vtxo sent to an ephemeral ark identity whose seed IS
  // the link. The claimer rebuilds the identity from the code, reads the
  // gift's mailbox for the vtxo, and sweeps it to their own ark address —
  // instant and free. The sender keeps the secret too, which is what makes
  // revoke possible (sweep it back before it's claimed; first cosign wins).
  const AG_MAGIC = 0x11;
  const AG_NET = { mainnet: 0, testnet: 1, signet: 2, mutinynet: 3, regtest: 4 };
  const AG_NET_BY = Object.fromEntries(Object.entries(AG_NET).map(([k, v]) => [v, k]));

  function encodeArkGiftCode(net, amountSat, secret) {
    const b = new Uint8Array(42);
    b[0] = AG_MAGIC;
    b[1] = AG_NET[net] ?? 0;
    new DataView(b.buffer).setBigUint64(2, BigInt(amountSat), true);
    b.set(secret, 10);
    return base32nopad.encode(b);
  }

  function decodeArkGiftCode(code) {
    try {
      const b = base32nopad.decode(String(code || '').toUpperCase());
      if (b.length !== 42 || b[0] !== AG_MAGIC || !(b[1] in AG_NET_BY)) return null;
      return {
        net: AG_NET_BY[b[1]],
        amountSat: Number(new DataView(b.buffer, b.byteOffset).getBigUint64(2, true)),
        secretHex: hex.encode(b.slice(10)),
      };
    } catch { return null; }
  }

  // A manager over the gift identity. State persists per device (keyed by the
  // secret's hash) so a claim interrupted mid-sweep resumes checkpointed.
  async function giftManager(secretHex) {
    const cfg = getArkConfig();
    if (!cfg) throw new Error(t('arkNotConnected'));
    const key = 'btc-wallet-arkgift:' + hex.encode(sha256(hex.decode(secretHex))).slice(0, 24);
    const mgr = new ArkManager({
      account: HDKey.fromMasterSeed(hex.decode(secretHex)),
      storage: {
        load: () => { try { return JSON.parse(localStorage.getItem(key) || 'null'); } catch { return null; } },
        save: (s) => { try { localStorage.setItem(key, JSON.stringify(s)); } catch {} },
      },
      arkUrl: cfg.ark, esploraUrl: cfg.esplora, network: getNetwork(), honorsExpired: !!cfg.honorsExpired,
    });
    await mgr.init();
    return mgr;
  }

  // The gift vtxo's key/outpoint for direct status checks (receive key 0).
  const giftKey0 = (secretHex) => {
    const n = HDKey.fromMasterSeed(hex.decode(secretHex)).deriveChild(3).deriveChild(0);
    return n.privateKey;
  };
  const pointRawFromId = (id) => {
    const [txid, vout] = id.split(':');
    const raw = new Uint8Array(36);
    raw.set(hex.decode(txid).reverse(), 0);
    new DataView(raw.buffer).setUint32(32, Number(vout), true);
    return raw;
  };

  function arkGiftRecords() {
    if (!ark || !ark.state) return [];
    return (ark.state.gifts = ark.state.gifts || []);
  }

  // A gift's record id IS the destination vtxo of the send that funded it, so
  // the history row and detail view can recognise their own gift sends.
  const giftForMovement = (m) => (m && m.type === 'send' && m.vtxoId
    ? arkGiftRecords().find((g) => g.id === m.vtxoId) : null);

  // Lazily mark records whose vtxo the server reports spent (claimed — or our
  // own revoke). Throttled: this is called from the gift card's render path.
  let arkGiftsCheckedAt = 0;
  function refreshArkGiftRecords() {
    if (!ark || Date.now() - arkGiftsCheckedAt < 30_000) return;
    arkGiftsCheckedAt = Date.now();
    const open = arkGiftRecords().filter((g) => !g.revoked && !g.claimed);
    Promise.all(open.map(async (g) => {
      try {
        const st = await getVtxoStatus(ark.arkUrl, pointRawFromId(g.id), giftKey0(g.secretHex));
        if (st === VTXO_STATE_SPENT) { g.claimed = true; return true; }
      } catch {}
      return false;
    })).then((flags) => { if (flags.some(Boolean)) ark._save(); });
  }

  // Fund a fresh bearer gift identity. Shared by the gifts feature's hook and
  // the zap flow's locked-gift fallback; `lockedTo` records who a locked gift
  // was for (the sender can still revoke either kind while unclaimed).
  async function createArkGift(amountSat, lockedTo = null) {
    const mgr = await connectArk();
    const secret = crypto.getRandomValues(new Uint8Array(32));
    const secretHex = hex.encode(secret);
    const gm = await giftManager(secretHex);
    const address = gm.address();
    const actionId = await mgr.send(address, amountSat);
    const action = mgr.state.actions.find((a) => a.id === actionId);
    if (!action || action.step === 'failed') throw new Error(action?.error || t('claimFailed'));
    const vtxoId = decodeVtxo(hex.decode((action.destBytesList || [action.destBytes])[0])).id;
    arkGiftRecords().push({ id: vtxoId, amountSat, secretHex, created: Date.now(), revoked: false, claimed: false, ...(lockedTo ? { lockedTo } : {}) });
    mgr._save();
    return { code: encodeArkGiftCode(getNetwork(), amountSat, secret), amount: amountSat, address };
  }

  // Sweep the gift identity's balance to `destAddress`. Shared by claim
  // (recipient's address) and revoke (sender's own address).
  async function sweepArkGift(code, destAddress) {
    const g = decodeArkGiftCode(code);
    if (!g) throw new Error('not an ark gift');
    if (g.net !== getNetwork()) throw new Error(t('arkGiftWrongNet', { net: g.net }));
    const gm = await giftManager(g.secretHex);
    await gm.sync();
    await gm.reconcile().catch(() => {});
    const amount = gm.balance().spendableSat;
    if (!amount) throw Object.assign(new Error(t('giftTakenTitle')), { giftTaken: true });
    await gm.send(destAddress, amount);
    return amount;
  }

  // Offboard the whole ark balance back into this wallet's own on-chain
  // receive address — the mirror image of boarding.
  // Offboard `amountSat` (or everything when omitted). An offboard moves
  // whole vtxos — no change — so a partial amount first mints an exact-amount
  // vtxo via a self-send (regtest-verified: the mailbox delivers self-sends),
  // then exits just that one. The number the user typed is the number that
  // leaves Spending; fees come off what arrives in Savings.
  // Send-to-on-chain from Spending: amount in, exit out — an offboard whose
  // destination is whatever address was pasted.
  // The cooperative fee, asked of the ASP for the address on screen: what
  // the send costs and the smallest balance it can move, before anyone taps.
  async function quoteOffboard(o, address) {
    o.quoteFor = address; o.quote = null;
    let quote = null;
    try { quote = await (await connectArk()).offboardQuote(addrScript(address), o.vtxoIds); }
    catch {} // no quote: the send itself still says what went wrong
    if (o.quoteFor !== address) return; // the address changed meanwhile
    o.quote = quote; o.quoteDone = true;
    if (ui.arkOffboardSend === o) render();
  }
  function arkOffboardSendView() {
    const o = ui.arkOffboardSend;
    // chosen coins: the amount is theirs and is not a field
    const chosen = o.vtxoIds ? freeCoins(arkStateNow()).filter((v) => o.vtxoIds.includes(v.id)) : null;
    const spendable = chosen ? chosen.reduce((n, v) => n + v.amountSat, 0) : (arkBalance()?.spendableSat || 0);
    if (o.quoteFor !== o.address) {
      o.quote = null; o.quoteDone = false; o.quoteFor = o.address;
      let ok = false; try { addrScript(o.address); ok = true; } catch {}
      if (ok) quoteOffboard(o, o.address); else o.quoteDone = true;
    }
    const q = o.quote;
    const tooSmall = !!q && spendable < q.minSat;
    return h('div', { class: 'card col', style: 'gap:12px' },
      h('h3', {}, t(o.fromCoins ? 'arkCoinsCoopTitle' : 'arkExitSendTitle')),
      h('label', { class: 'field' },
        h('span', { class: 'lab' }, t('recipient')),
        h('input', { type: 'text', class: 'mono-input', value: o.address, spellcheck: 'false', autocomplete: 'off', autocapitalize: 'none',
          onInput: (e) => { o.address = e.target.value.trim(); },
          onChange: () => render() })), // a new address gets its own quote
      h('div', { class: 'small faint' }, t('arkExitSendNote')),
      q ? h('div', { class: 'small muted' }, t('arkOffboardQuote', {
        fee: fmtSats(q.totalSat), chain: fmtSats(q.chainSat), service: fmtSats(q.serviceSat), min: fmtSats(q.minSat),
      })) : !o.quoteDone ? h('div', { class: 'small faint' }, t('arkOffboardQuoting')) : null,
      tooSmall ? h('div', { class: 'notice' }, t('arkOffboardBelowMin', { n: fmtSats(spendable), min: fmtSats(q.minSat) })) : null,
      chosen ? h('div', { class: 'small ark-coop-chosen' }, chosen.length === 1 ? t('arkCoopSelectedAmtOne', { amount: fmtSats(spendable) + ' sats' }) : t('arkCoopSelectedAmt', { n: chosen.length, amount: fmtSats(spendable) + ' sats' }))
        : h('div', { class: 'input-group' },
          h('input', { type: 'number', min: '1', placeholder: String(spendable), value: o.amount,
            onInput: (e) => { o.amount = e.target.value; } }),
          h('button', { type: 'button', onClick: () => { o.amount = String(spendable); render(); } }, t('max'))),
      ui.arkError ? h('div', { class: 'notice err' }, ui.arkError) : null,
      h('div', { class: 'row gap6' },
        h('button', { class: 'btn-ghost grow', onClick: () => {
          ui.arkOffboardSend = null; ui.arkError = ''; ui.send = blankSend();
          if (o.fromCoins) ctx.goBack(() => ctx.openWalletSettings('spending')); else render();
        } }, t('back')),
        ui.arkBusy === 'offboard'
          ? h('button', { class: 'btn-primary grow', disabled: true }, h('span', { class: 'spinner sm' }))
          : h('button', { class: 'btn-primary grow', disabled: tooSmall, onClick: () => {
              const amount = chosen ? String(spendable) : String(o.amount ?? '').trim();
              const sats = amount ? Number(amount) : spendable;
              if (!Number.isSafeInteger(sats) || sats <= 0 || sats > spendable) { ui.arkError = t('enterValidAmtForN', { n: 1 }); render(); return; }
              try { addrScript(o.address); } catch { ui.arkError = t('arkOffboardBadAddress'); render(); return; }
              // checked before a partial amount is split off into its own coin
              if (q && sats < q.minSat) {
                ui.arkCoopFailed = false;
                ui.arkError = t('arkOffboardAmtBelowMin', { min: fmtSats(q.minSat), fee: fmtSats(q.totalSat) }); render(); return;
              }
              doArkOffboard(sats >= spendable ? 0 : sats, o.address, chosen ? o.vtxoIds : undefined);
            } }, t('arkSendBtn'))),
      // This send IS the cooperative exit. The trustless fallback only
      // appears when cooperation actually failed (not when the amount was
      // just too small for the fees) — and it states, before
      // anything is confirmed, exactly what it does and what the mining
      // fees from Savings will be.
      (() => {
        if (!ui.arkError || !ui.arkCoopFailed || ui.arkBusy === 'offboard' || !ark) return null;
        let feeEst = 0;
        try { feeEst = estimateExitFeeSat(ark); } catch {}
        const balance = arkBalance()?.spendableSat || 0;
        // A trustless exit that costs more than it moves isn't an option,
        // it's a trap — say so, and point at the road that actually fits a
        // small balance: Lightning carries no mining fees at all.
        if (feeEst >= balance) {
          return h('div', { class: 'col', style: 'gap:8px;border-top:1px solid var(--border,rgba(128,128,128,.2));padding-top:10px' },
            h('div', { class: 'small muted' }, t('arkUniUneconomical', { fee: fmtSats(feeEst), n: fmtSats(balance) })));
        }
        const savings = wallet.spendable || 0;
        const short = savings < feeEst;
        return h('div', { class: 'col', style: 'gap:8px;border-top:1px solid var(--border,rgba(128,128,128,.2));padding-top:10px' },
          h('div', { class: 'small muted' }, t('arkUniFallbackBody', { fee: fmtSats(feeEst) })),
          short ? h('div', { class: 'small err' }, t('arkUniFallbackShort', { need: fmtSats(feeEst), have: fmtSats(savings) })) : null,
          h('button', {
            class: 'btn-block', disabled: !!ui.arkBusy || short,
            onClick: () => {
              ui.arkOffboardSend = null; ui.arkError = ''; ui.send = blankSend();
              doArkExit();
              ui.tab = 'history'; // the exit lives as a pending record there
              render();
            },
          }, t('arkUniFallbackBtn', { fee: fmtSats(feeEst) })));
      })());
  }

  // vtxoIds: exactly these coins go (the coins page's ticked subset);
  // otherwise an amount is split off the balance, or everything goes.
  async function doArkOffboard(amountSat, destAddress = null, vtxoIds = undefined) {
    ui.arkBusy = 'offboard'; ui.arkError = ''; ui.arkCoopFailed = false; render();
    try {
      const address = destAddress || wallet.freshReceive().address;
      const spk = addrScript(address);
      const mgr = await connectArk();
      const spendables = () => freeCoins(mgr.state);
      const total = spendables().reduce((n, v) => n + v.amountSat, 0);
      let ids = vtxoIds; // undefined = all spendable vtxos
      if (!ids && amountSat && amountSat < total) {
        let target = spendables().find((v) => v.amountSat === amountSat);
        if (!target) {
          const before = new Set(spendables().map((v) => v.id));
          await mgr.send(mgr.address(), amountSat);
          for (let i = 0; i < 30 && !target; i++) {
            await new Promise((r) => setTimeout(r, 2000));
            await mgr.sync().catch(() => {});
            target = spendables().find((v) => v.amountSat === amountSat && !before.has(v.id));
          }
          if (!target) throw new Error(t('arkSplitTimeout'));
        }
        ids = [target.id];
      }
      const action = await mgr.startOffboard(spk, address, ids);
      ui.arkOffboardAmt = '';
      ui.arkMoveOpen = false;
      if (ui.arkOffboardSend?.fromCoins) ui.tab = 'receive';
      ui.arkOffboardSend = null;
      ui.send = blankSend();
      ui.arkOffboarded = { txid: action.txid, netSat: action.netSat, feeSat: action.feeSat };
      wallet.scan().catch(() => {}); // surface the incoming pending tx promptly
    } catch (e) {
      ui.arkCoopFailed = !e.tooSmall;
      ui.arkError = e.tooSmall ? t('arkOffboardAmtBelowMin', { min: fmtSats(e.minSat), fee: fmtSats(e.feeSat) }) : e.message;
    }
    ui.arkBusy = null; render();
  }

  // VTXO upkeep, by the user's choice of custody (Settings → Spending):
  //   custodial (the default) — nothing renews. A coin past its timelock is
  //     coinos's IOU: the server sweeps the tree and keeps cosigning spends of
  //     the coin (captaind allow_expired_arkoor), so the balance works as a v2
  //     one did, and no renewal fee is ever paid. The holder trusts coinos.
  //   self — renew in the last hours before expiry, the free ppm bracket, one
  //     base fee per round (~300 sats): a unilateral exit is always possible.
  //   exit — the same, plus a coin is renewed as soon as its history is four
  //     hops deep: an exit pays one on-chain transaction per hop, so this
  //     keeps the exit price of every coin near a fresh coin's. Costs the
  //     top bracket + base each time, so only for coins worth it.
  // The policy's window is when THIS app renews a coin (blocks of life left);
  // margin/grid aim the SERVER's own backstop order — a participation the ASP
  // runs on its own, registered far in advance, snapped to a grid so every
  // wallet's orders share one round. renewPolicy() in ark/manager.js.
  //
  // Consolidation is gone from here: it used to trigger at 20 coins, bill the
  // top ppm bracket on every fresh coin, and was 84% of all renewal fees paid
  // in Sep–Oct 2026 — the "money draining" people saw. Multi-input sends take
  // up to MAX_SEND_INPUTS coins; small change folds into a renewal that is
  // happening anyway, for next to nothing; the Manage page consolidates on
  // request.
  const CUSTODY_DEFAULT = 'custodial';
  function getCustody() {
    let v = wallet.loadFeatureState ? wallet.loadFeatureState('arkCustody', null) : null;
    if (v === 'early') v = 'exit'; // the third tier's first name (one day in October 2026)
    return CUSTODY_TIERS.includes(v) ? v : CUSTODY_DEFAULT;
  }
  function setCustody(tier) { if (wallet.saveFeatureState) wallet.saveFeatureState('arkCustody', tier); }
  const custodyPolicy = () => renewPolicy(getCustody(), getNetwork());
  // Switching: a renewing tier starts covering coins right away (the throttles
  // are reset so the next sync registers backstops and renews what is due),
  // and the worker's mirror learns the tier so closed-app renewals follow it.
  // Orders already registered with the server keep running whatever the tier
  // (there is no cancel; a spent input voids one) — they were priced when
  // registered and renew one coin each, once.
  function applyCustody(tier) {
    if (!CUSTODY_TIERS.includes(tier) || tier === getCustody()) return;
    setCustody(tier);
    arkAutoRefreshAt = 0; arkBackstopAt = 0; arkRenewWarn = null;
    if (ark && ark.state) maybeAutoRefresh(ark).catch(() => {});
    writeBgMirror().catch(() => {});
    toast(t('arkCustodySaved'));
    render();
  }
  let arkAutoRefreshAt = 0;
  let arkBackstopAt = 0;
  // Set when the balance is too small to renew itself (total minus round fee
  // under the server's 330-sat output minimum) AND a vtxo is inside the
  // renewal window: { deadlineMs, sat }. The wallet-screen notice reads this.
  let arkRenewWarn = null;
  // Pasting your OWN ark address — or a coinos name that resolves to it —
  // is never a payment: it means "top up Spending". Route to the board
  // panel, funded from on-chain Savings; prefill an amount when the caller
  // has one (the review path carries the typed amount, paste-time has none
  // and the panel's own field takes over).
  async function boardOwnAddress(addr, { connect = false, amountSat = 0 } = {}) {
    if (!arkAvailable() || wallet.watchOnly) return false;
    let mgr = ark;
    if (!mgr) {
      if (!connect) return false;
      try { mgr = await connectArk(); } catch { return false; }
    }
    try { if (addr !== mgr.address()) return false; } catch { return false; }
    ctx.goHome();
    ui.arkMoveOpen = true;
    ui.arkMoveDir = 'toSpending';
    ui.arkBoardAmt = amountSat > 0 ? String(amountSat) : '';
    ui.send = blankSend();
    ui.sendError = '';
    toast(t('arkOwnAddrBoard'));
    render();
    return true;
  }

  async function maybeAutoRefresh(mgr) {
    if (wallet.watchOnly || !mgr || !mgr.state) return;
    if (Date.now() - arkAutoRefreshAt < 30 * 60_000) return;
    const policy = custodyPolicy();
    // "coinos holds my coins": nothing renews on its own and nothing warns.
    // The server honors a coin past its timelock, and the holder chose this.
    if (!policy) { arkRenewWarn = null; return; }
    // NOT filtered by expiryRejected. A coin the server refused as expired
    // can still be REFRESHED — that is the one thing an expired vtxo can
    // always do — and excluding it here meant a wallet holding nothing else
    // did nothing at all: no renewal attempt, and no warning either.
    const spendables = freeCoins(mgr.state);
    if (!spendables.length) { arkRenewWarn = null; return; }
    // Register the server-side backstop for anything not covered yet. Ahead
    // of the in-flight guard below on purpose: a standing order takes no coin
    // and starts no round, so a send in progress is no reason to skip the one
    // renewal that survives the app never being opened again. Stamped on its
    // own clock — the guard below can return before the refresh throttle is
    // stamped, and this must not then run on every five-second sync.
    if (Date.now() - arkBackstopAt > 30 * 60_000) {
      arkBackstopAt = Date.now();
      await mgr.ensureScheduledRefreshes(policy.margin, 8, policy.grid).catch(() => {});
    }
    // never start a round while any other action is still in flight
    if ((mgr.state.actions || []).some((a) => !['done', 'failed'].includes(a.step))) return;
    arkAutoRefreshAt = Date.now();
    try {
      const tip = await mgr.chain.tipHeight();
      const expiringCoins = spendables.filter((v) => v.expiryHeight && v.expiryHeight - tip < policy.window);
      // The exit tier also renews a coin whose history has grown deep — each
      // hop is one more on-chain transaction in a unilateral exit — but only
      // a coin worth it: never more than a tenth of the coin on its renewal
      // (300 sats to flatten a 21-sat coin's history would be absurd, and
      // such a coin's exit is uneconomic whatever its depth).
      const depthOf = (v) => { try { return mgr._decoded(v).genesis.length; } catch { return 0; } };
      const deepCoins = !policy.maxDepth ? [] : spendables.filter((v) =>
        !expiringCoins.includes(v) && depthOf(v) >= policy.maxDepth && mgr.refreshFee([v], tip) * 10 <= v.amountSat);
      if (!expiringCoins.length && !deepCoins.length) { arkRenewWarn = null; return; }
      if (!expiringCoins.length) {
        // nothing is expiring: this round is for the deep coins alone, and
        // they pay for it — the floor logic below still applies
        arkRenewWarn = null;
        let renewSet = [...deepCoins, ...spendables.filter((v) => !deepCoins.includes(v) && v.amountSat < 1000)];
        const netSat = (set) => set.reduce((n, v) => n + v.amountSat, 0) - mgr.refreshFee(set, tip);
        if (netSat(renewSet) < 330) return;
        await mgr.refresh(renewSet.map((v) => v.id));
        render();
        return;
      }
      const totalSat = spendables.reduce((n, v) => n + v.amountSat, 0);
      const renewable = totalSat - mgr.refreshFee(spendables, tip) >= 330;
      if (!renewable) {
        // Can't save these coins ourselves — tell the user while receiving
        // any amount (or spending) can still beat the clock.
        const minExpiry = Math.min(...spendables.map((v) => v.expiryHeight || Infinity));
        const blockMs = getNetwork() === 'regtest' ? 10_000 : 600_000;
        arkRenewWarn = { deadlineMs: Date.now() + Math.max(0, minExpiry - tip) * blockMs, sat: totalSat };
        notifyRenewWarn();
        render();
        return;
      }
      arkRenewWarn = null;
      // Renew ONLY the coins that need it: dragging far-from-expiry coins
      // into the round would bill their (higher) fee bracket for nothing.
      // Small change rides along, though: a coin under 1,000 sats costs at
      // most 2 sats of ppm in this round, and folding it in now spares it a
      // whole base fee's worth of round of its own when its turn comes.
      let renewSet = [...expiringCoins, ...deepCoins, ...spendables.filter((v) => !expiringCoins.includes(v) && !deepCoins.includes(v) && v.amountSat < 1000)];
      // The set must clear the server's 330-sat output floor BY ITSELF — the
      // renewable check above prices the whole balance. Two dust coins at
      // expiry (133 sats between them) failed their renewal round silently
      // every 30 minutes forever. Pull in the smallest healthy coins until the
      // renewed output is mintable.
      const extras = spendables
        .filter((v) => !renewSet.includes(v))
        .sort((a, b) => a.amountSat - b.amountSat);
      const netSat = (set) => set.reduce((n, v) => n + v.amountSat, 0) - mgr.refreshFee(set, tip);
      while (netSat(renewSet) < 330 && extras.length) renewSet = [...renewSet, extras.shift()];
      if (netSat(renewSet) < 330) return; // whole balance can't clear the floor — the warn above covers it
      await mgr.refresh(renewSet.map((v) => v.id));
      render();
    } catch {} // transient — the next throttled attempt retries
  }

  // A local heads-up (at most one a day) for users who granted notifications —
  // the in-app notice alone can't reach someone who isn't looking.
  function notifyRenewWarn() {
    try {
      if (typeof Notification === 'undefined' || Notification.permission !== 'granted') return;
      const KEY = 'arkRenewNotifiedAt';
      if (Date.now() - (Number(localStorage.getItem(KEY)) || 0) < 24 * 3600_000) return;
      localStorage.setItem(KEY, String(Date.now()));
      const body = t('arkRenewWarnPush', {
        date: new Date(arkRenewWarn.deadlineMs).toLocaleDateString(),
      });
      navigator.serviceWorker?.ready
        .then((reg) => reg.showNotification('coinos', { body }))
        .catch(() => { try { new Notification('coinos', { body }); } catch {} });
    } catch {}
  }

  // Moving money between the two balances, in plain terms. This is the only
  // place the two rails meet, and it never names them: Saving is on-chain,
  // Spending is instant, and the wallet handles the rest.
  // Amount field with an inline Max — a text affordance inside the input's
  // right edge rather than a button eating a third of the row.
  function amountField({ value, onInput, maxSat, placeholder, onMax }) {
    return h('div', { class: 'amt-field' },
      h('input', {
        type: 'number', inputmode: 'numeric', min: '0', placeholder,
        value: value || '',
        onInput,
      }),
      maxSat > 0
        ? h('button', { type: 'button', class: 'amt-max', onClick: onMax }, t('max'))
        : null);
  }

  // Boarding drains an on-chain balance, so Max must leave room for the
  // mining fee: ask the tx builder what a sweep would actually deliver — TO
  // THE REAL OUTPUT SHAPE. The board funding address is P2TR, 12 vbytes
  // bigger than this wallet's P2WPKH change; drafting the sweep against
  // change priced Max a dozen sats past what the funding transaction could
  // carry, and tapping Max earned "insufficient funds". The manager's own
  // key stands in for the funding key — same size, always a valid point.
  function maxBoardSat() {
    try {
      return Math.max(0, previewBoardFunding(wallet, ark, 0, true).fundingSat);
    } catch {
      return 0;
    }
  }

  // The ASP decides how many confirmations a board needs — say that number,
  // not a hardcoded one that contradicts the n/need counter under the balance.
  const boardedNote = () => {
    const n = (ark && ark.info && ark.info.requiredBoardConfirmations) || 1;
    return n === 1 ? t('arkBoardedNoteOne') : t('arkBoardedNote', { n });
  };

  // An ASP pauses boarding by asking a minimum no board could meet (ours
  // did on 2026-10-05, for an upstream captaind fix); say so instead of
  // quoting a 21M BTC minimum. Lowering the minimum again lifts it here.
  const boardsPaused = () => ((ark && ark.info && ark.info.minBoardAmountSat) || 0) >= 2_100_000_000_000_000;
  function boardForm() {
    if (boardsPaused()) return h('div', { class: 'notice small' }, t('arkBoardPaused'));
    const minBoard = (ark && ark.info && ark.info.minBoardAmountSat) || 0;
    const canBoard = wallet.spendable >= minBoard;
    return h('div', { class: 'col', style: 'width:100%;gap:8px' },
      h('div', { class: 'input-group' },
        amountField({
          value: ui.arkBoardAmt,
          placeholder: t('arkOffboardAmtPlaceholder'), // the minimum is stated below
          onInput: (e) => { ui.arkBoardAmt = e.target.value; render(); },
          maxSat: canBoard ? wallet.spendable : 0,
          onMax: () => { ui.arkBoardAmt = String(maxBoardSat()); render(); },
        }),
        h('button', { class: 'btn-primary', disabled: !!ui.arkBusy || !canBoard, onClick: doArkBoard },
          ui.arkBusy === 'board' ? h('span', { class: 'spinner sm' }) : t('arkBoardBtn'))),
      (() => {
        const sats = parseInt((ui.arkBoardAmt || '').trim(), 10);
        if (!sats || sats < minBoard || !ark) return null;
        try {
          const quote = previewBoardFunding(wallet, ark, sats);
          return h('div', { class: 'col small muted', style: 'text-align:center;gap:4px' },
            t('arkBoardFeeNote', { fee: quote.feeSat.toLocaleString(), net: quote.netSat.toLocaleString() }),
            h('div', { class: 'small faint' },
              t('arkFeeChain') + ': ' + fmtAmount(quote.chainFeeSat) + ' ' + unitLabel() + ' · '
              + t('arkFeeService') + ': ' + fmtAmount(quote.serviceFeeSat) + ' ' + unitLabel()));
        } catch (e) {
          return h('div', { class: 'notice err small' }, e.message);
        }
      })(),
      canBoard
        ? h('div', { class: 'small faint', style: 'text-align:center' },
            t('arkBoardAvailable', { n: fmtAmount(wallet.spendable) + ' ' + unitLabel() }))
        : h('div', { class: 'small faint', style: 'text-align:center' },
            t('arkBoardNoFunds', { n: minBoard.toLocaleString() })));
  }

  // Moving money between the two balances, inline on the balance card — the
  // one door between the rails opens right where the balances live.
  function movePanel() {
    if (!ark) connectArk().catch(() => {});
    const dir = ui.arkMoveDir || 'toSpending';
    const b = arkBalance();
    return h('div', { class: 'col balance-move' },
      h('div', { class: 'seg' },
        h('button', { class: dir === 'toSpending' ? 'active' : '', onClick: () => { ui.arkMoveDir = 'toSpending'; ui.arkError = ''; render(); } }, t('moveToSpending')),
        h('button', { class: dir === 'toSaving' ? 'active' : '', onClick: () => { ui.arkMoveDir = 'toSaving'; ui.arkError = ''; render(); } }, t('moveToSaving'))),
      dir === 'toSpending'
        ? h('div', { class: 'col', style: 'gap:8px' },
            h('p', { class: 'small muted', style: 'margin:0' }, t('moveToSpendingDesc')),
            ark ? boardForm() : h('div', { class: 'row gap6', style: 'align-items:center' },
              h('span', { class: 'spinner sm' }), h('span', { class: 'small muted' }, t('arkConnecting'))))
        : h('div', { class: 'col', style: 'gap:8px' },
            h('p', { class: 'small muted', style: 'margin:0' }, t('moveToSavingDesc')),
            // no "X sats in Spending" line — the balance sits right above on this card
            (() => {
              const spendable = b ? b.spendableSat : 0;
              const sats = parseInt((ui.arkOffboardAmt || '').trim(), 10) || 0;
              const valid = sats > 0 && sats <= spendable;
              return h('div', { class: 'col', style: 'gap:8px' },
                h('div', { class: 'input-group' },
                  amountField({
                    value: ui.arkOffboardAmt,
                    placeholder: t('arkOffboardAmtPlaceholder'),
                    onInput: (e) => { ui.arkOffboardAmt = e.target.value; render(); },
                    maxSat: spendable,
                    onMax: () => { ui.arkOffboardAmt = String(spendable); render(); },
                  }),
                  h('button', {
                    class: 'btn-primary', disabled: !!ui.arkBusy || !valid,
                    onClick: () => doArkOffboard(sats),
                  }, ui.arkBusy === 'offboard' ? h('span', { class: 'spinner sm' }) : t('moveToSavingBtn'))),
                ui.arkBusy === 'offboard' && sats < spendable
                  ? h('div', { class: 'small muted', style: 'text-align:center' }, t('arkSplitting'))
                  : null,
                h('button', {
                  class: 'linklike small', style: 'align-self:center',
                  onClick: () => { ui.arkMoveOpen = false; ui.arkExitPage = true; ui.arkError = ''; render(); },
                }, t('arkUniTitle')));
            })()),
      ui.arkError ? h('div', { class: 'notice err' }, ui.arkError) : null,
      // the panel unfolds on the balance card with no obvious way back out —
      // a dismiss returns you to the plain card
      h('button', {
        class: 'linklike small', style: 'align-self:center;margin-top:2px',
        onClick: () => { ui.arkMoveOpen = false; ui.arkError = ''; render(); },
      }, t('cancel')));
  }


  // "Payment received!" takeover for unseen Ark receives.
  function arkCelebration() {
    // An Ark payment landed — same celebration as an on-chain receive, dismissed
    // with a tap (the ack persists in the ark state so it shows exactly once).
    const arkUnseen = ark && ark.state ? ark.unseenReceives() : [];
    if (arkUnseen.length) {
      const amt = arkUnseen.reduce((n, m) => n + m.amountSat, 0);
      return h(
        'div',
        {
          class: 'card col',
          style: 'align-items:center;text-align:center;gap:14px;cursor:pointer;padding:48px 20px',
          onClick: () => { ark.ackReceives(); render(); },
        },
        h('div', { class: 'check-badge' }, '✓'),
        h('h2', { style: 'margin:0' }, t('paymentReceived')),
        amt ? h('div', { class: 'amount-pos', style: 'font-size:18px' }, fmtAmount(amt) + ' ' + unitLabel()) : null,
        h('div', { class: 'small muted' }, t('tapToProceed'))
      );
    }
    return null;
  }

  // Offboard success screen — mirror of the boarded screen.
  function arkOffboardedScreen() {
    if (!ui.arkOffboarded) return null;
    const o = ui.arkOffboarded;
    const url = wallet.api.explorerTx(o.txid);
    return h(
      'div',
      { class: 'card col', style: 'align-items:center;text-align:center;gap:14px;padding:40px 20px' },
      h('div', { class: 'check-badge' }, '✓'),
      h('h2', { style: 'margin:0' }, t('arkOffboardedTitle')),
      h('div', { class: 'amount-pos', style: 'font-size:18px' }, fmtAmount(o.netSat) + ' ' + unitLabel()),
      h('p', { class: 'small muted', style: 'margin:0' }, t('arkOffboardedNote')),
      o.feeSat ? h('div', { class: 'small faint' }, t('feeShort', { x: fmtAmount(o.feeSat) })) : null,
      h('div', { class: 'addr-box', style: 'width:100%' }, o.txid),
      h('div', { class: 'row gap6' },
        copyBtn(o.txid, t('copyTxid')),
        h('a', { class: 'btn btn-sm', href: url, target: '_blank', rel: 'noopener', onClick: (e) => { e.preventDefault(); openExternal(url); } }, t('viewOnMempool'))),
      h('button', { class: 'btn-primary btn-block', onClick: () => { ui.arkOffboarded = null; ui.arkExitPage = null; render(); } }, t('done'))
    );
  }

  // Boarding success screen (txid + explorer link) until dismissed.
  function arkBoardedScreen() {
    // A board just broadcast — show its success screen until dismissed.
    if (ui.arkBoarded) {
      const b = ui.arkBoarded;
      const url = wallet.api.explorerTx(b.txid);
      return h(
        'div',
        { class: 'card col', style: 'align-items:center;text-align:center;gap:14px;padding:40px 20px' },
        h('div', { class: 'check-badge' }, '✓'),
        h('h2', { style: 'margin:0' }, t('arkBoardedTitle')),
        h('div', { class: 'amount-pos', style: 'font-size:18px' }, fmtAmount(b.netSat) + ' ' + unitLabel()),
        h('p', { class: 'small muted', style: 'margin:0' }, boardedNote()),
        h('div', { class: 'addr-box', style: 'width:100%' }, b.txid),
        h('div', { class: 'row gap6' },
          copyBtn(b.txid, t('copyTxid')),
          h('a', { class: 'btn btn-sm', href: url, target: '_blank', rel: 'noopener', onClick: (e) => { e.preventDefault(); openExternal(url); } }, t('viewOnMempool'))),
        h('button', { class: 'btn-primary btn-block', onClick: () => { ui.arkBoarded = null; render(); } }, t('done'))
      );
    }
    return null;
  }

  // Per-exit progress lines (chain hops / timelock countdown / claiming), with
  // a cancel for an exit that never published. Shown on the exit page.
  function arkExitStatusLines() {
    const s = arkStateNow();
    const acts = ((s && s.actions) || []).filter((a) => a.type === 'exit' && !['done', 'failed'].includes(a.step));
    if (!acts.length) return [];
    const exitDelta = (ark && ark.info && ark.info.vtxoExitDelta) || 144;
    const totalSat = acts.reduce((n, a) => n + a.amountSat, 0);
    // One story for the whole batch: each coin's chain unrolls a confirmed
    // hop per block, then waits out the CSV timelock, then the claim itself
    // confirms. Coins run in parallel, so the slowest one sets the ETA.
    const blocksFor = (a) =>
      a.step === 'chain' ? ((a.txids || []).length - (a.hopsDone || 0)) + exitDelta + 1
        : a.step === 'timelock' ? Math.max(0, a.claimableAt - (a.tipSeen || 0)) + 1
        : 1;
    const mins = Math.max(...acts.map(blocksFor)) * 10;
    const eta = getNetwork() === 'regtest' ? t('arkExitSoon')
      : mins >= 2880 ? `${Math.round(mins / 1440)} days`
      : mins >= 120 ? `${Math.round(mins / 60)} hours`
      : `${mins} minutes`;
    // The most advanced tx that's actually out there — the one worth watching.
    // A chain hop that errored before broadcast has nothing to link yet.
    let watch = null, watchScore = -1;
    for (const a of acts) {
      const score = a.step === 'claiming' ? 3 : a.step === 'timelock' ? 2 : a.hopsDone > 0 ? 1 : 0;
      const txid = exitWatchTxid(a);
      if (score > 0 && txid && score > watchScore) { watch = txid; watchScore = score; }
    }
    const err = acts.find((a) => a.lastError && a.actionable);
    const softErr = !err && acts.some((a) => a.lastError);
    // Cancelling is only real while nothing has touched the chain AND the
    // driver is parked waiting on the user (a needs-fee stall) — a healthy
    // exit may be mid-broadcast this very second. One button for the whole
    // batch, gone the moment it would be a lie.
    const cancellable = acts.every((a) => a.actionable && !(a.hopsDone > 0) && a.step === 'chain');
    return [h('div', { class: 'small muted', style: 'margin-top:4px' },
      t('arkExitSummary', { n: fmtSats(totalSat), eta }),
      err ? h('div', { class: 'small err' }, err.lastError)
        : softErr ? h('div', { class: 'small faint' }, t('arkExitRetrying')) : null,
      watch ? h('div', { style: 'margin-top:4px' },
        h('a', { class: 'linklike small', href: wallet.api.explorerTx(watch), target: '_blank', rel: 'noopener' }, t('arkExitViewTx'))) : null,
      cancellable
        ? h('button', { class: 'linklike small', style: 'display:block;margin-top:4px', onClick: () => {
            for (const a of acts) {
              a.step = 'failed';
              const v = ark && ark._vtxo(a.vtxoId);
              if (v && v.state === 'pending') v.state = 'spendable';
            }
            if (ark) ark._save();
            render();
          } }, t('arkExitCancel'))
        : null)];
  }

  // The exit page: cooperative offboard vs unilateral exit, with explanation.
  // Reached from the "Exit" link on the Ark balance line.
  function arkExitPage() {
    if (ui.arkOffboarded) return arkOffboardedScreen(); // cooperative success takeover
    const b = arkBalance() || { spendableSat: 0, pendingSat: 0 };
    const spendable = b.spendableSat;
    const total = b.spendableSat + b.pendingSat;
    const nSpend = exitableCoins(arkStateNow(), (ark && ark._tipH) || 0).length;
    const exitingSat = ((arkStateNow() && arkStateNow().actions) || [])
      .filter((a) => a.type === 'exit' && !['done', 'failed'].includes(a.step))
      .reduce((n, a) => n + a.amountSat, 0);
    const exits = arkExitStatusLines();
    const back = () => ctx.goBack(() => { ui.arkExitPage = null; ui.arkError = ''; });
    return h('div', { class: 'col', style: 'gap:16px' },
      h('div', { class: 'card col', style: 'gap:8px' },
        h('h3', { class: 'row gap6', style: 'align-items:center;margin:0' }, h('span', { html: ARK_ICON(18) }), t('arkExitPageTitle')),
        h('p', { class: 'small muted', style: 'margin:0' }, t('arkExitPageIntro')),
        total > 0 ? h('div', { class: 'row between', style: 'margin-top:4px' },
          h('span', { class: 'small muted' }, t('arkBalance')),
          h('span', { class: 'small' }, fmtAmount(total) + ' ' + unitLabel())) : null,
        null),
      // cooperative
      h('div', { class: 'card col', style: 'gap:8px' },
        h('h4', { style: 'margin:0' }, t('arkCoopTitle')),
        h('p', { class: 'small muted', style: 'margin:0' }, t('arkCoopDesc')),
        spendable > 0
          ? h('button', { class: 'btn-primary btn-block', disabled: !!ui.arkBusy, onClick: () => doArkOffboard() },
              ui.arkBusy === 'offboard' ? h('span', { class: 'spinner sm' }) : t('arkOffboardBtn', { n: fmtNative(spendable) }))
          : h('div', { class: 'small faint' }, exitingSat > 0 ? t('arkExitCoopHeld') : t('arkExitNoBalance'))),
      // unilateral
      h('div', { class: 'card col', style: 'gap:8px' },
        h('h4', { style: 'margin:0' }, t('arkUniTitle')),
        h('p', { class: 'small muted', style: 'margin:0' }, t('arkUniDesc')),
        nSpend > 0
          ? h('button', { class: 'btn-ghost btn-block', disabled: !!ui.arkBusy, onClick: doArkExit },
              ui.arkBusy === 'exit' ? h('span', { class: 'spinner sm' }) : t('arkExitBtn'))
          : null,
        ...exits),
      ui.arkError ? h('div', { class: 'notice err' }, ui.arkError) : null,
      h('button', { class: 'btn-ghost btn-block', onClick: back }, t('back'))
    );
  }

  return {
    id: 'ark',
    init() { _autoSelected = false; ui.accountUserChosen = false; initArk(); },
    stop() { stopArk(); },
    // Boot waits on this before opening a wallet: the Spending balance and
    // its history live in the ark store, which is IndexedDB and therefore
    // opens asynchronously. Painting first meant painting an empty Spending
    // wallet and filling it in a beat later — a 0 that counted itself up,
    // green, as if money had just arrived. Capped, because a store that
    // won't open must not hold the whole app hostage; the retry in initArk
    // catches up if it lands after the cap.
    arkStoreReady() {
      const store = wallet._arkStore;
      if (!store || store.ready) return null;
      return Promise.race([
        store.open().catch(() => {}),
        new Promise((r) => setTimeout(r, 800)),
      ]);
    },
    // the Spending face's settings page: the custody choice, then its coins
    spendingSettings() {
      if (wallet.watchOnly) return null; // a locked wallet can't renew or exit
      return arkCoinsPage({ embedded: true }); // the custody strategy sits inside, after the coins
    },
    // the wallet's own pages keep the top nav: these are pages, not takeovers
    screenView() {
      const page = ui.arkCoinsPage ? arkCoinsPage() : ui.arkExitPage ? arkExitPage() : null;
      return page ? h('div', { class: 'col', style: 'gap:16px' }, ctx.brandHeader(true), page) : null;
    },
    receiveTakeover() {
      const offboarded = arkOffboardedScreen();
      if (offboarded) return offboarded;
      const boarded = arkBoardedScreen();
      if (boarded) return boarded;
      return arkCelebration();
    },
    isSendDest(a) { return isArkAddress(a) && arkAvailable(); },
    hideSendControls(a) { return isArkAddress(a); },
    // Max for an ark recipient: arkoor sends are free, so the whole
    // spendable Spending balance is the honest maximum — WHEN Spending is
    // the selected rail. From Savings this destination is either a board
    // (your own address — review routes it to the board panel) or a
    // wrong-rail send review will bounce; either way the honest maximum is
    // what Savings can actually fund. Filling Spending's number here handed
    // the board panel an amount Savings couldn't cover, and the user read
    // the resulting 'insufficient funds' as a fee miscalculation.
    sendMaxFill(a) {
      if (!isArkAddress(a)) return null;
      const sat = ctx.getAccount() === 'spending'
        ? (arkBalance()?.spendableSat || 0)
        : maxBoardSat();
      if (!sat) return null;
      return ctx.amountField(sat);
    },
    sendFormNote(a) {
      if (!isArkAddress(a)) return null;
      maybeReconcile();
      return h('div', { class: 'small faint' }, t('arkSendHint'));
    },
    interceptReview(s) {
      if (s.recipients.length === 1) {
        const inv = (s.recipients[0].address || '').trim().replace(/^lightning:/i, '');
        if (maybeLnInvoice(inv) && startArkLnPay(inv)) return true;
      }
      if (s.recipients.length === 1 && isArkAddress(s.recipients[0].address)) {
        if (!arkAvailable()) throw new Error(t('arkNotConnected'));
        const sats = ctx.parseAmount(s.recipients[0].amount, ctx.getUnit());
        if (!sats || sats <= 0) throw new Error(t('enterValidAmtForN', { n: 1 }));
        const dest = s.recipients[0].address.trim();
        const fromSavings = ctx.getAccount() !== 'spending';
        (async () => {
          // Whose address is this? The manager may still be connecting, so
          // resolve async before painting a review. Our own address routes
          // to the board panel with the typed amount riding along.
          try { await connectArk(); }
          catch (e) { ui.sendError = e.message; render(); return; }
          if (await boardOwnAddress(dest, { amountSat: sats })) return;
          if (fromSavings) {
            // An ark payment spends the Spending balance — never silently
            // spend a different balance than the one selected.
            ui.sendError = t('arkPayFromSpending');
          } else {
            const via = s.recipients[0].via && s.recipients[0].via.ark === dest ? s.recipients[0].via : null;
            ui.arkSend = { address: dest, amountSat: sats, via };
          }
          render();
        })();
        return true;
      }
      return false;
    },
    resetSend() {
      ui.arkLnFromSavings = null; ui.arkLnFromSavingsOk = false; ui.arkOffboardSend = null;
      ui.arkLnPaid = null; ui.arkLnPay = null; ui.arkZapped = null; ui.arkZap = null;
      ui.arkSent = null; ui.arkSend = null;
    },
    sendView() {
      if (ui.arkLnFromSavings) return arkLnFromSavingsView();
      if (ui.arkOffboardSend) return arkOffboardSendView();
      if (ui.arkLnPaid || ui.arkLnPay) return arkLnPayView();
      if (ui.arkZapped || ui.arkZap) return arkZapView();
      if (ui.arkSent || ui.arkSend) return arkSendReview();
      return null;
    },
    // A bolt11 pays from the ark balance when it can cover it. Reached via the
    // swaps feature's delegation (its matcher runs first) or directly in
    // builds without the swaps feature.
    startArkLnPay(invoice, meta) { return startArkLnPay(invoice, meta); },
    // The zaps feature's generic Lightning seams (once served by the retired
    // swaps feature): the ASP pays invoices natively over ark.
    canLnPay() { return arkAvailable() && !wallet.watchOnly && !!(ark && ark.info); },
    // Fetch + verify a bolt12 invoice for an offer (the ASP's CLN speaks the
    // onion messages) — resolves { invoice (lni), amountSat, paymentHash }.
    async arkFetchBolt12Invoice(offerStr, amountSat) {
      const mgr = await connectArk();
      return mgr.fetchBolt12(offerStr, amountSat);
    },
    lnSpendableSat() { const b = arkBalance(); return b ? b.spendableSat : 0; },
    spendingRenewingSat() { return renewingSat(); },
    // Max for any Lightning amount form: spendable minus estimated fees.
    lnMaxSendSat() { return lnMaxSat(); },
    settingsCards() { return [autoWithdrawCard()]; },
    advancedSettingsCards() { return [arkServerCard()].filter(Boolean); },
    // a wallet signing out takes its ark state with it, wherever it lives
    wipeCache(prefixes) { for (const p of prefixes) wallet._arkStore.removePrefix(p); },
    // The onboarding wizard's top-up step borrows the board form wholesale.
    arkBoardForm() {
      if (!arkAvailable() || wallet.watchOnly) return null;
      if (!ark) { connectArk().catch(() => {}); return null; }
      return boardForm();
    },
    // A payment wants more Spending than exists: open the board panel with a
    // prefill that nets out to the need (gross of the board fee, with a bit
    // of routing headroom) — editable, so boarding extra is one keystroke.
    arkOfferBoard(needSat) {
      if (!arkAvailable() || wallet.watchOnly) return false;
      const b = arkBalance();
      const have = b ? b.spendableSat : 0;
      const short = Math.max(0, Math.ceil(needSat * 1.01) + 2 - have);
      let gross = short;
      try { for (let i = 0; i < 4; i++) gross = short + boardFee(gross, ark.info.boardFees); } catch {}
      const minBoard = (ark && ark.info && ark.info.minBoardAmountSat) || 0;
      ctx.goHome();
      ui.arkMoveOpen = true;
      ui.arkMoveDir = 'toSpending';
      ui.arkBoardAmt = String(Math.max(gross, minBoard));
      render();
      return true;
    },
    startLnPay(invoice, meta) { return startArkLnPay(invoice, meta); },
    // ---- headless seam for the NWC wallet service ----
    arkPayInvoice(invoice, opts = {}) {
      if (opts.pk) noteZap('inv:' + invoice, opts.pk); // a one-tap zap's face on its history row
      return payInvoiceHeadless(invoice, opts);
    },
    // The settled outcome of a payment another device of this wallet
    // started (the ASP refuses a second HTLC for the same invoice).
    async arkLnOutcome(paymentHash, timeoutMs) {
      const mgr = await connectArk();
      return mgr.lnOutcome(paymentHash, timeoutMs);
    },
    arkSpendableSat() { const b = arkBalance(); return b ? b.spendableSat : 0; },
    arkReady() { return arkAvailable(); },
    // A Lightning invoice for another feature to watch (point of sale):
    // the action id is the handle, the poller tells it when it settles.
    async arkLnInvoice(amountSat, description) {
      const mgr = await connectArk();
      const a = await mgr.createLnInvoice(amountSat, description);
      return { id: a.id, invoice: a.invoice, paymentHash: a.paymentHash, amountSat, expiresAt: a.expiresAt };
    },
    arkLnWatch(id, onSettle) { pollArkLn(id, onSettle); return true; },
    arkLnUnwatch(id) { stopArkLnPoll(id); return true; },
    async arkLnCancel(id) { const mgr = await connectArk(); await mgr.cancelLnInvoice(id); return true; },
    async arkMakeInvoice(amountSat, description) {
      const mgr = await connectArk();
      const a = await mgr.createLnInvoice(amountSat, description);
      return { invoice: a.invoice, paymentHash: a.paymentHash, amountSat, expiresAt: a.expiresAt };
    },
    // NIP-47 lookup_invoice: a payment of ours by hash or bolt11. One that
    // is still pending gets a push first (a receive whose HTLCs have
    // arrived is claimed right here), so a merchant polling sees it settle.
    async arkLnLookup(q) {
      const mgr = await connectArk();
      const found = mgr.lnLookup(q);
      if (!found || found.state !== 'pending') return found;
      const a = (mgr.state.actions || []).find((x) => x.paymentHash === found.payment_hash && x.type.startsWith('ln-'));
      if (a) await Promise.race([mgr.driveLn(a.id).catch(() => {}), new Promise((r) => setTimeout(r, 8000))]);
      return mgr.lnLookup(q);
    },
    arkMovements() { const s = arkStateNow(); if (!s) return []; const twins = lnFoldedIds(s.movements); return (s.movements || []).filter((m) => !twins.has(m.id)); },
    // The wallet's reusable ark receive address (BIP-353 names publish it).
    async arkStaticAddress() {
      const mgr = await connectArk();
      return mgr.address();
    },
    // Whether background answering can mirror right now.
    arkBgReady() { return !!(ark && ark.info && ark.state); },
    // nwc.js calls this (with its connections) whenever the mirror should
    // refresh: on enable, on connection changes, after payments, on a timer.
    async arkBgWrite(connections, offer, prefs) { return writeBgMirror(connections, offer, prefs); },
    async arkBgSpendableSat() {
      const rec = await loadBg(wallet._cacheKey());
      return ((rec && rec.mgr && rec.mgr.vtxos) || [])
        .filter((v) => v.state === 'spendable').reduce((n, v) => n + (v.amountSat || 0), 0);
    },
    // Worker payments become ordinary history lines once the app opens.
    async arkBgNoteSpends(spends) {
      const mgr = await connectArk();
      for (const sp of spends) {
        mgr._movement({
          type: 'ln-send', amountSat: sp.amountSat, status: 'complete',
          detail: `while closed · fee ${sp.feeSat || 0} sat`, invoice: sp.invoice || '', preimage: sp.preimage || '',
        });
      }
      mgr._save();
    },
    // A name that resolved to OUR OWN ark address: the names feature asks
    // before filling the send form, so the board panel opens at paste time —
    // nobody should have to type an amount into a payment form just to be
    // told they were topping themselves up.
    arkBoardIfOwn(addr) { return boardOwnAddress(addr, { connect: true }); },
    // An npub pasted into Send becomes an ark zap (needs the nostr seam from
    // the sync feature and a connected-able ark). A bolt11 is handled here
    // only in builds without the swaps feature (whose matcher runs first and
    // delegates back via the startArkLnPay hook).
    matchSendText(text) {
      const inv = (text || '').trim().replace(/^lightning:/i, '');
      // A raw paste of our own ark address means the same thing — start the
      // check now (the manager may need to connect); if it's ours the board
      // panel replaces the filled form a beat later.
      if (isArkAddress(inv) && arkAvailable()) {
        if (foreignArkAddr(inv)) { ui.sendError = t('arkForeignServer'); render(); return true; }
        boardOwnAddress(inv, { connect: true }).catch(() => {});
      }
      // A BIP-21 URI with an ark= instruction (Noah, Second's wallets, our
      // own names): same server → pay over Ark, instant and free, with the
      // URI's amount; another server → the on-chain address, and say why.
      if (/^bitcoin:/i.test(inv) && arkAvailable() && !wallet.watchOnly) {
        const dec = parseBip21Uri(inv);
        const arkAddr = dec && dec.params && dec.params.ark;
        if (arkAddr && isArkAddress(arkAddr)) {
          if (foreignArkAddr(arkAddr)) { toast(t('arkForeignBip21'), 4000); return false; }
          boardOwnAddress(arkAddr, { connect: true }).catch(() => {});
          const s = ui.send;
          s.recipients[0].address = arkAddr;
          const btc = Number(dec.params.amount);
          if (btc > 0) { s.recipients[0].amount = amountFill(Math.round(btc * 1e8)); s.max = false; }
          ui.sendError = '';
          render();
          return true;
        }
      }
      // In a Spending wallet an on-chain address means "exit ark to there":
      // the offboard happens right in the send flow, no Move money ceremony.
      if (ctx.getAccount() === 'spending' && wallet.isOnchainAddress(inv) && arkAvailable()) {
        const b = arkBalance() || {};
        if ((b.spendableSat || 0) > 0) {
          ui.arkOffboardSend = { address: inv, amount: '' };
          ui.sendError = '';
          render();
          return true;
        }
        // Every coin is mid-exit: the send page is for CREATING payments,
        // so stay right here with an honest error — the in-flight exit is a
        // history record now, and sendFormExtras links straight to it.
        if ((b.pendingSat || 0) > 0
            && (arkStateNow()?.actions || []).some((a) => a.type === 'exit' && !['done', 'failed'].includes(a.step))) {
          ui.sendError = t('arkNoSpendableMidExit');
          render();
          return true;
        }
      }
      if (maybeLnInvoice(inv)) {
        if (startArkLnPay(inv)) return true;
        if (arkAvailable() && !wallet.watchOnly) {
          // An invoice Spending can't cover used to fall through SILENTLY —
          // the bolt11 landed in the address field looking like a dead
          // paste. Own it: offer to board the shortfall from Savings when
          // there is one, else say plainly what's short.
          const need = (maybeLnInvoice(inv) || {}).amountSat || 0;
          if (need && wallet.spendable > 1000 && ctx.hook('arkOfferBoard', need)) return true;
          ui.sendError = t('arkLnExceedsSpending', {
            need: fmtAmount(need) + ' ' + unitLabel(),
            have: fmtAmount(arkBalance()?.spendableSat || 0) + ' ' + unitLabel(),
          });
          render();
          return true;
        }
        return false;
      }
      const pk = npubToHex(text);
      if (!pk || !arkAvailable() || !wallet.nostrFetch) return false;
      startNpubPay(pk, String(text).trim());
      return true;
    },
    // Zap a person — optionally a specific note of theirs (the profile feed's
    // ⚡ button) — through the same resolution ladder as a pasted npub. The
    // event id rides into the receipt's e tag; callers fall back to the
    // lnZapNpub hook when ark can't serve this build/wallet.
    zapNpub(pk, npub, eventId, autoSat, moment) {
      if (!arkAvailable() || !wallet.nostrFetch) return false;
      startNpubPay(pk, npub, eventId || null, autoSat || 0, moment);
      return true;
    },
    sendFormExtras() {
      if (ctx.getAccount() !== 'spending') return null;
      const acts = ((arkStateNow() && arkStateNow().actions) || []).filter((a) => a.type === 'exit' && !['done', 'failed'].includes(a.step));
      if (!acts.length) return null;
      return h('button', { class: 'linklike small', style: 'align-self:center', onClick: () => {
        ui.tab = 'history';
        ui.sendError = '';
        ui.arkExitDetail = acts[0].id;
        render();
      } }, t('arkExitInFlightLink', { n: fmtAmount(acts.reduce((s2, a) => s2 + a.amountSat, 0)) }));
    },
    historyEntries(_txs, sel) {
      if (sel && sel !== 'spending') return []; // ark movements are the Spending timeline
      const s = arkStateNow();
      if (!s) return [];
      // Memoized on the state's REVISION, not a timer. This rebuild sorts and
      // dedupes every movement, resolves gifts, and touches secp256k1 — ~60ms
      // cold. A 1.5s TTL used to re-cool it between unhurried flicks, so every
      // account switch paid the rebuild and stuttered the slide; keyed on _rev
      // it's reused until the data actually changes (each _save bumps _rev),
      // and stays warm no matter how slowly the user flicks back and forth.
      const key = `${s._rev || 0}:${(s.movements || []).length}:${(s.actions || []).length}`;
      if (this._histMemo && this._histMemo.key === key) return this._histMemo.val;
      const val = this._histBuild(s);
      this._histMemo = { key, val };
      return val;
    },
    _histBuild(s) {
      // In-flight exits are payments the user made — they belong in history
      // as pending records, not on a monitoring page nobody thinks to visit.
      const exits = (s.actions || [])
        .filter((a) => a.type === 'exit' && !['done', 'failed'].includes(a.step))
        .map((a) => ({ time: exitStartedTs(a), render: () => arkExitActionItem(a) }));
      // ...and renewals you asked for (a Renew tap), while the round runs
      const renewals = (s.actions || [])
        .filter((a) => a.type === 'refresh' && a.manual && !['done', 'failed'].includes(a.step))
        .map((a) => ({ time: exitStartedTs(a), render: () => arkRefreshActionItem(a) }));
      // ...and Lightning payments on their way, until their Sent row exists
      const paid = new Set((s.movements || []).filter((m) => m.type === 'ln-send' && m.status === 'complete').map((m) => m.paymentHash));
      const lnPending = (s.actions || [])
        .filter((a) => a.type === 'ln-pay' && !['done', 'failed'].includes(a.step) && !paid.has(a.paymentHash))
        .map((a) => { const m = lnPendingMove(a); return { time: m.ts, render: () => arkHistoryItem(m), csv: arkCsvRow(m) }; });
      // Same-payment duplicates (the old settle race, or a snapshot adopted
      // whole before the merge learned to dedupe) fold at display time too —
      // the earliest telling wins, everywhere, however the state got here.
      // Renewals fold on their unlock hash (two devices can adopt the same
      // participation), and only ones that COST something get a row — a free
      // renewal is net zero, invisible money movement, noise.
      const seenPay = new Set();
      const lnTwins = lnFoldedIds(s.movements); // a claimed LN receive's coin, told again by the mailbox
      const moves = (s.movements || [])
        .filter((m) => !lnTwins.has(m.id))
        .filter((m) => ['receive', 'send', 'board', 'offboard', 'exit', 'ln-send', 'ln-receive', 'refresh', 'reconcile'].includes(m.type)
          && (m.status === 'complete' || (m.type === 'send' && m.status === 'failed')))
        .filter((m) => m.type !== 'refresh' || m.feeSat > 0 || m.manual) // a renewal you asked for is worth a row even when free
        .sort((m, n) => (m.ts || 0) - (n.ts || 0))
        .filter((m) => {
          if (!m.type.startsWith('ln-') && !(m.type === 'refresh' && m.unlockHash)) return true;
          const key = m.type + ':' + (m.unlockHash || m.paymentHash || m.preimage || m.invoice || m.id);
          if (seenPay.has(key)) return false;
          seenPay.add(key);
          return true;
        });
      // Coins the server reported spent elsewhere: without a row for them the
      // history stops summing to the balance (cooney's looked 29k sats rich).
      // One reconcile pass marks many coins in the same instant — fold each
      // pass (and re-imported duplicates, deduped by coin) into one row.
      // A coin whose spend is ACCOUNTED FOR is excluded outright — a
      // renewal's inputs (the renewed coin balances the books invisibly),
      // and equally a send's, an offboard's, an exit's: those movements and
      // actions sync, so painting the vanished input beside the real Sent
      // row showed one spend twice, at input magnitude the second time.
      // The red row survives only for spends nothing anywhere explains.
      const accounted = new Set();
      for (const a of s.actions || []) {
        for (const id of a.inputIds || []) accounted.add(id);
        for (const part of a.parts || []) if (part.inputId) accounted.add(part.inputId);
      }
      for (const m of s.movements || []) for (const id of m.inputIds || []) accounted.add(id);
      const out = [];
      const seenCoin = new Set();
      for (const m of moves) {
        if (m.type !== 'reconcile') { out.push(m); continue; }
        if (m.vtxoId && (seenCoin.has(m.vtxoId) || accounted.has(m.vtxoId))) continue;
        if (m.vtxoId) seenCoin.add(m.vtxoId);
        const last = out[out.length - 1];
        if (last && last.type === 'reconcile' && last.ts === m.ts) {
          last.amountSat += m.amountSat;
          last.count += 1;
          if (m.vtxoId) last.vtxoIds.push(m.vtxoId);
        } else {
          out.push({ ...m, count: 1, vtxoIds: m.vtxoId ? [m.vtxoId] : [] });
        }
      }
      return exits.concat(renewals, lnPending, out.map((m) => ({ time: m.ts, render: () => arkHistoryItem(m), csv: arkCsvRow(m) })));
    },
    historyDetail() {
      if (ui.arkExitDetail) {
        const a = ((arkStateNow() && arkStateNow().actions) || []).find((x) => x.id === ui.arkExitDetail);
        if (a && !['done', 'failed'].includes(a.step)) return arkExitActionDetail(a);
        ui.arkExitDetail = null;
      }
      // the folded reconcile row isn't a stored movement — its detail rides
      // the ui state the row's tap put there (and nav history restores)
      if (ui.arkReconDetail && typeof ui.arkReconDetail === 'object') return arkReconDetailView(ui.arkReconDetail);
      if (!ui.arkMoveDetail) return null;
      const s = arkStateNow();
      if (s && String(ui.arkMoveDetail).startsWith('lnpay:')) {
        const a = (s.actions || []).find((x) => 'lnpay:' + x.id === ui.arkMoveDetail);
        const done = a && (s.movements || []).find((x) => x.type === 'ln-send' && x.paymentHash === a.paymentHash);
        if (done) return arkMoveDetailView(done);
        if (a && !['done', 'failed'].includes(a.step)) return arkMoveDetailView(lnPendingMove(a));
      }
      const m = s ? (s.movements || []).find((x) => x.id === ui.arkMoveDetail) : null;
      if (m) return arkMoveDetailView(m);
      ui.arkMoveDetail = null;
      return null;
    },
    // The spendable off-chain balance IS the wallet's "Spending" — the balance
    // card shows it by name, so this feature only reports the number.
    // "Move money" under the balance — the one door between the two balances.
    balanceActions() { return []; }, // Move money retired: exits ride the Send field now
    balanceExtra() {
      if (!ui.arkMoveOpen || wallet.watchOnly || !arkAvailable()) return null;
      return movePanel();
    },
    // Sats mid-board (the on-chain tx awaiting its confirmation) — Spending
    // doesn't count them yet, but a top-up PROMPT must: nagging someone to
    // top up again while their top-up confirms is noise.
    spendingBoardingSat() {
      const b = arkBalance();
      return b ? b.boardingSat || 0 : 0;
    },
    spendingSat() {
      const b = arkBalance();
      return b ? b.spendableSat + b.pendingSat : 0;
    },
    balanceLines() {
      const b = arkBalance();
      if (!b) return [];
      // Money mid-move: it has left Saving but hasn't landed in Spending, so
      // say where it went rather than letting it vanish for a confirmation —
      // with the confirmation count, so the wait has a visible reason.
      if (!(b.boardingSat > 0)) return [];
      const a = ((arkStateNow() || {}).actions || []).find(
        (x) => x.type === 'board' && x.fundingTxid && !['done', 'failed'].includes(x.step) && x.needConfs);
      const prog = a ? ` · ${Math.min(a.confs || 0, a.needConfs)}/${a.needConfs}` : '';
      return [{ label: t('movingLabel') + prog, sat: b.boardingSat, side: 'spending' }];
    },
    walletNotices() {
      // Everything the balance needs to say, said once. These used to be a
      // stack of separate boxes — two red cards and a grey line, three
      // Manage links between them, all pointing at the same page. One card
      // now: red if anything in it is a warning, plain otherwise, and one
      // Manage at the bottom.
      const lines = []; // { text, err, manage }
      // A pending move that keeps erroring would otherwise wait in silence.
      for (const a of ((arkStateNow() || {}).actions || [])) {
        if (a.type === 'board' && a.lastError && !['done', 'failed'].includes(a.step))
          lines.push({ text: t('arkBoardStuck', { error: a.lastError }), err: true });
      }
      if (arkRenewWarn && !wallet.watchOnly) lines.push({
        text: t('arkRenewWarn', {
          amount: fmtSats(arkRenewWarn.sat) + ' sats', // coin sizes are sats, whatever the display unit
          date: new Date(arkRenewWarn.deadlineMs).toLocaleDateString(),
        }), err: true,
      });
      // Coins past their expiry. The balance already leaves these out, and
      // until now it did so in silence — money apparently gone, with the one
      // page that could bring it back reachable only through an advisory
      // that most wallets never see (it wants four hops of depth) or a
      // renewal forecast that only appears when the renewal COSTS something,
      // which is no longer the normal case.
      //
      // An expired vtxo can still be renewed — that is the whole of the fix,
      // and it is one tap away on the Manage page. What it cannot do is be
      // spent over Ark or exited unilaterally, so saying nothing is the one
      // option that isn't honest.
      // On the coinos servers a coin past its timelock is still money (the
      // server keeps cosigning its spends) — the balance counts it and
      // there is nothing to warn about; the custody tier the user chose
      // says what expiry means to them. Elsewhere, the old warning.
      if (!wallet.watchOnly && ark && ark.balance && !ark.honorsExpired) {
        let expiredSat = 0;
        try { expiredSat = ark.balance().expiredSat || 0; } catch {}
        // Expired dust (under the 330-sat floor) cannot be renewed or exited
        // by anyone: no red warning over 21 sats, a quiet line and a Forget
        // button on the Manage page instead.
        if (expiredSat >= 330) lines.push({
          text: t('arkExpiredNotice', { amount: fmtSats(expiredSat) + ' sats' }), err: true, manage: true,
        });
        else if (expiredSat > 0) lines.push({ text: t('arkExpiredDust', { amount: fmtSats(expiredSat) + ' sats' }), manage: true });
      }
      // What a unilateral exit would cost, and when coins renew for how
      // much, are the Spending settings page's business (the gear on the
      // card), not lines under the balance.
      // The coins themselves are always one tap away on the card's gear; a
      // notice that is about them links straight there.
      const manage = lines.some((l) => l.manage)
        ? h('button', { class: 'linklike small', style: 'align-self:flex-end', onClick: () => ctx.openWalletSettings('spending') }, t('arkDepthBtn'))
        : null;
      if (!lines.length) return [];
      const err = lines.some((l) => l.err);
      // one plain advisory keeps its quiet centred line; anything more, or
      // anything urgent, is a card
      if (!err && lines.length === 1) {
        return [h('div', { class: 'small muted', style: 'margin:10px 0 0;text-align:center' }, lines[0].text, manage ? ' ' : null, manage)];
      }
      return [h('div', { class: 'notice' + (err ? ' err' : ' info') + ' col', style: 'margin:12px 0 0;gap:8px' },
        ...lines.map((l) => h('div', { style: l.err || !err ? '' : 'opacity:.8' }, l.text)),
        manage)];
    },
    decorateTxRow(tx) {
      const s = arkStateNow();
      if (!s) return null;
      const acts = s.actions || [];
      if (tx.net < 0) {
        const a = acts.find((x) => x.type === 'board' && x.fundingTxid === tx.txid);
        return a ? { icon: h('span', { html: ARK_MARK(16) }), label: h('span', {}, t('arkBoardHistory')) } : null;
      }
      const o = acts.find((x) => x.type === 'offboard' && x.txid === tx.txid);
      if (o) return { icon: h('span', { html: ARK_MARK(16) }), label: h('span', {}, t('arkOffboardHistory')) };
      const e = acts.find((x) => x.type === 'exit' && x.claimTxid === tx.txid);
      return e ? { icon: h('span', { html: ARK_MARK(16) }), label: h('span', {}, t('arkExitHistory')) } : null;
    },
    txDetailSection(tx) {
      const s = arkStateNow();
      if (!s) return null;
      const a = (s.actions || []).find((x) => x.type === 'board' && x.fundingTxid === tx.txid);
      if (!a) return null;
      const done = a.step === 'done';
      return h('div', { class: 'summary col', style: 'gap:0' },
        h('div', { class: 'row gap6', style: 'font-weight:600;margin:12px 0 2px;align-items:center' }, h('span', { html: ARK_ICON(16) }), t('arkBoardHistory')),
        h('div', { class: 'line' },
          h('span', { class: 'k' }, t('arkBalance')),
          h('span', { class: 'v' }, fmtAmount(a.amountSat - a.feeSat) + ' ' + unitLabel())),
        a.feeSat > 0
          ? h('div', { class: 'line' },
              h('span', { class: 'k' }, t('arkBoardFeeLabel')),
              h('span', { class: 'v' }, fmtAmount(a.feeSat) + ' ' + unitLabel()))
          : null,
        done ? null : h('div', { class: 'small muted', style: 'margin-top:2px' }, boardedNote()));
    },

    // ---- ark-gift hooks (called by the gifts feature via ctx.hook) ----
    arkGiftInfo() {
      // Persisted state, not the live manager: the gift form renders before
      // connectArk() has run, and a null here silently flips the gift to the
      // on-chain source — "more than your balance" against Savings while the
      // header shows a healthy Spending balance. Creation connects on demand.
      const b = arkAvailable() ? arkBalance() : null;
      if (!b) return null;
      maybeReconcile(); // the gift form is a send-intent signal too (throttled)
      return { spendableSat: b.spendableSat, pendingSat: b.pendingSat };
    },
    arkGiftDecode(code) { return decodeArkGiftCode(code); },
    // A fresh visitor (no wallets) opening a gift link lands on the gift's
    // network automatically instead of being told to change Settings.
    arkGiftAdoptNetwork(code) {
      const g = decodeArkGiftCode(code);
      if (!g || g.net === getNetwork()) return false;
      setNetwork(g.net);
      return true;
    },
    arkGiftCreate(amountSat) { return createArkGift(amountSat); },
    // Claim-side status: claimable (with the live amount), taken, wrongnet, or
    // unknown (not visible here — wrong server or not yet delivered).
    async arkGiftStatus(code) {
      const g = decodeArkGiftCode(code);
      if (!g) return null;
      if (g.net !== getNetwork()) return { state: 'wrongnet', net: g.net, amountSat: g.amountSat };
      const gm = await giftManager(g.secretHex);
      await gm.sync().catch(() => {});
      await gm.reconcile().catch(() => {});
      const amt = gm.balance().spendableSat;
      if (amt > 0) return { state: 'claimable', amountSat: amt };
      const seen = gm.state.vtxos.length > 0;
      return { state: seen ? 'taken' : 'unknown', amountSat: g.amountSat };
    },
    async arkGiftClaim(code) {
      if (wallet.watchOnly) throw new Error(t('arkWatchOnly'));
      const mine = await connectArk();
      const amount = await sweepArkGift(code, mine.address());
      await mine.sync().catch(() => {}); // pull the swept vtxo in right away
      mine.ackReceives(); // the gift UI celebrates; don't double-celebrate here
      return amount;
    },
    arkGiftOutstanding() {
      refreshArkGiftRecords();
      return arkGiftRecords().filter((g) => !g.revoked && !g.claimed)
        .map((g) => ({ id: g.id, amountSat: g.amountSat, created: g.created }));
    },
    async arkGiftRevoke(id) { return doArkGiftRevoke(id); },
  };

  async function doArkGiftRevoke(id) {
    const g = arkGiftRecords().find((x) => x.id === id);
    if (!g) throw new Error('unknown gift');
    const mine = await connectArk();
    const code = encodeArkGiftCode(getNetwork(), g.amountSat, hex.decode(g.secretHex));
    let amount;
    try {
      amount = await sweepArkGift(code, mine.address());
    } catch (e) {
      // beaten by the claimer — record it so the row self-heals immediately
      if (e && e.giftTaken) { g.claimed = true; mine._save(); }
      throw e;
    }
    g.revoked = true;
    mine._save();
    await mine.sync().catch(() => {});
    mine.ackReceives(); // our own sweep-back isn't a "payment received"
    return amount;
  }
}