All files mainCode.js

89.34% Statements 1920/2149
79.3% Branches 774/976
93.57% Functions 335/358
90.62% Lines 1886/2081

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605                                                                                                                                                      270x     270x     270x 270x 270x 270x 270x 270x 270x 270x 270x 270x     270x     270x 106x 10x 10x 10x 10x 10x             270x 270x 270x 270x     270x 188x           270x 270x   8x 8x 8x 8x       8x   262x   50x 50x     50x 50x 50x         50x       270x   58x 116x 116x         212x 246x 58x         270x 270x 270x 270x 270x       4946x     4942x   4946x 40x 40x 40x         6x 6x 6x 6x 6x   6x 6x 6x 6x     6x       6x 6x 6x 6x 6x 6x 6x       12x   6x 6x   6x       6x 6x             12x 12x           12x       12x     6x         6x   6x 6x 6x   6x     6x           6x     6x 6x     6x 6x 6x       6x     6x 6x       6x       6x   6x     6x           6x     6x 6x     6x 6x 6x       6x 6x           270x 270x 5940x     270x         270x 2970x 2970x 2x 2x   2x       270x 270x 270x 2x             270x   270x 270x 270x       270x                                                                                                                             635723416x         4660x         4660x 4660x   4660x               4660x     648x   648x                                   4x           6x           4x           6x           408x             42x                     52x                   54x                 36x           28x                       12x             3360x 3360x                                                                                                   270x                         2x 2x     2x       270x     270x 270x 270x     270x 270x 270x 270x     270x                                     270x 270x       1746x 1038x 1034x 632453212x 3130434x 1232x 1416x 298x 270x 4202x 1174x 956x 902x                                                   674x 674x     102910x     1924x   30x     12844x   4x     9944x   4x     98328x   6x     1114x   6x       270x   97000x 97000x 97000x 97000x 97000x       404x   404x       404x 404x 404x     404x 404x 404x 404x     404x 404x 404x 404x 404x       404x 404x 404x 404x   404x       100x 100x 100x 100x 100x 100x 100x     66x 66x 66x 66x 66x     202x 202x 202x       270x       648x     648x                 648x     648x   648x 648x               648x 648x         648x     648x                         648x 7128x   648x 648x 648x   648x         4x   4x         4x 44x         192x         270x   448x 448x 448x 448x 448x     448x 448x   448x 448x 448x     448x         102830x 4760x 4730x     324x 454x       97772x 97772x   97772x 97772x 97772x                 448x 448x 448x 448x 448x 448x 448x 448x 448x 448x         358x 164x   358x 358x   304x 10x   304x         3360x 3360x   3360x 72618x 79239568x 79239568x   72618x 17490452x 17490452x 17490452x 17490452x   72618x 72618x 72618x   3360x 3360x 3360x 3360x 3360x 3360x 3360x     3360x 74x       3360x 752x                 588x 588x 588x 588x 588x   588x 588x   588x       104x 104x       166x 166x       72618x 14056x 14056x 14056x 14056x   11020x     11020x   11020x 11020x           580x 572x       580x 208x     372x           580x     580x 580x 580x 580x 217930864x 217930864x 217930864x 217930864x 56508x 56508x   217930864x           208x 208x   208x 208x   208x 208x 208x     208x 208x 208x     208x 208x 208x 208x   208x 208x   208x         3010076x   3010076x       3010076x 3010076x     3010076x     1313492x 1313492x     3010076x             3010076x 5242130x 5170614x 6758x       1306734x         208x         208x       208x 208x 208x   208x 208x     208x     208x 208x     208x 208x 208x 208x     208x           208x 208x 21412x 3010076x     1703342x 1703342x 1703342x 8516710x 42583550x                   208x 208x 208x 208x   208x 208x       208x         208x           2x     2x         72618x   62152x 62152x 79239568x 79239568x 79239568x     72618x   28176x 28176x 17490452x 17490452x 17490452x           146836x 146836x 146836x 146836x 146836x 146836x           1864x         54x   54x         6x 6x   6x 6x 6x     6x 6x 6x 6x 6x     6x 12x 12x 6x     6x                 6x 6x 6x 6x   6x 6x           6x     6x 6x     6x 6x 210x 840x 840x 840x 840x         6x 6x 6x 6x 6x     6x 6x 6x 6x 6x 6x 6x 6x 6x   6x         270x   270x 270x 270x 270x 270x 270x 270x 270x       270x 270x       448x 448x 448x     448x 140x     448x 410x   448x         38x 38x 38x         8x 8x 8x 16x   8x 8x       198x 152x 152x         1426x         1022x         3452x 3438x 78x   3360x 3360x     3360x 3360x                     3360x         216x                     3360x 3360x 1770x 1770x 72618x           492x 492x 746x 14x     746x   492x         360x 10x 8x   10x       360x 26x       360x 348x           360x     360x     360x 360x 360x     360x 360x 526x 526x 6x           360x 360x 360x           360x 360x 360x     360x 408x     408x     408x 408x   360x 360x 360x     360x 408x       122x 122x 122x 408x     360x 526x     526x 526x   526x 408x 118x 118x 118x       526x 118x       360x       360x 360x     360x 360x 526x 408x         360x 360x 526x 526x 118x 118x 118x 118x     118x 4x 4x           118x 62x 56x 54x       118x   118x 6x             360x   360x 708x 8x   708x   292x 292x 292x 292x 292x 292x     408x 408x 408x     708x 102x     708x     408x 408x 408x     360x       360x 360x 360x   44x 44x 44x 44x 44x   316x     10x         564x 564x 564x 564x 564x 564x 564x 564x 564x           564x 564x   564x 564x       564x 564x 564x 564x 564x 564x 564x                     8800x       4226x       1164x       446x 446x         12x 12x 12x         48x 48x 48x         2904x 2904x       28x       54x 8x 8x   54x 8x 8x 8x                 360x   360x 12x     360x 162x   360x   360x           336x 336x 152x       34x     336x     336x       4x 8x   4x       16x 16x 14x 12x     16x 16x 4x         28x 28x     28x     28x 28x   28x                       28x 28x   28x       28x   28x 28x   28x     28x 6x         28x 28x 28x               28x         28x 28x 28x 28x   28x 28x 28x       114x 114x 114x 114x         270x       390x 390x         270x       340x 340x         818x 818x   818x 818x 754x           270x 270x 270x   270x     270x 528x 528x 784x 776x   784x   510x     18x       270x 636x 636x 510x 510x   126x 126x         270x 234x 234x       270x 82x 82x       270x         270x   270x 270x 270x       228x 228x 228x 228x         228x   228x                 228x 228x 228x 228x 228x 228x         354x 354x 354x       356x 356x 356x 548x 528x 548x 528x 548x 174x 174x 174x     174x 174x   528x 528x 528x 528x   356x 354x         2x 2x 2x 2x 2x 2x   2x   2x 2x 2x         2x 2x       2x 2x         2x 2x 2x     2x     2x   2x     2x     2x 2x 2x             36x   36x       36x 36x 36x 36x 36x 36x 36x 36x 36x 36x     36x 36x   36x 36x   36x 36x       36x 36x 36x 2x 2x 2x   36x 36x 36x     36x       36x 36x 36x 36x 36x     36x 36x 36x           12x 12x 12x       12x 4x 4x   4x 4x 4x         12x 12x 6x   4x 2x             12x 6x 6x         12x     12x 10x 10x                               12x 6x         12x 2x 2x 2x 2x 2x           270x   270x 270x 270x   270x 270x     270x 270x   270x           28x     28x           28x     28x     28x 2x             28x 28x     28x 82x   28x         28x 28x 82x       28x   28x                   28x         28x     28x 28x   28x 28x   28x 28x               28x 28x   28x 28x   28x           28x 28x     28x 28x   28x 2x 2x       28x 28x 28x           28x           28x 2x 2x 2x               28x 28x     28x 28x 28x 82x 54x   82x           28x     82x 82x         80x 80x 80x 82x       28x   28x 82x 82x   82x   164x   82x     98x   78x 78x   78x 78x 78x       82x   4x       28x               58x   58x 58x 8x   50x 58x 58x       28x 28x 28x         28x             28x       448x     448x   28x   28x 28x   28x     420x 420x 420x 420x 420x     448x   448x   448x 86x   334x     420x 420x         734x 734x         728x 728x           270x       6x 6x 6x   6x 66x             4x           54x 54x       54x 52x   2x             60x           36x 36x 36x 36x 36x 36x                 50x   50x       50x               8x 8x   8x           18x           6x 6x               14x   14x 12x   14x                                       298x 298x     298x 270x       298x 298x 3278x 3278x 256x         298x 88x             298x 298x 108x 108x   254x     254x 76x                     178x                   298x 298x 6x         298x       450x 450x 450x 450x 450x 450x 1154x 1154x 1154x 1154x     504x   650x 200x 200x 200x 200x   650x 650x 200x 200x 200x       450x   450x     450x 450x 42x 42x     450x                                                       450x         270x   270x       270x 270x 270x 270x 270x 270x 270x         270x   270x 46x 10x       270x 48x   14x 14x 14x 14x 14x 14x         270x 2x   2x       2x 2x     2x 2x 2x     2x 2x 2x     2x                                 2x 2x                             2x 4x 4x 4x                 4x       4x       4x       2x       2x 2x 2x 2x           2x       2x 2x 2x                                                                     2x     2x 2x 2x 2x                                                                                                     2x     2x     2x 4x 4x 2x 2x 2x   2x 2x 2x           270x 270x 270x 2x           42x     42x 42x               42x 2x   42x 42x 40x 40x           40x 36x 36x     36x 36x           36x 36x   36x     6x       54x     54x 54x               54x 54x 54x 50x 50x 50x 50x             52x 52x             270x   270x       2x 2x 2x 2x                   4x 4x       4x 4x 4x 4x 4x 4x   4x                           2x 2x           6x 6x         24x 24x           4x 4x 4x         2x 2x           2x 2x         2x 2x           2x 2x                 4x 4x                     130x     130x   12x 12x       118x 122x 106x 98x           104x 104x 104x 104x 104x 104x 94x 94x 94x 94x 94x 94x 6x 6x 6x 6x   10x             200x 200x 396x 198x   2x       86x 86x   86x   86x       86x 86x 172x 172x   86x       86x 86x 172x 172x   86x         270x   270x 270x 270x 270x 270x 270x 270x 270x 270x 270x 270x 270x       28x     28x 28x         28x 28x 14x   14x         14x 14x 14x 14x 14x 2x 2x 2x           14x 14x 14x 14x         14x   14x             14x 14x 14x       14x 14x   14x 14x       2x 2x 2x 4x   4x     4x 4x 4x 4x   4x 4x 4x     4x 2x 2x 2x 2x 2x 2x                   4x 4x 4x 4x 4x     4x 2x 2x 2x 2x 2x   4x 4x     2x 4x   2x       2x 2x 2x 2x 2x   2x 2x 2x 2x   2x 2x 2x   2x   922x       922x 922x     922x 922x   922x       922x     922x 14x               922x     922x 2x 2x   2x 920x   920x     2x       14x 14x 14x 14x 14x   14x 2x 2x     14x 14x     14x 14x     14x   14x       2x   2x           2x           2x 2x       2x 2x 2x     2x               2x 2x 2x 2x     2x                             2x 2x 2x 2x 2x 2x 2x       2x 2x         2x                   2x 2x     2x     922x               922x 922x 922x 14x 14x                   2x                               2x 2x               2x 922x 922x   922x                   922x     922x       2x 2x     2x 2x 2x     2x 2x 2x     2x 2x     2x                 2x 2x 2x 2x   2x   4x 4x 4x       4x     4x         4x     2x       2x 2x 2x 2x 2x   2x 2x       926x 926x 926x 926x 926x   926x 926x 926x     926x 926x 926x 926x     926x 926x   926x     926x 926x 926x     926x     926x 926x       926x 926x   926x 926x   926x 926x 926x 926x 926x 926x 926x 926x   926x   926x     926x 804x 804x   926x     926x 804x 804x     804x 804x     804x 804x 804x 804x 804x 804x 804x 804x   804x   804x 804x   804x 804x       926x 922x 922x           270x   270x 270x 270x 270x 270x 270x 270x 270x 270x 270x 270x         392x   2x 2x     392x 392x 392x     392x         392x 392x 392x 392x 392x     392x 392x 392x     392x         392x               392x 392x 392x 392x                           452x 452x 392x 392x     452x 452x 452x 452x 452x     452x 452x   452x     452x                                                       48x   26x     22x 22x 22x 58x               152x 330x               1022x 1048x                   336x 336x 502x 502x       336x 336x 496x           336x             28x       5390x 5390x   5390x           442x   3452x     4946x 4946x 4946x 4946x   2x 2x           4946x 4946x 284x   284x 284x 284x   4946x 4x 4x     4x 8x 4x 4x   2x   2x 2x 2x   2x 2x       4x 2x           2x 2x 2x 2x 50x 50x 22x 22x     2x 2x 16x 16x 16x 22x   16x   16x       454x 184x 206x 842x   184x 184x       348x           4x               2x 16x 16x 2x                 2x 2x   2x     2x 2x 2x               2x           2x         270x   270x 270x 270x       86x 86x   86x 104x 104x 104x 104x 104x     86x 38x         140x 38x 38x         86x 86x 46x 46x         104x 104x 104x 104x 104x   104x 64x 64x       64x 64x 64x 64x 18x 18x 18x   46x   64x 50x         64x     64x 26x 8x   18x 18x 18x           18x   18x     38x     104x         104x 104x 104x 100x   104x 86x   104x 104x   104x 68x 132x 62x 26x   62x 62x       104x         82x 82x 82x 82x     82x 82x 2434x 2434x 2434x 2434x 2434x         2434x 2434x 2434x   82x       332x 332x 332x 332x 332x   332x 332x 332x 332x   332x 4282x 4282x 4282x 4282x 4282x 4282x 4282x 4282x 3116x 3116x 3116x             270x   270x 270x     6x   6x     6x     12x 6x 6x       12x 6x 6x 6x 6x 6x 6x   6x   6x                 434x 434x 434x     96x 96x     180x       82x 58x 32x       20x         90x 90x   90x       1490x 1490x 1328x 162x 76x   86x       42x     42x 42x     42x 42x 42x   42x 164x 164x 164x   164x   164x 164x 122x 122x 122x     164x   122x 122x 122x     42x     324x 324x 324x 324x     324x 324x   324x 324x   324x 324x     324x       52x   52x     97066x     97066x 97066x 97066x 97066x     97066x     97066x 97066x     97066x 97066x 97066x     97066x 291198x   97066x     291198x 291198x 24828x   266370x         292912x 292912x 292912x 234142x       11020x   11020x             11020x 11020x 11020x   11020x 605684x 605684x 605684x     11020x 11020x     11020x 11020x 11020x 605684x 605684x   11020x 11020x     11020x       270x    
 
// =============================================================================
// MANDELBROT FRACTAL EXPLORER - APPLICATION ARCHITECTURE
// =============================================================================
//
// This application renders the Mandelbrot set with deep zoom capabilities,
// GPU acceleration, and extended-precision mathematics (DD and QD) for
// trillion-fold magnification.
//
// CORE COMPONENTS:
//
// 1. MandelbrotExplorer - Main application controller (this class below)
//    - Initializes all subsystems
//    - Coordinates application lifecycle
//    - Manages fullscreen mode and theme cycling
//
// 2. StateStore - Centralized state container
//    - Holds all application state in immutable tree
//    - Provides dispatch() to update state via actions
//    - Maintains action log for debugging
//
// 3. Config - Configuration facade
//    - Property getters/setters that delegate to StateStore
//    - Handles viewport sizing and color themes
//    - Maintains backward compatibility
//
// 4. Grid - Canvas and view manager
//    - Creates/destroys View objects for each zoom level
//    - Manages canvas DOM elements
//    - Coordinates with Scheduler for worker threads
//
// 5. View - Individual zoom level rendering
//    - Stores pixel iteration data
//    - Renders to canvas using color themes
//    - Manages multi-resolution compositing
//
// 6. Board subclasses - Fractal computation engines (run in worker threads)
//    - CpuBoard: Basic CPU computation
//    - PerturbationBoard: DD precision deep zoom (CPU)
//    - DDZhuoranBoard: Period detection for convergence (CPU)
//    - GpuBoard: WebGPU parallel computation
//    - GpuZhuoranBoard: WebGPU with period detection and perturbation
//
// UPDATE CYCLE EXAMPLE:
//
//   User clicks canvas to zoom
//     ↓
//   EventHandler → ZoomManager.cellclick()
//     ↓
//   Grid.makeView() creates new View and canvas
//     │
//     ├─→ Scheduler assigns Board to worker thread
//     │     ↓
//     │   Worker computes iterations, sends progress updates
//     │     ↓
//     │   Grid.updateViewFromWorkerResult() updates View
//     │     ↓
//     │   View.color() renders pixels to canvas
//     │
//     └─→ Grid.notifyurl() → URLHandler.updateurl() syncs browser URL
//
// OTHER CLASSES:
//
// - EventHandler: Mouse and keyboard input processing
// - ZoomManager: Zoom rectangle selection and coordinate calculation
// - URLHandler: Browser URL synchronization for bookmarking/sharing
// - Scheduler: Worker thread pool management and load balancing
// - MovieMode: Smooth zoom video recording and MP4 generation
// - OrbitComputer: Hover-to-show orbit visualization
// - RedrawProcess: Progressive rendering coordination
// - ReferenceOrbitThreading: Deep zoom perturbation helper
//
// =============================================================================
 
// Main application controller that coordinates all subsystems.
class MandelbrotExplorer {
  constructor() {
    // Create unified state store
    this.store = new StateStore();
 
    // Create subsystems with state store integration
    this.config = new Config(this.store);
    this.grid = new Grid(this.config, this.store);
    this.zoomManager = new ZoomManager(this.config, this.grid);
    this.urlHandler = new URLHandler(this.config, this.grid, this.store);
    this.eventHandler = new EventHandler(this);
    this.movieMode = new MovieMode(this);
    this.orbitComputer = new OrbitComputer(this);
    this.redrawProcess = new RedrawProcess(this);
    this.movieContainer = document.getElementById('movie');
    this.allViewsCompleted = false;
 
    // Listen for fullscreen changes
    document.addEventListener('fullscreenchange', () => this.onFullscreenChange());
 
    // Clear native tooltip when hovering over zoom numbers to show custom tooltip
    document.addEventListener('mouseover', (e) => {
      if (e.target.classList.contains('zoomnum') || e.target.closest('.zoomnum')) {
        const isZoomnum = e.target.classList.contains('zoomnum');
        const zoomnum = isZoomnum ? e.target : e.target.closest('.zoomnum');
        const gridDiv = zoomnum.closest('#grid > div');
        if (gridDiv) {
          gridDiv.setAttribute('title', '');
        }
      }
    });
  }
 
  start() {
    this.startTime = Date.now();
    console.log(new Date);
    let startState = this.urlHandler.parseUrl();
    this.config.initSizes();
 
    // Fill in default sizes if none were specified in URL
    if (startState.sizes.length === 0) {
      startState.sizes = this.config.firststate().sizes;
    }
 
    // Convert zoom/size from URL to absolute size
    // zoomFromUrl: {mantissa, exponent} from z= parameter
    // sizeFromUrl: {mantissa, exponent} from s= parameter (legacy)
    let actualSize = null;
    if (this.config.sizeFromUrl !== undefined) {
      // s= parameter: size value directly (e.g., s=1e-15)
      const { mantissa, exponent } = this.config.sizeFromUrl;
      delete this.config.sizeFromUrl;
      const size = mantissa * Math.pow(10, exponent);
      if (size === 0 || !isFinite(size)) {
        console.warn(`Size too extreme, capping at minimum supported size (~3e-310)`);
        actualSize = 3e-310;
      } else {
        actualSize = size;
      }
    } else if (this.config.zoomFromUrl !== undefined) {
      // z= parameter: {mantissa, exponent} for extreme zoom values
      const { mantissa, exponent } = this.config.zoomFromUrl;
      delete this.config.zoomFromUrl;
      // Compute size = firstsize / zoom = (firstsize / mantissa) * 10^(-exponent)
      // Now firstsize has the correct aspect-ratio-adjusted value
      const baseSize = this.config.firstsize / mantissa;
      const size = baseSize * Math.pow(10, -exponent);
      if (size === 0 || !isFinite(size)) {
        // Cap at ~1e310 zoom to ensure pixel sizes remain representable
        console.warn(`Zoom too extreme, capping at maximum supported zoom (~1e310)`);
        actualSize = 3e-310;
      } else {
        actualSize = size;
      }
    }
 
    if (actualSize !== null) {
      // Fill in sizes with the zoom-adjusted value
      for (let i = 0; i < startState.sizes.length; i++) {
        if (startState.sizes[i][0] === null) {
          startState.sizes[i][0] = actualSize / Math.pow(this.config.zoomfactor, i);
        }
      }
    } else {
      // Fill in sizes with default firstsize
      for (let i = 0; i < startState.sizes.length; i++) {
        if (startState.sizes[i][0] === null) {
          startState.sizes[i][0] = this.config.firstsize / Math.pow(this.config.zoomfactor, i);
        }
      }
    }
 
    this.initPlatform();
    this.grid.updateLayout(startState);
    this.grid.setupFullscreenButtonHover();
    this.eventHandler.setup();
    this.grid.updateHiddenViews(); // Initial update of hidden boards
  }
 
  checkAllViewsComplete() {
    if (this.allViewsCompleted) return;
 
    // Check if all views are done
    const allDone = this.grid.views.every(view => view && view.un === 0);
 
    if (allDone && this.grid.views.length > 0) {
      this.allViewsCompleted = true;
      const elapsed = Date.now() - this.startTime;
      console.log(`All views completed in ${(elapsed / 1000).toFixed(2)}s`);
    }
  }
 
