aboutsummaryrefslogtreecommitdiffstats
path: root/Dockerfile.postgres
diff options
context:
space:
mode:
authorAdam Soltys <[email protected]>2024-06-22 11:19:47 -0700
committerAdam Soltys <[email protected]>2024-06-22 11:19:47 -0700
commite740bdeea9bff31b674110e042fcc7e41934ac41 (patch)
tree07ada7566f6208c287190e22d93ea096a7b5793d /Dockerfile.postgres
parent0b7f6a88d9e7fd3965981b3fb8987f47c3c027b8 (diff)
downloadcoinos-server-e740bdeea9bff31b674110e042fcc7e41934ac41.tar.gz
coinos-server-e740bdeea9bff31b674110e042fcc7e41934ac41.zip
disallow spaces in usernames
Diffstat (limited to 'Dockerfile.postgres')
0 files changed, 0 insertions, 0 deletions
='n167' href='#n167'>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
// 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, previewGift, giftOutpoints, buildClaimTx, giftMinimum, parseExtendedKey, xpubToZpub, encryptVault, decryptVault } from './wallet.js';
import { qrSvg } from './qr.js';
import { scanQr } from './scan.js';
import { getSyncConfig, setSyncConfig } from './nostr.js';
import { getExplorerConfig, setExplorerConfig, explorerPresets, getDataMode, setDataMode, electrumPresets, getElectrumServerConfig, setElectrumServerConfig, getNetwork, setNetwork, NETWORKS } from './api.js';
import { isSilentPaymentAddress } from './silentpay.js';
import { t, LANGS, getLang, setLang, isRTL, loadLocale } from './i18n.js';
import {
  fmtBtc,
  fmtSats,
  parseAmount,
  shortAddr,
  shortTxid,
  timeAgo,
  SATS,
} from './format.js';

const wallet = new Wallet();

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 on the verify step
  importText: '',
  passphrase: '',
  showPass: false,
  revealShown: false, // recovery phrase unmasked on the Backup tab (after the warning)
  pubkeyShown: false, // account public key revealed in Settings
  giftMode: false, // gift sub-view active on the Send page
  giftAmount: '', // gift-create amount input
  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)
  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)
  giftsAll: false, // History: showing the full paginated list of sent gifts
  giftsPage: 0, // History: current page within the all-gifts list
  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,
};

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);
  for (const [k, v] of Object.entries(attrs || {})) {
    if (v == null || v === false) continue;
    if (k === 'class') e.className = v;
    else if (k === 'html') e.innerHTML = 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')
      e.addEventListener(k.slice(2).toLowerCase(), v);
    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;
}

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://github.com/asoltys/halwallet', target: '_blank', rel: 'noopener' }, 'GitHub')
    ),
    h(
      'div',
      { style: 'margin-top:4px' },
      h('button', { class: 'linklike', style: 'font-weight:400', onClick: openHowItWorks }, t('howItWorks')),
      // 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'))
    ),
    h('div', { style: 'margin-top:8px' }, languagePicker())
  );
}

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 { document.documentElement.dataset.theme = resolvedTheme(); } 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';

function render() {
  const screen =
    ui.screen === 'wallet'
      ? walletScreen()
      : ui.screen === 'accounts'
        ? accountsScreen()
        : ui.screen === 'accountSettings'
          ? accountSettingsScreen()
        : ui.screen === 'vault'
          ? vaultScreen()
          : ui.screen === 'claim'
          ? claimScreen()
          : ui.screen === 'howItWorks'
            ? howItWorksScreen()
            : unlockScreen();
  root.replaceChildren(screen, footer());
  // 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 {}
  }
}
wallet.subscribe(render);

// ---------------------------------------------------------------- utilities
let toastTimer;
function toast(msg) {
  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'), 1600);
}

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>',
  });
}

// ---------------------------------------------------------------- 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 'btc' choice sticks.
  try {
    return localStorage.getItem(UNIT_KEY) === 'btc' ? 'btc' : 'sats';
  } catch {
    return 'sats';
  }
})();

function toggleUnit() {
  unit = unit === 'btc' ? 'sats' : 'btc';
  try {
    localStorage.setItem(UNIT_KEY, unit);
  } catch {}
  render();
}

const unitLabel = () => (unit === 'sats' ? 'sats' : 'BTC');
const fmtAmount = (sats) => (unit === 'sats' ? fmtSats(sats) : fmtBtc(sats));

// 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
function unlockScreen() {
  return h(
    'div',
    { class: 'col', style: 'gap:16px' },
    brandHeader(false),
    h(
      'div',
      { class: 'card col' },
      h(
        'div',
        { class: 'tabs' },
        tabBtn(t('createNew'), ui.unlockTab === 'create', () => { ui.unlockTab = 'create'; ui.unlockError = ''; render(); }),
        tabBtn(t('importExisting'), ui.unlockTab === 'import', () => { ui.unlockTab = 'import'; ui.unlockError = ''; render(); })
      ),
      ui.unlockTab === 'create' ? createPane() : importPane(),
      ui.unlockError && h('div', { class: 'notice err' }, ui.unlockError)
    ),
    ui.fromWallet && accounts.length
      ? 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'),
      para('hiwBasics4'),
      para('hiwBasics5'),
      h('p', { class: 'small muted hiw-tribute', style: 'margin:0' }, ...linkify(t('hiwTribute')))
    ),
    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'],
  ['Hal Finney', 'https://en.wikipedia.org/wiki/Hal_Finney_(computer_scientist)'],
];
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) {
  return h('button', { class: active ? 'active' : '', onClick }, label);
}

function createPane() {
  if (ui.createStep === 'gen') {
    if (!ui.draftMnemonic) {
      return h(
        'div',
        { class: 'col' },
        h('p', { class: 'muted' }, t('genIntro')),
        h(
          'button',
          {
            class: 'btn-primary btn-block',
            onClick: () => {
              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' },
        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(ui.draftMnemonic, t('copyPhrase')),
        h(
          'button',
          {
            class: 'btn-ghost btn-sm',
            onClick: () => {
              ui.draftMnemonic = newMnemonic();
              render();
            },
          },
          t('regenerate')
        )
      ),
      optionsPanel(),
      h(
        'button',
        {
          class: 'btn-primary btn-block',
          onClick: () => {
            ui.confirm = pickConfirm(words);
            ui.confirmPass = '';
            ui.unlockError = '';
            ui.createStep = 'confirm';
            render();
          },
        },
        t('verifyBackup')
      ),
      h(
        'button',
        { class: 'btn-block', onClick: () => openWallet(ui.draftMnemonic) },
        t('skipVerification')
      )
    );
  }

  // confirm step (optional — reachable via "Verify backup")
  const hasPass = !!ui.passphrase;
  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()),
        })
      )
    ),
    // Only verify the passphrase if one was actually entered.
    hasPass &&
      h(
        'label',
        { class: 'field' },
        h('span', { class: 'lab' }, t('reenterPassphrase')),
        h('input', {
          type: 'password',
          class: 'mono-input',
          autocomplete: 'off',
          value: ui.confirmPass,
          onInput: (e) => (ui.confirmPass = e.target.value),
        })
      ),
    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; }
          if (hasPass && ui.confirmPass !== ui.passphrase) {
            ui.unlockError = t('passphraseMismatch'); render(); return;
          }
          openWallet(ui.draftMnemonic);
        },
      }, t('openWallet'))
    ),
    h('button', { class: 'btn-block', onClick: () => openWallet(ui.draftMnemonic) }, 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: '' }));
}

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('div', { class: 'row between' },
        h('span', { class: 'lab' }, t('importLabel')),
        pasteBtn((text) => { ta.value = text; ui.importText = text; })
      ),
      ta
    ),
    optionsPanel(),
    h('button', { class: 'btn-primary btn-block', onClick: () => openWallet(ui.importText) }, t('openWallet'))
  );
}

