aboutsummaryrefslogtreecommitdiffstats
path: root/static/punks/31.webp
diff options
context:
space:
mode:
authorAdam Soltys <[email protected]>2026-10-09 14:49:59 -0700
committerAdam Soltys <[email protected]>2026-10-09 14:49:59 -0700
commita30c16fcaac5c89acc1ace58aff8a6746ab45d05 (patch)
tree8d94172f4d7062002e4cffcfb67508e63eb46a41 /static/punks/31.webp
parent70f8866007f8658a3e6b9cd9ba80229b70fd9252 (diff)
downloadcoinosv3-a30c16fcaac5c89acc1ace58aff8a6746ab45d05.tar.gz
coinosv3-a30c16fcaac5c89acc1ace58aff8a6746ab45d05.zip
Amounts: no minus sign on money going out. The word (Sent, Renewal, Exiting…) and the red already say it's a debit — history rows, the transaction details, the sent screens, and on-chain rows (whose negative net printed its own sign). Received keeps its +.
Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Vps2H27rhbG9ZqseGfMrc3
Diffstat (limited to 'static/punks/31.webp')
0 files changed, 0 insertions, 0 deletions
32' href='#n132'>132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765
// Bitcoin Wallet — UI controller (vanilla DOM, no framework).
//
// State lives in `ui` + the singleton `wallet`. Mutating handlers call render(),
// which rebuilds the active screen. Text inputs write back into `ui` on `input`
// (without re-rendering) so their values survive structural re-renders.

import { Wallet, newMnemonic, isValidMnemonic, accountXpubFor, cacheKeyFor, utxoId, parseExtendedKey, xpubToZpub, encryptVault, decryptVault } from './wallet.js';
import { qrSvg } from './qr.js';
import './rich-text.js'; // <coinos-text>, the composers' field
import { makeSearcher, resultRows, searchable, punkUrl, warmSearch } from './recipient-search.js';
import { assetUrl } from './asset-url.js';
import { npubOf, seedPubkey, neventOf, parseNostrPubkey } from './nostr.js';
import { nip98Header } from './nip98.js';
import { uploadPublicMedia, MediaUploadError } from './media-upload.js';
import { NOSTR_MARK } from './features/nostrlogin.js';
import { scanQr } from './scan.js';
import { dataSources, getSource, setSource, getNetwork, setNetwork, NETWORKS } from './api.js';
import { STAGING } from './build-flags.js';
import { buildFeatures, loadDeferredFeatures } from './features/index.js';
import { cacheReady, cacheStore } from './cache-store.js';
import { t, LANGS, getLang, setLang, isRTL, loadLocale } from './i18n.js';
import { rateNow, rateAt, refreshRates, haveRate, getCurrency, setCurrency, currencies, fmtFiat, fmtFiatBare } from './rates.js';
import {
  fmtBtc,
  fmtSats,
  parseAmount,
  shortAddr,
  shortTxid,
  timeAgo,
  SATS,
  BITCOIN_ICON,
} from './format.js';

const wallet = new Wallet();

// ---- optional features ------------------------------------------------
// Swaps and Ark plug into fixed seams (receive modes, send
// matchers, history entries, balance lines, settings cards, lifecycle hooks).
// FEATURES/ctx are assembled near the bottom of this file, once every helper
// they capture exists; the hooks below are only ever called at runtime.
const featureHook = (name, ...args) => {
  for (const f of FEATURES) {
    if (!f[name]) continue;
    const v = f[name](...args);
    if (v) return v;
  }
  return null;
};
const featureAll = (name, ...args) => FEATURES.flatMap((f) => (f[name] ? f[name](...args) : []));
// `typed` distinguishes keystroke input from paste/scan: some matchers (a
// lightning address) match mid-typing and must not yank the form away.
const featureMatchSend = (text, typed) => FEATURES.some((f) => f.matchSendText && f.matchSendText(text, typed));








const ui = {
  screen: 'unlock', // 'unlock' | 'wallet' | 'claim' | 'howItWorks'
  claimStep: null, // 'welcome' | 'backup' when opening a gift link
  claimChecking: false, // verifying the gift's funding coin is still unspent
  claimTaken: null, // { txid } if the gift was already claimed (coin spent)
  returnScreen: 'unlock', // where 'howItWorks' returns to (Back / logo)
  unlockTab: 'create', // 'create' | 'import' | 'watch'
  watchXpub: '', // watch-only xpub/zpub input
  watchLabel: '', // watch-only account label input
  fromWallet: false, // unlock screen reached as "add wallet" (show a back button)
  pw: null, // { purpose, accId, mode, v1, v2, error } — vault password prompt
  vaultPw: '', // on-open vault unlock input
  vaultError: '',
  confirmClear: false, // "Clear all" confirmation shown
  editId: null, // account being renamed
  editLabel: '',
  createStep: 'gen', // 'gen' | 'confirm'
  draftMnemonic: '',
  confirm: [], // [{ index, value }]
  confirmPass: '', // re-entered passphrase (confirm field, shown once one is typed)
  importText: '',
  passphrase: '',
  showPass: false,
  revealShown: false, // recovery phrase: false | 'masked' (grid, dots) | 'words'
  pubkeyShown: false, // account public key revealed in Settings
  giftMode: false, // gift sub-view active on the Send page
  giftAmount: '', // gift-create amount input
  viewGift: null, // re-viewing a previously created gift's link/QR { code, locked, amount, claimCode }
  claimChoose: null, // opening a gift with existing wallets present: { code } — pick a target
  giftCode: null, // last-created gift PSBT code
  giftError: '',
  giftMax: false, // gift the whole spendable balance (no-change sweep)
  giftSplitOffer: null, // { amt, lock, freed, fee } when offering to split a coin first
  revokeId: null, // outpoint of a gift being revoked (confirm state)
  claimCode: null, // gift code being claimed (opened from a #gift= link)
  claimLocked: null, // npub-locked gift blob opened from a /lg/ link (public fields)
  claimCodeInput: '', // one-time claim code typed on the locked-gift screen
  claimedAmount: 0,
  claimError: '',
  offlineFallback: false, // auto-entered offline because the network was unreachable
  unlockError: '',

  tab: 'receive', // receive | send | history | settings
  receiveSeenIndex: null, // fresh receive index the user has acknowledged
  txDetail: null, // txid being viewed in the history detail view
  txPage: 0, // History: current page of transactions (10 per page)
  addrScan: false, // Settings: showing the per-address rescan list
  addrScanPage: 0, // Settings: current page within the address list
  rescanning: new Set(), // 'chain/index' ids queued/in-flight for rescan
  send: blankSend(),
  draft: null, // built tx summary awaiting review
  broadcastTx: null, // scanned signed tx awaiting broadcast confirmation
  bump: null, // RBF bump in progress: { prep, feeChoice, customFee }
  sendError: '',
  sendResult: null, // { txid } | { signedHex, txid }
  busy: false,
};
let sendPageOpen = false, sendPageRendered = false;

function clearSend() {
  ui.send = blankSend();
  ui.draft = null; ui.broadcastTx = null; ui.sendResult = null; ui.sendError = '';
  featureAll('resetSend');
  sendSearcher.clear(false);
  sendSearch.rows = null; sendSearch.sync = null; sendSearch.pick = null; sendSearch.el = null;
  clearTimeout(sendRevealTimer);
}

// Take the wallet to the Send pane: any payment detail left open (a tapped
// history row — which claims the whole tab area, whichever tab is picked)
// closes first. A feature that jumped straight to ui.tab = 'send' used to
// land on a renewal's detail card instead of the form.
// A new recipient also clears previous payment reviews and results.
function showSend({ fresh = false } = {}) {
  ui.txDetail = null; ui.arkMoveDetail = null; ui.arkReconDetail = null; ui.arkExitDetail = null; ui.giftDetail = null;
  ui.bump = null;
  ui.sendError = '';
  if (fresh) clearSend();
  // the Send tab lives on the wallet screen: from a page like Spending's
  // settings (its co-operative exit) the tab flipped out of sight
  ui.screen = 'wallet';
  ui.tab = 'send';
}

function blankSend() {
  return {
    recipients: [{ address: '', amount: '' }],
    unit: 'btc',
    max: false,
    feeChoice: 'halfHourFee',
    customFee: '',
    manual: false,
    coins: new Set(),
  };
}

// ---------------------------------------------------------------- DOM helper
function h(tag, attrs = {}, ...children) {
  const e = document.createElement(tag);
  const lazy = lazySrcTag(e.nodeName);
  for (const [k, v] of Object.entries(attrs || {})) {
    if (v == null || v === false) continue;
    if (k === 'src' && lazy) { e.setAttribute('data-lazy-src', v); continue; }
    if (k === 'class') e.className = v;
    else if (k === 'html') { e.innerHTML = v; e._html = v; }
    else if (k === 'value') e.value = v;
    else if (k === 'checked' || k === 'disabled' || k === 'selected') e[k] = !!v;
    else if (k.startsWith('on') && typeof v === 'function') {
      // assigned as an on* PROPERTY (not addEventListener) so the morph can
      // transplant handlers between renders: assignment replaces, and _evs
      // records which slots this render claimed
      const n = 'on' + k.slice(2).toLowerCase();
      e[n] = v;
      (e._evs || (e._evs = new Set())).add(n);
    } else e.setAttribute(k, v);
  }
  for (const c of children.flat()) {
    if (c == null || c === false || c === true) continue;
    e.append(c.nodeType ? c : document.createTextNode(String(c)));
  }
  return e;
}

// A media element starts downloading the moment its src is set — even off
// the document. Every render builds a fresh tree to diff against the live
// one, so an <img src> or <video src> built here used to start a load per
// repaint that the morph then threw away (a feed scroll built two hundred
// videos and fourteen hundred images in sixteen seconds). The source waits
// on data-lazy-src and becomes src only once the node is in the page (see
// promoteLazySrc); the morph treats the two as the same attribute.
// (a function declaration: h() is called at module load before a const here
// would be initialized)
function lazySrcTag(name) { return name === 'IMG' || name === 'VIDEO' || name === 'AUDIO' || name === 'SOURCE'; }
function promoteLazySrc(root) {
  for (const el of root.querySelectorAll('[data-lazy-src]')) {
    const v = el.getAttribute('data-lazy-src');
    el.removeAttribute('data-lazy-src');
    if (el.getAttribute('src') !== v) el.setAttribute('src', v);
  }
}
// a node appended by hand, outside render(), gets its source the same way
if (typeof MutationObserver !== 'undefined' && typeof document !== 'undefined') {
  new MutationObserver((ms) => {
    for (const m of ms) for (const n of m.addedNodes) {
      if (n.nodeType !== 1) continue;
      if (n.hasAttribute('data-lazy-src')) promoteLazySrc({ querySelectorAll: () => [n] });
      promoteLazySrc(n);
    }
  }).observe(document.documentElement, { childList: true, subtree: true });
}
// ---------------------------------------------------------------- morphing
// render() builds a fresh tree exactly as before, but instead of replacing
// the document we PATCH the live DOM into its shape. Nodes keep their
// identity across renders, so :hover, focus, text selection, CSS transitions
// and scroll positions survive every background repaint — the strobing that
// full replacement caused (and that focus/scroll bookkeeping only papered
// over) is gone at the root. Escape hatch: a node carrying data-fresh is
// swapped wholesale whenever the new render produced a different one (used
// where a detached node runs its own animation frames).
function morph(a, b) {
  if (a === b) return;
  // A subtree frozen for a gesture (the balance carousel mid-drag/mid-glide)
  // is left exactly as it stands: patching it would strip the drag's inline
  // snap override and yank the scroll. endCarouselDrag unfreezes and runs a
  // syncing render once motion stops.
  if (a.nodeType === 1 && a._skipMorph) return;
  if (a.nodeType === 3 && b.nodeType === 3) {
    if (a.data !== b.data) a.data = b.data;
    return;
  }
  if (a.nodeType !== 1 || b.nodeType !== 1 || a.nodeName !== b.nodeName
    || b.hasAttribute?.('data-fresh')) {
    a.replaceWith(b);
    return;
  }
  // attributes (className and style strings ride along as attributes)
  // A reused BUTTON whose class changes is a different control wearing the
  // same node (screens lining up positionally) — its `transition: background`
  // would visibly crossfade the old style into the new one (a dark filled
  // button melting into a text link read as a black flash). Repaints aren't
  // style animations: snap it, restore the transition after the paint.
  // A node with a data-key is only ever patched into a node with the SAME
  // key: siblings line up by position, so a conditional sibling appearing or
  // vanishing would otherwise hand one section's live state (an expanded
  // <details>) to its neighbour.
  if (a.getAttribute('data-key') !== b.getAttribute('data-key')) {
    a.replaceWith(b);
    return;
  }
  const snap = a.nodeName === 'BUTTON' && a.getAttribute('class') !== b.getAttribute('class');
  // <details open> is the user's doing (the browser toggles the attribute on
  // click), like a field's value: a render that doesn't set `open` leaves it
  // alone instead of collapsing the section on every background repaint.
  // <coinos-text> sets its own editing attributes when it joins the page;
  // the freshly built copy doesn't have them yet, and must not strip them
  const userOwned = (at) => (a.nodeName === 'DETAILS' && at.name === 'open')
    || (a.nodeName === 'COINOS-TEXT' && /^(contenteditable|role|aria-multiline|aria-placeholder|data-empty)$/.test(at.name));
  for (const at of [...a.attributes]) {
    if (b.hasAttribute(at.name) || userOwned(at)) continue;
    if (at.name === 'src' && b.hasAttribute('data-lazy-src')) continue; // the lazy source stands for it
    a.removeAttribute(at.name);
  }
  for (const at of [...b.attributes]) {
    if (at.name === 'data-lazy-src') { if (a.getAttribute('src') !== at.value) a.setAttribute('src', at.value); continue; }
    if (a.getAttribute(at.name) !== at.value) a.setAttribute(at.name, at.value);
  }
  if (snap) {
    a.style.transition = 'none';
    requestAnimationFrame(() => requestAnimationFrame(() => { a.style.transition = ''; }));
  }
  // event handler slots claimed via h()
  if (a._evs) for (const n of a._evs) if (!(b._evs && b._evs.has(n))) a[n] = null;
  if (b._evs) for (const n of b._evs) a[n] = b[n];
  a._evs = b._evs;
  // live form state: value/checked are properties, not attributes — but never
  // fight the user over a field they're currently editing
  const tag = a.nodeName;
  if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT') {
    if (document.activeElement !== a) {
      if (a.value !== b.value) a.value = b.value;
      if (a.checked !== b.checked) a.checked = b.checked;
    }
    if (a.disabled !== b.disabled) a.disabled = b.disabled;
  }
  // the contenteditable field: its text is its value, owned like a
  // textarea's — synced when not being edited, children never diffed
  if (tag === 'COINOS-TEXT') {
    if (document.activeElement !== a && a.value !== b.value) a.value = b.value;
    return;
  }
  // innerHTML-authored subtrees (svg icons, QRs): compare source, not nodes
  if (b._html != null) {
    if (a._html !== b._html) a.innerHTML = b._html;
    a._html = b._html;
    return;
  }
  if (a._html != null) {
    // the live node was innerHTML-authored but this render built children —
    // clear and fall through so the child loop rebuilds it (returning here
    // once left a form's field permanently empty)
    a.textContent = '';
    a._html = undefined;
  }
  // children, by position; snapshot first (appending b's children moves them)
  const ac = [...a.childNodes];
  const bc = [...b.childNodes];
  if (allKeyed(bc)) return morphKeyed(a, ac, bc);
  for (let i = 0; i < bc.length; i++) {
    if (!ac[i]) a.append(bc[i]);
    else if (ac[i] !== bc[i]) morph(ac[i], bc[i]);
  }
  for (let i = bc.length; i < ac.length; i++) ac[i].remove();
}

function morphChildren(parent, next) {
  const cur = [...parent.childNodes];
  if (allKeyed(next)) return morphKeyed(parent, cur, next);
  for (let i = 0; i < next.length; i++) {
    if (!cur[i]) parent.append(next[i]);
    else if (cur[i] !== next[i]) morph(cur[i], next[i]);
  }
  for (let i = next.length; i < cur.length; i++) cur[i].remove();
}

// A list whose every child carries a data-key is reconciled BY KEY, not by
// position: a post let in at the top of the feed used to be patched onto
// the old first row's node, and every row below it onto its neighbour's —
// so the node the new post was built as never reached the page (nothing
// that animates its own arrival could run), and each row's live state slid
// one post down. Keyed, the new row is inserted as itself and the old rows
// keep their nodes, moved down. Partially keyed lists keep the positional
// rule above, where a keyed node still refuses to patch into another key.
const allKeyed = (nodes) => nodes.length > 0
  && nodes.every((n) => n.nodeType === 1 && n.hasAttribute('data-key'));
function morphKeyed(parent, cur, next) {
  const byKey = new Map();
  for (const n of cur) if (n.nodeType === 1 && n.hasAttribute('data-key')) byKey.set(n.getAttribute('data-key'), n);
  // Drop what the new render no longer has BEFORE placing the rest: with
  // stale nodes still in front, every survivor's position was off by the
  // stale count and each one was pulled out and re-inserted — a move per row
  // per repaint (the feed's window evicting rows at the top did this to all
  // the rows below on every scroll), and a moved <video> is taken out of
  // the document and back, which restarts its loading.
  const wanted = new Set(next.map((b) => b.getAttribute('data-key')));
  for (const n of cur) {
    if (n.parentNode !== parent) continue;
    const k = n.nodeType === 1 ? n.getAttribute('data-key') : null;
    if (k == null || !wanted.has(k)) n.remove();
  }
  const kept = new Set();
  for (let i = 0; i < next.length; i++) {
    const b = next[i];
    const have = byKey.get(b.getAttribute('data-key'));
    let node = b;
    if (have && !kept.has(have)) {
      morph(have, b); // may itself swap the node out (data-fresh, tag change)
      node = have.parentNode === parent ? have : b;
    }
    kept.add(node);
    const at = parent.childNodes[i] || null;
    if (at !== node) parent.insertBefore(node, at);
  }
  for (const n of cur) if (!kept.has(n) && n.parentNode === parent) n.remove();
}

const root = document.getElementById('app');
function footer() {
  return h(
    'div',
    { class: 'footer small muted center' },
    h(
      'div',
      {},
      t('footerMadeBy') + ' ',
      h('a', { href: 'https://adamsoltys.com', target: '_blank', rel: 'noopener' }, 'Adam Soltys'),
      h('span', { class: 'faint' }, ' · '),
      t('footerSourceOn') + ' ',
      h('a', { href: 'https://git.coinos.io/coinosv3.git/', target: '_blank', rel: 'noopener' }, 'git.coinos.io')
    ),
    h(
      'div',
      { style: 'margin-top:4px' },
      h('button', { class: 'linklike', style: 'font-weight:400', onClick: openHowItWorks }, t('howItWorks')),
      // the hat shop: needs a wallet to pay from, so only once one is open
      activeAccount() && FEATURES.some((f) => f.openHatShop)
        ? h('span', {}, h('span', { class: 'faint' }, ' · '),
            h('button', { class: 'linklike', style: 'font-weight:400', onClick: () => { clearFeatureNav(); ui.screen = 'wallet'; featureHook('openHatShop'); } }, t('footerSupport')))
        : null,
      // Chrome no longer prompts to install on its own — surface our own link
      // once it reports the app is installable. We render from a persisted flag
      // (not the live event) so the link is present on the first paint after a
      // refresh, avoiding a layout shift when beforeinstallprompt fires late.
      installable()
        ? h('span', {}, h('span', { class: 'faint' }, ' · '),
            h('button', { class: 'linklike', style: 'font-weight:400', onClick: triggerInstall }, t('installApp')))
        : null,
      h('span', { class: 'faint' }, ' · '),
      h('button', { class: 'linklike', style: 'font-weight:400', onClick: toggleTheme }, resolvedTheme() === 'dark' ? t('lightMode') : t('darkMode'))
    ),
    // Display preferences live together: the language this reads in, and the
    // money amounts are shown in. (The currency sat under Settings → Network
    // for exactly one day, where nobody found it.)
    h('div', { class: 'row gap6', style: 'margin-top:8px;justify-content:center' }, languagePicker(), currencyPicker()),
    // The commit stamp settles "is my PWA fresh?" AND "what code is this?" in
    // one glance — its own last line, so it never wraps the credits on mobile.
    h('div', { class: 'faint', style: 'margin-top:6px' },
      'Running git commit ',
      h('a', { class: 'faint', href: 'https://git.coinos.io/coinosv3.git/commit/?id={{COMMIT}}', target: '_blank', rel: 'noopener' }, '{{COMMIT}}'))
  );
}

const THEME_KEY = 'btc-wallet-theme';
function resolvedTheme() {
  try {
    const s = localStorage.getItem(THEME_KEY);
    if (s === 'dark' || s === 'light') return s;
  } catch {}
  try { return matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'; } catch {}
  return 'light';
}
function applyTheme() {
  try {
    const th = resolvedTheme();
    document.documentElement.dataset.theme = th;
    // the browser's status bar (a PWA, or the Android app) takes its colour
    // from here: the page background in light, the dark theme colour in dark
    const meta = document.querySelector('meta[name="theme-color"]');
    if (meta) meta.setAttribute('content', th === 'dark' ? '#15171a' : '#eef0f3');
  } catch {}
}
function toggleTheme() {
  try { localStorage.setItem(THEME_KEY, resolvedTheme() === 'dark' ? 'light' : 'dark'); } catch {}
  applyTheme();
  render();
}

// PWA install. Chrome fires beforeinstallprompt when the app qualifies; we stash
// the event and reveal an "Install app" link, then replay it on a user tap (the
// browser requires a gesture). The link's visibility is driven by a persisted
// flag rather than the live event so it's present on the first paint after a
// refresh (no layout shift); the event only supplies the prompt to replay.
// We deliberately do NOT call e.preventDefault(): modern Chrome shows no banner
// of its own to suppress, and preventDefault-without-prompt() logs a console
// warning. The event stays usable for our own e.prompt() on tap.
const INSTALLABLE_KEY = 'btc-wallet-installable';
let installPrompt = null;
function isStandalone() {
  try {
    return matchMedia('(display-mode: standalone)').matches || navigator.standalone === true;
  } catch { return false; }
}
function installable() {
  if (isStandalone()) return false;
  try { return localStorage.getItem(INSTALLABLE_KEY) === '1'; } catch { return false; }
}
function setInstallable(v) {
  try {
    if (v) localStorage.setItem(INSTALLABLE_KEY, '1');
    else localStorage.removeItem(INSTALLABLE_KEY);
  } catch {}
}
if (typeof window !== 'undefined') {
  window.addEventListener('beforeinstallprompt', (e) => {
    installPrompt = e;
    // Only re-render if this changes what's on screen; on a refresh the link is
    // already shown from the persisted flag, so nothing moves.
    const wasShown = installable();
    setInstallable(true);
    if (!wasShown) render();
  });
  window.addEventListener('appinstalled', () => {
    installPrompt = null;
    setInstallable(false);
    render();
  });
}
async function triggerInstall() {
  const e = installPrompt;
  // The prompt event may not have fired yet this load even though the link is
  // shown from the persisted flag; bail quietly if so.
  if (!e) return;
  installPrompt = null;
  e.prompt();
  try {
    await e.userChoice;
  } catch {}
}

// Open the How it works page, remembering where to return to.
function openHowItWorks() {
  if (ui.screen === 'howItWorks') return;
  ui.returnScreen = ui.screen;
  ui.screen = 'howItWorks';
  render();
}

// Per-tab session nav (tab + open tx), so a refresh keeps the user's place.
const NAV_KEY = 'btc-wallet-nav';

// Index path from #app down to a node, and back — used to re-find the focused
// field after a full rebuild (a background re-render produces the same structure).
function focusPath(el) {
  const path = [];
  for (let n = el; n && n !== root; n = n.parentNode) {
    const p = n.parentNode;
    if (!p) return null;
    path.unshift(Array.prototype.indexOf.call(p.children, n));
  }
  return path;
}
function nodeAtPath(path) {
  let n = root;
  for (const i of path) n = n && n.children[i];
  return n || null;
}

// ---- one-shot animation gating -------------------------------------------
// The renderer rebuilds the whole DOM on every render, so a CSS mount
// animation would replay on every background repaint (balance ticks, chat
// bursts). These helpers answer "did this change since the last render?" —
// things animate only in the render where they actually happened.
const _uiSeen = new Map();
function uiChanged(key, val) {
  const prev = _uiSeen.get(key);
  _uiSeen.set(key, val);
  return prev !== val;
}
// A background render can land mid-animation and rebuild the node without
// its one-shot class, killing the motion. animWindow answers "how far into
// the animation started by this change are we?" — callers re-apply the class
// with a negative animation-delay so a rebuild RESUMES the animation.
let _navAt = -1e9;
let _swipeDir = null; // set by the swipe handler just before render
// tab switches carousel just the content pane, not the whole page
let _tabAt = -1e9;
let _tabCls = 'anim-tab-left';
let _tabSeen = false; // a tab has rendered before (slides are for CHANGES, not arrivals)
let _prevTabIdx = 0;
const _animAt = new Map();
function animWindow(key, val, durMs) {
  if (uiChanged(key, val)) _animAt.set(key, performance.now());
  const dt = performance.now() - (_animAt.get(key) ?? -1e9);
  return dt < durMs ? dt : -1;
}
function applyAnim(el, cls, dt) {
  if (dt < 0 || !el || !el.classList) return;
  el.classList.add(cls);
  el.style.animationDelay = -Math.round(dt) + 'ms';
}

// A balance that counts to its new value instead of teleporting, with a green
// breath when money arrived. Keyed so background renders don't re-animate.
const _amtLast = new Map();
function animatedAmount(key, sat) {
  const prev = _amtLast.get(key);
  _amtLast.set(key, sat);
  // data-fresh: this node animates itself with its own rAF loop after render,
  // so the morph must install THIS node, not patch text onto last render's
  const el = h('span', { 'data-fresh': '1' }, fmtAmount(sat));
  if (prev !== undefined && prev !== sat) {
    const from = prev, to = sat, t0 = performance.now(), dur = 550;
    const step = (t) => {
      if (!el.isConnected) return; // a newer render owns the number now
      const p = Math.min(1, (t - t0) / dur);
      const e = 1 - Math.pow(1 - p, 3);
      el.textContent = fmtAmount(Math.round(from + (to - from) * e));
      if (p < 1) requestAnimationFrame(step);
    };
    requestAnimationFrame(step);
    if (to > from) el.classList.add('amt-flash');
  }
  return el;
}

let _carDragging = false; // a balance-carousel drag is in progress
let _renderDeferred = false;
// /chat runs the standalone public community view: it owns #app outright,
// and every app render (feature init, emitter ticks) must stand down or the
// onboarding screen paints over the chat moments after it mounts.
let _publicChatMode = false;
// True until boot has decided whether a session is restoring. Anything that
// renders before then (a deferred feature chunk landing, an emitter tick) is
// rendering without knowing whether anyone is signed in — and the signed-out
// welcome screen is the one screen that must never be guessed at. The boot
// shell holds the frame for those few ms instead; see the dispatch below.
let _bootDeciding = true;
// Belt and braces: a boot path that returns early (or throws) must not leave
// the welcome screen held back forever. Nothing legitimate is still deciding
// four seconds in — the store wait alone caps at 800ms.
setTimeout(() => { if (_bootDeciding) { _bootDeciding = false; render(); } }, 4000);
// A picture, full screen. Posts show images cropped to a few hundred pixels
// so a feed stays a feed; this is where you actually look at one. Tap
// anywhere (or Escape, or Back) to close — no chrome, nothing to aim at.
function imageViewer() {
  if (!ui.lightbox) return null;
  const close = () => {
    if (!ui.lightbox) return;
    ui.lightbox = null;
    // Dismiss before history traversal and its page render finish. Read the
    // mounted viewer: morphing can replace handlers with a new render's ones.
    document.querySelector('.lightbox')?.remove();
    document.documentElement.classList.remove('no-scroll');
    goBack(() => { ui.lightbox = null; });
  };
  // A tap on the picture closes it at every zoom level; gestures are filtered
  // by attachZoom before this click handler runs.
  const img = h('img', { src: ui.lightbox, alt: '', draggable: 'false' });
  const box = h('div', {
    class: 'lightbox', onClick: close,
    role: 'dialog', 'aria-modal': 'true',
  }, img,
     // stop the bubble: the backdrop closes too, and two pops walk out of the room
     h('button', { class: 'lightbox-x', 'aria-label': t('close'), onClick: (e) => { e.stopPropagation(); close(); } }, '\u00d7'));
  attachZoom(box, img);
  return box;
}
// Pinch to zoom (up to 5×) around the fingers, drag to pan a zoomed picture,
// the wheel to zoom on a desktop. Single taps dismiss immediately rather
// than waiting to distinguish a double-tap. The viewport turns browser zoom
// off, so the picture does its own. Only the first-mounted nodes keep these
// listeners: later renders morph into them, and the img is left out of the
// morph so its transform survives a background render.
function attachZoom(box, img, { wheel = true } = {}) {
  img._skipMorph = true;
  const MAX = 5, pts = new Map();
  let s = 1, x = 0, y = 0, pinch = null, pan = null, moved = false;
  const base = () => ({ bx: img.offsetLeft + img.offsetWidth / 2, by: img.offsetTop + img.offsetHeight / 2 });
  const clamp = () => {
    if (s <= 1) { s = 1; x = 0; y = 0; return; }
    const mx = Math.max(0, (img.offsetWidth * s - window.innerWidth) / 2), my = Math.max(0, (img.offsetHeight * s - window.innerHeight) / 2);
    x = Math.min(mx, Math.max(-mx, x)); y = Math.min(my, Math.max(-my, y));
  };
  const apply = (animate) => {
    img.style.transition = animate ? 'transform .2s ease' : 'none';
    img.style.transform = s === 1 && !x && !y ? '' : `translate(${x}px, ${y}px) scale(${s})`;
    img.style.cursor = s > 1 ? 'grab' : '';
    // zoomed, the finger pans the picture; at 1× the touch is the page's (a pager's swipe)
    img.style.touchAction = s > 1 ? 'none' : '';
  };
  // scale to ns keeping the picture point under (cx, cy) where it is
  const zoomAt = (ns, cx, cy) => {
    const { bx, by } = base();
    const px = (cx - bx - x) / s, py = (cy - by - y) / s;
    s = Math.min(MAX, Math.max(1, ns));
    x = cx - bx - px * s; y = cy - by - py * s;
  };
  box.addEventListener('pointerdown', (e) => {
    if (e.target.closest('.lightbox-x')) return;
    pts.set(e.pointerId, { x: e.clientX, y: e.clientY });
    if (pts.size === 1) moved = false;
    begin();
  });
  const begin = () => {
    const p = [...pts.values()];
    if (p.length >= 2) {
      moved = true; // two fingers are a gesture even before either moves
      const { bx, by } = base();
      const mx = (p[0].x + p[1].x) / 2, my = (p[0].y + p[1].y) / 2;
      pinch = { d: Math.hypot(p[0].x - p[1].x, p[0].y - p[1].y) || 1, s, px: (mx - bx - x) / s, py: (my - by - y) / s };
      pan = null;
    } else if (p.length === 1) {
      pinch = null;
      pan = { sx: p[0].x, sy: p[0].y, x, y };
    }
  };
  box.addEventListener('pointermove', (e) => {
    if (!pts.has(e.pointerId)) return;
    pts.set(e.pointerId, { x: e.clientX, y: e.clientY });
    const p = [...pts.values()];
    if (pinch && p.length >= 2) {
      const { bx, by } = base();
      const d = Math.hypot(p[0].x - p[1].x, p[0].y - p[1].y);
      const mx = (p[0].x + p[1].x) / 2, my = (p[0].y + p[1].y) / 2;
      s = Math.min(MAX, Math.max(0.8, pinch.s * d / pinch.d)); // a little give below 1, snapped back on release
      x = mx - bx - pinch.px * s; y = my - by - pinch.py * s;
      moved = true;
      apply(false);
    } else if (pan && p.length === 1) {
      const dx = p[0].x - pan.sx, dy = p[0].y - pan.sy;
      if (Math.abs(dx) + Math.abs(dy) > 8) moved = true;
      if (s > 1) { x = pan.x + dx; y = pan.y + dy; clamp(); apply(false); }
    }
  });
  const end = (e) => {
    if (!pts.delete(e.pointerId)) return;
    if (e.type === 'pointercancel') moved = true;
    if (pts.size) { begin(); return; } // one finger lifted mid-pinch: carry on as a pan
    pinch = pan = null;
    clamp(); apply(true);
  };
  box.addEventListener('pointerup', end);
  box.addEventListener('pointercancel', end);
  // a drag or a pinch is not a tap: nothing closes after one
  box.addEventListener('click', (e) => {
    if (e.target.closest('.lightbox-x')) return;
    if (moved) { moved = false; e.stopImmediatePropagation(); e.preventDefault(); return; }
  }, true);
  if (wheel) box.addEventListener('wheel', (e) => {
    e.preventDefault();
    zoomAt(s * Math.exp(-e.deltaY * 0.002), e.clientX, e.clientY);
    clamp(); apply(false);
  }, { passive: false });
}
if (typeof window !== 'undefined') {
  window.addEventListener('keydown', (e) => { if (e.key === 'Escape' && ui.lightbox) goBack(() => { ui.lightbox = null; }); });
  // Enter walks the Send flow: from an amount (or any field) it presses the
  // screen's main button — Review, Pay, Send — and with nothing focused it
  // presses it again, so amount ⏎ reviews and ⏎ again confirms. A held key
  // (auto-repeat) never presses anything: one deliberate tap per step.
  window.addEventListener('keydown', (e) => {
    if (e.key !== 'Enter' || e.repeat || e.isComposing || e.shiftKey || e.ctrlKey || e.altKey || e.metaKey) return;
    if (ui.screen !== 'wallet' || ui.tab !== 'send') return;
    const pane = document.querySelector('[data-send-pane]');
    if (!pane) return;
    const a = document.activeElement;
    const onBody = !a || a === document.body || a === document.documentElement;
    // buttons and links answer Enter themselves; the recipient field has its own
    if (!onBody && !(a.tagName === 'INPUT' && pane.contains(a) && !/^(checkbox|radio|button|submit)$/.test(a.type))) return;
    const btn = pane.querySelector('.btn-primary.btn-block:not(:disabled), .btn-primary.grow:not(:disabled)');
    if (!btn) return;
    e.preventDefault();
    if (!onBody) a.blur(); // the next Enter belongs to the screen this one opens
    btn.click();
  });
}

function render() {
  if (_publicChatMode) return;
  // A background render mid carousel-drag rebuilds the strip; the morph then
  // strips the drag's inline scroll-snap-type:none, so mandatory snap yanks
  // the card back to its origin — the "jump partway through" stutter (a
  // position jump, not a dropped frame). Hold renders while the FINGER is
  // down (pointermove writes scrollLeft on the main thread — a render there
  // eats frames); after release the strip is morph-frozen (_skipMorph)
  // instead, so the glide runs undisturbed while the history below is
  // already switching to the chosen account.
  if (_carDragging) { _renderDeferred = true; return; }
  // A render that throws must never brick the page silently: stale DOM keeps
  // its handlers, every one of them calls render again, and every tap turns
  // into a no-op. Show the error and offer the way out instead.
  try { renderInner(); } catch (err) { renderCrash(err); }
}
function endCarouselDrag() {
  _carDragging = false;
  // the strip was frozen against the morph for the glide — unfreeze it and
  // make sure one render runs so it catches up with any state committed early
  const strip = document.querySelector('.bal-carousel');
  if (strip && strip._skipMorph) { strip._skipMorph = false; _renderDeferred = true; }
  if (_renderDeferred) { _renderDeferred = false; render(); }
}
function renderCrash(err) {
  console.error('render failed:', err);
  try {
    const div = document.createElement('div');
    div.className = 'card col';
    div.style.cssText = 'margin:20px;gap:10px';
    const h3 = document.createElement('h3');
    h3.textContent = 'Something broke';
    const pre = document.createElement('div');
    pre.className = 'small muted';
    pre.style.cssText = 'word-break:break-word;white-space:pre-wrap';
    pre.textContent = String((err && (err.stack || err.message)) || err).slice(0, 600);
    const btn = document.createElement('button');
    btn.className = 'btn-primary btn-block';
    btn.textContent = 'Reload';
    btn.onclick = () => location.reload();
    div.append(h3, pre, btn);
    root.replaceChildren(div);
  } catch {}
}
function renderInner() {
  // A direct render subsumes any coalesced one queued by a background emit, so
  // drop the pending one (a user action must not trigger a second rebuild).
  if (_renderRaf) { clearTimeout(_renderRaf); _renderRaf = 0; }
  _lastRender = Date.now();
  // Preserve focus + caret across the rebuild, so a background update (poll, a
  // payment push, an SP scan) can't kick the user out of a field they're editing.
  const a = document.activeElement;
  let fpath = null, selStart = null, selEnd = null;
  if (a && root.contains(a) && /^(INPUT|SELECT|TEXTAREA|COINOS-TEXT)$/.test(a.tagName)) {
    fpath = focusPath(a);
    try { selStart = a.selectionStart; selEnd = a.selectionEnd; } catch {}
  }
  // Same idea for scrollable strips (the punks carousel): a rebuild must not
  // yank a half-scrolled list back to its start. Anything marked with
  // data-keep-scroll gets its position carried across the swap.
  const scrolls = {};
  for (const el of root.querySelectorAll('[data-keep-scroll]'))
    if (el.scrollLeft || el.scrollTop)
      scrolls[el.getAttribute('data-keep-scroll')] = { l: el.scrollLeft, t: el.scrollTop };
  // The padlock's "protect this device?" ask is modal: it belongs over
  // whatever page the tap happened on. A feature screen (your profile, a chat
  // thread) used to swallow it — walletScreen paints the card, and
  // screenView outranks walletScreen, so the padlock did nothing visible
  // until you navigated back to the wallet and the card finally appeared
  // there. Declining still lands back exactly where the tap happened,
  // because nothing else moves. Onboarding keeps its precedence.
  const lockAsk = ui.pw && ui.pw.purpose === 'lock' && !(ui.onb || onbInProgress());
  sendPageRendered = false;
  const featScreen = !lockAsk && featureHook('screenView');
  const screen =
    (lockAsk && h('div', { class: 'col', style: 'gap:16px' }, brandHeader(false), pwPromptCard()))
    || featScreen
    || (ui.screen === 'wallet'
      ? walletScreen()
      : ui.screen === 'accounts'
        ? accountsScreen()
        : ui.screen === 'accountSettings'
          ? accountSettingsScreen()
        : ui.screen === 'vault'
          ? vaultScreen()
          : ui.screen === 'howItWorks'
            ? howItWorksScreen()
            : _bootDeciding
              // Not "nobody is signed in" — "we don't know yet". Painting
              // Get started here is what flashed the sign-in page over a
              // wallet that was about to restore. Every other screen is a
              // deliberate choice and still paints; this one waits.
            ? h('div', { class: 'col', style: 'gap:16px' }, BOOT_NAV ? null : brandHeader(false))
              : shouldOnboard() ? onboardScreen() : unlockScreen());
  // Track the pane actually rendered: a profile or chat hides Send even
  // when its wallet tab is still selected. Reviews/results stay in Send.
  if (sendPageOpen && !sendPageRendered) clearSend();
  sendPageOpen = sendPageRendered;
  // Navigation animates; background repaints must not. The key is every
  // ui field that decides which page is on screen.
  const navKey = [ui.screen, ui.tab === 'settings', ui.chatOpen, ui.msgView, ui.msgPeer, ui.msgCommunity,
    ui.profilePk, ui.settingsPage, ui.addrScan, ui.arkExitPage, ui.txDetail, ui.giftMode, ui.claimStep, ui.nameEditOpen,
    ui.noteThread && ui.noteThread.focusId, !!ui.userSearch, !!ui.zapSetup, !!ui.hatShop, !!ui.feedEdit, ui.settingsView].join('|');
  // A deep-linked profile landing is ONE page settling, not a chain of
  // navigations: boot screens shuffle beneath the shell (unlock → restored
  // wallet), then the resolved profile replaces the shell in place. The key
  // still updates, but nothing slides or re-animates until the landing ends.
  if (uiChanged('nav', navKey)) {
    // ui.navAnimSkip: a one-shot "this navigation must not animate" — set by
    // sign-in right before the wallet screen takes over, so the handover is
    // an instant swap instead of a fade over a page that's still settling.
    if (!(ui.pubProfPending || ui.pubProfHold || ui.navAnimSkip)) _navAt = performance.now();
    ui.navAnimSkip = false;
  }
  applyAnim(screen, 'anim-page', (performance.now() - _navAt) < 340 ? performance.now() - _navAt : -1);
  // The bottom nav rides every page of a signed-in wallet and a visitor's
  // public pages — never over sign-in, onboarding or the lock prompt.
  const navPage = ui.pubProf || (activeAccount() && ['wallet', 'accounts', 'accountSettings'].includes(ui.screen) && !(ui.onb || onbInProgress()));
  const bottomNav = navPage && !lockAsk && !_bootDeciding ? featureHook('bottomNav') : null;
  if (bottomNav) bottomNav.prepend(h('div', { class: 'app-nav-wide app-nav-brand' }, brandLogo()));
  // the wallet beside the feed and chats on a wide screen (its own page needs no twin)
  const side = bottomNav && featScreen && WIDE_MQ && WIDE_MQ.matches ? walletSide() : null;
  morphChildren(root, [screen, footer(), ...(bottomNav ? [bottomNav] : []), ...(side ? [side] : []), ...(ui.lightbox ? [imageViewer()] : [])]);
  promoteLazySrc(root); // sources on the nodes that actually made it into the page
  try { document.documentElement.classList.toggle('no-scroll', !!(ui.lightbox || ui.mediaPager)); } catch {}
  if (fpath) {
    const el = nodeAtPath(fpath);
    if (el && el !== a && /^(INPUT|SELECT|TEXTAREA|COINOS-TEXT)$/.test(el.tagName)) {
      try { el.focus({ preventScroll: true }); if (selStart != null && el.setSelectionRange) el.setSelectionRange(selStart, selEnd); } catch {}
    }
  }
  for (const el of root.querySelectorAll('[data-keep-scroll]')) {
    const s = scrolls[el.getAttribute('data-keep-scroll')];
    if (s) { el.scrollLeft = s.l; el.scrollTop = s.t; }
  }
  // Fast-poll the receive address only while the user is actually watching for a
  // payment (wallet screen, Receive tab, online). Idempotent — safe each render.
  wallet.setWatchReceive(ui.screen === 'wallet' && ui.tab === 'receive' && !wallet.offline);
  if (ui.screen === 'wallet') {
    commitAccount(); // entering the wallet (any path) keeps a provisional gift account
    // Remember where we are so a refresh restores it (only meaningful on the wallet).
    try { sessionStorage.setItem(NAV_KEY, JSON.stringify({ tab: ui.tab, txDetail: ui.txDetail })); } catch {}
  }
  syncHistory(); // mirror the current screen into browser history (Back/Forward)
}

// Background state changes (a wake scan, cross-device sync merges, WS payment
// pushes) can fire a burst of emits — especially when the PWA is refocused
// after being backgrounded. Rendering synchronously on each one rebuilds the
// whole screen dozens of times in a row and starves user input, so the app
// feels frozen for a second or two. Coalesce those into at most one render per
// 200ms: one-per-frame still meant a visible strobe during boot bursts (every
// rebuild swaps the node under the cursor, dropping its :hover until the next
// mouse move — buttons flashed under a resting pointer). Direct user actions
// still call render() synchronously and always take priority; render() itself
// stamps the throttle, so a user render pushes the next background one out.
let _renderRaf = 0;
let _lastRender = 0;
const BG_RENDER_MIN_MS = 200;
function scheduleRender() {
  if (_renderRaf) return;
  const wait = Math.max(0, BG_RENDER_MIN_MS - (Date.now() - _lastRender));
  _renderRaf = setTimeout(() => { _renderRaf = 0; render(); }, wait);
}
wallet.subscribe(scheduleRender);

// ---- browser-history navigation ------------------------------------------
// Mirror the app's screen position into the browser history so the Back/Forward
// buttons (and Android/system back) move between screens we've actually viewed.
// We snapshot only the navigation-relevant `ui` fields, so incidental re-renders
// (typing, polling, balance updates) don't create history entries.
// arkMoveDetail/arkExitDetail/giftDetail are the ark and gift rows' detail
// views — most Spending payments open one of these, and leaving them out
// meant the phone's native Back skipped past the history list entirely
// (it landed on whatever tab minted the previous entry).
// lightbox: a full-screen photo is a place too — the phone's Back must close
// it, not pop the screen under it (which once walked a viewer straight back
// to the start page, so the photo's × then looked like a logout).
const NAV_FIELDS = ['screen', 'tab', 'txDetail', 'arkMoveDetail', 'arkReconDetail', 'arkExitDetail', 'giftDetail', 'bump', 'giftMode', 'claimStep', 'chatOpen', 'msgView', 'feedId', 'pubProf', 'arkCoinsPage', 'arkExitPage', 'msgCommunity', 'msgPeer', 'profilePk', 'profEdit', 'profEditFilled', 'profOverThread', 'settingsPage', 'nameEditOpen', 'noteThread', 'userSearch', 'zapSetup', 'hatShop', 'lightbox', 'mediaPager', 'feedEdit', 'settingsView'];
function navSnapshot() {
  const s = {};
  for (const f of NAV_FIELDS) s[f] = ui[f] ?? null;
  // Screens with volatile sub-state (a reply draft, typed amounts, search
  // results streaming in) snapshot only what IDENTIFIES the screen — a
  // keystroke must never mint a history entry.
  if (ui.noteThread) s.noteThread = { rootId: ui.noteThread.rootId, focusId: ui.noteThread.focusId, seed: ui.noteThread.seed };
  if (ui.userSearch) s.userSearch = { q: '', rows: null };
  if (ui.feedEdit) s.feedEdit = { ...ui.feedEdit, q: '', rows: null, pq: '', packRows: null, pt: null };
  if (ui.zapSetup) s.zapSetup = { pk: ui.zapSetup.pk, npub: ui.zapSetup.npub, eventId: ui.zapSetup.eventId, amount: '21' };
  // Keep the editable fields in this history entry so a refresh restores the
  // draft. Copy them: later keystrokes must not mutate earlier snapshots.
  s.profEdit = ui.profilePk && ui.profEdit ? Object.fromEntries(
    ['uname', 'name', 'about', 'picture', 'banner'].map(k => [k, ui.profEdit[k] || ''])) : null;
  if (s.profEdit) s.profEdit.touched = { ...ui.profEdit.touched };
  s.profEditFilled = !!s.profEdit && !!ui.profEditFilled;
  return s;
}
const navSig = ({ profEdit, profEditFilled, ...s }) => JSON.stringify({ ...s, profEdit: !!profEdit });
let navStack = []; // in-memory mirror of the history entries (to detect an in-app Back)
let navIndex = -1;
let restoringHistory = false; // true while applying a popstate (suppresses pushing)

// The address bar names what is on screen when that thing has a nostr
// address of its own: a thread is /nevent1… (the post or reply it opened
// on), a profile /npub1…. So the link in the bar is the link to the post —
// copy it, send it, reload it — the same paths the deep links already open.
// Every other screen keeps whatever path it had (the till at /pos, the
// plain app at /); only a path we set ourselves is taken back to /.
const OWN_PATH = /^\/(nevent|note|npub)1[a-z0-9]+\/?$/i;
function navUrl(snap) {
  try {
    const fp = featureHook('navPath', snap); // a feed with a public address
    if (fp) return fp;
    const th = snap.noteThread;
    if (snap.profilePk && (snap.profOverThread || !th)) return '/' + npubOf(snap.profilePk);
    if (th && th.focusId) {
      const author = th.seed && th.seed.id === th.focusId ? th.seed.pubkey : undefined;
      const enc = neventOf(th.focusId, author);
      if (enc) return '/' + enc;
    }
    return OWN_PATH.test(location.pathname) ? '/' : undefined;
  } catch { return undefined; }
}

function syncHistory() {
  if (restoringHistory) return;
  try {
    const snap = navSnapshot();
    const sig = navSig(snap);
    if (navIndex >= 0 && sig === navSig(navStack[navIndex])) {
      // Typing changes the draft, not the page. Replace the current entry
      // instead of making Back walk through every version of the form.
      if (JSON.stringify(snap) !== JSON.stringify(navStack[navIndex])) {
        history.replaceState({ nav: snap, i: navIndex }, '', navUrl(snap));
        navStack[navIndex] = snap;
      }
      return;
    }
    // The renders between a reload and the restore of where it was (the
    // unlock screen, a deep-linked profile over it, the wallet opening) are
    // one slot, not a trail: pushing them put two or three dead entries
    // between the restored screen and the one before it, so Back after a
    // reload went nowhere useful.
    if (bootPending && navIndex >= 0) {
      navStack = navStack.slice(0, navIndex + 1);
      navStack[navIndex] = snap;
      history.replaceState({ nav: snap, i: navIndex }, '', navUrl(snap));
      if (ui.screen === 'wallet') bootPending = false;
      return;
    }
    // Every screen change is a new history entry. (We deliberately don't try to
    // detect in-app "back" navigations — an A→B→A pattern is indistinguishable
    // from a genuine back, so guessing corrupts the stack. An in-app back just
    // adds an entry; Back/Forward still walk the screens correctly.)
    navStack = navStack.slice(0, navIndex + 1); // drop any forward entries
    navStack.push(snap);
    navIndex++;
    const entry = { nav: snap, i: navIndex };
    if (navIndex === 0) history.replaceState(entry, '', navUrl(snap));
    else history.pushState(entry, '', navUrl(snap));
  } catch {} // history API failures must never break a render
}

// A refresh must land where the user was — on a profile, a settings page, a
// tab — not back home. history.state survives reload, but any boot-time
// render runs syncHistory and replaceStates a blank snapshot over it — so
// the pre-reload nav is captured HERE, at script load, before any render.
const BOOT_NAV = (() => { try { return (history.state && history.state.nav) || null; } catch { return null; } })();
// ...and until it is restored (or the wallet is simply open, or a few
// seconds pass on the unlock screen), boot renders share one history slot.
let bootPending = !!BOOT_NAV;
if (bootPending) setTimeout(() => { bootPending = false; }, 5000);
function restoreNavFromHistory(renderNow = true) {
  try {
    const nav = BOOT_NAV;
    if (!nav || ui.screen !== 'wallet') return;
    bootPending = false;
    // The page that saved this nav may have had no wallet (the start screen,
    // the vault prompt); with an account open now, those screens are stale.
    // Restoring one painted the start page over a perfectly good wallet.
    if (['unlock', 'vault'].includes(nav.screen) && activeAccount()) nav.screen = 'wallet';
    for (const f of NAV_FIELDS) if (f in nav) ui[f] = (f === 'profEdit' || f === 'feedEdit') && nav[f] ? structuredClone(nav[f]) : nav[f];
    ui.lightbox = null; nav.lightbox = null; // an object URL doesn't survive a reload
    ui.mediaPager = null; nav.mediaPager = null; // nor does the feed under a media pager, not yet
    navStack = [nav];
    navIndex = 0;
    // A reload is a continuation of the same page, not a navigation. Do not
    // replay the full-page entrance animation as boot state settles.
    ui.navAnimSkip = true;
    _navAt = -1e9;
    history.replaceState({ nav, i: 0 }, '', navUrl(nav)); // undo any boot-render clobber (and the boot's path tidy)
    if (renderNow) render();
  } catch {}
}

window.addEventListener('popstate', (e) => {
  const st = e.state;
  let snap = (st && st.nav) || navSnapshot();
  // The entries minted before sign-in (welcome, sign-in, the seed) are still
  // in the browser's history. Walking Back into one with a wallet open showed
  // the start page over a perfectly open session — which reads as "I got
  // logged out". With a wallet open, those entries become the wallet home.
  if (['unlock', 'vault'].includes(snap.screen) && activeAccount() && ui.screen === 'wallet') {
    snap = Object.fromEntries(NAV_FIELDS.map((f) => [f, null]));
    snap.screen = 'wallet'; snap.tab = ui.tab ?? null;
    try { history.replaceState({ nav: snap, i: st && typeof st.i === 'number' ? st.i : navIndex }, ''); } catch {}
  }
  restoringHistory = true;
  try {
    for (const f of NAV_FIELDS) ui[f] = (f === 'profEdit' || f === 'feedEdit') && snap[f] ? structuredClone(snap[f]) : f in snap ? snap[f] : null;
    if (st && typeof st.i === 'number') navIndex = st.i;
    else { const i = navStack.findIndex((s) => navSig(s) === navSig(snap)); if (i >= 0) navIndex = i; }
    render();
  } finally {
    restoringHistory = false;
  }
});

// In-app "back" buttons call this instead of mutating ui + render() directly, so
// they POP the history entry they're leaving rather than pushing a duplicate.
// When there's no in-app entry to pop (e.g. the page was reloaded straight into a
// sub-screen), fall back to navigating to the explicit parent.
function goBack(toParent) {
  if (navIndex > 0) history.back();
  else { toParent(); render(); }
}
// Whether an in-app Back has anywhere of ours to go. A page opened straight
// from a link has nothing under it; its Back would invent a parent.
const canGoBack = () => navIndex > 0;

// ---------------------------------------------------------------- utilities
let toastTimer;
function toast(msg, ms = 1600) {
  let t = document.querySelector('.toast');
  if (!t) {
    t = h('div', { class: 'toast' });
    document.body.append(t);
  }
  t.textContent = msg;
  requestAnimationFrame(() => t.classList.add('show'));
  clearTimeout(toastTimer);
  toastTimer = setTimeout(() => t.classList.remove('show'), ms);
}

async function copy(text) {
  try {
    await navigator.clipboard.writeText(text);
  } catch {
    const ta = h('textarea', { value: text });
    document.body.append(ta);
    ta.select();
    try {
      document.execCommand('copy');
    } catch {}
    ta.remove();
  }
  toast(t('copied'));
}

// Open a URL in a new window/tab. window.open is more reliable than an
// <a target="_blank"> inside an installed PWA (standalone mode), where the link
// can otherwise navigate the app away instead of opening externally.
function openExternal(url) {
  try { window.open(url, '_blank', 'noopener,noreferrer'); } catch {}
}

function download(filename, text, mime = 'application/json') {
  const url = URL.createObjectURL(new Blob([text], { type: mime }));
  const a = h('a', { href: url, download: filename });
  document.body.append(a);
  a.click();
  a.remove();
  setTimeout(() => URL.revokeObjectURL(url), 1000);
}


function copyBtn(text, label = t('copy')) {
  return h('button', { class: 'btn-sm', onClick: () => copy(text) }, label);
}

// A small "paste from clipboard" button; apply(text) receives the trimmed text.
// Returns null where the Clipboard read API isn't available (the catch keeps it
// silent if a browser blocks the read).
function pasteBtn(apply) {
  if (typeof navigator === 'undefined' || !navigator.clipboard || !navigator.clipboard.readText) return null;
  return h('button', {
    type: 'button', class: 'btn-sm', title: t('paste'),
    onClick: async () => { try { const txt = await navigator.clipboard.readText(); if (txt) apply(txt.trim()); } catch {} },
    html: '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"/><rect x="8" y="2" width="8" height="4" rx="1" ry="1"/></svg>',
  });
}

// Paste, for a textarea. Beside a one-line input the button belongs in the
// input-group (see Send); above a textarea it floats next to the label as a
// box heavier than the label itself. So put it inside the field — and only
// while the field is empty, which is the only time it's wanted and the only
// time it can't cover what you typed.
function pasteInto(ta, apply) {
  const btn = pasteBtn((text) => { apply(text); sync(); });
  if (!btn) return ta;
  btn.classList.add('paste-in');
  btn.append(h('span', {}, t('paste')));
  const wrap = h('div', { class: 'paste-wrap' }, ta, btn);
  // Toggled on the node rather than through render(): re-rendering a textarea
  // on every keystroke rebuilds it under the caret.
  const sync = () => wrap.classList.toggle('has-text', !!ta.value);
  ta.addEventListener('input', sync);
  sync();
  return wrap;
}

// ---------------------------------------------------------------- display unit
// Global BTC/sats preference, persisted in localStorage across refreshes and
// logouts. Every unit label on the site is clickable to toggle it.
const UNIT_KEY = 'btc-wallet-unit';
let unit = (() => {
  // Default to sats for first-time users; only an explicit choice sticks.
  try {
    const v = localStorage.getItem(UNIT_KEY);
    return v === 'btc' || v === 'fiat' ? v : 'sats';
  } catch {
    return 'sats';
  }
})();

// sats → BTC → your money → sats. Fiat is a display unit like the other two
// rather than a second number beside them: the balance is one figure, and
// which figure is your choice. It's skipped entirely when no price has ever
// been fetched — a third position showing blanks is worse than two that work.
function toggleUnit() {
  const ring = haveRate() ? ['sats', 'btc', 'fiat'] : ['sats', 'btc'];
  unit = ring[(ring.indexOf(unit) + 1) % ring.length];
  try {
    localStorage.setItem(UNIT_KEY, unit);
  } catch {}
  render();
}

// A sats figure as the amount field types it in the current unit — what a
// Max button or a fixed-amount invoice fills in. Fiat is floored to the
// cent so a filled-in maximum never parses back to more than was offered.
// The figure it filled is remembered with its exact sats: a fiat maximum
// rounded to the cent would otherwise parse back a few sats short and leave
// them behind. Typing anything else parses as typed.
let lastFill = null;
function amountField(sat) {
  let s;
  const r = unit === 'fiat' && rateNow();
  if (unit === 'sats') s = String(sat);
  else if (r) s = (Math.floor((sat / 1e8) * r * 100) / 100).toFixed(2);
  else s = (sat / 1e8).toFixed(8);
  lastFill = { s, unit, sat };
  return s;
}
function parseField(v, u = unit) {
  if (lastFill && lastFill.unit === u && String(v).trim() === lastFill.s) return lastFill.sat;
  return parseAmount(v, u, rateNow());
}

const unitLabel = () => (unit === 'sats' ? 'sats' : unit === 'fiat' ? getCurrency() : 'BTC');

// "Worth X then · Y now" for a payment's detail page — the one place both
// numbers earn their keep, because that page is where the question is asked.
// Absent when there's no price, and when the two would say the same thing.
function worthLine(sats, at, row = null) {
  const then = rateAt(at);
  const now = rateNow();
  if (!now || !at) return null;
  const line = row || ((k, v) => h('div', { class: 'line' }, h('span', { class: 'k' }, k), h('span', { class: 'v' }, v)));
  // A payment we have a price for is shown at that price; one we don't is
  // shown at today's, without ceremony. (The '~' that used to mark the
  // difference was more bookkeeping than the beta warrants.)
  const thenStr = then.rate && !then.stale ? fmtFiat(sats, then.rate) : null;
  const nowStr = fmtFiat(sats, now);
  if (!thenStr) return line(t('worthNow'), nowStr);
  return line(t('worthThen'), thenStr + (thenStr === nowStr ? '' : ' · ' + t('worthNowInline', { v: nowStr })));
}
// `at` is when the money moved. In fiat it picks the price recorded at that
// moment, so a payment is shown for what it was worth then — the number the
// rest of the world remembers it by. Without it (a balance, a form) the live
// price is used. A '~' means we had no sample near that time and had to price
// it at today's, which is a different claim and shouldn't look like the same
// one.
const fmtAmount = (sats, at) => {
  if (unit === 'sats') return fmtSats(sats);
  if (unit === 'btc') return fmtBtc(sats);
  const { rate } = rateAt(at);
  if (!rate) return fmtSats(sats);
  // bare, like the other two units: whatever labels this number — the unit
  // tag beside a balance, the toggle everywhere else — says which money it is
  return fmtFiatBare(sats, rate);
};

// A clickable unit label. cls lets callers inherit surrounding sizing.
function unitTag(cls = '') {
  return h('button', { type: 'button', class: 'unit-tag ' + cls, title: t('switchUnit'), onClick: toggleUnit }, unitLabel());
}

// ================================================================ UNLOCK
// The create/import card on its own — the unlock screen wraps it in the
// classic chrome, the onboarding wizard's "Get started" step shows it bare.
function unlockCard() {
  // The entropy page takes the card over entirely — seed words, tabs and
  // other controls step aside until Submit or Back.
  if (ui.entropyPage) return h('div', { class: 'card col' }, entropyPage());
  // Inside the first-run wizard the words are already on screen: no tabs,
  // just a line underneath for whoever brought their own seed (and one back).
  const wizard = ui.screen === 'unlock' && ui.onb && ui.onb.step === 'seed';
  const swap = wizard ? h('button', {
    class: 'linklike small', style: 'align-self:center',
    onClick: () => {
      clearSeedDrafts(); ui.unlockError = '';
      if (ui.unlockTab === 'create') ui.unlockTab = 'import';
      else { ui.unlockTab = 'create'; ui.createStep = 'gen'; ui.draftRandom = ui.draftMnemonic = newMnemonic(); }
      render();
    },
  }, ui.unlockTab === 'create' ? t('onbHaveSeed') : t('onbCreateInstead')) : null;
  return h(
    'div',
    { class: 'card col' },
    wizard ? null : h(
      'div',
      { class: 'tabs' },
      tabBtn(t('createNew'), ui.unlockTab === 'create', () => { clearSeedDrafts(); ui.unlockTab = 'create'; ui.unlockError = ''; render(); }),
      tabBtn(t('importExisting'), ui.unlockTab === 'import', () => { clearSeedDrafts(); ui.unlockTab = 'import'; ui.unlockError = ''; render(); })
    ),
    ui.unlockTab === 'create' ? createPane() : importPane(),
    ui.unlockError && h('div', { class: 'notice err' }, ui.unlockError),
    swap
  );
}

function unlockScreen() {
  return h(
    'div',
    { class: 'col', style: 'gap:16px' },
    brandHeader(false),
    unlockCard(),
    featureHook('unlockExtra'),
    ui.fromWallet && accounts.length && !ui.entropyPage
      ? h('button', { class: 'btn-ghost btn-block', onClick: () => { ui.fromWallet = false; ui.screen = 'wallet'; ui.unlockError = ''; render(); } }, t('back'))
      : null
  );
}

// ================================================================ HOW IT WORKS
function howItWorksScreen() {
  const back = () => {
    ui.screen = ui.returnScreen === 'wallet' ? 'wallet' : 'unlock';
    render();
  };
  const para = (key) => h('p', { class: 'muted', style: 'margin:0' }, ...linkify(t(key)));
  return h(
    'div',
    { class: 'col', style: 'gap:16px' },
    brandHeader(false),
    h(
      'div',
      { class: 'card col', style: 'gap:14px' },
      h('h3', {}, t('hiwBasicsTitle')),
      para('hiwBasics1'),
      para('hiwBasics2'),
      para('hiwBasics3')
    ),
    h('div', { class: 'card col', style: 'gap:14px' },
      h('h3', {}, '⚡ ' + t('hiwLnTitle')),
      para('hiwLn1')),
    h('div', { class: 'card col', style: 'gap:14px' },
      h('h3', {}, '🎁 ' + t('hiwGiftsTitle')),
      para('hiwGifts1')),
    // The standalone file: the whole app inlined into one HTML — the
    // save-and-open-offline story the split build gave up. Only offered when
    // there's a server to download it from (on file:// you already have it).
    location.protocol.startsWith('http')
      ? h('div', { class: 'card col', style: 'gap:14px' },
          h('h3', {}, '💾 ' + t('hiwStandaloneTitle')),
          para('hiwStandalone1'),
          h('a', { href: '/standalone.html', download: 'coinos.html' }, t('hiwStandaloneLink')))
      : null,
    h('button', { class: 'btn-block', onClick: back }, t('back'))
  );
}

// Turn known tokens (e.g. mempool.space) into links within a plain string,
// returning an array of text + anchor nodes. Keeps i18n strings link-free.
const HIW_LINKS = [
  ['mempool.space', 'https://mempool.space'],
];
function linkify(text) {
  const esc = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  const re = new RegExp('(' + HIW_LINKS.map(([tok]) => esc(tok)).join('|') + ')', 'g');
  const out = [];
  let last = 0;
  let m;
  while ((m = re.exec(text))) {
    if (m.index > last) out.push(text.slice(last, m.index));
    const href = HIW_LINKS.find(([tok]) => tok === m[0])[1];
    out.push(h('a', { href, target: '_blank', rel: 'noopener' }, m[0]));
    last = m.index + m[0].length;
  }
  if (last < text.length) out.push(text.slice(last));
  return out;
}

function tabBtn(label, active, onClick) {
  // Act on POINTERDOWN, not click: on a phone the click event lands
  // 100–250ms after the finger does, and a tab switch has no scroll or
  // long-press ambiguity to wait out — native segmented controls switch on
  // touch-down for exactly this reason. The click handler stays for
  // keyboard/AT activation; re-selecting the current tab is a no-op, so the
  // pair firing together costs nothing.
  //
  // And feedback comes FIRST: the full re-render can take 100ms+ on a
  // phone, and running it synchronously meant even the button's own active
  // state waited for the whole pane to build. Flip the strip's classes with
  // a direct DOM write (paints this frame), then run the real render after
  // that paint — double-rAF is the "after the next paint" idiom.
  // The down-timestamp lives ON THE NODE, not in this closure: the
  // pointerdown's own render replaces these handlers (fresh closure, zero
  // timestamp) before the browser delivers the paired click, and with tabs
  // that TOGGLE, letting that click through un-did the tap it belonged to.
  const select = (btn) => {
    if (btn && btn.parentElement) {
      for (const b of btn.parentElement.children) b.classList.toggle('active', b === btn);
    }
    requestAnimationFrame(() => requestAnimationFrame(onClick));
  };
  return h('button', {
    class: active ? 'active' : '',
    onPointerdown: (e) => {
      if (e.button !== 0) return;
      e.currentTarget._downAt = performance.now();
      select(e.currentTarget);
    },
    onClick: (e) => { if (performance.now() - (e.currentTarget._downAt || 0) > 500) select(e.currentTarget); },
  }, label);
}

function createPane() {
  if (ui.createStep === 'gen') {
    // The wizard shows words, never a Generate button: a refresh restores
    // the step but not the draft (drafts live in memory only), so draw a
    // fresh set right here. Nothing was made from the old words.
    if (!ui.draftMnemonic && ui.onb && ui.onb.step === 'seed') ui.draftRandom = ui.draftMnemonic = newMnemonic();
    if (!ui.draftMnemonic) {
      return h(
        'div',
        { class: 'col' },
        h('p', { class: 'muted' }, t('genIntro')),
        h(
          'button',
          {
            class: 'btn-primary btn-block',
            onClick: () => {
              ui.draftRandom = ui.draftMnemonic = newMnemonic();
              render();
            },
          },
          t('generateSeed')
        )
      );
    }
    const words = ui.draftMnemonic.split(' ');
    return h(
      'div',
      { class: 'col' },
      h('div', { class: 'warn-box' }, t('writeDownWarn')),
      h(
        'div',
        { class: 'words', style: '--rows-3:' + Math.ceil(words.length / 3) + ';--rows-2:' + Math.ceil(words.length / 2) },
        words.map((w, i) =>
          h('div', { class: 'w' }, h('span', { class: 'n' }, i + 1), h('span', { class: 't' }, w))
        )
      ),
      h('button', { class: 'btn-block', style: 'display:flex;align-items:center;justify-content:center;gap:8px', onClick: () => copy(ui.draftMnemonic) },
        h('span', { style: 'display:flex', html: '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect width="14" height="14" x="8" y="8" rx="2" ry="2"/><path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"/></svg>' }),
        t('copy')),
      optionsPanel(),
      h(
        'button',
        {
          class: 'btn-primary btn-block',
          onClick: () => {
            // catch a mistyped passphrase here, while the field to fix it is
            // still on screen — the verify step only samples the words
            if (ui.passphrase && ui.confirmPass !== ui.passphrase) {
              ui.unlockError = t('passphraseMismatch'); render(); return;
            }
            ui.confirm = pickConfirm(words);
            ui.unlockError = '';
            ui.createStep = 'confirm';
            render();
          },
        },
        t('verifyBackup')
      ),
      h(
        'button',
        { class: 'btn-block', onClick: () => openWallet(ui.draftMnemonic, { generated: true }) },
        t('skipVerification')
      )
    );
  }

  // confirm step (optional — reachable via "Verify backup")
  return h(
    'div',
    { class: 'col' },
    h('p', { class: 'muted' }, t('confirmBackupIntro')),
    ...ui.confirm.map((c, i) =>
      h(
        'label',
        { class: 'field' },
        h('span', { class: 'lab' }, t('wordN', { n: c.index + 1 })),
        h('input', {
          type: 'text',
          class: 'mono-input',
          autocapitalize: 'none',
          autocomplete: 'off',
          spellcheck: 'false',
          value: c.value,
          onInput: (e) => (ui.confirm[i].value = e.target.value.trim()),
        })
      )
    ),
    h('div', { class: 'row gap6' },
      h('button', { class: 'btn-ghost', onClick: () => { ui.createStep = 'gen'; render(); } }, t('back')),
      h('button', {
        class: 'btn-primary grow',
        onClick: () => {
          const words = ui.draftMnemonic.split(' ');
          const ok = ui.confirm.every((c) => c.value.toLowerCase() === words[c.index]);
          if (!ok) { ui.unlockError = t('wordsMismatch'); render(); return; }
          openWallet(ui.draftMnemonic, { generated: true });
        },
      }, t('openWallet'))
    ),
    h('button', { class: 'btn-block', onClick: () => openWallet(ui.draftMnemonic, { generated: true }) }, t('skipVerification'))
  );
}

function pickConfirm(words) {
  const idx = new Set();
  while (idx.size < 3) idx.add(Math.floor(Math.random() * words.length));
  return [...idx].sort((a, b) => a - b).map((index) => ({ index, value: '' }));
}

// The BYO-entropy page, shared by Create (re-derives the draft phrase) and
// Import (fills the phrase field): the typed text alone determines the seed,
// so the same text recreates the same wallet anywhere. Nothing derives while
// typing — Submit does it once, then hands back the phrase view.
function entropyPage() {
  const forCreate = ui.entropyPage === 'create';
  return h(
    'div',
    { class: 'col', style: 'gap:10px' },
    h('h3', { style: 'margin:0' }, t('entropyToggle')),
    h('p', { class: 'small muted', style: 'margin:0' }, t('entropyHint')),
    h('div', { class: 'warn-box small' }, t('entropyWarn')),
    h('textarea', {
      rows: '3', style: 'font-family:var(--sans)', placeholder: t('entropyPlaceholder'),
      autocapitalize: 'none', autocomplete: 'off', spellcheck: 'false',
      value: ui.entropyEntry || '',
      onInput: (e) => (ui.entropyEntry = e.target.value),
    }),
    h(
      'div',
      { class: 'row gap6' },
      h('button', { class: 'btn-ghost grow', onClick: () => { ui.entropyPage = null; ui.entropyEntry = ''; render(); } }, t('back')),
      h('button', { class: 'btn-primary grow', onClick: () => {
        const txt = (ui.entropyEntry || '').trim();
        if (forCreate) {
          ui.ownEntropy = txt;
          ui.draftMnemonic = txt ? newMnemonic(128, txt) : (ui.draftRandom || ui.draftMnemonic || newMnemonic());
        } else {
          ui.importEntropy = txt;
          // fills the phrase field with its derived words; clearing the text
          // clears only what it filled — a pasted phrase is left alone
          if (txt) ui.importText = ui._entropyFilled = newMnemonic(128, txt);
          else if (ui.importText === ui._entropyFilled) ui.importText = '';
        }
        ui.entropyPage = null;
        ui.entropyEntry = '';
        render();
      } }, t('entropySubmit'))
    )
  );
}

// A seed phrase or entropy typed into the start screens is secret material,
// not a draft: nothing typed there survives leaving the field — switching
// tabs, backing out of the entropy page, going home. Whatever you come back
// to is empty. (An opened wallet clears these too, in openWallet/lock.)
function clearSeedDrafts() {
  ui.importText = ''; ui._entropyFilled = null;
  ui.entropyEntry = ''; ui.ownEntropy = ''; ui.importEntropy = '';
}

function importPane() {
  const ta = h('textarea', {
    placeholder: t('importPlaceholder'),
    autocapitalize: 'none',
    autocomplete: 'off',
    spellcheck: 'false',
    value: ui.importText,
    onInput: (e) => (ui.importText = e.target.value),
  });
  return h(
    'div',
    { class: 'col' },
    h(
      'label',
      { class: 'field' },
      h('span', { class: 'lab' }, t('importLabel')),
      pasteInto(ta, (text) => { ta.value = text; ui.importText = text; })
    ),
    // A wallet born from typed entropy comes back the same way: the entropy
    // page fills the phrase field with its derived words, visibly.
    h(
      'button',
      {
        class: 'btn-ghost btn-sm', style: 'align-self:flex-start',
        onClick: () => { ui.entropyPage = 'import'; ui.entropyEntry = ''; render(); },
      },
      t('entropyToggle')
    ),
    optionsPanel(),
    h('button', { class: 'btn-primary btn-block', onClick: () => openWallet(ui.importText) }, t('openWallet'))
  );
}

function optionsPanel() {
  const pass = h(
    'label',
    { class: 'field' },
    h('span', { class: 'lab' },
      t('passphrase'),
      // People assume a password logs in or encrypts; a BIP39 passphrase does
      // neither, and getting that wrong loses money — worth a sentence here.
      h('button', {
        class: 'linklike small', type: 'button', style: 'margin-left:8px',
        onClick: (e) => { e.preventDefault(); ui.passInfoOpen = !ui.passInfoOpen; render(); },
      }, t('passWhatsThis'))),
    ui.passInfoOpen ? h('p', { class: 'small muted', style: 'margin:0 0 6px' }, t('passInfo')) : null,
    h(
      'div',
      { class: 'input-group' },
      h('input', {
        type: ui.showPass ? 'text' : 'password',
        class: 'mono-input',
        autocomplete: 'off',
        value: ui.passphrase,
        // rendering mid-keystroke is safe (focus + caret are preserved), but
        // only the empty↔non-empty flip changes what's on screen (the confirm
        // field below), so only that flip pays for a rebuild
        onInput: (e) => { const had = !!ui.passphrase; ui.passphrase = e.target.value; if (had !== !!ui.passphrase) render(); },
      }),
      h('button', { class: 'btn-sm', type: 'button', onClick: () => { ui.showPass = !ui.showPass; render(); } }, ui.showPass ? t('hide') : t('show'))
    )
  );
  // A typo here IS a different wallet, silently — so once a passphrase is
  // typed, it's typed twice. (Not needed when it's empty, which is most people.)
  const confirm = ui.passphrase
    ? h(
        'label',
        { class: 'field' },
        h('span', { class: 'lab' }, t('reenterPassphrase')),
        h('input', {
          type: ui.showPass ? 'text' : 'password',
          class: 'mono-input',
          autocomplete: 'off',
          value: ui.confirmPass,
          onInput: (e) => (ui.confirmPass = e.target.value),
        })
      )
    : null;
  return [pass, confirm];
}

// Import accepts a recovery phrase, an xpub/zpub (watch-only), or an xprv/zprv
// (full spending). Classify the pasted text and open the right kind of wallet.
async function openWallet(input, opts = {}) {
  ui.unlockError = '';
  const raw = (input || '').trim();
  const m = raw.replace(/\s+/g, ' ');
  if (isValidMnemonic(m)) {
    // last line of defense — the panes with the confirm field on screen also
    // check before handing off, so this error always lands somewhere fixable
    if (ui.passphrase && ui.confirmPass !== ui.passphrase) { ui.unlockError = t('passphraseMismatch'); render(); return; }
    await enterWallet(m, ui.passphrase, { generated: opts.generated });
    ui.draftMnemonic = ''; // discard the used draft so the next "Add wallet" generates a fresh seed
    return;
  }
  let pk;
  try { pk = parseExtendedKey(raw); } catch { ui.unlockError = t('invalidImport'); render(); return; }
  const acc = pk.kind === 'xpub'
    ? addOrGetAccount({ type: 'watch', label: defaultLabel('watch'), xpub: pk.key })
    : addOrGetAccount({ type: 'full', label: defaultLabel('full'), xprv: pk.key });
  ui.fromWallet = false;
  await activateAccount(acc, { fresh: true });
}

// Register a full (seed) wallet as an account and open it.
async function enterWallet(mnemonic, passphrase, opts = {}) {
  // A wallet opening is a new set of numbers: the count-up animation must
  // not run from the previous account's balance (a fresh wallet used to
  // count DOWN from the old one to zero).
  _amtLast.clear();
  const acc = addOrGetAccount({
    type: 'full',
    label: defaultLabel('full'),
    mnemonic: (mnemonic || '').trim().replace(/\s+/g, ' '),
    passphrase: passphrase || '',
  });
  // Has this person ever had the recovery phrase in front of them? Creating
  // a wallet shows it; importing one means they typed it. A sign-in DERIVES
  // it — Google, a passkey and a nostr key all end up at a seed the user has
  // never seen, and which nobody can reissue for them. That is the one case
  // worth asking about, so it's recorded once and never guessed at again.
  if (acc.seedSeen === undefined) acc.seedSeen = !opts.nostrPubkey;
  await activateAccount(acc, { ...opts, fresh: true });
}

// Load an account into the wallet and start scanning. Full-account seeds are
// kept in sessionStorage (ephemeral); a refresh restores the open account.
async function activateAccount(acc, opts = {}) {
  // Tear down the previous account's feature runtime BEFORE the wallet
  // switches identity: live relay subscriptions and in-memory state (chat
  // threads, decrypted DMs) belong to the old keys, and surviving into this
  // account they'd both leak the old account's messages on screen and block
  // the new account's own subscriptions from ever starting.
  _featuresInited = false;
  for (const f of FEATURES) { try { f.stop && f.stop(); } catch {} }
  activeId = acc.id;
  rememberActive(acc.id);
  // A gift link generates this wallet only to claim into. Keep it provisional
  // until the user commits (claims, or chooses to keep it / enters the wallet),
  // so bailing from an already-claimed gift doesn't leave an empty account.
  if (opts.gift && !opts.existingClaim) acc.provisional = true;
  // The network is a per-wallet property: activating a wallet activates its
  // network. Accounts created before this carried none — they adopt the
  // current global choice once, then keep it. The global setting remains the
  // default for the NEXT new wallet.
  if (!acc.network) acc.network = getNetwork();
  // The relay backup said this wallet has a Spending side: latch it BEFORE
  // the first paint, so a restored wallet doesn't open as savings-only and
  // reflow when the name lookup proves Spending a beat later.
  if (opts.spendingHint && !acc.spendingSetup) { acc.spendingSetup = Date.now(); }
  const netName = acc.network;
  const stillActive = () => activeAccount() === acc && getNetwork() === netName;
  if (netName !== getNetwork()) {
    setNetwork(netName);
    for (const f of FEATURES) { try { f.networkChanged && f.networkChanged(netName); } catch {} }
  }
  if (acc.type === 'watch') wallet.load({ xpub: acc.xpub, netName, offline: false });
  else if (acc.xprv) wallet.load({ xprv: acc.xprv, netName, offline: false });
  else wallet.load({ mnemonic: acc.mnemonic, passphrase: acc.passphrase || '', netName, offline: false, spFresh: !!opts.generated, accountIndex: acc.deriveIndex || 0 });
  // Record the account-level xpub so this wallet survives a session wipe as a
  // watch-only entry (see the durable account directory) — you keep seeing your
  // balance/history and re-enter the seed to spend again.
  if (acc.type !== 'watch' && !acc.provisional) acc.xpub = wallet.accountXpub();
  // an account rebuilt by a silent sign-in starts with the phrase "unseen";
  // the directory remembers if it was seen on this device before
  if (acc.xpub && !acc.seedSeen) {
    try {
      const dir = JSON.parse(localStorage.getItem(WATCH_KEY) || '[]');
      if (dir.some((e) => e.xpub === acc.xpub && e.seedSeen)) acc.seedSeen = true;
    } catch {}
  }
  persistAccounts();
  autoSave(acc);
  // A name fetched during sign-in seeds the names state BEFORE features init
  // and the first paint — the Receive pane opens showing its QR.
  if (opts.nameHint) { try { featureHook('namesSeed', opts.nameHint); } catch {} }
  for (const f of FEATURES) { try { f.init && f.init(); } catch {} } // per-feature wallet lifecycle
  _featuresInited = true; // a deferred feature landing after this point gets its init() on arrival
  // A freshly generated identity provably has no profile yet — let features
  // skip the "is there a kind-0?" wait (avatar would sit blank meanwhile).
  if (opts.generated) featureHook('identityGenerated');
  const hadCache = wallet.restoreCache(); // show last-known balance/history instantly
  // An opened gift link starts on a claim/back-up screen instead of the wallet.
  ui.screen = opts.gift ? 'claim' : 'wallet';
  ui.claimStep = 'welcome';
  ui.claimCode = opts.gift || null;
  ui.claimError = '';
  ui.claimTaken = null;
  ui.claimNotVisible = false;
  ui.claimChecking = !!opts.gift; // gate the Claim button until we've checked
  // Restore the tab / open tx from the last session so a refresh keeps the
  // user's place. A gift link always opens the claim screen instead.
  const nav = (() => { try { return JSON.parse(sessionStorage.getItem(NAV_KEY) || 'null'); } catch { return null; } })();
  // With no place to return to, a wallet that was just opened — a sign-in,
  // an unlock, a switch to another account — lands on Receive: its deposit
  // address and QR up at once. Reopening the same wallet mid-flow (a seed
  // loaded into a watch-only one) keeps History.
  const keep = nav && (opts.restoreNav || !opts.fresh); // a sign-in starts fresh, a refresh resumes
  ui.tab = (!opts.gift && keep && nav.tab) || (opts.fresh ? 'receive' : 'history');
  ui.txDetail = (!opts.gift && keep && nav.txDetail) || null;
  // Not baselined yet — stays null until the scan + ack logic below sets it,
  // so the celebration never fires for payments that were already there at
  // import (the index only looks "advanced" because the scan hadn't run yet).
  ui.receiveSeenIndex = null;
  ui.arkRecvAddr = null; // the ark receive address belongs to one wallet+network
  ui.send = blankSend();
  ui.draft = null;
  ui.sendResult = null;
  ui.giftMode = false;
  ui.offlineFallback = false;
  // Restore the target page before the wallet's first paint. Painting home
  // first and then replacing it with a thread made refresh visibly flash.
  if (opts.restoreNav) restoreNavFromHistory(false);
  render();
  if (ui.txDetail) openTx(ui.txDetail); // restored a tx detail — fill in fee/details if missing

  // No manual offline switch: try to scan, and if the network is unreachable,
  // fall back to offline mode automatically.
  if (typeof navigator !== 'undefined' && navigator.onLine === false) {
    enterOfflineFallback();
    return;
  }
  try {
    // Celebration baseline. Opening/importing/switching a wallet (opts.fresh)
    // baselines to the current frontier, so payments already received before
    // opening never trigger the "payment received" screen. On a same-session
    // refresh we restore the persisted ack — which is advanced the moment the
    // celebration is shown, so a payment celebrates once and never reappears.
    let ack;
    if (opts.fresh) {
      ack = wallet.nextReceiveIndex;
      wallet.setReceiveAck(ack);
    } else {
      ack = wallet.getReceiveAck();
      if (ack == null) {
        ack = wallet.nextReceiveIndex;
        wallet.setReceiveAck(ack);
      }
    }
    // For a fresh open, leave receiveSeenIndex null until the post-scan baseline
    // below. Setting it now (to the pre-scan frontier) lets the socket's reconcile
    // credit a deposit that predates this open and briefly flash the "payment
    // received" screen before the baseline catches up. A same-session refresh
    // uses the persisted ack right away.
    if (!opts.fresh) ui.receiveSeenIndex = ack;

    // Go Live immediately: the socket must not wait on Nostr (up to 6s) or any
    // discovery scan. The cache/Nostr state is already on screen.
    wallet.startRealtime();

    // Opened a gift link? Let the gifts feature verify its funding coin is
    // still unspent before the claim proceeds.
    if (opts.gift) featureHook('giftOpened', opts.gift);

    // Cross-device state in the background. State comes from the local cache or
    // Nostr — both restore the full balance, coins, and history — so a full API
    // scan runs ONLY when we have neither (e.g. a seed imported on a fresh device
    // with no synced state); that's what discovers the used addresses. Otherwise
    // the socket + frontier poll keep us current with no refresh-time burst.
    const hadNostr = wallet.watchOnly || !wallet.syncFromNostr ? false : await wallet.syncFromNostr();
    if (!stillActive()) return;
    if (!hadCache && !hadNostr) {
      await wallet.scan({ silent: false });
    }
    if (!stillActive()) return;
    // Re-baseline a fresh open against the final frontier (Nostr or the discovery
    // scan may have advanced it) so payments that predate the open don't celebrate.
    if (opts.fresh) { ack = wallet.nextReceiveIndex; wallet.setReceiveAck(ack); ui.receiveSeenIndex = ack; }
    wallet.retrack(); // re-subscribe to the latest frontier (Nostr/scan may have moved it)
  } catch {
    // A scan can finish after logout or an account switch. Its failure must
    // not put the new session (or an empty wallet) into offline mode.
    if (stillActive()) enterOfflineFallback();
  }
}

// --- accounts -------------------------------------------------------------

// Open the unlock screen in ADDITIVE mode: the sign-in doors (Nostr signer,
// passkey, Google, pasted key/phrase) add the identity alongside the current
// accounts instead of replacing them, and Back returns to the wallet. Shared
// by the Accounts screen and the profile page.
function signInAnother() {
  clearSeedDrafts();
  ui.fromWallet = true; ui.unlockError = ''; ui.screen = 'unlock';
  // Starts on Create new (its Generate button), not the seed-import box.
  ui.unlockTab = 'create'; ui.createStep = 'gen'; ui.draftMnemonic = ''; ui.confirm = [];
  ui.profilePk = null; ui.profEdit = null; ui.profEditFilled = false; ui.chatOpen = false;
  render();
}

// The nostr login persisted against an account's OWN wallet state. Feature
// state lives in localStorage keyed by the seed, so this answers "who is that
// account?" for every account on the device, not just the open one — no
// stamping, nothing to go stale.
function loginPkOf(a) {
  try {
    const base = a.type === 'watch' ? a.xpub : a.xprv || (a.mnemonic ? `${a.mnemonic}\n${a.passphrase || ''}` : null);
    if (!base) return null;
    const key = cacheKeyFor(a.deriveIndex ? `${base}\n#${a.deriveIndex}` : base);
    return (JSON.parse(localStorage.getItem(key + ':nostrlogin') || 'null') || {}).pubkey || null;
  } catch { return null; }
}

// Whose wallet this is: the nostr login it carries, else the key its seed
// derives, else whatever was last stamped on the record. The accounts screen
// and the identity switcher have to agree on this or they describe different
// worlds.
function identityPkOf(a) {
  if (!a) return null;
  let dir = [];
  try { dir = JSON.parse(localStorage.getItem(WATCH_KEY) || '[]'); } catch {}
  const stamped = (a.xpub && (dir.find((d) => d.xpub === a.xpub) || {}).nostrPk) || null;
  return loginPkOf(a)
    || (a.mnemonic ? seedPubkey(a.mnemonic, a.passphrase || '', a.deriveIndex || 0) : null)
    || a.nostrPk || stamped;
}

// The identities on this device — one per seed (a seed's Spending and
// Savings faces are the same person), each with the nostr key its header
// avatar wears: the nostr login when there is one, else the seed's own key.
// Both are read from the account itself; the key remembered on the record
// (saveDirectory) and in the durable directory by xpub is only the fallback,
// for a watch-only entry whose seed isn't here to ask.
// One key per person: a seed's Spending and Savings accounts share it.
const seedKeyOf = (a) => a.type === 'watch' ? 'w:' + a.xpub
  : a.mnemonic ? 'm:' + a.mnemonic + '\n' + (a.passphrase || '') + '\n' + (a.deriveIndex || 0)
    : 'x:' + (a.xprv || a.xpub || a.id);

function identities() {
  const pkOf = identityPkOf;
  const bySeed = new Map();
  for (const a of accounts) {
    if (a.provisional) continue;
    const key = seedKeyOf(a);
    const active = a.id === activeId;
    const pk = pkOf(a);
    const cur = bySeed.get(key);
    if (!cur) bySeed.set(key, { id: a.id, pk, active, label: seedName(a), network: a.network, watch: a.type === 'watch' });
    else {
      if (active) { cur.id = a.id; cur.active = true; }
      if (!cur.pk && pk) cur.pk = pk;
    }
  }
  const out = [...bySeed.values()];
  const me = out.find((x) => x.active);
  if (me) me.pk = ctx.shownPubkey() || me.pk;
  return out;
}

// Page-level navigation owned by the features (a profile, a chat thread, a
// search, the zap setup) — dropped whenever the session underneath it
// changes, so the next paint is the app's own screen and not the page the
// previous identity (or the unlocked wallet) was reading.
function clearFeatureNav() {
  ui.arkCoinsPage = null; ui.arkExitPage = null;
  ui.profilePk = null; ui.profEdit = null; ui.profEditFilled = false;
  ui.chatOpen = false; ui.userSearch = null; ui.noteThread = null; ui.zapSetup = null;
}

// Sign out of the CURRENT identity only. "Log out" locks every account on
// the device, which is the wrong size when two people (or two of your own
// keys) are signed in and just one should leave. This removes that
// identity's accounts — session, directory, cache, vault — and leaves the
// others exactly as they were, landing on the next one. A nostr login can
// sign straight back in (its seed lives on the relays, encrypted to its
// key); a bare seed wallet needs its recovery phrase, and the confirmation
// says which.
function signOutIdentity() {
  const me = activeAccount();
  if (!me) return;
  const key = seedKeyOf(me);
  const mine = accounts.filter((a) => seedKeyOf(a) === key).map((a) => a.id);
  clearFeatureNav();
  // the active one last: wiping it is what hands off to the next identity
  for (const id of mine.filter((id) => id !== me.id)) wipeAccount(id);
  wipeAccount(me.id);
  if (!activeAccount()) { ui.screen = 'unlock'; ui.unlockTab = 'create'; ui.onb = { step: 'welcome' }; }
  render();
}
// Whether the current identity can come back without a recovery phrase:
// a nostr login (extension, bunker, passkey, Google) re-derives its wallet.
const identityRecoverable = () => !!loginPkOf(activeAccount() || {});

// Switch to another identity already signed in on this device: the wallet
// it opens lands on its own history, out of any profile or chat the previous
// identity had open.
function switchIdentity(id) {
  const acc = accounts.find((a) => a.id === id);
  if (!acc) return;
  clearFeatureNav();
  switchToView(acc.id, viewsOf(acc)[0]);
}
// The working set of wallets you can switch between. Full (seed-bearing)
// accounts live only in sessionStorage — ephemeral, wiped when the browser
// closes (no seed on disk by default). Watch-only accounts hold just an xpub,
// so they're additionally persisted in localStorage and reload across restarts.
const ACCOUNTS_KEY = 'btc-wallet-accounts'; // sessionStorage: session list + active
const WATCH_KEY = 'btc-wallet-watch'; // localStorage: persisted watch-only accounts

let accounts = [];
let activeId = null;

const genId = () => 'a' + Date.now().toString(36) + Math.random().toString(36).slice(2, 7);
const credId = (a) => (a.type === 'watch' ? 'w:' + a.xpub : a.xprv ? 'x:' + a.xprv : 'f:' + a.mnemonic + '|' + (a.passphrase || '') + (a.deriveIndex ? '|#' + a.deriveIndex : ''));
const activeAccount = () => accounts.find((a) => a.id === activeId) || null;
// The wallet you last used, remembered durably (localStorage): a fresh window
// or tab — a link clicked from outside, a cold start — starts with no session
// and would otherwise always reopen the FIRST wallet in the directory, not
// the one you switched to elsewhere. Directory ids are stable across sessions.
const LAST_ACTIVE_KEY = 'btc-wallet-last-active';
function rememberActive(id) { try { localStorage.setItem(LAST_ACTIVE_KEY, id); } catch {} }
function preferredAccount() {
  let id = null;
  try { id = localStorage.getItem(LAST_ACTIVE_KEY); } catch {}
  return accounts.find((a) => a.id === id) || accounts[0] || null;
}

function defaultLabel(type) {
  const n = accounts.filter((a) => a.type === type).length + 1;
  return t(type === 'watch' ? 'watchLabelN' : 'walletLabelN', { n });
}

// The durable account directory (localStorage): a view-only mirror of every
// account — id, label, and account xpub, never a seed. So a wallet survives a
// session wipe (browser closed without "Save to device") as a watch-only entry:
// you keep seeing balance/history and re-enter the seed to spend again.
function loadWatchAccounts() {
  try {
    const dir = JSON.parse(localStorage.getItem(WATCH_KEY) || '[]');
    return dir.filter((d) => d.xpub).map((d) => ({ id: d.id, label: d.label, type: 'watch', xpub: d.xpub, autoLock: d.autoLock || 0, network: d.network, nostrPk: d.nostrPk }));
  } catch { return []; }
}
function saveDirectory() {
  try {
    // Remember each wallet's nostr identity alongside its xpub: a watch-only
    // reopening still shows WHO this wallet is (avatar, npub, profile) even
    // though nothing can be signed until the keys are back.
    const dir = accounts.filter((a) => a.xpub && !a.provisional).map((a) => {
      if (a.id === activeId && !wallet.watchOnly) {
        // remember the identity the header actually SHOWS — a nostr login
        // outranks the seed-derived key, locked or not
        try {
          a.nostrPk = (featureHook('nostrLoginIdentity') || {}).pubkey
            || (wallet.nostrPubkey && wallet.nostrPubkey()) || a.nostrPk;
        } catch {}
      }
      return { id: a.id, label: a.label, xpub: a.xpub, autoLock: a.autoLock || 0, network: a.network, nostrPk: a.nostrPk, seedSeen: !!a.seedSeen };
    });
    localStorage.setItem(WATCH_KEY, JSON.stringify(dir));
  } catch {}
}
function persistAccounts() {
  try { sessionStorage.setItem(ACCOUNTS_KEY, JSON.stringify({ accounts, activeId })); } catch {}
  saveDirectory();
}
function clearAccounts() {
  accounts = [];
  activeId = null;
  try { sessionStorage.removeItem(ACCOUNTS_KEY); } catch {}
}

// Add an account (deduped by credential), returning the stored object.
function addOrGetAccount(partial) {
  const cid = credId(partial);
  let acc = accounts.find((a) => credId(a) === cid);
  if (!acc) {
    // every new wallet is born on the currently-selected network
    acc = { id: genId(), network: getNetwork(), ...partial };
    // the Add-wallet chooser fixed this wallet's purpose before the seed flow
    if (ui.newWalletKind) { acc.kind = ui.newWalletKind; ui.newWalletKind = null; }
    accounts.push(acc);
    persistAccounts();
  }
  return acc;
}

// A wallet on an existing seed: the next unused BIP84 account index under the
// parent's phrase. Its coins, ark state, cache and nostr identity are all its
// own; the parent's seed phrase backs up both.
function createDerivedWallet(parentId, kind) {
  const parent = accounts.find((a) => a.id === parentId);
  if (!parent || !parent.mnemonic) return;
  const siblings = accounts.filter((x) => x.mnemonic === parent.mnemonic && (x.passphrase || '') === (parent.passphrase || ''));
  const next = 1 + Math.max(0, ...siblings.map((x) => x.deriveIndex || 0));
  const acc = {
    id: genId(), type: 'full', network: parent.network || getNetwork(),
    label: `${parent.label} +${next}`,
    viewLabels: { [kind]: `${kind === 'spending' ? t('spendingName') : t('savingsName')} ${next + 1}` },
    mnemonic: parent.mnemonic, passphrase: parent.passphrase || '',
    deriveIndex: next, kind,
  };
  accounts.push(acc);
  persistAccounts();
  if (parent.persisted) { acc.persisted = true; writeVault(); }
  ui.addWallet = null;
  activateAccount(acc, { fresh: true });
}

// Commit the active account — clear the "provisional" gift flag so it's no
// longer discarded on bail. Called once the user claims, keeps, or enters it.
function commitAccount() {
  const a = accounts.find((x) => x.id === activeId);
  if (a && a.provisional) {
    delete a.provisional;
    if (a.type !== 'watch') a.xpub = wallet.accountXpub(); // now eligible for the durable directory
    persistAccounts();
  }
  autoSave(a);
}

function removeAccount(id) {
  const acc = accounts.find((a) => a.id === id);
  if (!acc) return;
  accounts = accounts.filter((a) => a.id !== id);
  persistAccounts();
  if (activeId === id) {
    if (accounts.length) activateAccount(accounts[0], { fresh: true });
    else lock();
  } else {
    render();
  }
}

function switchAccount(id) {
  const acc = accounts.find((a) => a.id === id);
  if (!acc) return;
  activateAccount(acc, { fresh: true });
}

// Restore accounts after a refresh (sessionStorage); on a fresh session, prompt
// to unlock the encrypted vault if there is one, else seed from watch-only
// accounts. Returns true if it handled the entry (opened or showed a prompt).
function restoreAccountsState() {
  let sess = null;
  try { sess = JSON.parse(sessionStorage.getItem(ACCOUNTS_KEY) || 'null'); } catch {}
  // the "Unlock for" deadline outlives refreshes: past it, the password is
  // required again no matter what the session cache still holds
  if (unlockDeadlinePassed()) {
    try { sessionStorage.removeItem(ACCOUNTS_KEY); localStorage.removeItem(UNLOCK_UNTIL_KEY); } catch {}
    sess = null;
  } else {
    armUnlockDeadline();
  }
  if (sess && Array.isArray(sess.accounts) && sess.accounts.length) {
    accounts = sess.accounts;
    const active = accounts.find((a) => a.id === sess.activeId) || accounts[0];
    activateAccount(active, { restoreNav: true });
    return true;
  }
  if (hasVault()) {
    // A blank (optional) vault password unlocks seamlessly with no prompt.
    if (attemptVaultUnlock('')) {
      if (accounts.length) activateAccount(preferredAccount(), { fresh: true, restoreNav: true });
      else { ui.screen = 'unlock'; render(); }
      return true;
    }
    ui.screen = 'vault'; ui.passkeyAsk = true; render(); return true;
  }
  const watch = loadWatchAccounts();
  if (watch.length) {
    accounts = watch.slice();
    activateAccount(preferredAccount(), { fresh: true, restoreNav: true });
    return true;
  }
  return false;
}

// --- encrypted vault (optional password-persisted full accounts) ----------
const VAULT_KEY = 'btc-wallet-vault';
// Whether we've offered a password on locking. Asked once, ever: someone who
// says no has chosen, and a wallet that nags is a wallet people stop reading.
const LOCK_PW_KEY = 'btc-wallet-lockpw';
const lockPwAsked = () => { try { return !!localStorage.getItem(LOCK_PW_KEY); } catch { return true; } };
const markLockPwAsked = () => { try { localStorage.setItem(LOCK_PW_KEY, '1'); } catch {} };
let vaultPassword = null; // in memory once unlocked/set this session; cleared on lock
// Locked with a passkey instead of a password: the vault's password is then
// a secret only that passkey's PRF produces (passkey.js), and the blob names
// the credential to ask for. Held beside vaultPassword while it's in use.
let vaultPasskeyId = null;
const passkeySecret = (pw) => typeof pw === 'string' && pw.startsWith('passkey:');
const vaultPasskey = () => (loadVaultBlob() || {}).passkey || null;
function sealVault(list, password) {
  const b = encryptVault(list, password);
  if (passkeySecret(password) && vaultPasskeyId) b.passkey = vaultPasskeyId;
  return b;
}

function loadVaultBlob() {
  try { return JSON.parse(localStorage.getItem(VAULT_KEY) || 'null'); } catch { return null; }
}
function hasVault() { return !!loadVaultBlob(); }

// Re-encrypt the vault from the currently-persisted full accounts (needs the
// in-memory password). Removes the blob when nothing is persisted.
function writeVault() {
  if (vaultPassword == null) return;
  const list = accounts.filter((a) => a.type === 'full' && a.persisted)
    .map((a) => (a.xprv ? { label: a.label, xprv: a.xprv, network: a.network } : { label: a.label, mnemonic: a.mnemonic, passphrase: a.passphrase || '', network: a.network }));
  try {
    if (!list.length) localStorage.removeItem(VAULT_KEY);
    else localStorage.setItem(VAULT_KEY, JSON.stringify(sealVault(list, vaultPassword)));
  } catch {}
}

// Bring vault-saved seeds into the session. Each upgrades the matching watch-only
// directory entry (by xpub) to a spendable full account so wallets aren't
// duplicated; one with no directory entry is added fresh.
function mergeVaultList(list) {
  for (const v of list) {
    // Derive on the wallet's OWN network: accountXpubFor defaults to mainnet,
    // and a testnet wallet derives under a different coin type, so leaving it
    // to the default produced an xpub that could never match the stored one —
    // every unlock re-added the same wallet as a new entry.
    const net = v.network || getNetwork();
    const xpub = v.xprv ? accountXpubFor({ xprv: v.xprv }, net) : accountXpubFor({ mnemonic: v.mnemonic, passphrase: v.passphrase || '' }, net);
    const existing = accounts.find((a) => a.xpub === xpub);
    if (existing) {
      existing.type = 'full';
      if (v.xprv) { existing.xprv = v.xprv; delete existing.mnemonic; delete existing.passphrase; }
      else { existing.mnemonic = v.mnemonic; existing.passphrase = v.passphrase || ''; delete existing.xprv; }
      if (v.label) existing.label = v.label;
      if (v.network && !existing.network) existing.network = v.network;
      existing.persisted = true;
    } else {
      const acc = addOrGetAccount(
        v.xprv
          ? { type: 'full', label: v.label || defaultLabel('full'), xprv: v.xprv, xpub }
          : { type: 'full', label: v.label || defaultLabel('full'), mnemonic: v.mnemonic, passphrase: v.passphrase || '', xpub }
      );
      if (v.network) acc.network = v.network;
      acc.persisted = true;
    }
  }
}

// Keeping a wallet is the default: a seed that only lives in this tab is one
// refresh away from being gone, and that surprise costs people money. So a
// wallet saves itself to the device unless the vault is locked behind a real
// password — then the manual Save button (and the padlock's save-first ask)
// still covers it. No password is set here; Settings can add one later.
function autoSave(acc) {
  if (!acc || acc.type !== 'full' || acc.persisted || acc.provisional) return;
  if (vaultPassword == null) {
    if (hasVault()) {
      // A blank-password vault opens by itself — treating it as locked left
      // every wallet created after a plain reload silently unsaved. Fold its
      // wallets into the session first: writeVault rebuilds the blob from
      // session accounts, and the saved ones must not fall out of it here.
      let list;
      try { list = decryptVault(loadVaultBlob(), ''); } catch { return; } // a real password: manual
      vaultPassword = '';
      mergeVaultList(list);
    } else {
      vaultPassword = '';
    }
  }
  acc.persisted = true;
  writeVault();
  persistAccounts();
}

// Toggle persistence on a full account. Prompts for the vault password when it
// isn't unlocked this session ('set' the first time, 'enter' if a vault exists).
function startSave(id) {
  const acc = accounts.find((a) => a.id === id);
  if (!acc || acc.type !== 'full') return;
  if (vaultPassword != null) { acc.persisted = true; writeVault(); persistAccounts(); render(); return; }
  ui.pw = { purpose: 'save', accId: id, mode: hasVault() ? 'enter' : 'set', v1: '', v2: '', error: '' };
  render();
}
// --- load a seed into a watch-only account (make it spendable) --------------
function startLoadSeed(opts = {}) {
  // accId lets the per-wallet settings page import a seed for a specific
  // (possibly non-active) watch-only wallet; defaults to the active one.
  ui.loadSeed = { value: '', passphrase: '', save: !!opts.save, error: '', accId: opts.accId || activeId };
  render();
}
function cancelLoadSeed() { ui.loadSeed = null; render(); }
async function doLoadSeed() {
  const ls = ui.loadSeed;
  const acc = (ls && accounts.find((a) => a.id === ls.accId)) || activeAccount();
  if (!ls || !acc || !acc.xpub) return;
  const raw = (ls.value || '').trim().replace(/\s+/g, ' ');
  if (!raw) { ls.error = t('enterSeedToSpend'); render(); return; }
  let next = null;
  try {
    if (isValidMnemonic(raw)) {
      if (accountXpubFor({ mnemonic: raw, passphrase: ls.passphrase || '' }, acc.network || getNetwork()) !== acc.xpub) { ls.error = t('seedMismatch'); render(); return; }
      next = { mnemonic: raw, passphrase: ls.passphrase || '' };
    } else {
      const pk = parseExtendedKey(raw); // throws if not an extended key
      if (pk.kind !== 'xprv') { ls.error = t('seedNeedsPrivate'); render(); return; }
      if (accountXpubFor({ xprv: pk.key }, acc.network || getNetwork()) !== acc.xpub) { ls.error = t('seedMismatch'); render(); return; }
      next = { xprv: pk.key };
    }
  } catch { ls.error = t('seedInvalid'); render(); return; }
  // Upgrade in place — keep id/label/xpub so the cache, directory entry and
  // history all carry over; the account is now spendable.
  acc.type = 'full';
  if (next.mnemonic) { acc.mnemonic = next.mnemonic; acc.passphrase = next.passphrase; delete acc.xprv; }
  else { acc.xprv = next.xprv; delete acc.mnemonic; delete acc.passphrase; }
  const save = ls.save;
  ui.loadSeed = null;
  await activateAccount(acc, { fresh: false });
  if (save) startSave(acc.id); // opens the Save-to-device (vault) flow
  else render();
}

function startForget(id) {
  if (vaultPassword != null) {
    const acc = accounts.find((a) => a.id === id);
    if (acc) acc.persisted = false;
    writeVault(); persistAccounts(); render();
    return;
  }
  ui.pw = { purpose: 'forget', accId: id, mode: 'enter', v1: '', v2: '', error: '' };
  render();
}
function cancelPw() {
  // Declining the lock-time offer is an answer, not a postponement.
  if (ui.pw && ui.pw.purpose === 'lock') markLockPwAsked();
  // Backing out of save-before-lock means "don't lock" — go home, keys intact.
  if (ui.pw && ui.pw.purpose === 'locksave') ui.screen = 'wallet';
  ui.pw = null;
  render();
}
function startChangePw() {
  ui.pw = { purpose: 'change', mode: 'change', v0: '', v1: '', v2: '', error: '' };
  render();
}
function submitPw() {
  const p = ui.pw;
  if (p.purpose === 'change') {
    // Re-encrypt the actual vault (decrypt with the current password, encrypt
    // with the new one) so we never drop wallets that aren't in this session.
    let list;
    try { list = decryptVault(loadVaultBlob(), p.v0 || ''); } catch { p.error = t('pwWrong'); render(); return; }
    if (p.v1 !== p.v2) { p.error = t('pwMismatch'); render(); return; }
    try { localStorage.setItem(VAULT_KEY, JSON.stringify(encryptVault(list, p.v1 || ''))); } catch {}
    if (vaultPassword != null) vaultPassword = p.v1 || ''; // keep the unlocked session in sync
    ui.pw = null;
    render();
    toast(t('pwChanged'));
    return;
  }
  if (p.purpose === 'passkeyOn') {
    let list;
    try { list = decryptVault(loadVaultBlob(), p.v1 || ''); } catch { p.error = t('pwWrong'); render(); return; }
    vaultPassword = p.v1 || '';
    mergeVaultList(list);
    ui.pw = null;
    enablePasskeyLock();
    return;
  }
  if (p.purpose === 'lock') {
    if (!p.v1) { p.error = t('pwNeededToLock'); render(); return; }
    if (p.v1 !== p.v2) { p.error = t('pwMismatch'); render(); return; }
    // Fold any blank-password vault contents into the session before the
    // re-encrypt: writeVault rebuilds the blob from session accounts, and a
    // wallet saved by an earlier session must not fall out of the vault just
    // because a password is being set now.
    try { mergeVaultList(decryptVault(loadVaultBlob(), '')); } catch {}
    vaultPassword = p.v1;
    writeVault();
    persistAccounts();
    markLockPwAsked();
    ui.pw = null;
    softLock(); // stay home, watch-only: closed padlock + "Locked" toast
    return;
  }
  if (p.mode === 'set') {
    // Password is optional — a blank one just persists without protection.
    if (p.v1 !== p.v2) { p.error = t('pwMismatch'); render(); return; }
    vaultPassword = p.v1 || '';
  } else {
    let list;
    try { list = decryptVault(loadVaultBlob(), p.v1); } catch { p.error = t('pwWrong'); render(); return; }
    vaultPassword = p.v1;
    mergeVaultList(list); // bring existing persisted accounts into the session
  }
  const acc = accounts.find((a) => a.id === p.accId);
  if (acc) acc.persisted = p.purpose === 'save' || p.purpose === 'locksave';
  writeVault();
  persistAccounts();
  const finishLock = p.purpose === 'locksave';
  ui.pw = null;
  if (finishLock) { softLock(); return; }
  render();
}

// Lock with a passkey (fingerprint or face) instead of a password. The
// vault's wallets are re-sealed under the passkey's secret; from then on
// opening them takes the passkey, and the recovery words remain the way back
// if it's ever lost. `lockAfter`: the padlock's offer — lock once it's set.
async function enablePasskeyLock({ lockAfter = false } = {}) {
  // what the vault holds now, under whatever opens it today
  if (hasVault()) {
    let list;
    try { list = decryptVault(loadVaultBlob(), vaultPassword != null ? vaultPassword : ''); } catch {
      ui.pw = { purpose: 'passkeyOn', mode: 'enter', v0: '', v1: '', v2: '', error: '' };
      render(); return;
    }
    mergeVaultList(list);
  }
  let made;
  try {
    const pass = await import('./passkey.js');
    made = await pass.lockPasskeyCreate();
  } catch (e) {
    const pass = await import('./passkey.js').catch(() => null);
    if (!(pass && pass.passkeyCancelled(e))) toast(t('passkeyLockFailed', { msg: (e && e.message) || String(e) }), 4000);
    render(); return;
  }
  vaultPassword = made.secret;
  vaultPasskeyId = made.id;
  // a wallet that only lives in this tab joins the vault, or it couldn't come back
  const active = activeAccount();
  if (active && active.type === 'full' && !active.provisional) active.persisted = true;
  writeVault();
  persistAccounts();
  markLockPwAsked();
  ui.pw = null;
  if (lockAfter) { softLock(); return; }
  render();
  toast(t('passkeyLockOnToast'));
}
// Back to no lock at all (the padlock offers a password or the passkey
// again). Needs the passkey once, unless this session already holds it.
async function disablePasskeyLock() {
  let secret = passkeySecret(vaultPassword) ? vaultPassword : null;
  if (!secret) {
    const s2 = await passkeyVaultSecret();
    if (!s2) return;
    secret = s2;
  }
  let list;
  try { list = decryptVault(loadVaultBlob(), secret); } catch { toast(t('pwWrong')); return; }
  mergeVaultList(list);
  vaultPassword = '';
  vaultPasskeyId = null;
  writeVault();
  persistAccounts();
  render();
  toast(t('passkeyLockOffToast'));
}
// The fingerprint or face check: the vault's secret, or null (cancelled or
// failed — a failure is shown where the unlock was asked for).
async function passkeyVaultSecret() {
  const id = vaultPasskey();
  if (!id) return null;
  const pass = await import('./passkey.js');
  try { return await pass.lockPasskeyUnlock(id); } catch (e) {
    if (!pass.passkeyCancelled(e)) { ui.vaultError = (e && e.message) || String(e); toast(ui.vaultError, 4000); render(); }
    return null;
  }
}
async function unlockVaultWithPasskey() {
  ui.vaultError = '';
  const secret = await passkeyVaultSecret();
  if (!secret) return;
  ui.vaultPw = secret;
  unlockVault();
  ui.vaultPw = '';
}
// The password prompts that only need the vault opened (save, forget, lock
// a stray wallet) take the passkey instead when that's what locks it.
async function submitPwWithPasskey() {
  const p = ui.pw;
  const secret = await passkeyVaultSecret();
  if (!secret || ui.pw !== p) return;
  p.v1 = secret;
  submitPw();
}

// Try to decrypt the vault with the given password; on success, seed the
// accounts (watch-only directory + the unlocked full wallets). Returns success.
function attemptVaultUnlock(password) {
  let list;
  try { list = decryptVault(loadVaultBlob(), password); } catch { return false; }
  vaultPassword = password;
  vaultPasskeyId = passkeySecret(password) ? vaultPasskey() : null;
  // Start from the durable directory (watch-only views of every known wallet),
  // then upgrade the vault-saved ones to spendable — so non-saved wallets still
  // appear (watch-only) instead of vanishing.
  accounts = loadWatchAccounts();
  mergeVaultList(list);
  // Now that we have the password, finish signing out any saved wallets whose
  // timer expired while we were away (couldn't re-encrypt the vault until now).
  if (_bootAwayMs) {
    const due = accounts.filter((a) => accAutoLock(a) > 0 && _bootAwayMs >= accAutoLock(a));
    for (const a of due) { wipeAccountCache(a); accounts = accounts.filter((x) => x.id !== a.id); }
    if (due.some((a) => a.persisted)) writeVault();
    _bootAwayMs = 0;
  }
  return true;
}

// "Unlock for": a session deadline chosen at the password prompt. Past it the
// app relocks (back to this prompt) — wallets stay saved, nothing is wiped.
const UNLOCK_FOR_KEY = 'btc-wallet-unlock-for';
const UNLOCK_UNTIL_KEY = 'btc-wallet-unlock-until';
const UNLOCK_FOR_OPTIONS = [
  { ms: 300_000, label: 'unlockFor5m' },
  { ms: 1_800_000, label: 'unlockFor30m' },
  { ms: 86_400_000, label: 'unlockFor1d' },
  { ms: 0, label: 'unlockForever' },
];
let _unlockUntilTimer = null;
function armUnlockDeadline() {
  clearTimeout(_unlockUntilTimer); _unlockUntilTimer = null;
  let until = 0;
  try { until = Number(localStorage.getItem(UNLOCK_UNTIL_KEY)) || 0; } catch {}
  if (!until) return;
  const left = until - Date.now();
  if (left <= 0) {
    try { localStorage.removeItem(UNLOCK_UNTIL_KEY); } catch {}
    if (activeAccount() && !wallet.watchOnly) softLock();
    return;
  }
  _unlockUntilTimer = setTimeout(armUnlockDeadline, Math.min(left, 60_000));
}
function unlockDeadlinePassed() {
  try { const u = Number(localStorage.getItem(UNLOCK_UNTIL_KEY)) || 0; return u > 0 && Date.now() >= u; } catch { return false; }
}

// On-open vault unlock (password prompt).
function unlockVault() {
  if (!attemptVaultUnlock(ui.vaultPw)) { ui.vaultError = t('pwWrong'); render(); return; }
  ui.vaultPw = '';
  ui.vaultError = '';
  ui.justLocked = false;
  const ms = ui.unlockFor != null ? ui.unlockFor : Number(localStorage.getItem(UNLOCK_FOR_KEY)) || 0;
  try {
    localStorage.setItem(UNLOCK_FOR_KEY, String(ms));
    if (ms > 0) localStorage.setItem(UNLOCK_UNTIL_KEY, String(Date.now() + ms));
    else localStorage.removeItem(UNLOCK_UNTIL_KEY);
  } catch {}
  armUnlockDeadline();
  const cur = accounts.find((a) => a.id === activeId) || preferredAccount();
  if (cur) activateAccount(cur, { fresh: true });
  else lock(); // everything got signed out by the timer
}
function skipVault() {
  ui.vaultPw = '';
  ui.vaultError = '';
  const watch = loadWatchAccounts();
  if (watch.length) { accounts = watch.slice(); activateAccount(preferredAccount(), { fresh: true }); }
  else { ui.screen = 'unlock'; render(); }
}

function enterOfflineFallback() {
  wallet.setOffline(true);
  wallet.deriveWindow(40);
  ui.offlineFallback = true;
  ui.claimChecking = false; // can't verify a gift offline; don't hang on the loader
  ui.tab = 'settings';
  render();
}

async function retryOnline() {
  ui.offlineFallback = false;
  wallet.setOffline(false);
  ui.tab = 'history';
  render();
  try {
    await wallet.scan();
    wallet.startRealtime();
  } catch {
    enterOfflineFallback();
  }
}

// --- auto log-out, per wallet ----------------------------------------------
// Each account can choose how long the app may sit in the background before that
// wallet is signed out (removed from this device — session, directory, cache,
// and its vault entry). Other wallets are untouched. The countdown only runs
// while the app is hidden/unfocused, never while you're looking at it. 0 = never.
const AUTOLOCK_OPTIONS = [
  { ms: 0, label: 'autolockNever' },
  { ms: 60_000, label: 'autolock1m' },
  { ms: 300_000, label: 'autolock5m' },
  { ms: 3_600_000, label: 'autolock1h' },
  { ms: 86_400_000, label: 'autolock1d' },
];
const accAutoLock = (a) => (a && Number(a.autoLock)) || 0;

const AWAY_AT_KEY = 'btc-wallet-bg-at';
let _awayTimer = null;
let _bootAwayMs = 0; // away duration carried into the vault-unlock check this session
const _awayAt = () => { try { return Number(localStorage.getItem(AWAY_AT_KEY)) || 0; } catch { return 0; } };
const _clearAwayAt = () => { try { localStorage.removeItem(AWAY_AT_KEY); } catch {} };

// Remove one wallet's cached state — the xpub mirror plus its seed-keyed cache
// (when the seed is at hand), including the :ack/:gift suffixes.
function wipeAccountCache(acc) {
  if (!acc) return;
  const ids = [];
  if (acc.xpub) ids.push(acc.xpub);
  if (acc.xprv) ids.push(acc.xprv);
  else if (acc.mnemonic) ids.push(`${acc.mnemonic}\n${acc.passphrase || ''}`);
  const bases = ids.map(cacheKeyFor);
  try {
    const keys = [];
    for (let i = 0; i < localStorage.length; i++) { const k = localStorage.key(i); if (k && bases.some((b) => k.startsWith(b))) keys.push(k); }
    keys.forEach((k) => localStorage.removeItem(k));
  } catch {}
  for (const b of bases) { try { cacheStore().removePrefix(b); } catch {} }
  for (const f of FEATURES) { try { f.wipeCache && f.wipeCache(bases); } catch {} }
}

// Sign out a single wallet: remove it from the device entirely (session,
// directory, cache, and the vault if it was saved). Others are left alone.
function wipeAccount(id) {
  const acc = accounts.find((a) => a.id === id);
  if (!acc) return;
  const wasActive = activeId === id;
  wipeAccountCache(acc);
  const wasPersisted = acc.persisted;
  accounts = accounts.filter((a) => a.id !== id);
  if (wasPersisted && vaultPassword != null) writeVault(); // re-encrypt the vault without it
  persistAccounts(); // refresh the durable directory
  if (wasActive) {
    if (accounts.length) activateAccount(accounts[0], { fresh: true });
    else lock();
  }
}

// Sign out every loaded wallet whose timer has elapsed for the given away time.
function evaluateOverdue(away) {
  const due = accounts.filter((a) => accAutoLock(a) > 0 && away >= accAutoLock(a)).map((a) => a.id);
  for (const id of due) wipeAccount(id);
}

// Arm a timer for the soonest-due wallet so a blurred-but-visible window still
// signs out on time (the timestamp covers throttled/backgrounded tabs).
function armAwayTimer() {
  clearTimeout(_awayTimer); _awayTimer = null;
  const awayAt = _awayAt();
  if (!awayAt) return;
  const locks = accounts.map(accAutoLock).filter((ms) => ms > 0);
  if (!locks.length) return;
  const elapsed = Date.now() - awayAt;
  if (locks.some((ms) => elapsed >= ms)) { evaluateOverdue(elapsed); armAwayTimer(); return; }
  const next = Math.min(...locks.map((ms) => ms - elapsed));
  _awayTimer = setTimeout(() => { evaluateOverdue(Date.now() - awayAt); armAwayTimer(); }, Math.max(0, next));
}

function onAppHidden() {
  try { localStorage.setItem(AWAY_AT_KEY, String(Date.now())); } catch {}
  armAwayTimer();
}
function onAppVisible() {
  clearTimeout(_awayTimer); _awayTimer = null;
  const awayAt = _awayAt(); _clearAwayAt();
  if (awayAt) evaluateOverdue(Date.now() - awayAt);
  armUnlockDeadline(); // background tabs throttle timers — recheck on return
  // A phone freezes a backgrounded tab: timers stop, relay sockets are cut,
  // and nothing that happened while you were away ever arrives. Features that
  // hold live connections get told how long the app was gone so they can
  // catch up rather than sit on a dead subscription.
  const away = awayAt ? Date.now() - awayAt : 0;
  for (const f of FEATURES) { try { f.resumed && f.resumed(away); } catch {} }
}

// At boot the in-memory timer is gone (reload / discarded tab). Drop overdue
// wallets from the persisted session and directory before anything is restored;
// overdue saved wallets are removed from the vault when it's unlocked.
function applyBootAutoLogout() {
  const awayAt = _awayAt(); _clearAwayAt();
  if (!awayAt) return;
  const away = Date.now() - awayAt;
  _bootAwayMs = away;
  const overdue = (a) => { const ms = Number(a.autoLock) || 0; return ms > 0 && away >= ms; };
  try {
    const sess = JSON.parse(sessionStorage.getItem(ACCOUNTS_KEY) || 'null');
    if (sess && Array.isArray(sess.accounts)) {
      const keep = sess.accounts.filter((a) => { if (overdue(a)) { wipeAccountCache(a); return false; } return true; });
      sess.accounts = keep;
      if (!keep.find((a) => a.id === sess.activeId)) sess.activeId = keep[0] ? keep[0].id : null;
      sessionStorage.setItem(ACCOUNTS_KEY, JSON.stringify(sess));
    }
  } catch {}
  try {
    const dir = JSON.parse(localStorage.getItem(WATCH_KEY) || '[]');
    const keep = dir.filter((d) => { if (overdue(d)) { wipeAccountCache(d); return false; } return true; });
    localStorage.setItem(WATCH_KEY, JSON.stringify(keep));
  } catch {}
}

function lock({ offerPassword = false } = {}) {
  wallet.stopRealtime();
  // A locked session must not keep listening as the account that just left —
  // and whatever logs in next must not inherit its threads or subscriptions.
  _featuresInited = false;
  for (const f of FEATURES) { try { f.stop && f.stop(); } catch {} }
  clearAccounts();
  vaultPassword = null;
  vaultPasskeyId = null;
  wallet.load({ mnemonic: '', passphrase: '', netName: getNetwork(), offline: false });
  wallet.mnemonic = '';
  // Wallets save themselves to this device without asking, under an empty
  // password unless one is set. Demanding a password on the way out is then
  // theatre — it protects nothing and asks for something nobody chose. With no
  // password, logging out means dropping back to the wallet list; with one, it
  // means what it says.
  const noPassword = hasVault() && attemptVaultUnlock('');
  ui.screen = !hasVault() ? 'unlock' : noPassword ? 'accounts' : 'vault';
  ui.unlockTab = 'create';
  ui.fromWallet = false;
  ui.watchXpub = '';
  ui.watchLabel = '';
  ui.pw = null;
  clearFeatureNav(); // a profile/chat from the locked session must not outlive it
  ui.vaultPw = '';
  ui.vaultError = '';
  ui.confirmClear = false;
  ui.confirmRemove = null;
  ui.editId = null;
  ui.editLabel = '';
  ui.createStep = 'gen';
  ui.draftMnemonic = '';
  ui.importText = '';
  ui.entropyPage = null;
  ui.entropyEntry = '';
  ui.ownEntropy = '';
  ui.importEntropy = '';
  ui.passphrase = '';
  ui.confirmPass = '';
  ui.confirm = [];
  ui.revealShown = false;
  ui.pubkeyShown = false;
  ui.giftMode = false;
  ui.giftAmount = '';
  ui.giftCode = null;
  ui.giftError = '';
  ui.giftMax = false;
  ui.giftSplitOffer = null;
  ui.revokeId = null;
  ui.receiveSeenIndex = null;
  ui.txDetail = null;
  ui.broadcastTx = null;
  ui.bump = null;
  // Offer to set a password on the way out — but once, ever: someone who said
  // "Not now" has answered, and a wallet that nags is a wallet people stop
  // reading. (The padlock is different: it asks every time via softLock's
  // in-place prompt, because locking without a password is impossible and
  // the tap would otherwise be a confusing trip to the wallet list.)
  if (noPassword && offerPassword && !lockPwAsked()) {
    ui.pw = { purpose: 'lock', mode: 'set', v0: '', v1: '', v2: '', error: '' };
  }
  render();
}

// ================================================================ WALLET
// The avatar IS your profile now — one tap opens it (edit lives there).
// Settings and Lock stand beside it as their own icons; no popup menu.
// The nostr identity the header avatar stands for, when there is one.
const headerIdentity = () => (featureHook('nostrLoginIdentity') || {}).pubkey || (wallet.nostrPubkey && wallet.nostrPubkey())
  || (activeAccount() || {}).nostrPk || null;
function avatarMenu() {
  const me = headerIdentity();
  // Older watch-only accounts may have no remembered Nostr identity. Keep
  // account access available even when there is no profile to open.
  const node = (me && featureHook('headerAvatar', me))
    || h('span', {
      class: 'chat-avatar header-ava fallback',
      html: '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>',
    });
  return h('button', {
    class: 'header-avatar' + (me ? ' header-railed' : ''),
    title: me ? t('profYourProfile') : t('walletSettings'),
    'aria-label': me ? t('profYourProfile') : t('walletSettings'),
    onClick: () => {
      clearFeatureNav(); ui.screen = 'wallet';
      if (!me || !featureHook('showProfile', me)) { openWalletSettings(); return; }
      render();
    },
  }, node);
}

function settingsBtn() {
  return h('button', {
    class: 'header-msgs' + ' header-railed', title: t('tabSettings'), 'aria-label': t('tabSettings'),
    onClick: () => {
      clearFeatureNav();
      ui.screen = 'wallet'; ui.tab = 'settings'; ui.settingsPage = null; render();
    },
  }, h('span', {
    class: 'hm-ico',
    html: '<svg width="21" height="21" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09a1.65 1.65 0 0 0-1-1.51 1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09a1.65 1.65 0 0 0 1.51-1 1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33h.09a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82v.09a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg>',
  }));
}

// Lock in place: the keys leave, the view stays. The wallet remains on screen
// watch-only (balances and history, no spending), the padlock closes, and
// tapping it again asks for the password to bring the keys back.
function softLock() {
  const watch = loadWatchAccounts();
  let blankPw = false;
  try { decryptVault(loadVaultBlob(), ''); blankPw = true; } catch {}
  // No protecting password yet: locking would protect nothing, so ask for one
  // right here — keys intact, home still on screen. Submitting saves the
  // vault under it and locks in place; "Not now" just closes the prompt.
  // (Tearing the session down first meant "Not now" stranded people on the
  // wallet list, signed out of a wallet they never asked to leave.)
  if (!hasVault() || blankPw) {
    ui.pw = { purpose: 'lock', mode: 'set', v0: '', v1: '', v2: '', error: '' };
    render();
    return;
  }
  // Nothing watchable: this session can't stay on screen — classic full lock.
  if (!watch.length) { lock({ offerPassword: true }); ui.justLocked = true; return; }
  // A wallet that isn't IN the vault can't come back from a lock — unlocking
  // decrypts the vault, and this seed isn't there (created while the vault
  // sat locked, so autoSave couldn't write it). Save it first: with the
  // session password if we hold it, else ask for the vault password now.
  const active = activeAccount();
  if (active && active.type === 'full' && !active.provisional && !active.persisted) {
    if (vaultPassword != null) {
      active.persisted = true;
      writeVault();
      persistAccounts();
    } else {
      ui.pw = { purpose: 'locksave', accId: active.id, mode: 'enter', v1: '', v2: '', error: '' };
      ui.screen = 'accounts'; // the pw prompt renders on the accounts screen
      render();
      return;
    }
  }
  const keepId = activeId;
  // The lock is going through: leave whatever page the padlock was tapped
  // from, so what you land on is the wallet wearing a closed padlock — from
  // a profile page the toast was the only sign anything had happened.
  clearFeatureNav();
  _featuresInited = false;
  for (const f of FEATURES) { try { f.stop && f.stop(); } catch {} }
  vaultPassword = null;
  vaultPasskeyId = null;
  accounts = watch.slice();
  persistAccounts();
  const cur = accounts.find((a) => a.id === keepId) || accounts[0];
  activateAccount(cur, { fresh: true });
  toast(t('lockedToast'));
}

// Lock (or unlock) the wallets on this device — a row on the Accounts page,
// where the other whole-device actions (log out, clear) live; it used to be
// a header icon, one tap from a mis-tap on every screen.
function lockBtn() {
  if (!activeAccount()) return null;
  const locked = wallet.watchOnly && hasVault();
  return h('button', {
    class: 'btn-ghost btn-block',
    title: locked ? t('unlock') : t('lockWallet'),
    'aria-label': locked ? t('unlock') : t('lockWallet'),
    onClick: locked
      ? () => {
          if (attemptVaultUnlock('')) {
            const cur = accounts.find((a) => a.id === activeId) || accounts[0];
            if (cur) activateAccount(cur, { fresh: true });
          } else { ui.justLocked = false; ui.screen = 'vault'; ui.passkeyAsk = true; render(); }
        }
      : () => softLock(),
  }, h('span', { style: 'font-size:15px;line-height:1;margin-right:6px' }, locked ? '\u{1F512}' : '\u{1F513}'), locked ? t('unlock') : t('lockWallet'));
}

// Find anyone on nostr from the header — results open their profile.
// Wide screens trade the search icon for a field in the header or sticky
// wallet sidebar. It drives the search page, which drops its own copy.
function headerSearch() {
  if (!featureHook('userSearchAvailable')) return null;
  return h('input', {
    type: 'text', class: 'header-search', placeholder: t('searchUsers') + '…', 'aria-label': t('searchUsers'),
    value: (ui.userSearch && ui.userSearch.q) || '', autocapitalize: 'none', autocomplete: 'off', spellcheck: 'false',
    onInput: (e) => { clearFeatureNavKeepSearch(); featureHook('userSearchQuery', e.target.value); },
  });
}
function clearFeatureNavKeepSearch() {
  if (ui.userSearch) return; // already on the search page: just the query moves
  clearFeatureNav(); ui.screen = 'wallet';
}

function searchBtn() {
  if (!featureHook('userSearchAvailable')) return null;
  return h('button', {
    class: 'header-msgs' + ' header-railed',
    title: t('searchUsers'),
    'aria-label': t('searchUsers'),
    onClick: () => {
      clearFeatureNav(); ui.screen = 'wallet';
      featureHook('openUserSearch');
      render();
      setTimeout(() => document.querySelector('.user-search-input')?.focus(), 60);
    },
  }, h('span', {
    class: 'hm-ico',
    html: '<svg width="21" height="21" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="11" r="7"/><path d="m21 21-4.35-4.35"/></svg>',
  }));
}

function brandLogo() {
  return h(
      'div',
      { class: 'brand' + (STAGING ? ' staging' : ' beta'), style: 'cursor:pointer', title: t('home'), onClick: goHome },
      STAGING ? h('span', { class: 'staging-badge', title: 'staging build: new wallets start on Mutinynet' }, 'staging')
        : h('span', { class: 'beta-badge' }, 'v3 beta'),
      h('div', { class: 'logo-full', 'aria-label': 'coinos', role: 'img', html: '<svg viewBox="0 0 224 72" height="40" fill="currentColor" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" clip-rule="evenodd" d="M36 4.23529C18.4568 4.23529 4.23529 18.4568 4.23529 36C4.23529 53.5432 18.4568 67.7647 36 67.7647C53.5432 67.7647 67.7647 53.5432 67.7647 36C67.7647 18.4568 53.5432 4.23529 36 4.23529ZM0 36C0 16.1177 16.1177 0 36 0C55.8823 0 72 16.1177 72 36C72 55.8823 55.8823 72 36 72C16.1177 72 0 55.8823 0 36Z" fill="currentColor"/><path fill-rule="evenodd" clip-rule="evenodd" d="M36 58.5882C48.4751 58.5882 58.5882 48.4751 58.5882 36C58.5882 23.5248 48.4751 13.4117 36 13.4117C23.5249 13.4117 13.4118 23.5248 13.4118 36C13.4118 48.4751 23.5249 58.5882 36 58.5882ZM36 54C45.9411 54 54 45.9411 54 36C54 26.0589 45.9411 18 36 18C26.0589 18 18 26.0589 18 36C18 45.9411 26.0589 54 36 54Z" fill="currentColor"/><path fill-rule="evenodd" clip-rule="evenodd" d="M36.0001 22.8988C36.0001 22.8988 36 22.8988 36 22.8988C28.7644 22.8988 22.8988 28.7644 22.8988 36C22.8988 43.2356 28.7644 49.1012 36 49.1012C36 49.1012 36.0001 49.1012 36.0001 49.1012V22.8988Z" fill="currentColor"/><path d="M97.608 27.704C99.544 27.704 101.248 28.088 102.72 28.856C104.192 29.624 105.368 30.688 106.248 32.048C107.144 33.408 107.68 34.952 107.856 36.68H102.864C102.752 35.928 102.48 35.216 102.048 34.544C101.616 33.856 101.032 33.304 100.296 32.888C99.56 32.456 98.672 32.24 97.632 32.24C95.776 32.24 94.264 32.928 93.096 34.304C91.944 35.68 91.368 37.792 91.368 40.64C91.368 43.264 91.92 45.352 93.024 46.904C94.128 48.456 95.704 49.232 97.752 49.232C98.776 49.232 99.648 49.008 100.368 48.56C101.104 48.096 101.68 47.528 102.096 46.856C102.528 46.168 102.808 45.48 102.936 44.792H107.784C107.64 46.472 107.112 47.968 106.2 49.28C105.304 50.592 104.12 51.624 102.648 52.376C101.192 53.112 99.512 53.48 97.608 53.48C95.336 53.48 93.312 52.984 91.536 51.992C89.776 50.984 88.392 49.528 87.384 47.624C86.376 45.704 85.872 43.392 85.872 40.688C85.872 38.112 86.344 35.856 87.288 33.92C88.232 31.968 89.584 30.448 91.344 29.36C93.104 28.256 95.192 27.704 97.608 27.704ZM122.09 53.48C119.722 53.48 117.658 52.976 115.898 51.968C114.138 50.944 112.77 49.48 111.794 47.576C110.834 45.672 110.354 43.384 110.354 40.712C110.354 38.12 110.818 35.848 111.746 33.896C112.69 31.944 114.042 30.424 115.802 29.336C117.562 28.248 119.666 27.704 122.114 27.704C124.482 27.704 126.538 28.224 128.282 29.264C130.026 30.304 131.37 31.792 132.314 33.728C133.274 35.664 133.754 37.992 133.754 40.712C133.754 43.224 133.298 45.44 132.386 47.36C131.49 49.264 130.17 50.76 128.426 51.848C126.698 52.936 124.586 53.48 122.09 53.48ZM122.114 49.04C123.458 49.04 124.562 48.672 125.426 47.936C126.306 47.2 126.954 46.192 127.37 44.912C127.802 43.632 128.018 42.176 128.018 40.544C128.018 39.024 127.826 37.624 127.442 36.344C127.074 35.064 126.45 34.04 125.57 33.272C124.706 32.488 123.554 32.096 122.114 32.096C120.754 32.096 119.626 32.456 118.73 33.176C117.85 33.88 117.186 34.872 116.738 36.152C116.306 37.416 116.09 38.88 116.09 40.544C116.09 42.048 116.282 43.448 116.666 44.744C117.066 46.024 117.706 47.064 118.586 47.864C119.466 48.648 120.642 49.04 122.114 49.04ZM143.518 28.184V53H137.902V28.184H143.518ZM143.59 18.32V23.84H137.806V18.32H143.59ZM149.367 53V28.184H155.079V31.736C155.463 31.096 155.983 30.48 156.639 29.888C157.311 29.296 158.135 28.816 159.111 28.448C160.087 28.08 161.231 27.896 162.543 27.896C164.079 27.896 165.503 28.2 166.815 28.808C168.143 29.416 169.207 30.368 170.007 31.664C170.823 32.96 171.231 34.632 171.231 36.68V53H165.375V37.376C165.375 35.744 164.927 34.536 164.031 33.752C163.135 32.952 162.007 32.552 160.647 32.552C159.719 32.552 158.839 32.712 158.007 33.032C157.175 33.336 156.495 33.808 155.967 34.448C155.455 35.072 155.199 35.856 155.199 36.8V53H149.367ZM186.348 53.48C183.98 53.48 181.916 52.976 180.156 51.968C178.396 50.944 177.028 49.48 176.052 47.576C175.092 45.672 174.612 43.384 174.612 40.712C174.612 38.12 175.076 35.848 176.004 33.896C176.948 31.944 178.3 30.424 180.06 29.336C181.82 28.248 183.924 27.704 186.372 27.704C188.74 27.704 190.796 28.224 192.54 29.264C194.284 30.304 195.628 31.792 196.572 33.728C197.532 35.664 198.012 37.992 198.012 40.712C198.012 43.224 197.556 45.44 196.644 47.36C195.748 49.264 194.428 50.76 192.684 51.848C190.956 52.936 188.844 53.48 186.348 53.48ZM186.372 49.04C187.716 49.04 188.82 48.672 189.684 47.936C190.564 47.2 191.212 46.192 191.628 44.912C192.06 43.632 192.276 42.176 192.276 40.544C192.276 39.024 192.084 37.624 191.7 36.344C191.332 35.064 190.708 34.04 189.828 33.272C188.964 32.488 187.812 32.096 186.372 32.096C185.012 32.096 183.884 32.456 182.988 33.176C182.108 33.88 181.444 34.872 180.996 36.152C180.564 37.416 180.348 38.88 180.348 40.544C180.348 42.048 180.54 43.448 180.924 44.744C181.324 46.024 181.964 47.064 182.844 47.864C183.724 48.648 184.9 49.04 186.372 49.04ZM210.995 53.48C209.267 53.48 207.627 53.208 206.075 52.664C204.539 52.104 203.243 51.232 202.187 50.048C201.147 48.864 200.491 47.336 200.219 45.464H205.355C205.579 46.376 205.971 47.12 206.531 47.696C207.107 48.272 207.787 48.696 208.571 48.968C209.355 49.224 210.155 49.352 210.971 49.352C212.459 49.352 213.659 49.096 214.571 48.584C215.499 48.072 215.963 47.28 215.963 46.208C215.963 45.424 215.707 44.8 215.195 44.336C214.683 43.872 213.867 43.52 212.747 43.28L208.019 42.2C205.923 41.736 204.235 40.968 202.955 39.896C201.691 38.824 201.051 37.312 201.035 35.36C201.019 33.888 201.387 32.576 202.139 31.424C202.891 30.272 204.011 29.368 205.499 28.712C206.987 28.04 208.827 27.704 211.019 27.704C213.915 27.704 216.235 28.352 217.979 29.648C219.723 30.928 220.619 32.76 220.667 35.144H215.699C215.523 34.072 215.019 33.24 214.187 32.648C213.355 32.04 212.275 31.736 210.947 31.736C209.571 31.736 208.443 32 207.563 32.528C206.683 33.056 206.243 33.864 206.243 34.952C206.243 35.704 206.579 36.296 207.251 36.728C207.923 37.16 208.931 37.528 210.275 37.832L214.739 38.912C216.019 39.232 217.067 39.664 217.883 40.208C218.699 40.752 219.339 41.352 219.803 42.008C220.267 42.648 220.587 43.312 220.763 44C220.955 44.672 221.051 45.296 221.051 45.872C221.051 47.472 220.635 48.84 219.803 49.976C218.987 51.096 217.827 51.96 216.323 52.568C214.819 53.176 213.043 53.48 210.995 53.48Z" fill="currentColor"/></svg>' })
    );
}

function brandHeader(withLock) {
  const acc = activeAccount();
  return h(
    'div',
    { class: 'row between brand-header' },
    brandLogo(),
    withLock
      ? h('div', { class: 'row gap6', style: 'align-items:center' },
          searchBtn(),
          headerSearch(),
          settingsBtn(),
          avatarMenu())
      : ui.pubProf && !acc ? visitorButtons() : null
  );
}
// A visitor on a public page (a feed, a profile, a thread): find anyone,
// and the way in.
function visitorButtons() {
  return h('div', { class: 'row gap6', style: 'align-items:center' },
    h('button', {
      class: 'header-msgs', title: t('searchUsers'), 'aria-label': t('searchUsers'),
      onClick: () => { featureHook('visitorSearch'); setTimeout(() => document.querySelector('.user-search-input')?.focus(), 60); },
    }, h('span', { class: 'hm-ico', html: '<svg width="21" height="21" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="11" r="7"/><path d="m21 21-4.35-4.35"/></svg>' })),
    h('button', { class: 'btn-primary btn-sm', style: 'flex-shrink:0', onClick: () => featureHook('visitorSignIn') }, t('nlSignIn')));
}

// Settings tab — view the recovery phrase (+ passphrase) again (important for
// users who skipped backup verification) and the offline snapshot transfer.
// The phrase is gated: the real words are never put in the DOM until "Reveal",
// so the warning is read first.
// Rescan a single address on demand — recovers a deposit to a reused old
// address without a full wallet rescan. Multiple can be queued at once; the
// API layer's global scheduler serializes and spaces the underlying requests
// (and backs off on 429), so a flurry of clicks stays within the rate limit.
async function doRescanAddress(chain, index) {
  if (wallet.offline) { toast(t('scanOffline')); return; }
  const id = chain + '/' + index;
  if (ui.rescanning.has(id)) return; // already queued
  ui.rescanning.add(id);
  render();
  try {
    await wallet.rescanAddress(chain, index);
  } catch (e) {
    toast(e.message || t('rescanFailed'));
  }
  ui.rescanning.delete(id);
  render();
}

// Paginated list of every known address, each with its own rescan button.
function addressScanView() {
  const addrs = wallet.knownAddresses();
  const pages = Math.ceil(addrs.length / PAGE_SIZE) || 1;
  const page = Math.min(ui.addrScanPage, pages - 1);
  const slice = addrs.slice(page * PAGE_SIZE, page * PAGE_SIZE + PAGE_SIZE);
  return h(
    'div',
    { class: 'col', style: 'gap:16px' },
    h('div', { class: 'card col', style: 'gap:12px' },
      h('div', { class: 'row between' },
        h('h3', { style: 'margin:0' }, t('rescanAddresses')),
        h('button', { class: 'btn-sm', onClick: () => { ui.addrScan = false; render(); } }, t('back'))
      ),
      h('p', { class: 'small muted', style: 'margin:0' }, t('rescanAddrDesc')),
      h('div', { class: 'list' },
        ...slice.map((a) => {
          const id = a.chain + '/' + a.index;
          const busy = ui.rescanning.has(id);
          return h('div', { class: 'item' },
            h('div', { class: 'grow' },
              h('div', { class: 'mono small break' }, shortAddr(a.address, 16, 10),
                a.used ? null : h('span', { class: 'badge off dot', style: 'font-size:10px;margin-left:6px;padding:1px 7px' }, t('unusedTag'))),
              h('div', { class: 'path' }, `${a.chain}/${a.index}` + (a.balance ? ' · ' + fmtAmount(a.balance) + ' ' + unitLabel() : ''))
            ),
            busy
              ? h('button', { class: 'btn-sm', disabled: true }, h('span', { class: 'spinner sm' }))
              : h('button', { class: 'btn-sm', onClick: () => doRescanAddress(a.chain, a.index) }, t('rescanOne'))
          );
        })
      ),
      pager(page, addrs.length, (p) => { ui.addrScanPage = p; render(); })
    )
  );
}

// Settings is a hub: the main page is nothing but doors, each subpage owns
// one concern — Wallet (name/pubkey/seed), Payments (address + Spending),
// Network (chain + data source), Nostr, Advanced (rarities).
function settingsTab() {
  if (ui.addrScan && !wallet.offline) return addressScanView();
  const a = activeAccount();
  const page = (kids) => h('div', { class: 'col', style: 'gap:16px' }, ...kids,
    h('button', { class: 'btn-ghost btn-block', onClick: () => { ui.settingsPage = null; render(); } }, t('back')));
  switch (ui.settingsPage) {
    // the recovery phrase first: it is the one thing on this page that
    // matters if the phone is lost tonight
    case 'wallet': return page(a ? [recoveryCard(a), walletNameCard(a), pubkeyCard(a)] : []);
    case 'payments': return page(featureAll('settingsCards').reverse());
    case 'pos': return page(featureAll('posSettingsCards').reverse()); // the till's own card first, then the terminal's
    case 'network': return page([networkCard(), explorerCard()]); // an old bookmark of the tile; the cards live under Advanced now
    case 'nostr': return nostrSettingsView();
    case 'notifications': return page(featureAll('notifySettingsCards').reverse());
    case 'advanced': return advancedSettingsView();
  }
  const I = (d) => '<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round">' + d + '</svg>';
  const TILE_ICONS = {
    wallet: I('<rect x="2" y="6" width="20" height="14" rx="2"/><path d="M2 10h20"/><circle cx="17" cy="15" r="1.4"/>'),
    payments: I('<path d="M13 2 4.5 13.5H11L9.5 22 18 10.5h-6.5z"/>'),
    network: I('<circle cx="12" cy="12" r="9"/><path d="M3 12h18M12 3a15 15 0 0 1 0 18M12 3a15 15 0 0 0 0 18"/>'),
    nostr: I('<circle cx="8" cy="15" r="4"/><path d="M10.9 12.1 20 3l1 1-2 2 2 2-2.5 2.5L16 8l-2.2 2.2"/>'),
    // a till receipt: paper with a torn foot and two lines of figures
    pos: I('<path d="M6 3h12v18l-2-1.5-2 1.5-2-1.5-2 1.5-2-1.5L6 21z"/><line x1="9" y1="8" x2="15" y2="8"/><line x1="9" y1="12" x2="15" y2="12"/><line x1="12" y1="16" x2="15" y2="16"/>'),
    notifications: I('<path d="M18 8a6 6 0 0 0-12 0c0 7-3 9-3 9h18s-3-2-3-9"/><path d="M13.7 21a2 2 0 0 1-3.4 0"/>'),
    advanced: I('<line x1="4" y1="8" x2="20" y2="8"/><line x1="4" y1="16" x2="20" y2="16"/><circle cx="9" cy="8" r="2.2" fill="var(--surface,#fff)"/><circle cx="15" cy="16" r="2.2" fill="var(--surface,#fff)"/>'),
  };
  const tile = (id, label, desc) =>
    h('button', {
      class: 'card col settings-tile',
      style: 'align-items:flex-start;gap:6px;text-align:left;padding:14px;cursor:pointer;margin:0',
      onClick: () => { ui.settingsPage = id; render(); },
    },
      h('span', { class: 'st-ico', style: 'color:var(--muted)', html: TILE_ICONS[id] || '' }),
      h('span', { style: 'font-weight:600' }, label),
      h('span', { class: 'small faint' }, desc));
  const grid = (kids) => h('div', { style: 'display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:10px' }, ...kids);
  return h(
    'div',
    { class: 'col', style: 'gap:10px' },
    h('div', { class: 'row gap6', style: 'align-items:center;margin:2px 0 6px 4px' },
      h('span', { style: 'display:flex;color:var(--muted)', html: '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg>' }),
      h('h3', { style: 'margin:0' }, t('tabSettings'))),
    grid([
      tile('wallet', t('settingsWallet'), t('settingsWalletDesc')),
      tile('payments', t('settingsPayments'), t('settingsPaymentsDesc')),
      tile('pos', t('posTitle'), t('settingsPosDesc')),
      tile('nostr', t('nostrSettings'), t('settingsNostrDesc')),
      tile('notifications', t('settingsNotifications'), t('settingsNotifDesc')),
      tile('advanced', t('advancedSettings'), t('settingsAdvancedDesc')),
    ]),
    h('button', { class: 'btn-ghost btn-block', style: 'margin-top:6px', onClick: () => { ui.tab = wallet.offline ? 'settings' : 'history'; render(); } }, t('back'))
  );
}

// Everything nostr — identity, sync, wallet connect — on its own page.
// Ask the browser to send a URL scheme's links to this app (the ?u= path
// the Android intents already use). Chrome shows its own permission bar;
// a scheme it won't register throws and we say so.
function registerLinkHandler(scheme) {
  try {
    navigator.registerProtocolHandler(scheme, location.origin + '/?u=%s');
    toast(t('linkHandlerAsked'));
  } catch (e) { toast(t('linkHandlerRefused')); }
}
function nostrSettingsView() {
  return h(
    'div',
    { class: 'col', style: 'gap:16px' },
    ...featureAll('nostrSettingsCards'),
    // The browser's own "open these links here" registry: njump's "Your
    // default web app" is a web+nostr: link, and it opens whichever site
    // asked for that scheme last. Needs a tap (the browser asks).
    typeof navigator !== 'undefined' && navigator.registerProtocolHandler
      ? h('div', { class: 'card col', style: 'gap:8px' },
          h('h3', {}, t('linkHandlerTitle')),
          h('p', { class: 'small muted', style: 'margin:0' }, t('linkHandlerDesc')),
          h('div', { class: 'row gap6', style: 'flex-wrap:wrap' },
            h('button', { class: 'btn-sm', onClick: () => registerLinkHandler('web+nostr') }, t('linkHandlerNostr')),
            h('button', { class: 'btn-sm', onClick: () => registerLinkHandler('bitcoin') }, t('linkHandlerBitcoin'))))
      : null,
    h('button', { class: 'btn-ghost btn-block', onClick: () => { ui.settingsPage = null; render(); } }, t('back'))
  );
}

// Rarely used, easy to fat-finger: offline transfer, address rescan, auto-logout.
function advancedSettingsView() {
  const a = activeAccount();
  return h(
    'div',
    { class: 'col', style: 'gap:16px' },
    // which network, which explorer, which Ark server: changed once, if ever
    networkCard(),
    explorerCard(),
    ...featureAll('advancedSettingsCards'),
    wallet.watchOnly
      ? null
      : h(
          'div',
          { class: 'card col' },
          h('h3', {}, t('offlineTransfer')),
          snapshotActions()
        ),
    h(
      'div',
      { class: 'card col' },
      h('h3', {}, t('rescan')),
      h('p', { class: 'small muted', style: 'margin:0' }, t('rescanDesc')),
      wallet.offline
        ? null
        : h('button', { onClick: () => { ui.addrScan = true; ui.addrScanPage = 0; render(); } }, t('rescanAddresses'))
    ),
    a ? autolockCard(a) : null,
    h('button', { class: 'btn-ghost btn-block', onClick: () => { ui.settingsPage = null; render(); } }, t('back'))
  );
}

















// Move the ACTIVE wallet to another network (and make that the default for
// new wallets). Changes addresses/balances entirely, so the account is
// restamped and reloaded under it.
function changeNetwork(net) {
  if (net === getNetwork()) return;
  setNetwork(net);
  for (const f of FEATURES) { try { f.networkChanged && f.networkChanged(net); } catch {} }
  const acc = accounts.find((a) => a.id === activeId);
  if (acc) { acc.network = net; persistAccounts(); activateAccount(acc); } else render();
}





// Network selector. Per-network endpoints (Electrum server / block explorer) are
// configured in the Data source card below — no duplicate URL fields here.
function networkCard() {
  const net = getNetwork();
  return h(
    'div',
    { class: 'card col' },
    h('h3', {}, 'Network'),
    h('p', { class: 'small muted', style: 'margin:0' }, 'Bitcoin network this wallet operates on. Pick its servers under Data source.'),
    h('select', { onChange: (e) => changeNetwork(e.target.value) },
      NETWORKS.map((n) => h('option', { value: n.id, selected: net === n.id }, n.label)))
  );
}

function explorerCard() {
  const net = getNetwork();
  const src = getSource();
  const sources = dataSources(net);
  const pick = (id) => {
    setSource({ id, url: '' });
    render();
    // Switching source can swap the whole backend (electrum⇄esplora), so rebuild
    // + rescan — except an empty custom (wait for the URL).
    if (id !== 'custom' && !wallet.offline) wallet.reloadExplorer();
  };
  const typeDesc = t(src.type === 'electrum' ? 'detectedElectrum' : 'detectedEsplora');
  return h(
    'div',
    { class: 'card col' },
    h('h3', {}, t('dataSource')),
    h('p', { class: 'small muted', style: 'margin:0' }, t('dataSourceDesc')),
    h('select', { onChange: (e) => pick(e.target.value) },
      sources.map((o) => h('option', { value: o.id, selected: o.id === src.id }, o.id === 'custom' ? o.label : (o.url || o.base).replace(/^\w+:\/\//, '')))),
    src.id === 'custom'
      ? h('label', { class: 'field' },
          h('span', { class: 'lab' }, t('sourceUrl')),
          h('input', {
            type: 'text', class: 'mono-input', placeholder: 'wss://your-node:50004  ·  https://your-esplora/api',
            autocapitalize: 'none', autocomplete: 'off', spellcheck: 'false', value: src.url || '',
            onChange: (e) => { const url = e.target.value.trim(); setSource({ id: 'custom', url }); render(); if (!wallet.offline) wallet.reloadExplorer(); },
          }),
          h('div', { class: 'small faint' }, src.url ? typeDesc : t('sourceUrlHint'))
        )
      : h('div', { class: 'small faint' }, typeDesc)
  );
}


// Which money the third tap on an amount shows. The list is whatever the
// rates endpoint carries, so it's every currency coinos knows a price for.
// Changing it starts the recorded price history again: the samples behind
// "worth then" are denominated in the currency they were taken in, and
// relabelling them would be a lie.
function currencyPicker() {
  return h('select', {
    title: t('currencyLabel'),
    value: getCurrency(),
    onChange: (e) => { setCurrency(e.target.value); refreshRates({ force: true }).then(render); render(); },
  }, currencies().map((c) => h('option', { value: c, selected: c === getCurrency() }, c)));
}

// Language selector. Changing it persists the choice, flips text direction for
// RTL languages, and re-renders the whole app in the new language.
function languagePicker() {
  return h(
    'select',
    {
      value: getLang(),
      onChange: async (e) => {
        const code = e.target.value;
        setLang(code);
        await loadLocale(code); // fetch the locale's strings before re-rendering
        applyDir();
        featureHook('langChanged');
        render();
      },
    },
    LANGS.map(([code, name]) => h('option', { value: code, selected: code === getLang() }, name))
  );
}

// Reflect the active language's writing direction on <html> (rtl for ar/ur).
function applyDir() {
  try {
    document.documentElement.dir = isRTL() ? 'rtl' : 'ltr';
    document.documentElement.lang = getLang();
  } catch {}
}

function goHome() {
  // Bailing from an unclaimed gift — discard the provisional wallet it generated.
  const active = accounts.find((a) => a.id === activeId);
  if (active && active.provisional) {
    accounts = accounts.filter((a) => a.id !== active.id);
    persistAccounts();
    activeId = accounts[0] ? accounts[0].id : null;
  }
  // A wallet is open → home is its Receive page (not the create/import screen),
  // so the logo is always a way back to your wallet.
  if (activeAccount()) {
    ui.screen = 'wallet';
    // Home means home: with a wallet already minted, even the wizard yields —
    // its remaining steps are niceties, not something to be trapped in.
    if (ui.onb || onbInProgress()) { ui.onb = null; try { localStorage.removeItem(ONB_STEP_KEY); } catch {} }
    // Clear every takeover a feature or subpage may hold —
    // chat, profile, ark exit, settings subpages, the address rescan list.
    ui.chatOpen = false;
    ui.profilePk = null;
    ui.profEdit = null;
    ui.userSearch = null;
    ui.noteThread = null;
    ui.zapSetup = null;
    ui.arkExitPage = null;
    ui.settingsPage = null;
    ui.logoutConfirm = null;
    ui.nostrReconnect = null;
    ui.addrScan = false;
    ui.arkMoveOpen = false;
    ui.nameEditOpen = null;
    // ...and every other page the history tracks (the vtxo list, a
    // transaction's detail, the hat shop, a lightbox…): home is home,
    // whatever was open. The chat's own position is kept for its next visit.
    for (const f of NAV_FIELDS) {
      if (['screen', 'tab', 'msgView', 'msgCommunity', 'msgPeer', 'feedId'].includes(f)) continue;
      ui[f] = ['chatOpen', 'giftMode', 'profEditFilled', 'profOverThread'].includes(f) ? false : null;
    }
    ui.arkCoinsSel = null; ui.arkRenewConfirm = null; ui.pos = null; ui.feedEdit = null; ui.feedMenu = null;
    ui.tab = wallet.offline ? 'settings' : 'history';
    ui.draft = null;
    ui.sendResult = null;
    ui.sendError = '';
    ui.fromWallet = false;
  } else if ((ui.onb && ui.onb.step !== 'welcome')
      || ui.draftMnemonic || ui.createStep !== 'gen' || ui.importText) {
    // Mid-create with no wallet minted yet (wizard step, a generated seed on
    // screen, the confirm quiz, a pasted import): the logo backs out to the
    // start page this began from — not the vault prompt, which reads as a
    // dead end when you were busy creating something new.
    ui.onb = { step: 'welcome' };
    try { localStorage.removeItem(ONB_STEP_KEY); } catch {}
    ui.nostrLoginOpen = false;
    ui.screen = 'unlock';
    ui.unlockTab = 'create';
    ui.createStep = 'gen';
    ui.draftMnemonic = '';
    clearSeedDrafts();
    ui.entropyPage = null;
    ui.confirm = [];
    ui.unlockError = '';
  } else if (hasVault()) {
    // Locked with saved wallets: home is the unlock prompt, not the
    // create-a-new-wallet flow — the logo must never read as "start over".
    // A passwordless vault isn't locked, though: open it silently and land
    // home instead of demanding a password nobody set.
    if (attemptVaultUnlock('') && accounts.length) {
      activateAccount(preferredAccount(), { fresh: true });
      return;
    }
    ui.screen = 'vault';
  } else {
    ui.screen = 'unlock';
    ui.unlockTab = 'create';
    ui.createStep = 'gen';
    ui.draftMnemonic = '';
    ui.confirm = [];
    ui.unlockError = '';
  }
  render();
}















// Wallets a gift could be claimed into: full accounts open this session plus the
// durable directory (every wallet's xpub, watch-only), deduped by xpub. Claiming
// sends the gift to the wallet's address; a watch-only one then needs the seed
// re-entered to spend. Empty for a first-time recipient.
function claimTargets() {
  let sess = null;
  try { sess = JSON.parse(sessionStorage.getItem(ACCOUNTS_KEY) || 'null'); } catch {}
  const open = ((sess && Array.isArray(sess.accounts)) ? sess.accounts : []).filter((a) => !a.provisional);
  const seen = new Set(open.map((a) => a.xpub).filter(Boolean));
  return [...open, ...loadWatchAccounts().filter((w) => !seen.has(w.xpub))];
}









// Account switcher: pick a wallet, add another, or lock the session.
function logoutConfirmScreen() {
  return h('div', { class: 'col', style: 'gap:16px' },
    brandHeader(false),
    h('div', { class: 'card col' },
      h('h3', {}, t('logout') + '?'),
      h('p', { class: 'small muted' }, t('logoutPopBlurb')),
      h('button', { class: 'btn-primary btn-block', onClick: () => { ui.logoutConfirm = null; ctx.logout(); } }, t('logout')),
      h('button', { class: 'btn-ghost btn-block', onClick: () => { ui.logoutConfirm = null; render(); } }, t('back'))));
}
function accountsScreen() {
  if (ui.pw) return h('div', { class: 'col', style: 'gap:16px' }, brandHeader(false), pwPromptCard());
  if (ui.logoutConfirm) return logoutConfirmScreen();
  if (ui.addWallet) {
    const aw = ui.addWallet;
    const fulls = accounts.filter((x) => x.type === 'full' && x.mnemonic);
    return h('div', { class: 'col', style: 'gap:16px' },
      brandHeader(false),
      h('div', { class: 'card col', style: 'gap:12px' },
        h('h3', {}, t('addWallet')),
        h('div', { class: 'seg', style: 'display:flex;width:100%' },
          ['spending', 'savings'].map((k) => h('button', {
            type: 'button', class: (aw.kind === k ? 'active ' : '') + 'grow',
            onClick: () => { aw.kind = k; render(); },
          }, k === 'spending' ? t('spendingName') : t('savingsName')))),
        h('div', { class: 'col gap6' },
          h('span', { class: 'small muted' }, t('addWalletSeed')),
          h('select', { onChange: (e) => { aw.from = e.target.value; render(); } },
            h('option', { value: 'new', selected: aw.from === 'new' }, t('addWalletNewSeed')),
            fulls.map((x) => h('option', { value: x.id, selected: aw.from === x.id }, t('addWalletShareSeed', { name: seedName(x) }))))),
        aw.from !== 'new' ? h('div', { class: 'small faint' }, t('addWalletShareNote')) : null,
        h('div', { class: 'row gap6' },
          h('button', { class: 'btn-ghost grow', onClick: () => { ui.addWallet = null; render(); } }, t('back')),
          h('button', { class: 'btn-primary grow', onClick: () => {
            const kind = aw.kind;
            if (aw.from === 'new') {
              ui.newWalletKind = kind;
              ui.addWallet = null;
              ui.draftMnemonic = ''; ui.createStep = 'gen'; ui.confirm = []; ui.passphrase = ''; ui.confirmPass = '';
              ui.showPass = false; ui.screen = 'unlock'; ui.unlockTab = 'create'; ui.fromWallet = true; ui.unlockError = '';
              render();
            } else {
              createDerivedWallet(aw.from, kind);
            }
          } }, t('addWalletGo')))));
  }
  if (ui.confirmClear) {
    return h('div', { class: 'col', style: 'gap:16px' },
      brandHeader(false),
      h('div', { class: 'card col' },
        h('h3', {}, t('clearAll')),
        h('div', { class: 'warn-box' }, t('clearAllWarn')),
        h('div', { class: 'row gap6' },
          h('button', { class: 'btn-ghost grow', onClick: () => { ui.confirmClear = false; render(); } }, t('back')),
          h('button', { class: 'btn-primary grow', onClick: clearAll }, t('clearAll'))
        )
      )
    );
  }
  if (ui.confirmRemove) {
    const acc = accounts.find((a) => a.id === ui.confirmRemove);
    return h('div', { class: 'col', style: 'gap:16px' },
      brandHeader(false),
      h('div', { class: 'card col' },
        h('h3', {}, t('removeWalletTitle')),
        h('div', { class: 'warn-box' }, t('removeWalletWarn', { name: acc ? seedName(acc) : '' })),
        h('div', { class: 'row gap6' },
          h('button', { class: 'btn-ghost grow', onClick: () => { ui.confirmRemove = null; render(); } }, t('back')),
          h('button', { class: 'btn-primary grow', onClick: () => { const id = ui.confirmRemove; ui.confirmRemove = null; removeAccount(id); } }, t('remove'))
        )
      )
    );
  }
  return h(
    'div',
    { class: 'col', style: 'gap:16px' },
    // Reached from an open wallet this is a page, not a boot screen — the
    // header icons (search, messages, settings, lock, avatar) stay put.
    // Cold boot lands here with nothing loaded yet, and then they hide.
    brandHeader(!!activeAccount()),
    h('div', { class: 'card col' },
      h('h3', {}, t('accounts')),
      h('div', { class: 'col', style: 'gap:0' },
        // Grouped by whose they are. Three signed-in identities used to give
        // three rows all called "Savings", indistinguishable from each other
        // and from duplicates — the wallets are per-identity, so the screen
        // has to say which identity.
        ...groupAccounts().flatMap(({ pk, rows }) => [
          identityHeading(pk),
          ...rows.flatMap((a) => viewsOf(a).map((view) => {
          const isActive = a.id === activeId && accountSel() === view;
          const netTag = a.network && a.network !== 'mainnet' ? ' · ' + a.network : '';
          const seedTag = '';
          const tag = (a.type === 'watch' ? ' · ' + t('watchOnlyTag') : '') + netTag + seedTag;
          if (ui.editId === a.id && ui.editView === view) {
            return h('div', { class: 'row gap6', style: 'padding:10px 0; border-bottom:1px solid var(--line)' },
              h('input', { type: 'text', style: 'flex:1', value: ui.editLabel, autofocus: true,
                onInput: (e) => (ui.editLabel = e.target.value),
                onKeyDown: (e) => { if (e.key === 'Enter') renameAccount(a.id); } }),
              h('button', { class: 'btn-sm', onClick: () => renameAccount(a.id) }, t('save')),
              h('button', { class: 'btn-sm', onClick: () => { ui.editId = null; render(); } }, t('back'))
            );
          }
          return h('div', { class: 'col', style: 'gap:4px; padding:10px 0; border-bottom:1px solid var(--line)' },
            h('div', { class: 'row between' },
              h('button', {
                class: 'linklike', style: 'text-align:left;flex:1;font-size:15px;' + (isActive ? 'font-weight:600' : ''),
                onClick: () => switchToView(a.id, view),
              }, (isActive ? '● ' : '○ ') + viewLabel(a, view) + tag),
              h('button', { class: 'btn-sm wallet-row-btn', title: t('renameWallet'), onClick: () => { ui.editId = a.id; ui.editView = view; ui.editLabel = viewLabel(a, view); render(); } }, '✎'),
              h('button', { class: 'btn-sm wallet-row-btn', title: t('walletSettings'), onClick: () => openAccountSettings(a.id), html: '<svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:block"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg>' }),
              h('button', { class: 'btn-sm wallet-row-btn', title: t('remove'), onClick: () => { ui.confirmRemove = a.id; render(); }, html: '<svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:block"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/><line x1="10" y1="11" x2="10" y2="17"/><line x1="14" y1="11" x2="14" y2="17"/></svg>' })
            ),
            a.type === 'full' && view === viewsOf(a)[viewsOf(a).length - 1]
              ? h('button', { class: 'linklike small', style: 'align-self:flex-start', onClick: () => (a.persisted ? startForget(a.id) : startSave(a.id)) },
                  a.persisted ? t('forgetDevice') : t('saveDevice'))
              : null
          );
        })),
        ])
      ),
      h('button', { class: 'btn-block', onClick: () => { ui.addWallet = { kind: 'spending', from: 'new' }; render(); } }, t('addWallet')),
      h('button', { class: 'btn-block', onClick: signInAnother }, t('signInAnother')),
      lockBtn(),
      activeAccount() ? h('button', { class: 'btn-ghost btn-block', onClick: () => { ui.logoutConfirm = true; render(); } }, t('logout')) : null,
      hasVault() && !vaultPasskey() ? h('button', { class: 'btn-ghost btn-block', onClick: startChangePw }, t('changePassword')) : null,
      h('button', { class: 'btn-ghost btn-block', onClick: () => { ui.confirmClear = true; render(); } }, t('clearAll'))
    ),
    h('button', { class: 'btn-ghost btn-block', onClick: () => goBack(() => { ui.screen = 'wallet'; }) }, t('back'))
  );
}

// The accounts on this device, gathered under the identity each belongs to,
// in the order they first appear.
function groupAccounts() {
  const out = [];
  const byPk = new Map();
  for (const a of accounts) {
    const pk = identityPkOf(a) || 'none';
    if (!byPk.has(pk)) { const g = { pk: pk === 'none' ? null : pk, rows: [] }; byPk.set(pk, g); out.push(g); }
    byPk.get(pk).rows.push(a);
  }
  return out;
}

// Who a group of wallets belongs to: their face and name, and a mark when
// it's the identity you're currently using. One identity on the device needs
// no heading at all — there's nothing to tell apart.
// Tapping the identity signs you in as it (its first wallet) and opens its
// profile page — the URL used to take the npub while the list stayed put,
// because the profile only paints over the wallet screen.
function openIdentityProfile(pk) {
  const g = groupAccounts().find((x) => x.pk === pk);
  const first = g && g.rows[0];
  if (first && first.id !== activeId) {
    clearFeatureNav();
    activateAccount(first, { fresh: true }); // the screen flip and feature init are synchronous
  } else { clearFeatureNav(); ui.screen = 'wallet'; }
  featureHook('openProfile', pk);
  render();
}
function identityHeading(pk) {
  if (!pk || groupAccounts().length < 2) return null;
  const me = ctx.shownPubkey && ctx.shownPubkey();
  const chip = featureHook('profileChip', pk, undefined, () => openIdentityProfile(pk));
  return h('div', {
    class: 'row gap6',
    style: 'align-items:center;padding:10px 0 4px;border-bottom:1px solid var(--line)',
  },
    chip || h('span', { class: 'small muted' }, (npubOf(pk) || pk).slice(0, 14) + '…'),
    pk === me ? h('span', { class: 'tag conf', style: 'margin-left:auto' }, t('accountsThisOne')) : null);
}

function renameAccount(id) {
  const acc = accounts.find((a) => a.id === id);
  if (acc) {
    const v = (ui.editLabel || '').trim();
    if (v) {
      // names belong to the VIEW now — Spending and Savings rename separately
      acc.viewLabels = { ...(acc.viewLabels || {}), [ui.editView || accountSel()]: v };
      persistAccounts();
      if (acc.persisted) writeVault();
    }
  }
  ui.editId = null;
  render();
}

// Open the per-wallet settings page for an account.
function openAccountSettings(id) {
  ui.settingsId = id;
  ui.editLabel = null;
  ui.revealShown = false;
  ui.pubkeyShown = false;
  ui.loadSeed = null;
  ui.screen = 'accountSettings';
  render();
}

// Per-wallet settings cards, shared by the per-account screen (Accounts → ⚙)
// and the main Settings tab (which inlines them for the active wallet).

function recoveryCard(a) {
  const isWatch = a.type === 'watch' || (!a.mnemonic && !a.xprv);
  const shown = ui.revealShown;
  const words = a.mnemonic ? a.mnemonic.split(' ') : [];
  if (isWatch) {
    return ui.loadSeed && ui.loadSeed.accId === a.id
      ? loadSeedCard()
      : h('div', { class: 'card col' },
          h('h3', {}, t('recoveryPhrase')),
          h('p', { class: 'small muted', style: 'margin:0' }, t('watchOnlyNote')),
          a.xpub
            ? h('button', { class: 'btn-primary btn-block', style: 'margin-top:4px', onClick: () => startLoadSeed({ accId: a.id }) }, t('loadSeedBtn'))
            : null
        );
  }
  if (!a.mnemonic)
    return h('div', { class: 'card col' }, h('h3', {}, t('importedKey')), h('p', { class: 'small muted', style: 'margin:0' }, t('importedKeyNote')));
  // Two steps on purpose. The first opens the card, with the words masked —
  // so the grid is on screen and you can see how much of it there is (and get
  // a warning) before anything readable is over your shoulder. The second
  // actually shows them.
  if (!shown)
    return h('div', { class: 'card col' },
      h('h3', {}, t('recoveryPhrase')),
      h('p', { class: 'small muted', style: 'margin:0' }, t('recoveryDesc')),
      h('button', { class: 'btn-block', onClick: () => { ui.revealShown = 'masked'; render(); } }, t('revealRecovery')));
  const unmasked = shown === 'words';
  return h('div', { class: 'card col' },
    h('h3', {}, t('recoveryPhrase')),
    h('div', { class: 'warn-box' }, t('recoveryWarn')),
    h('div', { class: 'words', style: '--rows-3:' + Math.ceil(words.length / 3) + ';--rows-2:' + Math.ceil(words.length / 2) }, words.map((w, i) =>
      h('div', { class: 'w' + (unmasked ? '' : ' masked') },
        h('span', { class: 'n' }, i + 1),
        h('span', { class: 't' }, unmasked ? w : '••••••')))),
    unmasked && a.passphrase
      ? h('div', { class: 'col gap6' }, h('span', { class: 'lab' }, t('bip39Passphrase')), h('div', { class: 'addr-box' }, a.passphrase))
      : null,
    unmasked
      ? h('div', { class: 'row gap6 wrap' },
          copyBtn(a.mnemonic, t('copyPhrase')),
          a.passphrase ? copyBtn(a.passphrase, t('copyPassphrase')) : null,
          h('button', { class: 'btn-sm grow', onClick: () => { ui.revealShown = false; render(); } }, t('hide')))
      : h('div', { class: 'row gap6' },
          h('button', { class: 'btn-primary grow', onClick: () => {
            ui.revealShown = 'words';
            // seeing it here counts: no need to be asked again elsewhere
            markSeedSeen(a);
            render();
          } }, t('revealWords')),
          // the same size as its neighbour: two halves of one row, not a
          // big button with a small one tucked beside it
          h('button', { class: 'btn-ghost grow', onClick: () => { ui.revealShown = false; render(); } }, t('hide')))
  );
}

function walletNameCard(a) {
  const saveName = () => {
    const v = (ui.editLabel || '').trim();
    if (v && v !== a.label) { a.label = v; persistAccounts(); if (a.persisted) writeVault(); }
    ui.editLabel = null;
    render();
  };
  return h('div', { class: 'card col' },
    h('h3', {}, t('walletName')),
    h('div', { class: 'row gap6' },
      h('input', { type: 'text', style: 'flex:1', value: ui.editLabel != null ? ui.editLabel : a.label,
        onInput: (e) => { ui.editLabel = e.target.value; },
        onKeyDown: (e) => { if (e.key === 'Enter') saveName(); } }),
      h('button', { class: 'btn-sm', onClick: saveName }, t('save'))
    )
  );
}

function pubkeyCard(a) {
  let zpub = '';
  try { if (a.xpub) zpub = xpubToZpub(a.xpub); } catch {}
  return h('div', { class: 'card col' },
    h('h3', {}, t('publicKey')),
    h('p', { class: 'small muted', style: 'margin:0' }, t('publicKeyDesc')),
    ui.pubkeyShown
      ? h('div', { class: 'col gap6' },
          h('div', { class: 'addr-box break', style: 'font-size:12px' }, zpub),
          h('div', { class: 'row gap6 wrap' },
            copyBtn(zpub, t('copyKey')),
            h('button', { class: 'btn-sm grow', onClick: () => { ui.pubkeyShown = false; render(); } }, t('hide'))))
      : h('button', { class: 'btn-block', onClick: () => { ui.pubkeyShown = true; render(); } }, t('showPublicKey'))
  );
}

function autolockCard(a) {
  return h('div', { class: 'card col' },
    h('h3', {}, t('autolockTitle')),
    h('p', { class: 'small muted', style: 'margin:0' }, t('autolockDesc')),
    h('select', { onChange: (e) => { a.autoLock = Number(e.target.value) || 0; persistAccounts(); if (a.persisted) writeVault(); render(); } },
      AUTOLOCK_OPTIONS.map((o) => h('option', { value: String(o.ms), selected: o.ms === accAutoLock(a) }, t(o.label))))
  );
}

// The balance card's gear: one face's settings. Spending leads with its
// coins (renewal, the cooperative move, a unilateral exit and what it costs);
// both carry the lock, the password and the recovery phrase that used to sit
// on the Accounts page.
function openWalletSettings(view) {
  clearFeatureNav();
  ui.settingsId = activeId;
  ui.settingsView = view || accountSel();
  ui.editLabel = null; ui.revealShown = false; ui.pubkeyShown = false; ui.loadSeed = null;
  ui.screen = 'accountSettings';
  render();
  try { window.scrollTo(0, 0); } catch {}
}
function securityCard() {
  if (!activeAccount()) return null;
  // With a nostr identity, signing in elsewhere and logging out live on your
  // profile; a wallet without one (an old watch-only) has no profile, so
  // they live here.
  const anon = !headerIdentity();
  return h('div', { class: 'card col', style: 'gap:8px' },
    h('h3', {}, t('securityTitle')),
    lockBtn(),
    passkeyLockRow(),
    hasVault() && !vaultPasskey() ? h('button', { class: 'btn-ghost btn-block', onClick: startChangePw }, t('changePassword')) : null,
    anon ? h('button', { class: 'btn-block', onClick: signInAnother }, t('signInAnother')) : null,
    anon ? h('button', { class: 'btn-ghost btn-block', onClick: () => { ui.logoutConfirm = true; render(); } }, t('logout')) : null);
}
// Settings → Security: lock with a passkey, or say that it is and offer the
// way back. Only where the browser does passkeys at all.
function passkeyLockRow() {
  if (vaultPasskey()) {
    return h('div', { class: 'col', style: 'gap:6px' },
      h('div', { class: 'small muted' }, '\u{1F510} ' + t('passkeyLockOnNote')),
      h('button', { class: 'btn-ghost btn-block', onClick: disablePasskeyLock }, t('passkeyLockOff')));
  }
  if (typeof window === 'undefined' || !window.PublicKeyCredential || !navigator.credentials) return null;
  return h('div', { class: 'col', style: 'gap:6px' },
    h('button', { class: 'btn-block', onClick: () => enablePasskeyLock() }, '\u{1F510} ' + t('passkeyLockBtn')),
    h('div', { class: 'small muted' }, t('passkeyLockDesc')));
}
function accountSettingsScreen() {
  if (ui.pw) return h('div', { class: 'col', style: 'gap:16px' }, brandHeader(false), pwPromptCard());
  if (ui.logoutConfirm) return logoutConfirmScreen();
  const a = accounts.find((x) => x.id === ui.settingsId) || activeAccount();
  if (!a) { ui.screen = 'accounts'; return accountsScreen(); }
  const view = ui.settingsView || accountSel();
  const spending = view === 'spending' && a.id === activeId;
  const leave = () => { ui.editLabel = null; ui.revealShown = false; ui.pubkeyShown = false; ui.loadSeed = null; goBack(() => { ui.screen = 'wallet'; }); };
  return h(
    'div',
    { class: 'col', style: 'gap:16px' },
    brandHeader(!!activeAccount()),
    h('div', { class: 'row gap6', style: 'align-items:center;margin:2px 0 -4px 4px' },
      h('span', { style: 'display:flex;color:var(--muted)', html: GEAR_ICON(20) }),
      h('h3', { style: 'margin:0' }, viewLabel(a, view))),
    spending ? featureHook('spendingSettings') : null,
    securityCard(),
    recoveryCard(a),
    view === 'spending' ? null : pubkeyCard(a),
    autolockCard(a),
    h('button', { class: 'btn-ghost btn-block', onClick: leave }, t('back'))
  );
}

// Wipe every wallet from this device: session accounts, the encrypted vault,
// and saved watch-only accounts. Unbacked-up seeds are unrecoverable after this.
function clearAll() {
  // Forget means forget: cached balances, history and feature state go with
  // the seeds (best effort — a still-locked vault's mnemonic-keyed caches
  // can't be found without its password; the xpub-keyed ones still match).
  for (const a of [...accounts, ...loadWatchAccounts()]) wipeAccountCache(a);
  try { localStorage.removeItem(VAULT_KEY); } catch {}
  try { localStorage.removeItem(WATCH_KEY); } catch {}
  ui.confirmClear = false;
  lock();
  featureHook('forgetAll'); // discard encrypted sync recovery copies too
}

function pwPromptCard() {
  const p = ui.pw;
  const change = p.purpose === 'change';
  const atLock = p.purpose === 'lock';
  const newish = change || p.mode === 'set'; // entering a (new) password with confirm
  const atLockSave = p.purpose === 'locksave'; // locking, but the vault needs its password first
  // opening the vault when a passkey, not a password, is what locks it
  const byPasskey = p.mode === 'enter' && !change && p.purpose !== 'passkeyOn' && !!vaultPasskey();
  return h('div', { class: 'card col' },
    h('h3', {}, atLock ? t('lockPwTitle') : atLockSave ? t('lockWallet') : change ? t('changePassword') : p.mode === 'set' ? t('setPassword') : t('enterPassword')),
    h('p', { class: 'small muted', style: 'margin:0' },
      atLock ? t('lockPwDesc') : change ? t('changePasswordDesc') : byPasskey ? t('passkeyEnterDesc') : atLockSave ? t('lockSaveDesc') : p.mode === 'set' ? t('setPasswordDesc') : t('enterPasswordDesc')),
    // the padlock's offer: a fingerprint or face instead of a password
    atLock && window.PublicKeyCredential ? h('button', { class: 'btn-primary btn-block', onClick: () => enablePasskeyLock({ lockAfter: true }) }, '\u{1F510} ' + t('passkeyLockBtn')) : null,
    atLock && window.PublicKeyCredential ? h('div', { class: 'small muted', style: 'text-align:center' }, t('lockPwOrPassword')) : null,
    byPasskey ? h('button', { class: 'btn-primary btn-block', onClick: submitPwWithPasskey }, '\u{1F510} ' + t('passkeyUnlock')) : null,
    change ? h('input', { type: 'password', placeholder: t('currentPassword'), value: p.v0, onInput: (e) => (p.v0 = e.target.value) }) : null,
    byPasskey ? null : h('input', { type: 'password', placeholder: newish ? t('passwordOptional') : t('password'), value: p.v1, onInput: (e) => (p.v1 = e.target.value) }),
    newish ? h('input', { type: 'password', placeholder: t('confirmPassword'), value: p.v2, onInput: (e) => (p.v2 = e.target.value) }) : null,
    p.error && h('div', { class: 'notice err' }, p.error),
    h('div', { class: 'row gap6' },
      h('button', { class: 'btn-ghost grow', onClick: cancelPw }, atLock ? t('lockPwSkip') : t('back')),
      byPasskey ? null : h('button', { class: (atLock ? 'btn-ghost' : 'btn-primary') + ' grow', onClick: submitPw }, newish ? t('save') : atLockSave ? t('lockAction') : t('unlock'))
    )
  );
}

// A passkey-locked vault asks for the fingerprint as it opens — on the app's
// own start and on the padlock's tap, not right after you locked it; once,
// so a cancel leaves the button rather than a loop.
function vaultScreen() {
  const byPasskey = !!vaultPasskey();
  if (ui.passkeyAsk) {
    ui.passkeyAsk = false;
    if (byPasskey) setTimeout(() => { if (ui.screen === 'vault') unlockVaultWithPasskey(); }, 0);
  }
  return h(
    'div',
    { class: 'col', style: 'gap:16px' },
    brandHeader(false),
    h('div', { class: 'card col' },
      h('div', { class: 'row gap6', style: 'align-items:center' },
        h('span', { style: 'font-size:20px;line-height:1' }, '\u{1F512}'),
        h('h3', { style: 'margin:0' }, ui.justLocked ? t('lockedTitle') : t('unlockSaved'))),
      h('p', { class: 'small muted', style: 'margin:0' }, byPasskey ? t('passkeyLockedDesc') : ui.justLocked ? t('lockedDesc') : t('unlockSavedDesc')),
      byPasskey ? null : h('input', { type: 'password', placeholder: t('password'), value: ui.vaultPw,
        onInput: (e) => (ui.vaultPw = e.target.value), onKeyDown: (e) => { if (e.key === 'Enter') unlockVault(); } }),
      h('div', { class: 'row between', style: 'align-items:center;gap:10px' },
        h('span', { class: 'small muted', style: 'white-space:nowrap;flex-shrink:0' }, t('unlockForLabel')),
        h('select', { onChange: (e) => { ui.unlockFor = Number(e.target.value) || 0; } },
          UNLOCK_FOR_OPTIONS.map((o) => h('option', {
            value: String(o.ms),
            selected: (ui.unlockFor != null ? ui.unlockFor : Number(localStorage.getItem(UNLOCK_FOR_KEY)) || 0) === o.ms,
          }, t(o.label))))),
      ui.vaultError && h('div', { class: 'notice err' }, ui.vaultError),
      byPasskey
        ? h('button', { class: 'btn-primary btn-block', onClick: unlockVaultWithPasskey }, '\u{1F510} ' + t('passkeyUnlock'))
        : h('button', { class: 'btn-primary btn-block', onClick: unlockVault }, t('unlock')),
      byPasskey ? h('div', { class: 'small muted', style: 'text-align:center' }, t('passkeyLostHint')) : null,
      h('button', { class: 'btn-ghost btn-block', onClick: skipVault },
        loadWatchAccounts().length ? t('viewWithoutPassword') : t('useAnotherWallet'))
    )
  );
}

// ================================================================ onboarding
// First visit on a fresh device: a full-screen wizard — welcome, then either
// create/import a seed or sign in with nostr — that ends the moment a wallet
// exists, dropping the user into a plain on-chain wallet. Spending is opt-in:
// the same wizard machinery serves the "set up a spending account" flow
// (username, avatar, confetti), but only when the user asks for it from the
// balance card. Shown whenever the device has no wallet — deleting every
// wallet brings it back. The current step is persisted so a refresh (or the
// legacy-migration round trip) resumes exactly where it left off.
const ONB_STEP_KEY = 'btc-wallet-onb-step';
// Set by the /migrate link (read at boot, next to /pos): open the coinos.io
// migration page as soon as this device can offer it.
const MIGRATE_LINK_KEY = 'btc-wallet-migrate-link';
function migrateLinkPending() {
  try {
    const at = Number(localStorage.getItem(MIGRATE_LINK_KEY));
    if (at && Date.now() - at < 86_400_000) return true;
    localStorage.removeItem(MIGRATE_LINK_KEY);
  } catch {}
  return false;
}
function endMigrateLink() {
  try { localStorage.removeItem(MIGRATE_LINK_KEY); } catch {}
}
function onbInProgress() {
  try { return !!localStorage.getItem(ONB_STEP_KEY); } catch { return false; }
}
function shouldOnboard() {
  return accounts.length === 0 && !hasVault();
}

const PUNK_PICKS = [7, 14, 21, 3, 33, 40, 47, 36, 61, 26, 12, 50];
// The value the wizard publishes is always the full-size art — that URL
// becomes this person's picture on every nostr client. The tiles in the
// picker are 56px, so they load the small copies.
const punkImg = (n) => `punks/${n}.webp`;
const punkTile = (n) => assetUrl(`punks-sm/${n}.webp`);
// Default covers (static/covers, Unsplash nature shots — see CREDITS.txt):
// published full size (1500x500), previewed from the 750px copies. Like the
// punk, a pubkey that never picks one still gets its own by default.
const COVER_COUNT = 12;
const coverImg = (n) => `covers/${n}.webp`;
const coverPreview = (n) => assetUrl(`covers-sm/${n}.webp`);
const defaultCover = (pk) => (pk ? parseInt(pk.slice(-6, -2), 16) % COVER_COUNT : 0) + 1;

async function onbUpload(file) {
  const fd = new FormData();
  fd.append('file', file);
  const endpoint = 'https://nostr.build/api/v2/upload/files';
  const authorization = await nip98Header({ signEvent: (event) => wallet.nostrSign(event) }, endpoint, 'POST');
  const response = await fetch(endpoint, {
    method: 'POST', body: fd, headers: { authorization }, signal: AbortSignal.timeout(60_000),
  });
  let body = null;
  try { body = await response.json(); } catch {}
  const url = response.ok && body?.data?.[0]?.url;
  if (!url) throw new Error(t('onbUploadFailed'));
  return url;
}

// ui.mediaProgress = { stage: 'shrink' | 'upload', pct } while a picture or
// video is on its way; the composers draw it as a bar under the field.
// A render per whole percent, no more.
function mediaProgress(stage, fraction) {
  const pct = Math.max(0, Math.min(100, Math.floor(fraction * 100)));
  const cur = ui.mediaProgress;
  if (cur && cur.stage === stage && cur.pct === pct) return;
  ui.mediaProgress = { stage, pct };
  render();
}
async function publicMediaUpload(file) {
  try {
    // a phone video is shrunk on the device first (see video-compress.js)
    if (/^video\//.test(file?.type || '')) {
      mediaProgress('shrink', 0);
      const { compressVideo } = await import('./video-compress.js');
      file = await compressVideo(file, (p) => mediaProgress('shrink', p));
    }
    mediaProgress('upload', 0);
    return await uploadPublicMedia(file, (event) => wallet.nostrSign(event), { onProgress: (p) => mediaProgress('upload', p) });
  } catch (error) {
    if (error instanceof MediaUploadError && error.code === 'too-big') throw new Error(t('mediaUploadTooBig'));
    if (error instanceof MediaUploadError && error.code === 'unsupported') throw new Error(t('mediaUploadUnsupported'));
    throw new Error(t('msgUploadFailed'));
  } finally {
    ui.mediaProgress = null;
  }
}

// Whether the wizard can offer Spending at all: an Ark-capable build on a
// network with the names registrar, for a full (signing) account. Elsewhere
// the offer would be a spinner that never resolves.
function canOfferSpending() {
  const acc = activeAccount();
  if (!acc || acc.type !== 'full' || wallet.watchOnly) return false;
  if (!featureHook('arkReady')) return false;
  return featureHook('namesAvailable') === 'yes';
}
function onboardScreen() {
  if (!ui.onb) {
    let saved = null;
    try { saved = localStorage.getItem(ONB_STEP_KEY); } catch {}
    // a saved step past wallet creation only makes sense if the wallet is here
    if (saved && !['welcome', 'signin', 'seed', 'migrate'].includes(saved) && !activeAccount()) saved = 'welcome';
    // 'legacy-went' survives the coinos.io round trip: the user left for the
    // migrate page, so coming back must offer "I'm done, continue" — the
    // in-memory flag died with the navigation and left them looping.
    ui.onb = saved === 'legacy-went'
      ? { step: 'legacy', wentToLegacy: true, fromLink: migrateLinkPending() }
      // the /migrate link on a device with no wallet opens on the move's own
      // page, which says a wallet comes first — not an unexplained welcome
      : { step: saved || (!activeAccount() && migrateLinkPending() ? 'migrate' : 'welcome'), fromLink: saved === 'legacy' && migrateLinkPending() };
    if (saved === 'signin') ui.nostrLoginOpen = true; // reopen the login card
  }
  const o = ui.onb;
  // The wizard's whole job ends the moment a wallet exists: hand the user
  // their on-chain wallet, receive page up. A nostr login in flight holds
  // this: the wallet opens mid-login, but whether the wizard should even
  // continue (a restored account has onboarded elsewhere) isn't known until
  // the login finishes.
  if ((o.step === 'welcome' || o.step === 'seed' || o.step === 'signin')
      && ui.screen === 'wallet' && activeAccount() && !ui.nostrLoginBusy) {
    // A wallet that arrived by SIGN-IN has a recovery phrase its owner has
    // never seen. Show it once, here, while it still reads as part of
    // setting up — rather than leaving it buried in settings until the day
    // they lose the Google account and find out it was never a backup.
    // Handled further down, where page()/title() exist.
    const arrived = activeAccount();
    if (arrived && arrived.mnemonic && !arrived.seedSeen) o.step = 'backup';
    else if (canOfferSpending()) {
      // Before the home screen: one offer to set up Spending (a name and a
      // payment address), with Not now a single tap away.
      o.step = 'spend'; o.enterAddr = undefined;
    } else {
      ui.onb = null;
      try { localStorage.removeItem(ONB_STEP_KEY); } catch {}
      // On-chain first: the wizard's promise is "your keys, your coins", and
      // Spending stays out of sight until the user sets it up.
      ui.account = 'savings';
      try { localStorage.setItem(ACCOUNT_KEY, 'savings'); } catch {}
      ui.tab = 'receive';
      return null; // the caller falls through to the wallet itself
    }
  }
  // Arriving by the /migrate link: the coinos.io move it asked for, in place
  // of the Spending offer. Coming back from it is the ordinary wizard.
  if (o.step === 'spend' && migrateLinkPending()) { endMigrateLink(); o.step = 'legacy'; }
  if (o.step === 'spend') {
    const addr = featureHook('namesAddress');
    if (o.enterAddr === undefined) o.enterAddr = addr || null;
    const custom = !!addr && !/^npub1/.test(addr);
    // A custom name this page didn't claim is an account that set itself up
    // before: a wallet a sign-in restored, whose name the registrar handed
    // back (owned by the login identity or the wallet key). There is nothing
    // to claim — the form stood here anyway, suggesting a profile name, and
    // retyping the name one already had "claimed" it again and painted the
    // same page. Out of the wizard, into the wallet as it was.
    if (custom && !o.claimedHere) { leaveWizard(); return null; }
    // Only a real (custom) name advances by itself — the background
    // auto-claim of the npub-shaped default doesn't count as setting up.
    if (custom && addr !== o.enterAddr) {
      // The avatar ask is for brand-new profiles. An identity that already
      // wears a face (a nostr login with a published picture) skips straight
      // past the punk picker — restyling a real profile helps nobody.
      const me = (featureHook('nostrLoginIdentity') || {}).pubkey || (wallet.nostrPubkey && wallet.nostrPubkey());
      const prof = me ? featureHook('cachedProfile', me) : null;
      o.step = prof && prof.picture ? nextAfterAvatar() : 'avatar';
    }
  }
  try { localStorage.setItem(ONB_STEP_KEY, o.step === 'legacy' && o.wentToLegacy ? 'legacy-went' : o.step); } catch {}
  const page = (kids) => h('div', { class: 'col onb', style: 'gap:20px' }, ...kids);
  const title = (txt) => h('h2', { class: 'onb-title' }, txt);
  // After the identity niceties: offer a first top-up when Savings can fund
  // one and Spending is empty-handed — a spending account with nothing in it
  // is a demo, not a wallet.
  // A function declaration, not a const: the spend step above calls this
  // while advancing past the avatar ask, i.e. BEFORE this line runs — a
  // const there is in its temporal dead zone and threw "Cannot access
  // before initialization", crashing onboarding right after a name claim or
  // a coinos.io migration landed (a profile with a picture took this path).
  function nextAfterAvatar() {
    return (featureHook('arkReady') && wallet.spendable > 1000
      && (featureHook('spendingSat') || 0) + (featureHook('spendingBoardingSat') || 0) < 1000)
      ? 'board' : 'success';
  }

  if (o.step === 'legacy') {
    // The migrate link carries this wallet's payment address, which the
    // background claim may still be minting. Don't make the user watch that:
    // show the finished page and wait (on the button) only if they tap
    // before it lands.
    const goLegacy = async () => {
      let addr = featureHook('namesAddress');
      if (!addr) {
        o.legacyBusy = true;
        render();
        for (let i = 0; i < 40 && !addr; i++) {
          await new Promise((r) => setTimeout(r, 500));
          addr = featureHook('namesAddress');
        }
        o.legacyBusy = false;
        if (!addr) { ui.onbError = t('onbLegacyNoAddr'); render(); return; }
      }
      o.wentToLegacy = true;
      // persist NOW — location.href never comes back through a render
      try { localStorage.setItem(ONB_STEP_KEY, 'legacy-went'); } catch {}
      location.href = `https://coinos.io/migrate?to=${encodeURIComponent(addr)}&back=${encodeURIComponent(location.origin + '/')}`;
    };
    // A migrated name mid-claim (the ?migrated= return) paints as progress
    // here, not as the pristine ask the user just finished answering.
    const claiming = ui.migrating || pendingMigratedName();
    return page([
      title(t('onbLegacyTitle')),
      h('p', { class: 'muted', style: 'margin:0' },
        claiming ? t('migrateWorking', { name: claiming }) : t('onbLegacyBody')),
      claiming
        ? h('div', { class: 'row gap6', style: 'justify-content:center;padding:8px 0' }, h('span', { class: 'spinner' }))
        : h('button', {
            class: 'btn-primary btn-block', style: 'padding:14px',
            disabled: !!o.legacyBusy, onClick: goLegacy,
          }, o.legacyBusy ? h('span', { class: 'spinner sm' }) : t('onbLegacyGo')),
      h('button', { class: 'btn-block', style: 'padding:14px', onClick: () => {
        // an existing wallet sent here by the /migrate link has nothing
        // left to set up: out of the wizard, back to the wallet
        if (o.fromLink) { endMigrateLink(); leaveWizard(); } else o.step = 'spend';
        render();
      } },
        o.wentToLegacy || claiming ? t('onbLegacyDone') : t('back')),
      ui.onbError ? h('div', { class: 'notice err' }, ui.onbError) : null,
    ]);
  }
  // Making your own keys: the words are the wallet, so show them at once,
  // no Generate to tap.
  const startCreate = () => {
    ui.unlockTab = 'create';
    ui.unlockError = '';
    ui.createStep = 'gen';
    if (!ui.draftMnemonic) ui.draftRandom = ui.draftMnemonic = newMnemonic();
    o.step = 'seed';
    render();
  };
  // All the sign-in doors (Google, passkey, Nostr) — the feature supplies
  // them; the single-button fallback keeps builds without it working.
  const signinDoors = () => featureHook('frontDoorSignin')
    || h('button', { class: 'btn-block', style: 'padding:14px', onClick: () => {
      o.step = 'signin';
      ui.nostrLoginOpen = true;
      render();
    } }, h('span', { style: 'display:flex;align-items:center;justify-content:center;gap:8px' },
      h('span', { style: 'display:flex;flex-shrink:0', html: NOSTR_MARK }),
      t('nlSignIn')));
  if (o.step === 'welcome') {
    return page([
      h('div', { class: 'onb-hero' }, brandHeader(false)),
      title(t('onbWelcomeTitle')),
      // Making your own keys is the path; a sign-in is the alternative,
      // below the line.
      h('button', {
        // a stable hook for tests, so this button survives its own copy
        id: 'onb-create',
        class: 'btn-primary btn-block', style: 'font-size:17px;padding:14px', onClick: startCreate,
      }, t('onbStart')),
      h('div', { class: 'onb-or' }, h('span', {}, t('onbOrSignIn'))),
      signinDoors(),
      // The move from the original coinos.io used to wait behind the
      // Spending offer, where nobody looking for it found it. Its own door
      // on the front page: it stashes the intent the /migrate link stashes
      // (the move needs a wallet and a payment address first) and explains
      // that before any twelve words appear.
      h('button', { id: 'onb-migrate', class: 'btn-block', style: 'padding:14px', onClick: () => {
        try { localStorage.setItem(MIGRATE_LINK_KEY, String(Date.now())); } catch {}
        ui.onbError = '';
        o.step = 'migrate';
        render();
      } }, t('onbMigrateDoor')),
      ui.onbError ? h('div', { class: 'notice err' }, ui.onbError) : null,
    ]);
  }
  if (o.step === 'migrate') {
    // The intent is kept across whichever way in they pick: once a wallet
    // exists, the Spending offer gives way to the coinos.io move (above).
    return page([
      h('div', { class: 'onb-hero' }, brandHeader(false)),
      title(t('onbLegacyTitle')),
      h('p', { class: 'muted', style: 'margin:0' }, t('onbMigrateIntro')),
      h('button', {
        id: 'onb-migrate-create',
        class: 'btn-primary btn-block', style: 'font-size:17px;padding:14px', onClick: startCreate,
      }, t('onbMigrateCreate')),
      h('div', { class: 'onb-or' }, h('span', {}, t('onbOrSignIn'))),
      signinDoors(),
      h('button', { class: 'linklike small', onClick: () => { endMigrateLink(); ui.onbError = ''; o.step = 'welcome'; render(); } }, t('back')),
      ui.onbError ? h('div', { class: 'notice err' }, ui.onbError) : null,
    ]);
  }
  if (o.step === 'backup') {
    const acc = activeAccount();
    // the wallet went away (switched, logged out) — nothing to back up
    if (!acc || !acc.mnemonic) { ui.onb = null; try { localStorage.removeItem(ONB_STEP_KEY); } catch {} return null; }
    const words = acc.mnemonic.split(' ');
    const done = () => {
      markSeedSeen(acc);
      if (canOfferSpending()) { o.step = 'spend'; o.enterAddr = undefined; render(); return; }
      ui.onb = null;
      try { localStorage.removeItem(ONB_STEP_KEY); } catch {}
      ui.account = 'savings';
      try { localStorage.setItem(ACCOUNT_KEY, 'savings'); } catch {}
      ui.tab = 'receive';
      render();
    };
    return page([
      title(t('onbBackupTitle')),
      h('p', { class: 'muted', style: 'margin:0' }, t('onbBackupBody')),
      h('div', { class: 'warn-box' }, t('writeDownWarn')),
      h('div', { class: 'words', style: '--rows-3:' + Math.ceil(words.length / 3) + ';--rows-2:' + Math.ceil(words.length / 2) }, words.map((w, i) =>
        h('div', { class: 'w' }, h('span', { class: 'n' }, i + 1), h('span', { class: 't' }, w)))),
      h('div', { class: 'row gap6' }, copyBtn(acc.mnemonic, t('copyPhrase'))),
      h('button', { class: 'btn-primary btn-block', style: 'padding:14px', onClick: done }, t('onbBackupDone')),
      // Later means later, not never: seedSeen stays false, so the wallet
      // keeps a quiet reminder until the phrase has actually been seen.
      // Except on the way to a coinos.io move: the balance about to arrive
      // must have its twelve words written down first, so Later isn't offered.
      migrateLinkPending() ? null : h('button', { class: 'btn-ghost btn-block', onClick: () => {
        if (canOfferSpending()) { o.step = 'spend'; o.enterAddr = undefined; render(); return; }
        ui.onb = null;
        try { localStorage.removeItem(ONB_STEP_KEY); } catch {}
        ui.account = 'savings';
        try { localStorage.setItem(ACCOUNT_KEY, 'savings'); } catch {}
        ui.tab = 'receive';
        render();
      } }, t('onbBackupLater')),
    ]);
  }
  if (o.step === 'seed') {
    // The classic create/import card, inside the wizard: getting started
    // means seeing (or bringing) your seed phrase, not a wallet minted
    // behind your back. Opening one ends the wizard into the wallet + tour.
    return page([
      title(t('onbSeedTitle')),
      unlockCard(),
      // the entropy page brings its own Back — one is enough
      ui.entropyPage ? null : h('button', { class: 'linklike small', onClick: () => { ui.unlockError = ''; o.step = 'welcome'; render(); } }, t('back')),
    ]);
  }
  if (o.step === 'signin') {
    return page([
      h('div', { class: 'onb-mark', html: NOSTR_MARK }),
      title(t('onbSigninTitle')),
      featureHook('unlockExtra') || h('div', { class: 'notice err' }, 'nostr login unavailable'),
      h('button', { class: 'linklike small', onClick: () => { o.step = 'welcome'; render(); } }, t('back')),
    ]);
  }
  if (o.step === 'spend') {
    return page([
      title(t('onbSpendTitle')),
      h('p', { class: 'muted', style: 'margin:0' }, t('onbSpendBody')),
      featureHook('namesClaimForm') || h('div', { class: 'row gap6', style: 'align-items:center' }, h('span', { class: 'spinner sm' }), h('span', { class: 'small muted' }, t('onbNameWait'))),
      // Optional means optional: one tap to the wallet, no questions — on
      // Savings, the account that exists without any setup.
      h('button', { class: 'btn-ghost btn-block', onClick: () => {
        ui.onb = null;
        try { localStorage.removeItem(ONB_STEP_KEY); } catch {}
        ui.account = 'savings';
        try { localStorage.setItem(ACCOUNT_KEY, 'savings'); } catch {}
        ui.tab = 'receive';
        render();
      } }, t('onbNotNow')),
    ]);
  }
  if (o.step === 'avatar') {
    const me = (featureHook('nostrLoginIdentity') || {}).pubkey || (wallet.nostrPubkey && wallet.nostrPubkey());
    const sel = o.avatar;
    // The big avatar IS the selection: it shows exactly what Continue will
    // publish — a picked punk, an upload, or the pubkey-derived default.
    const preview = sel || (me ? punkUrl(me) : null);
    // ...and the cover behind it the same: a default (number) or an upload
    // (URL). Untouched, it is this pubkey's default cover.
    const cover = o.cover ?? defaultCover(me);
    const coverN = typeof cover === 'number' ? cover : null;
    const step = (d) => {
      const from = coverN ?? (o.coverLast || defaultCover(me));
      o.cover = ((from - 1 + d + COVER_COUNT) % COVER_COUNT) + 1;
      o.coverLast = o.cover;
      render();
    };
    // the neighbours load ahead, so cycling never shows a blank cover
    if (coverN) for (const d of [1, -1]) { const im = new Image(); im.src = coverPreview(((coverN - 1 + d + COVER_COUNT) % COVER_COUNT) + 1); }
    return page([
      title(t('onbAvatarTitle')),
      h('p', { class: 'muted', style: 'margin:0' }, t('onbAvatarBody')),
      h('div', { class: 'onb-look' },
        h('div', {
          class: 'onb-cover', role: 'group', 'aria-label': t('onbCover'),
          style: `background-image:url(${JSON.stringify(coverN ? coverPreview(coverN) : cover)})` + (ui.onbBusy ? ';opacity:.5' : ''),
          // on the wizard state, not this render's closure: a render mid-swipe
          // swaps the handlers, and the release must still see the press
          onPointerdown: (e) => { o.swipeX = e.clientX; },
          onPointerup: (e) => {
            if (o.swipeX == null) return;
            const dx = e.clientX - o.swipeX; o.swipeX = null;
            if (Math.abs(dx) > 40) step(dx < 0 ? 1 : -1);
          },
        },
          h('button', { type: 'button', class: 'onb-cover-nav prev', 'aria-label': t('onbCoverPrev'), onClick: () => step(-1) }, '‹'),
          h('button', { type: 'button', class: 'onb-cover-nav next', 'aria-label': t('onbCoverNext'), onClick: () => step(1) }, '›'),
          h('span', { class: 'onb-cover-count' }, coverN ? `${coverN} / ${COVER_COUNT}` : t('onbCoverYours')),
          h('button', { type: 'button', class: 'onb-cover-upload', disabled: ui.onbBusy, 'aria-label': t('onbCoverUpload'), title: t('onbCoverUpload'),
            onClick: () => document.getElementById('onb-cover-file')?.click(),
            html: '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" style="display:block"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><path d="M17 8l-5-5-5 5"/><path d="M12 3v12"/></svg>' }),
          h('input', { type: 'file', id: 'onb-cover-file', accept: 'image/*', style: 'display:none', onChange: async (e) => {
            const f = e.target.files && e.target.files[0];
            if (!f) return;
            ui.onbBusy = true; ui.onbError = ''; render();
            try { o.cover = await onbUpload(f); } catch (err) { ui.onbError = err.message; }
            ui.onbBusy = false; render();
          } })),
        preview ? h('img', {
          class: 'onb-avatar', src: /^(https?|data|blob):/i.test(preview) ? preview : assetUrl(preview), alt: '',
          style: ui.onbBusy ? 'opacity:.5' : '',
          onError: (e) => { e.target.style.visibility = 'hidden'; },
        }) : null),
      h('div', { class: 'onb-punks', 'data-keep-scroll': 'punks' },
        ...PUNK_PICKS.map((n) =>
          h('img', {
            class: 'onb-punk' + (sel === punkImg(n) ? ' sel' : ''),
            src: punkTile(n), alt: '',
            onClick: () => { o.avatar = punkImg(n); render(); },
            onError: (e) => { e.target.remove(); }, // a 502'd punk removes itself
          }))),
      h('div', { class: 'row gap6' },
        h('button', { class: 'btn-block grow', disabled: ui.onbBusy, onClick: () => document.getElementById('onb-file')?.click() }, t('onbUpload')),
        h('input', { type: 'file', id: 'onb-file', accept: 'image/*', style: 'display:none', onChange: async (e) => {
          const f = e.target.files && e.target.files[0];
          if (!f) return;
          ui.onbBusy = true; ui.onbError = ''; render();
          try { o.avatar = await onbUpload(f); } catch (err) { ui.onbError = err.message; }
          ui.onbBusy = false; render();
        } })),
      ui.onbError ? h('div', { class: 'notice err' }, ui.onbError) : null,
      h('button', { class: 'btn-primary btn-block', style: 'padding:14px', disabled: ui.onbBusy, onClick: async () => {
        ui.onbBusy = true; ui.onbError = ''; render();
        try {
          const addr = featureHook('namesAddress');
          // keeping the default still publishes it — their punk should be
          // their face on every nostr client, not just here. A picked punk is
          // a relative path; kind 0 needs the absolute URL (a relative one
          // once replaced a real profile picture with a broken string).
          const picked = o.avatar && !/^https?:/i.test(o.avatar) ? 'https://v3.coinos.io/' + o.avatar : o.avatar;
          const picture = picked || (me ? new URL(punkUrl(me), 'https://v3.coinos.io/').href : undefined);
          const banner = typeof cover === 'number' ? 'https://v3.coinos.io/' + coverImg(cover) : cover;
          const fields = { name: addr ? addr.split('@')[0] : undefined, picture, banner };
          // Publishing the profile is a nicety — a signer that can't sign
          // right now (a sleeping phone bunker) must not trap the wizard.
          // And it's an OFFER: the address-derived name (and, unless they
          // actually picked one, the default punk) only fills gaps — it
          // never renames an identity that already has a profile.
          if (fields.name || fields.picture) {
            // a cover they actually chose replaces one they had; the default only fills a gap
            const fillOnly = ['name', ...(o.avatar ? [] : ['picture']), ...(o.cover != null ? [] : ['banner'])];
            try { await featureHook('publishProfile', fields, { fillOnly }); }
            catch (e) { toast(t('onbProfileSkipped')); console.warn('onboarding: profile publish failed —', e.message); }
          }
          o.step = nextAfterAvatar();
        } catch (e) { ui.onbError = e.message; }
        ui.onbBusy = false; render();
      } }, ui.onbBusy ? h('span', { class: 'spinner sm' }) : (o.avatar ? t('onbContinue') : t('onbSkipAvatar'))),
      h('button', { class: 'btn-ghost btn-block', disabled: ui.onbBusy, onClick: () => {
        // re-anchor the spend step's "name changed" detector to the name
        // as it stands NOW, or a just-claimed name bounces us right back here
        o.enterAddr = featureHook('namesAddress') || null;
        o.step = 'spend'; render();
      } }, t('back')),
    ]);
  }
  if (o.step === 'board') {
    return page([
      title(t('onbBoardTitle')),
      h('p', { class: 'muted', style: 'margin:0' }, t('onbBoardBody')),
      featureHook('arkBoardForm')
        || h('div', { class: 'row gap6', style: 'align-items:center;justify-content:center' },
             h('span', { class: 'spinner sm' }), h('span', { class: 'small muted' }, t('arkConnecting'))),
      h('button', { class: 'btn-primary btn-block', style: 'padding:14px', onClick: () => { o.step = 'success'; render(); } }, t('onbContinue')),
    ]);
  }
  // success
  return page([
    h('div', { class: 'onb-confetti' }, ...Array.from({ length: 18 }, () => h('i'))),
    h('h2', { class: 'onb-title', style: 'text-align:center' }, t('onbDoneTitle')),
    h('div', { class: 'check-badge onb-check' }, '✓'),
    h('p', { class: 'muted', style: 'margin:0;text-align:center' }, t('onbDoneBody')),
    h('button', { class: 'btn-primary btn-block', style: 'padding:14px', onClick: () => {
      try { localStorage.removeItem(ONB_STEP_KEY); } catch {}
      ui.onb = null;
      // Latch Spending onto the account only when the wizard actually set it
      // up (a claimed address or funds prove it) — finishing the wizard on a
      // network without names, or skipping the spend step, must not conjure
      // a Spending wallet nobody asked for.
      const acc = activeAccount();
      // A name claimed DURING this wizard run (it differs from the address
      // recorded on entry) is explicit setup on any network — that's the user
      // opting in, not stale evidence. Otherwise the mainnet-only rule from
      // spendingActive applies: a stored mainnet name must not vouch for
      // spending on another network.
      const addr = featureHook('namesAddress');
      const named = !!addr && !/^npub1/.test(addr);
      const claimedNow = named && addr !== o.enterAddr;
      const spendReady = claimedNow || (featureHook('spendingSat') || 0) > 0
        || (getNetwork() === 'mainnet' && named);
      if (spendReady) {
        if (acc && !acc.spendingSetup) { acc.spendingSetup = Date.now(); persistAccounts(); featureHook('spendingEvident'); }
        ui.account = 'spending';
        try { localStorage.setItem(ACCOUNT_KEY, 'spending'); } catch {}
      }
      ui.tab = 'receive';
      render();
    } }, t('onbEnter')),
    h('button', { class: 'btn-ghost btn-block', onClick: () => { o.step = 'avatar'; render(); } }, t('back')),
  ]);
}

// Returning from the legacy migration: coinos.io sends ?migrated=<username>
// once it has swept the balance and released the name. The param is stashed
// SYNCHRONOUSLY at boot (module init below) because the claim itself needs
// an open wallet — which can arrive well after any single post-load timer.
// The old one-shot ("1.5s after load, if a wallet is active") silently
// dropped the whole hand-off whenever the wallet wasn't ready yet, and the
// user came back to a migrate page that had no idea they'd just migrated.
const MIGRATED_KEY = 'btc-wallet-migrated-name';
try {
  const _mu = new URL(location.href);
  const _mn = _mu.searchParams.get('migrated');
  if (_mn) {
    localStorage.setItem(MIGRATED_KEY, _mn);
    _mu.searchParams.delete('migrated');
    history.replaceState(null, '', _mu.pathname + _mu.search + _mu.hash);
  }
} catch {}
function pendingMigratedName() {
  try { return localStorage.getItem(MIGRATED_KEY); } catch { return null; }
}
function claimMigratedName() {
  const name = pendingMigratedName();
  if (!name || ui.migrating) return;
  ui.migrating = name;
  render();
  let tries = 0;
  const attempt = () => {
    const p = featureHook('namesClaimName', name);
    if (!p || !p.then) { if (++tries < 12) return setTimeout(attempt, 5000); ui.migrating = null; return; }
    p.then(async () => {
      try { localStorage.removeItem(MIGRATED_KEY); } catch {}
      // Bring the old account's face and cover along — filled into empty
      // kind-0 slots only. Bounded wait: the wizard's punk-picker skip
      // checks the cached picture right after this, and losing the race
      // would ask a migrated user to restyle the profile they already have.
      await Promise.race([
        Promise.resolve(featureHook('adoptLegacyProfile', name)).catch(() => {}),
        new Promise((r) => setTimeout(r, 5000)),
      ]);
      ui.migrating = null;
      // Mid-onboarding: the migrate step's job is done — move the wizard
      // along instead of re-offering the page that was just completed. A
      // null enterAddr lets the spend step see the claimed name as change
      // and advance on its own.
      if (ui.onb && ui.onb.step === 'legacy') {
        if (ui.onb.fromLink) { endMigrateLink(); leaveWizard(); }
        else { ui.onb.step = 'spend'; ui.onb.enterAddr = null; }
      }
      toast(t('migrateClaimed', { name }));
      render();
    })
      .catch(() => {
        // DNS/registrar caches the legacy lookup briefly; give it a minute
        if (++tries < 12) return setTimeout(attempt, 5000);
        try { localStorage.removeItem(MIGRATED_KEY); } catch {}
        ui.migrating = null;
        toast(t('migrateClaimFailed', { name }));
        render();
      });
  };
  attempt();
}

function leaveWizard() {
  ui.onb = null;
  try { localStorage.removeItem(ONB_STEP_KEY); } catch {}
}

function walletScreen() {
  // The /migrate link on a device that already has a wallet: the wizard's
  // migrate page, on its own, once the wallet can mint a payment address.
  if (!ui.onb && !onbInProgress() && activeAccount() && migrateLinkPending() && canOfferSpending()) {
    ui.onb = { step: 'legacy', fromLink: true };
  }
  if (ui.onb || onbInProgress()) {
    const s = onboardScreen();
    if (s) return s; // null = the wizard just handed over; fall through
  }
  // A feature can hold the wallet behind a required onboarding step (picking
  // a username). Imported wallets skip it once their name is recovered.
  const ob = featureHook('onboardingView');
  if (ob) {
    return h('div', { class: 'col', style: 'gap:0' }, brandHeader(false), h('div', { class: 'mt16' }, ob));
  }
  // Settings is a full page of its own — no balance, no tab strip; the hub's
  // back button (or the logo / avatar menu) leads out. Offline keeps the
  // classic layout: settings is the forced tab there, and hiding the balance
  // and tab strip would wall off the cached balance, history, and receive.
  if (ui.tab === 'settings' && !wallet.offline) {
    return h(
      'div',
      { class: 'col', style: 'gap:0' },
      brandHeader(true),
      ui.offlineFallback && wallet.offline ? offlineBanner() : null,
      h('div', { class: 'mt16' }, tabContent())
    );
  }
  // Tab changes slide the content pane sideways like a carousel — swipe
  // direction when a gesture caused it, index order for taps. The balance
  // card and tab strip stay planted.
  const TAB_ORDER = ['history', 'receive', 'send'];
  if (uiChanged('tabnav', ui.tab)) {
    const idx = TAB_ORDER.indexOf(ui.tab);
    // The pane slides only BETWEEN tabs the user has seen: the first
    // observation after a sign-in (and the handover render itself) is the
    // wallet simply appearing, not a navigation.
    if (!ui.navAnimSkip && _tabSeen) {
      _tabCls = 'anim-tab-' + (_swipeDir || (idx >= 0 && idx < _prevTabIdx ? 'right' : 'left'));
      _tabAt = performance.now();
    }
    _tabSeen = true;
    if (idx >= 0) _prevTabIdx = idx;
  }
  _swipeDir = null;
  const pane = h('div', { class: 'tab-pane' }, tabContent());
  const tabDt = performance.now() - _tabAt;
  // skip the pane slide while a full-page entrance is already running
  if (performance.now() - _navAt > 400) applyAnim(pane, _tabCls, tabDt < 300 ? tabDt : -1);
  return h(
    'div',
    { class: 'col', style: 'gap:0' },
    brandHeader(true),
    h('div', { class: 'mt16' }, balanceCard()),
    ui.offlineFallback && wallet.offline ? offlineBanner() : null,
    backupNotice(),
    ...featureAll('walletNotices'),
    tabsBar(),
    pane
  );
}

// The recovery phrase has been on screen: record it once, everywhere it
// counts. Every account on the same seed is covered (one phrase backs them
// all), the session and vault copies are written, and the wallet cache is
// saved so the flag rides the synced snapshot to every other device — a
// phrase read on the laptop shouldn't keep nagging on the phone. The
// directory entry carries it too (saveDirectory), so a silent sign-in that
// rebuilds the account on this device finds it before any sync arrives.
function markSeedSeen(a) {
  if (!a || a.seedSeen) return;
  const same = (x) => x.mnemonic && x.mnemonic === a.mnemonic && (x.passphrase || '') === (a.passphrase || '');
  for (const x of accounts) if (x === a || same(x)) x.seedSeen = true;
  persistAccounts();
  if (a.persisted) writeVault();
  try { wallet.saveCache(); } catch {}
}
// The flag's ride on the wallet snapshot (local cache and the synced copy).
// Commutative — it only ever turns on — so older snapshots merge too.
wallet.registerCacheExtension({
  mergeAlways: true,
  save: () => ((activeAccount() || {}).seedSeen ? { seedSeen: true } : {}),
  load: (d) => {
    if (!d || !d.seedSeen) return;
    const a = activeAccount();
    if (!a || !a.mnemonic || a.seedSeen) return;
    const same = (x) => x.mnemonic && x.mnemonic === a.mnemonic && (x.passphrase || '') === (a.passphrase || '');
    for (const x of accounts) if (x === a || same(x)) x.seedSeen = true;
    persistAccounts();
    if (a.persisted) writeVault();
    // no render here: a synced merge emits from the wallet, and a local
    // cache load is mid-activation, which paints when it's done
  },
});

// A wallet whose recovery phrase has never been on screen keeps one quiet
// line about it. "Later" is a real answer, so this is a row and not a modal —
// but it doesn't dismiss, because the risk doesn't go away on its own. It
// disappears the moment the phrase is actually seen (here or in settings).
function backupNotice() {
  const a = activeAccount();
  if (!a || !a.mnemonic || a.seedSeen || wallet.watchOnly) return null;
  return h('div', { class: 'small muted', style: 'margin:10px 0 0;text-align:center' },
    t('backupReminder'),
    ' ',
    h('button', { class: 'linklike small', onClick: () => {
      ui.tab = 'settings';
      ui.settingsPage = 'wallet';
      ui.revealShown = 'masked';
      render();
    } }, t('backupReminderGo')));
}

function offlineBanner() {
  return h(
    'div',
    { class: 'notice info row between', style: 'margin:12px 0 0' },
    h('span', {}, t('offlineBanner')),
    h('button', { class: 'btn-sm', onClick: retryOnline }, t('retry'))
  );
}

// ---- the global account selector -------------------------------------
// The wallet is always "in" one of its two balances: Spending (Ark +
// Lightning) or Savings (on-chain). The balance card headline, the Receive
// pane, and the gift source all follow it.
const ACCOUNT_KEY = 'btc-wallet-account';
// Spending is opt-in: a wallet is born on-chain only, and the second balance
// (with its toggle, swipe, and Move money) appears once the user sets it up —
// or the moment money is already there (a restored wallet, a claimed gift),
// because a balance must never hide. Setting up = claiming a username, so a
// name claimed anywhere counts; the account flag latches it for accounts
// whose name lookup isn't available right now.
function spendingActive() {
  if (!featureHook('arkReady')) return false;
  const acc = activeAccount();
  // A single-purpose spending wallet IS the opt-in — the user created it by
  // picking "Spending" in Add wallet; no further evidence required.
  if (acc?.kind === 'spending') return true;
  if (acc?.spendingSetup) {
    // Self-heal a flag latched by the old cross-network name leak: off
    // mainnet, a LEGACY boolean flag (`true` — the buggy era's value; every
    // deliberate latch since carries a timestamp) with zero balance and no
    // ark history was never really set up — drop it.
    if (acc.spendingSetup === true && getNetwork() !== 'mainnet' && !(featureHook('spendingSat') || 0)
        && !(featureHook('arkMovements') || []).length) {
      delete acc.spendingSetup;
      persistAccounts();
    } else {
      return true;
    }
  }
  // A claimed payment address proves spending on MAINNET only: names feature
  // state is stored per-wallet without a network, so a mainnet name would
  // otherwise conjure a Spending wallet on mutinynet nobody set up.
  const addr = getNetwork() === 'mainnet' ? featureHook('namesAddress') : null;
  const evident = (featureHook('spendingSat') || 0) > 0 || (!!addr && !/^npub1/.test(addr));
  // Latch demonstrated use onto the record, so the Wallets list keeps showing
  // this seed's Spending side even while it's locked or not the active one.
  if (evident && acc && !acc.spendingSetup) { acc.spendingSetup = Date.now(); persistAccounts(); featureHook('spendingEvident'); }
  return evident;
}
// ---- the flat wallet model -------------------------------------------------
// Each seed record surfaces as up to two TOP-LEVEL wallets: its Spending (Ark)
// and Savings (on-chain) sides. A record with a fixed `kind` (single-purpose,
// possibly sharing another wallet's seed at a higher BIP84 account) surfaces
// once. "Spending" and "Savings" are the default names; renames are per-view.
function viewsOf(a) {
  if (!a) return [];
  if (a.kind) return [a.kind];
  if (a.type === 'watch') return ['savings'];
  // Spending is opt-in: a seed starts as its on-chain wallet alone, and grows
  // a Spending side only once the user sets one up (the wizard's spend step,
  // an explicit Add wallet, or funds/an address arriving — see the latch in
  // spendingActive).
  return a.spendingSetup ? ['spending', 'savings'] : ['savings'];
}
// How a SEED reads to the user: the names of the wallets it carries
// ("Spending + Savings") — its internal record label never surfaces.
function seedName(a) {
  return viewsOf(a).map((v) => viewLabel(a, v)).join(' + ');
}
function viewLabel(a, view) {
  if (a && a.viewLabels && a.viewLabels[view]) return a.viewLabels[view];
  return view === 'spending' ? t('spendingName') : t('savingsName');
}
function switchToView(id, view) {
  ui.accountUserChosen = true; // deliberate pick from the accounts screen
  ui.account = view;
  try { localStorage.setItem(ACCOUNT_KEY, view); } catch {}
  if (id === activeId) { ui.screen = 'wallet'; ui.tab = 'history'; render(); }
  else {
    const acc = accounts.find((a) => a.id === id);
    if (acc) switchAccount(id);
  }
}

function accountSel() {
  const a = activeAccount();
  if (a && a.kind) return a.kind; // single-purpose wallet: no other side
  if (!spendingActive()) return 'savings'; // one balance, no choice
  if (!ui.account) {
    let saved = null;
    try { saved = localStorage.getItem(ACCOUNT_KEY); } catch {}
    ui.account = saved === 'savings' ? 'savings' : 'spending';
  }
  return ui.account;
}
let _accDir = null; // which way the balance face should slide in
let _accAnim = false; // whether the current face switch animates (decided at the switch)
function setAccountSel(a, dir) {
  if (ui.account === a) return;
  ui.accountUserChosen = true; // deliberate pick — auto-select must not override
  _accDir = dir || (a === 'savings' ? 'left' : 'right');
  ui.account = a;
  try { localStorage.setItem(ACCOUNT_KEY, a); } catch {}
  // Selecting an account shows its Receive page — its own address, the
  // thing you most often switched for — and any open payment detail (which
  // belongs to the account it was opened from) closes with it.
  ui.txDetail = null; ui.arkMoveDetail = null; ui.arkReconDetail = null; ui.arkExitDetail = null; ui.giftDetail = null;
  ui.tab = 'receive';
  render();
}

const GEAR_ICON = (n) => `<svg width="${n}" height="${n}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" style="display:block"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09a1.65 1.65 0 0 0-1-1.51 1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09a1.65 1.65 0 0 0 1.51-1 1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33h.09a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82v.09a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg>`;
const SWAP_ICON = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:block"><path d="M8 3 4 7l4 4"/><path d="M4 7h16"/><path d="m16 21 4-4-4-4"/><path d="M20 17H4"/></svg>';

// Wide screens: the bottom nav is a rail on the left (CSS only) and, from
// 1220px, the wallet rides in a column on the right of the feed and chats —
// the balance, Receive and Send, and the latest payments, a glance away.
const WIDE_MQ = typeof matchMedia === 'function' ? matchMedia('(min-width: 1220px)') : null;
try { WIDE_MQ && WIDE_MQ.addEventListener('change', () => render()); } catch {}
function walletSide() {
  const toWallet = (tab) => { goHome(); ui.tab = tab; render(); };
  const spending = featureHook('spendingSat') || 0;
  const saving = wallet.spendable || 0;
  const sel = accountSel();
  const txs = sel === 'spending' ? [] : wallet.history || [];
  const entries = wallet.loaded ? [
    ...txs.map((tx) => ({ time: tx.confirmed ? (tx.blockTime || 0) * 1000 : Date.now(), render: () => txHistoryItem(tx) })),
    ...featureAll('historyEntries', txs, sel),
  ].sort((a, b) => b.time - a.time).slice(0, 6) : [];
  const rows = entries.map((e) => {
    const row = e.render();
    // a row opens its detail on the wallet page: go there first
    row.addEventListener('click', () => { goHome(); ui.tab = 'history'; }, true);
    return row;
  });
  const line = (label, sat) => h('div', { class: 'row between small' },
    h('span', { class: 'muted' }, label), h('span', {}, fmtAmount(sat) + ' ' + unitLabel()));
  return h('aside', { class: 'wallet-side col', 'data-key': 'wallet-side' },
    headerSearch(),
    h('div', { class: 'card col', style: 'gap:10px' },
      h('button', { type: 'button', class: 'wallet-side-total', onClick: () => toWallet('history') },
        h('span', { class: 'small muted' }, t('balance')),
        h('span', { class: 'wallet-side-amount' }, wallet.loaded ? fmtAmount(spending + saving) + ' ' + unitLabel() : '…')),
      spendingActive() ? line(t('spendingLabel'), spending) : null,
      spendingActive() ? line(t('savingLabel'), saving) : null,
      h('div', { class: 'row gap6' },
        h('button', { type: 'button', class: 'btn-primary grow', onClick: () => toWallet('receive') }, t('tabReceive')),
        h('button', { type: 'button', class: 'btn-primary grow', onClick: () => toWallet('send') }, t('tabSend')))),
    rows.length ? h('div', { class: 'card history-card' }, h('div', { class: 'list' }, ...rows)) : null);
}

function balanceCard() {
  // Dim + spin until this network has data (cache, Nostr state, or a scan has
  // populated balances once). `scanning` alone misses the window between
  // wallet.load() and the first scan — the cache check and Nostr sync on a
  // network switch — where a bare 0 reads as a final balance. Background
  // updates after that happen silently.
  const firstLoad = !wallet.loaded && !wallet.offline;
  const pending = wallet.pendingIncoming;
  const featLines = featureAll('balanceLines');
  // Money lives in two places and we name them for what they're FOR, not for
  // the rails underneath: Spending is the instant off-chain balance, Saving
  // is the on-chain one. The headline is simply everything you have.
  const spending = featureHook('spendingSat') || 0;
  const saving = wallet.spendable;
  const acc0 = activeAccount();
  const kindLocked = !!(acc0 && acc0.kind); // single-purpose top-level wallet
  const hasSpending = spendingActive();
  const sel = kindLocked ? acc0.kind : hasSpending ? accountSel() : 'savings';
  const isSpending = sel === 'spending';
  // a single-purpose wallet's switch jumps to a same-seed sibling wallet of
  // the opposite purpose, when one exists
  const opp = isSpending ? 'savings' : 'spending';
  const sibling = kindLocked
    ? accounts.find((x) => x.id !== acc0.id && x.mnemonic && x.mnemonic === acc0.mnemonic
        && (x.passphrase || '') === (acc0.passphrase || '') && viewsOf(x).includes(opp))
    : null;
  // The balance area: with both views live it's a CAROUSEL — the other face
  // peeks at the edge and drags/snaps into place (native scroll-snap), the
  // way wallet cards behave in BlueWallet. Snapping IS the account switch.
  // Single-purpose and savings-only wallets keep the lone face.
  // Each face's own settings: Spending's coins and exits, the seed, the lock.
  const manageBtn = (view) => h('button', {
    class: 'balance-switch balance-gear',
    title: t('walletSettings'), 'aria-label': t('walletSettings'),
    onClick: () => openWalletSettings(view),
    html: GEAR_ICON(17),
  });
  const faceFor = (view) => {
    const viewSpending = view === 'spending';
    return h('div', { class: 'balance-face' },
      h('div', { class: 'row between', style: 'align-items:center' },
        h('div', { class: 'row', style: 'gap:7px;align-items:center;min-width:0' },
          // account identity at a glance (user feedback): spending wears
          // lightning + the ark mark, savings the bitcoin disc — color says
          // which rail before the label is read
          hasSpending && !kindLocked
            ? h('span', {
                class: 'face-ico ' + (viewSpending ? 'spend' : 'save'),
                html: viewSpending ? '\u26a1' : BITCOIN_ICON(14),
              })
            : null,
          h('div', { class: 'small faint', style: 'text-transform:uppercase;letter-spacing:.06em' },
            kindLocked ? viewLabel(acc0, view)
              : hasSpending ? (viewSpending ? t('spendingLabel') : t('savingLabel')) : t('balance'))),
        manageBtn(view)),
      h('div', { class: 'amt', style: firstLoad ? 'opacity:.3' : '' },
        firstLoad ? h('span', { class: 'spinner sm', style: 'margin-right:8px' }) : null,
        animatedAmount('bal:' + view, viewSpending ? spending : saving), ' ', unitTag('unit')),
      // Pending incoming is an on-chain fact — it belongs to the Saving face.
      // A feature line says which side it belongs to (ark's Moving… is
      // Spending; a gift's Locked reservation is on-chain, so Saving) — one
      // face used to take them all, and a gift sent from Savings showed up
      // as locked money under Spending.
      (() => {
        const lines = (viewSpending ? [] : pending > 0 ? [{ label: t('pending'), sat: pending, cls: 'v pending' }] : [])
          .concat(featLines.filter((l) => (l.side || 'spending') === (viewSpending ? 'spending' : 'savings')));
        return lines.length
          ? h('div', { class: 'split' },
              ...lines.map((l) => h('div', {}, h('div', { class: 'k' }, l.label), h('div', { class: l.cls || 'v' }, fmtAmount(l.sat), ' ', unitTag()))))
          : null;
      })());
  };
  // Everything below the balance figure — the move button, top-up offer,
  // spend-setup offer and the inline unfold panel. In carousel mode these
  // belong to the SPENDING CARD ITSELF, not to whichever card is selected:
  // the strip's flex row stretches both cards to the tallest, so an extra
  // that appears only on selection made the whole strip change height right
  // as a swipe settled. Tied to the card, heights never move mid-swipe.
  const cardExtras = (view = sel) => [
    // "Move money" and friends: the only door between the two balances —
    // pointless (and confusing) while there's only one.
    ...(hasSpending ? featureAll('balanceActions') : []).map((a2) =>
      h('button', { class: 'btn-sm', style: 'margin-top:10px', onClick: a2.onClick }, a2.label)),
    // A seed with only a Savings side is one tap from growing a Spending one:
    // the offer sits right on the balance card. The tap creates it outright —
    // same seed, a "Spending" side, latched before any prompt so backing out
    // of the niceties can't take it away — then walks the username + avatar
    // steps, since a spending account is best enjoyed with a payment address.
    // (Explicit latches carry a timestamp; self-heal only eats legacy booleans.)
    // A Spending face running on fumes while Savings sits comfortable gets a
    // one-tap top-up into the board panel.
    hasSpending && view === 'spending' && !ui.arkMoveOpen && wallet.spendable > 1000
      && spending + (featureHook('spendingBoardingSat') || 0) < 1000
      && featureHook('arkReady') && !wallet.watchOnly
      ? h('button', { class: 'btn-sm', style: 'margin-top:10px', onClick: () => {
          // tapped on the peeking card: bring the card in with its panel
          if (accountSel() !== 'spending') {
            ui.accountUserChosen = true;
            ui.account = 'spending';
            try { localStorage.setItem(ACCOUNT_KEY, 'spending'); } catch {}
          }
          ui.arkMoveDir = 'toSpending'; ui.arkMoveOpen = true; render();
        } }, t('topUpFromSavings'))
      : null,
    !hasSpending && !kindLocked && featureHook('arkReady') && !wallet.watchOnly && acc0 && acc0.type === 'full'
      && featureHook('namesSettled') !== 'pending' // a restoring name may prove Spending any second — don't flash the setup ask
      ? h('button', { class: 'btn-sm', style: 'margin-top:10px', onClick: () => {
          acc0.spendingSetup = Date.now();
          persistAccounts();
          featureHook('spendingEvident');
          setAccountSel('spending', 'right');
          ui.onbError = '';
          ui.onb = { step: 'spend' };
          render();
        } }, t('spendSetup'))
      : null,
    // A feature can unfold UI right on the card (ark's inline move panel).
    (() => {
      if (!hasSpending) return null;
      const dt = animWindow('unfold', !!ui.arkMoveOpen, 300);
      const extra = featureHook('balanceExtra');
      if (!extra) return null;
      const w = h('div', {}, extra);
      applyAnim(w, 'anim-unfold', dt);
      return w;
    })(),
  ];
  const carouselMode = hasSpending && !kindLocked;
  if (carouselMode) {
    // Two SEPARATE cards side by side — the neighbor card peeks past the
    // active one's edge and drags/snaps into place, BlueWallet-style.
    const ORDER2 = ['spending', 'savings'];
    // Align the carousel to the selected card after this render lands — but
    // never fight a finger or live momentum, and NEVER touch layout when it's
    // already where it belongs. Boot fires many renders (cache, ark connect,
    // scan, nostr, balance ticks); reading offsetLeft/scrollLeft on each one
    // forced a synchronous layout mid-scroll — the stutter. `_alignedTo`
    // short-circuits before any layout read once the card is in place.
    requestAnimationFrame(() => {
      const el = document.querySelector('.bal-carousel');
      if (!el || el._alignedTo === sel) return;
      // never yank the card while a finger/mouse is on it, or right after a
      // scroll — a boot render firing this mid-drag was the "false start"
      if (el._dragging || Date.now() - (el._lastScroll || 0) < 350) return;
      const k = el.children[ORDER2.indexOf(sel)];
      if (!k) return;
      const target = k.offsetLeft + k.offsetWidth / 2 - el.clientWidth / 2;
      if (Math.abs(el.scrollLeft - target) > 6) el.scrollTo({ left: target, behavior: el._inited ? 'smooth' : 'auto' });
      el._alignedTo = sel;
      el._inited = true;
    });
    _accDir = null; // the drag is the animation here
    // Commit the account switch — shared by settle (the authority, at rest)
    // and the EARLY commit at release: the moment a flick's outcome is known
    // the history below starts loading, instead of waiting out the slide.
    // The strip itself stays morph-frozen until the glide lands, so this
    // render can't disturb the motion.
    const commitAccount = (el, view) => {
      // the scroll rests (or will rest) on this card — mark it aligned so
      // the post-render pass skips its layout read instead of re-aligning
      el._alignedTo = view;
      ui.accountUserChosen = true; // a deliberate pick — no auto-select behind it
      ui.account = view;
      try { localStorage.setItem(ACCOUNT_KEY, view); } catch {}
      // selecting Spending lands on its history (home); Savings opens on
      // its Receive pane, the deposit address being what you swiped over
      // for. Any open payment detail belonged to the other account.
      ui.txDetail = null; ui.arkMoveDetail = null; ui.arkReconDetail = null; ui.arkExitDetail = null; ui.giftDetail = null;
      ui.tab = view === 'savings' ? 'receive' : 'history';
      render();
    };
    // Where will a released touch flick land? Nearest card, pushed one over
    // when the finger left with real speed — the same physics mandatory snap
    // applies. A wrong guess only flashes the other history for a beat:
    // settle corrects it when the snap actually lands.
    const predictLanding = (el) => {
      const kids = [...el.children];
      if (!kids.length) return null;
      const mid = el.scrollLeft + el.clientWidth / 2;
      let idx = 0, d0 = Infinity;
      kids.forEach((k, i) => {
        const d = Math.abs(k.offsetLeft + k.offsetWidth / 2 - mid);
        if (d < d0) { d0 = d; idx = i; }
      });
      const s = el._flick || [];
      const a = s[0], b = s[s.length - 1];
      const vel = a && b && b.t > a.t ? (b.x - a.x) / (b.t - a.t) : 0; // px/ms, + = toward higher index
      if (Math.abs(vel) > 0.3) idx = Math.max(0, Math.min(kids.length - 1, idx + (vel > 0 ? 1 : -1)));
      return ORDER2[idx];
    };
    // The settled-card check, shared by the scroll debounce and drag release.
    // While a finger or mouse button is still DOWN nothing switches — hovering
    // a card mid-drag is browsing, not choosing; release is the choice.
    const settle = (el) => {
      if (el._dragging) return;
      // Direct scrollLeft writes during a mouse drag can queue scrollend.
      // It may arrive AFTER release, before the smooth glide's first frame.
      // Only the chosen destination can end that glide; an intermediate
      // position must not switch the pane back or restore snap early.
      if (el._mouseTarget != null) {
        if (Math.abs(el.scrollLeft - el._mouseTarget) > 2) return;
        el._mouseTarget = null;
        clearTimeout(el._snapT);
        el.style.scrollSnapType = '';
      }
      endCarouselDrag(); // motion has stopped — unfreeze the strip and sync it
      const mid = el.scrollLeft + el.clientWidth / 2;
      let best = 0, bestD = Infinity;
      [...el.children].forEach((k, i) => {
        const d = Math.abs(k.offsetLeft + k.offsetWidth / 2 - mid);
        if (d < bestD) { bestD = d; best = i; }
      });
      const view = ORDER2[best];
      if (view && view !== accountSel()) commitAccount(el, view);
    };
    return h('div', {
      class: 'bal-carousel',
      // The account switch (and its history-list rebuild) is the heaviest work
      // the carousel triggers, so it must never run mid-glide (that dropped a
      // frame and read as a stutter). The switch is driven by the onScroll
      // debounce below, which naturally trails the LAST scroll event — during a
      // smooth glide or momentum scroll, scroll events fire continuously until
      // motion stops, so the debounce lands after the card is already at rest.
      // (scrollend would be the semantic signal but it doesn't fire reliably
      // for programmatic scrolls across browsers, so it's not relied on.)
      onScrollend: (e) => { const el = e.currentTarget; if (!el._dragging) { clearTimeout(el._settle); settle(el); } },
      onTouchstart: (e) => {
        const el = e.currentTarget;
        el._dragging = true; _carDragging = true; el._skipMorph = true;
        // where the finger landed, and where it found the strip — a tap
        // moves neither
        el._x0 = el.scrollLeft;
        el._tx = (e.touches[0] || {}).clientX || 0;
        el._moved = false;
        clearTimeout(el._settle);
      },
      onTouchmove: (e) => {
        const el = e.currentTarget;
        if (!el._moved && Math.abs(((e.touches[0] || {}).clientX || 0) - (el._tx || 0)) > 4) el._moved = true;
      },
      onTouchend: (e) => {
        const el = e.currentTarget;
        el._dragging = false; // onScroll's debounce settles it
        // A TAP, not a drag: the strip never moved. Unfreeze it right now.
        // Otherwise the freeze stood until a scroll settled — and a tap
        // produces no scroll events, so it stood until the 700ms safety net,
        // and the morph refused every render in between. That's why tapping
        // the unit tag on a phone took most of a second to change the number
        // while the same tap on a laptop (the mouse path has always had this
        // guard) was instant.
        if (!el._moved && Math.abs(el.scrollLeft - (el._x0 || 0)) < 2) { endCarouselDrag(); return; }
        // The finger is up: lift the render hold (the strip stays frozen via
        // _skipMorph) and commit the predicted landing NOW, so the history
        // below loads under the glide instead of after it.
        _carDragging = false;
        const view = predictLanding(el);
        if (view && view !== accountSel()) commitAccount(el, view);
        // safety: if momentum produces no scroll events, settle may never
        // fire — unfreeze the strip and flush anyway
        setTimeout(() => { if (!el._dragging && (el._skipMorph || _renderDeferred)) endCarouselDrag(); }, 700);
      },
      // Desktop: scroll-snap has no mouse drag, so emulate one — grab the
      // strip and pull. Touch keeps the native pan (pointerType check);
      // buttons keep their clicks untouched. Mandatory snap fights raw
      // scrollLeft writes, so it's lifted for the drag and restored once the
      // release glide lands on a card.
      onPointerDown: (e) => {
        if (e.pointerType !== 'mouse' || e.button !== 0) return;
        if (e.target.closest && e.target.closest('button, a, input')) return;
        e.preventDefault(); // no text selection while pulling
        const el = e.currentTarget;
        // A new grab invalidates any pending snap-restore from the previous
        // release: bumping the token makes a stale restore a no-op, so it can
        // never re-apply mandatory snap mid-glide and yank the card back to
        // where it started. Kill its timer too so they don't pile up.
        el._dragGen = (el._dragGen || 0) + 1;
        clearTimeout(el._snapT);
        clearTimeout(el._settle);
        el._mouseTarget = null;
        const x0 = e.clientX, s0 = el.scrollLeft;
        const kids0 = [...el.children];
        // the card the drag started on — a flick throws relative to it
        let fromIdx = 0, fromD = Infinity;
        kids0.forEach((k, i) => {
          const d = Math.abs(k.offsetLeft + k.offsetWidth / 2 - (s0 + el.clientWidth / 2));
          if (d < fromD) { fromD = d; fromIdx = i; }
        });
        let moved = false;
        const samples = []; // recent pointer positions for release velocity
        const mv = (ev) => {
          const dx = ev.clientX - x0;
          if (!moved && Math.abs(dx) > 4) {
            moved = true;
            el._dragging = true;
            _carDragging = true; // hold renders so nothing eats frames under the pull
            el._skipMorph = true; // and freeze the strip against any later mid-glide morph
            el.classList.add('grabbing');
            el.style.scrollSnapType = 'none';
          }
          if (moved) {
            el.scrollLeft = s0 - dx;
            el._lastScroll = Date.now();
            samples.push({ t: performance.now(), x: ev.clientX });
            while (samples.length > 8 || (samples.length && samples[0].t < performance.now() - 140)) samples.shift();
          }
        };
        const up = () => {
          window.removeEventListener('pointermove', mv);
          window.removeEventListener('pointerup', up);
          el.classList.remove('grabbing');
          el._dragging = false;
          if (!moved) { endCarouselDrag(); return; }
          el._dragged = Date.now(); // the release's click must not double as a card tap
          // Commit to a neighbor on a small, deliberate move — not only when
          // the drag drags PAST the halfway point. A short flick that traveled
          // ~20% of a card toward the neighbor, or any quick flick, switches;
          // otherwise it snaps back. (Nearest-point settling made a short pull
          // spring back to where it started — the "slide then jump back"
          // glitch.) Direction: a flick uses its velocity sign, a slow drag
          // uses how far it actually moved from the card it grabbed.
          const kids = [...el.children];
          const last = samples[samples.length - 1];
          const past = samples[0];
          const vel = last && past && last.t > past.t ? (last.x - past.x) / (last.t - past.t) : 0;
          const pitch = kids[1] ? (kids[1].offsetLeft - kids[0].offsetLeft) : el.clientWidth || 1;
          const fromCenter = kids[fromIdx].offsetLeft + kids[fromIdx].offsetWidth / 2;
          const nowCenter = el.scrollLeft + el.clientWidth / 2;
          const travelled = (nowCenter - fromCenter) / pitch; // + = toward higher index
          let dir = 0;
          if (Math.abs(vel) > 0.12) dir = vel < 0 ? 1 : -1; // quick flick
          else if (Math.abs(travelled) > 0.15) dir = travelled > 0 ? 1 : -1; // pulled ~a sixth of a card
          const best = Math.max(0, Math.min(kids.length - 1, fromIdx + dir));
          const k = kids[best];
          // Clamp to the real scroll range: the end cards cannot always be
          // perfectly centered within the strip's padding.
          el._mouseTarget = k ? Math.max(0, Math.min(el.scrollWidth - el.clientWidth,
            k.offsetLeft + k.offsetWidth / 2 - el.clientWidth / 2)) : el.scrollLeft;
          el.scrollTo({ left: el._mouseTarget, behavior: 'smooth' });
          // The shared settle handler restores snap only at this destination.
          // If the browser omits scrollend, finish there after a bounded wait.
          // A newer grab invalidates this fallback, including its unfreeze.
          const gen = el._dragGen;
          clearTimeout(el._snapT);
          el._snapT = setTimeout(() => {
            if (el._dragGen !== gen || el._dragging || el._mouseTarget == null) return;
            el.scrollTo({ left: el._mouseTarget, behavior: 'instant' });
            settle(el);
          }, 700);
          // The chosen card is known RIGHT HERE — commit it now so the
          // history below loads under the glide. The hold lifts (renders may
          // run again) but the strip stays morph-frozen until settle; settle
          // then finds the account already switched and just syncs the strip.
          _carDragging = false;
          const view = ORDER2[best];
          if (view && view !== accountSel()) commitAccount(el, view);
        };
        window.addEventListener('pointermove', mv);
        window.addEventListener('pointerup', up);
      },
      onScroll: (e) => {
        const el = e.target;
        el._lastScroll = Date.now();
        // recent positions — predictLanding reads the release velocity off
        // these when a touch flick lifts (same window the desktop drag keeps)
        (el._flick ||= []).push({ t: performance.now(), x: el.scrollLeft });
        while (el._flick.length > 8 || (el._flick.length && el._flick[0].t < performance.now() - 140)) el._flick.shift();
        // trails the LAST scroll event: during a glide/momentum scroll these
        // fire continuously, so this lands ~130ms after motion stops — after
        // the card is at rest, never mid-glide. settle bails while _dragging.
        clearTimeout(el._settle);
        el._settle = setTimeout(() => settle(el), 130);
      },
    }, ORDER2.map((v) => h('div', {
      class: 'card balance bal-slide face-' + v,
      // Tapping the peeking neighbor switches to it outright — the post-render
      // alignment then glides it into place. Guarded against a desktop drag's
      // release click and against buttons riding on the card.
      onClick: v === sel ? undefined : (e) => {
        if (e.target.closest && e.target.closest('button, a, input')) return;
        const strip = e.currentTarget.parentNode;
        if (strip && Date.now() - (strip._dragged || 0) < 300) return;
        ui.accountUserChosen = true; // deliberate pick
        ui.account = v;
        try { localStorage.setItem(ACCOUNT_KEY, v); } catch {}
        ui.txDetail = null; ui.arkMoveDetail = null; ui.arkReconDetail = null; ui.arkExitDetail = null; ui.giftDetail = null;
        ui.tab = v === 'savings' ? 'receive' : 'history'; // as commitAccount
        render();
      },
    }, faceFor(v), ...(v === 'spending' ? cardExtras(v) : []))));
  }
  const dtRaw = animWindow('acct', sel, 300);
  // Decide AT the change whether this face switch animates: only deliberate
  // switches (tap/swipe set _accDir) slide — a background flip (arkReady
  // arriving and revealing Spending right after sign-in) must not.
  if (dtRaw >= 0 && dtRaw < 16.7) _accAnim = !!_accDir && !ui.navAnimSkip;
  const dtAcc = _accAnim ? dtRaw : -1;
  const heroEl = faceFor(sel);
  applyAnim(heroEl, 'anim-tab-' + (_accDir || 'left'), dtAcc);
  _accDir = null;
  return h('div', { class: 'card balance' + (hasSpending && !kindLocked ? ' face-' + sel : '') }, heroEl, ...cardExtras());
}



function tabsBar() {
  // Settings lives in the avatar menu, not the tab strip. History isn't a tab
  // at all any more — it's the wallet's HOME, under the two tabs: tapping the
  // lit tab again (or native back) puts it away and the history is what's left.
  const tabs = [
    ['receive', t('tabReceive')],
    // Watch-only wallets show Send too — it prompts to load the seed to spend.
    ['send', t('tabSend')],
  ];
  return h(
    'div',
    { class: 'tabs' },
    tabs.map(([id, label]) =>
      tabBtn(label, ui.tab === id, () => {
        ui.tab = ui.tab === id ? 'history' : id;
        ui.sendError = ''; // a stale send error never survives a tab change
        ui.revealShown = false; // re-mask the recovery phrase whenever tabs change
        ui.nostrExportStep = false; // and the exported nostr key
        ui.txDetail = null; // back to the history list when leaving/returning
        ui.arkMoveDetail = null;
        ui.arkReconDetail = null;
        ui.giftDetail = null;
        ui.addrScan = false; // and back to the main Settings, not the address list
        ui.settingsPage = null;
        ui.bump = null;
        ui.giftMode = false;
        render();
      })
    )
  );
}

// On a desktop (a real pointer, a real keyboard) Send is ready to type into:
// the recipient field has the cursor when the tab opens, and the amount field
// takes it the moment it appears, so a picked recipient goes straight to
// typing the number. Once per field: it never pulls focus back after you've
// moved on, and never off another field you're in (a zap comment) — only off
// nothing, or (for the amount) off the recipient field that just resolved.
// Leaving Send takes its fields off the page, so coming back builds new ones
// and the cursor lands again, however you left. Phones keep their keyboard
// down until a tap.
function focusSendField() {
  if (matchMedia('(pointer: coarse)').matches) return;
  const pane = document.querySelector('[data-send-pane]');
  if (!pane) return;
  const amt = pane.querySelector('input[type=number]:not(:disabled)');
  const dest = pane.querySelector('textarea.send-dest:not(:disabled)');
  const field = amt || dest;
  if (!field || field._autoFocused) return;
  field._autoFocused = true;
  // Only typing is protected: a clicked button (the Send tab itself keeps the
  // focus a mouse click gave it) or a link has nothing to lose.
  const a = document.activeElement;
  const typing = a && a !== document.body && (a.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(a.tagName));
  if (typing && !(amt && a.classList.contains('send-dest'))) return;
  field.focus();
}

function tabContent() {
  if (ui.tab === 'settings') return settingsTab();
  if (ui.tab === 'history') return historyTab();
  // Receive and Send are panes that fold open ABOVE the home view, not
  // replacements for it: the transaction history stays visible below them, so
  // getting back to it is scrolling, not hunting for the toggle. A history
  // DETAIL (a tapped row) still claims the whole area — you're reading one
  // payment, not browsing — as does the receive celebration takeover.
  const hist = historyTab();
  const detailOpen = ui.bump || ui.txDetail || ui.arkMoveDetail
    || ui.arkReconDetail || ui.arkExitDetail || ui.giftDetail;
  if (detailOpen) return hist;
  sendFocused = false;
  const pane = ui.tab === 'receive' ? receiveTab() : sendTab();
  if (ui.tab === 'send' && pane && pane.setAttribute) {
    pane.setAttribute('data-send-pane', '');
    requestAnimationFrame(focusSendField);
  }
  // Past the recipient — an amount to enter, a payment to confirm — the
  // history is one more thing on screen while you're about to send.
  if (ui.tab === 'send' && sendFocused) return pane;
  return h('div', { class: 'col', style: 'gap:16px' },
    pane,
    h('div', { class: 'small faint', style: 'text-transform:uppercase;letter-spacing:.06em;margin-top:4px' }, t('tabHistory')),
    hist);
}

// A payment is "recent" enough to celebrate if it's still pending or confirmed
// within the last couple hours. This is a hard guard so an old payment can never
// trigger the celebration on import, regardless of receive-index bookkeeping.
function hasRecentIncoming() {
  // "Recent" means "plausibly the payment you're watching for right now".
  // The open-time baseline can't cover a payment the socket only DISCOVERS
  // seconds after it was taken — with a 2h window, money that landed a while
  // ago celebrated on open as if it had just arrived. A payment confirmed
  // more than 15 minutes ago is news, not an event.
  const now = Date.now() / 1000;
  return wallet.txs.some((tx) => tx.net > 0 && (!tx.confirmed || (tx.blockTime && now - tx.blockTime < 900)));
}

// ---------------------------------------------------------------- Receive
// A dropdown that shows an icon beside each option (a native <select> can't
// render SVG). opts: [{id,label,icon}] where icon is an emoji or an <svg>
// string. Closes on select or on a tap outside (transparent backdrop).
function iconGlyph(ic) {
  if (!ic) return null;
  return String(ic).trim().startsWith('<')
    ? h('span', { class: 'sel-ico', html: ic })
    : h('span', { class: 'sel-ico' }, ic);
}

function receiveTab() {
  // Feature takeovers: boarding success, Ark receive celebration, etc.
  const takeover = featureHook('receiveTakeover');
  if (takeover) return takeover;

  // A payment landed on the shown address (the fresh index advanced past what
  // the user last saw) — celebrate, and wait for a tap before showing the next.
  // Until receiveSeenIndex has been baselined (post-scan, in enterWallet) it
  // stays null and we never celebrate. The recency guard additionally ensures an
  // already-old payment never celebrates when a wallet is opened.
  if (ui.receiveSeenIndex != null && wallet.nextReceiveIndex > ui.receiveSeenIndex && hasRecentIncoming()) {
    // Mark it acknowledged as soon as it's shown — so a refresh or navigating
    // away (without tapping) won't bring the celebration back. It stays visible
    // this session (ui.receiveSeenIndex is unchanged) until the tap below.
    wallet.setReceiveAck(wallet.nextReceiveIndex);
    let amt = 0;
    for (let i = ui.receiveSeenIndex; i < wallet.nextReceiveIndex; i++) {
      const e = wallet._addrInfo(0, i);
      if (e) amt += (e.confirmed || 0) + (e.pending || 0);
    }
    return h(
      'div',
      {
        class: 'card col',
        style: 'align-items:center;text-align:center;gap:14px;cursor:pointer;padding:48px 20px',
        onClick: () => { ui.receiveSeenIndex = wallet.nextReceiveIndex; wallet.setReceiveAck(wallet.nextReceiveIndex); 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'))
    );
  }

  // The pane follows the global account: Spending shows the payment address
  // (receives Ark and Lightning), Savings shows a fresh on-chain address.
  const fresh = wallet.freshReceive();
  const nameMode = featureAll('receiveModes').find((m) => m.id === 'name');
  if (accountSel() === 'spending') {
    // Spending needs the network (registrar + ark); offline, offer the
    // on-chain path right here instead of an endless spinner.
    if (wallet.offline)
      return h('div', { class: 'card col', style: 'gap:12px' },
        h('div', { class: 'notice info' }, t('receiveOfflineSpending')),
        h('button', { class: 'btn-primary btn-block', onClick: () => setAccountSel('savings') }, t('receiveUseSavings')));
    if (nameMode) return nameMode.render(null);
    // No payment address off mainnet — show the reusable ark address rather
    // than silently falling back to an on-chain one that isn't Spending.
    if (featureHook('arkReady')) {
      if (!ui.arkRecvAddr) {
        Promise.resolve(featureHook('arkStaticAddress'))
          .then((a2) => { if (a2 && ui.arkRecvAddr !== a2) { ui.arkRecvAddr = a2; render(); } })
          .catch(() => {});
        return h('div', { class: 'card col', style: 'align-items:center;padding:24px' }, h('span', { class: 'spinner' }));
      }
      return h(
        'div',
        { class: 'card col', style: 'align-items:center;gap:14px' },
        h('div', { html: qrSvg(ui.arkRecvAddr) }),
        h('div', { class: 'addr-box break', style: 'width:100%' }, ui.arkRecvAddr),
        copyBtn(ui.arkRecvAddr, t('copyAddress'))
      );
    }
  }
  const addr = fresh.address;
  return h(
    'div',
    { class: 'card col', style: 'align-items:center;gap:14px' },
    h('div', { html: qrSvg(addr) }),
    h('div', { class: 'addr-box', style: 'width:100%' }, addr),
    copyBtn(addr, t('copyAddress'))
  );
}



// ---------------------------------------------------------------- Send
// Form to enter a recovery phrase / xprv and make a watch-only wallet spendable.
// Shared by the Send tab and Settings. The entered seed must derive to this
// account's xpub — you can't load the wrong wallet's seed.
function loadSeedCard() {
  const ls = ui.loadSeed;
  const seedTa = h('textarea', {
    class: 'mono-input', rows: '3', placeholder: t('seedPlaceholder'),
    autocapitalize: 'none', autocomplete: 'off', spellcheck: 'false', value: ls.value,
    onInput: (e) => { ls.value = e.target.value; },
  });
  return h(
    'div',
    { class: 'card col' },
    h('h3', { style: 'margin:0' }, t('loadSeedTitle')),
    h('p', { class: 'small muted', style: 'margin:0' }, t('loadSeedDesc')),
    pasteInto(seedTa, (text) => { seedTa.value = text; ls.value = text; }),
    h('input', {
      type: 'password', class: 'mono-input', placeholder: t('bip39PassphraseOpt'),
      autocapitalize: 'none', autocomplete: 'off', value: ls.passphrase,
      onInput: (e) => { ls.passphrase = e.target.value; },
    }),
    h('label', { class: 'row gap6', style: 'align-items:center;cursor:pointer' },
      h('input', { type: 'checkbox', checked: ls.save, onChange: (e) => { ls.save = e.target.checked; } }),
      h('span', { class: 'small' }, t('alsoSaveDevice'))
    ),
    ls.error ? h('div', { class: 'notice err' }, ls.error) : null,
    h('div', { class: 'row gap6' },
      h('button', { class: 'btn-ghost', onClick: cancelLoadSeed }, t('cancel')),
      h('button', { class: 'btn-primary grow', onClick: doLoadSeed }, t('loadSeedBtn'))
    )
  );
}

let sendFocused = false; // the send pane is past the recipient (set while it renders)
function sendTab() {
  sendPageRendered = true;
  // Watch-only wallet (e.g. restored after a session wipe without "Save to
  // device"): prompt to re-enter the seed before spending.
  if (wallet.watchOnly) {
    if (ui.loadSeed) return loadSeedCard();
    return h('div', { class: 'card col', style: 'gap:12px' },
      h('h3', {}, t('watchOnlySendTitle')),
      h('p', { class: 'small muted', style: 'margin:0' }, t('watchOnlySendDesc')),
      h('button', { class: 'btn-primary btn-block', onClick: () => startLoadSeed() }, t('loadSeedBtn'))
    );
  }
  if (ui.sendResult) return sendResultView();
  // an NFC/intent payment waiting for its feature: the tap flow's paying shell
  if (ui.intentWait) {
    return h('div', { class: 'card col autopay-card', style: 'align-items:center;text-align:center;gap:14px;padding:48px 20px' },
      h('div', { class: 'check-badge autopay-badge' }, '\u26a1'),
      h('div', { class: 'small muted autopay-foot' }, ''));
  }
  if (ui.broadcastTx) { sendFocused = true; return broadcastConfirmView(); }
  const featView = featureHook('sendView');
  if (featView) { sendFocused = true; return featView; }
  if (ui.draft) { sendFocused = true; return reviewView(); }
  // the amount shows once a recipient is a real destination
  if ((ui.send.recipients || []).some((r) => destReady(r.address))) sendFocused = true;
  return sendForm();
}



// QR scanning is only possible in a secure context with a camera.
const canScan = () =>
  typeof navigator !== 'undefined' && !!(navigator.mediaDevices && navigator.mediaDevices.getUserMedia);

// Open the camera, then route the decoded payload: a BIP21 URI or address fills
// the form; a raw signed-tx hex goes to a broadcast confirmation.
async function scanIntoSend() {
  let text;
  try {
    text = await scanQr(t);
  } catch (e) {
    ui.sendError = e.message;
    render();
    return;
  }
  if (text) handleScanned(text);
}

function handleScanned(raw) {
  const text = raw.trim();
  const s = ui.send;
  ui.sendError = '';

  // A scanned bolt11 (optionally lightning:-prefixed) → pay it over Lightning.
  if (featureMatchSend(text)) return;

  if (/^bitcoin:/i.test(text)) {
    const { address, amount } = parseBip21(text);
    if (!address) {
      ui.sendError = t('scanUnrecognized');
      render();
      return;
    }
    s.recipients[0].address = address;
    if (amount != null) {
      s.recipients[0].amount = amount;
      s.max = false;
    }
    render();
    return;
  }

  // A raw signed transaction (hex) — confirm before broadcasting.
  const compact = text.replace(/\s+/g, '');
  if (/^[0-9a-fA-F]+$/.test(compact) && compact.length >= 100 && compact.length % 2 === 0) {
    try {
      const info = wallet.parseRawTx(compact);
      ui.broadcastTx = { hex: compact, ...info };
      render();
      return;
    } catch {
      /* not a parseable tx — fall through and treat as an address */
    }
  }

  // Otherwise treat it as an address (review will validate it).
  s.recipients[0].address = text;
  render();
}

// bitcoin:<address>?amount=<btc>&label=... — amount is in BTC; convert to the
// current display unit so it lands in the form's amount field correctly.
function parseBip21(uri) {
  const m = /^bitcoin:([^?]*)(?:\?(.*))?$/i.exec(uri.trim());
  if (!m) return {};
  const address = decodeURIComponent((m[1] || '').trim());
  let amount = null;
  if (m[2]) {
    const amt = new URLSearchParams(m[2]).get('amount');
    if (amt && isFinite(Number(amt)) && Number(amt) > 0) {
      const sats = Math.round(Number(amt) * SATS);
      amount = unit === 'sats' ? String(sats) : String(Number(amt));
    }
  }
  return { address, amount };
}

function broadcastConfirmView() {
  const b = ui.broadcastTx;
  return h(
    'div',
    { class: 'card col' },
    h('h3', {}, t('broadcastScanned')),
    h(
      'div',
      { class: 'summary col', style: 'gap:0' },
      ...b.outputs.map((o) =>
        h('div', { class: 'line' },
          h('span', { class: 'k mono break' }, o.address ? shortAddr(o.address, 14, 8) : '—'),
          h('span', { class: 'v' }, fmtAmount(o.value), ' ', unitTag())
        )
      ),
      h('div', { class: 'line' },
        h('span', { class: 'k' }, t('transactionId')),
        h('span', { class: 'v mono break' }, shortTxid(b.txid))
      )
    ),
    ui.sendError && h('div', { class: 'notice err' }, ui.sendError),
    h('div', { class: 'row gap6' },
      h('button', { class: 'btn-ghost', onClick: () => { ui.broadcastTx = null; ui.sendError = ''; render(); } }, t('back')),
      ui.busy
        ? h('button', { class: 'btn-primary grow', disabled: true }, h('span', { class: 'spinner' }))
        : h('button', { class: 'btn-primary grow', onClick: broadcastScanned }, t('broadcastNow'))
    )
  );
}

// --- RBF fee bump (with a fee-rate picker) ---------------------------------
function bumpRate() {
  const s = ui.bump;
  if (s.feeChoice === 'custom') return Math.max(1, Math.round(Number(s.customFee) || 1));
  const fr = wallet.feeRates;
  return (fr && fr[s.feeChoice]) || 5;
}

// Open the bump screen: fetch + reconstruct the original, default to Priority.
async function bumpFee(txid) {
  if (wallet.offline) { toast(t('scanOffline')); return; }
  ui.busy = true;
  render();
  try {
    const prep = await wallet.prepareBump(txid);
    ui.bump = { prep, feeChoice: 'fastestFee', customFee: '' };
    ui.sendError = '';
  } catch (e) {
    toast(e.message);
  }
  ui.busy = false;
  render();
}

function bumpView() {
  const s = ui.bump;
  const feeOpts = [
    ['economyFee', t('feeEconomy')],
    ['halfHourFee', t('feeNormal')],
    ['fastestFee', t('feePriority')],
    ['custom', t('feeCustom')],
  ];
  const rate = bumpRate();
  let pl = null;
  try { pl = wallet.planBump(s.prep, rate); } catch {}
  const newFee = pl && pl.ok ? pl.fee : null;
  const planErr = pl && !pl.ok ? t('bumpInsufficient') : '';
  return h(
    'div',
    { class: 'card col' },
    h('h3', {}, t('bumpConfirm')),
    h('div', { class: 'summary col', style: 'gap:0' },
      ...s.prep.recipients.map((r) =>
        h('div', { class: 'line' },
          h('span', { class: 'k mono break' }, r.address ? shortAddr(r.address, 14, 8) : '—'),
          h('span', { class: 'v' }, fmtAmount(r.value), ' ', unitTag())
        )
      ),
      h('div', { class: 'line' },
        h('span', { class: 'k' }, t('networkFee')),
        h('span', { class: 'v' }, fmtAmount(s.prep.oldFee) + ' → ' + (newFee != null ? fmtAmount(newFee) : '—') + ' ' + unitLabel())
      )
    ),
    h('div', { class: 'field' },
      h('span', { class: 'lab' }, t('feeRate')),
      h('div', { class: 'seg', style: 'display:flex;width:100%' },
        feeOpts.map(([k, label]) =>
          h('button', {
            type: 'button', class: (s.feeChoice === k ? 'active ' : '') + 'grow',
            onClick: () => { s.feeChoice = k; if (k === 'custom' && !s.customFee) s.customFee = String(rate); render(); },
          }, label)
        )
      ),
      s.feeChoice === 'custom'
        ? h('div', { class: 'input-group mt8' },
            h('input', { type: 'number', min: '1', placeholder: 'sat/vB', value: s.customFee,
              onInput: (e) => (s.customFee = e.target.value), onChange: () => render() }),
            h('span', { class: 'small muted', style: 'align-self:center' }, 'sat/vB'))
        : h('div', { class: 'small faint mt8' }, t('selectedRate', { n: rate }))
    ),
    (ui.sendError || planErr) && h('div', { class: 'notice err' }, ui.sendError || planErr),
    h('div', { class: 'row gap6' },
      h('button', { class: 'btn-ghost', onClick: () => { ui.sendError = ''; goBack(() => { ui.bump = null; }); } }, t('back')),
      ui.busy
        ? h('button', { class: 'btn-primary grow', disabled: true }, h('span', { class: 'spinner' }))
        : h('button', { class: 'btn-primary grow', disabled: !newFee, onClick: doBump }, t('replaceTx'))
    )
  );
}

async function doBump() {
  ui.busy = true;
  ui.sendError = '';
  render();
  try {
    const d = wallet.buildBump(ui.bump.prep, bumpRate());
    const txid = await wallet.broadcast(d.hex);
    ui.sendResult = { txid };
    ui.bump = null;
    ui.txDetail = null;
    ui.tab = 'send';
    await wallet.scan().catch(() => {});
  } catch (e) {
    ui.sendError = t('broadcastFailed', { msg: e.message });
  }
  ui.busy = false;
  render();
}

async function broadcastScanned() {
  if (wallet.offline) { ui.sendError = t('scanOffline'); render(); return; }
  ui.busy = true;
  ui.sendError = '';
  render();
  try {
    const txid = await wallet.broadcast(ui.broadcastTx.hex);
    ui.sendResult = { txid };
    ui.broadcastTx = null;
    await wallet.scan().catch(() => {});
  } catch (e) {
    ui.sendError = t('broadcastFailed', { msg: e.message });
  }
  ui.busy = false;
  render();
}

// Full address as wrapping nodes, first/last 6 chars emphasized — readable
// without horizontally scrolling the input. Returns DOM nodes for in-place
// updates (the address input doesn't re-render on every keystroke).
// How many lines the recipient field needs to show all of what's in it.
// Characters per line come from the field's own width and font, measured
// the first time it's typed in (a monospace field: every character is as
// wide as a 0); until then a phone-width guess. A rows attribute, not an
// inline height, so a re-render reproduces it instead of resetting it.
// An empty field is as tall as its hint, measured in the hint's own font:
// the whole of it shows too, in any language.
let destCpl = 30, destHintRows = 1;
function measureDest(el) {
  try {
    const cs = getComputedStyle(el);
    const c = measureDest.c || (measureDest.c = document.createElement('canvas').getContext('2d'));
    c.font = cs.font;
    const w = el.clientWidth - parseFloat(cs.paddingLeft) - parseFloat(cs.paddingRight);
    const cw = c.measureText('0').width;
    if (w > 0 && cw > 0) destCpl = Math.max(8, Math.floor(w / cw));
    const ph = el.getAttribute('placeholder') || '';
    const pcs = getComputedStyle(el, '::placeholder');
    c.font = `${pcs.fontSize} ${pcs.fontFamily}`;
    if (w > 0 && ph) destHintRows = Math.min(3, Math.max(1, Math.ceil(c.measureText(ph).width / w)));
  } catch {}
}
const destRows = (v) => (String(v || '').length
  ? Math.min(6, Math.max(1, Math.ceil(String(v).length / destCpl)))
  : destHintRows);

// True once the destination is a real on-chain or silent-payment address — used to
// progressively reveal the amount/fee/coin controls. A Lightning invoice instead
// auto-advances to its own confirmation, so it never needs them.
function destReady(a) {
  a = (a || '').trim();
  return !!a && (wallet.isOnchainAddress(a) || FEATURES.some((f) => f.isSendDest && f.isSendDest(a)));
}

// Recipient search under the destination input: usernames and npubs resolve
// to candidates with avatars; picking one runs the same path as pasting.
const sendSearch = { rows: null, sync: null, pick: null, el: null };
let sendRevealTimer = null;
// A lightning address typed and then left alone: once typing has paused,
// ask whether it's real (the names and zaps features each know a way), and
// go on to the amount if anything answers. A half-typed domain answers
// nothing, so it just waits, with no error.
let sendPauseTimer = null;
const LN_ADDRESS_SHAPE = /^[^\s@]+@[^\s@]+\.[a-z]{2,}$/i;
const SEND_PAUSE_MS = 900;
// With the phone keyboard up, the space under the recipient field is scarce —
// park the field at the top of the view so the candidate list gets what's
// left. Runs on focus and again whenever fresh candidates land (the list
// growing is what pushes things under the keyboard). The .send-suggest
// bottom margin (style.css) guarantees there's page below to scroll into.
function parkSendField() {
  if (!matchMedia('(pointer: coarse)').matches) return;
  const el = document.activeElement;
  if (el && el.isConnected && el.tagName === 'INPUT') el.scrollIntoView({ block: 'start', behavior: 'smooth' });
}
// Results update the panel IMPERATIVELY (sendSearch.sync, set by the mounted
// recipient row) rather than via render(): a full render swaps the focused
// input for a fresh node, which resets Android's keyboard session and cancels
// key auto-repeat — holding backspace deleted one character per press.
const sendSearcher = makeSearcher((q, rows) => {
  // Suggestions already know the person's picture. Share that profile and
  // warm the large portrait before a selection can paint the Send form.
  for (const cand of rows || []) featureHook('warmRecipient', cand);
  sendSearch.rows = rows;
  if (sendSearch.sync) sendSearch.sync(); else render();
  if (rows && rows.length) setTimeout(parkSendField, 50);
});

// One recipient: address + amount. Max is only offered for a single recipient.
function recipientRow(s, r, i) {
  const single = s.recipients.length === 1;
  const maxOn = single && s.max;
  r._ready = destReady(r.address); // reflected each render; onInput re-renders on a flip
  // same idea for destination annotations (e.g. the lightning-address zap
  // button): they only exist in the rendered tree, so a flip must re-render
  r._note = !!featureHook('sendFormNote', r.address);
  // A payment name resolved to an address on the person's behalf: keep
  // showing the name (and their face) — the ark1… it became is plumbing.
  const viaOf = () => (r.via && r.via.ark === r.address ? r.via : null);
  const via = viaOf();

  // Updated imperatively on input (and on render) so paste, typing, and scan
  // all reflect immediately without disrupting the input's focus/cursor.
  // data-fresh: these two are filled IMPERATIVELY through closures over this
  // render's nodes — the morph must install these exact nodes, not keep last
  // render's (whose closures are stale). Both are fully filled before the
  // morph runs, so the wholesale swap carries identical content.
  // The field itself wraps and grows, so a whole address is always on
  // screen (it used to be repeated below a one-line input for checking).
  const syncCheck = () => {};
  // The suggestions panel gets the same imperative treatment — see the
  // sendSearcher note: a render between key repeats kills backspace-hold.
  // One panel for the life of the page, rows rebuilt only when the results
  // change: a background render must not swap the row under the pointer
  // (a fresh node drops :hover, and the highlight blinked on every tick).
  // data-fresh still installs this exact node wherever the morph lands it.
  const suggest = i === 0 ? (sendSearch.el ||= h('div', { class: 'list send-suggest', style: 'display:none', 'data-fresh': '1' })) : null;
  const syncSuggest = () => {
    if (!suggest) return;
    const show = !!(sendSearch.rows && sendSearch.rows.length && searchable(r.address));
    const rows = show ? sendSearch.rows : null;
    if (suggest._rows === rows) return;
    suggest._rows = rows;
    suggest.replaceChildren(...(rows ? resultRows(h, rows, (cand) => sendSearch.pick(cand), (pk, node) => featureHook('wrapAvatar', pk, node)) : []));
    suggest.style.display = rows ? '' : 'none';
  };
  if (i === 0) sendSearch.sync = syncSuggest;

  // A pasted/typed/scanned payload a feature recognizes (e.g. a bolt11) jumps
  // straight to that feature's own confirmation flow.
  const tryFeature = (v, typed) => featureMatchSend(v, typed);
  const shown = via ? via.name : r.address;
  const addrInput = h('textarea', {
    class: 'mono-input grow send-dest', placeholder: i === 0 ? t('destPlaceholder') : 'bc1q…',
    rows: String(destRows(shown)), wrap: 'soft',
    autocapitalize: 'none', autocomplete: 'off', spellcheck: 'false', value: shown,
    // one line of text: Enter doesn't break it — it picks the top suggestion
    // when the list is showing
    onKeydown: (e) => {
      if (e.key !== 'Enter') return;
      e.preventDefault();
      if (e.isComposing || e.repeat) return;
      const top = i === 0 && suggest && suggest._rows && suggest._rows[0];
      if (top) sendSearch.pick(top);
    },
    // pasted text is complete: it moves on at once, like the Paste button
    onPaste: () => { r._pasted = true; },
    // the delay lets the keyboard start opening (and any render() swap of
    // this input) before parkSendField measures the live activeElement.
    // warmSearch pre-opens the search transports so the first keystroke's
    // results don't pay three cold handshakes.
    onFocus: () => { warmSearch(); setTimeout(parkSendField, 300); },
    onInput: (e) => {
      // a pasted address with a line break in it is still one address
      if (/[\r\n]/.test(e.target.value)) e.target.value = e.target.value.replace(/[\r\n]+/g, '');
      const v = e.target.value;
      measureDest(e.target);
      e.target.rows = destRows(v);
      r.address = v; syncCheck();
      const hadError = !!ui.sendError;
      ui.sendError = ''; // editing the destination starts over — drop stale errors
      if (i === 0) sendSearcher.update(v); // candidates render when results land
      const pasted = r._pasted; r._pasted = false;
      clearTimeout(sendPauseTimer);
      if (tryFeature(v, !pasted)) return;           // a bolt11 (or anything pasted) advances to its own confirmation
      if (single && LN_ADDRESS_SHAPE.test(v.trim())) {
        sendPauseTimer = setTimeout(async () => {
          if (r.address !== v) return;
          const answers = featureAll('probeLnAddress', v.trim());
          if (!answers.length) return;
          const real = await Promise.any(answers.map((p) => Promise.resolve(p).then((x) => x || Promise.reject()))).then(() => true, () => false);
          // still the same text, still on this form
          if (real && r.address === v && ui.tab === 'send' && ui.send === s) tryFeature(v, false);
        }, SEND_PAUSE_MS);
      }
      // reveal/hide amount + controls as validity flips, an annotation
      // (zap button) appears/disappears, or an error clears — but only after
      // typing pauses: an immediate render swaps this input for a fresh node,
      // and Android cancels key auto-repeat when the focused field resets
      // (holding backspace deleted a single character).
      if (hadError || destReady(v) !== r._ready || !!featureHook('sendFormNote', v) !== r._note) {
        clearTimeout(sendRevealTimer);
        sendRevealTimer = setTimeout(render, 250);
      }
    },
  });
  const pickRecipient = (cand) => {
    featureHook('warmRecipient', cand);
    const v = cand.address || npubOf(cand.pk);
    // State first: clear() re-renders, and that render must already see the
    // picked address — the old order repainted the half-typed query and left
    // the pick looking like it did nothing.
    r.address = v;
    ui.sendError = '';
    sendSearcher.clear();
    if (!featureMatchSend(v)) render();
  };
  const row = h(
    'div',
    { class: 'col gap6' },
    h('div', { class: 'input-group' },
      addrInput,
      pasteBtn((text) => { addrInput.value = text; r.address = text; ui.sendError = ''; syncCheck(); if (!tryFeature(text)) render(); }),
      i === 0 && canScan() && h('button', {
        type: 'button', class: 'btn-sm', title: t('scanQr'), onClick: scanIntoSend,
        html: '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 8V5a1 1 0 0 1 1-1h3M16 4h3a1 1 0 0 1 1 1v3M20 16v3a1 1 0 0 1-1 1h-3M8 20H5a1 1 0 0 1-1-1v-3"/></svg>',
      }),
      !single && h('button', { type: 'button', class: 'btn-sm', title: t('remove'), onClick: () => { s.recipients.splice(i, 1); render(); } }, '✕')
    ),
    via ? h('div', { class: 'row gap6 send-via', style: 'align-items:center' },
      via.pk && !single ? featureHook('avatarNode', via.pk) : null,
      via.pk && single ? null : h('span', { class: 'small' }, via.name),
      h('span', { class: 'small faint' }, t('sendNameHint'))) : null,
    suggest,
    r._ready ? h('div', { class: 'input-group' },
      h('input', {
        type: 'number', step: unit === 'sats' ? '1' : '0.00000001', min: '0',
        placeholder: unit === 'sats' ? '0' : '0.00000000',
        disabled: maxOn,
        value: maxOn
          ? (unit === 'sats' ? String(estimatedMaxSats()) : fmtBtc(estimatedMaxSats()))
          : r.amount,
        onInput: (e) => {
          let v = e.target.value;
          // Chrome emits scientific notation when stepping tiny BTC amounts.
          if (v && /e/i.test(v)) {
            const n = Number(v);
            if (isFinite(n)) {
              v = unit === 'sats' ? String(Math.round(n)) : n.toFixed(8).replace(/\.?0+$/, '');
              e.target.value = v;
            }
          }
          r.amount = v;
        },
      }),
      h('button', { type: 'button', title: t('switchUnit'), onClick: toggleUnit }, unitLabel()),
      single && !featureHook('hideSendControls', r.address) && h('button', { type: 'button', class: s.max ? 'btn-primary' : '', onClick: () => { s.max = !s.max; render(); } }, t('max')),
      // features that hide the fee controls (ark) can still offer their own
      // Max — it fills the amount with that rail's spendable balance
      single && featureHook('hideSendControls', r.address)
        ? (() => {
            const v = featureHook('sendMaxFill', r.address);
            return v != null ? h('button', { type: 'button', onClick: () => { r.amount = v; s.max = false; render(); } }, t('max')) : null;
          })()
        : null
    ) : null
  );
  syncCheck();
  // the field's real width, once: a pasted or picked address gets its true
  // line count rather than the guess
  if (!measureDest.done) requestAnimationFrame(() => {
    const el = document.querySelector('.send-dest');
    if (!el || measureDest.done) return;
    measureDest.done = true;
    const before = destCpl + ':' + destHintRows;
    measureDest(el);
    if (destCpl + ':' + destHintRows !== before) render();
  });
  if (i === 0) sendSearch.pick = pickRecipient; // the persistent rows call this render's
  syncSuggest();
  return row;
}

function sendForm() {
  const s = ui.send;
  // Progressive disclosure: until the destination is a valid on-chain/SP address,
  // show only the destination input (a Lightning invoice auto-advances instead).
  const ready = destReady((s.recipients[0] || {}).address);
  const plainAddr = (s.recipients[0] || {}).address;
  const via = s.recipients[0]?.via;
  const recipientPk = s.recipients.length === 1
    ? (via?.ark === plainAddr && via.pk) || parseNostrPubkey(plainAddr) : null;
  const arkDest = s.recipients.length === 1 && !!featureHook('hideSendControls', plainAddr);
  const feeOpts = [
    ['economyFee', t('feeEconomy')],
    ['halfHourFee', t('feeNormal')],
    ['fastestFee', t('feePriority')],
    ['custom', t('feeCustom')],
  ];
  return h(
    'div',
    { class: 'card col' },
    recipientPk ? featureHook('profileChip', recipientPk, 'lg') : null,
    h(
      'div',
      { class: 'field' },
      h('span', { class: 'lab' }, s.recipients.length > 1 ? t('recipients') : t('recipient')),
      h('div', { class: 'col', style: 'gap:14px' },
        s.recipients.map((r, i) => recipientRow(s, r, i))
      ),
      ready && !arkDest && s.recipients.length < 10 &&
        h('button', {
          type: 'button', class: 'linklike small mt8',
          onClick: () => { s.recipients.push({ address: '', amount: '' }); s.max = false; render(); },
        }, t('addRecipient'))
    ),
    // any feature may annotate the destination (ark hint, lightning-address
    // zap offer, …) — each hook decides for itself whether the text is its
    s.recipients.length === 1 && !(s.recipients[0].via && s.recipients[0].via.ark === s.recipients[0].address)
      ? (featureHook('sendFormNote', plainAddr) || null) : null,
    ready && !arkDest && h(
      'div',
      { class: 'field' },
      h('span', { class: 'lab' }, t('feeRate')),
      h(
        'div',
        { class: 'seg', style: 'display:flex;width:100%' },
        feeOpts.map(([k, label]) =>
          h('button', {
            type: 'button', class: (s.feeChoice === k ? 'active ' : '') + 'grow',
            onClick: () => {
              s.feeChoice = k;
              if (k === 'custom' && !s.customFee) {
                s.customFee = String((wallet.feeRates && wallet.feeRates.economyFee) || 1);
              }
              render();
            },
          }, label)
        )
      ),
      s.feeChoice === 'custom' &&
        h('div', { class: 'input-group mt8' },
          h('input', { type: 'number', min: '1', placeholder: 'sat/vB', value: s.customFee, onInput: (e) => (s.customFee = e.target.value) }),
          h('span', { class: 'small muted', style: 'align-self:center' }, 'sat/vB')
        ),
      s.feeChoice !== 'custom' &&
        h('div', { class: 'small faint mt8' }, t('selectedRate', { n: currentFeeRate() }))
    ),
    ready && !arkDest ? coinControl() : null,
    ui.sendError && h('div', { class: 'notice err' }, ui.sendError),
    ready && h('button', { class: 'btn-primary btn-block', onClick: reviewSend }, t('reviewTx')),
    ...FEATURES.map((f) => (f.sendFormExtras ? f.sendFormExtras() : null))
  );
}

function coinControl() {
  const s = ui.send;
  const head = h(
    'div',
    { class: 'row between' },
    h('span', { class: 'lab', style: 'margin:0' }, t('coinSelection')),
    h(
      'div',
      { class: 'seg' },
      h('button', { type: 'button', class: !s.manual ? 'active' : '', onClick: () => { s.manual = false; render(); } }, t('automatic')),
      h('button', { type: 'button', class: s.manual ? 'active' : '', onClick: () => { s.manual = true; render(); } }, t('manual'))
    )
  );
  if (!s.manual) return h('div', { class: 'col gap6' }, head);

  if (!wallet.utxos.length)
    return h('div', { class: 'col gap6' }, head, h('div', { class: 'small muted' }, t('noCoins')));

  let selTotal = 0;
  const rows = wallet.utxos.map((u) => {
    const id = utxoId(u);
    const checked = s.coins.has(id);
    if (checked) selTotal += u.value;
    return h(
      'label',
      { class: 'coin' },
      h('input', {
        type: 'checkbox', checked,
        onChange: (e) => { e.target.checked ? s.coins.add(id) : s.coins.delete(id); render(); },
      }),
      h('div', { class: 'grow' },
        h('div', { class: 'mono small break' }, shortAddr(u.address, 14, 10),
          !u.confirmed ? h('span', { class: 'tag pending', style: 'margin-left:6px' }, t('pendingTag')) : null),
        h('div', { class: 'path' }, `${u.chain}/${u.index} · ${shortTxid(u.txid)}:${u.vout}`)
      ),
      h('div', { class: 'amount small' }, fmtAmount(u.value))
    );
  });
  return h(
    'div',
    { class: 'col gap6' },
    head,
    h('div', { class: 'list' }, rows),
    h('div', { class: 'row between small' },
      h('span', { class: 'muted' }, t('nSelected', { n: s.coins.size })),
      h('span', { class: 'amount' }, fmtAmount(selTotal), ' ', unitTag())
    )
  );
}

// Coins that a send would draw from (all, or the manually-selected subset).
function spendableCoins() {
  const s = ui.send;
  return s.manual ? wallet.utxos.filter((u) => s.coins.has(utxoId(u))) : wallet.utxos;
}

// Estimated max sendable = selected total − fee for (n inputs, 1 output).
function estimatedMaxSats() {
  const coins = spendableCoins();
  const total = coins.reduce((a, u) => a + u.value, 0);
  const vbytes = 11 + 68 * coins.length + 31;
  const fee = Math.ceil(vbytes * currentFeeRate());
  return Math.max(0, total - fee);
}

function currentFeeRate() {
  const s = ui.send;
  if (s.feeChoice === 'custom') return Math.max(1, Math.round(Number(s.customFee) || 1));
  const fr = wallet.feeRates;
  if (fr && fr[s.feeChoice]) return fr[s.feeChoice];
  return 5;
}

function reviewSend() {
  ui.sendError = '';
  try {
    const s = ui.send;
    // Feature destinations (bolt11 → Lightning swap, ark1 → Ark send, ...)
    // divert to their own confirmation flows.
    for (const f of FEATURES) {
      if (f.interceptReview && f.interceptReview(s)) return;
    }
    const feeRate = currentFeeRate();
    let coinIds = null;
    if (s.manual) {
      coinIds = [...s.coins];
      if (!coinIds.length) throw new Error(t('selectCoin'));
    }
    let recipients, sendMax = false;
    if (s.max && s.recipients.length === 1) {
      const addr = s.recipients[0].address.trim();
      if (!addr) throw new Error(t('enterRecipientAddr'));
      recipients = [{ address: addr, amount: 0 }];
      sendMax = true;
    } else {
      recipients = s.recipients.map((r, i) => {
        const addr = r.address.trim();
        if (!addr) throw new Error(t('enterAddrForN', { n: i + 1 }));
        const sats = parseField(r.amount);
        if (!sats || sats <= 0) throw new Error(t('enterValidAmtForN', { n: i + 1 }));
        return { address: addr, amount: sats };
      });
    }
    ui.draft = wallet.buildTx({ recipients, feeRate, coinIds, sendMax });
  } catch (e) {
    ui.draft = null;
    ui.sendError = e.message;
  }
  render();
}







function reviewView() {
  const d = ui.draft;
  const changeAddr = wallet.freshChange().address;
  const outs = d.outputs.filter((o) => o.address !== changeAddr);
  return h(
    'div',
    { class: 'card col' },
    h('h3', {}, t('reviewTx')),
    h(
      'div',
      { class: 'summary col', style: 'gap:0' },
      ...outs.map((o) =>
        h('div', { class: 'line' },
          h('span', { class: 'k mono break' }, shortAddr(o.address, 14, 8)),
          h('span', { class: 'v' }, fmtAmount(o.amount), ' ', unitTag())
        )
      ),
      h('div', { class: 'line' },
        h('span', { class: 'k' }, t('networkFee')),
        h('span', { class: 'v' }, fmtAmount(d.fee), ' ', unitTag())
      )
    ),
    ui.sendError && h('div', { class: 'notice err' }, ui.sendError),
    wallet.spendsUnconfirmed(d.tx)
      ? h('div', { class: 'notice info' }, t('unconfirmedInputWarn'))
      : null,
    wallet.offline
      ? h('div', { class: 'notice info' }, t('offlineSignNote'))
      : null,
    h(
      'div',
      { class: 'row gap6' },
      h('button', { class: 'btn-ghost', onClick: () => { ui.draft = null; ui.sendError = ''; render(); } }, t('back')),
      ui.busy
        ? h('button', { class: 'btn-primary grow', disabled: true }, h('span', { class: 'spinner' }))
        : wallet.offline
          ? h('button', { class: 'btn-primary grow', onClick: signForExport }, t('signTx'))
          : h('button', { class: 'btn-primary grow', onClick: broadcast }, t('signBroadcast'))
    ),
    // Online: also allow signing without broadcasting, to relay the signed tx
    // from another device (air-gapped, or a different network).
    !wallet.offline && !ui.busy
      ? h('button', { class: 'btn-block', style: 'margin-top:8px', onClick: signForExport }, t('signExport'))
      : null
  );
}

async function broadcast() {
  ui.busy = true;
  ui.sendError = '';
  render();
  try {
    const hexTx = wallet.sign(ui.draft.tx);
    const txid = await Promise.race([
      wallet.broadcast(hexTx),
      new Promise((_, rej) => setTimeout(() => rej(new Error(t('broadcastTimeout'))), 30000)),
    ]);
    wallet.applySentTx(ui.draft.tx); // update balance/history locally, right now
    ui.sendResult = { txid };
    ui.draft = null;
    ui.send = blankSend();
    ui.busy = false;
    render(); // the realtime watcher / backstop poll reconciles + confirms later
    return;
  } catch (e) {
    ui.sendError = t('broadcastFailed', { msg: e.message });
  }
  ui.busy = false;
  render();
}

function signForExport() {
  ui.sendError = '';
  try {
    const tx = ui.draft.tx;
    const hexTx = wallet.sign(tx);
    ui.sendResult = { signedHex: hexTx, txid: tx.id };
    ui.draft = null;
    ui.send = blankSend();
  } catch (e) {
    ui.sendError = t('signingFailed', { msg: e.message });
  }
  render();
}

function sendResultView() {
  const r = ui.sendResult;
  const again = h('button', { class: 'btn-block mt8', onClick: () => { ui.sendResult = null; render(); } }, t('done'));
  if (r.signedHex) {
    return h(
      'div',
      { class: 'card col' },
      h('div', { class: 'warn-box' }, t('txSignedNote')),
      h('div', { class: 'small muted' }, t('transactionId')),
      h('div', { class: 'addr-box' }, r.txid),
      h('div', { class: 'small muted mt8' }, t('signedTxRaw')),
      h('textarea', { readonly: true, style: 'min-height:120px', value: r.signedHex }),
      h('div', { class: 'row gap6' },
        copyBtn(r.signedHex, t('copyHex')),
        h('button', { class: 'btn-sm', onClick: () => download(`tx-${r.txid.slice(0, 8)}.txt`, r.signedHex, 'text/plain') }, t('downloadLabel')),
        h('div', { class: 'grow', html: '' })
      ),
      h('details', { class: 'mt8' }, h('summary', { class: 'small muted' }, t('showQrAirgap')), h('div', { style: 'margin-top:10px', html: qrSvg(r.signedHex) })),
      again
    );
  }
  return h(
    'div',
    { class: 'card col', style: 'align-items:center' },
    h('div', { class: 'notice ok', style: 'width:100%' }, t('txBroadcast')),
    h('div', { class: 'small muted' }, t('transactionId')),
    h('div', { class: 'addr-box' }, r.txid),
    h('div', { class: 'row gap6' },
      copyBtn(r.txid, t('copyTxid')),
      h('a', { class: 'btn btn-sm', href: wallet.api.explorerTx(r.txid), target: '_blank', rel: 'noopener', onClick: (e) => { e.preventDefault(); openExternal(wallet.api.explorerTx(r.txid)); } }, t('viewOnMempool'))
    ),
    again
  );
}







function txHistoryItem(tx) {
  const incoming = tx.net >= 0;
  const stuck = !tx.confirmed && wallet.isStuck(tx);
  const deco = featureHook('decorateTxRow', tx); // e.g. a claimed gift's claim tx
  return h(
    'div',
    { class: 'item', style: 'cursor:pointer', onClick: () => openTx(tx.txid) },
    // rail glyph in the direction-tinted circle: feature decoration (ark/
    // gift) if any, else the Bitcoin mark for a plain on-chain tx. Direction
    // is carried by the tint + signed amount.
    deco
      ? h('div', { class: `ico ${incoming ? 'in' : 'out'}` }, deco.icon)
      : h('div', { class: `ico ${incoming ? 'in' : 'out'}`, html: BITCOIN_ICON(22) }),
    h('div', { class: 'grow' },
      h('div', { class: 'row gap6' },
        deco ? deco.label :
        incoming ? t('received') : t('sent'),
        tx.confirmed ? null
          : stuck ? h('span', { class: 'tag', style: 'background:var(--red-soft);color:var(--red)' }, t('stuckTag'))
          : h('span', { class: 'tag pending' }, t('pendingTag'))
      ),
      h('div', { class: 'small faint' }, tx.confirmed ? timeAgo(tx.blockTime) : stuck ? t('stuckNote') : t('awaitingConfirmation'))
    ),
    h('div', { style: 'text-align:right' },
      // priced at the moment it happened, not at today's number
      h('div', { class: incoming ? 'amount-pos' : 'amount-neg' }, fmtAmount(Math.abs(tx.net), tx.blockTime)),
      !incoming && tx.fee ? h('div', { class: 'small faint' }, t('feeShort', { x: fmtAmount(tx.fee, tx.blockTime) })) : null
    )
  );
}

// Prev / page-of / next controls. Returns null when there's only one page.
// The buttons LOOP within the pages (never disabled): Next on the last page
// returns to page 1, Prev on page 1 jumps to the end — unlike the swipe
// ring, they never leave the list for the tabs.
const PAGE_SIZE = 10;
// The history list currently on screen ({ page, pages }), null when a detail
// view / spinner / another tab is up — the swipe gesture paginates against
// this and only falls through to tab navigation once the pages run out.
let _histPager = null;
function pager(page, total, onPage) {
  const pages = Math.ceil(total / PAGE_SIZE);
  if (pages <= 1) return null;
  return h('div', { class: 'row between', style: 'align-items:center;padding-top:10px' },
    h('button', { class: 'btn-sm', onClick: () => onPage((page - 1 + pages) % pages) }, t('prevPage')),
    // the page number is a picker: forty pages is a long swipe to the middle
    h('select', {
      class: 'small muted page-pick', 'aria-label': t('pageXofY', { x: page + 1, y: pages }),
      onChange: (e) => onPage(parseInt(e.target.value, 10) || 0),
    }, ...Array.from({ length: pages }, (_, i) => h('option', { value: String(i), selected: i === page }, t('pageXofY', { x: i + 1, y: pages })))),
    h('button', { class: 'btn-sm', onClick: () => onPage((page + 1) % pages) }, t('nextPage'))
  );
}

function historyTab() {
  _histPager = null; // set again below only when the pageable list renders
  if (ui.bump) return bumpView();
  // History is SCOPED to the selected account: Savings shows the on-chain
  // ledger (BIP84 txs, silent-payment receipts, gift reservations), Spending
  // shows the ark side (receives, sends, boards, LN) — each card of the
  // carousel owns its own timeline.
  const histSel = accountSel();
  const txs = histSel === 'spending' ? [] : wallet.history; // newest first
  const featDetail = featureHook('historyDetail');
  if (featDetail) return featDetail;
  if (ui.txDetail) {
    const tx = wallet.history.find((x) => x.txid === ui.txDetail);
    if (tx) return txDetailView(tx);
    ui.txDetail = null;
  }
  if (wallet.offline)
    return h('div', { class: 'card' }, h('p', { class: 'muted center', style: 'margin:0' }, t('historyOffline')));
  if (!wallet.loaded || (histSel !== 'spending' && wallet.historyLoading && !txs.length))
    return h(
      'div',
      { class: 'card center col', style: 'align-items:center;gap:10px' },
      h('span', { class: 'spinner' }),
      wallet.historyLoading ? h('p', { class: 'small muted', style: 'margin:0' }, t('loadingHistory')) : null
    );
  const featEntries = featureAll('historyEntries', txs, histSel);
  if (!txs.length && !featEntries.length)
    return h('div', { class: 'card' }, h('p', { class: 'muted center', style: 'margin:0' }, t('noTxYet')));

  // Transactions and feature entries merge into one timeline.
  const entries = [
    ...txs.map((tx) => ({ time: tx.confirmed ? (tx.blockTime || 0) * 1000 : Date.now(), render: () => txHistoryItem(tx) })),
    ...featEntries,
  ].sort((a, b) => b.time - a.time);
  const txPages = Math.ceil(entries.length / PAGE_SIZE);
  const txPage = Math.min(ui.txPage, Math.max(0, txPages - 1));
  const txSlice = entries.slice(txPage * PAGE_SIZE, txPage * PAGE_SIZE + PAGE_SIZE);
  _histPager = { page: txPage, pages: txPages };
  return h(
    'div',
    { class: 'card history-card' },
    h('div', { class: 'list' },
      ...txSlice.map((e) => e.render())
    ),
    pager(txPage, entries.length, (p) => { ui.txPage = p; render(); }),
    wallet.historyLoading
      ? h(
          'div',
          { class: 'row gap6', style: 'padding:10px 0 2px;justify-content:center' },
          h('span', { class: 'spinner sm' }),
          h('span', { class: 'small muted' }, t('loadingHistory'))
        )
      : null
  );
}

// Open a tx's detail view, lazily fetching its fee/details if we don't have them
// yet. A watcher-credited receive arrives with no fee (the push can't compute it
// from the raw tx), so fill it in from the explorer on demand — works for pending
// mempool txs too.
async function openTx(txid) {
  ui.txDetail = txid;
  render();
  const tx = wallet.history.find((t) => t.txid === txid);
  if (!tx || tx.fee || wallet.offline) return;
  try {
    const full = await wallet.api.getTx(txid);
    if (!full || ui.txDetail !== txid) return;
    if (full.fee != null) tx.fee = full.fee;
    if (full.weight) tx.vsize = Math.ceil(full.weight / 4);
    if (full.status && full.status.confirmed) {
      tx.confirmed = true;
      tx.blockHeight = full.status.block_height || tx.blockHeight;
      tx.blockTime = full.status.block_time || tx.blockTime;
    }
    wallet.saveCache();
    render();
  } catch {}
}


function txDetailView(tx) {
  const incoming = tx.net >= 0;

  const line = (k, v) => h('div', { class: 'line' }, h('span', { class: 'k' }, k), h('span', { class: 'v' }, v));
  return h(
    'div',
    { class: 'card col' },
    h('div', { class: 'row between' },
      h('h3', {}, incoming ? t('received') : t('sent')),
      h('span', { class: `tag ${tx.confirmed ? 'conf' : 'pending'}` }, tx.confirmed ? t('confirmedTag') : t('pendingTag'))
    ),
    h('div', { class: 'amt', style: 'font-size:30px' },
      h('span', { class: incoming ? 'amount-pos' : 'amount-neg' }, fmtAmount(Math.abs(tx.net), tx.blockTime)),
      ' ', unitTag('unit')
    ),
    h('div', { class: 'summary col', style: 'gap:0' },
      line(t('status'), tx.confirmed ? t('confirmed') : t('pending')),
      tx.confirmed ? line(t('block'), String(tx.blockHeight || '—')) : null,
      tx.confirmed && tx.blockTime ? line(t('date'), new Date(tx.blockTime * 1000).toLocaleString()) : null,
      // what it was worth then, beside what it is now — the one place both
      // numbers earn their keep, because this is the page you open to ask
      worthLine(tx.net, tx.blockTime),
      tx.fee ? line(t('networkFee'), fmtAmount(tx.fee, tx.blockTime) + ' ' + unitLabel()) : null
    ),
    ...FEATURES.map((f) => (f.txDetailSection ? f.txDetailSection(tx) : null)),
    !tx.confirmed && wallet.isStuck(tx)
      ? h('div', { class: 'warn-box' }, incoming ? t('stuckIncomingNote') : t('stuckOutgoingNote'))
      : null,
    h('div', { class: 'col gap6' },
      h('span', { class: 'lab' }, t('transactionId')),
      h('div', { class: 'addr-box', style: 'font-size:13px' }, tx.txid)
    ),
    h('div', { class: 'row gap6 wrap' },
      copyBtn(tx.txid, t('copyId')),
      h('a', { class: 'btn btn-sm', href: wallet.api.explorerTx(tx.txid), target: '_blank', rel: 'noopener', onClick: (e) => { e.preventDefault(); openExternal(wallet.api.explorerTx(tx.txid)); } }, t('viewOnMempool'))
    ),
    // RBF: an unconfirmed send can be rebroadcast at a higher fee.
    !tx.confirmed && !incoming && !wallet.offline
      ? (ui.busy
          ? h('button', { class: 'btn-primary btn-block', disabled: true }, h('span', { class: 'spinner' }))
          : h('button', { class: 'btn-primary btn-block', onClick: () => bumpFee(tx.txid) }, t('bumpFee')))
      : null,
    h('button', { class: 'btn-ghost btn-block', onClick: () => goBack(() => { ui.txDetail = null; }) }, t('backToHistory'))
  );
}

// Offline snapshot exchange: export coins on an online device, import on an
// offline (air-gapped) one to sign without internet.
function snapshotActions() {
  return h(
    'div',
    { class: 'col gap6' },
    h('p', { class: 'small muted', style: 'margin:0' },
      t('offlineTransferDesc')),
    h('div', { class: 'row gap6 wrap' },
      h('button', { class: 'btn-sm', disabled: !wallet.utxos.length, onClick: exportSnapshot }, t('exportSnapshot')),
      h('label', { class: 'btn btn-sm', style: 'cursor:pointer' }, t('importSnapshot'),
        h('input', { type: 'file', accept: 'application/json,.json', style: 'display:none', onChange: importSnapshotFile })
      )
    )
  );
}

function exportSnapshot() {
  const snap = wallet.exportSnapshot();
  const stamp = new Date().toISOString().slice(0, 10);
  download(`wallet-snapshot-${wallet.netName}-${stamp}.json`, JSON.stringify(snap, null, 2));
  toast(t('snapshotExported'));
}

async function importSnapshotFile(e) {
  const file = e.target.files[0];
  if (!file) return;
  try {
    const snap = JSON.parse(await file.text());
    const res = wallet.importSnapshot(snap);
    let msg = t('importedNCoins', { n: res.imported });
    if (res.unmatched.length) msg += t('unmatchedSuffix', { n: res.unmatched.length });
    toast(msg);
    ui.tab = 'settings';
    render();
  } catch (err) {
    toast(t('importFailed', { msg: err.message }));
  }
  e.target.value = '';
}

// ================================================================ start
// Load the active language's strings (English is inline; others are fetched),
// ---- feature registry -------------------------------------------------
// Optional features receive the app context and plug into fixed seams. This
// sits just before boot so every helper it captures is defined; the hooks are
// only invoked at runtime (first render happens after loadLocale below).
const ctx = {
  h, ui, render, wallet, toast, copy, copyBtn, pasteBtn, blankSend, goBack, canGoBack, goHome, openExternal, showSend,
  openWalletSettings: (view) => openWalletSettings(view),
  // one page of the Settings hub, from anywhere (Notifications' gear)
  openSettingsPage: (page) => { clearFeatureNav(); ui.screen = 'wallet'; ui.tab = 'settings'; ui.settingsPage = page; render(); try { window.scrollTo(0, 0); } catch {} },
  fmtAmount, unitLabel, unitTag, getUnit: () => unit, toggleUnit, download, amountField,
  // in fiat the typed figure is money, so it needs today's price to become sats
  parseAmount: parseField,
  worthLine,
  openImage: (src) => { ui.lightbox = src; render(); },
  attachZoom: (box, img, opts) => attachZoom(box, img, opts),
  // What woke this run, if anything did, and how to say we're finished.
  // Both read through a closure: ctx is built before these are defined, and
  // a bare `wakeDone` shorthand captured the binding while it was still
  // undefined — the job then ran its full half minute every time.
  wakePayload: () => WAKE_PAYLOAD,
  wakeDone: () => wakeDone(),
  // "The next balance isn't a change, it's the first real value" — state
  // arriving late (the ark store opening past boot's patience) must not read
  // as money landing: without this the balance counts up from 0 in green,
  // which is the celebration a received payment gets.
  forgetAmountAnim: () => _amtLast.clear(),
  // Start at 21 sats; an explicitly saved preference wins across devices.
  zapDefaultSat: () => (wallet.loadFeatureState ? (wallet.loadFeatureState('prefs', {}).zapSat ?? 21) : 21),
  setZapDefaultSat: (n) => {
    const p = wallet.loadFeatureState('prefs', {});
    p.zapSat = Math.max(1, Math.floor(n) || 0);
    wallet.saveFeatureState('prefs', p);
    try { wallet.saveCache(); } catch {}
  },
  // the tap's sound effect — on unless switched off from the held-⚡ screen
  zapSound: () => !wallet.loadFeatureState || wallet.loadFeatureState('prefs', {}).zapSound !== false,
  setZapSound: (on) => {
    const p = wallet.loadFeatureState('prefs', {});
    if (on) delete p.zapSound; else p.zapSound = false;
    wallet.saveFeatureState('prefs', p);
    try { wallet.saveCache(); } catch {}
  },
  // Per-recipient auto-pay budget: a fixed-amount LNURL/address the user
  // trusts to pay without confirmation, up to this many sats. Keyed by the
  // recipient's address/lnurl. Synced with the rest of prefs.
  lnBudget: (key) => {
    if (!key || !wallet.loadFeatureState) return 0;
    return (wallet.loadFeatureState('prefs', {}).lnBudgets || {})[key] || 0;
  },
  setLnBudget: (key, sat) => {
    if (!key) return;
    const p = wallet.loadFeatureState('prefs', {});
    p.lnBudgets = { ...(p.lnBudgets || {}) };
    if (sat > 0) p.lnBudgets[key] = Math.floor(sat); else delete p.lnBudgets[key];
    wallet.saveFeatureState('prefs', p);
    try { wallet.saveCache(); } catch {}
  },
  brandHeader, languagePicker, activeAccount, setAccounts: (list) => { accounts = list; },
  getAccounts: () => accounts,
  claimTargets, enterWallet, activateAccount, commitAccount,
  // cross-feature calls (e.g. gifts asking the ark feature for ark-gift
  // support) — lazy so it resolves against the final FEATURES list, and a
  // build without the target feature simply gets null back
  hook: (name, ...args) => featureHook(name, ...args),
  // full sign-out (distinct from the padlock's lock-in-place): clear the
  // session and leave — offering a password if none protects the vault yet
  logout: () => {
    lock({ offerPassword: true });
    // Logging out means the front door, not the password prompt: land on the
    // start page (Get started / sign in). Saved wallets stay one Unlock away.
    if (!ui.pw) { ui.screen = 'unlock'; ui.unlockTab = 'create'; ui.onb = { step: 'welcome' }; render(); }
  },
  // The drastic exit: leave AND remove everything saved on this device.
  // Routes through the Delete-all warning — never a single tap.
  // The popup has already shown the delete-everything warning by the time
  // this runs — wipe now and land on the front door.
  // identity switching lives on the profile page (the Accounts screen is
  // about Spending/Savings faces, not who you are)
  signInAnother, identities, switchIdentity, signOutIdentity, identityRecoverable,
  logoutForget: () => {
    ui.profilePk = null; ui.profEdit = null; ui.profEditFilled = false; ui.chatOpen = false;
    ui.pubProf = null;
    clearAll();
  },
  // the identity the header avatar currently wears (login > seed key >
  // remembered) — profile "mine"-ness must match what the user clicked
  shownPubkey: () => (featureHook('nostrLoginIdentity') || {}).pubkey
    || (wallet.nostrPubkey && wallet.nostrPubkey()) || (activeAccount() || {}).nostrPk || null,
  getAccount: () => accountSel(),
  setAccount: (a, dir) => setAccountSel(a, dir),
  // Open (or create) a wallet from a mnemonic — used by nostr login.
  openMnemonic: async (mnemonic, passphrase, opts) => enterWallet(mnemonic, passphrase, opts),
  // Profile pictures retain the metadata-scrubbing image uploader. Public
  // post media uses resilient Blossom storage and media-specific failures.
  uploadImage: (file) => onbUpload(file),
  uploadMedia: (file) => publicMediaUpload(file),
  // A nostr login that lands mid-wizard: a restored wallet has been through
  // onboarding elsewhere, so the wizard ends without tour or prompts; a fresh
  // one falls through to the wallet + tour on the next render.
  onbNostrLogin: (restored) => {
    if (!ui.onb) return;
    if (restored) { ui.onb = null; try { localStorage.removeItem(ONB_STEP_KEY); } catch {} }
  },
};
// Android wrapper intents: the TWA app (android/) registers for lightning:/
// bitcoin:/nostr:/lnurl: URIs and forwards them here as ?u=<encoded>. Read
// BEFORE features construct: a nostr npub/nprofile rewrites itself onto the
// existing /npub… profile deep link (which the messages feature reads at
// construction); payment URIs stash for dispatch once a wallet is open.
// Woken by the Android wrapper (see android/, WakeJob): the wallet is being
// loaded off-screen to deal with something. The payload is read once, here,
// because whether anything CAN be done depends on whether a wallet opens at
// all — and if none does, the job should end straight away rather than hold
// a WebView open for half a minute over a locked wallet.
const WAKE_PAYLOAD = (() => {
  try {
    const w = new URLSearchParams(location.search).get('wake');
    if (w == null) return null;
    history.replaceState(null, '', location.pathname || '/');
    return w;
  } catch { return null; }
})();
const wakeDone = () => {
  try { if (WAKE_PAYLOAD != null && window.CoinosHost && window.CoinosHost.done) window.CoinosHost.done(); } catch {}
};

// v3.coinos.io/pos: the point of sale, straight away — a bookmark or a
// home-screen icon for the till. Consumed here (before any feature reads
// the path) and opened once a wallet is up; the pos feature owns the rest.
const BOOT_POS = (() => {
  try {
    if (!/^\/pos\/?$/i.test(location.pathname)) return false;
    history.replaceState(null, '', '/' + (location.search || ''));
    return true;
  } catch { return false; }
})();
if (BOOT_POS) ui.posAtBoot = true;
// v3.coinos.io/migrate: a link to hand someone who hasn't found the
// coinos.io move in the UI. Stashed (not just flagged) because the page it
// leads to needs an open wallet and a payment address — a fresh device gets
// there through the whole wizard, a locked one through its unlock. A day
// later the link's intent is stale and is dropped unannounced.
if ((() => {
  try {
    if (!/^\/migrate\/?$/i.test(location.pathname)) return false;
    history.replaceState(null, '', '/' + (location.search || ''));
    return true;
  } catch { return false; }
})()) {
  try { localStorage.setItem(MIGRATE_LINK_KEY, String(Date.now())); } catch {}
}
const INTENT_URI = (() => {
  try {
    const u = new URLSearchParams(location.search).get('u');
    if (!u) return null;
    history.replaceState(null, '', location.pathname || '/');
    // web+nostr: is what a browser hands a registered protocol handler
    // (njump's "Your default web app"); nostr: is the Android intent
    const m = u.match(/^(?:web\+)?nostr:((npub|nprofile|note|nevent)1[a-z0-9]+)\/?$/i);
    if (m) { history.replaceState(null, '', '/' + m[1]); return null; }
    return u.replace(/^web\+/i, '');
  } catch { return null; }
})();
const FEATURES = buildFeatures(ctx);
// Deferred features (gifts, NWC, POS) hold placeholder slots in FEATURES —
// hook precedence is position — and arrive as separate chunks right after
// boot, filled in place. If a wallet opened before they landed, each newcomer
// gets the init() it missed; if the wallet locked again, it doesn't.
let _featuresInited = false;
const _deferredReady = (async () => {
  try {
    const late = await loadDeferredFeatures(ctx, FEATURES);
    if (_featuresInited) for (const f of late) { try { f.init && f.init(); } catch {} }
    if (late.length) render();
  } catch (e) { console.error('deferred features failed to load', e); }
})();

// apply text direction, then restore a wallet left open in this tab — otherwise
// show the unlock screen.
applyDir();
// Auto log-out: start the countdown only when the app loses focus / is hidden,
// and cancel it the moment it's focused again. So it never logs out mid-use.
// Swipe left/right moves between the main tabs, the way thumbs expect.
// Horizontal-dominant, quick, and only on the wallet's own tab pages — never
// inside chat, profiles, takeovers, or the (offline-forced) settings tab.
(() => {
  const ORDER = ['history', 'receive', 'send'];
  let sx = 0, sy = 0, t0 = 0, live = false, onBalance = false, swallowClick = false;
  window.addEventListener('click', (e) => {
    if (!swallowClick) return;
    swallowClick = false;
    e.stopPropagation();
    e.preventDefault();
  }, true);
  window.addEventListener('touchstart', (e) => {
    live = e.touches.length === 1 && ui.screen === 'wallet' && !ui.chatOpen && !ui.profilePk
      && !ui.arkExitPage && ORDER.includes(ui.tab);
    if (!live) return;
    // the carousel owns its own drag — the flip gesture only serves the
    // single-face balance (kind-locked / savings-only wallets)
    if (e.target.closest && e.target.closest('.bal-carousel')) { live = false; return; }
    onBalance = !!(e.target.closest && e.target.closest('.balance'));
    sx = e.touches[0].clientX;
    sy = e.touches[0].clientY;
    t0 = Date.now();
  }, { passive: true });
  window.addEventListener('touchcancel', () => { live = false; }, { passive: true });
  window.addEventListener('touchend', (e) => {
    if (!live) return;
    live = false;
    const t = e.changedTouches[0];
    const dx = t.clientX - sx, dy = t.clientY - sy;
    if (Date.now() - t0 > 600 || Math.abs(dx) < 60 || Math.abs(dx) < 1.8 * Math.abs(dy)) return;
    // A touch sequence still fires a compatibility click at the release
    // point; after a swipe that would ALSO press whatever is under the
    // finger. Swallow exactly one click.
    swallowClick = true;
    setTimeout(() => { swallowClick = false; }, 400);
    // a swipe that began on the balance card flips the account instead
    if (onBalance) {
      const want = dx < 0 ? 'savings' : 'spending';
      if (spendingActive()) setAccountSel(want, dx < 0 ? 'left' : 'right');
      return;
    }
    // The swipe surfaces form ONE RING that loops:
    //   … page0 ⇄ page1 … lastPage ⇄ Receive ⇄ Send ⇄ page0 …
    // Swiping left over the history list turns pages older (the pager's
    // Next); at the last page it wraps into Receive, then Send, then back to
    // page 0. Swiping right from page 0 goes the other way — Send, then
    // Receive, then the LAST page. No dead ends anywhere.
    const resets = () => {
      // same resets as a tab-bar tap
      ui.sendError = '';
      ui.revealShown = false;
      ui.txDetail = null;
      ui.arkMoveDetail = null;
      ui.arkReconDetail = null;
      ui.giftDetail = null;
      ui.addrScan = false;
      ui.bump = null;
      ui.giftMode = false;
    };
    const goTab = (tab) => { _swipeDir = dx < 0 ? 'left' : 'right'; ui.tab = tab; resets(); render(); };
    // entering history from a wrap lands on a chosen page (an oversized
    // index clamps to the last page in historyTab)
    const goHist = (page) => { _swipeDir = dx < 0 ? 'left' : 'right'; ui.tab = 'history'; resets(); ui.txPage = page; render(); };
    if (ui.tab === 'history') {
      // a detail view / spinner / empty list publishes no pager — treat it
      // as a single page so the swipe still reaches the tabs
      const { page, pages } = _histPager || { page: 0, pages: 1 };
      if (dx < 0) { if (page < pages - 1) { ui.txPage = page + 1; render(); } else goTab('receive'); }
      else if (page > 0) { ui.txPage = page - 1; render(); }
      else goTab('send');
      return;
    }
    if (ui.tab === 'receive') { if (dx < 0) goTab('send'); else goHist(1e9); return; }
    if (ui.tab === 'send') { if (dx < 0) goHist(0); else goTab('receive'); return; }
  }, { passive: true });
})();

window.addEventListener('blur', onAppHidden);
window.addEventListener('focus', onAppVisible);
document.addEventListener('visibilitychange', () => {
  if (document.visibilityState === 'hidden') onAppHidden();
  else onAppVisible();
});
// Claim a stashed migrated name as soon as a wallet is actually open — a
// vault unlock or slow boot can put that minutes after 'load'. The stash
// survives reloads, so an unfinished claim resumes on the next visit too.
// Dispatch a stashed payment intent (lightning:/bitcoin:/lnurl: from the
// Android wrapper) once a wallet is actually open — a locked vault or slow
// boot can put that well after load. handleScanned routes it exactly like a
// scanned QR: bolt11s and lnurls through the feature chain, bitcoin: through
// BIP-21 (nostr profile intents already rerouted onto the /npub deep link).
const LN_INTENT = /^(lightning:|lnurl|lnbc|lntb|lntbs|lnbcrt|lno1|noffer1)|^[^\s:@/]+@[^\s@/]+\.[a-z]{2,}$/i;
if (INTENT_URI) {
  const started = Date.now();
  const tick = setInterval(() => {
    if (Date.now() - started > 10 * 60_000) return clearInterval(tick);
    if (!activeAccount() || !wallet.loaded || ui.screen !== 'wallet') return;
    clearInterval(tick);
    ui.tab = 'send';
    // A lightning:lnurl… (or ln-address, bolt11, offer) intent — an NFC tap
    // at a till — often lands BEFORE the feature that pays it is ready (ark
    // connects lazily, so zaps' matchSendText declines). Hold it on the same
    // paying shell the tap flow shows, never the raw URI in the recipient
    // field, and hand it over the moment a feature claims it; only after a
    // long wait does it fall back to the form like a scan.
    if (featureMatchSend(INTENT_URI)) return render();
    if (!LN_INTENT.test(INTENT_URI)) { render(); return handleScanned(INTENT_URI); }
    ui.intentWait = true;
    render();
    const waitStart = Date.now();
    const retry = setInterval(() => {
      const claimed = ui.intentWait && featureMatchSend(INTENT_URI);
      if (!claimed && ui.intentWait && Date.now() - waitStart < 20_000) return;
      clearInterval(retry);
      const wasWaiting = ui.intentWait;
      ui.intentWait = false;
      if (!claimed && wasWaiting) handleScanned(INTENT_URI);
      render();
    }, 150);
  }, 500);
}

// Chip strips (the feed chips, a profile's lists) scroll sideways: a finger
// swipes them, a mouse drags them. A drag that moved isn't a click on the
// chip it started on.
(() => {
  let drag = null;
  document.addEventListener('pointerdown', (e) => {
    if (e.pointerType !== 'mouse' || e.button !== 0) return;
    const el = e.target.closest && e.target.closest('.feed-chips');
    if (!el || el.scrollWidth <= el.clientWidth) return;
    drag = { el, x: e.clientX, left: el.scrollLeft, moved: false };
  });
  document.addEventListener('pointermove', (e) => {
    if (!drag) return;
    const dx = e.clientX - drag.x;
    if (!drag.moved && Math.abs(dx) < 5) return;
    drag.moved = true;
    drag.el.classList.add('dragging');
    drag.el.scrollLeft = drag.left - dx;
  });
  const end = () => {
    if (!drag) return;
    const d = drag; drag = null;
    d.el.classList.remove('dragging');
    if (!d.moved) return;
    const eat = (ev) => { ev.stopPropagation(); ev.preventDefault(); };
    document.addEventListener('click', eat, { capture: true, once: true });
    setTimeout(() => document.removeEventListener('click', eat, { capture: true }), 0); // a release off the strip has no click to eat
  };
  document.addEventListener('pointerup', end);
  document.addEventListener('pointercancel', () => { if (drag) drag.el.classList.remove('dragging'); drag = null; });
})();

// The feed scrolls like a phone on a desktop. A mouse wheel's notch gives
// it a push that coasts and slows, so a few turns travel a few posts and
// quick turns stack up; a trackpad (which already coasts) is left alone.
// And a mouse can grab the feed and flick it: drag up or down, let go while
// moving and it keeps going. A drag that starts sideways is still a text
// selection, and a drag that moved isn't a click on what it started on.
(() => {
  if (typeof window === 'undefined' || matchMedia('(prefers-reduced-motion: reduce)').matches) return;
  const SCOPE = '.feed-page, .notes-feed';
  const TAU = 325; // ms: how quickly a coast dies down (the phone's feel)
  const VMAX = 16; // px/ms
  const inScope = (t) => {
    const el = t && t.closest ? t : t && t.parentElement;
    if (!el || !el.closest(SCOPE)) return false;
    if (el.closest('input, textarea, select, video, audio, [contenteditable], .feed-chips, .lightbox, .media-pager')) return false;
    // something inside that scrolls on its own (a caption, a list) keeps its wheel
    for (let n = el; n && n !== document.body; n = n.parentElement) {
      if (n.scrollHeight > n.clientHeight + 1 && /(auto|scroll)/.test(getComputedStyle(n).overflowY)) return false;
    }
    return true;
  };
  let v = 0, acc = 0, raf = 0, last = 0, tau = TAU;
  let lastDir = 0, lastMoveAt = 0; // which way the coast last moved the page, and when
  const stop = () => { v = 0; acc = 0; if (raf) cancelAnimationFrame(raf); raf = 0; };
  const tick = (now) => {
    const dt = Math.max(0, Math.min(40, now - last)); last = Math.max(last, now); // a frame stamp can predate the push
    acc += v * dt;
    const step = Math.trunc(acc);
    if (step) {
      const y = window.scrollY;
      window.scrollBy({ top: step, behavior: 'instant' });
      acc -= step;
      lastDir = Math.sign(step); lastMoveAt = now;
      if (window.scrollY === y) return stop(); // an end of the page
    }
    v *= Math.exp(-dt / tau);
    if (Math.abs(v) < 0.02) return stop();
    raf = requestAnimationFrame(tick);
  };
  const coast = (nv, t = TAU) => {
    v = Math.max(-VMAX, Math.min(VMAX, nv)); tau = t;
    if (!raf && v) { last = performance.now(); raf = requestAnimationFrame(tick); }
  };
  // ---- the wheel
  // A turn back against the coast is a reader who flew past the post they
  // wanted and is hunting for it: the page is caught at once, and that notch
  // and the next few are short, quick steps (a quarter of a notch's travel,
  // settling fast) rather than a fresh flight the other way. Each notch on
  // in the same direction grows the step back towards a full one, so a few
  // flicks have the wheel flying again; a turn back while hunting starts the
  // small steps over, and a pause ends the hunt — the next notch is the
  // plain push from rest it has always been.
  const HUNT = [0.25, 0.35, 0.5, 0.7, 0.85]; // of a notch's travel, notch by notch
  const HUNT_TAU = 110; // ms: a hunting step settles quickly
  const HUNT_IDLE = 2000; // ms without a notch, and the hunt is over
  let hunt = -1, huntDir = 0, huntAt = 0; // the next HUNT entry while hunting
  const halt = () => { stop(); hunt = -1; };
  let smoothUntil = 0; // a trackpad's events were just seen: hands off
  window.addEventListener('wheel', (e) => {
    if (e.ctrlKey || e.shiftKey || e.defaultPrevented) return;
    const notch = e.deltaMode === 1 || (e.wheelDeltaY && e.wheelDeltaY % 120 === 0 && !e.deltaX);
    if (!notch) { smoothUntil = e.timeStamp + 400; halt(); return; }
    if (e.timeStamp < smoothUntil || matchMedia('(pointer: coarse)').matches || !inScope(e.target)) return;
    e.preventDefault();
    const px = e.deltaMode === 1 ? e.deltaY * 40 : e.deltaY;
    const dir = Math.sign(px);
    if (!dir) return;
    const now = e.timeStamp;
    if (hunt >= 0 && now - huntAt > HUNT_IDLE) hunt = -1;
    // the way the page is going: its coast, the coast that just died, or the hunt
    const going = v ? Math.sign(v) : now - lastMoveAt < 400 ? lastDir : hunt >= 0 ? huntDir : 0;
    if (going && dir !== going) { stop(); hunt = 0; huntDir = dir; }
    else if (hunt >= 0 && ++hunt >= HUNT.length) hunt = -1;
    if (hunt >= 0) {
      // A reversal catches the old coast immediately. Discard its fractional
      // step and frame clock too: after a busy frame, applying the NEW velocity
      // to the OLD elapsed time made the first reverse step jump. Give the
      // notch a small response now, then a quick coast over the rest of its
      // (short) travel; quick flicks still add up.
      huntAt = now;
      const travel = px * 3 * HUNT[hunt];
      const first = dir * Math.min(16, Math.abs(travel / HUNT_TAU) * 16);
      window.scrollBy({ top: first, behavior: 'instant' });
      lastDir = dir; lastMoveAt = now;
      coast(v + (travel - first) / HUNT_TAU, HUNT_TAU);
    } else {
      // A notch into a page already moving pushes harder: the faster it
      // goes, the more each turn adds (up to 2.5x), so keeping the wheel
      // turning winds the speed up instead of settling at a stroll. From
      // rest a notch is the same push as ever.
      const gain = 1 + Math.min(1.5, Math.abs(v) / 4);
      coast(v + (px * 3 * gain) / TAU, TAU);
    }
  }, { passive: false });
  // anything else that moves the page takes over from a coast
  window.addEventListener('keydown', (e) => { if (/^(Arrow|Page|Home|End| )/.test(e.key)) halt(); });
  window.addEventListener('touchstart', halt, { passive: true });
  // ---- grab and flick
  let drag = null;
  document.addEventListener('pointerdown', (e) => {
    if (raf) halt(); // a click catches a coasting page, like a finger does
    if (e.pointerType !== 'mouse' || e.button !== 0 || !inScope(e.target)) return;
    drag = { x: e.clientX, y: e.clientY, ly: e.clientY, on: false, pts: [] };
  });
  document.addEventListener('dragstart', (e) => { if (drag) e.preventDefault(); }, true); // images/links: scroll, don't drag them out
  document.addEventListener('pointermove', (e) => {
    if (!drag) return;
    if (!(e.buttons & 1)) { drag = null; return; }
    if (drag.sel) return;
    if (!drag.on) {
      const dx = Math.abs(e.clientX - drag.x), dy = Math.abs(e.clientY - drag.y);
      if (dx < 6 && dy < 6) return;
      // clearly sideways: selecting text (and still not a click on the post)
      if (dx > 2 * dy) { drag.sel = true; return; }
      drag.on = true;
      document.documentElement.classList.add('grab-scrolling');
      try { getSelection().removeAllRanges(); } catch {}
    }
    window.scrollBy({ top: drag.ly - e.clientY, behavior: 'instant' });
    drag.ly = e.clientY;
    drag.pts.push([e.timeStamp, e.clientY]);
    while (drag.pts.length > 2 && e.timeStamp - drag.pts[0][0] > 100) drag.pts.shift();
  });
  const end = (e) => {
    if (!drag) return;
    const d = drag; drag = null;
    if (!d.on && !d.sel) return;
    if (d.on) {
      document.documentElement.classList.remove('grab-scrolling');
      const p = d.pts, a = p[0], b = p[p.length - 1];
      // released while moving: throw it; held still first: just let go
      if (a && b && b[0] > a[0] && e.timeStamp - b[0] < 60) coast((a[1] - b[1]) / (b[0] - a[0]) * 2.4);
    }
    // the press moved: what it started on isn't opened (Chrome still clicks it)
    const eat = (ev) => { ev.stopPropagation(); ev.preventDefault(); };
    document.addEventListener('click', eat, { capture: true, once: true });
    setTimeout(() => document.removeEventListener('click', eat, { capture: true }), 300);
  };
  document.addEventListener('pointerup', end);
  document.addEventListener('pointercancel', () => { if (drag?.on) document.documentElement.classList.remove('grab-scrolling'); drag = null; });
})();

window.addEventListener('load', () => {
  if (!pendingMigratedName()) return;
  const started = Date.now();
  const tick = setInterval(() => {
    if (!pendingMigratedName() || Date.now() - started > 10 * 60_000) return clearInterval(tick);
    if (activeAccount()) { clearInterval(tick); claimMigratedName(); }
  }, 1000);
});
loadLocale(getLang()).finally(async () => {
  applyBootAutoLogout(); // clear an overdue session before we read it for claim targets
  // Public read-only community chat: no wallet, no login — the join material
  // ships in the bundle, so the page decrypts client-side (src/public-chat.js).
  // A share-anywhere link; its sign-in button leads back to the normal app.
  if (location.pathname === '/chat') {
    _publicChatMode = true; // app renders stand down — the page owns #app
    const m = await import('./public-chat.js');
    m.mountPublicChat();
    return;
  }
  // A gift link's feature is deferred — wait for it before asking who owns
  // the URL, or the claim would fall through to a normal boot and be lost.
  if (/^\/(g|ag|lg)\//.test(location.pathname)) await _deferredReady;
  if (featureHook('bootUrl')) return; // a feature consumed the URL (e.g. a gift claim)
  // The Spending balance and its history are read from an IndexedDB-backed
  // store, which is synchronous to read but asynchronous to OPEN. Opening a
  // wallet before it lands paints a Spending card with nothing in it, and the
  // real numbers arrive a beat later — a visible jump, and the balance
  // counted itself up in green as if money had just come in. The shell is on
  // screen either way; waiting shows it a moment longer rather than showing a
  // wrong balance. The hook caps its own wait.
  // The price, early: the unit toggle only offers fiat once we've had one,
  // and a wallet opening in fiat should open with a number in it.
  refreshRates().then(() => { if (unit === 'fiat') render(); }).catch(() => {});
  setInterval(() => { refreshRates().then(() => { if (unit === 'fiat') render(); }).catch(() => {}); }, 10 * 60_000);
  const storeReady = featureHook('arkStoreReady');
  // the IndexedDB caches (profiles, reports, …) open alongside: a wallet's
  // caches are read as soon as it opens
  await Promise.all([storeReady, cacheReady()].filter(Boolean)).catch(() => {});
  // Ask the browser not to evict this site's storage under disk pressure.
  // Chrome answers without a prompt (yes for an installed or busy site).
  try { navigator.storage?.persist?.().catch(() => {}); } catch {}
  _bootDeciding = false; // from here on the screen is a decision, not a guess
  const opened = restoreAccountsState();
  if (!opened) render();
  if (WAKE_PAYLOAD != null) {
    // Nothing opened — a locked vault, or no wallet on this device. There is
    // nothing to answer with, so say so now.
    if (!opened) wakeDone();
    // And a backstop: a wallet that opened but has no feature interested in
    // this payload must still end the job.
    else setTimeout(wakeDone, 40_000);
  }
});