  cycleUnknownColor(backward) {
    const palette = this.config.unknownColorPalette;
    const inc = backward ? palette.length - 1 : 1;
    const currentIndex = palette.indexOf(this.config.unknowncolor);
    const ind = (currentIndex + inc) % palette.length;
    this.config.setUnknowncolor(palette[ind]);
    // Update div backgrounds instead of redrawing canvases
    for (let k = 0; k < this.grid.views.length; ++k) {
      const canvas = this.grid.canvas(k);
      if (canvas && canvas.parentElement) {
        canvas.parentElement.style.backgroundColor = this.config.unknowncolor;
      }
    }
    this.urlHandler.updateurl();
  }
 
  cycleColorTheme(backward) {
    const inc = backward ? this.config.colorThemes.all.length - 1 : 1;
    const themes = this.config.colorThemes.all;
    const currentIndex = themes.indexOf(this.config.theme);
    const nextIndex = (currentIndex + inc) % themes.length;
    this.config.setTheme(themes[nextIndex]);
    this.redrawProcess.start();
    this.urlHandler.updateurl();
  }
 
  toggleFullscreen() {
    if (!document.fullscreenElement) {
      // Save pre-fullscreen settings
      this.preFullscreenGridcols = this.config.gridcols;
      this.preFullscreenAspectRatio = this.config.aspectRatio;
 
      document.documentElement.requestFullscreen().catch(err => {
        console.log(`Error attempting to enable fullscreen: ${err.message}`);
      });
    } else {
      if (document.exitFullscreen) {
        document.exitFullscreen();
      }
    }
  }
 
  onFullscreenChange() {
    // Update state
    if (this.store) {
      this.store.dispatch(
        this.store.actions.setFullscreen(!!document.fullscreenElement)
      );
    }
 
    // Exit movie mode if active
    if (this.movieMode.active) {
      this.movieMode.toggle();
    }
 
    if (document.fullscreenElement) {
      // Entering fullscreen
      // Only process if grid has views
      if (!this.grid.views || this.grid.views.length === 0) {
        return;
      }
 
      // Delay to allow browser to fully transition to fullscreen
      setTimeout(() => {
        // Calculate fullscreen aspect ratio from actual window dimensions
        const viewportWidth = window.innerWidth;
        const viewportHeight = window.innerHeight;
        const viewportAspectRatio = viewportWidth / viewportHeight;
 
        const oldFirstsize = this.config.firstsize;
 
        // Set grid to 1 column and aspect ratio to match viewport (batched)
        this.store.dispatch(this.store.actions.updateConfig({
          gridcols: 1,
          aspectRatio: viewportAspectRatio
        }));
 
        // Get current state before recalculating sizes
        const state = this.grid.currentGridState();
 
        // Call initSizes to recalculate dimensions for fullscreen
        this.config.initSizes();
        const newFirstsize = this.config.firstsize;
 
        // Scale all existing view sizes proportionally
        const scaleFactor = newFirstsize / oldFirstsize;
        for (let i = 0; i < state.sizes.length; i++) {
          state.sizes[i][0] *= scaleFactor;
        }
 
        // Skip initSizes in updateLayout since we already called it
        this.grid.updateLayout(state, true);
 
        // Only update URL if we have views
        if (this.grid.views && this.grid.views.length > 0) {
          this.urlHandler.updateurl();
        }
 
        // Scroll to top immediately
        window.scrollTo(0, 0);
      }, 100);  // 100ms delay to allow fullscreen transition
    } else {
      // Exiting fullscreen - restore pre-fullscreen settings
      if (this.preFullscreenGridcols !== undefined && this.grid.views &&
          this.grid.views.length > 0) {
        const oldFirstsize = this.config.firstsize;
 
        // Restore pre-fullscreen settings (batched)
        this.store.dispatch(this.store.actions.updateConfig({
          gridcols: this.preFullscreenGridcols,
          aspectRatio: this.preFullscreenAspectRatio
        }));
 
        // Get current state before recalculating sizes
        const state = this.grid.currentGridState();
 
        // Call initSizes to recalculate dimensions
        this.config.initSizes();
        const newFirstsize = this.config.firstsize;
 
        // Scale all existing view sizes proportionally
        const scaleFactor = newFirstsize / oldFirstsize;
        for (let i = 0; i < state.sizes.length; i++) {
          state.sizes[i][0] *= scaleFactor;
        }
 
        // Skip initSizes in updateLayout since we already called it
        this.grid.updateLayout(state, true);
        this.urlHandler.updateurl();
      }
    }
  }
 
  initPlatform() {
    if (this.config.mac) {
      for (let el of document.querySelectorAll('[mac]')) {
        el.innerHTML = el.getAttribute('mac');
      }
    }
    if (this.config.mobile) {
      for (let el of document.querySelectorAll('[mobile]')) {
        el.innerHTML = el.getAttribute('mobile');
      }
    }
    for (let el of document.querySelectorAll('.moviemode')) {
      el.href = '#movie';
      el.onclick = (() => {
        if (this.grid.views.length > 1) {
          this.movieMode.toggle();
        }
        return true;
      });
    }
    // Set up fullscreen button
    const fullscreenButton = document.getElementById('fullscreen-button');
    if (fullscreenButton) {
      fullscreenButton.onclick = () => {
        this.toggleFullscreen();
      };
    }
  }
}
 
// Centralized state management with action dispatch pattern.
class StateStore {
  constructor() {
    this.state = this.createInitialState();
    this.actionLog = [];  // For debugging
    this.enableLogging = false;  // Set to true for debugging
  }
 
  createInitialState() {
    return {
      // Viewport and rendering configuration
      config: {
        // Canvas dimensions
        vw: 0,                    // Viewport width
        gridcols: 1,              // Number of grid columns
        cssDims: 0,               // CSS pixel size
        cssDimsWidth: 0,          // CSS width
        cssDimsHeight: 0,         // CSS height
        dimsWidth: 0,             // Canvas pixel width
        dimsHeight: 0,            // Canvas pixel height
        pixelRatio: 2,            // Device pixel ratio
 
        // Computation parameters
        exponent: 2,              // Mandelbrot exponent (z^n + c)
        enableGPU: true,          // Allow WebGPU acceleration
        forceBoard: null,         // Force specific board type
        debug: null,              // Debug string for controlling behaviors
 
        // Display parameters
        theme: 'warm',            // Color theme
        unknowncolor: '#000',     // Color for uncomputed pixels
        zoomfactor: 5,            // Default zoom factor
        aspectRatio: 1.0,         // Default aspect ratio
 
        // Initial view parameters
        firstsize: 3.0,           // Initial view size
 
        // Platform detection
        mobile: false,
        mac: false
      },
 
      // Views (zoom levels)
      views: [],  // Array of { k, sizes: [size, re, im], hidden, parentK }
 
      // UI state
      ui: {
        mouseDown: false,
        mouseButton: null,
        mousePosition: { x: 0, y: 0 },
        focusedView: null,        // Currently focused view index
        zoomRectangle: null,      // { k, x, y, width, height }
        orbitPoint: null,         // { k, x, y, orbit: [...] }
        movieMode: {
          active: false,
          progress: 0,
          rendering: false
        },
        fullscreen: false
      },
 
      // Computation status (updated from workers)
      computation: {
        views: {},                // k -> { un, di, ch, it, workerInfo, boardType }
        isComputing: false,
        allCompleted: false
      }
    };
  }
 
  // Get current state (immutable)
  getState() {
    return this.state;
  }
 
  // Dispatch an action to update state
  dispatch(action) {
    if (this.enableLogging) {
      console.log('Action:', action.type, action);
      console.log('Old state:', JSON.parse(JSON.stringify(this.state)));
    }
 
    const oldState = this.state;
    this.state = this.reducer(this.state, action);
 
    if (this.enableLogging) {
      console.log('New state:', JSON.parse(JSON.stringify(this.state)));
      this.actionLog.push({ action, oldState, newState: this.state, timestamp: Date.now() });
    }
  }
 
  // Reducer: pure function that computes new state from old state + action
  reducer(state, action) {
    switch (action.type) {
      // Configuration updates
      case 'CONFIG_INIT_SIZES': {
        const { vw, gridcols, cssDims, cssDimsWidth, cssDimsHeight,
                dimsWidth, dimsHeight, pixelRatio, firstsize } = action;
        return {
          ...state,
          config: {
            ...state.config,
            vw,
            gridcols,
            cssDims,
            cssDimsWidth,
            cssDimsHeight,
            dimsWidth,
            dimsHeight,
            pixelRatio,
            firstsize
          }
        };
      }
 
      case 'CONFIG_SET_ASPECT_RATIO':
        return {
          ...state,
          config: { ...state.config, aspectRatio: action.aspectRatio }
        };
 
      case 'CONFIG_SET_THEME':
        return {
          ...state,
          config: { ...state.config, theme: action.theme }
        };
 
      case 'CONFIG_SET_PIXEL_RATIO':
        return {
          ...state,
          config: { ...state.config, pixelRatio: action.pixelRatio }
        };
 
      case 'CONFIG_SET_UNKNOWN_COLOR':
        return {
          ...state,
          config: { ...state.config, unknowncolor: action.unknowncolor }
        };
 
      case 'CONFIG_UPDATE':
        return {
          ...state,
          config: { ...state.config, ...action.config }
        };
 
      // UI state updates
      case 'UI_MOUSE_DOWN':
        return {
          ...state,
          ui: {
            ...state.ui,
            mouseDown: true,
            mouseButton: action.button,
            mousePosition: action.position
          }
        };
 
      case 'UI_MOUSE_UP':
        return {
          ...state,
          ui: {
            ...state.ui,
            mouseDown: false,
            mouseButton: null
          }
        };
 
      case 'UI_MOUSE_MOVE':
        return {
          ...state,
          ui: {
            ...state.ui,
            mousePosition: action.position
          }
        };
 
      case 'UI_SET_FOCUSED_VIEW':
        return {
          ...state,
          ui: { ...state.ui, focusedView: action.k }
        };
 
      case 'UI_MOVIE_MODE_TOGGLE':
        return {
          ...state,
          ui: {
            ...state.ui,
            movieMode: {
              ...state.ui.movieMode,
              active: !state.ui.movieMode.active
            }
          }
        };
 
      case 'UI_SET_FULLSCREEN':
        return {
          ...state,
          ui: { ...state.ui, fullscreen: action.fullscreen }
        };
 
      // Computation status updates
      case 'COMPUTATION_UPDATE_VIEW': {
        const { k, un, di, ch, it, workerInfo, boardType } = action;
        return {
          ...state,
          computation: {
            ...state.computation,
            views: {
              ...state.computation.views,
              [k]: { un, di, ch, it, workerInfo, boardType }
            }
          }
        };
      }
 
      default:
        return state;
    }
  }
 
  // Action creators (convenience methods)
  actions = {
    // Config actions
    initSizes: (sizes) => ({ type: 'CONFIG_INIT_SIZES', ...sizes }),
    setAspectRatio: (aspectRatio) => ({ type: 'CONFIG_SET_ASPECT_RATIO', aspectRatio }),
    setTheme: (theme) => ({ type: 'CONFIG_SET_THEME', theme }),
    setPixelRatio: (pixelRatio) => ({ type: 'CONFIG_SET_PIXEL_RATIO', pixelRatio }),
    setUnknownColor: (unknowncolor) => ({ type: 'CONFIG_SET_UNKNOWN_COLOR', unknowncolor }),
    updateConfig: (config) => ({ type: 'CONFIG_UPDATE', config }),
 
    // UI actions
    mouseDown: (button, position) => ({ type: 'UI_MOUSE_DOWN', button, position }),
    mouseUp: () => ({ type: 'UI_MOUSE_UP' }),
    mouseMove: (position) => ({ type: 'UI_MOUSE_MOVE', position }),
    setFocusedView: (k) => ({ type: 'UI_SET_FOCUSED_VIEW', k }),
    toggleMovieMode: () => ({ type: 'UI_MOVIE_MODE_TOGGLE' }),
    setFullscreen: (fullscreen) => ({ type: 'UI_SET_FULLSCREEN', fullscreen }),
 
    // Computation actions
    updateComputationView: (k, data) => ({
      type: 'COMPUTATION_UPDATE_VIEW',
      k,
      un: data.un,
      di: data.di,
      ch: data.ch,
      it: data.it,
      workerInfo: data.workerInfo,
      boardType: data.boardType
    })
  };
}
 
// Global configuration: display dimensions, palettes, and render settings.
class Config {
  // Constants for iteration and convergence
  static MAX_CHAOTIC_ITERATIONS = 100000;
 
  // Constants for display and zoom
  static DEFAULT_ZOOM_FACTOR = 5;
  static DEFAULT_ASPECT_RATIO = 1.0;
  static WIDESCREEN_ASPECT_RATIO = 16 / 9;
  static CENTER_COORDINATE = 0.5;
 
  // Feigenbaum / Myrberg point (real-axis accumulation point of period doubling)
  // OEIS A218453: 65-digit precision, parsed to quad-double (QD) format
  static get FEIGENBAUM_POINT_QD() {
    if (!this._FEIGENBAUM_POINT_QD) {
      this._FEIGENBAUM_POINT_QD = decimalToQD(
        '-1.4011551890920506005238267878938612922263080433973196089372614966');
    }
    return this._FEIGENBAUM_POINT_QD;
  }
 
  constructor(store) {
    this.store = store;
 
    // Initialize viewport width
    document.body.style.overflowY = 'scroll';
    const vw = document.documentElement.clientWidth || (window.innerWidth - 20);
    document.body.style.overflowY = '';
 
    // Calculate initial values
    const dgc = Math.min(2, Math.ceil(vw / 501));
    const pixelRatio = Math.max(Math.ceil(window.devicePixelRatio || 1), 2);
    const mobile = ('ontouchstart' in document.documentElement);
    const mac = (navigator.platform.indexOf('Mac') === 0);
 
    // Initialize state
    this.store.dispatch(this.store.actions.updateConfig({
      vw,
      gridcols: dgc,
      exponent: 2,
      enableGPU: true,
      forceBoard: null,
      firstrQD: [-0.5, 0, 0, 0],
      firstjQD: [0.0, 0, 0, 0],
      firstsize: 3.0,
      pixelRatio,
      zoomfactor: Config.DEFAULT_ZOOM_FACTOR,
      aspectRatio: Config.DEFAULT_ASPECT_RATIO,
      theme: 'warm',
      unknowncolor: '#000',
      mobile,
      mac
    }));
 
    // Color palette options (not stored in state)
    this.unknownColorPalette = ["#000", "transparent", "#fff", "yellow", "red", "rgb(32,16,64)"];
    this.defineColorThemes();
  }
 
  // Read-only property getters (set once in constructor/URL or computed)
  get vw() { return this.store.getState().config.vw; }
  get cssDimsWidth() { return this.store.getState().config.cssDimsWidth; }
  get cssDimsHeight() { return this.store.getState().config.cssDimsHeight; }
  get dimsWidth() { return this.store.getState().config.dimsWidth; }
  get dimsHeight() { return this.store.getState().config.dimsHeight; }
  get zoomfactor() { return this.store.getState().config.zoomfactor; }
  get firstsize() { return this.store.getState().config.firstsize; }
  get mobile() { return this.store.getState().config.mobile; }
  get mac() { return this.store.getState().config.mac; }
  get exponent() { return this.store.getState().config.exponent; }
  get enableGPU() { return this.store.getState().config.enableGPU; }
  get forceBoard() { return this.store.getState().config.forceBoard; }
  get debug() { return this.store.getState().config.debug; }
 
  // Check if a debug flag is set (supports both simple flags and key=value flags)
  // Examples: debug=m,x=foo,t  →  hasDebugFlag('m')=true, hasDebugFlag('x')=true
  hasDebugFlag(flag) {
    const debug = this.debug;
    if (!debug) return false;
    const parts = debug.split(',').map(f => f.trim());
    return parts.some(p => p === flag || p.startsWith(flag + '='));
  }
 
  // Get the value of a debug flag (returns null if not set or no value)
  // Examples: debug=m,x=foo,t  →  getDebugFlag('x')='foo', getDebugFlag('m')=null
  getDebugFlag(flag) {
    const debug = this.debug;
    if (!debug) return null;
    const parts = debug.split(',').map(f => f.trim());
    for (const part of parts) {
      if (part === flag) return null; // Flag exists but has no value
      if (part.startsWith(flag + '=')) {
        return part.substring(flag.length + 1);
      }
    }
    return null;
  }
 
  get firstrQD() { return this.store.getState().config.firstrQD; }
  get firstjQD() { return this.store.getState().config.firstjQD; }
 
  // Backward compatibility computed property
  get dimsArea() { return this.dimsWidth * this.dimsHeight; }
 
  // Writable properties - only these have runtime setter methods
  get gridcols() { return this.store.getState().config.gridcols; }
  setGridcols(value) {
    this.store.dispatch(this.store.actions.updateConfig({ gridcols: value }));
  }
 
  get pixelRatio() { return this.store.getState().config.pixelRatio; }
  setPixelRatio(value) {
    this.store.dispatch(this.store.actions.setPixelRatio(value));
  }
 
  get aspectRatio() { return this.store.getState().config.aspectRatio; }
  setAspectRatio(value) {
    this.store.dispatch(this.store.actions.setAspectRatio(value));
  }
 
  get theme() { return this.store.getState().config.theme; }
  setTheme(value) {
    this.store.dispatch(this.store.actions.setTheme(value));
  }
 
  get unknowncolor() { return this.store.getState().config.unknowncolor; }
  setUnknowncolor(value) {
    this.store.dispatch(this.store.actions.setUnknownColor(value));
  }
 
  defineColorThemes() {
    this.colorThemes = {
      warm: (i, frac, fracD, fracL, s) => {
        frac = Math.max(frac, Math.min(0.99, fracD / (Math.max(1e-3, fracL))));
        let hue = (Math.log(i + 20) * 200) % 360;
        let chroma = 100;
        let light = 15 * frac + 85 * frac ** 5;
        return hclColor(hue, chroma, light);
      },
      neon: (i, frac, fracD, fracL, s) => {
        // Keep colors saturated - no desaturation to white at high iterations
        frac = Math.max(frac, Math.min(0.99, fracD / (Math.max(1e-3, fracL))));
        // Use logarithmic scaling for iteration count to keep bands visible at high iterations
        let angle = (Math.log(i + 10) * 0.8) * Math.PI;
 
        // Generate three offset sine waves for RGB, keeping them always saturated
        // Add phase offsets to create color variety
        let r = Math.abs(Math.sin(angle));
        let g = Math.abs(Math.sin(angle + Math.PI * 2/3));
        let b = Math.abs(Math.sin(angle + Math.PI * 4/3));
 
        // Boost saturation by pushing down the minimum channel
        let minChannel = Math.min(r, g, b);
        r = Math.max(0, r - minChannel * 2/3);
        g = Math.max(0, g - minChannel * 2/3);
        b = Math.max(0, b - minChannel * 2/3);
 
        // Normalize so at least one channel is always at full brightness
        let maxChannel = Math.max(r, g, b);
        if (maxChannel > 0) {
          r /= maxChannel;
          g /= maxChannel;
          b /= maxChannel;
        }
 
        // Scale for neon glow - higher brightness for more saturation
        let brightness = 0.5 + 0.4 * frac;
        r = intcolor(r * brightness);
        g = intcolor(g * brightness);
        b = intcolor(b * brightness);
 
        return `rgb(${r},${g},${b})`;
      },
      iceblue: (i, frac, fracD, fracL, s) => {
        // Current implementation
        let ff = Math.pow(frac, 2);
        let fr = Math.pow(frac, 0.333);
        let fg = Math.pow(frac, 3);
        let g = intcolor(Math.max(fg, Math.min(fr, i * Math.pow(s, 0.33) / 64)));
        let r = intcolor(Math.min(fr, i * Math.pow(s, 0.22) / 64));
        let b = intcolor(ff / 3 + 0.667);
        return `rgb(${r},${g},${b})`;
      },
      tiedye: (i, frac, fracD, fracL, s) => {
        frac = Math.max(frac, Math.min(0.99, fracD / (Math.max(1e-3, fracL))));
        let hue = (Math.log(i + 20) * 1000) % 360;
        let chroma = 100;
        let light = 25 * frac + 75 * frac ** 5;
        return hclColor(hue, chroma, light);
      },
      gray: (i, frac, fracD, fracL, s) => {
        frac = Math.max(frac, Math.min(0.99, fracD / (Math.max(1e-3, fracL))));
        let value = intcolor(0.15 + 0.85 * frac ** 5);
        return `rgb(${value},${value},${value})`;
      },
      // Add more color themes here
    };
    this.colorThemes.all = Object.keys(this.colorThemes);
  }
 
  initSizes() {
    let cssDims, cssDimsWidth, cssDimsHeight;
 
    // In fullscreen, use full window dimensions with no margins
    if (document.fullscreenElement) {
      const availWidth = window.innerWidth;
      const availHeight = window.innerHeight;
 
      // Directly set width and height to fill the viewport
      cssDimsWidth = availWidth;
      cssDimsHeight = availHeight;
      cssDims = cssDimsWidth;  // For compatibility
    } else {
      cssDims = Math.max(32, Math.floor((this.vw - 28) / this.gridcols) - 20);
 
      // Calculate width and height based on aspect ratio
      if (this.aspectRatio >= 1.0) {
        // Wider than tall
        cssDimsWidth = cssDims;
        cssDimsHeight = Math.floor(cssDims / this.aspectRatio);
      } else {
        // Taller than wide
        cssDimsHeight = cssDims;
        cssDimsWidth = Math.floor(cssDims * this.aspectRatio);
      }
    }
 
    const dimsWidth = Math.floor(cssDimsWidth * this.pixelRatio);
    const dimsHeight = Math.floor(cssDimsHeight * this.pixelRatio);
 
    // Calculate firstsize to ensure we fit width extent of 3 and height extent of 2.5
    // Width constraint: size must be at least 3.0
    // Height constraint: size / aspectRatio must be at least 2.5, so size >= 2.5 * aspectRatio
    const firstsize = Math.max(3.0, 2.5 * this.aspectRatio);
 
    // Dispatch all updates at once
    this.store.dispatch(this.store.actions.initSizes({
      vw: this.vw,
      gridcols: this.gridcols,
      cssDims,
      cssDimsWidth,
      cssDimsHeight,
      dimsWidth,
      dimsHeight,
      pixelRatio: this.pixelRatio,
      firstsize
    }));
 
    // Update DOM elements
    for (const el of document.querySelectorAll('.pixelratio')) {
      el.innerText = this.pixelRatio;
    }
    for (const el of document.querySelectorAll('#text')) {
      const minHelpWidth = 390;
      const helpColumns = Math.ceil((minHelpWidth + 36) / (cssDims + 20));
      // Columns plus margin minus padding
      el.style.maxWidth = `${(cssDims + 20) * helpColumns - 20 - 16}px`;
    }
  }
 