function optionsPanel() {
  return h(
    'label',
    { class: 'field' },
    h('span', { class: 'lab' }, t('passphrase')),
    h(
      'div',
      { class: 'input-group' },
      h('input', {
        type: ui.showPass ? 'text' : 'password',
        class: 'mono-input',
        autocomplete: 'off',
        value: ui.passphrase,
        onInput: (e) => (ui.passphrase = e.target.value),
      }),
      h('button', { class: 'btn-sm', type: 'button', onClick: () => { ui.showPass = !ui.showPass; render(); } }, ui.showPass ? t('hide') : t('show'))
    )
  );
}

// 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) {
  ui.unlockError = '';
  const raw = (input || '').trim();
  const m = raw.replace(/\s+/g, ' ');
  if (isValidMnemonic(m)) { await enterWallet(m, ui.passphrase); 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 = {}) {
  const acc = addOrGetAccount({
    type: 'full',
    label: defaultLabel('full'),
    mnemonic: (mnemonic || '').trim().replace(/\s+/g, ' '),
    passphrase: passphrase || '',
  });
  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 = {}) {
  activeId = 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) acc.provisional = true;
  const netName = getNetwork();
  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 });
  // 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();
  persistAccounts();
  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.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; } })();
  ui.tab = (!opts.gift && nav && nav.tab) || 'receive';
  ui.txDetail = (!opts.gift && nav && 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.send = blankSend();
  ui.draft = null;
  ui.sendResult = null;
  ui.giftMode = false;
  ui.offlineFallback = 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);
      }
    }
    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? Verify its funding coin is still unspent before letting
    // the claim proceed — so a second opener can't try to race/double-spend.
    if (opts.gift) checkGiftClaimed(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 ? false : await wallet.syncFromNostr();
    if (!hadCache && !hadNostr) {
      await wallet.scan({ silent: false });
    }
    // 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 {
    enterOfflineFallback();
  }
}

// --- accounts -------------------------------------------------------------
// 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 || ''));
const activeAccount = () => accounts.find((a) => a.id === activeId) || 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 }));
  } catch { return []; }
}
function saveDirectory() {
  try {
    const dir = accounts.filter((a) => a.xpub && !a.provisional).map((a) => ({ id: a.id, label: a.label, xpub: a.xpub, autoLock: a.autoLock || 0 }));
    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) {
    acc = { id: genId(), ...partial };
    accounts.push(acc);
    persistAccounts();
  }
  return acc;
}

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

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) 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 {}
  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);
    return true;
  }
  if (hasVault()) {
    // A blank (optional) vault password unlocks seamlessly with no prompt.
    if (attemptVaultUnlock('')) {
      if (accounts.length) activateAccount(accounts[0], { fresh: true });
      else { ui.screen = 'unlock'; render(); }
      return true;
    }
    ui.screen = 'vault'; render(); return true;
  }
  const watch = loadWatchAccounts();
  if (watch.length) {
    accounts = watch.slice();
    activateAccount(accounts[0], { fresh: true });
    return true;
  }
  return false;
}

// --- encrypted vault (optional password-persisted full accounts) ----------
const VAULT_KEY = 'btc-wallet-vault';
let vaultPassword = null; // in memory once unlocked/set this session; cleared on lock

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 } : { label: a.label, mnemonic: a.mnemonic, passphrase: a.passphrase || '' }));
  try {
    if (!list.length) localStorage.removeItem(VAULT_KEY);
    else localStorage.setItem(VAULT_KEY, JSON.stringify(encryptVault(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) {
    const xpub = v.xprv ? accountXpubFor({ xprv: v.xprv }) : accountXpubFor({ mnemonic: v.mnemonic, passphrase: v.passphrase || '' });
    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;
      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 }
      );
      acc.persisted = true;
    }
  }
}

// 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.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.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() { 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.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';
  writeVault();
  persistAccounts();
  ui.pw = null;
  render();
}

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

