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 | 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 1x 1x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 23x 23x 23x 32x 32x 32x 32x 23x 23x 32x 32x 32x 32x 32x 32x 32x 32x 15x 15x 15x 15x 15x 32x 32x 32x 32x 15x 4x 4x 15x 4x 4x 4x 32x 32x 32x 32x 31x 32x 31x 32x 32x 32x 32x 32x 32x 32x 15x 15x 15x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 15x 15x 15x 15x 15x 32x 32x 32x 32x 32x 15x 15x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 15x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 15x 15x 32x 32x 32x 32x 32x 15x 15x 15x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 31x 31x 32x 31x 31x 31x 31x 32x 31x 31x 31x 31x 31x 31x 31x 31x 32x 31x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 23x 32x 32x 32x 32x 32x 15x 15x 15x 15x 15x 15x 15x 1x 15x 15x 15x 15x 32x 32x 32x 32x 15x 15x 15x 32x 32x 32x 32x 32x 15x 32x 32x 32x 32x 15x 32x 32x 32x 32x 32x 32x 23x 23x 32x 32x 32x 32x 32x 23x 23x 23x 23x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 15x 15x 15x 15x 32x 32x 32x 32x 32x 32x 32x 32x 23x 23x 23x 23x 23x 23x 32x 32x 32x 32x 23x 4x 4x 4x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 2x 29x 29x 29x 29x 29x 29x 29x 31x 31x 31x 31x 31x 31x 29x 29x 29x 29x 174x 174x 174x 174x 174x 174x 174x 174x 174x 174x 174x 174x 174x 174x 174x 174x 174x 174x 174x 174x 174x 174x 174x 174x 174x 174x 174x 174x 174x 174x 174x 174x 174x 174x 174x 174x 29x 29x 2x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 32x 32x 32x 32x 31x 31x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 2x 29x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 31x 32x 32x 32x 31x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 32x 32x 32x 32x 32x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 2x 29x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 29x 29x 29x 29x 174x 174x 174x 174x 174x 174x 174x 174x 174x 174x 174x 174x 174x 174x 174x 174x 174x 174x 174x 174x 174x 174x 174x 174x 174x 174x 174x 174x 174x 174x 174x 174x 174x 174x 29x 29x 2x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 25x 32x 32x 32x 32x 32x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 32x 32x 32x 32x 32x 32x 32x | 'use client'
import * as DropdownMenu from '@radix-ui/react-dropdown-menu'
import { animated, to, useSpring } from '@react-spring/web'
import { css } from '@styled/css'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import useMeasure from 'react-use-measure'
import simplify from 'simplify-js'
import { useIsSpectator } from '@/contexts/SpectatorModeContext'
import { useTheme } from '@/contexts/ThemeContext'
import { useVisualDebugSafe } from '@/contexts/VisualDebugContext'
import { useUserId } from '@/lib/arcade/game-sdk'
import { getNthNonSpaceLetter, normalizeToBaseLetter } from '../features/letter-confirmation'
import {
DEFAULT_DIFFICULTY_CONFIG,
getAssistanceLevel,
getCountryFlagEmoji,
USA_MAP,
WORLD_MAP,
} from '../maps'
import { MusicControlModal, useMusic } from '../music'
import { useKnowYourWorld } from '../Provider'
import type { MapData } from '../types'
import {
shouldShowAutoHintToggle,
shouldShowAutoSpeakToggle,
shouldShowGuidanceDropdown,
} from '../utils/guidanceVisibility'
import { SimpleLetterKeyboard, useIsTouchDevice } from './SimpleLetterKeyboard'
// Animation duration in ms - must match MapRenderer
const GIVE_UP_ANIMATION_DURATION = 2000
// Duration for the "attention grab" phase of the name display (ms)
const NAME_ATTENTION_DURATION = 3000
// React-spring config for smooth takeover transitions
const TAKEOVER_ANIMATION_CONFIG = { tension: 170, friction: 20 }
/**
* Convert {x, y} points array to SVG path string.
*/
function pointsToSvgPath(points: Array<{ x: number; y: number }>): string {
if (points.length === 0) return ''
let path = `M ${points[0].x} ${points[0].y}`
for (let i = 1; i < points.length; i++) {
path += ` L ${points[i].x} ${points[i].y}`
}
path += ' Z'
return path
}
interface GameInfoPanelProps {
mapData: MapData
currentRegionName: string | null
currentRegionId: string | null
selectedMap: 'world' | 'usa'
foundCount: number
totalRegions: number
progress: number
/** Callback when hints are unlocked (after name confirmation) */
onHintsUnlock?: () => void
}
export function GameInfoPanel({
mapData,
currentRegionName,
currentRegionId,
selectedMap,
foundCount,
totalRegions,
progress,
onHintsUnlock,
}: GameInfoPanelProps) {
const isSpectator = useIsSpectator()
const { resolvedTheme } = useTheme()
const isDark = resolvedTheme === 'dark'
const { isVisualDebugEnabled } = useVisualDebugSafe()
const {
state,
lastError,
clearError,
giveUp,
confirmLetter,
controlsState,
setIsInTakeover,
puzzlePieceTarget,
setPuzzlePieceTarget,
setCelebration,
} = useKnowYourWorld()
// Destructure controls state from context
const {
showHotCold,
hotColdEnabled,
onHotColdToggle,
currentHint,
isGiveUpAnimating,
// Speech/audio state
isSpeechSupported,
isSpeaking,
onSpeak,
onStopSpeaking,
// Auto settings
autoSpeak,
onAutoSpeakToggle,
autoHint,
onAutoHintToggle,
} = controlsState
// Get game state values
const {
giveUpVotes = [],
activeUserIds = [],
gameMode,
currentPlayer,
playerMetadata = {},
} = state
// Get viewer ID for vote checking
const { data: viewerId } = useUserId()
// Touch device detection for virtual keyboard
const isTouchDevice = useIsTouchDevice()
// Track "not your turn" notification
const [showNotYourTurn, setShowNotYourTurn] = useState(false)
// Check if it's the local viewer's turn (for turn-based mode)
const isMyTurn = useMemo(() => {
if (gameMode !== 'turn-based') return true // Always "your turn" in non-turn-based modes
if (!currentPlayer || !viewerId) return false
const currentPlayerMeta = playerMetadata[currentPlayer]
return currentPlayerMeta?.userId === viewerId
}, [gameMode, currentPlayer, viewerId, playerMetadata])
// Get current player's emoji for display
const currentPlayerEmoji = useMemo(() => {
if (!currentPlayer) return null
return playerMetadata[currentPlayer]?.emoji || null
}, [currentPlayer, playerMetadata])
// Music context and modal state
const music = useMusic()
const [isMusicModalOpen, setIsMusicModalOpen] = useState(false)
// Get current difficulty level config
const currentDifficultyLevel = useMemo(() => {
const mapDiffConfig =
(selectedMap === 'world' ? WORLD_MAP : USA_MAP).difficultyConfig || DEFAULT_DIFFICULTY_CONFIG
return (
mapDiffConfig.levels.find((level) => level.id === state.difficulty) || mapDiffConfig.levels[0]
)
}, [selectedMap, state.difficulty])
// Parse error message and format based on difficulty config
const formattedError = useMemo(() => {
if (!lastError) return null
// Check for "CLICKED:" prefix which indicates a wrong click
if (lastError.startsWith('CLICKED:')) {
const regionName = lastError.slice('CLICKED:'.length)
if (currentDifficultyLevel?.wrongClickShowsName) {
return `That was ${regionName}`
}
return null // Just show "Wrong!" without region name
}
// Other errors pass through as-is
return lastError
}, [lastError, currentDifficultyLevel])
// During give-up animation, show the given-up region's name instead of the next region
const displayRegionName = isGiveUpAnimating
? (state.giveUpReveal?.regionName ?? currentRegionName)
: currentRegionName
const displayRegionId = isGiveUpAnimating
? (state.giveUpReveal?.regionId ?? currentRegionId)
: currentRegionId
// Get flag emoji for the displayed region (not necessarily the current prompt)
const displayFlagEmoji =
selectedMap === 'world' && displayRegionId ? getCountryFlagEmoji(displayRegionId) : ''
// Get the region's SVG path for the takeover shape display
const displayRegionPath = useMemo(() => {
if (!displayRegionId) return null
const region = mapData.regions.find((r) => r.id === displayRegionId)
return region?.path ?? null
}, [displayRegionId, mapData.regions])
// Ref to hidden path element for accurate getBBox measurement
const hiddenPathRef = useRef<SVGPathElement>(null)
// Accurate bounding box from getBBox() - updated when region changes
const [accurateBBox, setAccurateBBox] = useState<{
x: number
y: number
width: number
height: number
} | null>(null)
// Simplified path for tracer animation - calculated using browser's native path methods
const [simplifiedTracerPaths, setSimplifiedTracerPaths] = useState<string[] | null>(null)
// Measure accurate bounding box AND generate simplified tracer path using hidden SVG
// This ensures part 1 and part 2 use identical positioning
useEffect(() => {
if (hiddenPathRef.current && displayRegionPath) {
// Use requestAnimationFrame to ensure path is rendered
requestAnimationFrame(() => {
if (hiddenPathRef.current) {
const pathEl = hiddenPathRef.current
const bbox = pathEl.getBBox()
setAccurateBBox({
x: bbox.x,
y: bbox.y,
width: bbox.width,
height: bbox.height,
})
// Sample points along the path using browser's native getPointAtLength()
// This correctly handles all SVG path commands
const totalLength = pathEl.getTotalLength()
const numSamples = 500 // Sample more points for better detection of jumps
const allPoints: Array<{ x: number; y: number }> = []
for (let i = 0; i <= numSamples; i++) {
const distance = (i / numSamples) * totalLength
const point = pathEl.getPointAtLength(distance)
allPoints.push({ x: point.x, y: point.y })
}
// Detect jumps between sub-paths and split into separate segments
// A jump is when consecutive points are much farther apart than average
const segments: Array<Array<{ x: number; y: number }>> = []
let currentSegment: Array<{ x: number; y: number }> = [allPoints[0]]
// Calculate average distance between consecutive points
let totalDist = 0
for (let i = 1; i < allPoints.length; i++) {
const dx = allPoints[i].x - allPoints[i - 1].x
const dy = allPoints[i].y - allPoints[i - 1].y
totalDist += Math.sqrt(dx * dx + dy * dy)
}
const avgDist = totalDist / (allPoints.length - 1)
const jumpThreshold = avgDist * 5 // A jump is 5x the average distance
for (let i = 1; i < allPoints.length; i++) {
const dx = allPoints[i].x - allPoints[i - 1].x
const dy = allPoints[i].y - allPoints[i - 1].y
const dist = Math.sqrt(dx * dx + dy * dy)
if (dist > jumpThreshold) {
// This is a jump - save current segment and start new one
if (currentSegment.length > 2) {
segments.push(currentSegment)
}
currentSegment = [allPoints[i]]
} else {
currentSegment.push(allPoints[i])
}
}
// Don't forget the last segment
if (currentSegment.length > 2) {
segments.push(currentSegment)
}
// Simplify each segment - keep separate for simultaneous animations on each island
const tolerance = Math.max(bbox.width, bbox.height) * 0.02 // 2% tolerance (less aggressive)
const simplifiedSegments = segments.map((seg) => simplify(seg, tolerance, true))
// Convert each segment to a separate SVG path string
const pathStrings: string[] = []
let totalSimplifiedPoints = 0
for (const simplified of simplifiedSegments) {
if (simplified.length > 2) {
let pathStr = `M ${simplified[0].x} ${simplified[0].y}`
for (let i = 1; i < simplified.length; i++) {
pathStr += ` L ${simplified[i].x} ${simplified[i].y}`
}
pathStr += ' Z'
pathStrings.push(pathStr)
totalSimplifiedPoints += simplified.length
}
}
setSimplifiedTracerPaths(pathStrings)
console.log('[PathSimplify]', {
regionId: displayRegionId,
totalLength,
sampledPoints: allPoints.length,
segments: segments.length,
simplifiedPoints: totalSimplifiedPoints,
reduction: `${Math.round((1 - totalSimplifiedPoints / allPoints.length) * 100)}%`,
})
}
})
} else {
setAccurateBBox(null)
setSimplifiedTracerPaths(null)
}
}, [displayRegionPath, displayRegionId])
// Get the region's SVG path for puzzle piece animation
// Uses the exact SVG bounding box from getBBox() passed in the target
const puzzlePieceShape = useMemo(() => {
if (!puzzlePieceTarget) return null
const region = mapData.regions.find((r) => r.id === puzzlePieceTarget.regionId)
if (!region?.path) return null
// Use the exact SVG bounding box from getBBox() - this is pixel-perfect
const { x, y, width, height } = puzzlePieceTarget.svgBBox
const viewBox = `${x} ${y} ${width} ${height}`
return {
path: region.path,
viewBox,
}
}, [puzzlePieceTarget, mapData.regions])
// Track if animation is in progress (local state based on timestamp)
const [isAnimating, setIsAnimating] = useState(false)
// Track if we're in the "attention grab" phase for the name display
const [isAttentionPhase, setIsAttentionPhase] = useState(false)
// Name confirmation progress from shared state (synced across sessions)
const confirmedLetterCount = state.nameConfirmationProgress ?? 0
const [nameConfirmed, setNameConfirmed] = useState(false)
// Optimistic letter count ref - prevents race conditions when typing fast
// This is updated immediately on keypress, before server responds
const optimisticLetterCountRef = useRef(confirmedLetterCount)
// Get assistance level config
const assistanceConfig = useMemo(() => {
return getAssistanceLevel(state.assistanceLevel)
}, [state.assistanceLevel])
// Check if name confirmation is required (learning mode)
const requiresNameConfirmation = assistanceConfig.nameConfirmationLetters ?? 0
const isLearningMode = state.assistanceLevel === 'learning'
// Measure the takeover container (region name + instructions) reactively
// react-use-measure handles ResizeObserver automatically
const [takeoverContainerRef, takeoverBounds] = useMeasure()
// Ref to the takeover region shape SVG for capturing source position
const takeoverRegionShapeRef = useRef<SVGSVGElement>(null)
// Track the last puzzlePieceTarget regionId to avoid resetting animation on unrelated re-renders
const lastPuzzlePieceRegionIdRef = useRef<string | null>(null)
// Calculate the safe scale factor based on measured container size
// Automatically updates when container resizes thanks to react-use-measure
const safeScale = useMemo(() => {
if (!currentRegionName || !isLearningMode) return 2.5
if (takeoverBounds.width === 0 || takeoverBounds.height === 0) return 2.5
// Calculate max scale that keeps element within viewport bounds
// Leave 40px padding on each side
const maxWidthScale = (window.innerWidth - 80) / takeoverBounds.width
const maxHeightScale = (window.innerHeight - 80) / takeoverBounds.height
// Use the smaller of width/height constraints, clamped between 1.5 and 3.5
const calculatedScale = Math.min(maxWidthScale, maxHeightScale)
return Math.max(1.5, Math.min(3.5, calculatedScale))
}, [currentRegionName, isLearningMode, takeoverBounds.width, takeoverBounds.height])
// Calculate takeover progress based on letters typed (0 = full takeover, 1 = complete)
// Suppress takeover during give up animation to avoid visual conflict
const takeoverProgress = useMemo(() => {
// During give up animation, suppress takeover (progress = 1 means no takeover)
if (isGiveUpAnimating) return 1
if (!isLearningMode || requiresNameConfirmation === 0) return 1
const progress = Math.min(1, confirmedLetterCount / requiresNameConfirmation)
console.log('[GameInfoPanel] takeoverProgress:', {
confirmedLetterCount,
requiresNameConfirmation,
progress,
stateProgress: state.nameConfirmationProgress,
})
return progress
}, [
isLearningMode,
requiresNameConfirmation,
confirmedLetterCount,
isGiveUpAnimating,
state.nameConfirmationProgress,
])
// Spring animation for scale only - position is handled by CSS centering
const takeoverSpring = useSpring({
scale: safeScale - (safeScale - 1) * takeoverProgress,
config: TAKEOVER_ANIMATION_CONFIG,
})
// Determine if this is a NEW puzzle piece animation (different region or first time)
// This prevents resetting the animation on unrelated re-renders (like cursor movement)
const isNewPuzzlePiece =
puzzlePieceTarget?.sourceRect &&
puzzlePieceTarget.regionId !== lastPuzzlePieceRegionIdRef.current
// Update the ref when we start a new animation
if (isNewPuzzlePiece) {
lastPuzzlePieceRegionIdRef.current = puzzlePieceTarget.regionId
}
// Clear the ref when puzzlePieceTarget becomes null (animation complete)
if (!puzzlePieceTarget && lastPuzzlePieceRegionIdRef.current !== null) {
lastPuzzlePieceRegionIdRef.current = null
}
// Puzzle piece animation spring - animates from takeover position to map position
const puzzlePieceSpring = useSpring({
// Only animate when we have both target and source (sourceRect)
to: puzzlePieceTarget?.sourceRect
? {
// Target: actual screen position of region on map (top-left coords)
x: puzzlePieceTarget.x,
y: puzzlePieceTarget.y,
width: puzzlePieceTarget.width,
height: puzzlePieceTarget.height,
opacity: 1, // Keep visible during animation
}
: {
// Default: centered on screen (fallback)
x: typeof window !== 'undefined' ? (window.innerWidth - 400) / 2 : 200,
y: typeof window !== 'undefined' ? (window.innerHeight - 400) / 2 : 100,
width: 400,
height: 400,
opacity: 1,
},
from: puzzlePieceTarget?.sourceRect
? {
// Start: actual position from takeover screen
x: puzzlePieceTarget.sourceRect.x,
y: puzzlePieceTarget.sourceRect.y,
width: puzzlePieceTarget.sourceRect.width,
height: puzzlePieceTarget.sourceRect.height,
opacity: 1,
}
: undefined,
// Only reset when it's a NEW puzzle piece, not on every re-render
reset: isNewPuzzlePiece,
config: { tension: 120, friction: 18 },
onRest: () => {
if (puzzlePieceTarget) {
// Animation complete - start celebration
setCelebration({
regionId: puzzlePieceTarget.regionId,
regionName: puzzlePieceTarget.regionName,
type: puzzlePieceTarget.celebrationType,
startTime: Date.now(),
})
setPuzzlePieceTarget(null)
}
},
})
// Tracer intensity spring - controls speed, size, opacity, and focus based on letter progress
// 0 letters = slow/big/faint, all letters = fast/laser-focused/bright
// All values smoothly animated via react-spring
const tracerIntensity =
requiresNameConfirmation > 0 ? confirmedLetterCount / requiresNameConfirmation : 0
// Exponential curve for more dramatic pickup (x^3 gives steep curve at the end)
const exponentialIntensity = tracerIntensity ** 2.5
// Heating color interpolation: blue → purple → orange → gold
// Gold at the end matches the celebration styling on the map
const heatStops = [
{ t: 0, r: 59, g: 130, b: 246 }, // Cool blue
{ t: 0.33, r: 168, g: 85, b: 247 }, // Purple (warming)
{ t: 0.66, r: 249, g: 115, b: 22 }, // Orange (hot)
{ t: 1, r: 255, g: 215, b: 0 }, // Gold (matches celebration)
]
// Find which segment we're in and interpolate
const t = tracerIntensity
let heatColors = { r: 59, g: 130, b: 246 }
for (let i = 0; i < heatStops.length - 1; i++) {
if (t >= heatStops[i].t && t <= heatStops[i + 1].t) {
const segmentT = (t - heatStops[i].t) / (heatStops[i + 1].t - heatStops[i].t)
heatColors = {
r: heatStops[i].r + segmentT * (heatStops[i + 1].r - heatStops[i].r),
g: heatStops[i].g + segmentT * (heatStops[i + 1].g - heatStops[i].g),
b: heatStops[i].b + segmentT * (heatStops[i + 1].b - heatStops[i].b),
}
break
}
}
const tracerSpring = useSpring({
// Size multiplier: 1.5 (big) → 0.3 (laser-focused)
sizeScale: 1.5 - exponentialIntensity * 1.2,
// Glow multiplier: 1.5 (soft/large) → 0.4 (concentrated)
glowScale: 1.5 - exponentialIntensity * 1.1,
// Ember size multiplier
emberScale: 1.0 - exponentialIntensity * 0.6,
// Overall opacity: 25% at 0 letters → 100% at all letters (smoothly animated)
overallOpacity: 0.25 + tracerIntensity * 0.75,
// Speed multiplier for duration calculation: 1 (slow) → 200 (blazing fast)
// Using exponential curve: 1 → 5 → 40 → 200
speedMultiplier: 1 + exponentialIntensity * 199,
// Heating border colors (RGB components for smooth interpolation)
heatR: heatColors.r,
heatG: heatColors.g,
heatB: heatColors.b,
// Stroke width increases as it heats up: 2 → 4
strokeWidth: 2 + tracerIntensity * 2,
// Fill opacity increases slightly as it heats up
fillOpacity: 0.3 + tracerIntensity * 0.2,
config: { tension: 180, friction: 18 },
})
// Duration for tracer animation - computed from exponential intensity
// Base duration 15s divided by speed: 15s → 3s → 0.375s → 0.075s (200x faster at max!)
const tracerDuration = 15 / (1 + exponentialIntensity * 199)
// Exponential sparkle counts - dramatic growth but capped for performance
// Embers: 1 → 3 → 8 → 16 (filtered glow, keep lower)
// Flying sparks: 2 → 8 → 24 → 48 (no filter, can have more)
const emberCount =
requiresNameConfirmation > 0 ? [1, 3, 8, 16][Math.min(confirmedLetterCount, 3)] : 1
const sparkCount =
requiresNameConfirmation > 0 ? [2, 8, 24, 48][Math.min(confirmedLetterCount, 3)] : 2
// Whether we're in puzzle piece animation mode (has sourceRect means animation is active)
const isPuzzlePieceAnimating =
puzzlePieceTarget !== null && puzzlePieceTarget.sourceRect !== undefined
// Whether we're in the "fade back in" phase (target set, waiting for sourceRect capture)
const isFadingBackIn = puzzlePieceTarget !== null && puzzlePieceTarget.sourceRect === undefined
// Track if we're showing the laser effect (brief delay after all letters entered)
const [showingLaserEffect, setShowingLaserEffect] = useState(false)
// Memoize whether we're in active takeover mode
// Takeover visible: during typing OR showing laser effect OR fading back in OR during animation
const isInTakeoverLocal =
isLearningMode &&
(takeoverProgress < 1 || showingLaserEffect || isFadingBackIn || isPuzzlePieceAnimating)
const showPulseAnimation = isLearningMode && takeoverProgress < 0.5
// Sync takeover state to context (so MapRenderer can suppress hot/cold feedback)
// Also consider puzzle piece animation as a takeover state
useEffect(() => {
setIsInTakeover(isInTakeoverLocal || isPuzzlePieceAnimating)
}, [isInTakeoverLocal, isPuzzlePieceAnimating, setIsInTakeover])
// Reset local UI state when region changes
// Note: nameConfirmationProgress is reset on the server when prompt changes
useEffect(() => {
if (currentRegionId) {
setNameConfirmed(false)
setShowingLaserEffect(false)
setIsAttentionPhase(true)
// End attention phase after duration
const timeout = setTimeout(() => {
setIsAttentionPhase(false)
}, NAME_ATTENTION_DURATION)
return () => clearTimeout(timeout)
}
}, [currentRegionId])
// Check if all required letters have been confirmed
useEffect(() => {
if (
requiresNameConfirmation > 0 &&
confirmedLetterCount >= requiresNameConfirmation &&
!nameConfirmed
) {
// Start showing laser effect
setShowingLaserEffect(true)
onHintsUnlock?.()
// After 750ms, hide the laser effect and mark as confirmed
const timeout = setTimeout(() => {
setShowingLaserEffect(false)
setNameConfirmed(true)
}, 750)
return () => clearTimeout(timeout)
}
}, [confirmedLetterCount, requiresNameConfirmation, nameConfirmed, onHintsUnlock])
// Sync optimistic ref with server state when it arrives
// This ensures we stay in sync if server rejects a move
useEffect(() => {
optimisticLetterCountRef.current = confirmedLetterCount
}, [confirmedLetterCount])
// Reset optimistic ref when region changes
useEffect(() => {
optimisticLetterCountRef.current = 0
}, [currentRegionName])
// Capture source rect from takeover region shape when puzzlePieceTarget is set
// This provides the starting position for the fly-to-map animation
// Add a delay so the takeover is visible before the animation starts
useEffect(() => {
// Only capture if target is set but doesn't have sourceRect yet
if (puzzlePieceTarget && !puzzlePieceTarget.sourceRect) {
// Brief delay to let the takeover fade back in and be visible
const timeoutId = setTimeout(() => {
if (takeoverRegionShapeRef.current) {
const sourceRect = takeoverRegionShapeRef.current.getBoundingClientRect()
// Update the target with the source rect
setPuzzlePieceTarget((prev) =>
prev && !prev.sourceRect
? {
...prev,
sourceRect: {
x: sourceRect.left,
y: sourceRect.top,
width: sourceRect.width,
height: sourceRect.height,
},
}
: prev
)
}
}, 400) // 400ms delay to show takeover before animation
return () => clearTimeout(timeoutId)
}
}, [puzzlePieceTarget, setPuzzlePieceTarget])
// Listen for keypresses to confirm letters (only when name confirmation is required)
// Dispatches to shared state so all multiplayer sessions see the same progress
useEffect(() => {
if (isSpectator) return
if (requiresNameConfirmation === 0 || nameConfirmed || !currentRegionName) {
return
}
const handleKeyDown = (e: KeyboardEvent) => {
// Ignore if typing in an input or textarea
if (e.target instanceof HTMLInputElement || e.target instanceof HTMLTextAreaElement) {
return
}
// Only accept single character keys (letters only)
const pressedLetter = e.key.toLowerCase()
if (pressedLetter.length !== 1 || !/[a-z]/i.test(pressedLetter)) {
return
}
// In turn-based mode, only allow the current player to type
if (gameMode === 'turn-based' && !isMyTurn) {
setShowNotYourTurn(true)
// Auto-hide the notice after 2 seconds
setTimeout(() => setShowNotYourTurn(false), 2000)
return
}
// Use optimistic count to prevent race conditions when typing fast
const nextLetterIndex = optimisticLetterCountRef.current
if (nextLetterIndex >= requiresNameConfirmation) {
return // Already confirmed all required letters
}
// Get the nth non-space letter (skipping spaces in the name)
// e.g., "US Virgin Islands" → letter 0='U', 1='S', 2='V' (skips the space)
const letterInfo = getNthNonSpaceLetter(currentRegionName, nextLetterIndex)
if (!letterInfo) {
return // No more letters to confirm
}
// Normalize accented letters to base ASCII (e.g., 'é' → 'e', 'ñ' → 'n')
// so users can type region names like "Côte d'Ivoire" or "São Tomé" with a regular keyboard
const expectedLetter = normalizeToBaseLetter(letterInfo.char)
console.log('[LetterConfirm] Keyboard input:', {
pressedLetter,
letterInfo,
expectedLetter,
match: pressedLetter === expectedLetter,
regionName: currentRegionName,
letterIndex: nextLetterIndex,
})
if (pressedLetter === expectedLetter) {
// Optimistically advance count before server responds
optimisticLetterCountRef.current = nextLetterIndex + 1
// Dispatch to shared state - server validates and broadcasts to all sessions
confirmLetter(pressedLetter, nextLetterIndex)
}
// Ignore wrong characters silently (no feedback, no backspace needed)
}
window.addEventListener('keydown', handleKeyDown)
return () => window.removeEventListener('keydown', handleKeyDown)
}, [
isSpectator,
requiresNameConfirmation,
nameConfirmed,
currentRegionName,
confirmLetter,
gameMode,
isMyTurn,
])
// Check if animation is in progress based on timestamp
useEffect(() => {
if (!state.giveUpReveal?.timestamp) {
setIsAnimating(false)
return
}
const elapsed = Date.now() - state.giveUpReveal.timestamp
if (elapsed < GIVE_UP_ANIMATION_DURATION) {
setIsAnimating(true)
// Clear animation flag after remaining time
const timeout = setTimeout(() => {
setIsAnimating(false)
}, GIVE_UP_ANIMATION_DURATION - elapsed)
return () => clearTimeout(timeout)
} else {
setIsAnimating(false)
}
}, [state.giveUpReveal?.timestamp])
// Handle give up with keyboard shortcut (G key)
const handleGiveUp = useCallback(() => {
if (!isAnimating && state.gamePhase === 'playing') {
giveUp()
}
}, [isAnimating, state.gamePhase, giveUp])
// Keyboard shortcut for give up (works even in pointer lock mode)
useEffect(() => {
if (isSpectator) return
const handleKeyDown = (e: KeyboardEvent) => {
// 'G' key for Give Up
if (e.key === 'g' || e.key === 'G') {
// Don't trigger if user is typing in an input
if (e.target instanceof HTMLInputElement || e.target instanceof HTMLTextAreaElement) {
return
}
// Don't trigger if we're waiting for name confirmation letters
if (requiresNameConfirmation > 0 && !nameConfirmed) {
return
}
handleGiveUp()
}
}
window.addEventListener('keydown', handleKeyDown)
return () => window.removeEventListener('keydown', handleKeyDown)
}, [isSpectator, handleGiveUp, requiresNameConfirmation, nameConfirmed])
// Auto-dismiss errors after 3 seconds
useEffect(() => {
if (lastError) {
const timeout = setTimeout(() => clearError(), 3000)
return () => clearTimeout(timeout)
}
}, [lastError, clearError])
// Shared styles for floating panels
const floatingPanelBase = {
backdropFilter: 'blur(12px)',
shadow: 'lg',
zIndex: 50,
} as const
return (
<>
{/* Hidden SVG for accurate getBBox measurement - ensures consistent positioning */}
{displayRegionPath && (
<svg
data-element="hidden-bbox-measure"
style={{
position: 'absolute',
left: '-9999px',
top: '-9999px',
width: '1px',
height: '1px',
overflow: 'hidden',
pointerEvents: 'none',
}}
>
<path ref={hiddenPathRef} d={displayRegionPath} />
</svg>
)}
{/* Global keyframes for animations */}
<style>{`
@keyframes glowPulse {
0%, 100% { box-shadow: 0 0 10px rgba(59, 130, 246, 0.3); }
50% { box-shadow: 0 0 20px rgba(59, 130, 246, 0.6), 0 0 30px rgba(59, 130, 246, 0.3); }
}
@keyframes attentionGrab {
0% {
transform: scale(0.8);
opacity: 0;
}
10% {
transform: scale(1.25);
opacity: 1;
text-shadow: 0 0 20px rgba(59, 130, 246, 0.8), 0 0 40px rgba(59, 130, 246, 0.4);
}
60% {
transform: scale(1.2);
text-shadow: 0 0 15px rgba(59, 130, 246, 0.6), 0 0 30px rgba(59, 130, 246, 0.3);
}
100% {
transform: scale(1);
text-shadow: none;
}
}
@keyframes nameShake {
0%, 100% { transform: translateX(0); }
20% { transform: translateX(-4px); }
40% { transform: translateX(4px); }
60% { transform: translateX(-4px); }
80% { transform: translateX(4px); }
}
@keyframes confirmPop {
0% { transform: scale(1); }
50% { transform: scale(1.1); }
100% { transform: scale(1); }
}
@keyframes slideInFromTop {
0% { transform: translateX(-50%) translateY(-100%); opacity: 0; }
100% { transform: translateX(-50%) translateY(0); opacity: 1; }
}
@keyframes slideInFromBottom {
0% { transform: translateX(-50%) translateY(100%); opacity: 0; }
100% { transform: translateX(-50%) translateY(0); opacity: 1; }
}
@keyframes takeoverPulse {
0%, 100% { opacity: 1; }
50% { opacity: 0.85; }
}
`}</style>
{/* Takeover overlay - contains scrim backdrop, region shape, and takeover text */}
{/* Also shows during puzzle piece animation (silhouette only) */}
<div
data-element="takeover-overlay"
className={css({
position: 'fixed',
top: 0,
left: 0,
right: 0,
bottom: 0,
zIndex: 150,
pointerEvents: 'none',
// Smooth transition for the whole overlay
transition: 'opacity 0.3s ease-out',
})}
style={{
opacity: isInTakeoverLocal || isPuzzlePieceAnimating ? 1 : 0,
}}
>
{/* Backdrop scrim with blur - fade out during puzzle piece animation */}
<div
data-element="takeover-scrim"
className={css({
position: 'absolute',
top: 0,
left: 0,
right: 0,
bottom: 0,
transition: 'opacity 0.3s ease-out',
})}
style={{
backgroundColor: isDark ? 'rgba(0, 0, 0, 0.6)' : 'rgba(255, 255, 255, 0.6)',
backdropFilter: 'blur(8px)',
WebkitBackdropFilter: 'blur(8px)',
// Fade out scrim during puzzle piece animation
opacity: isPuzzlePieceAnimating ? 0 : 1,
}}
/>
{/* Region shape silhouette - shown during takeover, until animation starts */}
{/* Uses accurateBBox from getBBox() for consistent positioning between parts 1 and 2 */}
{displayRegionPath &&
accurateBBox &&
isInTakeoverLocal &&
!isPuzzlePieceAnimating &&
(() => {
// Use puzzlePieceTarget.svgBBox if available (part 2), otherwise use accurateBBox (part 1)
// Both come from getBBox() so positioning should be identical
const bbox = puzzlePieceTarget?.svgBBox ?? accurateBBox
const viewBox = `${bbox.x} ${bbox.y} ${bbox.width} ${bbox.height}`
const aspectRatio = bbox.width / bbox.height
// Calculate container size that fits within 60% of viewport while preserving aspect ratio
const maxSize =
typeof window !== 'undefined'
? Math.min(window.innerWidth, window.innerHeight) * 0.6
: 400
let width: number
let height: number
if (aspectRatio > 1) {
// Wider than tall
width = maxSize
height = maxSize / aspectRatio
} else {
// Taller than wide
height = maxSize
width = maxSize * aspectRatio
}
// Center on screen
const x = typeof window !== 'undefined' ? (window.innerWidth - width) / 2 : 200
const y = typeof window !== 'undefined' ? (window.innerHeight - height) / 2 : 100
// Calculate a reasonable tracer size based on the viewBox dimensions
const tracerSize = Math.max(bbox.width, bbox.height) * 0.03
// Use pre-calculated simplified paths from state (calculated using browser's getPointAtLength)
// Each element is a separate island/segment - we animate all simultaneously
// Fall back to original path if simplified not ready yet
const tracerPaths =
simplifiedTracerPaths && simplifiedTracerPaths.length > 0
? simplifiedTracerPaths
: [displayRegionPath]
return (
<svg
ref={takeoverRegionShapeRef}
data-element="takeover-region-shape"
viewBox={viewBox}
preserveAspectRatio="xMidYMid meet"
style={{
position: 'fixed',
left: `${x}px`,
top: `${y}px`,
width: `${width}px`,
height: `${height}px`,
zIndex: 151,
pointerEvents: 'none',
overflow: 'visible',
}}
>
{/* Definitions for glow effects */}
<defs>
{/* Simplified paths for smooth animation - one per island/segment */}
{tracerPaths.map((path, idx) => (
<path key={`motion-path-${idx}`} id={`tracer-motion-path-${idx}`} d={path} />
))}
</defs>
{/* DEBUG: Render simplified paths visibly (only when visual debug enabled) */}
{isVisualDebugEnabled &&
tracerPaths.map((path, idx) => (
<path
key={`debug-path-${idx}`}
d={path}
fill="none"
stroke="red"
strokeWidth={3}
strokeDasharray="10,5"
vectorEffect="non-scaling-stroke"
opacity={0.8}
/>
))}
<defs>
{/* Glow filter for the main flame */}
<filter id="flame-glow" x="-100%" y="-100%" width="300%" height="300%">
<feGaussianBlur stdDeviation={tracerSize * 1.2} result="blur" />
<feMerge>
<feMergeNode in="blur" />
<feMergeNode in="blur" />
<feMergeNode in="blur" />
<feMergeNode in="SourceGraphic" />
</feMerge>
</filter>
{/* Smaller glow for sparks */}
<filter id="spark-glow" x="-200%" y="-200%" width="500%" height="500%">
<feGaussianBlur stdDeviation={tracerSize * 0.5} result="blur" />
<feMerge>
<feMergeNode in="blur" />
<feMergeNode in="SourceGraphic" />
</feMerge>
</filter>
{/* Fire gradient - hot core to cooler edges */}
<radialGradient id="flame-gradient">
<stop offset="0%" stopColor="#ffffff" stopOpacity="1" />
<stop offset="20%" stopColor="#fffde7" stopOpacity="1" />
<stop offset="40%" stopColor="#ffd54f" stopOpacity="0.95" />
<stop offset="60%" stopColor="#ff9800" stopOpacity="0.85" />
<stop offset="80%" stopColor="#f44336" stopOpacity="0.6" />
<stop offset="100%" stopColor="#d32f2f" stopOpacity="0" />
</radialGradient>
{/* Ember gradient for trailing sparks */}
<radialGradient id="ember-gradient">
<stop offset="0%" stopColor="#ffeb3b" stopOpacity="1" />
<stop offset="50%" stopColor="#ff9800" stopOpacity="0.8" />
<stop offset="100%" stopColor="#ff5722" stopOpacity="0" />
</radialGradient>
</defs>
{/* Region fill and stroke - heats up as letters are typed */}
<animated.path
id="region-outline-path"
d={displayRegionPath}
fill={to(
[
tracerSpring.heatR,
tracerSpring.heatG,
tracerSpring.heatB,
tracerSpring.fillOpacity,
],
(r, g, b, opacity) =>
`rgba(${Math.round(r)}, ${Math.round(g)}, ${Math.round(b)}, ${opacity})`
)}
stroke={to(
[tracerSpring.heatR, tracerSpring.heatG, tracerSpring.heatB],
(r, g, b) => `rgb(${Math.round(r)}, ${Math.round(g)}, ${Math.round(b)})`
)}
strokeWidth={tracerSpring.strokeWidth}
vectorEffect="non-scaling-stroke"
/>
{/* Tracer animation groups - one for each island/segment, all animate simultaneously */}
{tracerPaths.map((_, pathIdx) => (
<animated.g
key={`tracer-${confirmedLetterCount}-${pathIdx}`}
opacity={tracerSpring.overallOpacity}
>
{/* Outer fire glow - size scales with intensity */}
<animated.circle
r={tracerSpring.sizeScale.to((s) => tracerSize * 1.5 * s)}
fill="url(#flame-gradient)"
filter="url(#flame-glow)"
opacity={tracerSpring.glowScale.to((g) => 0.5 + g * 0.2)}
>
<animateMotion dur={`${tracerDuration}s`} repeatCount="indefinite">
<mpath href={`#tracer-motion-path-${pathIdx}`} />
</animateMotion>
</animated.circle>
{/* Main flame body */}
<animated.circle
r={tracerSpring.sizeScale.to((s) => tracerSize * s)}
fill="url(#flame-gradient)"
filter="url(#flame-glow)"
>
<animateMotion dur={`${tracerDuration}s`} repeatCount="indefinite">
<mpath href={`#tracer-motion-path-${pathIdx}`} />
</animateMotion>
</animated.circle>
{/* Hot white core - gets more intense/bright as letters progress */}
<animated.circle
r={tracerSpring.sizeScale.to((s) => tracerSize * 0.35 * (2 - s))}
fill="white"
>
<animateMotion dur={`${tracerDuration}s`} repeatCount="indefinite">
<mpath href={`#tracer-motion-path-${pathIdx}`} />
</animateMotion>
<animate
attributeName="opacity"
values="1;0.85;1;0.9;1"
dur="0.15s"
repeatCount="indefinite"
/>
</animated.circle>
{/* Trailing embers - exponentially increasing count (no filter for performance) */}
{Array.from({ length: emberCount }, (_, i) => {
const offset = (i + 1) / (emberCount + 1) // Spread evenly behind the main flame
return (
<animated.circle
key={`ember-${pathIdx}-${i}`}
r={tracerSpring.emberScale.to(
(e) => tracerSize * (0.6 - (i / emberCount) * 0.35) * e
)}
fill="url(#ember-gradient)"
>
<animateMotion
dur={`${tracerDuration}s`}
repeatCount="indefinite"
begin={`-${offset * tracerDuration * 0.4}s`}
>
<mpath href={`#tracer-motion-path-${pathIdx}`} />
</animateMotion>
<animate
attributeName="opacity"
values="0.9;0.6;0.3;0.1"
dur="0.4s"
repeatCount="indefinite"
/>
</animated.circle>
)
})}
{/* Flying sparks - exponentially increasing count (no filter for performance) */}
{Array.from({ length: sparkCount }, (_, i) => {
const startOffset = i / sparkCount // Distribute evenly around the path
return (
<circle key={`spark-${pathIdx}-${i}`} r={tracerSize * 0.15} fill="#ffeb3b">
<animateMotion
dur={`${tracerDuration}s`}
repeatCount="indefinite"
begin={`${startOffset * tracerDuration}s`}
>
<mpath href={`#tracer-motion-path-${pathIdx}`} />
</animateMotion>
<animate
attributeName="opacity"
values="1;0.8;0.3;0"
dur="0.5s"
repeatCount="indefinite"
begin={`${startOffset * tracerDuration}s`}
/>
</circle>
)
})}
</animated.g>
))}
</svg>
)
})()}
{/* Animated puzzle piece silhouette - flies from center to map position */}
{/* Uses gold styling to match celebration on the map */}
{puzzlePieceShape && isPuzzlePieceAnimating && (
<animated.svg
data-element="puzzle-piece-silhouette"
viewBox={puzzlePieceShape.viewBox}
preserveAspectRatio="none"
style={{
position: 'fixed',
left: puzzlePieceSpring.x.to((x) => `${x}px`),
top: puzzlePieceSpring.y.to((y) => `${y}px`),
width: puzzlePieceSpring.width.to((w) => `${w}px`),
height: puzzlePieceSpring.height.to((h) => `${h}px`),
opacity: puzzlePieceSpring.opacity,
zIndex: 9000,
pointerEvents: 'none',
}}
>
<path
d={puzzlePieceShape.path}
fill="rgba(255, 215, 0, 0.7)"
stroke="rgba(255, 180, 0, 1)"
strokeWidth={3}
vectorEffect="non-scaling-stroke"
/>
</animated.svg>
)}
{/* Takeover text - CSS centered, only scale is animated */}
{/* Hidden during puzzle piece animation */}
{!isPuzzlePieceAnimating && (
<animated.div
data-element="takeover-content"
className={css({
position: 'absolute',
// CSS centering
top: '50%',
left: '50%',
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
transformOrigin: 'center center',
})}
style={{
// Combine centering translation with animated scale
transform: takeoverSpring.scale.to((s) => `translate(-50%, -50%) scale(${s})`),
animation: showPulseAnimation ? 'takeoverPulse 0.8s ease-in-out infinite' : 'none',
}}
>
{/* Region name display */}
<div
data-element="takeover-region-name"
className={css({
fontSize: { base: 'lg', sm: 'xl', md: '2xl' },
fontWeight: 'bold',
color: isDark ? 'white' : 'blue.900',
whiteSpace: 'nowrap',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
gap: { base: '1', sm: '2' },
// Frosted glass backdrop for better contrast
background: isDark ? 'rgba(0, 0, 0, 0.4)' : 'rgba(255, 255, 255, 0.5)',
backdropFilter: 'blur(8px)',
padding: '8px 16px',
borderRadius: '8px',
})}
style={{
// Enhanced multi-layer text shadow for halo effect
textShadow: isDark
? `0 0 8px rgba(0,0,0,0.9),
0 0 16px rgba(0,0,0,0.6),
0 2px 4px rgba(0,0,0,0.9),
-1px -1px 0 rgba(0,0,0,0.6),
1px -1px 0 rgba(0,0,0,0.6),
-1px 1px 0 rgba(0,0,0,0.6),
1px 1px 0 rgba(0,0,0,0.6)`
: '0 2px 4px rgba(0,0,0,0.2)',
}}
>
{displayFlagEmoji && (
<span
className={css({
fontSize: { base: 'lg', sm: 'xl', md: '2xl' },
})}
>
{displayFlagEmoji}
</span>
)}
<span>
{displayRegionName
? (() => {
// Track non-space letter index as we iterate
let nonSpaceIndex = 0
return displayRegionName.split('').map((char, index) => {
const isSpace = char === ' '
const currentNonSpaceIndex = isSpace ? -1 : nonSpaceIndex
// Increment non-space counter AFTER getting current index
if (!isSpace) {
nonSpaceIndex++
}
// Spaces are always shown as confirmed (not underlined, full opacity)
if (isSpace) {
return (
<span
key={index}
className={css({
transition: 'all 0.15s ease-out',
})}
>
{char}
</span>
)
}
// For letters, check confirmation status using non-space index
const needsConfirmation =
!isGiveUpAnimating &&
requiresNameConfirmation > 0 &&
!nameConfirmed &&
currentNonSpaceIndex < requiresNameConfirmation
const isConfirmed = currentNonSpaceIndex < confirmedLetterCount
const isNextToConfirm =
currentNonSpaceIndex === confirmedLetterCount && needsConfirmation
return (
<span
key={index}
className={css({
transition: 'all 0.15s ease-out',
})}
style={{
opacity: needsConfirmation && !isConfirmed ? 0.4 : 1,
textDecoration: isNextToConfirm ? 'underline' : 'none',
textDecorationColor: isNextToConfirm
? isDark
? '#60a5fa'
: '#3b82f6'
: undefined,
textUnderlineOffset: isNextToConfirm ? '4px' : undefined,
}}
>
{char}
</span>
)
})
})()
: '...'}
</span>
</div>
{/* Type-to-unlock instruction */}
{!isGiveUpAnimating && requiresNameConfirmation > 0 && !nameConfirmed && (
<div
data-element="takeover-type-instruction"
className={css({
marginTop: '2',
fontSize: { base: 'sm', sm: 'md' },
color: isDark ? 'amber.300' : 'amber.700',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
gap: '1.5',
})}
>
{/* In turn-based mode, show current player's emoji to indicate whose turn it is */}
{gameMode === 'turn-based' && currentPlayerEmoji ? (
<span>{currentPlayerEmoji}</span>
) : (
<span>⌨️</span>
)}
<span>
{gameMode === 'turn-based' && !isMyTurn
? `Waiting for ${playerMetadata[currentPlayer]?.name || 'player'} to type...`
: `Type the underlined letter${requiresNameConfirmation > 1 ? 's' : ''}`}
</span>
</div>
)}
{/* "Not your turn" notice */}
{showNotYourTurn && (
<div
data-element="not-your-turn-notice"
className={css({
marginTop: '3',
paddingY: '2',
paddingX: '4',
bg: isDark ? 'red.900/80' : 'red.100',
color: isDark ? 'red.200' : 'red.800',
rounded: 'lg',
fontSize: 'sm',
fontWeight: 'medium',
textAlign: 'center',
})}
>
⏳ Not your turn! Wait for{' '}
{playerMetadata[currentPlayer]?.name || 'the other player'}.
</div>
)}
</animated.div>
)}
{/* On-screen keyboard for mobile/touch devices - OUTSIDE animated container so it doesn't scale */}
{!isGiveUpAnimating &&
!isPuzzlePieceAnimating &&
requiresNameConfirmation > 0 &&
!nameConfirmed &&
currentRegionName && (
<div
data-element="mobile-keyboard-container"
className={css({
position: 'fixed',
bottom: '0',
left: '50%',
transform: 'translateX(-50%)',
pointerEvents: 'auto',
zIndex: 160,
paddingBottom: '2',
width: '100%',
maxWidth: '500px',
px: '2',
})}
>
<SimpleLetterKeyboard
uppercase={(() => {
// Check if the next expected letter is uppercase (skipping spaces)
const letterInfo = getNthNonSpaceLetter(currentRegionName, confirmedLetterCount)
if (!letterInfo) return false
return letterInfo.char.toUpperCase() === letterInfo.char
})()}
isDark={isDark}
onKeyPress={(letter) => {
// In turn-based mode, only allow the current player to type
if (gameMode === 'turn-based' && !isMyTurn) {
setShowNotYourTurn(true)
setTimeout(() => setShowNotYourTurn(false), 2000)
return
}
const nextLetterIndex = optimisticLetterCountRef.current
if (nextLetterIndex >= requiresNameConfirmation) return
// Get the nth non-space letter (skipping spaces)
const letterInfo = getNthNonSpaceLetter(currentRegionName, nextLetterIndex)
if (!letterInfo) return
// Normalize accented letters to base ASCII (e.g., 'é' → 'e', 'ñ' → 'n')
const expectedLetter = normalizeToBaseLetter(letterInfo.char)
const pressedLetter = letter.toLowerCase()
console.log('[LetterConfirm] Virtual keyboard:', {
pressedLetter,
letterInfo,
expectedLetter,
match: pressedLetter === expectedLetter,
regionName: currentRegionName,
letterIndex: nextLetterIndex,
})
if (pressedLetter === expectedLetter) {
// Optimistically advance count before server responds
optimisticLetterCountRef.current = nextLetterIndex + 1
// Dispatch to shared state
confirmLetter(pressedLetter, nextLetterIndex)
}
}}
/>
</div>
)}
</div>
{/* TOP-CENTER: Prompt Display - positioned below game nav (~150px) */}
{/* Background fills left-to-right as progress increases */}
<div
data-element="floating-prompt"
className={css({
position: 'absolute',
top: { base: '130px', sm: '150px' },
left: '50%',
transform: 'translateX(-50%)',
width: { base: '92vw', sm: '420px', md: '500px', lg: '560px' },
padding: { base: '2', sm: '3' },
...floatingPanelBase,
border: { base: '2px solid', sm: '3px solid' },
borderColor: 'blue.500',
rounded: { base: 'xl', sm: '2xl' },
textAlign: 'center',
// Overflow handled in inline style to avoid css() recalculation
})}
style={{
animation: 'glowPulse 2s ease-in-out infinite',
overflow: isInTakeoverLocal ? 'visible' : 'hidden',
// Prompt pane stays behind scrim; only takeover-container elevates above
background: isDark
? `linear-gradient(to right, rgba(22, 78, 99, 0.3) ${progress}%, rgba(30, 58, 138, 0.25) ${progress}%)`
: `linear-gradient(to right, rgba(34, 197, 94, 0.25) ${progress}%, rgba(59, 130, 246, 0.2) ${progress}%)`,
}}
>
{/* Remaining count - centered at top */}
<div
data-element="remaining-count"
className={css({
fontSize: { base: 'xs', sm: 'sm' },
fontWeight: 'bold',
color: isDark ? 'cyan.300' : 'cyan.700',
marginBottom: '1',
})}
>
{totalRegions - foundCount} left
</div>
{/* Header row with Find label and controls */}
<div
className={css({
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
marginBottom: '1',
})}
>
<div
className={css({
fontSize: 'xs',
color: isDark ? 'blue.300' : 'blue.700',
fontWeight: 'bold',
textTransform: 'uppercase',
letterSpacing: 'wide',
})}
>
🎯 Find
</div>
{/* Right side controls: Give Up button and Guidance dropdown */}
<div
className={css({
display: 'flex',
alignItems: 'center',
gap: '1.5',
})}
>
{/* Give Up button - subtle design */}
<button
onClick={(e) => {
e.stopPropagation()
if (!isGiveUpAnimating) {
giveUp()
}
}}
disabled={isGiveUpAnimating}
data-action="give-up"
title={
requiresNameConfirmation > 0 && !nameConfirmed
? 'Type letters first'
: "Press 'G' to give up"
}
style={{
...(isGiveUpAnimating
? { opacity: 0.4, cursor: 'not-allowed', transform: 'none' }
: {}),
}}
className={css({
padding: '1 2.5',
fontSize: 'xs',
cursor: isGiveUpAnimating ? 'not-allowed' : 'pointer',
bg: 'transparent',
color: isDark ? 'blue.400' : 'blue.600',
rounded: 'md',
border: '1px solid',
borderColor: isDark ? 'blue.700' : 'blue.300',
fontWeight: 'medium',
transition: 'all 0.15s',
opacity: 0.7,
_hover: {
opacity: 1,
borderColor: isDark ? 'blue.500' : 'blue.400',
},
_disabled: {
opacity: 0.4,
cursor: 'not-allowed',
},
})}
>
{(() => {
const isCooperativeMultiplayer =
gameMode === 'cooperative' && activeUserIds.length > 1
const hasLocalSessionVoted = viewerId && giveUpVotes.includes(viewerId)
const voteCount = giveUpVotes.length
const totalSessions = activeUserIds.length
// Show (G) shortcut hint only when not waiting for name confirmation
const showShortcut = !(requiresNameConfirmation > 0 && !nameConfirmed)
if (isCooperativeMultiplayer) {
if (hasLocalSessionVoted) {
return `✓ ${voteCount}/${totalSessions}`
}
if (voteCount > 0) {
return `Give Up ${voteCount}/${totalSessions}`
}
}
return showShortcut ? 'Give Up (G)' : 'Give Up'
})()}
</button>
{/* Guidance dropdown - only show if there are options to configure */}
{shouldShowGuidanceDropdown(assistanceConfig) && (
<DropdownMenu.Root>
<DropdownMenu.Trigger asChild>
<button
data-action="guidance-dropdown"
title="Guidance settings"
className={css({
paddingY: '1',
paddingX: '2',
fontSize: 'xs',
cursor: 'pointer',
bg: 'transparent',
color: isDark ? 'blue.400' : 'blue.600',
rounded: 'md',
border: '1px solid',
borderColor: isDark ? 'blue.700' : 'blue.300',
fontWeight: 'medium',
transition: 'all 0.15s',
opacity: 0.7,
display: 'flex',
alignItems: 'center',
gap: '1',
_hover: {
opacity: 1,
borderColor: isDark ? 'blue.500' : 'blue.400',
},
})}
>
<span>⚙️</span>
<svg
className={css({ w: '3', h: '3' })}
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M19 9l-7 7-7-7"
/>
</svg>
</button>
</DropdownMenu.Trigger>
<DropdownMenu.Portal>
<DropdownMenu.Content
data-element="guidance-dropdown-content"
className={css({
bg: isDark ? 'gray.800' : 'white',
border: '1px solid',
borderColor: isDark ? 'gray.700' : 'gray.200',
rounded: 'lg',
shadow: 'lg',
padding: '2',
minWidth: '160px',
zIndex: 1000,
})}
sideOffset={5}
align="end"
>
{/* Auto-Show Hints toggle - only if hints are available */}
{shouldShowAutoHintToggle(assistanceConfig) &&
(() => {
const isLocked = requiresNameConfirmation > 0 && !nameConfirmed
return (
<DropdownMenu.CheckboxItem
data-setting="auto-hint"
checked={autoHint}
disabled={isLocked}
onCheckedChange={() => !isLocked && onAutoHintToggle()}
className={css({
display: 'flex',
alignItems: 'center',
gap: '2',
padding: '2',
fontSize: 'xs',
cursor: isLocked ? 'not-allowed' : 'pointer',
rounded: 'md',
color: isLocked
? isDark
? 'gray.500'
: 'gray.400'
: isDark
? 'gray.200'
: 'gray.700',
outline: 'none',
opacity: isLocked ? 0.6 : 1,
_hover: isLocked
? {}
: {
bg: isDark ? 'gray.700' : 'gray.100',
},
_focus: isLocked
? {}
: {
bg: isDark ? 'gray.700' : 'gray.100',
},
})}
>
{isLocked ? (
<span>🔒</span>
) : (
<DropdownMenu.ItemIndicator>
<span>✓</span>
</DropdownMenu.ItemIndicator>
)}
<span
className={css({
marginLeft: isLocked || autoHint ? '0' : '4',
})}
>
💡 Auto-Show Hints
</span>
</DropdownMenu.CheckboxItem>
)
})()}
{/* Auto-speak toggle - only if speech supported AND hints available */}
{isSpeechSupported &&
shouldShowAutoSpeakToggle(assistanceConfig) &&
(() => {
const isLocked = requiresNameConfirmation > 0 && !nameConfirmed
return (
<DropdownMenu.CheckboxItem
data-setting="auto-speak"
checked={autoSpeak}
disabled={isLocked}
onCheckedChange={() => !isLocked && onAutoSpeakToggle()}
className={css({
display: 'flex',
alignItems: 'center',
gap: '2',
padding: '2',
fontSize: 'xs',
cursor: isLocked ? 'not-allowed' : 'pointer',
rounded: 'md',
color: isLocked
? isDark
? 'gray.500'
: 'gray.400'
: isDark
? 'gray.200'
: 'gray.700',
outline: 'none',
opacity: isLocked ? 0.6 : 1,
_hover: isLocked
? {}
: {
bg: isDark ? 'gray.700' : 'gray.100',
},
_focus: isLocked
? {}
: {
bg: isDark ? 'gray.700' : 'gray.100',
},
})}
>
{isLocked ? (
<span>🔒</span>
) : (
<DropdownMenu.ItemIndicator>
<span>✓</span>
</DropdownMenu.ItemIndicator>
)}
<span
className={css({
marginLeft: isLocked || autoSpeak ? '0' : '4',
})}
>
🔈 Auto Speak
</span>
</DropdownMenu.CheckboxItem>
)
})()}
{/* Hot/Cold toggle - only if available */}
{showHotCold &&
(() => {
const isLocked = requiresNameConfirmation > 0 && !nameConfirmed
return (
<>
<DropdownMenu.Separator
className={css({
height: '1px',
bg: isDark ? 'gray.700' : 'gray.200',
marginY: '1',
marginX: '0',
})}
/>
<DropdownMenu.CheckboxItem
data-setting="hot-cold"
checked={hotColdEnabled}
disabled={isLocked}
onCheckedChange={() => !isLocked && onHotColdToggle?.()}
className={css({
display: 'flex',
alignItems: 'center',
gap: '2',
padding: '2',
fontSize: 'xs',
cursor: isLocked ? 'not-allowed' : 'pointer',
rounded: 'md',
color: isLocked
? isDark
? 'gray.500'
: 'gray.400'
: isDark
? 'gray.200'
: 'gray.700',
outline: 'none',
opacity: isLocked ? 0.6 : 1,
_hover: isLocked
? {}
: {
bg: isDark ? 'gray.700' : 'gray.100',
},
_focus: isLocked
? {}
: {
bg: isDark ? 'gray.700' : 'gray.100',
},
})}
>
{isLocked ? (
<span>🔒</span>
) : (
<DropdownMenu.ItemIndicator>
<span>✓</span>
</DropdownMenu.ItemIndicator>
)}
<span
className={css({
marginLeft: isLocked || hotColdEnabled ? '0' : '4',
})}
>
{hotColdEnabled ? '🔥' : '❄️'} Hot/Cold
</span>
</DropdownMenu.CheckboxItem>
</>
)
})()}
{/* Music settings - always available */}
<DropdownMenu.Separator
className={css({
height: '1px',
bg: isDark ? 'gray.700' : 'gray.200',
marginY: '1',
marginX: '0',
})}
/>
<DropdownMenu.Item
data-action="open-music-settings"
onSelect={() => setIsMusicModalOpen(true)}
className={css({
display: 'flex',
alignItems: 'center',
gap: '2',
padding: '2',
fontSize: 'xs',
cursor: 'pointer',
rounded: 'md',
color: isDark ? 'gray.200' : 'gray.700',
outline: 'none',
_hover: {
bg: isDark ? 'gray.700' : 'gray.100',
},
_focus: {
bg: isDark ? 'gray.700' : 'gray.100',
},
})}
>
<span>{music.isPlaying ? '🎵' : '🔇'}</span>
<span>Music Settings</span>
</DropdownMenu.Item>
</DropdownMenu.Content>
</DropdownMenu.Portal>
</DropdownMenu.Root>
)}
</div>
</div>
{/* Region name container - ref used for measuring position for takeover */}
{/* Content hidden during takeover (shown in overlay instead) */}
<div
ref={takeoverContainerRef}
data-element="region-name-container"
className={css({
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
position: 'relative',
})}
style={{
// Hide during takeover since it's shown in the overlay
visibility: isInTakeoverLocal ? 'hidden' : 'visible',
}}
>
{/* Region name display */}
<div
data-element="region-name-display"
className={css({
fontSize: { base: 'lg', sm: 'xl', md: '2xl' },
fontWeight: 'bold',
color: isDark ? 'white' : 'blue.900',
whiteSpace: 'nowrap',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
gap: { base: '1', sm: '2' },
})}
style={{
textShadow: isDark ? '0 2px 4px rgba(0,0,0,0.3)' : 'none',
}}
>
{displayFlagEmoji && (
<span
className={css({
fontSize: { base: 'lg', sm: 'xl', md: '2xl' },
})}
>
{displayFlagEmoji}
</span>
)}
<span>
{displayRegionName
? (() => {
// Track non-space letter index as we iterate
let nonSpaceIndex = 0
return displayRegionName.split('').map((char, index) => {
const isSpace = char === ' '
const currentNonSpaceIndex = isSpace ? -1 : nonSpaceIndex
// Increment non-space counter AFTER getting current index
if (!isSpace) {
nonSpaceIndex++
}
// Spaces are always shown as confirmed (not underlined, full opacity)
if (isSpace) {
return (
<span
key={index}
className={css({
transition: 'all 0.15s ease-out',
})}
>
{char}
</span>
)
}
// For letters, check confirmation status using non-space index
const needsConfirmation =
!isGiveUpAnimating &&
requiresNameConfirmation > 0 &&
!nameConfirmed &&
currentNonSpaceIndex < requiresNameConfirmation
const isConfirmed = currentNonSpaceIndex < confirmedLetterCount
const isNextToConfirm =
currentNonSpaceIndex === confirmedLetterCount && needsConfirmation
return (
<span
key={index}
className={css({ transition: 'all 0.15s ease-out' })}
style={{
opacity: needsConfirmation && !isConfirmed ? 0.4 : 1,
textDecoration: isNextToConfirm ? 'underline' : 'none',
textDecorationColor: isNextToConfirm
? isDark
? '#60a5fa'
: '#3b82f6'
: undefined,
textUnderlineOffset: isNextToConfirm ? '4px' : undefined,
}}
>
{char}
</span>
)
})
})()
: '...'}
</span>
</div>
{/* Type-to-unlock instruction */}
{!isGiveUpAnimating && requiresNameConfirmation > 0 && !nameConfirmed && (
<div
data-element="type-to-unlock"
className={css({
marginTop: '2',
fontSize: { base: 'sm', sm: 'md' },
color: isDark ? 'amber.300' : 'amber.700',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
gap: '1.5',
})}
>
{/* In turn-based mode, show current player's emoji to indicate whose turn it is */}
{gameMode === 'turn-based' && currentPlayerEmoji ? (
<span>{currentPlayerEmoji}</span>
) : (
<span>⌨️</span>
)}
<span>
{gameMode === 'turn-based' && !isMyTurn
? `Waiting for ${playerMetadata[currentPlayer]?.name || 'player'} to type...`
: `Type the underlined letter${requiresNameConfirmation > 1 ? 's' : ''}`}
</span>
</div>
)}
</div>
{/* Inline hint - shown after name is confirmed (or always in non-learning modes) */}
{currentHint && (requiresNameConfirmation === 0 || nameConfirmed) && (
<div
data-element="inline-hint"
className={css({
marginTop: '2',
fontSize: 'md',
color: isDark ? 'blue.300' : 'blue.700',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
gap: '1.5',
whiteSpace: 'nowrap',
overflow: 'hidden',
maxWidth: '100%',
})}
>
{/* Speaker button - subtle styling */}
{isSpeechSupported ? (
<button
onClick={(e) => {
e.stopPropagation()
if (isSpeaking) {
onStopSpeaking()
} else {
onSpeak()
}
}}
data-action="speak-hint"
title={isSpeaking ? 'Stop speaking' : 'Read hint aloud'}
className={css({
background: 'transparent',
border: 'none',
padding: '0',
cursor: 'pointer',
fontSize: 'inherit',
lineHeight: 'inherit',
color: 'inherit',
opacity: isSpeaking ? 1 : 0.7,
transition: 'opacity 0.2s',
_hover: { opacity: 1 },
flexShrink: 0,
})}
>
{isSpeaking ? '⏹️' : '🔈'}
</button>
) : (
<span className={css({ opacity: 0.7 })}>💡</span>
)}
<span
className={css({
overflow: 'hidden',
textOverflow: 'ellipsis',
})}
>
{currentHint}
</span>
</div>
)}
{/* Voting status for cooperative mode */}
{gameMode === 'cooperative' &&
activeUserIds.length > 1 &&
giveUpVotes.length > 0 &&
giveUpVotes.length < activeUserIds.length &&
viewerId &&
giveUpVotes.includes(viewerId) && (
<div
data-element="give-up-voters"
className={css({
marginTop: '2',
fontSize: 'xs',
color: isDark ? 'yellow.300' : 'yellow.700',
textAlign: 'center',
})}
>
Waiting for {activeUserIds.length - giveUpVotes.length} other{' '}
{activeUserIds.length - giveUpVotes.length === 1 ? 'player' : 'players'}
...
</div>
)}
</div>
{/* BOTTOM-CENTER: Error Banner (toast-style) */}
{lastError && (
<div
data-element="floating-error"
className={css({
position: 'absolute',
bottom: { base: '2', sm: '4' },
left: '50%',
transform: 'translateX(-50%)',
paddingY: '2',
paddingX: '4',
bg: 'red.100/95',
color: 'red.900',
rounded: 'xl',
border: '2px solid',
borderColor: 'red.500',
display: 'flex',
alignItems: 'center',
gap: '2',
fontSize: 'sm',
...floatingPanelBase,
maxWidth: { base: 'calc(100% - 16px)', sm: '400px' },
})}
style={{
animation: 'slideInFromBottom 0.3s ease-out',
}}
>
<span>⚠️</span>
<div className={css({ flex: 1, fontWeight: 'bold' })}>
Wrong!{formattedError ? ` ${formattedError}` : ''}
</div>
<button
onClick={clearError}
className={css({
padding: '1',
fontSize: 'xs',
cursor: 'pointer',
fontWeight: 'bold',
color: 'red.700',
_hover: { color: 'red.900' },
})}
>
✕
</button>
</div>
)}
{/* Music Control Modal */}
<MusicControlModal open={isMusicModalOpen} onOpenChange={setIsMusicModalOpen} />
</>
)
}
|