  updateExponent(newExponent) {
    if (newExponent < 2) { return; }
    // Bulk update exponent and initial center (origin for z^n, n>2)
    this.store.dispatch(this.store.actions.updateConfig({
      exponent: newExponent,
      firstrQD: [newExponent > 2 ? 0.0 : -0.5, 0, 0, 0],
      firstjQD: [0.0, 0, 0, 0]
    }));
    for (const el of document.querySelectorAll('.exponent')) {
      el.innerText = newExponent;
    }
  }
 
  firststate() {
    return {sizes:[[this.firstsize, this.firstrQD, this.firstjQD]], hidden:[]};
  }
}
 
// Rendering layer that draws computed pixel data to canvas.
class View {
  constructor(k, size, re, im, config, id, grid = null) {
    this.k = k;
    this.id = id;
    this.config = config;
    this.grid = grid;
    this.convergedData = new Map();
 
    // Multi-resolution compositing
    this.parentView = null;
    this.childView = null;
 
    this.initview(size, re, im);
    this.workerInfo = 'no worker';
    this.boardType = null;
 
    // Store exponent at creation time - views computed with different exponent are incompatible
    this.exponent = config.exponent;
  }
 
  // Getter properties that derive from sizesQD (the authoritative source)
  // sizesQD format: [sizeDouble, reQD, imQD]
  get size() { return this.sizesQD[0]; }
  get re() { return this.sizesQD[1]; }
  get im() { return this.sizesQD[2]; }
 
  // Derived scalar properties
  get pixelSize() { return this.size / this.config.dimsWidth; }
  get zoomFactor() { return this.config.firstsize / this.size; }
 
  // Static helper: lookup histogram fractions for a given iteration count
  static lookupHistogram(i, histogram) {
    let j = 0;
    for (; j < histogram.length - 1 && i < histogram[j][0]; j += 1) {}
    // Clamp to last valid index if iteration exceeds histogram range
    j = Math.min(j, histogram.length - 1);
    const [, uFrac, dFrac, lFrac] = histogram[j];
    return {
      fracK: 1 - uFrac,  // Fraction known
      fracD: 1 - dFrac,  // Fraction diverged
      fracL: 1 - lFrac   // Estimated limit on fracD
    };
  }
 
  initview(size, re, im) {
    // Store size as double (sufficient for scaling), coordinates as QD
    this.sizesQD = [typeof size === 'number' ? size : qdToNumber(size), toQD(re), toQD(im)];
    this.nn = new Array(this.config.dimsArea).fill(0);
    this.un = this.config.dimsArea;
    this.di = 0;
    this.ch = 0;
    this.it = 0;
    this.hi = [[0, 1, 1, 0]];
    this.convergedData.clear();
    this.boardStartTime = Date.now();
    this.boardEndTime = null;
  }
 
  setParentView(parentView) {
    // Clear old parent's reference to us
    if (this.parentView && this.parentView.childView === this) {
      this.parentView.childView = null;
    }
    this.parentView = parentView;
    if (parentView) {
      // Clear old child reference before setting new one
      if (parentView.childView && parentView.childView !== this) {
        parentView.childView.parentView = null;
      }
      parentView.childView = this;
    }
  }
 
  updateFromWorkerResult(data) {
    const { changeList, un, di, ch, it, workerInfo, boardType } = data;
    const changedIndices = [];
 
    for (const { nn, vv, iter } of changeList) {
      for (const index of nn) {
        this.nn[index] = iter;
        changedIndices.push(index);
      }
      for (const entry of vv) {
        const { index, z, p } = entry;
        this.nn[index] = -iter;
        this.convergedData.set(index, { z: toQDc(z), p });  // Normalize to QDc format
        changedIndices.push(index);
      }
      this.di += nn.length;
      this.un -= nn.length + vv.length;
      this.updateHistogram(this.un, this.di, iter);
    }
    this.un = un;
    this.di = di;
    this.ch = ch;
    this.it = it;
    this.workerInfo = workerInfo;
    if (boardType) {
      this.boardType = boardType;
    }
    // Freeze stats timing when board completes (un === 0 means 100%)
    if (this.un === 0 && !this.boardEndTime) {
      this.boardEndTime = Date.now();
    }
 
    // Propagate updates to child view
    if (this.childView && changedIndices.length > 0) {
      this.updateChildPixels(changedIndices);
    }
  }
 
  updateChildPixels(parentIndices) {
    // No-op: child computes its own pixels, no need for parent updates
  }
 
  currentc(j) {
    const { dimsWidth, dimsHeight, aspectRatio } = this.config;
    const x = j % dimsWidth;
    const y = Math.floor(j / dimsWidth);
    const rFrac = (x / dimsWidth) - Config.CENTER_COORDINATE;
    const jFrac = Config.CENTER_COORDINATE - (y / dimsHeight);
    // Use QD precision for scaling to preserve accuracy at deep zoom
    const rQD = toQDAdd(this.re, toQDScale(this.size, rFrac));
    const iQD = toQDAdd(this.im, toQDScale(this.size, jFrac / aspectRatio));
    // Return QD complex format (8 elements: 4 real + 4 imaginary) for full precision
    return [rQD[0], rQD[1], rQD[2], rQD[3], iQD[0], iQD[1], iQD[2], iQD[3]];
  }
 
  currentz(j) {
    const data = this.convergedData.get(j);
    return data ? data.z : null;
  }
 
  currentp(j) {
    const data = this.convergedData.get(j);
    return data ? data.p : null;
  }
 
  updateHistogram(un, di, i) {
    if (this.hi[0][1] - un / this.config.dimsArea >= 1 / 256) {  // Histogram resolution
      const uFrac = un / this.config.dimsArea;
      const dFrac = 1 - di / this.config.dimsArea;
      this.hi.unshift([i, uFrac, dFrac, 0]);
      if (this.hi.length > 10) {
        // Estimate the limit of di as i goes to infinity.
        const sample = this.hi.slice(0, this.hi.length - 2).map(
           (e, i) => ({ x: e[0], y: e[2], weight: (e[0] - this.hi[i+1][0]) ** 4 })
        ).reverse();
        const estimate = Math.min(1, Math.max(0, estimateLimit(sample)));
        // Smooth the estimate.
        const avg = (estimate + this.hi[1][3] * 4) / 5;
        this.hi[0][3] = avg;
      }
    }
  }
 
  draw(ctx, colorview = null, unknownColor = 'transparent') {
    if (colorview === null) {
      colorview = this;
    }
 
    // Draw composite: parent pixels + local pixels
    if (this.parentView) {
      this.drawComposite(ctx, colorview, unknownColor);
    } else {
      // No parent, just draw normally
      this.drawLocal(ctx, colorview, unknownColor);
    }
  }
 
  drawLocal(ctx, colorview = null, unknownColor = 'transparent') {
    // Draw only locally computed pixels
    if (colorview === null) {
      colorview = this;
    }
    const n = this.nn;
    const msort = n.map((v, i) => i).sort((a, b) => n[a] - n[b]);
    let prev = null;
    for (let m of msort) {
      const x = m % this.config.dimsWidth;
      const y = (m - x) / this.config.dimsWidth;
      const cur = n[m];
      if (prev !== cur) {
        ctx.fillStyle = colorview.makecolor(cur, null, null, unknownColor);
        prev = cur;
      }
      ctx.fillRect(x, y, 1, 1);
    }
  }
 
  // Calculate coordinate mapping from parent to child canvas using QD precision
  calculateParentMapping() {
    const parent = this.parentView;
    const { dimsWidth, dimsHeight, aspectRatio } = this.config;
 
    const [childSizeQD, childCenterRQD, childCenterIQD] = this.sizesQD;
    const [parentSizeQD, parentCenterRQD, parentCenterIQD] = parent.sizesQD;
 
    const childSize = qdToNumber(childSizeQD);
    const parentSize = qdToNumber(parentSizeQD);
    const parentHeight = parentSize / aspectRatio;
 
    // sx = ((childCenterR - parentCenterR) + (parentSize - childSize)/2) / parentSize * dimsWidth
    const deltaR = toQDSub(childCenterRQD, parentCenterRQD);
    const deltaRNum = qdToNumber(deltaR);
    const sx = ((deltaRNum + (parentSize - childSize) / 2) / parentSize) * dimsWidth;
 
    // sy = (deltaI + (parentHeight - childHeight)/2) / parentHeight * dimsHeight
    const childHeight = childSize / aspectRatio;
    const deltaI = toQDSub(parentCenterIQD, childCenterIQD);
    const deltaINum = qdToNumber(deltaI);
    const sy = ((deltaINum + (parentHeight - childHeight) / 2) / parentHeight) * dimsHeight;
 
    const sw = (childSize / parentSize) * dimsWidth;
    const sh = (childSize / parentSize) * dimsHeight;
 
    return { sx, sy, sw, sh };
  }
 
  // Check if a parent pixel should be cleared (unknown or on boundary)
  shouldClearParentPixel(px, py, parentData, sx, sy, sw, sh) {
    const { dimsWidth, dimsHeight } = this.config;
 
    if (px < 0 || px >= dimsWidth || py < 0 || py >= dimsHeight) {
      return false;
    }
 
    const parentIdx = py * dimsWidth + px;
    const val = parentData[parentIdx];
 
    // Clear if unknown
    if (val === 0) return true;
 
    // Check for diverged/converged boundary
    const isDiverged = val > 0;
    const isConverged = val < 0;
 
    // Check 4-connected neighbors for opposite type
    const neighbors = [
      py > 0 ? parentData[(py - 1) * dimsWidth + px] : null,
      py < dimsHeight - 1 ? parentData[(py + 1) * dimsWidth + px] : null,
      px > 0 ? parentData[py * dimsWidth + (px - 1)] : null,
      px < dimsWidth - 1 ? parentData[py * dimsWidth + (px + 1)] : null,
    ];
 
    for (const n of neighbors) {
      if (n !== null && n !== 0) {
        if ((isDiverged && n < 0) || (isConverged && n > 0)) {
          return true;
        }
      }
    }
    return false;
  }
 
  drawComposite(ctx, colorview = null, unknownColor = 'transparent') {
    // Draw parent canvas scaled as background, then local pixels on top
    if (colorview === null) {
      colorview = this;
    }
 
    // Clear canvas
    ctx.clearRect(0, 0, this.config.dimsWidth, this.config.dimsHeight);
 
    // Draw scaled parent canvas as background, but inflate unknown parent pixels
    // to avoid showing fuzzy boundary pixels
    if (this.parentView && this.grid) {
      const parent = this.parentView;
      const parentCanvas = this.grid.canvas(parent.k);
 
      if (parentCanvas) {
        const { sx, sy, sw, sh } = this.calculateParentMapping();
 
        // Create a temporary canvas at 3x parent resolution for finer inflation control
        const upsample = 3;
 
        // Calculate source dimensions in parent pixels (integer + 2px padding)
        const srcW = Math.ceil(sw) + 2;
        const srcH = Math.ceil(sh) + 2;
 
        // Dest must be exactly 3x source for proper pixel alignment
        const tempCanvas = document.createElement('canvas');
        tempCanvas.width = srcW * upsample;
        tempCanvas.height = srcH * upsample;
        const tempCtx = tempCanvas.getContext('2d');
 
        // Draw parent region upsampled 3x (with 1px padding at parent resolution)
        tempCtx.drawImage(parentCanvas,
          Math.floor(sx) - 1, Math.floor(sy) - 1,
          srcW, srcH,
          0, 0, srcW * upsample, srcH * upsample);
 
        // Inflate unknown parent pixels and diverged/converged boundaries
        const parentData = parent.nn;
        for (let py = Math.floor(sy) - 1; py < Math.ceil(sy + sh) + 1; py++) {
          for (let px = Math.floor(sx) - 1; px < Math.ceil(sx + sw) + 1; px++) {
            if (this.shouldClearParentPixel(px, py, parentData, sx, sy, sw, sh)) {
              // Clear pixel and 1-pixel margin at upsampled resolution
              // Each parent pixel maps to a 3x3 block, plus 1px inflation = 5x5 area
              const tx = (px - Math.floor(sx) + 1) * upsample;
              const ty = (py - Math.floor(sy) + 1) * upsample;
              for (let dy = -1; dy < upsample + 1; dy++) {
                for (let dx = -1; dx < upsample + 1; dx++) {
                  tempCtx.clearRect(tx + dx, ty + dy, 1, 1);
                }
              }
            }
          }
        }
 
        // Draw the masked parent pixels scaled to child canvas (faded)
        // Account for fractional pixel offset within the temp canvas
        // sx, sy may be fractional (e.g., 10.3), so child's edge isn't at an integer parent pixel
        const fracX = sx - Math.floor(sx);  // Fractional part (e.g., 0.3)
        const fracY = sy - Math.floor(sy);
        const tempSrcX = upsample + fracX * upsample;  // e.g., 3 + 0.3*3 = 3.9
        const tempSrcY = upsample + fracY * upsample;
 
        ctx.globalAlpha = 0.5;  // 50% opacity for parent pixels
        ctx.drawImage(tempCanvas,
          tempSrcX, tempSrcY,
          (srcW - 2) * upsample, (srcH - 2) * upsample,
          0, 0, this.config.dimsWidth, this.config.dimsHeight);
        ctx.globalAlpha = 1.0;  // Restore full opacity
      }
    }
 
    // Draw local computed pixels on top (using child's palette)
    this.drawLocal(ctx, colorview, unknownColor);
  }
 
  clearcanvas(ctx) {
    // For views with parents, use composite drawing
    // For root views, just clear (div background shows through)
    if (this.parentView) {
      this.drawComposite(ctx);
    } else {
      ctx.clearRect(0, 0, this.config.dimsWidth, this.config.dimsHeight);
    }
  }
 
  drawchange(ctx, change) {
    if (change.nn.length) {
      // Draw diverged pixels - nn contains plain indices
      ctx.fillStyle = this.makecolor(change.iter);
      for (let m of change.nn) {
        const x = m % this.config.dimsWidth;
        const y = (m - x) / this.config.dimsWidth;
        ctx.fillRect(x, y, 1, 1);
      }
    }
    if (change.vv.length) {
      // Draw converged pixels - vv contains {index, r, i} objects
      ctx.fillStyle = this.makecolor(-change.iter);
      for (let v of change.vv) {
        const x = v.index % this.config.dimsWidth;
        const y = (v.index - x) / this.config.dimsWidth;
        ctx.fillRect(x, y, 1, 1);
      }
    }
  }
 
  makecolor(i, histogram = null, scale = null, unknownColor = 'transparent') {
    if (i === 0) return unknownColor;  // Color for uncomputed pixels
    if (i < 0) return 'black';
    const hi = histogram || this.hi;
    const size = scale || this.size;
    const fracs = View.lookupHistogram(i, hi);
    return this.config.colorThemes[this.config.theme](
       i, fracs.fracK, fracs.fracD, fracs.fracL, size);
  }
 
  uninteresting() {
    // Boring: nothing computed, or done with less than 5 colors
    return this.di <= 0 || (this.un === 0 && this.hi.length <= 5);
  }
 
  unfinished() {
    // Chaotic points in the spike counted as finished after max iterations.
    const result = Math.max(0, this.un +
      (this.it < Config.MAX_CHAOTIC_ITERATIONS ? 0 : -this.ch));
    return result;
  }
 
 
  debugStatus() {
    const debugGraph = this.renderHiGraph(600, 300);
    const maxPeriod = this.convergedData.values().map(
        d => fibonacciPeriod(d.p)).reduce((a, b) => Math.max(a, b), 0);
    const maxEscape = this.nn.reduce((a, b) => Math.max(a, b), 0)
    this.nn.reduce((iMin, x, i, arr) => x < arr[iMin] ? i : iMin, 0);
    const boardName = this.boardType || 'Board';
 
    // Calculate performance metrics (freeze timing when board completes)
    const endTime = this.boardEndTime || Date.now();
    const elapsedSecs = (endTime - this.boardStartTime) / 1000;
    const finishedPixels = this.di + this.ch;
    const itersPerSec = elapsedSecs > 0 ? this.it / elapsedSecs : 0;
    const pixelsPerSec = elapsedSecs > 0 ? finishedPixels / elapsedSecs : 0;
 
    // Format rate: always show 3 significant digits, readable format
    const formatRate = (r) => {
      if (r === 0) return '0';
      if (r >= 1000) return formatLargeInt(Math.round(r));  // comma-formatted integers
      return r.toPrecision(3);  // handles 0.001 to 999, and scientific for very small/large
    };
 
    return `${formatRate(itersPerSec)} iter/s, ${formatRate(pixelsPerSec)} px/s (${elapsedSecs.toFixed(1)}s)\n` +
           `${boardName} ${this.id}:\n` +
           `${this.di} diverged, ${this.un} unfinished, ${this.ch} chaotic\n` +
           `max period ${maxPeriod}, max escape ${maxEscape}\n` +
           `${this.workerInfo}\n` +
           `<img src="${debugGraph}" style="width:300px;height:150px">`;
  }
 
  renderHiGraph(width, height) {
    const canvas = document.createElement('canvas');
    canvas.width = width;
    canvas.height = height;
    const ctx = canvas.getContext('2d');
 
    const hi = this.hi;
    const scale = [
      (y) => y / hi[Math.floor(hi.length / 8)][0] / 2,
      (y) => y,
      (y) => y,
      (y) => y,
    ];
    const barWidth = width / (hi.length * scale.length);
 
    // Background
    ctx.fillStyle = 'white';
    ctx.fillRect(0, 0, width, height);
 
    // Draw bars
    const colors = ['blue', 'red', 'green', 'purple'];
    hi.forEach((row, i) => {
      row.forEach((value, j) => {
        const x = i * scale.length * barWidth + j * barWidth;
        const barHeight = scale[j](value) * (height - 20);
        ctx.fillStyle = colors[j];
        ctx.fillRect(x, height - barHeight - 10, barWidth, barHeight);
      });
    });
 
    // Draw x-axis
    ctx.strokeStyle = 'black';
    ctx.beginPath();
    ctx.moveTo(0, height - 10);
    ctx.lineTo(width, height - 10);
    ctx.stroke();
 
    // Add labels
    ctx.font = '20px Arial';
    ctx.shadowColor = 'white';
    ctx.shadowBlur = 8;
    ctx.fillStyle = 'red';
    ctx.fillText(`Undone: ${this.hi[0][1]}`, 5, 30);
    ctx.fillStyle = 'green';
    ctx.fillText(`Dark: ${this.hi[0][2]}`, 5, 60);
    ctx.fillStyle = 'purple';
    ctx.fillText(`Est: ${this.hi[0][3]}`, 5, 90);
 
    return canvas.toDataURL();
  }
}
 
// Manages the array of views and their layout in the grid.
class Grid {
  constructor(config, store = null) {
    this.config = config;
    this.store = store;
    this.views = [];
    this.canvascount = 0;
    this.focusk = null;
    this.urlListeners = [];
    this.zoomListeners = [];
    this.scheduler = new Scheduler(this);
    // Stable views - only populated during an update process.
    // Holds union of views that can be reused if popstate fires mid-update.
    // Cleared to null when update completes (this.views is then the stable state).
    this.stableViews = null;
    this._mouseOverBoard = false;  // Track if mouse is over board views
  }
 
  makeView(k, size, re, im, deferComputation = false) {
    const id = k + Math.random();
    const view = new View(k, size, re, im, this.config, id, this);
    this.views[k] = view;
 
    // Set up parent-child relationship for multi-resolution compositing
    if (k > 0 && this.views[k - 1]) {
      view.setParentView(this.views[k - 1]);
    }
 
    if (!deferComputation) {
      this.scheduler.assignBoardToWorker(k, size, re, im, this.config, id);
    }
    return view;
  }
 
  startViewComputation(k) {
    // Start computation for a view (stage 3)
    const view = this.views[k];
    if (!view) return;
    this.scheduler.assignBoardToWorker(
      k, view.size, view.re, view.im, this.config, view.id);
  }
 
  removeView(k) {
    this.views[k] = null;
    let i = this.views.length - 1;
    for (i = this.views.length - 1; i >= 0; i -= 1) {
      if (this.views[i] !== null) { break; }
    }
    this.views.length = i + 1;
    this.scheduler.removeBoardFromWorker(k);
  }
 
  setFocusedView(k) {
    if (k !== this.focusk) {
      this.focusk = k;
      this.scheduler.setFocusedBoard(k);
    }
  }
 
  getHiddenViews() {
    return this.views.map((v, i) =>
            this.hiddencanvas(i) ? i : -1).filter(i => i !== -1);
  }
 
  updateHiddenViews() {
    this.scheduler.setHiddenBoards(this.getHiddenViews());
  }
 
  updateViewFromWorkerResult(k, data, workerIndex) {
    // First check current views
    if (this.views[k]) {
      if (this.views[k].id !== data.id) {
        return;
      }
      this.views[k].updateFromWorkerResult(data);
      this.updateCanvas(k, data);
 
      // Update state with computation status
      if (this.store) {
        this.store.dispatch(
          this.store.actions.updateComputationView(k, {
            un: data.un,
            di: data.di,
            ch: data.ch,
            it: data.it,
            workerInfo: data.workerInfo,
            boardType: data.boardType
          })
        );
      }
      return;
    }
 
    // If not in current views, check stableViews (may be mid-update)
    // This ensures we don't lose messages during updateLayout transitions
    if (this.stableViews) {
      for (const view of this.stableViews) {
        if (view && view.id === data.id) {
          view.updateFromWorkerResult(data);
          return;
        }
      }
    }
  }
 