// On-open vault unlock (password prompt).
function unlockVault() {
  if (!attemptVaultUnlock(ui.vaultPw)) { ui.vaultError = t('pwWrong'); render(); return; }
  ui.vaultPw = '';
  ui.vaultError = '';
  if (accounts.length) activateAccount(accounts[0], { 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(accounts[0], { 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 = 'receive';
  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 {}
}

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

// 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() {
  wallet.stopRealtime();
  clearAccounts();
  vaultPassword = null;
  wallet.load({ mnemonic: '', passphrase: '', netName: getNetwork(), offline: false });
  wallet.mnemonic = '';
  ui.screen = hasVault() ? 'vault' : 'unlock';
  ui.unlockTab = 'create';
  ui.fromWallet = false;
  ui.watchXpub = '';
  ui.watchLabel = '';
  ui.pw = null;
  ui.vaultPw = '';
  ui.vaultError = '';
  ui.confirmClear = false;
  ui.confirmRemove = null;
  ui.editId = null;
  ui.editLabel = '';
  ui.createStep = 'gen';
  ui.draftMnemonic = '';
  ui.importText = '';
  ui.passphrase = '';
  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;
  render();
}

// ================================================================ WALLET
function brandHeader(withLock) {
  const acc = activeAccount();
  return h(
    'div',
    { class: 'row between' },
    h(
      'div',
      { class: 'brand', style: 'cursor:pointer', title: t('home'), onClick: goHome },
      h('div', { class: 'logo' }, '₿'),
      h('h1', {}, t('appTitle'))
    ),
    withLock &&
      h('button', { class: 'btn-sm', onClick: () => { ui.screen = 'accounts'; render(); } },
        acc ? acc.label : t('accounts'))
  );
}

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

function settingsTab() {
  if (ui.addrScan && !wallet.offline) return addressScanView();
  return h(
    'div',
    { class: 'col', style: 'gap:16px' },
    // Quick link to the active wallet's own settings (name, seed, pubkey, auto-logout).
    activeAccount()
      ? h('div', { class: 'card col' },
          h('h3', {}, activeAccount().label),
          h('p', { class: 'small muted', style: 'margin:0' }, t('walletSettingsDesc')),
          h('button', { class: 'btn-primary btn-block', onClick: () => openAccountSettings(activeId) }, '⚙ ' + t('walletSettings'))
        )
      : null,
    // Recovery phrase + public key live on each wallet's own settings page now
    // (Accounts → ⚙). Watch-only wallets can still add their seed here.
    wallet.watchOnly
      ? (ui.loadSeed
          ? loadSeedCard()
          : h('div', { class: 'card col' },
              h('h3', {}, t('watchOnly')),
              h('p', { class: 'small muted', style: 'margin:0' }, t('watchOnlyNote')),
              activeAccount() && activeAccount().xpub
                ? h('button', { class: 'btn-primary btn-block', style: 'margin-top:4px', onClick: () => startLoadSeed() }, t('loadSeedBtn'))
                : null
            ))
      : null,
    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'))
    ),
    networkCard(),
    explorerCard(),
    wallet.watchOnly || !wallet.mnemonic ? null : syncCard()
  );
}


// Gift link: presign a chosen amount as a #gift= PSBT that whoever opens claims
// into a fresh wallet only they control. The coin is reserved until claimed.
function giftUrl() {
  return `${location.origin}/g/${ui.giftCode}`;
}
function giftRate() {
  return (wallet.feeRates && wallet.feeRates.halfHourFee) || 5;
}
function createGiftLink() {
  const rate = giftRate();
  if (ui.giftMax) { doCreateGiftAll(rate); return; }
  const min = giftMinimum(rate);
  const amt = parseAmount(ui.giftAmount, unit); // entered in the current display unit
  if (!amt || amt < min) { ui.giftError = t('giftAmountInvalid', { n: fmtAmount(min) + ' ' + unitLabel() }); render(); return; }
  const spendable = wallet.spendable;
  if (amt > spendable) { ui.giftError = t('giftExceedsBalance'); render(); return; }
  // A specific-amount gift must leave us a dust change output (the gift PSBT
  // commits one). If the amount is so close to the balance that no dust change
  // is possible, point the user at Max to gift the whole balance instead.
  const lock = wallet.giftLockPreview(amt);
  if (lock == null) {
    ui.giftError = t('giftNeedsHeadroom', { n: fmtAmount(Math.max(0, spendable - 294)) + ' ' + unitLabel() });
    render();
    return;
  }
  // Creating the gift now locks the whole source coin until it's claimed. If
  // best-fit can't find a near-exact coin, a pre-split would shrink the locked
  // change down to a dust pad (294) — worth offering only when the liquidity it
  // frees exceeds the split's own fee (otherwise you'd pay more than you regain).
  const splitFee = Math.ceil((11 + 68 + 31 * 2) * Math.max(1, Math.round(rate)));
  const freed = lock - amt - 294;
  if (freed > splitFee && !wallet.offline) {
    ui.giftSplitOffer = { amt, lock, freed, fee: splitFee };
    ui.giftError = '';
    render();
    return;
  }
  doCreateGift(amt, rate);
}
function doCreateGift(amt, rate) {
  try {
    ui.giftCode = wallet.createGift(amt, rate).code;
    ui.giftError = '';
    ui.giftSplitOffer = null;
  } catch (e) {
    ui.giftError = e.message;
    ui.giftSplitOffer = null;
  }
  render();
}
// Gift the whole spendable balance as a no-change sweep (the recipient receives
// everything minus their claim fee).
function doCreateGiftAll(rate) {
  try {
    ui.giftCode = wallet.createGiftAll(rate).code;
    ui.giftError = '';
    ui.giftMax = false;
    ui.giftSplitOffer = null;
  } catch (e) {
    ui.giftError = e.message;
  }
  render();
}
// Split + gift in one tap: broadcast a self-send carving out a right-sized
// coin, then immediately build the gift from that (unconfirmed) carve-out, so
// only ~the gift amount is locked and there's no confirmation wait. The link is
// ready right away; the recipient sees a pending balance until the split lands.
async function doSplitForGift(amt) {
  if (wallet.offline) { ui.giftError = t('scanOffline'); render(); return; }
  ui.busy = true; ui.giftError = ''; render();
  try {
    const rate = (wallet.feeRates && wallet.feeRates.halfHourFee) || 5;
    ui.giftCode = (await wallet.createGiftFromSplit(amt, rate)).code;
    ui.giftSplitOffer = null;
    ui.giftError = '';
  } catch (e) {
    ui.giftError = e.message || t('giftSplitFailed');
  }
  ui.busy = false;
  wallet.scan().catch(() => {}); // reconcile the split from the mempool
  render();
}
function giftCard() {
  const active = wallet.outstandingGifts();
  return h(
    'div',
    { class: 'card col' },
    h('h3', {}, t('giftLink')),
    ui.giftCode
      ? h('div', { class: 'col', style: 'align-items:center;gap:10px' },
          // Uppercase the whole URL + alphanumeric mode → much smaller QR. The
          // domain is case-insensitive and the base32 code is already uppercase;
          // the opener parses /g/ and the code case-insensitively.
          h('div', { html: qrSvg(giftUrl().toUpperCase(), { ec: 'L', mode: 'Alphanumeric' }) }),
          h('div', { class: 'addr-box break', style: 'width:100%;font-size:12px' }, giftUrl()),
          h('div', { class: 'row gap6 wrap' },
            copyBtn(giftUrl(), t('copyLink')),
            h('button', { class: 'btn-sm grow', onClick: () => { ui.giftCode = null; ui.giftAmount = ''; ui.giftMax = false; render(); } }, t('giftAnother'))
          )
        )
      : ui.giftSplitOffer
      ? (() => {
          const o = ui.giftSplitOffer;
          const u = ' ' + unitLabel();
          return h('div', { class: 'col gap6' },
            h('div', { class: 'small muted' },
              t('giftSplitExplain', { lock: fmtAmount(o.lock) + u, change: fmtAmount(o.lock - o.amt) + u, fee: fmtAmount(o.fee) + u })),
            ui.giftError && h('div', { class: 'notice err' }, ui.giftError),
            ui.busy
              ? h('button', { class: 'btn-primary btn-block', disabled: true }, h('span', { class: 'spinner' }))
              : h('div', { class: 'col gap6' },
                  h('button', { class: 'btn-primary btn-block', onClick: () => doSplitForGift(o.amt) }, t('giftSplitFirst')),
                  h('button', { class: 'btn-block', onClick: () => doCreateGift(o.amt, giftRate()) }, t('giftLockWhole', { n: fmtAmount(o.lock) + u })),
                  h('button', { class: 'linklike small', style: 'align-self:center', onClick: () => { ui.giftSplitOffer = null; render(); } }, t('back'))
                )
          );
        })()
      : h('div', { class: 'col gap6' },
          h('div', { class: 'input-group' },
            h('input', { type: 'number', step: unit === 'sats' ? '1' : '0.00000001', min: '0', inputmode: 'decimal', placeholder: t('giftAmountLabel'),
              disabled: ui.giftMax,
              value: ui.giftMax ? (unit === 'sats' ? String(wallet.spendable) : fmtBtc(wallet.spendable)) : ui.giftAmount,
              onInput: (e) => (ui.giftAmount = e.target.value) }),
            h('button', { type: 'button', class: ui.giftMax ? 'btn-primary' : '', onClick: () => { ui.giftMax = !ui.giftMax; ui.giftError = ''; render(); } }, t('max')),
            h('div', { style: 'display:flex;align-items:center' }, unitTag())
          ),
          h('div', { class: 'small faint' }, ui.giftMax ? t('giftAllNote') : t('giftMinNote', { n: fmtAmount(giftMinimum(giftRate())) + ' ' + unitLabel() })),
          ui.giftError && h('div', { class: 'notice err' }, ui.giftError),
          h('button', { class: 'btn-block', onClick: createGiftLink }, t('giftLinkReveal'))
        ),
    active.length
      ? h('div', { class: 'col gap6', style: 'margin-top:4px' },
          h('span', { class: 'small muted' }, t('giftReserved', { n: active.length })),
          ...active.map((g) => {
            const amt = g.value != null ? fmtAmount(g.value) + ' ' + unitLabel() : g.id.slice(0, 12) + '…';
            const label = amt + (g.reserved ? '' : ' · ' + t('giftReclaimedTag'));
            if (ui.revokeId === g.id) {
              return h('div', { class: 'col gap6' },
                h('span', { class: 'small muted' }, g.reserved ? t('giftReclaimPrompt') : t('giftRevokeConfirm')),
                ui.busy
                  ? h('button', { class: 'btn-primary btn-block', disabled: true }, h('span', { class: 'spinner' }))
                  : h('div', { class: 'row gap6' },
                      g.reserved ? h('button', { class: 'btn-ghost grow', onClick: () => doReclaim(g.id) }, t('giftReclaim')) : null,
                      h('button', { class: 'btn-primary grow', onClick: () => doRevoke(g.id) }, t('giftRevoke'))
                    ),
                ui.busy ? null : h('button', { class: 'btn-ghost btn-block', onClick: () => { ui.revokeId = null; render(); } }, t('back'))
              );
            }
            return h('div', { class: 'row between' },
              h('span', { class: 'small mono' }, label),
              h('button', { class: 'btn-sm', onClick: () => { ui.revokeId = g.id; render(); } }, g.reserved ? t('giftReclaim') : t('giftRevoke'))
            );
          })
        )
      : null
  );
}

// Passive reclaim: just free the coin for a future payment (no fee, no
// broadcast). The link stays claimable until the coin is actually spent.
function doReclaim(id) {
  wallet.unreserve(id);
  ui.revokeId = null;
  toast(t('giftReclaimed'));
  render();
}

// Active revoke: spend the coin back now (pays a fee), killing the link.
async function doRevoke(id) {
  if (wallet.offline) { toast(t('scanOffline')); return; }
  ui.busy = true;
  render();
  try {
    const rate = (wallet.feeRates && wallet.feeRates.fastestFee) || 10;
    await wallet.revokeGift(id, rate);
    ui.revokeId = null;
    toast(t('giftRevoked'));
    wallet.scan().catch(() => {});
  } catch (e) {
    toast(e.message);
  }
  ui.busy = false;
  render();
}

// Switch the active Bitcoin network. Changes addresses/balances entirely, so we
// persist the choice and reload the active account (or empty wallet) under it.
function changeNetwork(net) {
  if (net === getNetwork()) return;
  setNetwork(net);
  const acc = accounts.find((a) => a.id === activeId);
  if (acc) 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 mode = getDataMode();
  const cfg = getExplorerConfig();
  const ecfg = getElectrumServerConfig();
  const setMode = (m) => {
    if (m === getDataMode()) return;
    setDataMode(m);
    render();
    // electrum⇄explorer swaps the whole backend, so rebuild + rescan.
    if (!wallet.offline) wallet.reloadExplorer();
  };
  return h(
    'div',
    { class: 'card col' },
    h('h3', {}, t('dataSource')),
    h('p', { class: 'small muted', style: 'margin:0' }, t('dataSourceDesc')),
    h('select', { onChange: (e) => setMode(e.target.value) },
      h('option', { value: 'electrum', selected: mode === 'electrum' }, t('modeElectrum')),
      h('option', { value: 'explorer', selected: mode === 'explorer' }, t('modeExplorer'))
    ),
    mode === 'electrum'
      ? h('div', { class: 'col', style: 'gap:8px' },
          h('div', { class: 'small faint' }, t('backendElectrumDesc')),
          h('select', {
            onChange: (e) => { setElectrumServerConfig({ server: e.target.value, url: ecfg.url }); render(); if (e.target.value !== 'custom' || ecfg.url) wallet.reloadExplorer(); },
          }, electrumPresets(net).map((o) => h('option', { value: o.id, selected: o.id === ecfg.server }, o.label))),
          ecfg.server === 'custom'
            ? h('label', { class: 'field' },
                h('span', { class: 'lab' }, t('electrumUrl')),
                h('input', {
                  type: 'text', class: 'mono-input', placeholder: 'wss://your-node:50004',
                  autocapitalize: 'none', autocomplete: 'off', spellcheck: 'false', value: ecfg.url,
                  onChange: (e) => { setElectrumServerConfig({ server: 'custom', url: e.target.value.trim() }); wallet.reloadExplorer(); },
                }),
                h('div', { class: 'small faint' }, t('electrumUrlHint'))
              )
            : null
        )
      : null,
    mode === 'explorer'
      ? h('div', { class: 'col', style: 'gap:8px' },
          h('div', { class: 'small faint' }, t('modeExplorerDesc')),
          h('select', {
            onChange: (e) => { setExplorerConfig({ server: e.target.value, url: cfg.url }); render(); if (e.target.value !== 'custom' || cfg.url) wallet.reloadExplorer(); },
          }, explorerPresets(net).map((o) => h('option', { value: o.id, selected: o.id === cfg.server }, o.label))),
          cfg.server === 'custom'
            ? h('label', { class: 'field' },
                h('span', { class: 'lab' }, t('explorerUrl')),
                h('input', {
                  type: 'text', class: 'mono-input', placeholder: 'https://mempool.space/api',
                  autocapitalize: 'none', autocomplete: 'off', spellcheck: 'false', value: cfg.url,
                  onChange: (e) => { setExplorerConfig({ server: 'custom', url: e.target.value.trim() }); wallet.reloadExplorer(); },
                }),
                h('div', { class: 'small faint' }, t('explorerUrlHint'))
              )
            : null
        )
      : null
  );
}

// Cross-device sync settings: toggle + editable relay list (default coinos).
function syncCard() {
  const cfg = getSyncConfig();
  const setEnabled = (enabled) => {
    if (enabled === cfg.enabled) return;
    setSyncConfig({ enabled, relays: cfg.relays });
    render();
    // On enable, pull anything newer from the relays, then push our copy up.
    if (enabled && !wallet.offline) {
      wallet.syncFromNostr().catch(() => {}).finally(() => wallet.saveCache());
    }
  };
  return h(
    'div',
    { class: 'card col' },
    h('h3', {}, t('deviceSync')),
    h('p', { class: 'small muted', style: 'margin:0' }, t('deviceSyncDesc')),
    h('div', { class: 'row between' },
      h('span', { class: 'lab', style: 'margin:0' }, t('syncAcross')),
      h('div', { class: 'seg' },
        h('button', { type: 'button', class: cfg.enabled ? 'active' : '', onClick: () => setEnabled(true) }, t('syncOn')),
        h('button', { type: 'button', class: !cfg.enabled ? 'active' : '', onClick: () => setEnabled(false) }, t('syncOff'))
      )
    ),
    cfg.enabled
      ? h('label', { class: 'field' },
          h('span', { class: 'lab' }, t('relaysLabel')),
          h('textarea', {
            placeholder: 'wss://relay.example.com',
            autocapitalize: 'none', autocomplete: 'off', spellcheck: 'false',
            style: 'min-height:64px',
            value: cfg.relays.join('\n'),
            onInput: (e) => {
              const relays = e.target.value.split('\n').map((s) => s.trim()).filter(Boolean);
              setSyncConfig({ enabled: true, relays });
            },
          }),
          h('div', { class: 'small faint' }, t('relaysHint'))
        )
      : null
  );
}

// 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();
        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';
    ui.tab = wallet.offline ? 'settings' : 'receive';
    ui.draft = null;
    ui.sendResult = null;
    ui.sendError = '';
    ui.fromWallet = false;
  } else {
    ui.screen = 'unlock';
    ui.unlockTab = 'create';
    ui.createStep = 'gen';
    ui.draftMnemonic = '';
    ui.confirm = [];
    ui.unlockError = '';
  }
  render();
}

