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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 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x | import { getCustomCrop } from './customCrops'
import type { MapData, MapRegion } from './types'
/**
* Convert a 2-letter country code to a flag emoji
* Uses Unicode Regional Indicator Symbols
* @param countryCode - ISO 3166-1 alpha-2 country code (e.g., "us", "fr")
* @returns Flag emoji string (e.g., "🇺🇸", "🇫🇷") or empty string if invalid
*/
export function getCountryFlagEmoji(countryCode: string): string {
if (!countryCode || countryCode.length !== 2) return ''
const code = countryCode.toUpperCase()
// Regional Indicator Symbols start at U+1F1E6 (A) and go to U+1F1FF (Z)
// Formula: 0x1F1E6 + (letterIndex) where A=0, B=1, etc.
const firstChar = code.charCodeAt(0)
const secondChar = code.charCodeAt(1)
// Validate both chars are A-Z
if (firstChar < 65 || firstChar > 90 || secondChar < 65 || secondChar > 90) {
return ''
}
const firstSymbol = String.fromCodePoint(0x1f1e6 + (firstChar - 65))
const secondSymbol = String.fromCodePoint(0x1f1e6 + (secondChar - 65))
return firstSymbol + secondSymbol
}
/**
* Type definition for @svg-maps packages
*/
interface SvgMapData {
label: string
viewBox: string
locations: Array<{ id: string; name: string; path: string }>
}
/**
* Cached map data - will be populated either via static imports (browser)
* or dynamic imports (Node.js server)
*/
let worldMapSource: SvgMapData | null = null
let usaMapSource: SvgMapData | null = null
/**
* Load map sources dynamically (async - for server-side)
* In browser, this is called eagerly at module load time
* In Node.js server, this is called on-demand
*/
async function ensureMapSourcesLoaded(): Promise<void> {
if (worldMapSource && usaMapSource) {
return // Already loaded
}
// Dynamic import works in both browser (via Next.js bundler) and Node.js (native ESM support)
const [worldModule, usaModule] = await Promise.all([
import('@svg-maps/world'),
import('@svg-maps/usa'),
])
worldMapSource = worldModule.default
usaMapSource = usaModule.default
console.log('[Maps] Loaded via dynamic import:', {
world: worldMapSource?.locations?.length,
usa: usaMapSource?.locations?.length,
env: typeof window === 'undefined' ? 'server' : 'browser',
})
}
/**
* Promise tracking the map loading process.
* Initialized lazily on first access (not at module load) so the 1.2 MB
* @svg-maps chunks are only fetched when the game is actually played.
*/
let browserMapsLoadingPromise: Promise<void> | null = null
/**
* Start loading maps in the browser. Safe to call multiple times — only
* kicks off the fetch once. Returns the shared loading promise.
*/
function startLoadingMaps(): Promise<void> {
if (!browserMapsLoadingPromise) {
browserMapsLoadingPromise = (async () => {
await ensureMapSourcesLoaded()
// Populate the caches
await getWorldMapData()
await getUSAMapData()
})().catch((err) => {
console.error('[Maps] Failed to load map data in browser:', err)
browserMapsLoadingPromise = null // allow retry
throw err
})
}
return browserMapsLoadingPromise
}
/**
* Region size category for difficulty-based filtering
*/
export type RegionSize = 'huge' | 'large' | 'medium' | 'small' | 'tiny'
/**
* Hints mode for difficulty levels
*/
export type HintsMode = 'onRequest' | 'limited' | 'none'
/**
* Give up behavior mode
*/
export type GiveUpMode = 'reaskSoon' | 'reaskEnd' | 'countsAgainst' | 'skipEntirely'
/**
* Difficulty level configuration for a map
*/
export interface DifficultyLevel {
id: string // e.g., 'learning', 'easy', 'normal', 'expert'
label: string // Display name
emoji?: string // Optional emoji
description?: string // Short description for UI
detailedDescription?: string // Longer description for tooltip/modal
// Region filtering (new size-based system)
includeSizes?: RegionSize[] // Which size categories to include
// Legacy filtering (for backwards compatibility)
excludeRegions?: string[] // Explicit region IDs to exclude
keepPercentile?: number // 0-1, keep this % of largest regions (default 1.0)
// Feature flags
hotColdEnabled?: boolean // Hot/cold feedback when clicking wrong regions
hintsMode?: HintsMode // How hints work
hintLimit?: number // For 'limited' mode, how many hints per game
autoHintDefault?: boolean // Default state of auto-hint checkbox
struggleHintEnabled?: boolean // Show hint after struggling (timer-based)
giveUpMode?: GiveUpMode // What happens when player gives up
wrongClickShowsName?: boolean // Show "That was [name]" vs just "Wrong!"
}
/**
* Per-map difficulty configuration
* @deprecated Use AssistanceLevelConfig instead - difficulty conflated region filtering with assistance
*/
export interface MapDifficultyConfig {
levels: DifficultyLevel[]
defaultLevel: string // ID of default level
}
/**
* Assistance level configuration - controls gameplay features separate from region filtering
*/
export interface AssistanceLevelConfig {
id: 'learning' | 'guided' | 'helpful' | 'standard' | 'none'
label: string
emoji: string
description: string
// Feature flags
hotColdEnabled: boolean
hintsMode: HintsMode
hintLimit?: number // For 'limited' mode
autoHintDefault: boolean
struggleHintEnabled: boolean
giveUpMode: GiveUpMode
wrongClickShowsName: boolean
// Name reinforcement
nameConfirmationLetters?: number // If set, require typing first N letters before hints unlock
}
/**
* Assistance levels - separate from region filtering
*/
export const ASSISTANCE_LEVELS: AssistanceLevelConfig[] = [
{
id: 'learning',
label: 'Learning',
emoji: '📚',
description:
'Type first 3 letters to unlock hints, maximum feedback, best for memorizing names',
hotColdEnabled: true,
hintsMode: 'onRequest',
autoHintDefault: true,
struggleHintEnabled: true,
giveUpMode: 'reaskSoon',
wrongClickShowsName: true,
nameConfirmationLetters: 3, // Must type first 3 letters to unlock hints
},
{
id: 'guided',
label: 'Guided',
emoji: '🎓',
description: 'Maximum help - auto hints, hot/cold feedback, shows names on wrong clicks',
hotColdEnabled: true,
hintsMode: 'onRequest',
autoHintDefault: true,
struggleHintEnabled: true,
giveUpMode: 'reaskSoon',
wrongClickShowsName: true,
},
{
id: 'helpful',
label: 'Helpful',
emoji: '💡',
description: 'Hot/cold feedback and hints available on request',
hotColdEnabled: true,
hintsMode: 'onRequest',
autoHintDefault: false,
struggleHintEnabled: false,
giveUpMode: 'reaskEnd',
wrongClickShowsName: true,
},
{
id: 'standard',
label: 'Standard',
emoji: '🎯',
description: 'Limited hints (3), no hot/cold feedback',
hotColdEnabled: false,
hintsMode: 'limited',
hintLimit: 3,
autoHintDefault: false,
struggleHintEnabled: false,
giveUpMode: 'countsAgainst',
wrongClickShowsName: false,
},
{
id: 'none',
label: 'No Assistance',
emoji: '🏆',
description: 'Pure challenge - no hints or feedback',
hotColdEnabled: false,
hintsMode: 'none',
autoHintDefault: false,
struggleHintEnabled: false,
giveUpMode: 'skipEntirely',
wrongClickShowsName: false,
},
]
/**
* Get assistance level config by ID
*/
export function getAssistanceLevel(id: string): AssistanceLevelConfig {
return ASSISTANCE_LEVELS.find((l) => l.id === id) || ASSISTANCE_LEVELS[1] // Default to 'helpful'
}
/**
* Default region sizes to include (all sizes = complete set)
*/
export const ALL_REGION_SIZES: RegionSize[] = ['huge', 'large', 'medium', 'small', 'tiny']
/**
* Display configuration for each region size
*/
export const REGION_SIZE_CONFIG: Record<
RegionSize,
{ label: string; emoji: string; description: string }
> = {
huge: {
label: 'Major',
emoji: '🌍',
description: 'Large, well-known countries/states',
},
large: {
label: 'Large',
emoji: '🗺️',
description: 'Large territories',
},
medium: {
label: 'Medium',
emoji: '📍',
description: 'Mid-sized territories',
},
small: {
label: 'Small',
emoji: '🏝️',
description: 'Small territories and islands',
},
tiny: {
label: 'Tiny',
emoji: '🔍',
description: 'Microstates and remote territories',
},
}
/**
* Default assistance level
*/
export const DEFAULT_ASSISTANCE_LEVEL = 'helpful'
/**
* Default region sizes (medium difficulty - most regions)
*/
export const DEFAULT_REGION_SIZES: RegionSize[] = ['huge', 'large', 'medium']
/**
* Global default difficulty config for maps without custom config
* @deprecated - kept for backwards compatibility, use ASSISTANCE_LEVELS instead
* New 4-level system: Learning, Easy, Normal, Expert
*/
export const DEFAULT_DIFFICULTY_CONFIG: MapDifficultyConfig = {
levels: [
{
id: 'learning',
label: 'Learning',
emoji: '🌱',
description: 'Guided exploration with maximum help',
detailedDescription:
'Large countries only (~57). Hot/cold feedback guides you. Hints auto-open and appear if stuck.',
includeSizes: ['huge', 'large'],
hotColdEnabled: true,
hintsMode: 'onRequest',
autoHintDefault: true,
struggleHintEnabled: true,
giveUpMode: 'reaskSoon',
wrongClickShowsName: true,
},
{
id: 'easy',
label: 'Easy',
emoji: '😊',
description: 'Helpful feedback as you learn',
detailedDescription: 'Most countries (~163). Hot/cold feedback. Press H for hints anytime.',
includeSizes: ['huge', 'large', 'medium'],
hotColdEnabled: true,
hintsMode: 'onRequest',
autoHintDefault: false,
struggleHintEnabled: false,
giveUpMode: 'reaskEnd',
wrongClickShowsName: true,
},
{
id: 'normal',
label: 'Normal',
emoji: '🎯',
description: 'Standard challenge',
detailedDescription: 'Nearly all countries (~223). No hot/cold. 3 hints per game.',
includeSizes: ['huge', 'large', 'medium', 'small'],
hotColdEnabled: false,
hintsMode: 'limited',
hintLimit: 3,
autoHintDefault: false,
struggleHintEnabled: false,
giveUpMode: 'countsAgainst',
wrongClickShowsName: false,
},
{
id: 'expert',
label: 'Expert',
emoji: '🏆',
description: 'Test your knowledge',
detailedDescription: 'All countries including tiny islands (256). No hints. Pure geography.',
includeSizes: ['huge', 'large', 'medium', 'small', 'tiny'],
hotColdEnabled: false,
hintsMode: 'none',
autoHintDefault: false,
struggleHintEnabled: false,
giveUpMode: 'skipEntirely',
wrongClickShowsName: false,
},
],
defaultLevel: 'easy',
}
/**
* USA state size categories (by geographic area and recognition)
* Uses state abbreviations (lowercase) from @svg-maps/usa
*/
const USA_STATE_SIZE_CATEGORIES: Record<RegionSize, Set<string>> = {
// Huge: Instantly recognizable, largest states (~8)
huge: new Set([
'ca', // California
'tx', // Texas
'fl', // Florida
'ny', // New York
'ak', // Alaska
'mt', // Montana
'az', // Arizona
'nv', // Nevada
]),
// Large: Major states, clearly visible (~10)
large: new Set([
'nm', // New Mexico
'co', // Colorado
'or', // Oregon
'wa', // Washington
'ut', // Utah
'wy', // Wyoming
'mi', // Michigan
'il', // Illinois
'pa', // Pennsylvania
'oh', // Ohio
]),
// Medium: Recognizable states, moderate size (~17)
medium: new Set([
'id', // Idaho
'nd', // North Dakota
'sd', // South Dakota
'ne', // Nebraska
'ks', // Kansas
'ok', // Oklahoma
'mn', // Minnesota
'ia', // Iowa
'mo', // Missouri
'ar', // Arkansas
'la', // Louisiana
'wi', // Wisconsin
'in', // Indiana
'ga', // Georgia
'nc', // North Carolina
'va', // Virginia
'tn', // Tennessee
]),
// Small: Smaller states (~10)
small: new Set([
'sc', // South Carolina
'al', // Alabama
'ms', // Mississippi
'ky', // Kentucky
'wv', // West Virginia
'md', // Maryland
'nj', // New Jersey
'ma', // Massachusetts
'me', // Maine
'hi', // Hawaii
]),
// Tiny: Small states, harder to find (~6)
tiny: new Set([
'vt', // Vermont
'nh', // New Hampshire
'ct', // Connecticut
'ri', // Rhode Island
'de', // Delaware
'dc', // District of Columbia
]),
}
/**
* Get the size category for a US state
*/
function getUSAStateSizeCategory(stateId: string): RegionSize | null {
for (const [size, ids] of Object.entries(USA_STATE_SIZE_CATEGORIES)) {
if (ids.has(stateId)) {
return size as RegionSize
}
}
return null
}
/**
* Check if a US state should be included based on difficulty level's size requirements
*/
function shouldIncludeUSAState(stateId: string, includeSizes: RegionSize[]): boolean {
const category = getUSAStateSizeCategory(stateId)
if (!category) {
// If no category found, include by default
return true
}
return includeSizes.includes(category)
}
/**
* USA map difficulty config - 4 levels like world map
*/
export const USA_DIFFICULTY_CONFIG: MapDifficultyConfig = {
levels: [
{
id: 'learning',
label: 'Learning',
emoji: '🌱',
description: 'Guided exploration with maximum help',
detailedDescription:
'Major states only (~18). Hot/cold feedback guides you. Hints auto-open and appear if stuck.',
includeSizes: ['huge', 'large'],
hotColdEnabled: true,
hintsMode: 'onRequest',
autoHintDefault: true,
struggleHintEnabled: true,
wrongClickShowsName: true,
giveUpMode: 'reaskSoon',
},
{
id: 'easy',
label: 'Easy',
emoji: '😊',
description: 'Comfortable challenge with guidance',
detailedDescription: 'Most states (~35). Hot/cold feedback. Press H for hints anytime.',
includeSizes: ['huge', 'large', 'medium'],
hotColdEnabled: true,
hintsMode: 'onRequest',
autoHintDefault: false,
struggleHintEnabled: false,
wrongClickShowsName: true,
giveUpMode: 'reaskEnd',
},
{
id: 'normal',
label: 'Normal',
emoji: '🎯',
description: 'Standard challenge with limited hints',
detailedDescription: 'Nearly all states (~45). No hot/cold. 3 hints per game.',
includeSizes: ['huge', 'large', 'medium', 'small'],
hotColdEnabled: false,
hintsMode: 'limited',
hintLimit: 3,
autoHintDefault: false,
struggleHintEnabled: false,
giveUpMode: 'countsAgainst',
wrongClickShowsName: false,
},
{
id: 'expert',
label: 'Expert',
emoji: '🏆',
description: 'Full challenge, no assistance',
detailedDescription: 'All 51 states/territories. No hints. Pure geography.',
includeSizes: ['huge', 'large', 'medium', 'small', 'tiny'],
hotColdEnabled: false,
hintsMode: 'none',
autoHintDefault: false,
struggleHintEnabled: false,
giveUpMode: 'skipEntirely',
wrongClickShowsName: false,
},
],
defaultLevel: 'easy',
}
/**
* Region size categories for world map
* Curated based on actual geographic size and prominence (not bounding box area)
* ISO 3166-1 alpha-2 codes (lowercase)
*/
const REGION_SIZE_CATEGORIES: Record<RegionSize, Set<string>> = {
// Huge: Major powers, instantly recognizable (~15)
huge: new Set([
'ru', // Russia
'cn', // China
'us', // United States
'ca', // Canada
'br', // Brazil
'au', // Australia
'in', // India
'ar', // Argentina
'kz', // Kazakhstan
'dz', // Algeria
'cd', // DR Congo
'sa', // Saudi Arabia
'mx', // Mexico
'id', // Indonesia
'ly', // Libya
]),
// Large: Major countries, clearly visible (~42)
large: new Set([
'sd',
'ir',
'mn',
'pe',
'td',
'ne',
'ao',
'ml',
'za',
'co',
've',
'et',
'eg',
'mr',
'bo',
'ng',
'tz',
'cl',
'zm',
'mm',
'af',
'so',
'cf',
'ss',
'mg',
'mz',
'pk',
'tr',
'ke',
'fr',
'th',
'es',
'cm',
'pg',
'ma',
'ua',
'jp',
'de',
'pl',
'no',
'se',
'fi',
]),
// Medium: Recognizable countries, moderate size (~106)
medium: new Set([
// Europe
'gb',
'it',
'ro',
'gr',
'bg',
'hu',
'by',
'at',
'cz',
'rs',
'ie',
'lt',
'lv',
'hr',
'ba',
'sk',
'ee',
'dk',
'nl',
'be',
'ch',
'pt',
'al',
'md',
'mk',
'si',
'me',
'xk',
'is',
// Asia
'vn',
'my',
'ph',
'np',
'bd',
'kh',
'la',
'kp',
'kr',
'tw',
'uz',
'tm',
'kg',
'tj',
'iq',
'sy',
'jo',
'il',
'lb',
'az',
'ge',
'am',
'ye',
'om',
'ae',
'bt',
'ps',
'tl',
// Africa
'ci',
'bf',
'gh',
'gn',
'sn',
'ug',
'ga',
'tg',
'bj',
'er',
'mw',
'ls',
'sz',
'rw',
'bi',
'sl',
'lr',
'gm',
'gw',
'cg',
'gq',
'dj',
'tn',
'bw',
'na',
'zw',
'eh',
// Americas
'ec',
'py',
'uy',
'sr',
'gy',
'pa',
'cr',
'ni',
'hn',
'gt',
'bz',
'sv',
'cu',
'do',
'ht',
'jm',
'bs',
'tt',
'gf',
'gl',
// Oceania
'nz',
'fj',
]),
// Small: Smaller countries, harder to find (~60)
small: new Set([
// Caribbean
'bb',
'ag',
'dm',
'lc',
'vc',
'gd',
'kn',
'aw',
'cw',
'bq',
'sx',
'mf',
'bl',
'tc',
'vg',
'vi',
'ky',
'ai',
'ms',
'pr',
'bm',
'gp',
'mq',
// Europe
'lu',
'cy',
'mt',
'ax',
'fo',
'gg',
'im',
'je',
// Middle East
'kw',
'qa',
'bh',
// Africa
'cv',
'st',
'km',
'mu',
're',
'yt',
'sc',
'sh',
// Asia
'bn',
'sg',
'hk',
'mo',
'mv',
'lk',
'pm',
// Oceania
'ws',
'to',
'vu',
'sb',
'nc',
'pf',
'gu',
'as',
'mp',
'pw',
'fm',
]),
// Tiny: Microstates and tiny islands, very hard to find (~33)
tiny: new Set([
// Europe
'va',
'mc',
'sm',
'ad',
'li',
'gi',
// Pacific
'nr',
'tv',
'mh',
'ki',
'nu',
'tk',
'ck',
'wf',
'pn',
// Other territories
'io',
'cx',
'cc',
'nf',
'hm',
'bv',
'sj',
'fk',
'gs',
'aq',
'tf',
'go',
'ju', // French territories
'um-dq',
'um-fq',
'um-hq',
'um-jq',
'um-mq',
'um-wq', // US Minor Outlying Islands
]),
}
/**
* Geopolitical importance category for filtering
* Based on international influence (G7/G20/UNSC membership, regional power, etc.)
*/
export type ImportanceLevel = 'superpower' | 'major' | 'regional' | 'standard' | 'minor'
/**
* Geopolitical importance categories for world map
* Curated based on international influence and diplomatic standing
* ISO 3166-1 alpha-2 codes (lowercase)
*/
const REGION_IMPORTANCE_CATEGORIES: Record<ImportanceLevel, Set<string>> = {
// Superpower: UNSC P5 + G7 (~9 countries)
superpower: new Set([
'us', // United States - superpower
'cn', // China - superpower
'ru', // Russia - UNSC P5
'gb', // United Kingdom - UNSC P5, G7
'fr', // France - UNSC P5, G7
'de', // Germany - G7
'jp', // Japan - G7
'it', // Italy - G7
'ca', // Canada - G7
]),
// Major: G20 members and other major economies (~15)
major: new Set([
'in', // India - G20, rising power
'br', // Brazil - G20, regional power
'au', // Australia - G20
'kr', // South Korea - G20
'mx', // Mexico - G20
'id', // Indonesia - G20
'tr', // Turkey - G20, NATO
'sa', // Saudi Arabia - G20, OPEC leader
'ar', // Argentina - G20
'za', // South Africa - G20, BRICS
'es', // Spain - EU major
'nl', // Netherlands - EU founding
'pl', // Poland - EU major
'se', // Sweden - EU
'ch', // Switzerland - financial hub
]),
// Regional: Significant regional powers and influential nations (~45)
regional: new Set([
// Europe
'at',
'be',
'dk',
'fi',
'gr',
'ie',
'no',
'pt',
'cz',
'ro',
'hu',
// Middle East
'ae',
'il',
'eg',
'ir',
'iq',
'pk',
'qa',
'kw',
// Asia
'th',
'my',
'sg',
'vn',
'ph',
'bd',
'tw',
'hk',
// Africa
'ng',
'ke',
'et',
'dz',
'ma',
'gh',
// Americas
'cl',
'co',
'pe',
've',
'cu',
// Oceania
'nz',
]),
// Standard: Most UN member states with moderate influence (~100)
standard: new Set([
// Europe
'ua',
'by',
'sk',
'bg',
'hr',
'rs',
'lt',
'lv',
'ee',
'si',
'ba',
'mk',
'al',
'me',
'xk',
'md',
'is',
'cy',
'mt',
'lu',
// Asia
'af',
'kz',
'uz',
'tm',
'kg',
'tj',
'mn',
'np',
'lk',
'mm',
'kh',
'la',
'kp',
'bt',
'bn',
// Middle East
'jo',
'lb',
'sy',
'ye',
'om',
'bh',
'az',
'ge',
'am',
'ps',
// Africa
'tz',
'ug',
'zm',
'zw',
'sd',
'ss',
'cd',
'ao',
'mz',
'mg',
'cm',
'ci',
'sn',
'ml',
'bf',
'ne',
'td',
'cf',
'cg',
'ga',
'gq',
'bj',
'tg',
'gn',
'sl',
'lr',
'gm',
'gw',
'mr',
'tn',
'ly',
'so',
'er',
'dj',
'rw',
'bi',
'mw',
'bw',
'na',
'sz',
'ls',
// Americas
'ec',
'bo',
'py',
'uy',
'gy',
'sr',
'pa',
'cr',
'ni',
'hn',
'gt',
'sv',
'bz',
'do',
'ht',
'jm',
'tt',
'bs',
// Oceania
'pg',
'fj',
]),
// Minor: Small states, territories, and dependencies (~80+)
minor: new Set([
// Caribbean
'bb',
'ag',
'dm',
'lc',
'vc',
'gd',
'kn',
'aw',
'cw',
'bq',
'sx',
'mf',
'bl',
'tc',
'vg',
'vi',
'ky',
'ai',
'ms',
'pr',
'bm',
'gp',
'mq',
'gf',
// Europe
'li',
'ad',
'mc',
'sm',
'va',
'gi',
'fo',
'ax',
'gg',
'im',
'je',
// Pacific
'ws',
'to',
'vu',
'sb',
'nc',
'pf',
'gu',
'as',
'mp',
'pw',
'fm',
'mh',
'ki',
'nr',
'tv',
'nu',
'tk',
'ck',
'wf',
'pn',
// Indian Ocean
'mv',
'sc',
'mu',
'km',
'yt',
're',
// African territories
'cv',
'st',
'sh',
'eh',
// Asian territories
'mo',
'tl',
'io',
'cx',
'cc',
'nf',
// Other
'gl',
'pm',
'hm',
'bv',
'sj',
'fk',
'gs',
'aq',
'tf',
'go',
'ju',
'um-dq',
'um-fq',
'um-hq',
'um-jq',
'um-mq',
'um-wq',
]),
}
/**
* Display configuration for each importance level
*/
export const IMPORTANCE_LEVEL_CONFIG: Record<
ImportanceLevel,
{ label: string; emoji: string; description: string }
> = {
superpower: {
label: 'Superpower',
emoji: '🌟',
description: 'G7 and UNSC permanent members',
},
major: {
label: 'Major',
emoji: '🏛️',
description: 'G20 members and major economies',
},
regional: {
label: 'Regional',
emoji: '🌐',
description: 'Regional powers and influential nations',
},
standard: {
label: 'Standard',
emoji: '🏳️',
description: 'Most UN member states',
},
minor: {
label: 'Minor',
emoji: '🏝️',
description: 'Small states and territories',
},
}
/**
* All importance levels in order from most to least important
*/
export const ALL_IMPORTANCE_LEVELS: ImportanceLevel[] = [
'superpower',
'major',
'regional',
'standard',
'minor',
]
/**
* Population category for filtering
*/
export type PopulationLevel = 'huge' | 'large' | 'medium' | 'small' | 'tiny'
/**
* Population categories for world map
* Based on approximate population (2024 estimates)
* ISO 3166-1 alpha-2 codes (lowercase)
*/
const REGION_POPULATION_CATEGORIES: Record<PopulationLevel, Set<string>> = {
// Huge: 100M+ population (~13 countries)
huge: new Set([
'cn', // China - 1.4B
'in', // India - 1.4B
'us', // United States - 335M
'id', // Indonesia - 277M
'pk', // Pakistan - 235M
'br', // Brazil - 216M
'ng', // Nigeria - 224M
'bd', // Bangladesh - 173M
'ru', // Russia - 144M
'mx', // Mexico - 130M
'jp', // Japan - 125M
'et', // Ethiopia - 126M
'ph', // Philippines - 117M
]),
// Large: 30-100M population (~30 countries)
large: new Set([
'eg', // Egypt - 105M
'vn', // Vietnam - 99M
'cd', // DR Congo - 99M
'tr', // Turkey - 85M
'ir', // Iran - 87M
'de', // Germany - 84M
'th', // Thailand - 72M
'gb', // United Kingdom - 67M
'fr', // France - 68M
'it', // Italy - 59M
'za', // South Africa - 60M
'tz', // Tanzania - 65M
'mm', // Myanmar - 54M
'kr', // South Korea - 52M
'co', // Colombia - 52M
'ke', // Kenya - 54M
'es', // Spain - 48M
'ar', // Argentina - 46M
'ug', // Uganda - 48M
'dz', // Algeria - 45M
'sd', // Sudan - 46M
'ua', // Ukraine - 38M
'iq', // Iraq - 43M
'af', // Afghanistan - 41M
'pl', // Poland - 38M
'ca', // Canada - 40M
'ma', // Morocco - 37M
'sa', // Saudi Arabia - 36M
'uz', // Uzbekistan - 35M
'pe', // Peru - 34M
'my', // Malaysia - 34M
'ao', // Angola - 35M
]),
// Medium: 10-30M population (~50 countries)
medium: new Set([
've',
'np',
'gh',
'mz',
'ye',
'mg',
'kp',
'au',
'cm',
'ci',
'tw',
'ne',
'lk',
'bf',
'ml',
'sy',
'mw',
'ro',
'cl',
'kz',
'zm',
'ec',
'sn',
'td',
'nl',
'so',
'gt',
'zw',
'rw',
'gn',
'bj',
'bi',
'tn',
'be',
'bo',
'ht',
'cu',
'cz',
'jo',
'gr',
'do',
'se',
'pt',
'az',
'ae',
'hn',
'hu',
'tj',
'by',
'at',
'ch',
'pg',
'il',
'tg',
'sl',
'ss',
]),
// Small: 1-10M population (~60 countries)
small: new Set([
'hk',
'la',
'ly',
'rs',
'bg',
'pa',
'lb',
'lr',
'cf',
'ni',
'ie',
'cr',
'cg',
'ps',
'nz',
'sk',
'ge',
'hr',
'om',
'pr',
'dk',
'no',
'sg',
'er',
'fi',
'ky',
'mr',
'kw',
'bi',
'md',
'ja',
'na',
'mk',
'bw',
'lt',
'gm',
'ga',
'si',
'qa',
'xk',
'ba',
'lv',
'gw',
'ee',
'mu',
'tt',
'tl',
'cy',
'fj',
'dj',
'km',
'bt',
'gq',
'ls',
'sz',
'bh',
'mn',
'me',
'al',
'arm',
'jm',
'kg',
'tm',
]),
// Tiny: <1M population (~60+ countries/territories)
tiny: new Set([
// Caribbean
'bb',
'ag',
'dm',
'lc',
'vc',
'gd',
'kn',
'aw',
'cw',
'bq',
'sx',
'mf',
'bl',
'tc',
'vg',
'vi',
'ai',
'ms',
'bm',
'gp',
'mq',
'gf',
// Europe
'lu',
'mt',
'is',
'li',
'ad',
'mc',
'sm',
'va',
'gi',
'fo',
'ax',
'gg',
'im',
'je',
// Pacific
'ws',
'to',
'vu',
'sb',
'nc',
'pf',
'gu',
'as',
'mp',
'pw',
'fm',
'mh',
'ki',
'nr',
'tv',
'nu',
'tk',
'ck',
'wf',
'pn',
// Indian Ocean
'mv',
'sc',
're',
'yt',
// Africa
'cv',
'st',
'sh',
'eh',
// Asian/Other
'mo',
'bn',
'pm',
'io',
'cx',
'cc',
'nf',
'gl',
'hm',
'bv',
'sj',
'fk',
'gs',
'aq',
'tf',
'go',
'ju',
'um-dq',
'um-fq',
'um-hq',
'um-jq',
'um-mq',
'um-wq',
]),
}
/**
* Display configuration for each population level
*/
export const POPULATION_LEVEL_CONFIG: Record<
PopulationLevel,
{ label: string; emoji: string; description: string }
> = {
huge: {
label: 'Huge',
emoji: '🏙️',
description: 'Countries with 100M+ people',
},
large: {
label: 'Large',
emoji: '🌆',
description: 'Countries with 30-100M people',
},
medium: {
label: 'Medium',
emoji: '🏘️',
description: 'Countries with 10-30M people',
},
small: {
label: 'Small',
emoji: '🏡',
description: 'Countries with 1-10M people',
},
tiny: {
label: 'Tiny',
emoji: '🏝️',
description: 'Countries with <1M people',
},
}
/**
* All population levels in order from largest to smallest
*/
export const ALL_POPULATION_LEVELS: PopulationLevel[] = ['huge', 'large', 'medium', 'small', 'tiny']
/**
* Filter criteria type - which dimension to filter regions by
*/
export type FilterCriteria = 'size' | 'importance' | 'population'
/**
* Display configuration for filter criteria tabs
*/
export const FILTER_CRITERIA_CONFIG: Record<
FilterCriteria,
{ label: string; emoji: string; description: string }
> = {
size: {
label: 'Size',
emoji: '📏',
description: 'Filter by geographic size',
},
importance: {
label: 'Importance',
emoji: '🏛️',
description: 'Filter by geopolitical importance',
},
population: {
label: 'Population',
emoji: '👥',
description: 'Filter by population',
},
}
/**
* Get the importance category for a region ID
*/
export function getRegionImportanceCategory(regionId: string): ImportanceLevel | null {
for (const [level, ids] of Object.entries(REGION_IMPORTANCE_CATEGORIES)) {
if (ids.has(regionId)) {
return level as ImportanceLevel
}
}
return null
}
/**
* Get the population category for a region ID
*/
export function getRegionPopulationCategory(regionId: string): PopulationLevel | null {
for (const [level, ids] of Object.entries(REGION_POPULATION_CATEGORIES)) {
if (ids.has(regionId)) {
return level as PopulationLevel
}
}
return null
}
/**
* Check if a region should be included based on importance requirements
*/
export function shouldIncludeRegionByImportance(
regionId: string,
includeLevels: ImportanceLevel[]
): boolean {
const category = getRegionImportanceCategory(regionId)
if (!category) {
// If no category found, include by default (for regions not in our list)
return true
}
return includeLevels.includes(category)
}
/**
* Check if a region should be included based on population requirements
*/
export function shouldIncludeRegionByPopulation(
regionId: string,
includeLevels: PopulationLevel[]
): boolean {
const category = getRegionPopulationCategory(regionId)
if (!category) {
// If no category found, include by default (for regions not in our list)
return true
}
return includeLevels.includes(category)
}
/**
* Filter regions by importance levels
*/
export function filterRegionsByImportance(
regions: MapRegion[],
includeLevels: ImportanceLevel[]
): MapRegion[] {
if (includeLevels.length === 0 || includeLevels.length === ALL_IMPORTANCE_LEVELS.length) {
return regions
}
return regions.filter((r) => shouldIncludeRegionByImportance(r.id, includeLevels))
}
/**
* Filter regions by population levels
*/
export function filterRegionsByPopulation(
regions: MapRegion[],
includeLevels: PopulationLevel[]
): MapRegion[] {
if (includeLevels.length === 0 || includeLevels.length === ALL_POPULATION_LEVELS.length) {
return regions
}
return regions.filter((r) => shouldIncludeRegionByPopulation(r.id, includeLevels))
}
/**
* Get the size category for a region ID
*/
export function getRegionSizeCategory(regionId: string): RegionSize | null {
for (const [size, ids] of Object.entries(REGION_SIZE_CATEGORIES)) {
if (ids.has(regionId)) {
return size as RegionSize
}
}
return null // Region not categorized (shouldn't happen for world map)
}
/**
* Check if a region should be included based on difficulty level's size requirements
*/
export function shouldIncludeRegion(regionId: string, includeSizes: RegionSize[]): boolean {
const category = getRegionSizeCategory(regionId)
if (!category) {
// If no category found, include by default (for regions not in our list)
return true
}
return includeSizes.includes(category)
}
/**
* Parse SVG path into subpaths (separated by M commands, closed by Z)
* Returns array of point arrays, one per subpath
*/
function parsePathToSubpaths(pathString: string): Array<Array<[number, number]>> {
const subpaths: Array<Array<[number, number]>> = []
let currentSubpath: Array<[number, number]> = []
let currentX = 0
let currentY = 0
let subpathStartX = 0
let subpathStartY = 0
const commandRegex = /([MmLlHhVvCcSsQqTtAaZz])([^MmLlHhVvCcSsQqTtAaZz]*)/g
let match
while ((match = commandRegex.exec(pathString)) !== null) {
const command = match[1]
const params =
match[2]
.trim()
.match(/-?\d+\.?\d*/g)
?.map(Number) || []
switch (command) {
case 'M':
if (currentSubpath.length > 0) subpaths.push(currentSubpath)
currentSubpath = []
for (let i = 0; i < params.length - 1; i += 2) {
currentX = params[i]
currentY = params[i + 1]
if (i === 0) {
subpathStartX = currentX
subpathStartY = currentY
}
currentSubpath.push([currentX, currentY])
}
break
case 'm':
if (currentSubpath.length > 0) subpaths.push(currentSubpath)
currentSubpath = []
for (let i = 0; i < params.length - 1; i += 2) {
currentX += params[i]
currentY += params[i + 1]
if (i === 0) {
subpathStartX = currentX
subpathStartY = currentY
}
currentSubpath.push([currentX, currentY])
}
break
case 'L':
for (let i = 0; i < params.length - 1; i += 2) {
currentX = params[i]
currentY = params[i + 1]
currentSubpath.push([currentX, currentY])
}
break
case 'l':
for (let i = 0; i < params.length - 1; i += 2) {
currentX += params[i]
currentY += params[i + 1]
currentSubpath.push([currentX, currentY])
}
break
case 'H':
for (const x of params) {
currentX = x
currentSubpath.push([currentX, currentY])
}
break
case 'h':
for (const dx of params) {
currentX += dx
currentSubpath.push([currentX, currentY])
}
break
case 'V':
for (const y of params) {
currentY = y
currentSubpath.push([currentX, currentY])
}
break
case 'v':
for (const dy of params) {
currentY += dy
currentSubpath.push([currentX, currentY])
}
break
case 'C':
for (let i = 0; i < params.length - 5; i += 6) {
currentX = params[i + 4]
currentY = params[i + 5]
currentSubpath.push([currentX, currentY])
}
break
case 'c':
for (let i = 0; i < params.length - 5; i += 6) {
currentX += params[i + 4]
currentY += params[i + 5]
currentSubpath.push([currentX, currentY])
}
break
case 'S':
for (let i = 0; i < params.length - 3; i += 4) {
currentX = params[i + 2]
currentY = params[i + 3]
currentSubpath.push([currentX, currentY])
}
break
case 's':
for (let i = 0; i < params.length - 3; i += 4) {
currentX += params[i + 2]
currentY += params[i + 3]
currentSubpath.push([currentX, currentY])
}
break
case 'Q':
for (let i = 0; i < params.length - 3; i += 4) {
currentX = params[i + 2]
currentY = params[i + 3]
currentSubpath.push([currentX, currentY])
}
break
case 'q':
for (let i = 0; i < params.length - 3; i += 4) {
currentX += params[i + 2]
currentY += params[i + 3]
currentSubpath.push([currentX, currentY])
}
break
case 'T':
for (let i = 0; i < params.length - 1; i += 2) {
currentX = params[i]
currentY = params[i + 1]
currentSubpath.push([currentX, currentY])
}
break
case 't':
for (let i = 0; i < params.length - 1; i += 2) {
currentX += params[i]
currentY += params[i + 1]
currentSubpath.push([currentX, currentY])
}
break
case 'A':
for (let i = 0; i < params.length - 6; i += 7) {
currentX = params[i + 5]
currentY = params[i + 6]
currentSubpath.push([currentX, currentY])
}
break
case 'a':
for (let i = 0; i < params.length - 6; i += 7) {
currentX += params[i + 5]
currentY += params[i + 6]
currentSubpath.push([currentX, currentY])
}
break
case 'Z':
case 'z':
currentX = subpathStartX
currentY = subpathStartY
if (currentSubpath.length > 0) {
subpaths.push(currentSubpath)
currentSubpath = []
}
break
}
}
if (currentSubpath.length > 0) subpaths.push(currentSubpath)
return subpaths
}
/**
* Calculate polygon area using shoelace formula
*/
function calculatePolygonArea(points: Array<[number, number]>): number {
if (points.length < 3) return 0
let area = 0
for (let i = 0; i < points.length; i++) {
const j = (i + 1) % points.length
area += points[i][0] * points[j][1]
area -= points[j][0] * points[i][1]
}
return Math.abs(area) / 2
}
/**
* Calculate centroid of a polygon using shoelace formula
*/
function calculatePolygonCentroid(points: Array<[number, number]>): [number, number] {
if (points.length === 0) return [0, 0]
if (points.length < 3) {
const avgX = points.reduce((s, p) => s + p[0], 0) / points.length
const avgY = points.reduce((s, p) => s + p[1], 0) / points.length
return [avgX, avgY]
}
let signedArea = 0
let cx = 0
let cy = 0
for (let i = 0; i < points.length; i++) {
const j = (i + 1) % points.length
const cross = points[i][0] * points[j][1] - points[j][0] * points[i][1]
signedArea += cross
cx += (points[i][0] + points[j][0]) * cross
cy += (points[i][1] + points[j][1]) * cross
}
signedArea /= 2
if (Math.abs(signedArea) < 0.0001) {
const avgX = points.reduce((s, p) => s + p[0], 0) / points.length
const avgY = points.reduce((s, p) => s + p[1], 0) / points.length
return [avgX, avgY]
}
return [cx / (6 * signedArea), cy / (6 * signedArea)]
}
/**
* Get the bounding box center of the largest closed subpath in an SVG path.
* Uses bounding box center (not geometric centroid) for more visually predictable results
* on elongated shapes like Norway or Chile.
* Falls back to overall path bounding box center if subpath parsing fails.
*/
export function getLargestSubpathCentroid(pathString: string): { x: number; y: number } | null {
const subpaths = parsePathToSubpaths(pathString)
// If no subpaths found, return null to signal fallback should be used
if (subpaths.length === 0) {
return null
}
// Find largest subpath by area
let largestSubpath = subpaths[0]
let largestArea = calculatePolygonArea(largestSubpath)
for (let i = 1; i < subpaths.length; i++) {
const area = calculatePolygonArea(subpaths[i])
if (area > largestArea) {
largestArea = area
largestSubpath = subpaths[i]
}
}
// If largest subpath is empty or has no area, return null
if (largestSubpath.length === 0 || largestArea === 0) {
return null
}
// Calculate bounding box center of largest subpath
let minX = largestSubpath[0][0]
let maxX = largestSubpath[0][0]
let minY = largestSubpath[0][1]
let maxY = largestSubpath[0][1]
for (const [x, y] of largestSubpath) {
if (x < minX) minX = x
if (x > maxX) maxX = x
if (y < minY) minY = y
if (y > maxY) maxY = y
}
return { x: (minX + maxX) / 2, y: (minY + maxY) / 2 }
}
/**
* Calculate the centroid (center of mass) of an SVG path
* Properly parses SVG path commands to extract endpoint coordinates only
*/
function calculatePathCenter(pathString: string): [number, number] {
const points: Array<[number, number]> = []
// Parse SVG path commands to extract endpoint coordinates
// Regex matches: command letter followed by numbers
const commandRegex = /([MmLlHhVvCcSsQqTtAaZz])([^MmLlHhVvCcSsQqTtAaZz]*)/g
let currentX = 0
let currentY = 0
let match
while ((match = commandRegex.exec(pathString)) !== null) {
const command = match[1]
const params =
match[2]
.trim()
.match(/-?\d+\.?\d*/g)
?.map(Number) || []
switch (command) {
case 'M': // Move to (absolute)
if (params.length >= 2) {
currentX = params[0]
currentY = params[1]
points.push([currentX, currentY])
}
break
case 'm': // Move to (relative)
if (params.length >= 2) {
currentX += params[0]
currentY += params[1]
points.push([currentX, currentY])
}
break
case 'L': // Line to (absolute)
for (let i = 0; i < params.length - 1; i += 2) {
currentX = params[i]
currentY = params[i + 1]
points.push([currentX, currentY])
}
break
case 'l': // Line to (relative)
for (let i = 0; i < params.length - 1; i += 2) {
currentX += params[i]
currentY += params[i + 1]
points.push([currentX, currentY])
}
break
case 'H': // Horizontal line (absolute)
for (const x of params) {
currentX = x
points.push([currentX, currentY])
}
break
case 'h': // Horizontal line (relative)
for (const dx of params) {
currentX += dx
points.push([currentX, currentY])
}
break
case 'V': // Vertical line (absolute)
for (const y of params) {
currentY = y
points.push([currentX, currentY])
}
break
case 'v': // Vertical line (relative)
for (const dy of params) {
currentY += dy
points.push([currentX, currentY])
}
break
case 'C': // Cubic Bezier (absolute) - take only the endpoint (last 2 params)
for (let i = 0; i < params.length - 1; i += 6) {
if (i + 5 < params.length) {
currentX = params[i + 4]
currentY = params[i + 5]
points.push([currentX, currentY])
}
}
break
case 'c': // Cubic Bezier (relative) - take only the endpoint
for (let i = 0; i < params.length - 1; i += 6) {
if (i + 5 < params.length) {
currentX += params[i + 4]
currentY += params[i + 5]
points.push([currentX, currentY])
}
}
break
case 'Q': // Quadratic Bezier (absolute) - take only the endpoint (last 2 params)
for (let i = 0; i < params.length - 1; i += 4) {
if (i + 3 < params.length) {
currentX = params[i + 2]
currentY = params[i + 3]
points.push([currentX, currentY])
}
}
break
case 'q': // Quadratic Bezier (relative) - take only the endpoint
for (let i = 0; i < params.length - 1; i += 4) {
if (i + 3 < params.length) {
currentX += params[i + 2]
currentY += params[i + 3]
points.push([currentX, currentY])
}
}
break
case 'Z':
case 'z':
// Close path - no new point needed
break
}
}
if (points.length === 0) {
return [0, 0]
}
if (points.length < 3) {
// Not enough points for a polygon, fallback to average
const avgX = points.reduce((sum, p) => sum + p[0], 0) / points.length
const avgY = points.reduce((sum, p) => sum + p[1], 0) / points.length
return [avgX, avgY]
}
// Calculate polygon centroid using shoelace formula
let signedArea = 0
let cx = 0
let cy = 0
for (let i = 0; i < points.length; i++) {
const [x0, y0] = points[i]
const [x1, y1] = points[(i + 1) % points.length]
const crossProduct = x0 * y1 - x1 * y0
signedArea += crossProduct
cx += (x0 + x1) * crossProduct
cy += (y0 + y1) * crossProduct
}
signedArea *= 0.5
// Avoid division by zero
if (Math.abs(signedArea) < 0.0001) {
// Fallback to average of all points
const avgX = points.reduce((sum, p) => sum + p[0], 0) / points.length
const avgY = points.reduce((sum, p) => sum + p[1], 0) / points.length
return [avgX, avgY]
}
cx = cx / (6 * signedArea)
cy = cy / (6 * signedArea)
return [cx, cy]
}
/**
* Convert @svg-maps location data to our MapRegion format
*/
function convertToMapRegions(
locations: Array<{ id: string; name: string; path: string }>
): MapRegion[] {
return locations.map((location) => ({
id: location.id,
name: location.name,
path: location.path,
center: calculatePathCenter(location.path),
}))
}
/**
* Cached MapData instances (after conversion)
*/
let worldMapDataCache: MapData | null = null
let usaMapDataCache: MapData | null = null
/**
* Get World map data (async)
*/
async function getWorldMapData(): Promise<MapData> {
if (worldMapDataCache) {
return worldMapDataCache
}
await ensureMapSourcesLoaded()
if (!worldMapSource) {
throw new Error('[Maps] World map source not loaded')
}
worldMapDataCache = {
id: 'world',
name: worldMapSource.label || 'Map of World',
viewBox: worldMapSource.viewBox,
originalViewBox: worldMapSource.viewBox, // Same as viewBox for base map
customCrop: null, // No custom crop for base map
regions: convertToMapRegions(worldMapSource.locations || []),
}
return worldMapDataCache
}
/**
* Get USA map data (async)
*/
async function getUSAMapData(): Promise<MapData> {
if (usaMapDataCache) {
return usaMapDataCache
}
await ensureMapSourcesLoaded()
if (!usaMapSource) {
throw new Error('[Maps] USA map source not loaded')
}
usaMapDataCache = {
id: 'usa',
name: usaMapSource.label || 'Map of USA',
viewBox: usaMapSource.viewBox,
originalViewBox: usaMapSource.viewBox, // Same as viewBox for base map
customCrop: null, // No custom crop for base map
regions: convertToMapRegions(usaMapSource.locations || []),
difficultyConfig: USA_DIFFICULTY_CONFIG,
}
return usaMapDataCache
}
/**
* Get map data synchronously (for client components)
* In browser, throws a promise to trigger React Suspense if not loaded yet
*/
function getMapDataSync(mapId: 'world' | 'usa'): MapData {
const cache = mapId === 'world' ? worldMapDataCache : usaMapDataCache
if (!cache) {
// In browser, start loading (if not already) and throw the promise to trigger Suspense
if (typeof window !== 'undefined') {
throw startLoadingMaps()
}
throw new Error(
`[Maps] ${mapId} map not yet loaded. Use await getMapData() or ensure maps are preloaded.`
)
}
return cache
}
/**
* Synchronous exports for client components
* These proxy to the cache and throw if accessed before loading
*/
export const WORLD_MAP: MapData = new Proxy({} as MapData, {
get(target, prop) {
return getMapDataSync('world')[prop as keyof MapData]
},
})
export const USA_MAP: MapData = new Proxy({} as MapData, {
get(target, prop) {
return getMapDataSync('usa')[prop as keyof MapData]
},
})
/**
* Get map data by ID (async - for server-side code)
*/
export async function getMapData(mapId: 'world' | 'usa'): Promise<MapData> {
return mapId === 'world' ? await getWorldMapData() : await getUSAMapData()
}
/**
* Get a specific region by ID from a map (async)
*/
export async function getRegionById(mapId: 'world' | 'usa', regionId: string) {
const mapData = await getMapData(mapId)
return mapData.regions.find((r) => r.id === regionId)
}
/**
* Calculate bounding box for a set of SVG paths
*/
export interface BoundingBox {
minX: number
maxX: number
minY: number
maxY: number
width: number
height: number
}
export function calculateBoundingBox(paths: string[]): BoundingBox {
let minX = Infinity
let maxX = -Infinity
let minY = Infinity
let maxY = -Infinity
for (const pathString of paths) {
// Parse SVG path commands properly (similar to calculatePathCenter)
const commandRegex = /([MmLlHhVvCcSsQqTtAaZz])([^MmLlHhVvCcSsQqTtAaZz]*)/g
let currentX = 0
let currentY = 0
// Track the start of the current subpath (for z command)
let subpathStartX = 0
let subpathStartY = 0
let match
while ((match = commandRegex.exec(pathString)) !== null) {
const command = match[1]
const params =
match[2]
.trim()
.match(/-?\d+\.?\d*/g)
?.map(Number) || []
switch (command) {
case 'M': // Move to (absolute)
// First pair is moveto, subsequent pairs are implicit lineto (absolute)
for (let i = 0; i < params.length - 1; i += 2) {
currentX = params[i]
currentY = params[i + 1]
// First coordinate pair starts a new subpath
if (i === 0) {
subpathStartX = currentX
subpathStartY = currentY
}
minX = Math.min(minX, currentX)
maxX = Math.max(maxX, currentX)
minY = Math.min(minY, currentY)
maxY = Math.max(maxY, currentY)
}
break
case 'm': // Move to (relative)
// First pair is moveto (relative), subsequent pairs are implicit lineto (relative)
// Both use relative coordinates, so same logic applies
for (let i = 0; i < params.length - 1; i += 2) {
currentX += params[i]
currentY += params[i + 1]
// First coordinate pair starts a new subpath
if (i === 0) {
subpathStartX = currentX
subpathStartY = currentY
}
minX = Math.min(minX, currentX)
maxX = Math.max(maxX, currentX)
minY = Math.min(minY, currentY)
maxY = Math.max(maxY, currentY)
}
break
case 'L': // Line to (absolute)
for (let i = 0; i < params.length - 1; i += 2) {
currentX = params[i]
currentY = params[i + 1]
minX = Math.min(minX, currentX)
maxX = Math.max(maxX, currentX)
minY = Math.min(minY, currentY)
maxY = Math.max(maxY, currentY)
}
break
case 'l': // Line to (relative)
for (let i = 0; i < params.length - 1; i += 2) {
currentX += params[i]
currentY += params[i + 1]
minX = Math.min(minX, currentX)
maxX = Math.max(maxX, currentX)
minY = Math.min(minY, currentY)
maxY = Math.max(maxY, currentY)
}
break
case 'H': // Horizontal line (absolute)
for (const x of params) {
currentX = x
minX = Math.min(minX, currentX)
maxX = Math.max(maxX, currentX)
}
break
case 'h': // Horizontal line (relative)
for (const dx of params) {
currentX += dx
minX = Math.min(minX, currentX)
maxX = Math.max(maxX, currentX)
}
break
case 'V': // Vertical line (absolute)
for (const y of params) {
currentY = y
minY = Math.min(minY, currentY)
maxY = Math.max(maxY, currentY)
}
break
case 'v': // Vertical line (relative)
for (const dy of params) {
currentY += dy
minY = Math.min(minY, currentY)
maxY = Math.max(maxY, currentY)
}
break
case 'C': // Cubic Bezier (absolute)
for (let i = 0; i < params.length - 1; i += 6) {
if (i + 5 < params.length) {
// Check all control points and endpoint
for (let j = 0; j < 6; j += 2) {
const x = params[i + j]
const y = params[i + j + 1]
minX = Math.min(minX, x)
maxX = Math.max(maxX, x)
minY = Math.min(minY, y)
maxY = Math.max(maxY, y)
}
currentX = params[i + 4]
currentY = params[i + 5]
}
}
break
case 'c': // Cubic Bezier (relative)
for (let i = 0; i < params.length - 1; i += 6) {
if (i + 5 < params.length) {
// Check all control points and endpoint (converted to absolute)
for (let j = 0; j < 6; j += 2) {
const x = currentX + params[i + j]
const y = currentY + params[i + j + 1]
minX = Math.min(minX, x)
maxX = Math.max(maxX, x)
minY = Math.min(minY, y)
maxY = Math.max(maxY, y)
}
currentX += params[i + 4]
currentY += params[i + 5]
}
}
break
case 'Q': // Quadratic Bezier (absolute)
for (let i = 0; i < params.length - 1; i += 4) {
if (i + 3 < params.length) {
// Check control point and endpoint
for (let j = 0; j < 4; j += 2) {
const x = params[i + j]
const y = params[i + j + 1]
minX = Math.min(minX, x)
maxX = Math.max(maxX, x)
minY = Math.min(minY, y)
maxY = Math.max(maxY, y)
}
currentX = params[i + 2]
currentY = params[i + 3]
}
}
break
case 'q': // Quadratic Bezier (relative)
for (let i = 0; i < params.length - 1; i += 4) {
if (i + 3 < params.length) {
// Check control point and endpoint (converted to absolute)
for (let j = 0; j < 4; j += 2) {
const x = currentX + params[i + j]
const y = currentY + params[i + j + 1]
minX = Math.min(minX, x)
maxX = Math.max(maxX, x)
minY = Math.min(minY, y)
maxY = Math.max(maxY, y)
}
currentX += params[i + 2]
currentY += params[i + 3]
}
}
break
case 'Z':
case 'z':
// Close path - return to start of current subpath
currentX = subpathStartX
currentY = subpathStartY
break
}
}
}
return {
minX,
maxX,
minY,
maxY,
width: maxX - minX,
height: maxY - minY,
}
}
/**
* Filter world map regions by continent
*/
import { type ContinentId, getContinentForCountry } from './continents'
export function filterRegionsByContinent(
regions: MapRegion[],
continentId: ContinentId | 'all'
): MapRegion[] {
if (continentId === 'all') {
return regions
}
return regions.filter((region) => {
const continent = getContinentForCountry(region.id)
return continent === continentId
})
}
/**
* Calculate adjusted viewBox for a continent
* Uses custom crop if available, otherwise calculates from bounding box with padding
*/
export function calculateContinentViewBox(
regions: MapRegion[],
continentId: ContinentId | 'all',
originalViewBox: string,
mapId: string = 'world'
): string {
if (continentId === 'all') {
return originalViewBox
}
// Check for custom crop override first
const customCrop = getCustomCrop(mapId, continentId)
if (customCrop) {
return customCrop
}
const filteredRegions = filterRegionsByContinent(regions, continentId)
if (filteredRegions.length === 0) {
return originalViewBox
}
const paths = filteredRegions.map((r) => r.path)
const bbox = calculateBoundingBox(paths)
// Add 10% padding on each side
const paddingX = bbox.width * 0.1
const paddingY = bbox.height * 0.1
const newMinX = bbox.minX - paddingX
const newMinY = bbox.minY - paddingY
const newWidth = bbox.width + 2 * paddingX
const newHeight = bbox.height + 2 * paddingY
return `${newMinX} ${newMinY} ${newWidth} ${newHeight}`
}
/**
* Parse a viewBox string into numeric components
*/
export function parseViewBox(viewBox: string): {
x: number
y: number
width: number
height: number
} {
const parts = viewBox.split(' ').map(Number)
return {
x: parts[0] || 0,
y: parts[1] || 0,
width: parts[2] || 1000,
height: parts[3] || 500,
}
}
/**
* Calculate a display viewBox that:
* 1. Guarantees the crop region is fully visible and centered
* 2. Fills any remaining viewport space with more of the map (no letterboxing)
* 3. Stays within the original map's bounds
*
* This creates a "fit crop with fill" effect - the crop region is the minimum
* visible area, but we expand to fill the container's aspect ratio.
*
* @param originalViewBox - The full map's viewBox (bounds)
* @param cropRegion - The custom crop that MUST be visible
* @param containerAspect - The container's width/height ratio
* @returns The display viewBox string
*/
export function calculateFitCropViewBox(
originalViewBox: { x: number; y: number; width: number; height: number },
cropRegion: { x: number; y: number; width: number; height: number },
containerAspect: number // width / height
): string {
const cropAspect = cropRegion.width / cropRegion.height
let viewBoxWidth: number
let viewBoxHeight: number
// Step 1: Calculate dimensions to fill container while containing crop
if (containerAspect > cropAspect) {
// Container is WIDER than crop - expand horizontally
viewBoxHeight = cropRegion.height
viewBoxWidth = viewBoxHeight * containerAspect
} else {
// Container is TALLER than crop - expand vertically
viewBoxWidth = cropRegion.width
viewBoxHeight = viewBoxWidth / containerAspect
}
// Step 2: Center on crop region
const cropCenterX = cropRegion.x + cropRegion.width / 2
const cropCenterY = cropRegion.y + cropRegion.height / 2
let viewBoxX = cropCenterX - viewBoxWidth / 2
let viewBoxY = cropCenterY - viewBoxHeight / 2
// Step 3: Clamp to original map bounds (shift if needed, don't resize)
// Clamp X
if (viewBoxX < originalViewBox.x) {
viewBoxX = originalViewBox.x
} else if (viewBoxX + viewBoxWidth > originalViewBox.x + originalViewBox.width) {
viewBoxX = originalViewBox.x + originalViewBox.width - viewBoxWidth
}
// Clamp Y
if (viewBoxY < originalViewBox.y) {
viewBoxY = originalViewBox.y
} else if (viewBoxY + viewBoxHeight > originalViewBox.y + originalViewBox.height) {
viewBoxY = originalViewBox.y + originalViewBox.height - viewBoxHeight
}
// Step 4: Handle case where expanded viewBox exceeds map bounds
// (show entire map dimension, may result in letterboxing on that axis)
if (viewBoxWidth > originalViewBox.width) {
viewBoxWidth = originalViewBox.width
viewBoxX = originalViewBox.x
}
if (viewBoxHeight > originalViewBox.height) {
viewBoxHeight = originalViewBox.height
viewBoxY = originalViewBox.y
}
return `${viewBoxX.toFixed(2)} ${viewBoxY.toFixed(2)} ${viewBoxWidth.toFixed(2)} ${viewBoxHeight.toFixed(2)}`
}
/**
* Safe zone margins (in pixels) - areas reserved for UI elements
*/
export interface SafeZoneMargins {
top: number
right: number
bottom: number
left: number
}
/**
* Calculate a viewBox that fits the crop region into the "safe zone" (viewport minus UI margins)
* while filling the entire viewport with map content.
*
* This creates a layout where:
* 1. The crop region (findable regions) fits within the leftover rectangle (viewport minus margins)
* 2. Extra map content shows under the UI elements (no wasted space)
* 3. The entire viewport is filled with map - no letterboxing except at map bounds
*
* @param viewportWidth - The viewport width in pixels
* @param viewportHeight - The viewport height in pixels
* @param margins - Safe zone margins in pixels (areas reserved for UI)
* @param cropRegion - The crop region that must fit within the safe zone (in SVG coords)
* @param originalViewBox - The full map's bounds (in SVG coords)
* @returns The display viewBox string
*/
export function calculateSafeZoneViewBox(
viewportWidth: number,
viewportHeight: number,
margins: SafeZoneMargins,
cropRegion: { x: number; y: number; width: number; height: number },
originalViewBox: { x: number; y: number; width: number; height: number }
): string {
// Step 1: Calculate leftover rectangle (the area where crop must fit)
const leftoverWidth = viewportWidth - margins.left - margins.right
const leftoverHeight = viewportHeight - margins.top - margins.bottom
// Guard against invalid margins
if (leftoverWidth <= 0 || leftoverHeight <= 0) {
// Margins exceed viewport - fallback to standard fit
const containerAspect = viewportWidth / viewportHeight
return calculateFitCropViewBox(originalViewBox, cropRegion, containerAspect)
}
// Step 2: Calculate scale to fit crop into leftover rectangle
// This is pixels per SVG unit
const scaleX = leftoverWidth / cropRegion.width
const scaleY = leftoverHeight / cropRegion.height
const scale = Math.min(scaleX, scaleY) // Use the smaller scale to ensure crop fits
// Step 3: Calculate viewBox dimensions to fill entire viewport at this scale
const viewBoxWidth = viewportWidth / scale
const viewBoxHeight = viewportHeight / scale
// Step 4: Position viewBox so crop CENTER appears at leftover CENTER
// This is the key insight: position based on crop, not map bounds
const leftoverCenterX = margins.left + leftoverWidth / 2
const leftoverCenterY = margins.top + leftoverHeight / 2
const cropCenterX = cropRegion.x + cropRegion.width / 2
const cropCenterY = cropRegion.y + cropRegion.height / 2
// To make crop center appear at leftover center:
// (cropCenterX - viewBoxX) * scale = leftoverCenterX
// viewBoxX = cropCenterX - leftoverCenterX / scale
let viewBoxX = cropCenterX - leftoverCenterX / scale
let viewBoxY = cropCenterY - leftoverCenterY / scale
// Step 5: Try to shift viewBox to show more map content (reduce letterboxing)
// but ONLY if it doesn't push the crop outside the leftover area
// Calculate the valid range for viewBoxX that keeps crop in leftover area
// cropLeftPx = (crop.x - vbX) * scale >= margins.left => vbX <= crop.x - margins.left/scale
// cropRightPx = (crop.x + crop.w - vbX) * scale <= viewport.w - margins.right
// => vbX >= crop.x + crop.w - (viewport.w - margins.right)/scale
const viewBoxX_max = cropRegion.x - margins.left / scale
const viewBoxX_min = cropRegion.x + cropRegion.width - (viewportWidth - margins.right) / scale
const viewBoxY_max = cropRegion.y - margins.top / scale
const viewBoxY_min = cropRegion.y + cropRegion.height - (viewportHeight - margins.bottom) / scale
// Clamp viewBox to stay within these bounds (ensures crop stays in leftover area)
// Note: We DON'T clamp to map bounds here - we accept letterboxing (empty space outside map)
// to ensure the crop is correctly positioned in the leftover area
viewBoxX = Math.max(viewBoxX_min, Math.min(viewBoxX_max, viewBoxX))
viewBoxY = Math.max(viewBoxY_min, Math.min(viewBoxY_max, viewBoxY))
// Debug logging for safe zone calculation
if (process.env.NODE_ENV === 'development') {
// Calculate where crop actually appears on screen
const cropLeftPx = (cropRegion.x - viewBoxX) * scale
const cropTopPx = (cropRegion.y - viewBoxY) * scale
const cropWidthPx = cropRegion.width * scale
const cropHeightPx = cropRegion.height * scale
const cropRightPx = cropLeftPx + cropWidthPx
const cropBottomPx = cropTopPx + cropHeightPx
// Calculate leftover bounds
const leftoverLeft = margins.left
const leftoverTop = margins.top
const leftoverRight = viewportWidth - margins.right
const leftoverBottom = viewportHeight - margins.bottom
// Check if crop fits in leftover
const fitsLeft = cropLeftPx >= leftoverLeft
const fitsTop = cropTopPx >= leftoverTop
const fitsRight = cropRightPx <= leftoverRight
const fitsBottom = cropBottomPx <= leftoverBottom
const fitsAll = fitsLeft && fitsTop && fitsRight && fitsBottom
}
return `${viewBoxX.toFixed(2)} ${viewBoxY.toFixed(2)} ${viewBoxWidth.toFixed(2)} ${viewBoxHeight.toFixed(2)}`
}
/**
* Calculate SVG bounding box area for a region path
*/
function calculateRegionArea(pathString: string): number {
const numbers = pathString.match(/-?\d+\.?\d*/g)?.map(Number) || []
if (numbers.length === 0) {
return 0
}
const xCoords: number[] = []
const yCoords: number[] = []
for (let i = 0; i < numbers.length; i += 2) {
xCoords.push(numbers[i])
if (i + 1 < numbers.length) {
yCoords.push(numbers[i + 1])
}
}
if (xCoords.length === 0 || yCoords.length === 0) {
return 0
}
const minX = Math.min(...xCoords)
const maxX = Math.max(...xCoords)
const minY = Math.min(...yCoords)
const maxY = Math.max(...yCoords)
const width = maxX - minX
const height = maxY - minY
return width * height
}
/**
* Filter regions by size categories (primary filtering function)
* This is the new clean API that takes sizes directly
*/
export function filterRegionsBySizes(
regions: MapRegion[],
includeSizes: RegionSize[],
mapId: 'world' | 'usa' = 'world'
): MapRegion[] {
// If all sizes included, empty array, or undefined - return all regions
if (
!includeSizes ||
includeSizes.length === 0 ||
includeSizes.length === ALL_REGION_SIZES.length
) {
return regions
}
// Use appropriate size checker based on map
const shouldInclude =
mapId === 'usa'
? (id: string) => shouldIncludeUSAState(id, includeSizes)
: (id: string) => shouldIncludeRegion(id, includeSizes)
const filtered = regions.filter((r) => shouldInclude(r.id))
return filtered
}
/**
* Filter regions based on difficulty level configuration
* @deprecated Use filterRegionsBySizes instead
* Supports: 1) Size-based filtering (new), 2) Explicit exclusions, 3) Percentile-based (legacy)
*/
function filterRegionsByDifficulty(
regions: MapRegion[],
level: DifficultyLevel,
mapId: 'world' | 'usa' = 'world'
): MapRegion[] {
// 1. Size-based filtering (new system - highest priority)
if (level.includeSizes && level.includeSizes.length > 0) {
return filterRegionsBySizes(regions, level.includeSizes, mapId)
}
// 2. Explicit exclusions
if (level.excludeRegions && level.excludeRegions.length > 0) {
const filtered = regions.filter((r) => !level.excludeRegions!.includes(r.id))
console.log(
`[Difficulty Filter] ${level.id} mode: ${filtered.length}/${regions.length} regions (excluded: ${level.excludeRegions.join(', ')})`
)
return filtered
}
// 3. Legacy percentile filtering
const percentile = level.keepPercentile ?? 1.0
if (percentile >= 1.0) {
return regions // Include all regions
}
// Calculate areas for all regions
const regionsWithAreas = regions.map((region) => ({
region,
area: calculateRegionArea(region.path),
}))
// Sort by area (largest first)
regionsWithAreas.sort((a, b) => b.area - a.area)
// Keep top N% of largest regions
const keepCount = Math.ceil(regions.length * percentile)
const filtered = regionsWithAreas.slice(0, keepCount).map((item) => item.region)
// Debug logging
const excluded = regionsWithAreas.slice(keepCount)
if (excluded.length > 0) {
console.log(
`[Difficulty Filter] EXCLUDED (smallest ${excluded.length}):`,
excluded.map((item) => `${item.region.name} (${item.area.toFixed(0)} units²)`)
)
}
console.log(
`[Difficulty Filter] ${level.id} mode: ${filtered.length}/${regions.length} regions (top ${(percentile * 100).toFixed(0)}%)`
)
return filtered
}
/**
* Get filtered map data for a continent and difficulty (async - for server-side)
*/
export async function getFilteredMapData(
mapId: 'world' | 'usa',
continentId: ContinentId | 'all',
difficultyLevelId?: string // Optional difficulty level ID (uses map's default if not provided)
): Promise<MapData> {
const mapData = await getMapData(mapId)
// Get difficulty config for this map (or use global default)
const difficultyConfig = mapData.difficultyConfig || DEFAULT_DIFFICULTY_CONFIG
// Find the difficulty level by ID (or use default)
const levelId = difficultyLevelId || difficultyConfig.defaultLevel
const difficultyLevel = difficultyConfig.levels.find((level) => level.id === levelId)
if (!difficultyLevel) {
console.warn(
`[getFilteredMapData] Difficulty level "${levelId}" not found for map "${mapId}". Using default.`
)
const defaultLevel = difficultyConfig.levels.find(
(level) => level.id === difficultyConfig.defaultLevel
)
if (!defaultLevel) {
throw new Error(`Invalid difficulty config for map "${mapId}": no default level found`)
}
}
const level = difficultyLevel || difficultyConfig.levels[0]
let filteredRegions = mapData.regions
let adjustedViewBox = mapData.viewBox
let customCrop: string | null = null
// Apply continent filtering for world map
if (mapId === 'world' && continentId !== 'all') {
filteredRegions = filterRegionsByContinent(filteredRegions, continentId)
// Check for custom crop - this is what we'll use for fit-crop-with-fill
customCrop = getCustomCrop(mapId, continentId)
adjustedViewBox = calculateContinentViewBox(
mapData.regions,
continentId,
mapData.viewBox,
mapId
)
}
// Apply difficulty filtering
filteredRegions = filterRegionsByDifficulty(filteredRegions, level, mapId)
return {
...mapData,
regions: filteredRegions,
viewBox: adjustedViewBox,
originalViewBox: mapData.viewBox, // Always the base map's viewBox
customCrop, // The custom crop region if any (for fit-crop-with-fill)
}
}
/**
* Get filtered map data by size categories (async - for server-side)
* This is the new clean API that takes sizes directly
*/
export async function getFilteredMapDataBySizes(
mapId: 'world' | 'usa',
continentId: ContinentId | 'all',
includeSizes: RegionSize[]
): Promise<MapData> {
const mapData = await getMapData(mapId)
let filteredRegions = mapData.regions
let adjustedViewBox = mapData.viewBox
let customCrop: string | null = null
// Apply continent filtering for world map
if (mapId === 'world' && continentId !== 'all') {
filteredRegions = filterRegionsByContinent(filteredRegions, continentId)
customCrop = getCustomCrop(mapId, continentId)
adjustedViewBox = calculateContinentViewBox(
mapData.regions,
continentId,
mapData.viewBox,
mapId
)
}
// Apply size filtering
filteredRegions = filterRegionsBySizes(filteredRegions, includeSizes, mapId)
return {
...mapData,
regions: filteredRegions,
viewBox: adjustedViewBox,
originalViewBox: mapData.viewBox,
customCrop,
}
}
/**
* Get filtered map data by size categories synchronously (for client components)
* This is the new clean API that takes sizes directly
*/
export function getFilteredMapDataBySizesSync(
mapId: 'world' | 'usa',
continentId: ContinentId | 'all',
includeSizes: RegionSize[]
): MapData {
const mapData = mapId === 'world' ? WORLD_MAP : USA_MAP
let filteredRegions = mapData.regions
let adjustedViewBox = mapData.viewBox
let customCrop: string | null = null
// Apply continent filtering for world map
if (mapId === 'world' && continentId !== 'all') {
filteredRegions = filterRegionsByContinent(filteredRegions, continentId)
customCrop = getCustomCrop(mapId, continentId)
adjustedViewBox = calculateContinentViewBox(
mapData.regions,
continentId,
mapData.viewBox,
mapId
)
}
// Apply size filtering
filteredRegions = filterRegionsBySizes(filteredRegions, includeSizes, mapId)
return {
...mapData,
regions: filteredRegions,
viewBox: adjustedViewBox,
originalViewBox: mapData.viewBox,
customCrop,
}
}
/**
* Sub-map registry: maps country/region IDs to their detailed sub-maps
* For drill-down navigation in the map selector
*/
export interface SubMapEntry {
/** Continent this region belongs to */
continentId: ContinentId
/** ID of the sub-map (e.g., 'usa') */
mapId: 'usa' // Expandable to other maps in future
/** Display name for breadcrumbs */
name: string
/** Emoji for UI */
emoji: string
}
export const SUB_MAPS: Record<string, SubMapEntry> = {
us: {
continentId: 'north-america',
mapId: 'usa',
name: 'USA',
emoji: '🇺🇸',
},
// Future expansions:
// de: { continentId: 'europe', mapId: 'germany', name: 'Germany', emoji: '🇩🇪' },
// cn: { continentId: 'asia', mapId: 'china', name: 'China', emoji: '🇨🇳' },
}
/**
* Check if a region has a detailed sub-map available
*/
export function hasSubMap(regionId: string): boolean {
return regionId in SUB_MAPS
}
/**
* Get sub-map entry for a region, if available
*/
export function getSubMapEntry(regionId: string): SubMapEntry | null {
return SUB_MAPS[regionId] ?? null
}
/**
* Get sub-map data for a region, if available
* Returns the actual MapData for the sub-map
*/
export function getSubMapData(regionId: string): MapData | null {
const entry = SUB_MAPS[regionId]
if (!entry) return null
// Return the appropriate map data
if (entry.mapId === 'usa') {
return USA_MAP
}
return null
}
/**
* Get all regions in a continent that have sub-maps
*/
export function getSubMapsForContinent(continentId: ContinentId): string[] {
return Object.entries(SUB_MAPS)
.filter(([_, entry]) => entry.continentId === continentId)
.map(([regionId]) => regionId)
}
/**
* Get filtered map data synchronously (for client components)
* Uses the synchronous WORLD_MAP/USA_MAP proxies
*/
export function getFilteredMapDataSync(
mapId: 'world' | 'usa',
continentId: ContinentId | 'all',
difficultyLevelId?: string
): MapData {
const mapData = mapId === 'world' ? WORLD_MAP : USA_MAP
// Get difficulty config for this map (or use global default)
const difficultyConfig = mapData.difficultyConfig || DEFAULT_DIFFICULTY_CONFIG
// Find the difficulty level by ID (or use default)
const levelId = difficultyLevelId || difficultyConfig.defaultLevel
const difficultyLevel = difficultyConfig.levels.find((level) => level.id === levelId)
if (!difficultyLevel) {
console.warn(
`[getFilteredMapDataSync] Difficulty level "${levelId}" not found for map "${mapId}". Using default.`
)
const defaultLevel = difficultyConfig.levels.find(
(level) => level.id === difficultyConfig.defaultLevel
)
if (!defaultLevel) {
throw new Error(`Invalid difficulty config for map "${mapId}": no default level found`)
}
}
const level = difficultyLevel || difficultyConfig.levels[0]
let filteredRegions = mapData.regions
let adjustedViewBox = mapData.viewBox
let customCrop: string | null = null
// Apply continent filtering for world map
if (mapId === 'world' && continentId !== 'all') {
filteredRegions = filterRegionsByContinent(filteredRegions, continentId)
// Check for custom crop - this is what we'll use for fit-crop-with-fill
customCrop = getCustomCrop(mapId, continentId)
adjustedViewBox = calculateContinentViewBox(
mapData.regions,
continentId,
mapData.viewBox,
mapId
)
}
// Apply difficulty filtering
filteredRegions = filterRegionsByDifficulty(filteredRegions, level, mapId)
return {
...mapData,
regions: filteredRegions,
viewBox: adjustedViewBox,
originalViewBox: mapData.viewBox, // Always the base map's viewBox
customCrop, // The custom crop region if any (for fit-crop-with-fill)
}
}
|