  updateCanvas(k, data) {
    const canvas = this.canvas(k);
    if (canvas && data.changeList.length) {
      const ctx = canvas.getContext('2d');
      for (let change of data.changeList) {
        this.views[k].drawchange(ctx, change);
      }
    }
  }
 
  currentGridState() {
    let state = { hidden: [], sizes: [] };
    for (let k = 0; k < this.views.length; k++) {
      if (this.hiddencanvas(k)) {
        state.hidden.push(k);
      }
      // State format: [sizeScalar, reQD, imQD] for backward compatibility
      state.sizes.push([this.views[k].size, this.views[k].re, this.views[k].im]);
    }
    return state;
  }
 
  updateLayout(state = null, skipInitSizes = false) {
    // Abort any current update process and preserve its target state
    if (this.currentUpdateProcess) {
      if (!state) {
        state = this.currentUpdateProcess.targetState;
      }
      this.currentUpdateProcess.abort();
    }
 
    // Use current state only if no state provided and no process to abort
    if (!state) {
      state = this.currentGridState();
    }
 
    // Recalculate dimensions unless explicitly skipped
    if (!skipInitSizes) {
      this.config.initSizes();
    }
 
    // Save current views to stableViews for potential reuse.
    // This does NOT remove boards from workers - they continue computing.
    // Boards will be cleaned up at end of update for any views not reused.
    this.saveViewsToStable();
 
    // Find views to preserve by coordinate matching
    const preservedViews = this.findPreservableViews(state.sizes);
 
    // Clear and recreate the grid DOM (views array already cleared by saveViewsToStable)
    const gridElement = document.getElementById('grid');
    gridElement.innerHTML = '';
    this.canvascount = 0;
 
    // Create canvases for all views in the state
    const {sizes, hidden} = state;
    for (let k = 0; k < sizes.length; k++) {
      this.makecanvas(k, sizes[k]);
      if (hidden.includes(k)) {
        this.hidecanvas(k);
      }
    }
 
    // Update workers with hidden boards BEFORE creating boards
    // to prevent hidden boards from computing
    this.updateHiddenViews();
    this.currentUpdateProcess = this.createUpdateProcess(state, preservedViews);
    this.currentUpdateProcess.start();
  }
 
  // Find views in stableViews that match target coordinates, dimensions, and exponent
  // Returns Map of targetIdx -> view
  findPreservableViews(targetSizes) {
    const preservedViews = new Map();
    const targetArea = this.config.dimsWidth * this.config.dimsHeight;
    const targetExponent = this.config.exponent;
 
    // Helper to check if a view matches target coordinates, dimensions, AND exponent
    const viewMatchesTarget = (view, targetSizes) => {
      if (!view || !view.sizesQD || !targetSizes) return false;
 
      // Check exponent matches (views computed with different exponent are incompatible)
      if (view.exponent !== targetExponent) return false;
 
      // Check dimensions match
      const viewArea = view.nn?.length || 0;
      if (viewArea !== targetArea) return false;
 
      const [viewSizeQD, viewReQD, viewImQD] = view.sizesQD;
      const viewSize = qdToNumber(viewSizeQD);
      const [targetSize, targetRe, targetIm] = targetSizes;
 
      // Check zoom level - must be within 0.1%
      const sizeRatio = targetSize / viewSize;
      if (sizeRatio < 0.999 || sizeRatio > 1.001) return false;
 
      // Check coordinates - tolerance is 0.01% of view extent
      // Use QD subtraction to avoid precision loss at deep zoom
      const tolerance = viewSize * 0.0001;
      const reDiff = Math.abs(qdToNumber(toQDSub(viewReQD, targetRe)));
      const imDiff = Math.abs(qdToNumber(toQDSub(viewImQD, targetIm)));
      return reDiff < tolerance && imDiff < tolerance;
    };
 
    for (let targetIdx = 0; targetIdx < targetSizes.length; targetIdx++) {
      const targetSize = targetSizes[targetIdx];
 
      // Search stableViews for best match (most computed data)
      let bestView = null;
      let bestDi = -1;
 
      for (const view of (this.stableViews || [])) {
        if (!viewMatchesTarget(view, targetSize)) continue;
        if (view.di > bestDi) {
          bestDi = view.di;
          bestView = view;
        }
      }
 
      if (bestView) {
        preservedViews.set(targetIdx, bestView);
      }
    }
 
    return preservedViews;
  }
 
  createUpdateProcess(state, preservedViews) {
    let aborted = false;
    const usedViewIds = new Set();  // Track which stableView IDs were reused
 
    // Build list of indices that need new views (not preserved)
    const newViewIndices = [];
    for (let k = 0; k < state.sizes.length; k++) {
      if (!preservedViews.has(k)) {
        newViewIndices.push(k);
      }
    }
 
    // Function to place all preserved views immediately (called by start)
    const placePreservedViews = () => {
      for (let k = 0; k < state.sizes.length; k++) {
        const preserved = preservedViews.get(k);
        if (preserved) {
          usedViewIds.add(preserved.id);
          const oldK = preserved.k;
          preserved.k = k;
          this.views[k] = preserved;
 
          // Only need to update scheduler if the index changed
          if (oldK !== k) {
            this.scheduler.removeBoardFromWorker(oldK);
            this.scheduler.assignBoardToWorker(
              k, preserved.size, preserved.re, preserved.im,
              this.config, preserved.id);
          }
 
          // Set up parent-child relationship (view 0 has no parent)
          if (k > 0 && this.views[k - 1]) {
            preserved.setParentView(this.views[k - 1]);
          } else if (k === 0) {
            preserved.setParentView(null);
          }
 
          // Draw the preserved view to the canvas immediately
          this.views[k].draw(this.canvas(k).getContext('2d'));
 
          if (state.hidden.indexOf(k) >= 0) {
            this.hidecanvas(k);
          }
        }
      }
    };
 
    // Now process new views with 50ms delays
    let newViewIndex = 0;
 
    const processNextNew = () => {
      if (aborted) {
        return;
      }
      if (newViewIndex >= newViewIndices.length) {
        // All done
        this.notifyurl();
        this.notifyzoom();
        this.updateHiddenViews();
        this.cleanupUnusedStableViews(usedViewIds);
        this.currentUpdateProcess = null;
        return;
      }
 
      const k = newViewIndices[newViewIndex];
      this.views[k] = this.makeView(k, state.sizes[k][0], state.sizes[k][1], state.sizes[k][2]);
      this.views[k].draw(this.canvas(k).getContext('2d'));
 
      // Set up parent-child relationship for new view
      if (k > 0 && this.views[k - 1]) {
        this.views[k].setParentView(this.views[k - 1]);
      }
 
      if (state.hidden.indexOf(k) >= 0) {
        this.hidecanvas(k);
      }
      this.updateFullscreenButton();
      newViewIndex++;
      setTimeout(processNextNew, 50);
    };
 
    return {
      targetState: state,
      start: () => {
        // Place preserved views immediately (synchronously) on start
        placePreservedViews();
        this.updateFullscreenButton();
        if (newViewIndices.length === 0) {
          // No new views, finish immediately
          this.notifyurl();
          this.notifyzoom();
          this.updateHiddenViews();
          this.cleanupUnusedStableViews(usedViewIds);
          this.currentUpdateProcess = null;
        } else {
          processNextNew();
        }
      },
      abort: () => { aborted = true; }
    };
  }
 
  makecanvas(k, sizeInfo = null) {
    let gd = document.getElementById('grid');
    while (this.canvascount <= k) {
      let dd = document.createElement('div');
      dd.id = `b_${this.canvascount}`;
      dd.innerHTML = this.canvasstring(this.canvascount, sizeInfo);
      dd.className = 'hidemarks';
      dd.style.backgroundColor = this.config.unknowncolor;
      gd.appendChild(dd);
      this.canvascount += 1;
    }
  }
 
  canvasstring(k, sizeInfo = null) {
    // Use firstsize (which varies with aspect ratio) for display consistency
    let viewSize;
    if (k < this.views.length) {
      viewSize = this.views[k].size;
    } else if (sizeInfo && sizeInfo[0] !== null) {
      viewSize = sizeInfo[0];
    } else {
      viewSize = this.config.firstsize / Math.pow(this.config.zoomfactor, k);
    }
    let factor = this.config.firstsize / viewSize;
    factor = formatScale(factor);
    const w = this.config.dimsWidth;
    const h = this.config.dimsHeight;
    const cssW = this.config.cssDimsWidth;
    const cssH = this.config.cssDimsHeight;
    return `<canvas width="${w}" height="${h}" ` +
           `style="height:${cssH}px;width:${cssW}px;">` +
           `</canvas><div class="closebox"></div><div class="rect"></div>` +
           `<canvas class=overlay width=${w} height="${h}" ` +
           `style="height:${cssH}px;width:${cssW}px;">` +
           `</canvas><a class="zoomnum" target="_blank" href="?">${factor}` +
           `<div class="status"></div></a>`;
  }
 
  // Get the container element for a view
  container(k) {
    return document.getElementById(`b_${k}`);
  }
 
  canvas(k) {
    return this.container(k)?.firstElementChild;
  }
 
  rect(k) {
    return this.container(k)?.firstElementChild?.nextElementSibling?.nextElementSibling;
  }
 
  overlay(k) {
    const container = this.container(k);
    return container?.firstElementChild?.nextElementSibling
      ?.nextElementSibling?.nextElementSibling;
  }
 
  hidecanvas(k) {
    const container = this.container(k);
    if (container) {
      container.style.display = 'none';
    }
  }
 
  showcanvas(k) {
    const container = this.container(k);
    if (container) {
      container.style.display = '';
    }
  }
 
  hiddencanvas(k) {
    const container = this.container(k);
    return container?.style.display === 'none';
  }
 
  grid() {
    return document.getElementById('grid');
  }
 
  truncateviews(k) {
    while (this.views.length > k) {
      let removeIndex = this.views.length - 1;
      this.removeView(removeIndex);
    }
    while (this.canvascount > k) {
      let removeIndex = this.canvascount - 1;
      this.canvas(removeIndex)?.parentElement?.remove();
      this.canvascount -= 1;
    }
  }
 
  // Save current views to stableViews for potential reuse during navigation.
  // Unlike truncateviews, this does NOT remove boards from workers - they continue
  // computing (or stay paused if hidden). The boards will be cleaned up later
  // when stableViews is discarded.
  saveViewsToStable() {
    const viewsToSave = new Map();
    // Add existing stableViews first
    for (const view of (this.stableViews || [])) {
      if (view) viewsToSave.set(view.id, view);
    }
    // Add current views (may overlap with stableViews)
    for (const view of this.views) {
      if (view) viewsToSave.set(view.id, view);
    }
    this.stableViews = Array.from(viewsToSave.values());
    // Clear views array without removing boards
    this.views = [];
  }
 
  // Clean up boards for stableViews that weren't reused.
  // Called at the end of a successful update.
  cleanupUnusedStableViews(usedViewIds) {
    if (!this.stableViews) return;
    for (const view of this.stableViews) {
      if (view && !usedViewIds.has(view.id)) {
        // This view wasn't reused - remove its board from the worker.
        // Pass the view's ID so we only remove if the board at that index
        // still belongs to this view (not a new board created in its place).
        this.scheduler.removeBoardFromWorker(view.k, view.id);
      }
    }
    this.stableViews = null;
 
    // Debug check: verify no orphan boards remain after cleanup
    this.scheduler.checkForOrphanBoards(this.views);
  }
 
  showAllViews() {
    for (let j = 0; j < this.canvascount; ++j) {
      this.showcanvas(j);
    }
    this.notifyzoom();
  }
 
  truncatehiddenviews() {
    let j = this.canvascount - 1;
    for (; j > 0; j--) {
      if (!this.hiddencanvas(j)) {
        break;
      }
    }
    this.truncateviews(j + 1);
    if (j === 0) {
      this.showcanvas(j);
    }
  }
 
  updateProgress(overtarget, k) {
    if (overtarget.tagName === 'A' && overtarget.classList.contains('zoomnum')) {
      if (this.config.mobile) {
        overtarget.removeAttribute('href');
      } else {
        overtarget.href = this.bigurl(k, overtarget.showDebug);
      }
 
      let statusDiv = overtarget.querySelector('.status');
      if (!statusDiv) return;
 
      if (!overtarget.matches(':hover')) {
        // Clear text and reset alignment after animation transition
        setTimeout(() => {
          statusDiv.textContent = '';
          statusDiv.classList.remove('align-left');
          statusDiv.style.left = '';
        }, 300);
        return;
      }
 
      // Regular status
      // Use unfinished() for percentage (accounts for chaotic pixels after max iterations)
      const unfinishedCount = this.views[k].unfinished();
      let percentDone = Math.floor(1000 * (1.0 - unfinishedCount / this.config.dimsArea))/10.0;
      // Cap at 99.9% until truly complete to avoid showing 100% while still computing
      if (unfinishedCount > 0 && percentDone >= 99.9) {
        percentDone = 99.9;
      }
      // Use QD precision coordinates when available to preserve full precision in status
      const coords = formatcomplex(k, this.views[k].re, this.views[k].im)
        .replaceAll('-', '\u2212');
      const iters = formatLargeInt(this.views[k].it);
      const regularStatus = `${MSG.center_at_}${coords}\n${percentDone}` +
                             `${MSG.percent_done_after_}${iters}${MSG.iters}`;
      statusDiv.textContent = regularStatus;
 
      // Debug status
      if (overtarget.showDebug) {
        statusDiv.innerHTML += `\n${this.views[k].debugStatus()}`;
      }
 
      // Reposition popup if it would go off the left edge of the screen
      // Only check once (when not already aligned) to avoid flickering
      if (!statusDiv.classList.contains('align-left')) {
        const rect = statusDiv.getBoundingClientRect();
        if (rect.left < 0) {
          // Align with viewport left edge: calculate offset from zoomnum to viewport
          const zomnumRect = overtarget.getBoundingClientRect();
          statusDiv.classList.add('align-left');
          statusDiv.style.left = `${-zomnumRect.left}px`;
        }
      }
 
      setTimeout(() => this.updateProgress(overtarget, k), 100);
    }
  }
 
  bigurl(k, debug) {
    if (k >= this.views.length) return;
    const osize = this.views[k].size;
    const zoomFactor = this.config.firstsize / osize;  // Zoom factor (1.0 = default)
    const exponentParam = this.config.exponent !== 2 ?
      `&exponent=${this.config.exponent}` : '';
    const themeParam = this.config.theme !== 'warm' ? `&theme=${this.config.theme}` : '';
    const coords = formatcomplex(k, this.views[k].re, this.views[k].im);
    return `?z=${formatZoom(zoomFactor)}${exponentParam}&c=${coords}${themeParam}`;
  }
 
  clearseq(k) {
    const overlayElement = this.overlay(k);
    if (overlayElement) {
      let ctx = overlayElement.getContext('2d');
      ctx.clearRect(0, 0, this.config.dimsWidth, this.config.dimsHeight);
    }
  }
 
  onurlchange(callback) {
    this.urlListeners.push(callback);
  }
 
  notifyurl() {
    for (let cb of this.urlListeners) {
      cb();
    }
  }
 
  onzoomchange(callback) {
    this.zoomListeners.push(callback);
  }
 
  notifyzoom() {
    for (let cb of this.zoomListeners) {
      cb();
    }
  }
 
  updateFullscreenButton() {
    const button = document.getElementById('fullscreen-button');
    if (button && !document.fullscreenElement) {
      // Show button unless mouse is over a board view
      button.style.display = 'block';
      if (!this._mouseOverBoard) {
        button.style.opacity = '0.7';
      }
    }
  }
 
  setupFullscreenButtonHover() {
    const button = document.getElementById('fullscreen-button');
    const gridElement = document.getElementById('grid');
    if (!button || !gridElement) return;
 
    this._mouseOverBoard = false;
 
    // Check if button overlaps with any visible view
    const buttonOverlapsViews = () => {
      const btnRect = button.getBoundingClientRect();
      for (const child of gridElement.children) {
        if (child.style.display === 'none') continue;
        const viewRect = child.getBoundingClientRect();
        // Check for rectangle overlap
        if (btnRect.left < viewRect.right && btnRect.right > viewRect.left &&
            btnRect.top < viewRect.bottom && btnRect.bottom > viewRect.top) {
          return true;
        }
      }
      return false;
    };
 
    // Update button visibility based on mouse position and view overlap
    const updateButtonVisibility = () => {
      if (document.fullscreenElement) return;
      if (this._mouseOverBoard && buttonOverlapsViews()) {
        button.style.opacity = '0';
        button.style.pointerEvents = 'none';
      } else {
        button.style.opacity = '0.7';
        button.style.pointerEvents = '';
      }
    };
 
    // Fade out button when mouse enters grid AND button overlaps views
    gridElement.addEventListener('mouseenter', (e) => {
      this._mouseOverBoard = true;
      updateButtonVisibility();
    }, true);
 
    // Fade in button when mouse leaves the grid entirely
    gridElement.addEventListener('mouseleave', (e) => {
      this._mouseOverBoard = false;
      updateButtonVisibility();
    }, true);
 
    // Re-check on scroll in case views now overlap button
    window.addEventListener('scroll', updateButtonVisibility, { passive: true });
  }
}
 
// Draws zoom preview rectangles and handles zoom factor UI.
class ZoomManager {
  constructor(config, grid) {
    this.config = config;
    this.grid = grid;
    this.grid.onzoomchange(() => this.updateZoomRectangles());
  }
 
  showZoomRect(k, x, y, zf) {
    const s = this.grid.rect(k).style;
    const border = 1;
    let cssClass = '';
    if (zf > 50) {
      // Switch from rectangle to circle if the zoom area is tiny.
      zf = 25;
      cssClass = 'circle';
    }
    this.grid.rect(k).parentElement.className = cssClass;
 
    if (cssClass === 'circle') {
      // To make a circle, width and height must be equal.
      // We use the average of the would-be width and height for the diameter.
      const diameter = (this.config.cssDimsWidth + this.config.cssDimsHeight) / 2 / zf;
      s.width = `${diameter + 2 * border}px`;
      s.height = `${diameter + 2 * border}px`;
      s.left = `${x * this.config.cssDimsWidth - diameter / 2 - border}px`;
      s.top = `${y * this.config.cssDimsHeight - diameter / 2 - border}px`;
    } else {
      const rectWidth = this.config.cssDimsWidth / zf;
      const rectHeight = this.config.cssDimsHeight / zf;
      s.width = `${rectWidth + 2 * border}px`;
      s.height = `${rectHeight + 2 * border}px`;
      s.left = `${x * this.config.cssDimsWidth - rectWidth / 2 - border}px`;
      s.top = `${y * this.config.cssDimsHeight - rectHeight / 2 - border}px`;
    }
  }
 
  removeZoomRect(k) {
    let s = this.grid.rect(k).style;
    s.top = s.left = s.width = s.height = '';
    this.grid.rect(k).parentElement.className = 'hidemarks';
  }
 
  updateZoomRectangles() {
    let prevSizeQD = null, prevReQD = null, prevImQD = null;
    let prevK = 0;
    for (let k = 0; k < this.grid.views.length; k++) {
      if (this.grid.hiddencanvas(k)) { continue; }
      const view = this.grid.views[k];
      if (!view || !view.sizesQD) { continue; }
      const [currSizeQD, currReQD, currImQD] = view.sizesQD;
      if (prevSizeQD !== null) {
        const prevSize = qdToNumber(prevSizeQD);
        let x = qdToNumber(toQDSub(currReQD, prevReQD)) / prevSize + 0.5;
        let y = 0.5 - qdToNumber(toQDSub(currImQD, prevImQD)) /
          (prevSize / this.config.aspectRatio);
 
        let zf = prevSize / qdToNumber(currSizeQD);
        this.showZoomRect(prevK, x, y, zf);
      }
      prevSizeQD = currSizeQD;
      prevReQD = currReQD;
      prevImQD = currImQD;
      prevK = k;
    }
    if (prevSizeQD !== null) {
      this.removeZoomRect(prevK);
    }
  }
 
  zoomInAtCurrentPosition(hideCurrent) {
    let k = this.grid.views.length - 1;
    if (this.grid.views[k].uninteresting()) { return; }
    let osize = this.grid.views[k].size;
    let oreQD = this.grid.views[k].re;
    let oimQD = this.grid.views[k].im;
    let rre = Config.CENTER_COORDINATE;
    // Check if center is at (-0.5, 0) - use QD comparison
    if (k === 0 && qdEq(oreQD, -0.5) && qdEq(oimQD, 0)) {
      // Myreberg / Feigenbaum point
      const baseRe = this.grid.views[0].re;
      oreQD = Config.FEIGENBAUM_POINT_QD;
      rre = qdToNumber(toQDAdd(
        toQDScale(toQDSub(oreQD, baseRe), 1 / this.grid.views[0].size),
        Config.CENTER_COORDINATE
      ));
    }
    this.showZoomRect(k, rre, 0.5, this.config.zoomfactor);
    let nsize = osize / this.config.zoomfactor;
 
    // Stage 1: Create DOM and scroll immediately
    // Pass nsize to makecanvas so the zoom label shows correct scientific notation
    this.grid.makecanvas(k + 1, [nsize, null, null]);
    if (hideCurrent) {
      this.grid.canvas(k).parentElement.style.display = 'none';
      this.updateZoomRectangles();
      this.grid.updateHiddenViews();
    }
    this.grid.canvas(k + 1).parentElement.className = 'hidemarks';
    const canvas = this.grid.canvas(k + 1);
    canvas.parentElement.scrollIntoView({ behavior: 'smooth', block: 'center' });
 
    // Force browser to render stage 1 before continuing
    canvas.offsetHeight; // Trigger reflow
 
    // Stage 2: Create view structure
    setTimeout(() => {
      // Pass QD coordinates directly to preserve full precision at deep zoom
      let newView = this.grid.makeView(
        k + 1, nsize, oreQD, oimQD, true
      );
      this.grid.notifyurl();
 
      // Stage 3: Draw and start computation
      setTimeout(() => {
        newView.draw(canvas.getContext('2d'));
        this.grid.startViewComputation(k + 1);
      }, 0);
    }, 0);
  }
 