// ================================================================ GIFT / CLAIM
// Read a gift link, returning the code (and scrubbing it from the URL so the
// bearer instrument doesn't linger in the address bar / history). New links are
// /g/<base32-compact>; legacy links are #gift=<base64url-psbt>. Both validate by
// decoding to a real gift.
function readGiftHash() {
  try {
    let code = null;
    const pm = location.pathname.match(/^\/g\/([A-Za-z0-9]+)\/?$/i); // new path form
    if (pm) code = pm[1];
    else {
      const hm = location.hash.match(/^#gift=([A-Za-z0-9_-]+)$/); // legacy hash form
      if (hm) code = hm[1];
    }
    if (!code) return null;
    history.replaceState(null, '', '/');
    return previewGift(code) ? code : null;
  } catch {
    return null;
  }
}

// Has this gift already been claimed? Its funding coin being spent — even by an
// unconfirmed claim — means the gift is gone; show the "already claimed" screen
// rather than let the user attempt a doomed double-spend.
async function checkGiftClaimed(code) {
  const ops = giftOutpoints(code);
  if (!ops.length) { ui.claimChecking = false; render(); return; }
  try {
    const res = await wallet.api.outspend(ops[0].txid, ops[0].vout);
    if (res && res.spent) ui.claimTaken = { txid: res.txid || null };
  } catch {
    // Couldn't check (offline/transient) — leave it claimable; the broadcast in
    // doClaim is the final guard (a double-spend is rejected by the network).
  }
  ui.claimChecking = false;
  render();
}

// Broadcast the presigned gift to this fresh wallet's first receive address.
async function doClaim() {
  if (wallet.offline) { ui.claimError = t('scanOffline'); render(); return; }
  if (ui.claimChecking || ui.claimTaken) return; // not verified / already taken
  ui.busy = true;
  ui.claimError = '';
  render();
  try {
    const rate = (wallet.feeRates && wallet.feeRates.halfHourFee) || 5;
    const to = wallet.receive[0] ? wallet.receive[0].address : wallet.derive(0, 0).address;
    const claim = buildClaimTx(ui.claimCode, to, rate, wallet.netCfg.net);
    await wallet.broadcast(claim.hex);
    ui.claimedAmount = claim.amount;
    ui.claimStep = 'backup';
    commitAccount(); // claimed — this wallet now holds funds, keep it
    wallet.scan().catch(() => {});
  } catch (e) {
    // Broadcast failed — most likely someone claimed it in the race window.
    // Re-check the funding coin and, if spent, show the "already claimed" screen.
    const ops = giftOutpoints(ui.claimCode);
    if (ops.length) {
      try {
        const res = await wallet.api.outspend(ops[0].txid, ops[0].vout);
        if (res && res.spent) ui.claimTaken = { txid: res.txid || null };
      } catch {}
    }
    if (!ui.claimTaken) ui.claimError = t('claimFailed');
  }
  ui.busy = false;
  render();
}

// Gift-claim flow: a fresh wallet only the claimer controls. Step 'welcome'
// shows the amount + a Claim button; 'backup' (after a successful claim) shows
// the fresh recovery phrase to write down.
function claimScreen() {
  if (ui.claimStep === 'backup') {
    const words = wallet.mnemonic.split(' ');
    const claimed = ui.claimedAmount > 0; // false when "create a wallet anyway"
    return h(
      'div',
      { class: 'col', style: 'gap:16px' },
      brandHeader(false),
      h('div', { class: 'card col', style: 'align-items:center;text-align:center;gap:8px' },
        h('div', { style: 'font-size:72px;line-height:1' + (claimed ? ';color:var(--green)' : '') }, claimed ? '✓' : '🔑'),
        h('h2', { style: 'margin:0' }, claimed ? t('claimedTitle') : t('newWalletTitle')),
        h('p', { class: 'muted', style: 'margin:0' }, claimed ? t('claimedBody') : t('newWalletBody'))
      ),
      h('div', { class: 'card col' },
        h('h3', {}, t('recoveryPhrase')),
        h('div', { class: 'warn-box' }, t('writeDownWarn')),
        h('div', { class: 'words' },
          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(wallet.mnemonic, t('copyPhrase'))),
        h('button', { class: 'btn-primary btn-block', onClick: () => { ui.confirm = pickConfirm(words); ui.claimError = ''; ui.claimStep = 'verify'; render(); } }, t('verifyBackup')),
        h('button', { class: 'btn-block', onClick: () => { ui.screen = 'wallet'; ui.claimStep = null; render(); } }, t('skipVerification'))
      )
    );
  }
  if (ui.claimStep === 'verify') {
    // Same word-confirmation as new-wallet creation: prove the recipient wrote
    // the phrase down before sending them off into their freshly funded wallet.
    const words = wallet.mnemonic.split(' ');
    return h(
      'div',
      { class: 'col', style: 'gap:16px' },
      brandHeader(false),
      h('div', { class: 'card col' },
        h('h3', { style: 'margin-top:0' }, t('recoveryPhrase')),
        h('p', { class: 'muted', style: 'margin:0' }, 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()),
            })
          )
        ),
        ui.claimError && h('div', { class: 'notice err' }, ui.claimError),
        h('div', { class: 'row gap6' },
          h('button', { class: 'btn-ghost', onClick: () => { ui.claimStep = 'backup'; ui.claimError = ''; render(); } }, t('back')),
          h('button', {
            class: 'btn-primary grow',
            onClick: () => {
              const ok = ui.confirm.every((c) => c.value.toLowerCase() === words[c.index]);
              if (!ok) { ui.claimError = t('wordsMismatch'); render(); return; }
              ui.screen = 'wallet'; ui.claimStep = null; ui.claimError = '';
              render();
            },
          }, t('openWallet'))
        ),
        h('button', { class: 'btn-block', onClick: () => { ui.screen = 'wallet'; ui.claimStep = null; render(); } }, t('skipVerification'))
      )
    );
  }
  // While verifying the gift is still unclaimed, show a loading screen rather
  // than flashing the claimable amount (which would then jump to "already
  // claimed" for a spent gift).
  if (ui.claimChecking) {
    return h(
      'div',
      { class: 'col', style: 'gap:16px' },
      brandHeader(false),
      h('div', { class: 'card col', style: 'align-items:center;text-align:center;gap:14px;padding:32px 14px' },
        h('span', { class: 'spinner' }),
        h('p', { class: 'muted', style: 'margin:0' }, t('giftChecking'))
      )
    );
  }
  // Already claimed (funding coin spent, possibly only in the mempool) — show a
  // dead end with a link to the claim, instead of a claimable amount.
  if (ui.claimTaken) {
    return h(
      'div',
      { class: 'col', style: 'gap:16px' },
      brandHeader(false),
      h('div', { class: 'card col', style: 'align-items:center;text-align:center;gap:12px' },
        h('div', { style: 'font-size:56px;line-height:1' }, '🎁'),
        h('h2', { style: 'margin:0' }, t('giftTakenTitle')),
        h('p', { class: 'muted', style: 'margin:0' }, t('giftTakenBody'))
      ),
      // A fresh wallet was already generated for the claim — offer to keep it,
      // view the claim on a block explorer, or head back to the home screen.
      h('button', { class: 'btn-primary btn-block', onClick: () => { ui.claimTaken = null; ui.claimedAmount = 0; ui.claimStep = 'backup'; commitAccount(); render(); } }, t('createWalletAnyway')),
      ui.claimTaken.txid
        ? h('a', { class: 'btn btn-block', href: wallet.api.explorerTx(ui.claimTaken.txid), target: '_blank', rel: 'noopener', onClick: (e) => { e.preventDefault(); openExternal(wallet.api.explorerTx(ui.claimTaken.txid)); } }, t('viewOnMempool'))
        : null,
      h('button', { class: 'btn-ghost btn-block', onClick: goHome }, t('goToHome'))
    );
  }
  const pv = previewGift(ui.claimCode);
  // The headline is the full amount received (inputs minus the sender's change).
  // The network fee is determined now, at claim time, and comes out of that
  // amount — we surface the estimate on the Claim button so it isn't a surprise.
  const rate = Math.max(1, Math.round((wallet.feeRates && wallet.feeRates.halfHourFee) || 5));
  const estFee = pv ? Math.ceil((11 + 68 * pv.inputs + 31 * 2) * rate) : 0;
  const total = pv ? pv.room : 0;
  return h(
    'div',
    { class: 'col', style: 'gap:16px' },
    brandHeader(false),
    h('div', { class: 'card col', style: 'align-items:center;text-align:center;gap:12px' },
      h('div', { class: 'check-badge', style: 'background:var(--accent)' }, '🎁'),
      h('h2', { style: 'margin:0' }, t('giftWelcome')),
      h('div', { class: 'amt', style: 'font-size:30px' },
        h('span', { class: 'amount-pos' }, fmtAmount(total)), ' ', unitTag('unit')
      ),
      h('p', { class: 'muted', style: 'margin:0' }, t('claimBody'))
    ),
    ui.claimError && h('div', { class: 'notice err' }, ui.claimError),
    ui.busy || ui.claimChecking
      ? h('button', { class: 'btn-primary btn-block', disabled: true }, h('span', { class: 'spinner' }))
      : h('button', { class: 'btn-primary btn-block', onClick: doClaim },
          t('claimBtn'), ' ',
          h('span', { style: 'font-size:0.85em;opacity:0.9' }, '(' + t('claimFeeNote', { n: fmtAmount(estFee) + ' ' + unitLabel() }) + ')'))
  );
}