  cellclick(k, m, hideCurrent) {
    // Only accept clicks on cells with something computed in them.
    if (k >= this.grid.views.length || this.grid.views[k].uninteresting() ||
         this.grid.currentUpdateProcess) return;
    setTimeout(() => { this.cellclickdelay(k, m, hideCurrent); }, 1);
  }
 
  cellclickdelay(k, m, hideCurrent) {
    if (k >= this.grid.views.length || this.grid.currentUpdateProcess) return;
    let osize = this.grid.views[k].size;
    let ore = this.grid.views[k].re;
    let oim = this.grid.views[k].im;
    let cx = m % this.config.dimsWidth;
    let cy = (m - cx) / this.config.dimsWidth;
    const rectX = cx / this.config.dimsWidth;
    const rectY = cy / this.config.dimsHeight;
    this.showZoomRect(k, rectX, rectY, this.config.zoomfactor);
    this.grid.truncateviews(k + 1);
    // Update hidden views after truncating - this clears any stale hidden board indices
    // that no longer exist, preventing them from blocking new boards at those indices
    this.grid.updateHiddenViews();
    let nsize = osize / this.config.zoomfactor;
    // Compute fractional offsets from center (both as simple fractions)
    const offsetX = (cx / this.config.dimsWidth) - 0.5;
    const offsetY = 0.5 - rectY;
    // Scale offsets by size to preserve accuracy at deep zoom (toQDScale handles conversion)
    const nreQD = toQDAdd(ore, toQDScale(osize, offsetX));
    const nimQD = toQDAdd(oim, toQDScale(osize, offsetY / this.config.aspectRatio));
 
    // Stage 1: Create DOM and scroll immediately (instant visual feedback)
    // Pass nsize to makecanvas so the zoom label shows correct scientific notation
    this.grid.makecanvas(k + 1, [nsize, null, null]);
    this.grid.updateFullscreenButton();
    if (hideCurrent) {
      this.grid.canvas(k).parentElement.style.display = 'none';
      this.updateZoomRectangles();
      this.grid.updateHiddenViews();
    }
    this.grid.canvas(k + 1).parentElement.className = 'hidemarks';
    const canvas = this.grid.canvas(k + 1);
    canvas.parentElement.scrollIntoView({ behavior: 'smooth', block: 'center' });
 
    // Force browser to render stage 1 before continuing
    canvas.offsetHeight; // Trigger reflow
 
    // Stage 2: Create view structure
    // Pass QD precision coordinates to preserve full precision at deep zoom
    setTimeout(() => {
      let newView = this.grid.makeView(k + 1, nsize, nreQD, nimQD, true);
      this.grid.showcanvas(k + 1);
      this.grid.notifyurl();
      document.body.className = '';
 
      // Stage 3: Draw and start computation
      setTimeout(() => {
        newView.draw(canvas.getContext('2d'));
        this.grid.startViewComputation(k + 1);
      }, 0);
    }, 0);
  }
 
  centerViews(includeFirst) {
    const lastK = this.grid.views.length - 1;
    const oreQD = this.grid.views[lastK].re;
    const oimQD = this.grid.views[lastK].im;
 
    // Helper to check if view center is within 0.01% tolerance of target
    // Uses QD arithmetic to avoid precision loss at deep zoom
    const isWithinTolerance = (view, targetReQD, targetImQD) => {
      const viewSize = view.size;
      const tolerance = viewSize * 0.0001; // 0.01% of view extent
      // Compute difference in QD space, then convert to number
      const reDiff = Math.abs(qdToNumber(toQDSub(view.re, targetReQD)));
      const imDiff = Math.abs(qdToNumber(toQDSub(view.im, targetImQD)));
      return reDiff < tolerance && imDiff < tolerance;
    };
 
    // PHASE 1: Identify which views need board recreation (using ORIGINAL coords)
    // Must do this BEFORE updating any coordinates
    const needsRecreation = [];
    for (let k = includeFirst ? 0 : 1; k < this.grid.views.length - 1; k += 1) {
      if (qdCompare(this.grid.views[k].re, oreQD) ||
          qdCompare(this.grid.views[k].im, oimQD)) {
        if (!isWithinTolerance(this.grid.views[k], oreQD, oimQD)) {
          needsRecreation.push(k);
        }
      }
    }
 
    // PHASE 2: Update all view coordinates to target
    // This ensures URL will be correct immediately
    for (let k = includeFirst ? 0 : 1; k < this.grid.views.length - 1; k += 1) {
      this.grid.views[k].sizesQD[1] = oreQD;
      this.grid.views[k].sizesQD[2] = oimQD;
    }
 
    // PHASE 3: Update URL immediately (before expensive board recreation)
    // This prevents race condition if user refreshes during processing
    this.grid.notifyurl();
 
    // PHASE 4: Show zoom rectangles (coordinates are now all centered)
    if (!includeFirst) {
      const invPrevSize = 1 / this.grid.views[0].size;
      this.showZoomRect(
        0,
        qdToNumber(toQDAdd(
          toQD(0.5),
          toQDScale(
            toQDSub(oreQD, this.grid.views[0].re),
            invPrevSize
          ))),
        qdToNumber(toQDAdd(
          toQD(0.5),
          toQDScale(
            toQDSub(this.grid.views[0].im, oimQD),
            invPrevSize * this.config.aspectRatio
          ))),
           this.grid.views[0].size / this.grid.views[1].size);
    }
    for (let k = includeFirst ? 0 : 1; k < this.grid.views.length - 1; k += 1) {
      this.showZoomRect(
          k, 0.5, 0.5, this.grid.views[k].size / this.grid.views[k+1].size);
    }
 
    // PHASE 5: Recreate boards that were beyond tolerance
    for (const k of needsRecreation) {
      this.grid.scheduler.removeBoardFromWorker(k);
      const nsize = this.grid.views[k].size;
      this.grid.makeView(k, nsize, oreQD, oimQD);
      this.grid.views[k].clearcanvas(this.grid.canvas(k).getContext('2d'));
      this.grid.clearseq(k);
    }
  }
}
 
// Synchronizes view state with URL parameters for bookmarking and sharing.
class URLHandler {
  constructor(config, grid, store = null) {
    this.config = config;
    this.grid = grid;
    this.store = store;
    // Initialize from current URL so changes can be detected
    this.lastCenters = this.extractCenters(document.location.search);
    this.lastHidden = this.extractHidden(document.location.search);
    // Track whether we're processing a popstate event
    // During popstate, we should NEVER push new history entries
    this.processingPopState = false;
    this.grid.onurlchange(x => this.updateurl());
    // Handle browser back/forward navigation
    window.addEventListener('popstate', () => this.handlePopState());
  }
 
  handlePopState() {
    // Mark that we're processing a popstate event
    // This prevents updateurl() from pushing new history entries
    this.processingPopState = true;
 
    // If config parameters that require recomputation changed, reload
    if (this.configChangedRequiresRecompute()) {
      window.location.reload();
      return;
    }
 
    // Apply display-only config changes (theme, unknowncolor)
    this.applyDisplayConfigFromUrl();
 
    // Parse the URL from history to get target state
    const targetState = this.parseUrl();
 
    // Fill in default base view if no centers specified in URL
    if (targetState.sizes.length === 0) {
      targetState.sizes = [[null, this.config.firstrQD, this.config.firstjQD]];
    }
 
    // Build pool of all reusable views (union of stableViews and current views)
    // Use a Map to dedupe by id, then convert to array for consistent indexing
    // Add stableViews first (they have computed data we want to preserve)
    // then current views (may have newer data for same coordinates)
    const viewsById = new Map();  // id -> view
    for (const view of (this.grid.stableViews || [])) {
      if (view) viewsById.set(view.id, view);
    }
    for (const view of this.grid.views) {
      if (view) viewsById.set(view.id, view);
    }
    const reusableViews = Array.from(viewsById.values());
 
    // Build currentState from reusable views array
    // The indices here must match reusableViews array indices
    // State format: [sizeDouble, reQD, imQD] - matches sizesQD storage format
    const currentState = { hidden: [], sizes: [] };
    for (const view of reusableViews) {
      currentState.sizes.push(view.sizesQD);
    }
 
    // Find views to keep vs recreate by comparing coordinates
    const { viewsToKeep, newState } = this.computeViewTransition(currentState, targetState);
 
    if (viewsToKeep.length === 0) {
      // No views can be reused, just reload
      window.location.reload();
      return;
    }
 
    // Apply the optimized transition, passing the pool of reusable views
    // Note: applyViewTransition triggers updateLayout which is async.
    // processingPopState stays > 0 until the update completes and calls notifyurl().
    // We decrement it in updateurl() after the update completes.
    this.applyViewTransition(viewsToKeep, newState, reusableViews);
  }
 
  // Check if config parameters require full recomputation (not just redraw)
  configChangedRequiresRecompute() {
    const params = new URLSearchParams(document.location.search);
 
    // Parameters that require full recomputation
    const exponent = params.get('exponent');
    if (exponent && parseInt(exponent) !== this.config.exponent) return true;
 
    const gpu = params.get('gpu');
    if (gpu !== null && (parseInt(gpu) !== 0) !== this.config.enableGPU) return true;
 
    const aspectRatio = params.get('a');
    if (aspectRatio) {
      const m = aspectRatio.match(/(\d+):(\d+)/);
      if (m) {
        const ratio = parseInt(m[1]) / parseInt(m[2]);
        if (Math.abs(ratio - this.config.aspectRatio) > 0.01) return true;
      }
    }
 
    const pixelRatio = params.get('pixelratio');
    if (pixelRatio && parseInt(pixelRatio) !== this.config.pixelRatio) return true;
 
    const grid = params.get('grid');
    if (grid && parseInt(grid) !== this.config.gridcols) return true;
 
    return false;
  }
 
  // Apply display-only config changes (theme, unknowncolor) without recomputing
  // Also restores defaults when parameters are missing from URL
  applyDisplayConfigFromUrl() {
    const params = new URLSearchParams(document.location.search);
    let needsRedraw = false;
 
    // Theme: use URL value or default to 'warm'
    const theme = params.get('theme');
    const targetTheme = (theme && this.config.colorThemes.all.includes(theme)) ?
      theme : 'warm';
    if (targetTheme !== this.config.theme) {
      this.store.dispatch(this.store.actions.updateConfig({ theme: targetTheme }));
      needsRedraw = true;
    }
 
    // Unknown color: use URL value or default to '#000'
    const unk = params.get('unk');
    let targetColor = '#000';  // default
    if (unk) {
      targetColor = decodeURIComponent(unk);
      if (/^[0-9a-fA-F]{3}$|^[0-9a-fA-F]{6}$/.test(targetColor)) {
        targetColor = `#${targetColor}`;
      }
    }
    if (targetColor !== this.config.unknowncolor) {
      this.store.dispatch(this.store.actions.updateConfig({ unknowncolor: targetColor }));
      needsRedraw = true;
    }
 
    // Redraw all views if display config changed
    if (needsRedraw) {
      for (let k = 0; k < this.grid.views.length; k++) {
        if (this.grid.views[k]) {
          this.grid.views[k].draw(this.grid.canvas(k).getContext('2d'));
        }
      }
    }
  }
 
  // Compare current and target states, find which views can be reused
  computeViewTransition(currentState, targetState) {
    const viewsToKeep = [];  // Indices of current views to preserve
    const newState = { sizes: [], hidden: targetState.hidden };
 
    // Fill in sizes for target state (parseUrl leaves size as null)
    const zoomFactor = this.getZoomFactorFromUrl();
    let size = this.config.firstsize / zoomFactor;
    for (let i = 0; i < targetState.sizes.length; i++) {
      if (i > 0) {
        size = size / this.config.zoomfactor;
      }
      targetState.sizes[i][0] = size;
    }
 
    // Match target views against current views by coordinates AND zoom level
    // A view is defined by both its center and its size (zoom level)
    // Uses QD precision coordinates with 0.01% tolerance thresholds
    const viewsMatch = (targetSize, targetRe, targetIm,
                        currentSize, currentRe, currentIm) => {
      // Check zoom level first - must be within 0.1% of each other
      const sizeRatio = targetSize / currentSize;
      if (sizeRatio < 0.999 || sizeRatio > 1.001) return false;
 
      // Check coordinates - tolerance is 0.01% of the view's visible extent
      // Compute difference in QD precision first, then convert magnitude to double
      // (converting coords to double first would lose precision at deep zooms)
      const tolerance = currentSize * 0.0001;
      const reDiff = Math.abs(qdToNumber(toQDSub(targetRe, currentRe)));
      const imDiff = Math.abs(qdToNumber(toQDSub(targetIm, currentIm)));
      return reDiff < tolerance && imDiff < tolerance;
    };
 
    // Track which current views have been matched (can't reuse same view twice)
    const usedCurrentIndices = new Set();
 
    for (let targetIdx = 0; targetIdx < targetState.sizes.length; targetIdx++) {
      const [targetSize, targetRe, targetIm] = targetState.sizes[targetIdx];
      let foundMatch = false;
 
      for (let currentIdx = 0; currentIdx < currentState.sizes.length; currentIdx++) {
        // Skip if this current view was already matched to a previous target
        if (usedCurrentIndices.has(currentIdx)) continue;
 
        const [currentSize, currentRe, currentIm] = currentState.sizes[currentIdx];
 
        // Compare both coordinates and zoom level
        if (viewsMatch(targetSize, targetRe, targetIm, currentSize, currentRe, currentIm)) {
          // View matches - reuse it
          viewsToKeep.push({ targetIdx, currentIdx });
          usedCurrentIndices.add(currentIdx);
          // Use current view's size (preserves computation state)
          newState.sizes.push(currentState.sizes[currentIdx]);
          foundMatch = true;
          break;
        }
      }
 
      if (!foundMatch) {
        // No match - need to create new view
        newState.sizes.push(targetState.sizes[targetIdx]);
      }
    }
 
    return { viewsToKeep, newState };
  }
 
  /**
   * Parse a scientific notation string like "1e400" without JavaScript's parseFloat overflow.
   * Returns {mantissa, exponent} where the value = mantissa * 10^exponent.
   */
  parseScientificNotation(str) {
    str = str.trim().toLowerCase();
    // Match patterns like: 1e400, 1.5e+300, 2e-10, 1.23
    const match = str.match(/^([+-]?\d*\.?\d+)(?:e([+-]?\d+))?$/);
    if (!match) {
      return { mantissa: parseFloat(str), exponent: 0 };
    }
    const mantissa = parseFloat(match[1]);
    const exponent = match[2] ? parseInt(match[2], 10) : 0;
    return { mantissa, exponent };
  }
 
  getZoomFactorFromUrl() {
    const params = new URLSearchParams(document.location.search);
    let zVal = params.get('z');
    if (zVal) {
      zVal = zVal.replace(/ /g, '+');
      const { mantissa, exponent } = this.parseScientificNotation(zVal);
      return mantissa * Math.pow(10, exponent);
    }
    return 1.0;
  }
 
  // Apply the transition - updateLayout will automatically preserve matching views
  applyViewTransition(viewsToKeep, newState, reusableViews) {
    // Note: processingPopState counter is set in handlePopState and decremented in updateurl()
    // This ensures that the notifyurl() call at the end of updateLayout doesn't push history
    this.grid.updateLayout(newState);
  }
 
  updateurl() {
    if (!history.replaceState) return;
 
    // NEVER push history during popstate processing - this would destroy forward history
    if (this.processingPopState) {
      // Clear the flag - this update was triggered by a popstate
      this.processingPopState = false;
      // Just update lastCenters/lastHidden to match current URL, no history change
      this.lastCenters = this.extractCenters(document.location.search);
      this.lastHidden = this.extractHidden(document.location.search);
      // Don't call replaceState - the URL is already correct from the popstate
      return;
    }
 
    const newSearch = this.currenturl();
    const newCenters = this.extractCenters(newSearch);
    const newHidden = this.extractHidden(newSearch);
    var newUrl = new URL(window.location);
    newUrl.search = newSearch;
 
    // Use pushState if centers were removed/replaced OR hidden views changed
    const centersLost = this.lastCenters !== null &&
      centersWereLost(this.lastCenters, newCenters);
    const hiddenChanged = this.lastHidden !== null && this.lastHidden !== newHidden;
 
    if (centersLost || hiddenChanged) {
      history.pushState(null, '', newUrl);
    } else {
      history.replaceState(null, '', newUrl);
    }
 
    this.lastCenters = newCenters;
    this.lastHidden = newHidden;
  }
 
  // Extract the c parameter value from a URL string
  extractCenters(url) {
    const match = url.match(/[?&]c=([^&]*)/);
    return match ? match[1] : '';
  }
 
  // Extract the h parameter value from a URL string
  extractHidden(url) {
    const match = url.match(/[?&]h=([^&]*)/);
    return match ? match[1] : '';
  }
 
  setupUrlParameters() {
    // Registry of simple URL parameters with their parse logic
    // Each parse function adds properties to the configUpdates object
    this.urlParams = [
      {
        name: 'exponent',
        parse: (val, configUpdates) => {
          const exponent = Math.max(2, parseInt(val));
          configUpdates.exponent = exponent;
          if (exponent > 2) { configUpdates.firstrQD = [0.0, 0, 0, 0]; }
          // DOM update (side effect, not state)
          for (const el of document.querySelectorAll('.exponent')) {
            el.innerText = exponent;
          }
        }
      },
      {
        name: 'gpu',
        parse: (val, configUpdates) => {
          configUpdates.enableGPU = parseInt(val) !== 0;
        }
      },
      {
        name: 'board',
        parse: (val, configUpdates) => {
          const boardType = val.toLowerCase();
          const validTypes = [
            'cpu', 'ddz', 'qdz', 'pert', 'qdpert', 'gpu', 'gpuz',
            'adaptive', 'qdcpu'
          ];
          if (validTypes.includes(boardType)) {
            configUpdates.forceBoard = boardType;
          } else {
            console.warn(`Invalid board type: ${boardType}. Valid types: ${validTypes.join(', ')}`);
          }
        }
      },
      {
        name: 'grid',
        parse: (val, configUpdates) => {
          configUpdates.gridcols = Math.max(1, parseInt(val));
        }
      },
      {
        name: 'a',
        parse: (val, configUpdates) => {
          const m = val.match(/(\d+):(\d+)/);
          if (m) {
            const width = parseInt(m[1]);
            const height = parseInt(m[2]);
            if (width > 0 && height > 0) {
              configUpdates.aspectRatio = width / height;
            }
          }
        }
      },
      {
        name: 'z',
        parse: (val, configUpdates) => {
          // URLSearchParams decodes '+' as space, convert back for, e.g., 3e+20
          val = val.replace(/ /g, '+');
          // Parse scientific notation to handle extreme zoom values (e.g., 1e400)
          const { mantissa, exponent } = this.parseScientificNotation(val);
          // Store zoom parameters for later - size computation needs
          // aspect-ratio-adjusted firstsize
          // which isn't available until after initSizes() is called
          this.config.zoomFromUrl = { mantissa, exponent };
        }
      },
      {
        name: 's',
        parse: (val, configUpdates) => {
          // Legacy size parameter (e.g., s=1e-15 means view size of 1e-15)
          // Read-only: we accept it but output z= in URLs
          val = val.replace(/ /g, '+');
          const { mantissa, exponent } = this.parseScientificNotation(val);
          // Store size directly - will be used as actualSize in initSizes()
          this.config.sizeFromUrl = { mantissa, exponent };
        }
      },
      {
        name: 'pixelratio',
        parse: (val, configUpdates) => {
          configUpdates.pixelRatio = Math.max(1, parseInt(val));
        }
      },
      {
        name: 'theme',
        parse: (val, configUpdates) => {
          if (this.config.colorThemes.all.includes(val)) {
            configUpdates.theme = val;
          }
        }
      },
      {
        name: 'unk',
        parse: (val, configUpdates) => {
          // Allow any CSS color (e.g., 000, rgb(32,16,64), yellow, etc.)
          let color = decodeURIComponent(val);
          // Auto-prepend # for hex colors (e.g., 888 -> #888)
          if (/^[0-9a-fA-F]{3}$|^[0-9a-fA-F]{6}$/.test(color)) {
            color = `#${color}`;
          }
          configUpdates.unknowncolor = color;
        }
      },
      {
        name: 'debug',
        parse: (val, configUpdates) => {
          // Debug flags (comma-separated, supports key=value)
          // Suggested flags:
          //   w = load worker code on main thread (makes Board classes globally available for debugging)
          //   n = noinit (skip default view creation - starts with blank canvas)
          //   t = trace (enable detailed logging)
          //   x=value = example custom flag with value
          // Examples: ?debug=w,t  or  ?debug=w,n  or  ?debug=w,x=foobar
          configUpdates.debug = val;
        }
      }
    ];
  }
 
  parseUrl() {
    const startstate = { hidden: [], sizes: [] };
    const params = new URLSearchParams(document.location.search);
 
    // Parse all registered simple parameters
    if (!this.urlParams) {
      this.setupUrlParameters();
    }
 
    // Collect all config updates to batch them into a single dispatch
    const configUpdates = {};
    for (const param of this.urlParams) {
      const value = params.get(param.name);
      if (value) {
        param.parse(value, configUpdates);
      }
    }
 
    // Batch update all config changes at once
    if (Object.keys(configUpdates).length > 0) {
      this.config.store.dispatch(
        this.config.store.actions.updateConfig(configUpdates)
      );
    }
 
    // Parse coordinates parameter
    // Note: URLSearchParams decodes '+' as space, so we convert spaces back to '+'
    let c = params.get('c');
    if (c) {
      c = c.replace(/ /g, '+');
      for (const coords of c.split(',')) {
        // Parse complex number string (empty string returns null to inherit)
        const parsed = parseComplexToQD(coords);
 
        // If parsing failed or empty string, inherit from previous or default
        if (!parsed) {
          startstate.sizes.push([
            null,  // Placeholder - will be filled in after initSizes()
            startstate.sizes.length > 0 ?
              startstate.sizes[startstate.sizes.length - 1][1] :
              this.config.firstrQD,
            startstate.sizes.length > 0 ?
              startstate.sizes[startstate.sizes.length - 1][2] :
              this.config.firstjQD
          ]);
        } else {
          // Store parsed coordinates; size will be calculated later
          startstate.sizes.push([
            null,  // Placeholder - will be filled in after initSizes()
            parsed.re,
            parsed.im
          ]);
        }
      }
    }
 
    // Parse hidden views parameter
    const h = params.get('h');
    if (h) {
      startstate.hidden = h.split(',').map(x => parseInt(x));
    }
 
    // Don't fill in default sizes yet - wait until after initSizes()
    // so that firstsize accounts for aspect ratio
    return startstate;
  }
 
  currenturl() {
    let state = this.grid.currentGridState();
    let compactc = '';
    let commas = '';
    let prev = [this.config.firstrQD, this.config.firstjQD];
    let prevj = -1;
    for (let j = 0; j <= state.sizes.length; j++) {
      const view = this.grid.views[j];
      const viewReQD = view ? view.re : state.sizes[j]?.[1];
      const viewImQD = view ? view.im : state.sizes[j]?.[2];
      if (j < state.sizes.length &&
          !qdCompare(viewReQD, prev[0]) &&
          !qdCompare(viewImQD, prev[1])) {
        commas += ',';
      } else {
        if (prevj >= 0) {
          const pv = this.grid.views[prevj];
          const pre = pv ? pv.re : state.sizes[prevj][1];
          const pim = pv ? pv.im : state.sizes[prevj][2];
          compactc += `${formatcomplex(j - 1, pre, pim)},`;
        }
        compactc += commas;
        if (j < state.sizes.length) {
          commas = '';
          prev = [viewReQD, viewImQD];
          prevj = j;
        }
      }
    }
    compactc = compactc.slice(0, -1);
    // Calculate zoom factor for URL (z parameter)
    let zoomFactor = this.grid.views[0].zoomFactor;
 
    // Format aspect ratio for URL (only if not 1:1)
    let aspectRatioParam = '';
    if (this.config.aspectRatio !== 1.0) {
      const [num, den] = toSimpleFraction(this.config.aspectRatio);
      aspectRatioParam = `&a=${num}:${den}`;
    }
 
    const url =
        (Math.abs(zoomFactor - 1.0) > 0.01
            ? `&z=${formatZoom(zoomFactor)}` : '') +
        aspectRatioParam +
        (this.config.exponent !== 2
            ? `&exponent=${this.config.exponent}` : '') +
        (!this.config.enableGPU
            ? '&gpu=0' : '') +
        (this.config.forceBoard
            ? `&board=${this.config.forceBoard}` : '') +
        (compactc.length
            ? `&c=${compactc}` : '') +
        (this.config.gridcols !== Math.min(2, Math.ceil(this.config.vw / 501))
            ? `&grid=${this.config.gridcols}` : '') +
        (state.hidden.length
            ? `&h=${state.hidden}` : '') +
        (this.config.theme !== 'warm'
            ? `&theme=${this.config.theme}` : '') +
        (this.config.unknowncolor !== '#000'
            ? `&unk=${encodeURIComponent(
              /^#[0-9a-fA-F]{3}$|^#[0-9a-fA-F]{6}$/.test(this.config.unknowncolor)
              ? this.config.unknowncolor.substring(1)
              : this.config.unknowncolor)}` : '') +
        (this.config.pixelRatio !== 2
            ? `&pixelratio=${this.config.pixelRatio}` : '') +
        (this.config.debug
            ? `&debug=${this.config.debug}` : '') +
        (LANG_FROM_URL ? `&lang=${SELECTED_LANG}` : '');
    return url.replace('&', '?');
  }
}
 
// Handles mouse clicks, keyboard commands, and touch events.
class EventHandler {
  constructor(explorer) {
    this.explorer = explorer;
  }
 
  setup() {
    this.setupKeyboardCommands();
    this.setupEventDelegation();
    document.onmousedown = this.onmousedown.bind(this);
    document.onmousemove = this.onmousemove.bind(this);
    document.onmouseup = this.onmouseup.bind(this);
    document.body.onkeydown = this.onkeydown.bind(this);
    document.body.onmouseover = this.onmouseover.bind(this);
  }
 
  setupEventDelegation() {
    // Use event delegation on grid for closebox interactions
    const gridElement = document.getElementById('grid');
 
    gridElement.addEventListener('mousedown', (e) => {
      if (e.target.classList.contains('closebox')) {
        e.stopPropagation();
      }
    }, true);  // Use capture phase
 
    gridElement.addEventListener('click', (e) => {
      if (e.target.classList.contains('closebox') &&
          !this.explorer.grid.currentUpdateProcess) {
        e.target.parentElement.style.display = 'none';
        this.explorer.grid.truncatehiddenviews();
        this.explorer.zoomManager.updateZoomRectangles();
        this.explorer.grid.updateHiddenViews();
        this.explorer.grid.updateFullscreenButton();
        this.explorer.urlHandler.updateurl();
      }
    });
 
    // Handle right-click on canvas with custom context menu
    gridElement.addEventListener('contextmenu', (e) => {
      if (e.target.tagName === 'CANVAS' && !e.target.classList.contains('overlay')) {
        // If transparent mode, let native context menu handle it
        if (this.explorer.config.unknowncolor === 'transparent') {
          return;
        }
 
        e.preventDefault();
        const canvas = e.target;
 
        // Get view index from canvas parent id (format: b_0, b_1, etc.)
        const containerId = canvas.parentElement?.id;
        const k = containerId ? parseInt(containerId.split('_')[1]) : 0;
        const view = this.explorer.grid.views[k];
 
        // Build filename using view coordinates and zoom
        const zoomFactor = this.explorer.config.firstsize / view.size;
        const coords = formatcomplex(k, view.re, view.im);
        const filename = `mandelbrot-z${formatZoom(zoomFactor)}-c${coords}.png`;
 
        // Create composited canvas with background color
        const createCompositedBlob = () => {
          return new Promise((resolve) => {
            const tempCanvas = document.createElement('canvas');
            tempCanvas.width = canvas.width;
            tempCanvas.height = canvas.height;
            const tempCtx = tempCanvas.getContext('2d');
 
            // Draw background first, then original canvas on top
            tempCtx.fillStyle = this.explorer.config.unknowncolor;
            tempCtx.fillRect(0, 0, canvas.width, canvas.height);
            tempCtx.drawImage(canvas, 0, 0);
 
            tempCanvas.toBlob(resolve, 'image/png');
          });
        };
 
        // Create and show custom context menu (macOS style)
        const menu = document.createElement('div');
        menu.style.cssText = `
          position: fixed;
          left: ${e.clientX}px;
          top: ${e.clientY}px;
          background: rgba(227, 227, 226, 0.9);
          backdrop-filter: blur(20px);
          -webkit-backdrop-filter: blur(20px);
          border: 0.5px solid rgba(0, 0, 0, 0.15);
          border-radius: 6px;
          box-shadow: 0 6px 20px rgba(0, 0, 0, 0.2);
          padding: 6px;
          z-index: 10000;
          font: 13.5px -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
        `;
 
        const createMenuItem = (text) => {
          const item = document.createElement('div');
          item.textContent = text;
          item.style.cssText = `
            padding: 5px 8px;
            margin-bottom: 1px;
            cursor: default;
            white-space: nowrap;
            border-radius: 4px;
            color: rgb(35, 35, 35);
            text-align: left;
          `;
          item.addEventListener('mouseenter', () => {
            item.style.background = 'rgb(95, 150, 244)';
            item.style.color = '#fff';
          });
          item.addEventListener('mouseleave', () => {
            item.style.background = '';
            item.style.color = 'rgb(35, 35, 35)';
          });
          return item;
        };
 
        // Blink animation for menu selection
        const blinkItem = async (item) => {
          item.style.animation = 'menuBlink 0.25s ease-in-out';
          await new Promise(r => setTimeout(r, 250));
        };
        if (!document.getElementById('menuBlinkStyle')) {
          const style = document.createElement('style');
          style.id = 'menuBlinkStyle';
          style.textContent = `
            @keyframes menuBlink {
              0%, 100% { background: rgb(95, 150, 244); color: #fff; }
              50% { background: transparent; color: rgb(35, 35, 35); }
            }
          `;
          document.head.appendChild(style);
        }
 
        // Save image option
        const hasSavePicker = !!window.showSaveFilePicker;
        const saveItem = createMenuItem(hasSavePicker ? 'Save Image As...' : 'Download Image');
        saveItem.addEventListener('click', async () => {
          if (window.showSaveFilePicker) {
            // Start blink but don't await - must call picker synchronously for user gesture
            saveItem.style.animation = 'menuBlink 0.25s ease-in-out';
            setTimeout(() => menu.remove(), 250);
            try {
              const handle = await window.showSaveFilePicker({
                suggestedName: filename,
                startIn: 'downloads',
                types: [{
                  description: 'PNG Image',
                  accept: { 'image/png': ['.png'] }
                }]
              });
              // Then create blob and write
              const blob = await createCompositedBlob();
              const writable = await handle.createWritable();
              await writable.write(blob);
              await writable.close();
            } catch (err) {
              if (err.name !== 'AbortError') console.error('Save failed:', err);
            }
          } else {
            // Fallback for browsers without showSaveFilePicker (e.g. Safari)
            await blinkItem(saveItem);
            menu.remove();
            const blob = await createCompositedBlob();
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = filename;
            a.click();
            URL.revokeObjectURL(url);
          }
        });
        menu.appendChild(saveItem);
 
        // Copy image option (only if ClipboardItem is supported)
        const hasClipboardItem = typeof ClipboardItem !== 'undefined' && navigator.clipboard?.write;
        if (hasClipboardItem) {
          const copyItem = createMenuItem('Copy Image');
          copyItem.addEventListener('click', async () => {
            await blinkItem(copyItem);
            menu.remove();
            const blob = await createCompositedBlob();
            try {
              await navigator.clipboard.write([
                new ClipboardItem({ 'image/png': blob })
              ]);
              // Show toast notification
              const toast = document.createElement('div');
              toast.textContent = 'Image copied';
              toast.style.cssText = `
                position: fixed;
                top: 20px;
                left: 50%;
                transform: translateX(-50%);
                background: #1a3a5c;
                color: #fff;
                padding: 12px 20px;
                border-radius: 20px;
                font: 14px -apple-system, BlinkMacSystemFont, sans-serif;
                z-index: 10001;
                opacity: 1;
                transition: opacity 0.3s ease;
              `;
              document.body.appendChild(toast);
              setTimeout(() => { toast.style.opacity = '0'; }, 1500);
              setTimeout(() => toast.remove(), 1800);
            } catch (err) {
              // Show error toast (Safari doesn't allow clipboard write)
              const toast = document.createElement('div');
              toast.textContent = 'Copy not available';
              toast.style.cssText = `
                position: fixed;
                top: 20px;
                left: 50%;
                transform: translateX(-50%);
                background: #5c3a3a;
                color: #fff;
                padding: 12px 20px;
                border-radius: 20px;
                font: 14px -apple-system, BlinkMacSystemFont, sans-serif;
                z-index: 10001;
                opacity: 1;
                transition: opacity 0.3s ease;
              `;
              document.body.appendChild(toast);
              setTimeout(() => { toast.style.opacity = '0'; }, 1500);
              setTimeout(() => toast.remove(), 1800);
            }
          });
          menu.appendChild(copyItem);
        }
 
        document.body.appendChild(menu);
 
        // Close menu when clicking outside or pressing Escape
        const closeMenu = (event) => {
          if (event.type === 'keydown' && event.key !== 'Escape') return;
          if (event.type === 'mousedown' && menu.contains(event.target)) return;
          menu.remove();
          document.removeEventListener('mousedown', closeMenu, true);
          document.removeEventListener('keydown', closeMenu, true);
        };
        setTimeout(() => {
          document.addEventListener('mousedown', closeMenu, true);
          document.addEventListener('keydown', closeMenu, true);
        }, 0);
      }
    });
 
    // Handle closebox click on help text
    const textClosebox = document.querySelector('#text .closebox');
    if (textClosebox) {
      textClosebox.addEventListener('click', () => {
        document.getElementById('text').style.display = 'none';
      });
    }
  }
 
  onmousedown(e) {
    let target = this.eventtarget(e);
 
    // Dispatch mouse down state
    if (this.explorer.store) {
      this.explorer.store.dispatch(
        this.explorer.store.actions.mouseDown(e.button, {
          x: e.clientX,
          y: e.clientY
        })
      );
    }
 
    if (this.explorer.movieMode.active && (!target || target.id !== 'moviescale')) {
      this.explorer.movieMode.toggle();
    }
    if (e.button !== 0) { return true; }
    if (target) {
      let m = target.id.match(/b_(\d+)/);
      if (e.target.tagName === 'A') {
        if (m && !this.explorer.config.mobile) {
          e.target.href = this.explorer.grid.bigurl(m[1], e.metaKey || e.ctrlKey);
        }
        return true;
      }
      if (m) {
        let p = this.pointInTarget(e, target);
        let k = parseInt(m[1]);
 
        // Dispatch focused view change
        if (this.explorer.store) {
          this.explorer.store.dispatch(
            this.explorer.store.actions.setFocusedView(k)
          );
        }
 
        // Clear orbit before creating new view
        this.explorer.orbitComputer.updateOrbit(k, -1, target);
        this.explorer.zoomManager.cellclick(k, p.x + p.y * this.explorer.config.dimsWidth,
          e.metaKey || e.ctrlKey);
        return false;
      }
    }
    return true;
  }
 
  onmousemove(e) {
    let target = this.eventtarget(e);
 
    // Dispatch mouse move state
    if (this.explorer.store) {
      this.explorer.store.dispatch(
        this.explorer.store.actions.mouseMove({
          x: e.clientX,
          y: e.clientY
        })
      );
    }
 
    if (target) {
      let m = target.id.match(/b_(\d+)/);
      if (m) {
        let p = this.pointInTarget(e, target);
        let k = parseInt(m[1]);
        let j = p.x + p.y * this.explorer.config.dimsWidth;
        this.explorer.orbitComputer.updateOrbit(k, j, target);
      }
    }
  }
 
  onmouseup(e) {
    // Dispatch mouse up state
    if (this.explorer.store) {
      this.explorer.store.dispatch(
        this.explorer.store.actions.mouseUp()
      );
    }
  }
 
  setupKeyboardCommands() {
    const { grid, config, movieMode, zoomManager, urlHandler } = this.explorer;
 
    this.keyCommands = new Map([
      ['backspace', { // Close the deepest zoom view
        condition: () => grid.views.length > 1 && !grid.currentUpdateProcess,
        action: () => {
          const k = grid.views.length - 1;
          grid.truncateviews(k);
          grid.truncatehiddenviews();
          urlHandler.updateurl();
        }
      }],
      ['c', { // Center all views on the deepest zoom
        condition: () => grid.views.length > 1,
        action: (e) => zoomManager.centerViews(e.metaKey || e.ctrlKey)
      }],
      ['a', { // Toggle aspect ratio (1:1 ↔ 16:9)
        condition: () => !grid.currentUpdateProcess,
        action: () => {
          const oldFirstsize = config.firstsize;
          config.setAspectRatio(
            config.aspectRatio === Config.DEFAULT_ASPECT_RATIO ?
              Config.WIDESCREEN_ASPECT_RATIO : Config.DEFAULT_ASPECT_RATIO
          );
          config.initSizes();
          const newFirstsize = config.firstsize;
          const state = grid.currentGridState();
          const scaleFactor = newFirstsize / oldFirstsize;
          for (let i = 0; i < state.sizes.length; i++) {
            state.sizes[i][0] *= scaleFactor;
          }
          grid.updateLayout(state);
        }
      }],
      ['t', { // Cycle color theme (Shift for reverse)
        action: (e) => this.explorer.cycleColorTheme(e.shiftKey)
      }],
      ['u', { // Cycle unknown pixel color (Shift for reverse)
        action: (e) => this.explorer.cycleUnknownColor(e.shiftKey)
      }],
      ['i', { // Zoom in at center of deepest view
        action: (e) => zoomManager.zoomInAtCurrentPosition(e.metaKey || e.ctrlKey)
      }],
      ['?', { // Show help
        action: () => {
          document.getElementById('text').style.display = '';
          document.getElementById('text').scrollIntoView({ behavior: 'smooth' });
        }
      }],
      ['g', { // Shrink grid (fewer columns)
        condition: () => config.gridcols > 1,
        action: () => {
          config.setGridcols(config.gridcols - 1);
          grid.updateLayout();
        }
      }],
      ['h', { // Grow grid (more columns)
        action: () => {
          config.setGridcols(config.gridcols + 1);
          grid.updateLayout();
        }
      }],
      ['r', { // Restore all hidden views
        condition: () => !grid.currentUpdateProcess,
        action: () => {
          grid.showAllViews();
          urlHandler.updateurl();
          grid.updateHiddenViews();
        }
      }],
      ['x', { // Increase exponent (z² → z³ → z⁴...)
        action: () => {
          config.updateExponent(config.exponent + 1);
          grid.updateLayout(config.firststate());
        }
      }],
      ['z', { // Decrease exponent (z⁴ → z³ → z²)
        condition: () => config.exponent > 2,
        action: () => {
          config.updateExponent(config.exponent - 1);
          grid.updateLayout(config.firststate());
        }
      }],
      ['f', { // Increase pixel resolution (finer)
        action: () => {
          config.setPixelRatio(config.pixelRatio + 1);
          grid.updateLayout();
        }
      }],
      ['d', { // Decrease pixel resolution (coarser)
        condition: () => config.pixelRatio > 1,
        action: () => {
          config.setPixelRatio(config.pixelRatio - 1);
          grid.updateLayout();
        }
      }],
      ['m', { // Toggle movie mode
        condition: () => grid.views.length > 1,
        action: () => movieMode.toggle()
      }],
      ['enter', { // Toggle fullscreen
        action: (e) => {
          e.preventDefault();
          this.explorer.toggleFullscreen();
        }
      }],
      ['escape', { // Exit fullscreen
        condition: () => document.fullscreenElement,
        action: () => this.explorer.toggleFullscreen()
      }]
    ]);
  }
 
  onkeydown(e) {
    const key = e.key.toLowerCase();
 
    // Movie mode intercepts most keys
    if (this.explorer.movieMode.active &&
        !['shift', 'alt', 'control', 'meta', 'capslock'].includes(key)) {
      this.explorer.movieMode.toggle();
      return;
    }
 
    // Execute command if registered
    const command = this.keyCommands.get(key);
    if (command) {
      if (!command.condition || command.condition()) {
        command.action(e);
      }
    }
  }
 
  onmouseover(e) {
    document.body.className = 'hidemarks';
    this.explorer.grid.setFocusedView(null);
    let target = this.eventtarget(e);
    if (target) {
      let m = target.id.match(/b_(\d+)/);
      if (m) {
        let k = parseInt(m[1]);
        this.explorer.grid.setFocusedView(k);
        if (this.explorer.grid.views.length <= k) return;
        document.body.className = '';
        let overtarget = e.target;
        if (overtarget.tagName == 'A') {
          overtarget.showDebug = e.ctrlKey || e.metaKey;
          this.explorer.grid.updateProgress(overtarget, k);
          const statusDiv = overtarget.querySelector('.status');
          if (statusDiv) { statusDiv.scrollIntoView({ behavior: 'smooth', block: 'nearest' }); }
        }
      } else if (target.id.startsWith('movie') && (!e.target || e.target.id != 'movie')) {
        document.body.className = '';
      }
    }
  }
 
  eventtarget(e) {
    let target = (e.target ? e.target : e.srcElement ? e.srcElement : null);
    while (target) {
      if (target.id) { return target; }
      target = target.parentNode;
    }
    return null;
  }
 
  pointInTarget(ev, target) {
    let se = document.scrollingElement || document.body;
    let x = (ev.clientX + se.scrollLeft - this.absoluteLeft(target)) *
            this.explorer.config.pixelRatio;
    let y = (ev.clientY + se.scrollTop - this.absoluteTop(target)) *
            this.explorer.config.pixelRatio;
    return { x: Math.round(x), y: Math.round(y) };
  }
 
  absoluteLeft(target) {
    let left = 0;
    while (target) {
      left += target.offsetLeft;
      target = target.offsetParent;
    }
    return left;
  }
 
  absoluteTop(target) {
    let top = 0;
    while (target) {
      top += target.offsetTop;
      target = target.offsetParent;
    }
    return top;
  }
}
 
// Renders smooth zoom animations and encodes them as MP4 video.
class MovieMode {
  constructor(explorer) {
    this.explorer = explorer;
    this.active = false;
    this.movieCanvas = null;
    this.movieCtx = null;
    this.animationTimer = null;
    this.preRenderTimer = null;
    this.frameCanvases = [];
    this.capturedFrames = [];  // Array to store VideoFrames for WebCodecs
    this.videoEncoder = null;
    this.muxer = null;
    this.recordedBlob = null;
    this.isRecording = false;
  }
 
  toggle() {
    this.active = !this.active;
 
    // Dispatch movie mode toggle to state
    if (this.explorer.store) {
      this.explorer.store.dispatch(
        this.explorer.store.actions.toggleMovieMode()
      );
    }
 
    this.explorer.grid.scheduler.pauseComputation(this.active);
    if (this.active) {
      this.startMovie();
    } else {
      this.stopMovie();
    }
  }
 
  startMovie() {
    this.explorer.grid.grid().style.display = 'none';
    this.explorer.movieContainer.style.display = 'block';
    this.createMovieCanvas();
    this.explorer.movieContainer.scrollIntoView({ behavior: 'smooth' });
    this.preRenderTimer = setTimeout(() => {
      document.body.className = '';
      this.preRenderFrames(() => {
        this.startMovieAnimation();
      });
    }, 20);
  }
 
  stopMovie() {
    this.explorer.grid.grid().style.display = 'block';
    this.explorer.movieContainer.style.display = 'none';
    this.stopMovieAnimation();
    this.removeMovieCanvas();
  }
 