// Account switcher: pick a wallet, add another, or lock the session.
function accountsScreen() {
  if (ui.pw) return h('div', { class: 'col', style: 'gap:16px' }, brandHeader(false), pwPromptCard());
  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 ? acc.label : '' })),
        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' },
    brandHeader(false),
    h('div', { class: 'card col' },
      h('h3', {}, t('accounts')),
      h('div', { class: 'col', style: 'gap:0' },
        accounts.map((a) => {
          const isActive = a.id === activeId;
          const tag = a.type === 'watch' ? ' · ' + t('watchOnlyTag') : ''; // "saved" shown in the link below, not the title
          if (ui.editId === a.id) {
            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: () => { if (isActive) { ui.screen = 'wallet'; render(); } else switchAccount(a.id); },
              }, (isActive ? '● ' : '○ ') + a.label + tag),
              h('button', { class: 'btn-sm', title: t('walletSettings'), onClick: () => openAccountSettings(a.id) }, '⚙'),
              h('button', { class: 'btn-sm', title: t('remove'), onClick: () => { ui.confirmRemove = a.id; render(); } }, '✕')
            ),
            a.type === 'full'
              ? 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.screen = 'unlock'; ui.unlockTab = 'create'; ui.fromWallet = true; ui.unlockError = ''; render(); } }, t('addWallet')),
      hasVault() ? 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: () => { ui.screen = 'wallet'; render(); } }, t('back'))
  );
}

function renameAccount(id) {
  const acc = accounts.find((a) => a.id === id);
  if (acc) {
    const v = (ui.editLabel || '').trim();
    if (v) acc.label = 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: name, auto-logout, recovery phrase, and public key — for
// any account (not just the active one; full accounts keep their seed in memory).
function accountSettingsScreen() {
  const a = accounts.find((x) => x.id === ui.settingsId) || activeAccount();
  if (!a) { ui.screen = 'accounts'; return accountsScreen(); }
  const isWatch = a.type === 'watch' || (!a.mnemonic && !a.xprv);
  const shown = ui.revealShown;
  const words = a.mnemonic ? a.mnemonic.split(' ') : [];
  let zpub = '';
  try { if (a.xpub) zpub = xpubToZpub(a.xpub); } catch {}
  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: 'col', style: 'gap:16px' },
    brandHeader(false),
    // Recovery phrase (top)
    isWatch
      ? (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
            ))
      : !a.mnemonic
        ? h('div', { class: 'card col' }, h('h3', {}, t('importedKey')), h('p', { class: 'small muted', style: 'margin:0' }, t('importedKeyNote')))
        : h('div', { class: 'card col' },
            h('h3', {}, t('recoveryPhrase')),
            h('div', { class: 'warn-box' }, t('recoveryWarn')),
            h('div', { class: 'words' }, words.map((w, i) =>
              h('div', { class: 'w' + (shown ? '' : ' masked') }, h('span', { class: 'n' }, i + 1), h('span', { class: 't' }, shown ? w : '••••••')))),
            shown && a.passphrase
              ? h('div', { class: 'col gap6' }, h('span', { class: 'lab' }, t('bip39Passphrase')), h('div', { class: 'addr-box' }, a.passphrase))
              : null,
            shown
              ? 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('button', { class: 'btn-primary btn-block', onClick: () => { ui.revealShown = true; render(); } }, t('revealRecovery'))
          ),
    // Name
    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'))
      )
    ),
    // Public key (zpub)
    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'))
    ),
    // Auto-logout (bottom)
    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))))
    ),
    h('button', { class: 'btn-ghost btn-block', onClick: () => { ui.editLabel = null; ui.revealShown = false; ui.pubkeyShown = false; ui.loadSeed = null; ui.screen = 'accounts'; render(); } }, 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() {
  try { localStorage.removeItem(VAULT_KEY); } catch {}
  try { localStorage.removeItem(WATCH_KEY); } catch {}
  ui.confirmClear = false;
  lock();
}

function pwPromptCard() {
  const p = ui.pw;
  const change = p.purpose === 'change';
  const newish = change || p.mode === 'set'; // entering a (new) password with confirm
  return h('div', { class: 'card col' },
    h('h3', {}, change ? t('changePassword') : p.mode === 'set' ? t('setPassword') : t('enterPassword')),
    h('p', { class: 'small muted', style: 'margin:0' }, change ? t('changePasswordDesc') : p.mode === 'set' ? t('setPasswordDesc') : t('enterPasswordDesc')),
    change ? h('input', { type: 'password', placeholder: t('currentPassword'), value: p.v0, onInput: (e) => (p.v0 = e.target.value) }) : 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 }, t('back')),
      h('button', { class: 'btn-primary grow', onClick: submitPw }, newish ? t('save') : t('unlock'))
    )
  );
}