  createMovieCanvas() {
    // Recalculate dimensions in case fullscreen state has changed
    this.explorer.config.initSizes();
 
    this.explorer.movieContainer.innerHTML = '<div>' +
      `<canvas width=${this.explorer.config.dimsWidth} ` +
      `height=${this.explorer.config.dimsHeight} ` +
      `style="width:${this.explorer.config.cssDimsWidth}px;` +
      `height:${this.explorer.config.cssDimsHeight}px"></canvas>` +
      `<span id="moviestatus"></span>` +
      `<a id="moviescale" class="zoomnum">${MSG.pre_rendering_movie}</a></div>`;
    this.movieCanvas = this.explorer.movieContainer.firstElementChild.firstElementChild;
    this.movieCtx = this.movieCanvas.getContext('2d');
    this.movieCtx.drawImage(this.explorer.grid.canvas(0), 0, 0);
  }
 
  removeMovieCanvas() {
    while (this.explorer.movieContainer.firstChild) {
      this.explorer.movieContainer.removeChild(this.explorer.movieContainer.firstChild);
    }
    this.movieCanvas = null;
    this.movieCtx = null;
  }
 
  preRenderFrames(after) {
    this.frameCanvases = [];
    this.isPreRendering = true;
    let queueOneFrame = (k, after) => {
      return () => {
        // Abort if movie mode was stopped
        if (!this.isPreRendering) {
          return;
        }
        let status = document.getElementById('moviescale');
        if (status) {
          const scale = this.explorer.grid.views[k].zoomFactor;
          status.textContent = `${MSG.pre_rendering_}${formatScale(scale)}`;
        }
        let canvasPrev = null;
        let canvasCurrent = null;
        let canvasNext = null;
 
        // Render with k-1 palette (unknown = transparent)
        if (k > 0) {
          canvasPrev = document.createElement('canvas');
          canvasPrev.width = this.explorer.config.dimsWidth;
          canvasPrev.height = this.explorer.config.dimsHeight;
          const ctxPrev = canvasPrev.getContext('2d');
          this.explorer.grid.views[k].draw(ctxPrev, this.explorer.grid.views[k - 1], 'transparent');
          if (this.explorer.config.unknowncolor != '#000') {
            ctxPrev.strokeStyle = 'yellow';
            ctxPrev.lineWidth = this.explorer.config.pixelRatio * this.explorer.config.zoomfactor;
            const w = this.explorer.config.dimsWidth;
            const h = this.explorer.config.dimsHeight;
            ctxPrev.strokeRect(0, 0, w, h);
          }
        }
 
        // Render with k palette (unknown = black)
        canvasCurrent = document.createElement('canvas');
        canvasCurrent.width = this.explorer.config.dimsWidth;
        canvasCurrent.height = this.explorer.config.dimsHeight;
        const ctxCurrent = canvasCurrent.getContext('2d');
        this.explorer.grid.views[k].draw(ctxCurrent, this.explorer.grid.views[k], 'black');
 
        // Render with k+1 palette (unknown = black)
        if (k < this.explorer.grid.views.length - 1) {
          canvasNext = document.createElement('canvas');
          canvasNext.width = this.explorer.config.dimsWidth;
          canvasNext.height = this.explorer.config.dimsHeight;
          const ctxNext = canvasNext.getContext('2d');
          this.explorer.grid.views[k].draw(ctxNext, this.explorer.grid.views[k + 1], 'black');
        }
        this.frameCanvases.push({ prev: canvasPrev, current: canvasCurrent, next: canvasNext });
        this.preRenderTimer = setTimeout(after, 1);
      };
    }
    for (let k = this.explorer.grid.views.length - 1; k >= 0; k--) {
      after = queueOneFrame(k, after);
    }
    this.preRenderTimer = setTimeout(after, 0);
  }
 
  startMovieAnimation() {
    let frame = 0;
    let framesteps = 400;  // 60 FPS: 400 frames = 6.67 seconds (50% faster than 10 sec)
    let endpause = 120;    // Scaled for 60 FPS (was 180 for 30 FPS = 6 sec)
    let endrecord = 60;    // Keep 1 second end recording
    const totalFrames = (this.explorer.grid.views.length - 1) * framesteps;
 
    const scaleElement = document.getElementById('moviescale');
    const statusElement = document.getElementById('moviestatus');
    scaleElement.removeAttribute('href');
    statusElement.textContent = 'Capturing frames...';
 
    this.capturedFrames = [];
    this.recordedBlob = null;
    this.isRecording = true;
 
    const animate = () => {
      // Abort if movie mode was stopped
      if (!this.isRecording) {
        return;
      }
 
      const kk = Math.min(frame, totalFrames) / framesteps;
      this.drawMovieFrame(kk);
 
      // Capture frame for encoding (only during recording period)
      if (frame <= totalFrames + endrecord) {
        try {
          // Create VideoFrame from canvas with duration for 60 FPS
          const videoFrame = new VideoFrame(this.movieCanvas, {
            timestamp: this.capturedFrames.length * 16667,  // 60 FPS in microseconds
            duration: 16667  // Frame duration: 1/60 second = 16667 microseconds
          });
          this.capturedFrames.push(videoFrame);
 
          // Update status
          if (this.capturedFrames.length % 60 === 0) {
            statusElement.textContent = `Captured ${this.capturedFrames.length} frames...`;
          }
        } catch (e) {
          console.error('Error capturing frame:', e);
          statusElement.textContent = `Error: ${e.message}`;
        }
      }
 
      frame++;
 
      // Check if we're done capturing
      if (frame > totalFrames + endrecord) {
        this.isRecording = false;
        statusElement.textContent = 'Encoding video...';
        // Start encoding after a brief delay to update UI
        setTimeout(() => this.encodeVideo(statusElement), 100);
      } else if (frame <= totalFrames + endpause) {
        // Continue animation
        this.animationTimer = requestAnimationFrame(() => animate());
      }
    };
    animate();
  }
 
  stopMovieAnimation() {
    this.isPreRendering = false;
    this.isRecording = false;
    if (this.preRenderTimer) {
      clearTimeout(this.preRenderTimer);
      this.preRenderTimer = null;
    }
    if (this.animationTimer) {
      cancelAnimationFrame(this.animationTimer);
      this.animationTimer = null;
    }
    // Clean up prerendered frame canvases
    if (this.frameCanvases) {
      this.frameCanvases = [];
    }
    // Clean up captured frames
    if (this.capturedFrames) {
      for (let frame of this.capturedFrames) {
        frame.close();
      }
      this.capturedFrames = [];
    }
    this.recordedBlob = null;
  }
 
  async encodeVideo(statusElement) {
    try {
      // Check WebCodecs support
      if (!window.VideoEncoder) {
        statusElement.textContent = 'WebCodecs not supported in this browser';
        console.error('WebCodecs API not available');
        return;
      }
 
      if (!window.Mp4Muxer) {
        statusElement.textContent = 'mp4-muxer library not loaded';
        console.error('mp4-muxer not available');
        return;
      }
 
      const width = this.movieCanvas.width;
      const height = this.movieCanvas.height;
 
      // Calculate appropriate H.264 level based on resolution
      // H.264 uses 16x16 macroblocks, so round up to multiples of 16
      let codedWidth = Math.ceil(width / 16) * 16;
      let codedHeight = Math.ceil(height / 16) * 16;
      let codedArea = codedWidth * codedHeight;
 
      // H.264 level limits (format: level hex code, max coded area, level name)
      const levels = [
        ['1E', 414720, '3.0'],      // 720x576
        ['1F', 921600, '3.1'],      // 1280x720
        ['2A', 2073600, '4.2'],     // 1920x1080
        ['34', 8912896, '5.2'],     // 4096x2304 (4K)
        ['3E', 35651584, '6.2']     // 7680x4320 (8K)
      ];
 
      const maxArea = levels[levels.length - 1][1]; // 8K limit
      let encodingWidth = width;
      let encodingHeight = height;
      let downscaled = false;
 
      // If exceeds maximum, downscale to fit
      if (codedArea > maxArea) {
        const scaleFactor = Math.sqrt(maxArea * 0.95 / codedArea); // 0.95 for safety margin
        encodingWidth = Math.floor(width * scaleFactor);
        encodingHeight = Math.floor(height * scaleFactor);
        codedWidth = Math.ceil(encodingWidth / 16) * 16;
        codedHeight = Math.ceil(encodingHeight / 16) * 16;
        codedArea = codedWidth * codedHeight;
        downscaled = true;
        const msg = `Resolution ${width}x${height} exceeds H.264 limit, ` +
                    `downscaling to ${encodingWidth}x${encodingHeight}`;
        console.warn(msg);
        statusElement.textContent = msg;
      }
 
      // Select minimum level that supports this resolution
      let levelCode = '3E'; // Default to 6.2 (highest)
      let levelName = '6.2';
      for (const [code, levelMaxArea, name] of levels) {
        if (codedArea <= levelMaxArea) {
          levelCode = code;
          levelName = name;
          break;
        }
      }
 
      const codecString = `avc1.42E0${levelCode}`;
      console.log(`Video resolution: ${encodingWidth}x${encodingHeight}, ` +
                  `coded: ${codedWidth}x${codedHeight} (${codedArea} pixels), ` +
                  `using H.264 level ${levelName}`);
 
      // Initialize MP4 muxer
      this.muxer = new window.Mp4Muxer.Muxer({
        target: new window.Mp4Muxer.ArrayBufferTarget(),
        video: {
          codec: 'avc',
          width: encodingWidth,
          height: encodingHeight
        },
        fastStart: 'in-memory'
      });
 
      let encodedCount = 0;
      const totalFrames = this.capturedFrames.length;
 
      // Initialize video encoder
      this.videoEncoder = new VideoEncoder({
        output: (chunk, metadata) => {
          // Ensure metadata has decoderConfig with colorSpace for Safari compatibility
          if (metadata?.decoderConfig && !metadata.decoderConfig.colorSpace) {
            metadata.decoderConfig.colorSpace = {
              primaries: 'bt709',
              transfer: 'bt709',
              matrix: 'bt709',
              fullRange: false
            };
          }
          this.muxer.addVideoChunk(chunk, metadata);
          encodedCount++;
          if (encodedCount % 60 === 0) {
            const percent = Math.round(100 * encodedCount / totalFrames);
            statusElement.textContent = `Encoding: ${percent}%`;
          }
        },
        error: (e) => {
          console.error('Encoding error:', e);
          statusElement.textContent = `Encoding error: ${e.message}`;
        }
      });
 
      // Configure encoder for H.264 with dynamically calculated level
      this.videoEncoder.configure({
        codec: codecString,  // H.264 baseline profile with appropriate level
        width: encodingWidth,
        height: encodingHeight,
        bitrate: 30_000_000,  // 30 Mbps for high quality
        framerate: 60,
        // Provide colorSpace to ensure Safari includes it in metadata
        colorSpace: {
          primaries: 'bt709',
          transfer: 'bt709',
          matrix: 'bt709',
          fullRange: false
        }
      });
 
      // Create a temporary canvas for downscaling if needed
      let tempCanvas, tempCtx;
      if (downscaled) {
        tempCanvas = document.createElement('canvas');
        tempCanvas.width = encodingWidth;
        tempCanvas.height = encodingHeight;
        tempCtx = tempCanvas.getContext('2d');
      }
 
      // Encode all frames
      for (let i = 0; i < this.capturedFrames.length; i++) {
        const frame = this.capturedFrames[i];
        const keyFrame = i % 200 === 0;  // Keyframe every 3.33 seconds (200 frames at 60 FPS)
 
        if (downscaled) {
          // Scale frame to tempCanvas, then create new VideoFrame
          tempCtx.drawImage(frame, 0, 0, encodingWidth, encodingHeight);
          const scaledFrame = new VideoFrame(tempCanvas, {
            timestamp: frame.timestamp,
            duration: frame.duration
          });
          this.videoEncoder.encode(scaledFrame, { keyFrame });
          scaledFrame.close();
        } else {
          this.videoEncoder.encode(frame, { keyFrame });
        }
 
        frame.close();  // Release VideoFrame resources
      }
 
      // Wait for encoding to complete
      await this.videoEncoder.flush();
      this.videoEncoder.close();
 
      // Finalize muxer and get the video file
      this.muxer.finalize();
      const buffer = this.muxer.target.buffer;
      this.recordedBlob = new Blob([buffer], { type: 'video/mp4' });
 
      // Clean up
      this.capturedFrames = [];
      this.videoEncoder = null;
      this.muxer = null;
 
      // Update download link
      statusElement.textContent = '';  // Clear status
      this.updateDownloadLink();
 
      // Start looping animation
      this.startLoopAnimation();
 
    } catch (e) {
      console.error('Error encoding video:', e);
      statusElement.textContent = `Encoding failed: ${e.message}`;
    }
  }
 
  startLoopAnimation() {
    const framesteps = 400;  // Same as recording
    const totalFrames = (this.explorer.grid.views.length - 1) * framesteps;
    const pauseFrames = 120;  // 2 second pause at 60 FPS
    let frame = 0;
 
    const animate = () => {
      // During main animation
      if (frame <= totalFrames) {
        const kk = Math.min(frame, totalFrames) / framesteps;
        this.drawMovieFrame(kk);
      }
      // During pause at end - keep showing last frame
 
      frame++;
 
      // Loop back to start after pause
      if (frame > totalFrames + pauseFrames) {
        frame = 0;
      }
 
      // Continue animation indefinitely
      this.animationTimer = requestAnimationFrame(() => animate());
    };
 
    animate();
  }
 
  updateDownloadLink() {
    const scaleElement = document.getElementById('moviescale');
    scaleElement.textContent = 'Download mp4';
    scaleElement.href = URL.createObjectURL(this.recordedBlob);
    const k = this.explorer.grid.views.length - 1;
    const view = this.explorer.grid.views[k];
    // Use QD values for full precision at deep zoom
    const coords = formatcomplex(k, view.re, view.im);
    scaleElement.download = `mandelbrot${coords}-${view.it}.mp4`;
  }
 
  drawMovieFrame(kk) {
    if (this.movieCtx == null) { return; }
    const k = Math.floor(kk);
    const t = kk - k;
    const sourceView = this.explorer.grid.views[k];
    const targetView = k+1 < this.explorer.grid.views.length ?
                        this.explorer.grid.views[k+1] : sourceView;
    const sourceSize = sourceView.size;
    const targetSize = targetView.size;
    const zoomRatio = targetSize / sourceSize;
 
    // Use zoom ratio for exponential interpolation
    const mulT = Math.pow(zoomRatio, t);
    const expT = (zoomRatio == 1.0 ? t : (mulT - 1) / (zoomRatio - 1));
    const colorT = expT * expT;
    const interpolatedSize = sourceSize * mulT;
 
    // Use QD-precision spline interpolation for center coordinates at deep zoom
    const sourceCenter = [sourceView.re, sourceView.im];
    const targetCenter = [targetView.re, targetView.im];
 
    const p0 = k > 0 ? [
        this.explorer.grid.views[k-1].re,
        this.explorer.grid.views[k-1].im] : sourceCenter;
    const p1 = sourceCenter;
    const p2 = targetCenter
    const p3 = k+2 < this.explorer.grid.views.length ? [
        this.explorer.grid.views[k+2].re,
        this.explorer.grid.views[k+2].im] : targetCenter;
    const interpolatedCenter = catmullRomSplineQD(p0, p1, p2, p3, t);
 
    // Clear the movie canvas with black (so unfinished pixels appear black)
    this.movieCtx.fillStyle = 'black';
    this.movieCtx.fillRect(0, 0, this.explorer.config.dimsWidth,
                            this.explorer.config.dimsHeight);
 
    // Draw the current frame
    const scale = sourceSize / interpolatedSize;
    const offsetX = qdToNumber(toQDScale(toQDSub(interpolatedCenter[0], sourceCenter[0]),
                          this.explorer.config.dimsWidth / sourceSize));
    const sourceHeight = sourceSize / this.explorer.config.aspectRatio;
    const offsetY = qdToNumber(toQDScale(toQDSub(sourceCenter[1], interpolatedCenter[1]),
                          this.explorer.config.dimsHeight / sourceHeight));
    this.movieCtx.save();
    this.movieCtx.imageSmoothingEnabled = true;
    this.movieCtx.imageSmoothingQuality = 'high';
    const centerX = this.explorer.config.dimsWidth / 2;
    const centerY = this.explorer.config.dimsHeight / 2;
    this.movieCtx.translate(centerX, centerY);
    this.movieCtx.scale(scale, scale);
    this.movieCtx.translate(-this.explorer.config.dimsWidth / 2 - offsetX,
                            -this.explorer.config.dimsHeight / 2 - offsetY);
    this.movieCtx.globalAlpha = 1;
    // Use pre-rendered current canvas with black unknown pixels
    this.movieCtx.drawImage(this.frameCanvases[k].current, 0, 0);
 
    // Blend the color palette of the next frame (unknown = black)
    if (this.frameCanvases[k].next) {
      this.movieCtx.globalAlpha = colorT;
      this.movieCtx.drawImage(this.frameCanvases[k].next, 0, 0);
    }
    this.movieCtx.restore();
 
    // Draw the next frame
    if (k < this.explorer.grid.views.length - 1) {
      const targetScale = targetSize / interpolatedSize;
      const targetOffsetX = qdToNumber(toQDScale(
        toQDSub(interpolatedCenter[0], targetCenter[0]),
        this.explorer.config.dimsWidth / targetSize));
      const targetHeight = targetSize / this.explorer.config.aspectRatio;
      const targetOffsetY = qdToNumber(toQDScale(
        toQDSub(targetCenter[1], interpolatedCenter[1]),
        this.explorer.config.dimsHeight / targetHeight));
      this.movieCtx.save();
      this.movieCtx.imageSmoothingEnabled = true;
      this.movieCtx.imageSmoothingQuality = 'high';
      const targetCenterX = this.explorer.config.dimsWidth / 2;
      const targetCenterY = this.explorer.config.dimsHeight / 2;
      this.movieCtx.translate(targetCenterX, targetCenterY);
      this.movieCtx.scale(targetScale, targetScale);
      this.movieCtx.translate(-this.explorer.config.dimsWidth / 2 - targetOffsetX,
                              -this.explorer.config.dimsHeight / 2 - targetOffsetY);
      this.movieCtx.globalAlpha = 1;
      // Draw prev palette version (unknown = transparent, shows lower res through)
      this.movieCtx.drawImage(this.frameCanvases[k + 1].prev, 0, 0);
      this.movieCtx.globalAlpha = colorT;
      // Draw current palette version (unknown = black)
      this.movieCtx.drawImage(this.frameCanvases[k + 1].current, 0, 0);
      this.movieCtx.restore();
    }
 
    // Update scale text
    if (!this.recordedBlob) {
      const currentScale = Math.pow(this.explorer.config.zoomfactor, kk);
      document.getElementById('moviescale').textContent = formatScale(currentScale);
    }
  }
}
 
// Distributes computation work across web workers and balances load.
class Scheduler {
  constructor(grid) {
    this.grid = grid;
    this.workers = [];
    this.boardEfforts = new Map();
    this.boardIds = new Map();  // Track board ID at each index k
    this.assignments = {};
    this.lastBalanceTime = 0;
    this.lastReportTime = 0;
    this.balanceInterval = 5000; // Move jobs to load-balance every 5 seconds
    this.reportInterval = 60000; // Report no more than once every 1 minute
    this.workerCount = Math.max(1, Math.ceil(navigator.hardwareConcurrency * 0.75) || 1);
    this.webGPUWarningShown = false;
  }
 
  addWorker() {
    // Show WebGPU warning once when first worker is created
    if (this.workers.length === 0 && this.grid.config.enableGPU &&
        typeof navigator.gpu === 'undefined' && !this.webGPUWarningShown) {
      console.log('WebGPU not available in this browser, falling back to CPU boards');
      this.webGPUWarningShown = true;
    }
 
    try {
      const workerNum = this.workers.length;
      let worker;
 
      // Use MockWorker if available (debug mode with 'w' flag)
      if (typeof MockWorker !== 'undefined') {
        worker = new MockWorker(workerNum);
        console.log(`Created MockWorker ${workerNum} (main thread)`);
      } else {
        // Create real web worker
        const workerCode = this.assembleWorkerCode();
        const workerBlob = new Blob([workerCode], { type: 'application/javascript' });
        const workerUrl = URL.createObjectURL(workerBlob);
        worker = new Worker(workerUrl, { name: `Worker ${workerNum}` });
        URL.revokeObjectURL(workerUrl);
      }
 
      worker.onmessage = this.handleWorkerMessage.bind(this);
      this.workers.push(worker);
      window[`worker${workerNum}`] = worker;
 
      // Initialize new worker with current hidden boards state
      worker.postMessage({
        type: 'setHiddenBoards',
        data: { hiddenBoards: this.grid.getHiddenViews() }
      });
 
      return true;
    } catch (e) {
      console.log('Failed to start webworker', e);
      return false;
    }
  }
 
  assembleWorkerCode() {
    const workerCode = document.getElementById('workerCode');
    const mathCode = document.getElementById('mathCode');
    const workerStart = document.getElementById('workerStart');
    return '// Linefeeds to align line numbers with HTML.\n' +
           ''.padStart(lastScriptLineNumber, '\n') +
           '// <script id="workerCode">' +
           workerCode.textContent +
           '// <\/script>\n' +
           '// <script id="mathCode">' +
           mathCode.textContent +
           '// <\/script>\n' +
           '// <script id="workerStart">' +
           workerStart.textContent +
           '// <\/script>\n';
  }
 
  assignBoardToWorker(k, size, reQD, imQD, config, id) {
    let [workerNumber, minLoad] = this.findLeastLoadedWorker();
    if (workerNumber == -1 || (minLoad > 0 && this.workers.length < this.workerCount)) {
      if (this.addWorker()) {
        workerNumber = this.workers.length - 1;
      }
    }
    const worker = this.workers[workerNumber];
    const estimatedWork = config.dimsArea * ((size / config.dimsWidth < 1e-15) ? 7 : 1);
    this.boardEfforts.set(k, estimatedWork);
    this.boardIds.set(k, id);  // Track which board ID is at this index
    this.assignments[k] = workerNumber;
 
    // Ensure QD coordinates are properly formatted
    reQD = toQD(reQD);
    imQD = toQD(imQD);
 
    if (!isFinite(size)) {
      console.warn(`Board ${k}: non-finite size`, size);
    }
    worker.postMessage({
      type: 'addBoard',
      data: {
        k,
        size,
        reQD,
        imQD,
        config: {
          dimsArea: config.dimsArea,
          dimsWidth: config.dimsWidth,
          dimsHeight: config.dimsHeight,
          aspectRatio: config.aspectRatio,
          exponent: config.exponent,
          enableGPU: config.enableGPU,
          forceBoard: config.forceBoard,
          debug: config.debug
        },
        id,
        workerNumber
      }
    });
  }
 