function vaultScreen() {
  return h(
    'div',
    { class: 'col', style: 'gap:16px' },
    brandHeader(false),
    h('div', { class: 'card col' },
      h('h3', {}, t('unlockSaved')),
      h('p', { class: 'small muted', style: 'margin:0' }, t('unlockSavedDesc')),
      h('input', { type: 'password', placeholder: t('password'), value: ui.vaultPw,
        onInput: (e) => (ui.vaultPw = e.target.value), onKeyDown: (e) => { if (e.key === 'Enter') unlockVault(); } }),
      ui.vaultError && h('div', { class: 'notice err' }, ui.vaultError),
      h('button', { class: 'btn-primary btn-block', onClick: unlockVault }, t('unlock')),
      h('button', { class: 'btn-ghost btn-block', onClick: skipVault }, t('useAnotherWallet'))
    )
  );
}

function walletScreen() {
  return h(
    'div',
    { class: 'col', style: 'gap:0' },
    brandHeader(true),
    h('div', { class: 'mt16' }, balanceCard()),
    ui.offlineFallback && wallet.offline ? offlineBanner() : null,
    tabsBar(),
    tabContent()
  );
}

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

function balanceCard() {
  // Only dim on the very first load; background updates happen silently.
  const firstLoad = wallet.scanning && !wallet.loaded;
  const locked = wallet.lockedValue;
  const pending = wallet.pendingIncoming;
  return h(
    'div',
    { class: 'card balance' },
    h('div', { class: 'small faint', style: 'text-transform:uppercase;letter-spacing:.05em' }, t('balance')),
    // Headline is the spendable balance: confirmed coins plus our own pending
    // change, minus gift locks — so a pending spend debits immediately, while a
    // pending incoming receive stays out of it until it confirms.
    h('div', { class: 'amt', style: firstLoad ? 'opacity:.3' : '' }, fmtAmount(wallet.spendable), ' ', unitTag('unit')),
    pending > 0 || locked > 0
      ? h(
          'div',
          { class: 'split' },
          pending > 0
            ? h('div', {}, h('div', { class: 'k' }, t('pending')), h('div', { class: 'v pending' }, fmtAmount(pending), ' ', unitTag()))
            : null,
          locked > 0
            ? h('div', {}, h('div', { class: 'k' }, t('lockedInGifts')), h('div', { class: 'v' }, fmtAmount(locked), ' ', unitTag()))
            : null
        )
      : null
  );
}

function tabsBar() {
  const tabs = [
    ['receive', t('tabReceive')],
    // Watch-only wallets show Send too — it prompts to load the seed to spend.
    ['send', t('tabSend')],
    ['history', t('tabHistory')],
    ['settings', t('tabSettings')],
  ];
  return h(
    'div',
    { class: 'tabs' },
    tabs.map(([id, label]) =>
      tabBtn(label, ui.tab === id, () => {
        ui.tab = id;
        ui.revealShown = false; // re-mask the recovery phrase whenever tabs change
        ui.txDetail = null; // back to the history list when leaving/returning
        ui.giftsAll = false; // and back to the paged history, not the all-gifts view
        ui.addrScan = false; // and back to the main Settings, not the address list
        ui.bump = null;
        ui.giftMode = false;
        render();
      })
    )
  );
}

function tabContent() {
  switch (ui.tab) {
    case 'receive': return receiveTab();
    case 'send': return sendTab();
    case 'history': return historyTab();
    case 'settings': return settingsTab();
  }
}

// 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() {
  const now = Date.now() / 1000;
  return wallet.txs.some((tx) => tx.net > 0 && (!tx.confirmed || (tx.blockTime && now - tx.blockTime < 2 * 3600)));
}

// ---------------------------------------------------------------- Receive
function receiveTab() {
  // 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'))
    );
  }

  const fresh = wallet.freshReceive();
  return h(
    'div',
    { class: 'card col', style: 'align-items:center;gap:14px' },
    h('div', { html: qrSvg(fresh.address) }),
    h('div', { class: 'addr-box', style: 'width:100%' }, fresh.address),
    copyBtn(fresh.address, 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('div', { class: 'row between' },
      h('h3', { style: 'margin:0' }, t('loadSeedTitle')),
      pasteBtn((text) => { seedTa.value = text; ls.value = text; })
    ),
    h('p', { class: 'small muted', style: 'margin:0' }, t('loadSeedDesc')),
    seedTa,
    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'))
    )
  );
}

function sendTab() {
  // 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();
  if (ui.broadcastTx) return broadcastConfirmView();
  if (ui.draft) return reviewView();
  if (ui.giftMode) return giftView();
  return sendForm();
}

// The gift UI as a send-page sub-view (entered from a link on the send form).
function giftView() {
  return h(
    'div',
    { class: 'col', style: 'gap:12px' },
    giftCard(),
    h('button', { class: 'btn-ghost btn-block', onClick: () => { ui.giftMode = false; ui.giftCode = null; ui.giftError = ''; ui.giftMax = false; ui.giftSplitOffer = null; ui.revokeId = null; render(); } }, t('back'))
  );
}

// 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 = '';

  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.bump = 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', 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).
function addrVerifyNodes(a) {
  const n = 6;
  if (!a) return [];
  if (a.length <= n * 2) return [document.createTextNode(a)];
  return [
    h('span', { class: 'hl' }, a.slice(0, n)),
    document.createTextNode(a.slice(n, -n)),
    h('span', { class: 'hl' }, a.slice(-n)),
  ];
}

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

  // Updated imperatively on input (and on render) so paste, typing, and scan
  // all reflect immediately without disrupting the input's focus/cursor.
  const check = h('div', { class: 'addr-check' });
  const syncCheck = () => {
    const a = r.address.trim();
    const nodes = addrVerifyNodes(a);
    if (a && isSilentPaymentAddress(a)) nodes.push(h('span', { class: 'small faint', style: 'margin-left:6px' }, '· ' + t('silentPaymentNote')));
    check.replaceChildren(...nodes);
    check.style.display = a ? '' : 'none';
  };

  const addrInput = h('input', {
    type: 'text', class: 'mono-input grow', placeholder: 'bc1q…',
    autocapitalize: 'none', autocomplete: 'off', spellcheck: 'false', value: r.address,
    onInput: (e) => { r.address = e.target.value; syncCheck(); },
  });
  const row = h(
    'div',
    { class: 'col gap6' },
    h('div', { class: 'input-group' },
      addrInput,
      pasteBtn((text) => { addrInput.value = text; r.address = text; syncCheck(); }),
      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(); } }, '✕')
    ),
    check,
    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 && h('button', { type: 'button', class: s.max ? 'btn-primary' : '', onClick: () => { s.max = !s.max; render(); } }, t('max'))
    )
  );
  syncCheck();
  return row;
}

function sendForm() {
  const s = ui.send;
  const feeOpts = [
    ['economyFee', t('feeEconomy')],
    ['halfHourFee', t('feeNormal')],
    ['fastestFee', t('feePriority')],
    ['custom', t('feeCustom')],
  ];
  return h(
    'div',
    { class: 'card col' },
    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))
      ),
      s.recipients.length < 10 &&
        h('button', {
          type: 'button', class: 'linklike small mt8',
          onClick: () => { s.recipients.push({ address: '', amount: '' }); s.max = false; render(); },
        }, t('addRecipient'))
    ),
    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() }))
    ),
    coinControl(),
    ui.sendError && h('div', { class: 'notice err' }, ui.sendError),
    h('button', { class: 'btn-primary btn-block', onClick: reviewSend }, t('reviewTx')),
    h('button', { class: 'linklike small', style: 'align-self:center;margin-top:2px', onClick: () => { ui.giftMode = true; ui.sendError = ''; render(); } }, '🎁 ' + t('giftLink'))
  );
}

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;
    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 = parseAmount(r.amount, unit);
        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' },
          o.silent
            ? h('span', { class: 'k col', style: 'gap:2px;align-items:flex-start' },
                h('span', { class: 'mono break' }, shortAddr(o.silent, 12, 8)),
                h('span', { class: 'small faint' }, t('silentPaymentNote'))
              )
            : 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
  );
}

// ---------------------------------------------------------------- History
// An outstanding sent gift shown in History: tappable to cancel (reclaim the
// coin for a future payment, or revoke the link on-chain) without going through
// the Send → gift card. Reuses the same confirm state and handlers.
function giftHistoryItem(g) {
  if (ui.revokeId === g.id) {
    return h('div', { class: 'item col', style: 'align-items:stretch;gap:8px' },
      h('span', { class: 'small muted' }, g.reserved ? t('giftReclaimPrompt') : t('giftRevokeConfirm')),
      ui.busy
        ? h('button', { class: 'btn-primary btn-block', disabled: true }, h('span', { class: 'spinner' }))
        : h('div', { class: 'row gap6' },
            g.reserved ? h('button', { class: 'btn-ghost grow', onClick: () => doReclaim(g.id) }, t('giftReclaim')) : null,
            h('button', { class: 'btn-primary grow', onClick: () => doRevoke(g.id) }, t('giftRevoke'))
          ),
      ui.busy ? null : h('button', { class: 'btn-ghost btn-block', onClick: () => { ui.revokeId = null; render(); } }, t('back'))
    );
  }
  return h('div', { class: 'item' },
    h('div', { class: 'ico out' }, '🎁'),
    h('div', { class: 'grow' },
      h('div', { class: 'row gap6' }, t('giftHistoryTitle'),
        h('span', { class: 'tag pending' }, g.reserved ? t('giftUnclaimedTag') : t('giftReclaimedTag'))),
      g.reserved ? h('div', { class: 'small faint' }, t('lockedInGifts')) : null
    ),
    h('div', { style: 'text-align:right' },
      g.value != null ? h('div', { class: 'amount' }, fmtAmount(g.value)) : null,
      h('button', { class: 'btn-sm', style: 'margin-top:4px', onClick: () => { ui.revokeId = g.id; render(); } }, t('giftCancel'))
    )
  );
}

function txHistoryItem(tx) {
  const incoming = tx.net >= 0;
  const stuck = !tx.confirmed && wallet.isStuck(tx);
  return h(
    'div',
    { class: 'item', style: 'cursor:pointer', onClick: () => openTx(tx.txid) },
    h('div', { class: `ico ${incoming ? 'in' : 'out'}` }, incoming ? '↓' : '↑'),
    h('div', { class: 'grow' },
      h('div', { class: 'row gap6' },
        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' },
      h('div', { class: incoming ? 'amount-pos' : 'amount-neg' }, (incoming ? '+' : '') + fmtAmount(tx.net)),
      !incoming && tx.fee ? h('div', { class: 'small faint' }, t('feeShort', { x: fmtAmount(tx.fee) })) : null
    )
  );
}

// Prev / page-of / next controls. Returns null when there's only one page.
const PAGE_SIZE = 10;
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', disabled: page <= 0, onClick: () => onPage(page - 1) }, t('prevPage')),
    h('span', { class: 'small muted' }, t('pageXofY', { x: page + 1, y: pages })),
    h('button', { class: 'btn-sm', disabled: page >= pages - 1, onClick: () => onPage(page + 1) }, t('nextPage'))
  );
}

// Full paginated list of outstanding sent gifts, reached via "View all" when
// there are more than fit inline on the History page.
function giftsAllView(gifts) {
  const pages = Math.ceil(gifts.length / PAGE_SIZE);
  const page = Math.min(ui.giftsPage, Math.max(0, pages - 1));
  const slice = gifts.slice(page * PAGE_SIZE, page * PAGE_SIZE + PAGE_SIZE);
  return h(
    'div',
    { class: 'card col', style: 'gap:12px' },
    h('div', { class: 'row between' },
      h('h3', { style: 'margin:0' }, t('giftReserved', { n: gifts.length })),
      h('button', { class: 'btn-sm', onClick: () => { ui.giftsAll = false; ui.revokeId = null; render(); } }, t('back'))
    ),
    h('div', { class: 'list' }, ...slice.map(giftHistoryItem)),
    pager(page, gifts.length, (p) => { ui.giftsPage = p; render(); })
  );
}

function historyTab() {
  if (ui.bump) return bumpView();
  if (ui.txDetail) {
    const tx = wallet.txs.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.scanning && !wallet.loaded) || (wallet.historyLoading && !wallet.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
    );
  // Outstanding sent gifts (reserved/reclaimed but unclaimed) sit above the
  // on-chain history; they aren't transactions until claimed or revoked.
  const gifts = wallet.loaded ? wallet.outstandingGifts() : [];
  if (ui.giftsAll && gifts.length) return giftsAllView(gifts);
  if (!wallet.txs.length && !gifts.length)
    return h('div', { class: 'card' }, h('p', { class: 'muted center', style: 'margin:0' }, t('noTxYet')));

  // Show at most 3 gifts inline; the rest live behind "View all". Transactions
  // paginate 10 at a time.
  const giftsHead = gifts.slice(0, 3);
  const txPages = Math.ceil(wallet.txs.length / PAGE_SIZE);
  const txPage = Math.min(ui.txPage, Math.max(0, txPages - 1));
  const txSlice = wallet.txs.slice(txPage * PAGE_SIZE, txPage * PAGE_SIZE + PAGE_SIZE);
  return h(
    'div',
    { class: 'card' },
    h('div', { class: 'list' },
      ...giftsHead.map(giftHistoryItem),
      ...txSlice.map(txHistoryItem)
    ),
    gifts.length > 3
      ? h('button', { class: 'btn-sm btn-block', style: 'margin-top:8px', onClick: () => { ui.giftsAll = true; ui.giftsPage = 0; ui.revokeId = null; render(); } }, t('viewAllGifts', { n: gifts.length }))
      : null,
    pager(txPage, wallet.txs.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.txs.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' }, (incoming ? '+' : '') + fmtAmount(tx.net)),
      ' ', 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,
      tx.fee ? line(t('networkFee'), fmtAmount(tx.fee) + ' ' + unitLabel()) : 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: () => { ui.txDetail = null; render(); } }, 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),
// 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.
window.addEventListener('blur', onAppHidden);
window.addEventListener('focus', onAppVisible);
document.addEventListener('visibilitychange', () => {
  if (document.visibilityState === 'hidden') onAppHidden();
  else onAppVisible();
});
loadLocale(getLang()).finally(() => {
  const code = readGiftHash();
  if (code) { enterWallet(newMnemonic(), '', { gift: code }); return; }
  applyBootAutoLogout(); // clear an overdue session before it's restored
  if (!restoreAccountsState()) render();
});