  // Remove board at index k. If expectedId is provided, only remove if the
  // current board at k has that ID. This prevents removing a newer board
  // when an old view tries to clean up.
  removeBoardFromWorker(k, expectedId = null) {
    // If expectedId is provided, verify it matches before removing
    if (expectedId !== null && this.boardIds.get(k) !== expectedId) {
      // Board at this index has a different ID - don't remove it
      return;
    }
 
    this.boardEfforts.set(k, 0);
    this.boardIds.delete(k);
    this.workers.forEach(worker => {
      worker.postMessage({
        type: 'removeBoard',
        data: { k }
      });
    });
  }
 
  setFocusedBoard(k) {
    this.workers.forEach(worker => {
      worker.postMessage({
        type: 'setFocusedBoard',
        data: { k }
      });
    });
  }
 
  setHiddenBoards(hiddenBoards) {
    this.workers.forEach(worker => {
      worker.postMessage({
        type: 'setHiddenBoards',
        data: { hiddenBoards }
      });
    });
  }
 
  // Debug method: check for orphan boards (boards without matching views).
  // Call this after stableViews cleanup to detect board management bugs.
  checkForOrphanBoards(views) {
    const activeViewIds = new Set();
    for (const view of views) {
      if (view && view.id !== undefined) {
        activeViewIds.add(view.id);
      }
    }
 
    let orphanCount = 0;
    for (const [k, boardId] of this.boardIds.entries()) {
      if (!activeViewIds.has(boardId)) {
        console.warn(`Orphan board at k=${k} with id=${boardId} - no matching active view`);
        orphanCount++;
      }
    }
 
    if (orphanCount > 0) {
      console.warn(`Found ${orphanCount} orphan board(s). ` +
        `Active views: ${views.length}, tracked boards: ${this.boardIds.size}`);
    }
  }
 
  pauseComputation(pause) {
    this.workers.forEach(worker => worker.postMessage({ type: 'pause', data: { pause } }));
  }
 
  handleWorkerMessage(e) {
    const { type, data } = e.data;
    const workerIndex = this.workers.indexOf(e.target);
 
    switch (type) {
      case 'log':
        console.log(`Worker ${workerIndex}: ${data}`);
        break;
      case 'boardCreated':
        // GPU boards are now transferable via serialization, no special tracking needed
        break;
      case 'iterations':
        this.grid.updateViewFromWorkerResult(data.k, data, workerIndex);
        // fallthrough
      case 'update':
        if ('boardEffort' in data) { this.boardEfforts.set(data.k, data.boardEffort); }
        this.checkAndBalance(); // Check if we need to balance the load
        explorer.checkAllViewsComplete();
        break;
      case 'downloadTransfer':
        this.handleDownloadTransfer(data, workerIndex);
        break;
    }
  }
 
  checkAndBalance() {
    // Only apply load balancing periodically.
    const now = Date.now();
    if (now - this.lastBalanceTime < this.balanceInterval) { return; }
    this.lastBalanceTime = now;
 
    const workerLoads = this.workers.map((_, index) => this.getWorkerLoad(index));
    const lowEffort = Math.min(...workerLoads);
    const highEffort = Math.max(...Array.from(this.boardEfforts.values()));
 
    if (lowEffort * 2 < highEffort) {
      const transferCandidates = [];
      const sortedLoad = workerLoads
        .map((load, index) => [index, load])
        .sort((a, b) => b[1] - a[1]);
      for (let [workerIndex, load] of sortedLoad) {
        if (load > 2 * lowEffort) {
          const workerBoards = this.getWorkerBoards(workerIndex);
          if (workerBoards.length > 1) {
            // All boards are transferable now (GPU boards support serialization)
            const sortedBoards = workerBoards.sort(
                (a, b) => this.boardEfforts.get(b) + b/1000 - this.boardEfforts.get(a) - a/1000);
            if (now - this.lastReportTime > this.reportInterval) {
              console.log(this.report());
              this.lastReportTime = now;
            }
            transferCandidates.push(sortedBoards[1]);
            break;
          }
        }
      }
      if (transferCandidates.length > 0) {
        this.requestTransfers(transferCandidates);
      }
    }
  }
 
  report() {
    if (!this.workers.length) { return 'no workers'; }
    const workerLoads = this.workers.map(() => 0);
    const workerBoards = this.workers.map(() => []);
    for (const [boardK, workerIndex] of Object.entries(this.assignments)) {
      const effort = this.boardEfforts.get(parseInt(boardK));
      if (effort) {
        workerBoards[workerIndex].push([parseInt(boardK), effort]);
        workerLoads[workerIndex] += effort;
      }
    }
    let result = '';
    for (let i = 0; i < workerLoads.length; i++) {
      result += `worker ${i} (load ${workerLoads[i]}): `;
      workerBoards[i].sort((a, b) => b[1] + b[0]/1000 - a[1] - a[0]/1000);
      for (let j = 0; j < workerBoards[i].length; j++) {
        result += `${workerBoards[i][j][0]}->${workerBoards[i][j][1]} `;
      }
      result += '\n';
    }
    return result;
  }
 
  findLeastLoadedWorker() {
    if (!this.workers.length) { return [-1, 0]; }
    const workerLoads = new Array(this.workers.length).fill(0);
    for (const [boardK, workerIndex] of Object.entries(this.assignments)) {
      workerLoads[workerIndex] += this.boardEfforts.get(parseInt(boardK)) || 0;
    }
    const minLoad = Math.min(...workerLoads);
    return [workerLoads.indexOf(minLoad), minLoad];
  }
 
  getWorkerLoad(workerIndex) {
    return Object.entries(this.assignments)
      .filter(([_, assignedWorker]) => assignedWorker === workerIndex)
      .reduce((sum, [k, _]) => sum + (this.boardEfforts.get(parseInt(k)) || 0), 0);
  }
 
  getWorkerBoards(workerIndex) {
    return Object.entries(this.assignments)
      .filter(([k, assignedWorker]) =>
           this.boardEfforts.get(parseInt(k)) > 0 && assignedWorker === workerIndex)
      .map(([k, _]) => parseInt(k));
  }
 
  requestTransfers(boardKeys) {
    // Group transfer requests by worker
    for (const [workerIndex, worker] of this.workers.entries()) {
      const workerBoards = boardKeys.filter(k => this.assignments[k] === workerIndex);
      if (workerBoards.length > 0) {
        worker.postMessage({
          type: 'requestTransfer',
          data: { boardKeys: workerBoards }
        });
      }
    }
  }
 
  handleDownloadTransfer(data, sourceWorkerIndex) {
    const { transferredBoards } = data;
    for (const boardData of transferredBoards) {
      // Remove the board from its original worker
      delete this.assignments[boardData.k];
 
      // Find the least loaded worker and assign the board to it
      const [targetWorkerIndex, minLoad] = this.findLeastLoadedWorker();
      this.uploadTransferredBoard(boardData, targetWorkerIndex);
      console.log(`transferred ${boardData.type} ${boardData.k} ` +
                  `from worker ${sourceWorkerIndex} ` +
                  `to ${targetWorkerIndex} (load ${minLoad})`);
    }
  }
 
  uploadTransferredBoard(boardData, targetWorkerIndex) {
    // Send the board to its new worker
    this.workers[targetWorkerIndex].postMessage({
      type: 'uploadTransfer',
      data: { boardData }
    });
 
    // Update assignments and worker loads
    this.assignments[boardData.k] = targetWorkerIndex;
  }
}
 
// Computes and displays iteration orbits when hovering over points.
class OrbitComputer {
  constructor(explorer) {
    this.explorer = explorer;
    this.orbitinterval = null;
    this.orbittimeout = null;
  }
 
  updateOrbit(k, j, target) {
    this.stopOrbitProcess();
    const orb = [];
 
    const updateorbit = () => {
      const [neworb, cyc, ongoing, title] = this.calculateOrbit(k, j, orb);
      this.displayOrbit(k, neworb, cyc, target, title, orb.length > 0);
      orb.push(...neworb);
      if (!ongoing) { this.stopOrbitInterval(); }
      return ongoing;
    };
 
    if (updateorbit()) {
      this.orbitinterval = setInterval(updateorbit, 53);
    }
  }
 
  stopOrbitInterval() {
    if (this.orbitinterval) {
      clearInterval(this.orbitinterval);
      this.orbitinterval = null;
    }
  }
 
  stopOrbitProcess() {
    this.stopOrbitInterval();
    if (this.orbittimeout) {
      clearTimeout(this.orbittimeout);
      this.orbittimeout = null;
    }
  }
 
  calculateOrbit(k, j, oldOrb) {
    let cyc = [];
    let orb = [];
    let ongoing = false;
    let title = '';
    let view = this.explorer.grid.views[k];
 
    if (view && j >= 0 && j < this.explorer.config.dimsArea) {
      let c = view.currentc(j);  // Returns QD complex format (8 elements)
      let z = view.currentz(j);  // Returns QD complex format (8 elements)
 
      // Calculate a further orbit beyond the old orbit.
      // Orbits now use 8 elements per point (QD complex format)
      let finished = Math.max(view.currentp(j) || 0, Math.abs(view.nn[j] || 0));
      let whole = Math.min(finished || Math.max(view.it, 8));
      let more = Math.min(whole - oldOrb.length / 8, 53);
      if (oldOrb.length) {
        let s = oldOrb.slice(oldOrb.length - 8);
        orb = this.suborbit(s, c, more + 1);
        orb.splice(0, 8);
      } else {
        orb = this.suborbit(c, c, more);
      }
      if (!finished || (orb.length + oldOrb.length) / 8 < finished) {
        ongoing = true;
      }
      // Calculate a cycle and any messages
      // c is QD complex format: [r0, r1, r2, r3, i0, i1, i2, i3]
      // Use full QD precision (4 components each) to avoid discretization at deep zoom
      title = 'c=' +
        formatcomplex(k, [c[0], c[1], c[2], c[3]], [c[4], c[5], c[6], c[7]])
        .replaceAll('-', '\u2212');
      if (view.nn[j]) {
        if (view.nn[j] > 0) {
          title += MSG.diverges_in_ + view.nn[j];
        } else {
          let period = fibonacciPeriod(view.currentp(j));
          if (period == 1) {
            title += MSG.converges_after_ + formatLargeInt(view.currentp(j));
          } else {
            const iters = formatLargeInt(view.currentp(j));
            const periodStr = formatLargeInt(period);
            title += MSG.after_ + iters + MSG.period_ + periodStr;
          }
          let clen = fibonacciPeriod(view.currentp(j));
          // z is already in QD complex format (8 elements)
          cyc = z ? this.suborbit(z, c, clen) : [];
        }
      } else {
        ongoing = true;
      }
    }
    return [orb, cyc, ongoing, title];
  }
 
  displayOrbit(k, orb, cyc, target, title, preserve) {
    // Don't set title if the zoom number's custom tooltip is showing
    const zoomnum = target.querySelector('.zoomnum');
    const isZoomnumHovered = zoomnum && zoomnum.matches(':hover');
    if (!isZoomnumHovered) {
      target.setAttribute('title', title);
    }
    if (!preserve) {
      this.explorer.grid.clearseq(k);
    }
    this.showseq(k, orb, 'yellow');
    this.showseq(k, cyc, 'red');
 
    const orbitonallboards = () => {
      for (let i = 0; i < this.explorer.grid.views.length; i++) {
        if (!this.explorer.grid.hiddencanvas(i) && i != k) {
          if (!preserve) {
            this.explorer.grid.clearseq(i);
          }
          this.showseq(i, orb, 'yellow');
          this.showseq(i, cyc, 'red');
        }
      }
    };
    this.orbittimeout = setTimeout(orbitonallboards, 1);
  }
 
  suborbit(z, c, len) {
    // z and c are in QD complex format: [r0, r1, r2, r3, i0, i1, i2, i3]
    let r = [z[0], z[1], z[2], z[3]];
    let j = [z[4], z[5], z[6], z[7]];
    const cr = [c[0], c[1], c[2], c[3]];
    const cj = [c[4], c[5], c[6], c[7]];
 
    // Result stores 8 elements per point (QD complex format)
    let result = [r[0], r[1], r[2], r[3], j[0], j[1], j[2], j[3]];
    while (result.length < len * 8) {
      let j2 = toQDSquare(j);
      let ja = toQDMul(toQDDouble(r), j);
      let r2 = toQDSquare(r);
      let ra = toQDSub(r2, j2);
      for (let ord = 2; ord < this.explorer.config.exponent; ord++) {
        let rt = toQDSub(toQDMul(r, ra), toQDMul(j, ja));
        ja = toQDAdd(toQDMul(r, ja), toQDMul(j, ra));
        ra = rt;
      }
      r = toQDAdd(ra, cr);
      j = toQDAdd(ja, cj);
      result.push(r[0], r[1], r[2], r[3], j[0], j[1], j[2], j[3]);
    }
    return result;
  }
 
  showseq(k, seq, color) {
    if (k >= this.explorer.grid.views.length) { return; }
    const overlay = this.explorer.grid.overlay(k);
    if (!overlay) { return; }
    let ctx = overlay.getContext('2d');
    ctx.fillStyle = color;
    // Use QD values for full precision
    const view = this.explorer.grid.views[k];
    const s = view.size;
    const crQD = view.re;
    const cjQD = view.im;
    // seq is in QD complex format: 8 elements per point
    for (let i = 0; i < seq.length; i += 8) {
      let r = [seq[i], seq[i+1], seq[i+2], seq[i+3]];
      let j = [seq[i+4], seq[i+5], seq[i+6], seq[i+7]];
      let x = (qdToNumber(toQDSub(r, crQD)) / s + 0.5) * this.explorer.config.dimsWidth;
      const sHeight = s / this.explorer.config.aspectRatio;
      let y = (qdToNumber(toQDSub(cjQD, j)) / sHeight + 0.5) * this.explorer.config.dimsHeight;
      const w = this.explorer.config.dimsWidth;
      const h = this.explorer.config.dimsHeight;
      if (x >= 0 && y >= 0 && x < w && y < h) {
        ctx.beginPath();
        ctx.arc(x, y, 1 * this.explorer.config.pixelRatio, 0, 2 * Math.PI, false);
        ctx.fill();
      }
    }
  }
}
 
// Coordinates progressive canvas redraws as computation results arrive.
class RedrawProcess {
  constructor(explorer) {
    this.grid = explorer.grid;
    this.timer = null;
  }
  start() {
    this.stop();  // Ensure any existing cycle is stopped
    // Get current views and sort order (visible views first, then by index descending)
    this.canvasOrder = this.grid.views.map((b, i) => i).sort(
       (a, b) => (this.grid.hiddencanvas(a) * 1 - this.grid.hiddencanvas(b) * 1)
                 * this.grid.views.length + (b - a));
    this.drawNext();
  }
  stop() {
    if (this.timer) {
      clearTimeout(this.timer);
      this.timer = null;
    }
  }
  drawNext() {
    if (this.canvasOrder.length) {
      const index = this.canvasOrder.shift();
      const view = this.grid.views[index];  // Always get current view from grid
      const canvas = this.grid.canvas(index);
      if (canvas && view) {
        const ctx = canvas.getContext('2d');
        view.draw(ctx);
      }
      this.timer = setTimeout(() => this.drawNext(), 0);
    } else {
      this.stop();
    }
  }
}
 
// Utility functions
 
// Check if any center points from oldCenters are missing in newCenters.
// Used to determine when to push to browser history (for back button support).
function centersWereLost(oldCenters, newCenters) {
  if (!oldCenters) return false;
  if (oldCenters === newCenters) return false;
 
  // Parse centers into arrays of coordinate strings
  const oldParts = oldCenters.split(',').filter(s => s.length > 0);
  const newParts = newCenters.split(',').filter(s => s.length > 0);
 
  // If old had more centers, some were lost
  if (oldParts.length > newParts.length) return true;
 
  // Check if all old centers are present in new (in order, as prefix)
  // This handles the case of zooming deeper (adding centers) vs clicking elsewhere
  for (let i = 0; i < oldParts.length; i++) {
    if (i >= newParts.length || oldParts[i] !== newParts[i]) {
      return true;
    }
  }
 
  return false;
}
 
// Format zoom level for URL (z parameter) - compact scientific notation
// Strips trailing zeros: 5.00e+3 → 5e3, 1.50e+10 → 1.5e10
function formatZoom(z) {
  let s = z.toExponential(2);
  // Strip trailing zeros from mantissa and unnecessary + in exponent
  return s.replace(/\.?0+e/, 'e').replace('e+', 'e').replace('e0$', '');
}
 
// Format scale for human-readable display (e.g., "2.5x", "100x", "5.25e+25")
function formatScale(scale) {
  if (scale < 10) {
    return +scale.toFixed(1) + 'x';
  } else if (scale < 100000) {
    return +scale.toFixed(0) + 'x';
  } else {
    return scale.toExponential(2);
  }
}
 
function toSimpleFraction(decimal, maxDenominator = 100) {
  // Use continued fractions to find the best rational approximation
  // Returns [numerator, denominator]
  let bestNum = 1, bestDen = 1;
  let bestError = Math.abs(decimal - 1);
 
  // Continued fractions algorithm
  let h1 = 1, h2 = 0;
  let k1 = 0, k2 = 1;
  let x = decimal;
 
  for (let i = 0; i < 20; i++) {  // Limit iterations
    const a = Math.floor(x);
    const h = a * h1 + h2;
    const k = a * k1 + k2;
 
    if (k > maxDenominator) break;
 
    const error = Math.abs(decimal - h/k);
    if (error < bestError) {
      bestNum = h;
      bestDen = k;
      bestError = error;
    }
 
    if (error < 1e-10) break;  // Close enough
 
    x = 1 / (x - a);
    h2 = h1; h1 = h;
    k2 = k1; k1 = k;
  }
 
  return [bestNum, bestDen];
}
 
function formatcomplex(k, re, im) {
  const view = explorer.grid.views[k];
  const pix = view.pixelSize;
  let digits = Math.max(0, -Math.floor(Math.log10(pix)));
 
  // Use BigInt-based conversion for exact decimal output
  const reQD = toQD(re);
  const imQD = toQD(im);
 
  let rd = qdToDecimalString(reQD, digits);
  let id = qdToDecimalString(imQD, digits);
 
  let rs = reQD[0] < 0.0 ? '-' : '+';
  let is = imQD[0] < 0.0 ? '-' : '+';
 
  // Omit zero terms from complex number
  return ((rs + rd + is + id + 'i').
      replace(/\+0i$/, '').replace(/^\+0(?=[-+])/, '').replace(/^\+/, ''));
}
 
function formatLargeInt(i) {
  // Put a comma or period between thousands.
  return Intl.NumberFormat().format(i);
}
 
function hclColor(h, c, l) {
  // Normalize hue to be between 0 and 360 degrees
  // Chroma and Luminance should be between 0 and 100.
  h = h % 360;
  if (h < 0) h += 360;
  c = Math.min(Math.max(c, 0), 100);
  l = Math.min(Math.max(l, 0), 100);
 
  // Convert to radians
  const hRad = h * Math.PI / 180;
 
  // Constants for conversion
  const u = Math.cos(hRad) * c;
  const v = Math.sin(hRad) * c;
 
  // Direct conversion from HCL to RGB
  let r = l + 0.09551990792716 * u + 0.05406649830715 * v;
  let g = l - 0.03947567534454 * u - 0.01829165033556 * v;
  let b = l - 0.19638676772419 * u - 0.45388640918783 * v;
 
  // Apply gamma correction and convert to eight-bit value
  [r, g, b] = [r, g, b].map((x) => {
    return intcolor(gammaCorrect(x / 100));
  });
  return `rgb(${r},${g},${b})`
}
 
function gammaCorrect(channel) {
  if (channel <= 0.0031308) {
    return 12.92 * channel;
  } else {
    return 1.055 * Math.pow(channel, 1/2.4) - 0.055;
  }
}
 
// Converts normalized [0,1] float to 8-bit color string.
function intcolor(n) {
  if (n <= 0) { return "0"; }
  if (n >= 1) { return "255"; }
  return (n * 255).toString(10);
}
 
// Lineweaver-Burk estimate for how many pixels will be black
function estimateLimit(data) {
  // Transform data: x becomes 1/x
  const transformedData = data.map(point => ({
    x: 1 / (point.x ** 0.75),
    y: point.y,
    weight: point.weight || 1  // Default weight to 1 if not provided
  }));
 
  // Calculate weighted means
  let sumWeights = 0;
  let sumWeightedX = 0;
  let sumWeightedY = 0;
 
  for (let point of transformedData) {
    sumWeights += point.weight;
    sumWeightedX += point.weight * point.x;
    sumWeightedY += point.weight * point.y;
  }
 
  const meanX = sumWeightedX / sumWeights;
  const meanY = sumWeightedY / sumWeights;
 
  // Calculate slope and intercept
  let numerator = 0;
  let denominator = 0;
  for (let point of transformedData) {
    numerator += point.weight * (point.x - meanX) * (point.y - meanY);
    denominator += point.weight * Math.pow(point.x - meanX, 2);
  }
  const slope = numerator / denominator;
  const intercept = meanY - slope * meanX;
 
  // The intercept is our estimate of the limit as 1/x approaches 0 (i.e., as x approaches infinity)
  return intercept;
}
 
// Under Puppeteer, use 0 so worker blob has no line padding (for coverage alignment).
var lastScriptLineNumber = navigator.webdriver ? 0 :
  new Error().stack.match(/:(\d+)/)[1] | 0;