All files / web/src/arcade-games/card-sorting/components PlayingPhaseDrag.tsx

0% Statements 0/2069
0% Branches 0/1
0% Functions 0/1
0% Lines 0/2069

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           
'use client'

import { css } from '../../../../styled-system/css'
import { useCardSorting } from '../Provider'
import { useState, useEffect, useRef, useCallback } from 'react'
import { useSpring, animated, to } from '@react-spring/web'
import { useViewport } from '@/contexts/ViewportContext'
import type { SortingCard } from '../types'

// Add celebration animations
if (typeof document !== 'undefined') {
  const style = document.createElement('style')
  style.textContent = `
    @keyframes celebrate {
      0%, 100% {
        transform: scale(1) rotate(0deg);
        background-position: 0% 50%;
      }
      25% {
        transform: scale(1.2) rotate(-10deg);
        background-position: 100% 50%;
      }
      50% {
        transform: scale(1.3) rotate(0deg);
        background-position: 0% 50%;
      }
      75% {
        transform: scale(1.2) rotate(10deg);
        background-position: 100% 50%;
      }
    }
    @keyframes pulse {
      0%, 100% { opacity: 1; transform: scale(1); }
      50% { opacity: 0.8; transform: scale(1.1); }
    }
    @keyframes correctArrowGlow {
      0%, 100% {
        filter: brightness(1) drop-shadow(0 0 8px rgba(34, 197, 94, 0.6));
        opacity: 0.9;
      }
      50% {
        filter: brightness(1.3) drop-shadow(0 0 15px rgba(34, 197, 94, 0.9));
        opacity: 1;
      }
    }
    @keyframes correctBadgePulse {
      0%, 100% {
        transform: translate(-50%, -50%) scale(1);
      }
      50% {
        transform: translate(-50%, -50%) scale(1.15);
      }
    }
  `
  document.head.appendChild(style)
}

interface CardState {
  x: number // % of viewport width (0-100)
  y: number // % of viewport height (0-100)
  rotation: number // degrees
  zIndex: number
}

/**
 * Infers the sequence order of cards based on their spatial positions.
 * Uses a horizontal left-to-right ordering with some vertical tolerance.
 *
 * Algorithm:
 * 1. Group cards into horizontal "lanes" (vertical tolerance)
 * 2. Within each lane, sort left-to-right by x position
 * 3. Sort lanes top-to-bottom
 * 4. Flatten to get final sequence
 *
 * Note: Positions are in viewport percentages (0-100)
 */
function inferSequenceFromPositions(
  cardStates: Map<string, CardState>,
  allCards: SortingCard[]
): SortingCard[] {
  const VERTICAL_TOLERANCE = 8 // Cards within 8% of viewport height are in the same "lane"

  // Get all positioned cards
  const positionedCards = allCards
    .map((card) => {
      const state = cardStates.get(card.id)
      if (!state) return null
      return { card, ...state }
    })
    .filter(
      (
        item
      ): item is {
        card: SortingCard
        x: number
        y: number
        rotation: number
        zIndex: number
      } => item !== null
    )

  if (positionedCards.length === 0) return []

  // Sort by x position first
  const sortedByX = [...positionedCards].sort((a, b) => a.x - b.x)

  // Group into lanes
  const lanes: (typeof positionedCards)[] = []

  for (const item of sortedByX) {
    // Find a lane this card fits into (similar y position)
    const matchingLane = lanes.find((lane) => {
      // Check if card's y is within tolerance of lane's average y
      const laneAvgY = lane.reduce((sum, c) => sum + c.y, 0) / lane.length
      return Math.abs(item.y - laneAvgY) < VERTICAL_TOLERANCE
    })

    if (matchingLane) {
      matchingLane.push(item)
    } else {
      lanes.push([item])
    }
  }

  // Sort lanes top-to-bottom
  lanes.sort((laneA, laneB) => {
    const avgYA = laneA.reduce((sum, c) => sum + c.y, 0) / laneA.length
    const avgYB = laneB.reduce((sum, c) => sum + c.y, 0) / laneB.length
    return avgYA - avgYB
  })

  // Within each lane, sort left-to-right
  for (const lane of lanes) {
    lane.sort((a, b) => a.x - b.x)
  }

  // Flatten to get final sequence
  return lanes.flat().map((item) => item.card)
}

/**
 * Continuous curved path showing the full sequence of cards
 */
function ContinuousSequencePath({
  cardStates,
  sequence,
  correctOrder,
  viewportWidth,
  viewportHeight,
  spectatorEducationalMode,
  isSpectating,
}: {
  cardStates: Map<string, CardState>
  sequence: SortingCard[]
  correctOrder: SortingCard[]
  viewportWidth: number
  viewportHeight: number
  spectatorEducationalMode: boolean
  isSpectating: boolean
}) {
  if (sequence.length < 2) return null

  // Card dimensions (base size)
  const CARD_WIDTH = 140
  const CARD_HEIGHT = 180
  const CARD_HALF_WIDTH = CARD_WIDTH / 2
  const CARD_HALF_HEIGHT = CARD_HEIGHT / 2

  // Helper to check if a card is part of the correct prefix or suffix (and thus scaled to 50%)
  const isCardCorrect = (card: SortingCard): boolean => {
    const positionInSequence = sequence.findIndex((c) => c.id === card.id)
    if (positionInSequence < 0) return false

    // Check if card is part of correct prefix
    let isInCorrectPrefix = true
    for (let i = 0; i <= positionInSequence; i++) {
      if (sequence[i]?.id !== correctOrder[i]?.id) {
        isInCorrectPrefix = false
        break
      }
    }

    // Check if card is part of correct suffix
    let isInCorrectSuffix = true
    const offsetFromEnd = sequence.length - 1 - positionInSequence
    for (let i = 0; i <= offsetFromEnd; i++) {
      const seqIdx = sequence.length - 1 - i
      const correctIdx = correctOrder.length - 1 - i
      if (sequence[seqIdx]?.id !== correctOrder[correctIdx]?.id) {
        isInCorrectSuffix = false
        break
      }
    }

    const isCorrect = isInCorrectPrefix || isInCorrectSuffix
    return isSpectating ? spectatorEducationalMode && isCorrect : isCorrect
  }

  // Get all card positions (card centers) with scale information
  const cardCenters = sequence
    .map((card) => {
      const state = cardStates.get(card.id)
      if (!state) return null
      const scale = isCardCorrect(card) ? 0.5 : 1
      return {
        x: (state.x / 100) * viewportWidth + CARD_HALF_WIDTH,
        y: (state.y / 100) * viewportHeight + CARD_HALF_HEIGHT,
        cardId: card.id,
        scale,
      }
    })
    .filter((p): p is { x: number; y: number; cardId: string; scale: number } => p !== null)

  if (cardCenters.length < 2) return null

  // Helper function to find intersection of line from center in direction (dx, dy) with card rectangle
  const findCardEdgePoint = (
    centerX: number,
    centerY: number,
    dx: number,
    dy: number,
    scale: number
  ): { x: number; y: number } => {
    // Normalize direction
    const length = Math.sqrt(dx * dx + dy * dy)
    const ndx = dx / length
    const ndy = dy / length

    // Apply scale to card dimensions
    const scaledHalfWidth = CARD_HALF_WIDTH * scale
    const scaledHalfHeight = CARD_HALF_HEIGHT * scale

    // Find which edge we hit first
    const txRight = ndx > 0 ? scaledHalfWidth / ndx : Number.POSITIVE_INFINITY
    const txLeft = ndx < 0 ? -scaledHalfWidth / ndx : Number.POSITIVE_INFINITY
    const tyBottom = ndy > 0 ? scaledHalfHeight / ndy : Number.POSITIVE_INFINITY
    const tyTop = ndy < 0 ? -scaledHalfHeight / ndy : Number.POSITIVE_INFINITY

    const t = Math.min(txRight, txLeft, tyBottom, tyTop)

    return {
      x: centerX + ndx * t,
      y: centerY + ndy * t,
    }
  }

  // Calculate edge points for each card based on direction to next/prev card
  const positions = cardCenters.map((center, i) => {
    if (i === 0) {
      // First card: direction towards next card
      const next = cardCenters[i + 1]
      const dx = next.x - center.x
      const dy = next.y - center.y
      return findCardEdgePoint(center.x, center.y, dx, dy, center.scale)
    }
    if (i === cardCenters.length - 1) {
      // Last card: direction from previous card
      const prev = cardCenters[i - 1]
      const dx = center.x - prev.x
      const dy = center.y - prev.y
      return findCardEdgePoint(center.x, center.y, dx, dy, center.scale)
    }
    // Middle cards: average direction between prev and next
    const prev = cardCenters[i - 1]
    const next = cardCenters[i + 1]
    const dx = next.x - prev.x
    const dy = next.y - prev.y
    return findCardEdgePoint(center.x, center.y, dx, dy, center.scale)
  })

  if (positions.length < 2) return null

  // Build continuous curved path using cubic bezier curves with smooth transitions
  // Use Catmull-Rom style control points for smooth continuous curves
  let pathD = `M ${positions[0].x} ${positions[0].y}`

  for (let i = 0; i < positions.length - 1; i++) {
    const current = positions[i]
    const next = positions[i + 1]

    // Get previous and next-next points for tangent calculation (or use current/next if at edges)
    const prev = i > 0 ? positions[i - 1] : current
    const nextNext = i < positions.length - 2 ? positions[i + 2] : next

    // Calculate tangent vectors for smooth curve
    // Tangent at current point: direction from prev to next
    const tension = 0.3 // Adjust this to control curve tightness (0 = loose, 1 = tight)

    const tangent1X = (next.x - prev.x) * tension
    const tangent1Y = (next.y - prev.y) * tension

    // Tangent at next point: direction from current to nextNext
    const tangent2X = (nextNext.x - current.x) * tension
    const tangent2Y = (nextNext.y - current.y) * tension

    // Control points for cubic bezier
    const cp1X = current.x + tangent1X
    const cp1Y = current.y + tangent1Y
    const cp2X = next.x - tangent2X
    const cp2Y = next.y - tangent2Y

    pathD += ` C ${cp1X} ${cp1Y}, ${cp2X} ${cp2Y}, ${next.x} ${next.y}`
  }

  // Calculate badge positions along the actual drawn path at arc-length midpoint
  const badges: Array<{
    x: number
    y: number
    number: number
    isCorrect: boolean
  }> = []

  // Helper to evaluate cubic bezier at parameter t
  const evalCubicBezier = (
    p0x: number,
    p0y: number,
    cp1x: number,
    cp1y: number,
    cp2x: number,
    cp2y: number,
    p1x: number,
    p1y: number,
    t: number
  ) => {
    const mt = 1 - t
    return {
      x: mt * mt * mt * p0x + 3 * mt * mt * t * cp1x + 3 * mt * t * t * cp2x + t * t * t * p1x,
      y: mt * mt * mt * p0y + 3 * mt * mt * t * cp1y + 3 * mt * t * t * cp2y + t * t * t * p1y,
    }
  }

  for (let i = 0; i < positions.length - 1; i++) {
    const current = positions[i]
    const next = positions[i + 1]

    // Use the actual edge-based control points (same as the drawn path)
    const prev = i > 0 ? positions[i - 1] : current
    const nextNext = i < positions.length - 2 ? positions[i + 2] : next
    const tension = 0.3

    const tangent1X = (next.x - prev.x) * tension
    const tangent1Y = (next.y - prev.y) * tension
    const tangent2X = (nextNext.x - current.x) * tension
    const tangent2Y = (nextNext.y - current.y) * tension

    const cp1X = current.x + tangent1X
    const cp1Y = current.y + tangent1Y
    const cp2X = next.x - tangent2X
    const cp2Y = next.y - tangent2Y

    // Sample the curve at many points to calculate arc length
    const samples = 50
    const arcLengths: number[] = [0]
    let prevPoint = { x: current.x, y: current.y }

    for (let j = 1; j <= samples; j++) {
      const t = j / samples
      const point = evalCubicBezier(current.x, current.y, cp1X, cp1Y, cp2X, cp2Y, next.x, next.y, t)
      const segmentLength = Math.sqrt((point.x - prevPoint.x) ** 2 + (point.y - prevPoint.y) ** 2)
      arcLengths.push(arcLengths[arcLengths.length - 1] + segmentLength)
      prevPoint = point
    }

    // Find the t value that corresponds to 50% of arc length
    const totalArcLength = arcLengths[arcLengths.length - 1]
    const targetLength = totalArcLength * 0.5

    let tAtMidArc = 0.5
    for (let j = 0; j < arcLengths.length - 1; j++) {
      if (arcLengths[j] <= targetLength && targetLength <= arcLengths[j + 1]) {
        const ratio = (targetLength - arcLengths[j]) / (arcLengths[j + 1] - arcLengths[j])
        tAtMidArc = (j + ratio) / samples
        break
      }
    }

    // Evaluate curve at the arc-length midpoint
    const midPoint = evalCubicBezier(
      current.x,
      current.y,
      cp1X,
      cp1Y,
      cp2X,
      cp2Y,
      next.x,
      next.y,
      tAtMidArc
    )

    // Calculate tangent at this t for perpendicular offset
    const mt = 1 - tAtMidArc
    const tangentAtMidX =
      3 * mt * mt * (cp1X - current.x) +
      6 * mt * tAtMidArc * (cp2X - cp1X) +
      3 * tAtMidArc * tAtMidArc * (next.x - cp2X)
    const tangentAtMidY =
      3 * mt * mt * (cp1Y - current.y) +
      6 * mt * tAtMidArc * (cp2Y - cp1Y) +
      3 * tAtMidArc * tAtMidArc * (next.y - cp2Y)

    // Small perpendicular offset so badges sit slightly off the curve line
    const perpX = -tangentAtMidY
    const perpY = tangentAtMidX
    const perpLength = Math.sqrt(perpX * perpX + perpY * perpY)
    const offsetDistance = 5 // Small offset

    const finalX = midPoint.x + (perpX / perpLength) * offsetDistance
    const finalY = midPoint.y + (perpY / perpLength) * offsetDistance

    // Check if this connection is correct
    const isCorrect =
      correctOrder[i]?.id === sequence[i].id && correctOrder[i + 1]?.id === sequence[i + 1].id

    badges.push({
      x: finalX,
      y: finalY,
      number: i + 1,
      isCorrect,
    })
  }

  // Check if entire sequence is correct for coloring
  const allCorrect = sequence.every((card, idx) => correctOrder[idx]?.id === card.id)

  return (
    <div
      style={{
        position: 'absolute',
        left: 0,
        top: 0,
        width: '100%',
        height: '100%',
        pointerEvents: 'none',
        zIndex: 0,
      }}
    >
      <svg
        style={{
          position: 'absolute',
          left: 0,
          top: 0,
          width: '100%',
          height: '100%',
          overflow: 'visible',
        }}
      >
        {/* Continuous curved path */}
        <path
          d={pathD}
          stroke={allCorrect ? 'rgba(34, 197, 94, 0.8)' : 'rgba(251, 146, 60, 0.7)'}
          strokeWidth={allCorrect ? '8' : '6'}
          fill="none"
          style={{
            filter: allCorrect ? 'drop-shadow(0 0 8px rgba(34, 197, 94, 0.6))' : 'none',
          }}
        />

        {/* Arrowhead at the end */}
        {(() => {
          const i = positions.length - 2 // Last segment index
          const current = positions[i]
          const next = positions[i + 1]

          // Recalculate control points for last segment
          const prev = i > 0 ? positions[i - 1] : current
          const nextNext = next // At the end, so nextNext is same as next
          const tension = 0.3

          const tangent1X = (next.x - prev.x) * tension
          const tangent1Y = (next.y - prev.y) * tension
          const tangent2X = (nextNext.x - current.x) * tension
          const tangent2Y = (nextNext.y - current.y) * tension

          const cp1X = current.x + tangent1X
          const cp1Y = current.y + tangent1Y
          const cp2X = next.x - tangent2X
          const cp2Y = next.y - tangent2Y

          // Calculate tangent at t=1 (end of curve) for cubic bezier
          // Derivative: B'(t) = 3(1-t)²(P1-P0) + 6(1-t)t(P2-P1) + 3t²(P3-P2)
          // At t=1: B'(1) = 3(P3-P2)
          const tangentX = 3 * (next.x - cp2X)
          const tangentY = 3 * (next.y - cp2Y)
          const arrowAngle = Math.atan2(tangentY, tangentX)

          // Arrow triangle
          const tipX = next.x
          const tipY = next.y
          const baseX = tipX - Math.cos(arrowAngle) * 10
          const baseY = tipY - Math.sin(arrowAngle) * 10
          const left = `${baseX + Math.cos(arrowAngle + Math.PI / 2) * 6},${baseY + Math.sin(arrowAngle + Math.PI / 2) * 6}`
          const right = `${baseX + Math.cos(arrowAngle - Math.PI / 2) * 6},${baseY + Math.sin(arrowAngle - Math.PI / 2) * 6}`

          return (
            <polygon
              points={`${tipX},${tipY} ${left} ${right}`}
              fill={allCorrect ? 'rgba(34, 197, 94, 0.9)' : 'rgba(251, 146, 60, 0.8)'}
            />
          )
        })()}
      </svg>

      {/* Number badges */}
      {badges.map((badge) => (
        <div
          key={badge.number}
          style={{
            position: 'absolute',
            left: `${badge.x}px`,
            top: `${badge.y}px`,
            transform: 'translate(-50%, -50%)',
            background: badge.isCorrect ? '#22c55e' : '#f97316',
            color: 'white',
            borderRadius: '50%',
            width: '32px',
            height: '32px',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            fontSize: '14px',
            fontWeight: 'bold',
            border: '3px solid white',
            boxShadow: badge.isCorrect
              ? '0 0 0 2px #22c55e, 0 4px 8px rgba(0, 0, 0, 0.3)'
              : '0 0 0 2px #f97316, 0 4px 8px rgba(0, 0, 0, 0.3)',
            animation: badge.isCorrect ? 'correctBadgePulse 1.5s ease-in-out infinite' : 'none',
          }}
        >
          {badge.number}
        </div>
      ))}
    </div>
  )
}

/**
 * Animated arrow component using react-spring for smooth movements
 */
function AnimatedArrow({
  fromCard,
  toCard,
  isCorrect,
  sequenceNumber,
  isDragging,
  isResizing,
  viewportWidth,
  viewportHeight,
}: {
  fromCard: CardState
  toCard: CardState
  isCorrect: boolean
  sequenceNumber: number
  isDragging: boolean
  isResizing: boolean
  viewportWidth: number
  viewportHeight: number
}) {
  // Convert percentage positions to pixels
  const fromPx = {
    x: (fromCard.x / 100) * viewportWidth,
    y: (fromCard.y / 100) * viewportHeight,
  }
  const toPx = {
    x: (toCard.x / 100) * viewportWidth,
    y: (toCard.y / 100) * viewportHeight,
  }

  // Calculate arrow position (from center of current card to center of next card)
  const fromX = fromPx.x + 70 // 70 = half of card width (140px)
  const fromY = fromPx.y + 90 // 90 = half of card height (180px)
  const toX = toPx.x + 70
  const toY = toPx.y + 90

  // Calculate angle and distance
  const dx = toX - fromX
  const dy = toY - fromY
  const angle = Math.atan2(dy, dx) * (180 / Math.PI)
  const distance = Math.sqrt(dx * dx + dy * dy)

  // Use spring animation for arrow position and size
  // Disable animation when dragging or resizing
  const springProps = useSpring({
    fromX,
    fromY,
    distance,
    angle,
    immediate: isDragging || isResizing,
    config: {
      tension: 300,
      friction: 30,
    },
  })

  // Don't draw arrow if cards are too close
  if (distance < 80) return null

  // Calculate control point for bezier curve (perpendicular to line, offset by 30px)
  const midX = (fromX + toX) / 2
  const midY = (fromY + toY) / 2
  const perpAngle = angle + 90 // Perpendicular to the line
  const curveOffset = 30 // How much to curve (in pixels)
  const controlX = midX + Math.cos((perpAngle * Math.PI) / 180) * curveOffset
  const controlY = midY + Math.sin((perpAngle * Math.PI) / 180) * curveOffset

  // Calculate arrowhead position and angle at the end of the curve
  // For a quadratic bezier, the tangent at t=1 is: 2*(P2 - P1)
  const tangentX = toX - controlX
  const tangentY = toY - controlY
  const arrowAngle = Math.atan2(tangentY, tangentX) * (180 / Math.PI)

  return (
    <animated.div
      style={{
        position: 'absolute',
        left: 0,
        top: 0,
        width: '100%',
        height: '100%',
        pointerEvents: 'none',
        zIndex: 0,
      }}
    >
      <svg
        style={{
          position: 'absolute',
          left: 0,
          top: 0,
          width: '100%',
          height: '100%',
          overflow: 'visible',
        }}
      >
        {/* Curved line using quadratic bezier */}
        <animated.path
          d={to(
            [springProps.fromX, springProps.fromY, springProps.distance, springProps.angle],
            (fx, fy, dist, ang) => {
              // Recalculate curve with animated values
              const tx = fx + Math.cos((ang * Math.PI) / 180) * dist
              const ty = fy + Math.sin((ang * Math.PI) / 180) * dist
              const mx = (fx + tx) / 2
              const my = (fy + ty) / 2
              const perpAng = ang + 90
              const cx = mx + Math.cos((perpAng * Math.PI) / 180) * curveOffset
              const cy = my + Math.sin((perpAng * Math.PI) / 180) * curveOffset
              return `M ${fx} ${fy} Q ${cx} ${cy} ${tx} ${ty}`
            }
          )}
          stroke={isCorrect ? 'rgba(34, 197, 94, 0.8)' : 'rgba(251, 146, 60, 0.7)'}
          strokeWidth={isCorrect ? '4' : '3'}
          fill="none"
          style={{
            filter: isCorrect ? 'drop-shadow(0 0 8px rgba(34, 197, 94, 0.6))' : 'none',
          }}
        />

        {/* Arrowhead */}
        <animated.polygon
          points={to(
            [springProps.fromX, springProps.fromY, springProps.distance, springProps.angle],
            (fx, fy, dist, ang) => {
              // Recalculate end position and angle
              const tx = fx + Math.cos((ang * Math.PI) / 180) * dist
              const ty = fy + Math.sin((ang * Math.PI) / 180) * dist
              const mx = (fx + tx) / 2
              const my = (fy + ty) / 2
              const perpAng = ang + 90
              const cx = mx + Math.cos((perpAng * Math.PI) / 180) * curveOffset
              const cy = my + Math.sin((perpAng * Math.PI) / 180) * curveOffset
              const tangX = tx - cx
              const tangY = ty - cy
              const aAngle = Math.atan2(tangY, tangX)

              // Arrow points relative to tip
              const tipX = tx
              const tipY = ty
              const baseX = tipX - Math.cos(aAngle) * 10
              const baseY = tipY - Math.sin(aAngle) * 10
              const left = `${baseX + Math.cos(aAngle + Math.PI / 2) * 6},${baseY + Math.sin(aAngle + Math.PI / 2) * 6}`
              const right = `${baseX + Math.cos(aAngle - Math.PI / 2) * 6},${baseY + Math.sin(aAngle - Math.PI / 2) * 6}`
              return `${tipX},${tipY} ${left} ${right}`
            }
          )}
          fill={isCorrect ? 'rgba(34, 197, 94, 0.9)' : 'rgba(251, 146, 60, 0.8)'}
        />
      </svg>

      {/* Sequence number badge */}
      <animated.div
        style={{
          position: 'absolute',
          left: to(
            [springProps.fromX, springProps.fromY, springProps.distance, springProps.angle],
            (fx, fy, dist, ang) => {
              const tx = fx + Math.cos((ang * Math.PI) / 180) * dist
              const mx = (fx + tx) / 2
              const perpAng = ang + 90
              const cx = mx + Math.cos((perpAng * Math.PI) / 180) * curveOffset
              return `${cx}px`
            }
          ),
          top: to(
            [springProps.fromX, springProps.fromY, springProps.distance, springProps.angle],
            (fx, fy, dist, ang) => {
              const tx = fx + Math.cos((ang * Math.PI) / 180) * dist
              const ty = fy + Math.sin((ang * Math.PI) / 180) * dist
              const my = (fy + ty) / 2
              const perpAng = ang + 90
              const cy = my + Math.sin((perpAng * Math.PI) / 180) * curveOffset
              return `${cy}px`
            }
          ),
          transform: 'translate(-50%, -50%)',
          background: isCorrect ? 'rgba(34, 197, 94, 0.95)' : 'rgba(251, 146, 60, 0.95)',
          color: 'white',
          borderRadius: '50%',
          width: '24px',
          height: '24px',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          fontSize: '12px',
          fontWeight: 'bold',
          border: '2px solid white',
          boxShadow: isCorrect ? '0 0 12px rgba(34, 197, 94, 0.6)' : '0 2px 4px rgba(0,0,0,0.2)',
          animation: isCorrect ? 'correctBadgePulse 1.5s ease-in-out infinite' : 'none',
        }}
      >
        {sequenceNumber}
      </animated.div>
    </animated.div>
  )
}

/**
 * Animated card component using react-spring for smooth movements
 */
function AnimatedCard({
  card,
  cardState,
  isDragging,
  isResizing,
  isSpectating,
  isCorrect,
  draggedByPlayerId,
  localPlayerId,
  players,
  viewportWidth,
  viewportHeight,
  onPointerDown,
  onPointerMove,
  onPointerUp,
}: {
  card: SortingCard
  cardState: CardState
  isDragging: boolean
  isResizing: boolean
  isSpectating: boolean
  isCorrect: boolean
  draggedByPlayerId?: string
  localPlayerId?: string
  players: Map<string, { id: string; name: string; emoji: string }>
  viewportWidth: number
  viewportHeight: number
  onPointerDown: (e: React.PointerEvent) => void
  onPointerMove: (e: React.PointerEvent) => void
  onPointerUp: (e: React.PointerEvent) => void
}) {
  // Convert percentage position to pixels for rendering
  const pixelPos = {
    x: (cardState.x / 100) * viewportWidth,
    y: (cardState.y / 100) * viewportHeight,
  }

  // Determine if card is in correct prefix or suffix position
  // These cards should be scaled down to 50% and faded to 50% opacity
  const isInCorrectPosition = (() => {
    // For AnimatedCard, we need to recalculate since we don't have inferredSequence here
    // This is a simplified check - we'll need to pass this as a prop or recalculate
    return isCorrect
  })()

  // Use spring animation for position, rotation, scale, and opacity
  // Disable animation when:
  // - User is dragging (for immediate response on position/rotation)
  // - Viewport is resizing (for instant repositioning)
  const springProps = useSpring({
    left: pixelPos.x,
    top: pixelPos.y,
    rotation: cardState.rotation,
    scale: isInCorrectPosition ? 0.5 : 1,
    opacity: isInCorrectPosition ? 0.5 : 1,
    immediate: (key) => {
      // Scale and opacity always animate smoothly
      if (key === 'scale' || key === 'opacity') return false
      // Position and rotation are immediate when dragging or resizing
      return isDragging || isResizing
    },
    config: {
      tension: 300,
      friction: 30,
    },
  })

  return (
    <animated.div
      onPointerDown={onPointerDown}
      onPointerMove={onPointerMove}
      onPointerUp={onPointerUp}
      className={css({
        position: 'absolute',
        width: '140px',
        height: '180px',
        cursor: isSpectating ? 'default' : 'grab',
        touchAction: 'none',
        userSelect: 'none',
        transition: 'box-shadow 0.2s ease',
        borderRadius: '12px',
        overflow: 'hidden',
      })}
      style={{
        left: springProps.left.to((val) => `${val}px`),
        top: springProps.top.to((val) => `${val}px`),
        transform: to(
          [springProps.rotation, springProps.scale],
          (r, s) => `rotate(${r}deg) scale(${s})`
        ),
        opacity: springProps.opacity,
        zIndex: cardState.zIndex,
        boxShadow: isDragging ? '0 20px 40px rgba(0, 0, 0, 0.3)' : '0 4px 8px rgba(0, 0, 0, 0.15)',
      }}
    >
      <div
        className={css({
          width: '100%',
          height: '100%',
          background: 'white',
          borderRadius: '12px',
          border: isCorrect ? '3px solid #22c55e' : '3px solid #0369a1',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          padding: '12px',
          boxSizing: 'border-box',
          overflow: 'hidden',
          // Clip content to border-box so rounded corners work properly
          backgroundClip: 'border-box',
        })}
        dangerouslySetInnerHTML={{ __html: card.svgContent }}
      />

      {/* Player emoji overlay when card is being dragged by ANOTHER player */}
      {draggedByPlayerId &&
        draggedByPlayerId !== localPlayerId &&
        (() => {
          const player = players.get(draggedByPlayerId)
          if (!player) return null

          return (
            <div
              style={{
                position: 'absolute',
                top: 0,
                left: 0,
                right: 0,
                bottom: 0,
                borderRadius: '12px',
                background: 'rgba(59, 130, 246, 0.15)',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                fontSize: '120px',
                zIndex: 10,
                pointerEvents: 'none',
                opacity: 0.3,
              }}
            >
              {player.emoji}
            </div>
          )
        })()}
    </animated.div>
  )
}

export function PlayingPhaseDrag() {
  const {
    state,
    insertCard,
    checkSolution,
    goToSetup,
    updateCardPositions,
    canCheckSolution,
    elapsedTime,
    isSpectating,
    localPlayerId,
    players,
  } = useCardSorting()

  // Spectator educational mode (show correctness indicators)
  const [spectatorEducationalMode, setSpectatorEducationalMode] = useState(false)
  // Spectator stats sidebar collapsed state
  const [spectatorStatsCollapsed, setSpectatorStatsCollapsed] = useState(false)

  // Activity feed notifications
  interface ActivityNotification {
    id: string
    playerId: string
    playerEmoji: string
    playerName: string
    action: string
    timestamp: number
  }
  const [activityFeed, setActivityFeed] = useState<ActivityNotification[]>([])
  const activityIdCounter = useRef(0)

  // Perfect sequence countdown (auto-submit after 3-2-1)
  const [perfectCountdown, setPerfectCountdown] = useState<number | null>(null)

  const containerRef = useRef<HTMLDivElement>(null)
  const dragStateRef = useRef<{
    cardId: string
    offsetX: number
    offsetY: number
    startX: number
    startY: number
    initialRotation: number
  } | null>(null)

  // Generate a stable unique ID for this browser window/tab
  // This allows us to identify our own position updates when they echo back from the server
  const windowIdRef = useRef<string>()
  if (!windowIdRef.current) {
    windowIdRef.current = `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`
  }

  // Track card positions and visual states (UI only - not game state)
  const [cardStates, setCardStates] = useState<Map<string, CardState>>(new Map())
  const [draggingCardId, setDraggingCardId] = useState<string | null>(null)
  const [nextZIndex, setNextZIndex] = useState(1)

  // Track viewport dimensions for responsive positioning
  // Get viewport dimensions (uses mock dimensions in preview mode)
  const viewport = useViewport()

  // For spectators, reduce dimensions to account for panels
  const getEffectiveViewportWidth = () => {
    const baseWidth = viewport.width
    // Sidebar is hidden on mobile (< 768px), narrower on desktop
    if (isSpectating && !spectatorStatsCollapsed && baseWidth >= 768) {
      return baseWidth - 240 // Subtract stats sidebar width on desktop
    }
    return baseWidth
  }

  const getEffectiveViewportHeight = () => {
    const baseHeight = viewport.height
    const baseWidth = viewport.width
    if (isSpectating) {
      // Banner is 170px on mobile (130px mini nav + 40px spectator banner), 56px on desktop
      return baseHeight - (baseWidth < 768 ? 170 : 56)
    }
    return baseHeight
  }

  const [viewportDimensions, setViewportDimensions] = useState({
    width: getEffectiveViewportWidth(),
    height: getEffectiveViewportHeight(),
  })

  // Track if we're currently resizing to disable spring animations
  const [isResizing, setIsResizing] = useState(false)
  const resizeTimeoutRef = useRef<NodeJS.Timeout | null>(null)

  // Throttle position updates during drag (every 100ms)
  const lastSyncTimeRef = useRef<number>(0)

  // Track when we're waiting to check solution
  const [waitingToCheck, setWaitingToCheck] = useState(false)
  const cardsToInsertRef = useRef<SortingCard[]>([])
  const currentInsertIndexRef = useRef(0)

  // Helper to add activity notifications (only in collaborative mode)
  const addActivityNotification = useCallback(
    (playerId: string, action: string) => {
      if (state.gameMode !== 'collaborative') return
      if (playerId === localPlayerId) return // Don't show notifications for own actions

      const player = players.get(playerId)
      if (!player) return

      const notification: ActivityNotification = {
        id: `activity-${activityIdCounter.current++}`,
        playerId,
        playerEmoji: player.emoji,
        playerName: player.name,
        action,
        timestamp: Date.now(),
      }

      setActivityFeed((prev) => [...prev, notification])
    },
    [state.gameMode, localPlayerId, players]
  )

  // Auto-dismiss notifications after 3 seconds
  useEffect(() => {
    if (activityFeed.length === 0) return

    const timeout = setTimeout(() => {
      const now = Date.now()
      setActivityFeed((prev) => prev.filter((n) => now - n.timestamp < 3000))
    }, 100) // Check every 100ms for smooth removal

    return () => clearTimeout(timeout)
  }, [activityFeed])

  // Track previous state for detecting changes
  const prevDraggingPlayersRef = useRef<Set<string>>(new Set())

  // Detect state changes and generate activity notifications
  useEffect(() => {
    // Only track in collaborative mode
    if (state.gameMode !== 'collaborative') return
    if (!state.cardPositions) return

    // Detect who is currently dragging cards
    const currentlyDragging = new Set<string>()
    for (const pos of state.cardPositions) {
      if (pos.draggedByPlayerId && pos.draggedByPlayerId !== localPlayerId) {
        currentlyDragging.add(pos.draggedByPlayerId)
      }
    }

    // Detect new players starting to drag (activity notification)
    for (const playerId of currentlyDragging) {
      if (!prevDraggingPlayersRef.current.has(playerId)) {
        addActivityNotification(playerId, 'is moving cards')
      }
    }

    prevDraggingPlayersRef.current = currentlyDragging
  }, [state.cardPositions, state.gameMode, localPlayerId, addActivityNotification])

  // Handle viewport resize
  useEffect(() => {
    const handleResize = () => {
      // Set resizing flag to disable spring animations
      setIsResizing(true)

      // Update viewport dimensions immediately (accounting for spectator panels)
      setViewportDimensions({
        width: getEffectiveViewportWidth(),
        height: getEffectiveViewportHeight(),
      })

      // Clear any existing timeout
      if (resizeTimeoutRef.current) {
        clearTimeout(resizeTimeoutRef.current)
      }

      // After 150ms of no resize events, re-enable spring animations
      resizeTimeoutRef.current = setTimeout(() => {
        setIsResizing(false)
      }, 150)
    }

    window.addEventListener('resize', handleResize)
    return () => {
      window.removeEventListener('resize', handleResize)
      if (resizeTimeoutRef.current) {
        clearTimeout(resizeTimeoutRef.current)
      }
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  // Update viewport dimensions when spectator panels change
  useEffect(() => {
    setViewportDimensions({
      width: getEffectiveViewportWidth(),
      height: getEffectiveViewportHeight(),
    })
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isSpectating, spectatorStatsCollapsed])

  // Initialize card positions when game starts or restarts
  useEffect(() => {
    // Reset when entering playing phase or when cards change
    const allCards = [
      ...state.availableCards,
      ...state.placedCards.filter((c): c is SortingCard => c !== null),
    ]

    // Only initialize if we have cards and either:
    // 1. No card states exist yet, OR
    // 2. The number of cards has changed (new game started)
    const shouldInitialize =
      allCards.length > 0 && (cardStates.size === 0 || cardStates.size !== allCards.length)

    if (!shouldInitialize) return

    const newStates = new Map<string, CardState>()

    // Check if we have server positions to restore from
    const hasServerPositions = state.cardPositions && state.cardPositions.length === allCards.length

    allCards.forEach((card, index) => {
      const serverPos = state.cardPositions?.find((p) => p.cardId === card.id)

      if (hasServerPositions && serverPos) {
        // Restore from server (already in percentages)
        newStates.set(card.id, {
          x: serverPos.x,
          y: serverPos.y,
          rotation: serverPos.rotation,
          zIndex: serverPos.zIndex,
        })
      } else {
        // Generate scattered positions that look like cards thrown on a table
        // Card is ~140px wide on ~1000px viewport = ~14% of width
        // Card is ~180px tall on ~800px viewport = ~22.5% of height
        const xMargin = 5 // 5% margin on sides
        const yMargin = 15 // 15% margin for top UI

        // Create a more natural distribution by using clusters
        // Divide the play area into a rough grid, then add randomness
        const numCards = allCards.length
        const cols = Math.ceil(Math.sqrt(numCards * 1.5)) // Slightly wider grid
        const rows = Math.ceil(numCards / cols)

        const row = Math.floor(index / cols)
        const col = index % cols

        // Available space after margins
        const availableWidth = 100 - 2 * xMargin - 14
        const availableHeight = 100 - yMargin - 22.5

        // Grid cell size
        const cellWidth = availableWidth / cols
        const cellHeight = availableHeight / rows

        // Base position in grid (centered in cell)
        const baseX = xMargin + col * cellWidth + cellWidth / 2 - 7 // -7 to center card
        const baseY = yMargin + row * cellHeight + cellHeight / 2 - 11.25 // -11.25 to center card

        // Add significant randomness to make it look scattered (±40% of cell size)
        const offsetX = (Math.random() - 0.5) * cellWidth * 0.8
        const offsetY = (Math.random() - 0.5) * cellHeight * 0.8

        // Ensure we stay within bounds
        const x = Math.max(xMargin, Math.min(100 - 14 - xMargin, baseX + offsetX))
        const y = Math.max(yMargin, Math.min(100 - 22.5, baseY + offsetY))

        // More varied rotation for natural look
        const rotation = (Math.random() - 0.5) * 40 // -20 to 20 degrees

        // Randomize z-index for natural stacking
        const zIndex = Math.floor(Math.random() * numCards)

        newStates.set(card.id, { x, y, rotation, zIndex })
      }
    })

    setCardStates(newStates)
    setNextZIndex(Math.max(...Array.from(newStates.values()).map((s) => s.zIndex)) + 1)

    // If we generated new positions (not restored from server), send them to server
    if (!hasServerPositions && !isSpectating) {
      const positions = Array.from(newStates.entries()).map(([id, cardState]) => ({
        cardId: id,
        x: cardState.x,
        y: cardState.y,
        rotation: cardState.rotation,
        zIndex: cardState.zIndex,
        // Mark with our window ID to identify echoes
        draggedByWindowId: windowIdRef.current,
      }))
      updateCardPositions(positions)
    }
  }, [
    state.availableCards.length,
    state.placedCards.length,
    state.gameStartTime,
    state.cardPositions?.length,
    cardStates.size,
    isSpectating,
    updateCardPositions,
  ])

  // Sync server position updates (for spectators and multi-window sync)
  useEffect(() => {
    if (!state.cardPositions || state.cardPositions.length === 0) return
    if (cardStates.size === 0) return

    // Check if any updates originated from this window - if so, skip the entire batch
    // This prevents replaying our own movements when they echo back from the server
    const hasOurUpdates = state.cardPositions.some(
      (pos) => pos.draggedByWindowId === windowIdRef.current
    )
    if (hasOurUpdates) return

    // Check if server positions differ from current positions
    let needsUpdate = false
    const newStates = new Map(cardStates)

    for (const serverPos of state.cardPositions) {
      const currentState = cardStates.get(serverPos.cardId)
      if (!currentState) continue

      // Compare percentages directly (tolerance: 0.5%)
      if (
        Math.abs(currentState.x - serverPos.x) > 0.5 ||
        Math.abs(currentState.y - serverPos.y) > 0.5 ||
        Math.abs(currentState.rotation - serverPos.rotation) > 1 ||
        currentState.zIndex !== serverPos.zIndex
      ) {
        needsUpdate = true
        newStates.set(serverPos.cardId, {
          x: serverPos.x,
          y: serverPos.y,
          rotation: serverPos.rotation,
          zIndex: serverPos.zIndex,
        })
      }
    }

    if (needsUpdate && !draggingCardId) {
      // Only apply server updates if not currently dragging
      setCardStates(newStates)
    }
  }, [state.cardPositions, draggingCardId, cardStates])

  // Infer sequence from card positions
  const inferredSequence = inferSequenceFromPositions(cardStates, [
    ...state.availableCards,
    ...state.placedCards.filter((c): c is SortingCard => c !== null),
  ])

  // Format time display
  const formatTime = (seconds: number) => {
    const m = Math.floor(seconds / 60)
    const s = seconds % 60
    return `${m}:${s.toString().padStart(2, '0')}`
  }

  // Handle pointer down (start drag)
  const handlePointerDown = (e: React.PointerEvent, cardId: string) => {
    if (isSpectating) return

    const target = e.currentTarget as HTMLElement
    target.setPointerCapture(e.pointerId)

    // Get current card state to calculate proper offset
    const currentCard = cardStates.get(cardId)
    if (!currentCard) return

    // Calculate offset from card's actual position (in pixels) to pointer
    // This accounts for rotation and prevents position jump
    const cardPixelX = (currentCard.x / 100) * viewportDimensions.width
    const cardPixelY = (currentCard.y / 100) * viewportDimensions.height
    const offsetX = e.clientX - cardPixelX
    const offsetY = e.clientY - cardPixelY

    dragStateRef.current = {
      cardId,
      offsetX,
      offsetY,
      startX: e.clientX,
      startY: e.clientY,
      initialRotation: currentCard.rotation,
    }

    setDraggingCardId(cardId)

    // Bring card to front
    setCardStates((prev) => {
      const newStates = new Map(prev)
      const cardState = newStates.get(cardId)
      if (cardState) {
        newStates.set(cardId, { ...cardState, zIndex: nextZIndex })
      }
      return newStates
    })
    setNextZIndex((prev) => prev + 1)
  }

  // Handle pointer move (dragging)
  const handlePointerMove = (e: React.PointerEvent, cardId: string) => {
    if (!dragStateRef.current || dragStateRef.current.cardId !== cardId) return

    const { offsetX, offsetY } = dragStateRef.current

    // Calculate new position in pixels
    const newXPx = e.clientX - offsetX
    const newYPx = e.clientY - offsetY

    // Convert to percentages
    const viewportWidth = viewport.width
    const viewportHeight = viewport.height
    const newX = (newXPx / viewportWidth) * 100
    const newY = (newYPx / viewportHeight) * 100

    // Calculate rotation based on drag velocity, adding to initial rotation
    const dragDeltaX = e.clientX - dragStateRef.current.startX
    const dragRotation = Math.max(-15, Math.min(15, dragDeltaX * 0.05))
    const rotation = dragStateRef.current.initialRotation + dragRotation

    setCardStates((prev) => {
      const newStates = new Map(prev)
      const cardState = newStates.get(cardId)
      if (cardState) {
        newStates.set(cardId, {
          ...cardState,
          x: newX,
          y: newY,
          rotation,
        })

        // Send real-time position updates (throttled to every 100ms)
        if (!isSpectating) {
          const now = Date.now()
          if (now - lastSyncTimeRef.current > 100) {
            lastSyncTimeRef.current = now
            const positions = Array.from(newStates.entries()).map(([id, state]) => ({
              cardId: id,
              x: state.x,
              y: state.y,
              rotation: state.rotation,
              zIndex: state.zIndex,
              // Mark this card as being dragged by local player
              draggedByPlayerId: id === cardId ? localPlayerId : undefined,
              // Mark with our window ID to identify echoes
              draggedByWindowId: windowIdRef.current,
            }))
            updateCardPositions(positions)
          }
        }
      }
      return newStates
    })
  }

  // Handle pointer up (end drag)
  const handlePointerUp = (e: React.PointerEvent, cardId: string) => {
    if (!dragStateRef.current || dragStateRef.current.cardId !== cardId) return

    const target = e.currentTarget as HTMLElement
    target.releasePointerCapture(e.pointerId)

    // Reset rotation to slight random tilt
    const updatedStates = new Map(cardStates)
    const cardState = updatedStates.get(cardId)
    if (cardState) {
      updatedStates.set(cardId, {
        ...cardState,
        rotation: Math.random() * 10 - 5,
      })
      setCardStates(updatedStates)

      // Sync positions to server (already in percentages)
      if (!isSpectating) {
        const positions = Array.from(updatedStates.entries()).map(([id, state]) => ({
          cardId: id,
          x: state.x,
          y: state.y,
          rotation: state.rotation,
          zIndex: state.zIndex,
          // Clear draggedByPlayerId when drag ends
          draggedByPlayerId: undefined,
          // Mark with our window ID to identify echoes
          draggedByWindowId: windowIdRef.current,
        }))
        updateCardPositions(positions)
      }
    }

    dragStateRef.current = null
    setDraggingCardId(null)
  }

  // For drag mode, check solution is available when we have a valid inferred sequence
  const canCheckSolutionDrag = inferredSequence.length === state.cardCount

  // Real-time check: is the current sequence correct?
  const isSequenceCorrect =
    canCheckSolutionDrag &&
    inferredSequence.every((card, index) => {
      const correctCard = state.correctOrder[index]
      return correctCard && card.id === correctCard.id
    })

  // Start countdown when sequence is perfect
  useEffect(() => {
    if (isSequenceCorrect && !isSpectating) {
      // Start countdown from 3
      setPerfectCountdown(3)
    } else {
      // Reset countdown if sequence is no longer perfect
      setPerfectCountdown(null)
    }
  }, [isSequenceCorrect, isSpectating])

  // Countdown timer effect
  useEffect(() => {
    if (perfectCountdown === null) return
    if (perfectCountdown <= 0) {
      // Auto-submit when countdown reaches 0
      handleCheckSolution()
      setPerfectCountdown(null)
      return
    }

    // Decrement every 1.5 seconds
    const timer = setTimeout(() => {
      setPerfectCountdown((prev) => (prev !== null ? prev - 1 : null))
    }, 1500)

    return () => clearTimeout(timer)
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [perfectCountdown])

  // Watch for server confirmations and insert next card or check solution
  useEffect(() => {
    if (!waitingToCheck) return

    const cardsToInsert = cardsToInsertRef.current
    const currentIndex = currentInsertIndexRef.current

    console.log('[PlayingPhaseDrag] useEffect check:', {
      waitingToCheck,
      currentIndex,
      totalCards: cardsToInsert.length,
      canCheckSolution,
    })

    // If all cards have been sent, wait for server to confirm all are placed
    if (currentIndex >= cardsToInsert.length) {
      if (canCheckSolution) {
        console.log('[PlayingPhaseDrag] ✅ Server confirmed all cards placed, checking solution')
        setWaitingToCheck(false)
        cardsToInsertRef.current = []
        currentInsertIndexRef.current = 0
        checkSolution()
      }
      return
    }

    // Send next card
    const card = cardsToInsert[currentIndex]
    const position = inferredSequence.findIndex((c) => c.id === card.id)
    console.log(
      `[PlayingPhaseDrag] 📥 Inserting card ${currentIndex + 1}/${cardsToInsert.length}: ${card.id} at position ${position}`
    )
    insertCard(card.id, position)
    currentInsertIndexRef.current++
  }, [waitingToCheck, canCheckSolution, checkSolution, insertCard, inferredSequence])

  // Custom check solution that uses the inferred sequence
  const handleCheckSolution = () => {
    if (isSpectating) return
    if (!canCheckSolutionDrag) return

    // Send the complete inferred sequence to the server
    checkSolution(inferredSequence)
  }

  return (
    <div
      className={css({
        width: '100%',
        height: '100%',
        position: 'fixed',
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
      })}
    >
      {/* Spectator Banner */}
      {isSpectating && (
        <div
          className={css({
            position: 'fixed',
            top: { base: '130px', md: 0 },
            left: 0,
            right: 0,
            height: { base: '40px', md: '56px' },
            background: 'linear-gradient(135deg, #6366f1, #8b5cf6)',
            color: 'white',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'space-between',
            padding: { base: '0 8px', md: '0 24px' },
            zIndex: 100,
            boxShadow: '0 2px 8px rgba(0, 0, 0, 0.15)',
            gap: { base: '8px', md: '16px' },
          })}
        >
          {/* Player info */}
          <div
            className={css({
              display: 'flex',
              alignItems: 'center',
              gap: { base: '6px', md: '12px' },
              fontSize: { base: '12px', md: '16px' },
              fontWeight: 600,
            })}
          >
            <span className={css({ display: { base: 'none', sm: 'inline' } })}>👀 Spectating:</span>
            <span>
              {state.playerMetadata.emoji} {state.playerMetadata.name}
            </span>
          </div>

          {/* Progress */}
          <div
            className={css({
              display: 'flex',
              alignItems: 'center',
              gap: { base: '8px', md: '16px' },
              fontSize: { base: '11px', md: '14px' },
            })}
          >
            <div
              className={css({
                display: 'flex',
                alignItems: 'center',
                gap: { base: '4px', md: '8px' },
              })}
            >
              <span className={css({ display: { base: 'none', sm: 'inline' } })}>Progress:</span>
              <span
                className={css({
                  fontWeight: 600,
                  fontSize: { base: '12px', md: '16px' },
                })}
              >
                {state.placedCards.filter((c) => c !== null).length}/{state.cardCount}
              </span>
              <span className={css({ display: { base: 'none', sm: 'inline' } })}>cards</span>
            </div>

            {/* Educational Mode Toggle */}
            <button
              type="button"
              onClick={() => setSpectatorEducationalMode(!spectatorEducationalMode)}
              className={css({
                display: 'flex',
                alignItems: 'center',
                gap: { base: '4px', md: '8px' },
                padding: { base: '4px 8px', md: '6px 12px' },
                borderRadius: '20px',
                border: '2px solid rgba(255, 255, 255, 0.3)',
                background: spectatorEducationalMode
                  ? 'rgba(255, 255, 255, 0.2)'
                  : 'rgba(255, 255, 255, 0.1)',
                color: 'white',
                fontSize: { base: '11px', md: '14px' },
                fontWeight: 500,
                cursor: 'pointer',
                transition: 'all 0.2s',
                _hover: {
                  background: 'rgba(255, 255, 255, 0.25)',
                  borderColor: 'rgba(255, 255, 255, 0.5)',
                },
              })}
            >
              <span>{spectatorEducationalMode ? '✅' : '📚'}</span>
              <span className={css({ display: { base: 'none', sm: 'inline' } })}>
                Educational Mode
              </span>
            </button>
          </div>
        </div>
      )}

      {/* Spectator Stats Sidebar/Bottom Sheet */}
      {isSpectating && (
        <div
          className={css({
            position: 'fixed',
            // Mobile: bottom sheet, Desktop: right sidebar
            top: { base: 'auto', md: '56px' },
            bottom: {
              base: spectatorStatsCollapsed ? '-120px' : '0',
              md: 'auto',
            },
            right: { base: '0', md: spectatorStatsCollapsed ? '-240px' : '0' },
            left: { base: '0', md: 'auto' },
            width: { base: '100%', md: '240px' },
            height: { base: '120px', md: 'calc(100vh - 56px)' },
            background: 'rgba(255, 255, 255, 0.95)',
            boxShadow: {
              base: '0 -2px 12px rgba(0, 0, 0, 0.1)',
              md: '-2px 0 12px rgba(0, 0, 0, 0.1)',
            },
            transition: { base: 'bottom 0.3s ease', md: 'right 0.3s ease' },
            zIndex: 90,
            display: 'flex',
            flexDirection: 'column',
          })}
        >
          {/* Collapse/Expand Toggle */}
          <button
            type="button"
            onClick={() => setSpectatorStatsCollapsed(!spectatorStatsCollapsed)}
            className={css({
              position: 'absolute',
              // Mobile: top center, Desktop: left middle
              left: { base: '50%', md: '-40px' },
              top: { base: '-30px', md: '50%' },
              transform: { base: 'translateX(-50%)', md: 'translateY(-50%)' },
              width: { base: '80px', md: '40px' },
              height: { base: '30px', md: '80px' },
              background: 'rgba(255, 255, 255, 0.95)',
              border: 'none',
              borderRadius: { base: '8px 8px 0 0', md: '8px 0 0 8px' },
              boxShadow: {
                base: '0 -2px 8px rgba(0, 0, 0, 0.1)',
                md: '-2px 0 8px rgba(0, 0, 0, 0.1)',
              },
              cursor: 'pointer',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              fontSize: { base: '16px', md: '20px' },
              transition: 'all 0.2s',
              _hover: {
                background: 'rgba(255, 255, 255, 1)',
              },
            })}
          >
            <span className={css({ display: { base: 'inline', md: 'none' } })}>
              {spectatorStatsCollapsed ? '▲' : '▼'}
            </span>
            <span className={css({ display: { base: 'none', md: 'inline' } })}>
              {spectatorStatsCollapsed ? '◀' : '▶'}
            </span>
          </button>

          {/* Stats Content */}
          <div
            className={css({
              padding: { base: '8px 12px', md: '24px' },
              overflowY: 'auto',
              flex: 1,
            })}
          >
            <h3
              className={css({
                fontSize: { base: '12px', md: '18px' },
                fontWeight: 700,
                marginBottom: { base: '6px', md: '20px' },
                color: '#1e293b',
                borderBottom: '2px solid #e2e8f0',
                paddingBottom: { base: '3px', md: '8px' },
              })}
            >
              <span className={css({ display: { base: 'none', md: 'inline' } })}>
                📊 Live Stats
              </span>
              <span className={css({ display: { base: 'inline', md: 'none' } })}>📊 Stats</span>
            </h3>

            {/* Mobile: horizontal layout, Desktop: vertical layout */}
            <div
              className={css({
                display: { base: 'grid', md: 'block' },
                gridTemplateColumns: { base: 'repeat(3, 1fr)', md: 'none' },
                gap: { base: '8px', md: '0' },
              })}
            >
              {/* Time Elapsed */}
              <div
                className={css({
                  marginBottom: { base: '0', md: '16px' },
                  padding: { base: '8px', md: '12px' },
                  background: 'linear-gradient(135deg, #dbeafe, #bfdbfe)',
                  borderRadius: { base: '6px', md: '8px' },
                  border: '1px solid #93c5fd',
                })}
              >
                <div
                  className={css({
                    fontSize: { base: '10px', md: '12px' },
                    color: '#1e40af',
                    marginBottom: '4px',
                  })}
                >
                  <span className={css({ display: { base: 'none', md: 'inline' } })}>
                    ⏱️ Time Elapsed
                  </span>
                  <span className={css({ display: { base: 'inline', md: 'none' } })}>⏱️</span>
                </div>
                <div
                  className={css({
                    fontSize: { base: '16px', md: '24px' },
                    fontWeight: 700,
                    color: '#1e3a8a',
                  })}
                >
                  {Math.floor(elapsedTime / 60)}:{(elapsedTime % 60).toString().padStart(2, '0')}
                </div>
              </div>

              {/* Cards Placed */}
              <div
                className={css({
                  marginBottom: { base: '0', md: '16px' },
                  padding: { base: '8px', md: '12px' },
                  background: 'linear-gradient(135deg, #dcfce7, #bbf7d0)',
                  borderRadius: { base: '6px', md: '8px' },
                  border: '1px solid #86efac',
                })}
              >
                <div
                  className={css({
                    fontSize: { base: '10px', md: '12px' },
                    color: '#15803d',
                    marginBottom: '4px',
                  })}
                >
                  <span className={css({ display: { base: 'none', md: 'inline' } })}>
                    🎯 Cards Placed
                  </span>
                  <span className={css({ display: { base: 'inline', md: 'none' } })}>🎯</span>
                </div>
                <div
                  className={css({
                    fontSize: { base: '16px', md: '24px' },
                    fontWeight: 700,
                    color: '#14532d',
                  })}
                >
                  {state.placedCards.filter((c) => c !== null).length} / {state.cardCount}
                </div>
                <div
                  className={css({
                    fontSize: '11px',
                    color: '#15803d',
                    marginTop: '4px',
                    display: { base: 'none', md: 'block' },
                  })}
                >
                  {Math.round(
                    (state.placedCards.filter((c) => c !== null).length / state.cardCount) * 100
                  )}
                  % complete
                </div>
              </div>

              {/* Current Accuracy */}
              <div
                className={css({
                  marginBottom: { base: '0', md: '16px' },
                  padding: { base: '8px', md: '12px' },
                  background: 'linear-gradient(135deg, #fef3c7, #fde68a)',
                  borderRadius: { base: '6px', md: '8px' },
                  border: '1px solid #fbbf24',
                })}
              >
                <div
                  className={css({
                    fontSize: { base: '10px', md: '12px' },
                    color: '#92400e',
                    marginBottom: '4px',
                  })}
                >
                  <span className={css({ display: { base: 'none', md: 'inline' } })}>
                    ✨ Current Accuracy
                  </span>
                  <span className={css({ display: { base: 'inline', md: 'none' } })}>✨</span>
                </div>
                <div
                  className={css({
                    fontSize: { base: '16px', md: '24px' },
                    fontWeight: 700,
                    color: '#78350f',
                  })}
                >
                  {(() => {
                    const placedCards = state.placedCards.filter(
                      (c): c is SortingCard => c !== null
                    )
                    if (placedCards.length === 0) return '0%'
                    const correctCount = placedCards.filter(
                      (c, i) => state.correctOrder[i]?.id === c.id
                    ).length
                    return `${Math.round((correctCount / placedCards.length) * 100)}%`
                  })()}
                </div>
                <div
                  className={css({
                    fontSize: '11px',
                    color: '#92400e',
                    marginTop: '4px',
                    display: { base: 'none', md: 'block' },
                  })}
                >
                  Cards in correct position
                </div>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Floating action buttons */}
      {!isSpectating && (
        <div
          className={css({
            position: 'absolute',
            top: '16px',
            right: '16px',
            display: 'flex',
            gap: '12px',
            zIndex: 10,
          })}
        >
          {/* Check Solution Button with Label */}
          <div
            className={css({
              display: 'flex',
              flexDirection: 'column',
              alignItems: 'center',
              gap: '6px',
            })}
          >
            <button
              type="button"
              onClick={handleCheckSolution}
              disabled={!canCheckSolutionDrag}
              title="Check Solution"
              className={css({
                width: '64px',
                height: '64px',
                background: isSequenceCorrect
                  ? 'linear-gradient(135deg, #fbbf24, #f59e0b, #fbbf24)'
                  : canCheckSolutionDrag
                    ? 'linear-gradient(135deg, #bbf7d0, #86efac)'
                    : 'linear-gradient(135deg, #e5e7eb, #d1d5db)',
                border: '4px solid',
                borderColor: isSequenceCorrect
                  ? '#f59e0b'
                  : canCheckSolutionDrag
                    ? '#22c55e'
                    : '#9ca3af',
                borderRadius: '50%',
                fontSize: '32px',
                cursor: canCheckSolutionDrag ? 'pointer' : 'not-allowed',
                opacity: canCheckSolutionDrag ? 1 : 0.5,
                transition: isSequenceCorrect ? 'none' : 'all 0.2s ease',
                boxShadow: isSequenceCorrect
                  ? '0 0 30px rgba(245, 158, 11, 0.8), 0 0 60px rgba(245, 158, 11, 0.6)'
                  : '0 4px 12px rgba(0, 0, 0, 0.15)',
                animation: isSequenceCorrect ? 'celebrate 0.5s ease-in-out infinite' : 'none',
                backgroundSize: isSequenceCorrect ? '200% 200%' : '100% 100%',
                _hover:
                  canCheckSolutionDrag && !isSequenceCorrect
                    ? {
                        transform: 'scale(1.1)',
                        boxShadow: '0 6px 20px rgba(34, 197, 94, 0.4)',
                      }
                    : {},
              })}
              style={{
                animationName: isSequenceCorrect ? 'celebrate' : undefined,
              }}
            >
              {perfectCountdown !== null && perfectCountdown > 0 ? perfectCountdown : '✓'}
            </button>
            <div
              className={css({
                fontSize: '13px',
                fontWeight: 700,
                color: isSequenceCorrect ? '#f59e0b' : canCheckSolutionDrag ? '#22c55e' : '#9ca3af',
                textTransform: 'uppercase',
                letterSpacing: '0.5px',
                textShadow: isSequenceCorrect ? '0 0 10px rgba(245, 158, 11, 0.8)' : 'none',
                animation: isSequenceCorrect ? 'pulse 0.5s ease-in-out infinite' : 'none',
              })}
            >
              {isSequenceCorrect ? 'PERFECT!' : 'Done?'}
            </div>
          </div>
        </div>
      )}

      {/* Timer (minimal, top-left) - hidden for spectators since banner shows time */}
      {!isSpectating && (
        <div
          className={css({
            position: 'absolute',
            top: '16px',
            left: '16px',
            padding: '8px 16px',
            background: 'rgba(255, 255, 255, 0.9)',
            border: '2px solid rgba(59, 130, 246, 0.3)',
            borderRadius: '20px',
            fontSize: '16px',
            fontWeight: 600,
            color: '#0c4a6e',
            zIndex: 10,
            boxShadow: '0 2px 8px rgba(0, 0, 0, 0.1)',
          })}
        >
          ⏱️ {formatTime(elapsedTime)}
        </div>
      )}

      {/* Play area with freely positioned cards - adjust for spectator panels */}
      <div
        ref={containerRef}
        className={css({
          position: 'absolute',
          left: 0,
          background: 'linear-gradient(135deg, #f0f9ff, #e0f2fe)',
          overflow: 'hidden',
          transition: 'width 0.3s ease, height 0.3s ease, top 0.3s ease',
        })}
        style={{
          width:
            isSpectating && !spectatorStatsCollapsed && viewport.width >= 768
              ? 'calc(100vw - 240px)'
              : '100vw',
          height: isSpectating
            ? viewport.width < 768
              ? 'calc(100vh - 170px)'
              : 'calc(100vh - 56px)'
            : '100vh',
          top: isSpectating ? (viewport.width < 768 ? '170px' : '56px') : '0',
        }}
      >
        {/* Render continuous curved path through the entire sequence */}
        {inferredSequence.length > 1 && (
          <ContinuousSequencePath
            cardStates={cardStates}
            sequence={inferredSequence}
            correctOrder={state.correctOrder}
            viewportWidth={viewportDimensions.width}
            viewportHeight={viewportDimensions.height}
            spectatorEducationalMode={spectatorEducationalMode}
            isSpectating={isSpectating}
          />
        )}

        {/* Render all cards at their positions */}
        {[
          ...state.availableCards,
          ...state.placedCards.filter((c): c is SortingCard => c !== null),
        ].map((card) => {
          const cardState = cardStates.get(card.id)
          if (!cardState) return null

          const isDragging = draggingCardId === card.id

          // Check if card is in correct prefix or suffix position (for scaling/fading)
          const positionInSequence = inferredSequence.findIndex((c) => c.id === card.id)
          let isInCorrectPrefixOrSuffix = false

          if (positionInSequence >= 0) {
            // Check if card is part of correct prefix
            let isInCorrectPrefix = true
            for (let i = 0; i <= positionInSequence; i++) {
              if (inferredSequence[i]?.id !== state.correctOrder[i]?.id) {
                isInCorrectPrefix = false
                break
              }
            }

            // Check if card is part of correct suffix
            let isInCorrectSuffix = true
            const offsetFromEnd = inferredSequence.length - 1 - positionInSequence
            for (let i = 0; i <= offsetFromEnd; i++) {
              const seqIdx = inferredSequence.length - 1 - i
              const correctIdx = state.correctOrder.length - 1 - i
              if (inferredSequence[seqIdx]?.id !== state.correctOrder[correctIdx]?.id) {
                isInCorrectSuffix = false
                break
              }
            }

            isInCorrectPrefixOrSuffix = isInCorrectPrefix || isInCorrectSuffix
          }

          // Show correctness based on educational mode for spectators
          const isCorrect = isSpectating
            ? spectatorEducationalMode && isInCorrectPrefixOrSuffix
            : isInCorrectPrefixOrSuffix

          // Get draggedByPlayerId from server state
          const serverPosition = state.cardPositions.find((p) => p.cardId === card.id)
          const draggedByPlayerId = serverPosition?.draggedByPlayerId

          return (
            <AnimatedCard
              key={card.id}
              card={card}
              cardState={cardState}
              isDragging={isDragging}
              isResizing={isResizing}
              isSpectating={isSpectating}
              isCorrect={isCorrect}
              draggedByPlayerId={draggedByPlayerId}
              localPlayerId={localPlayerId}
              players={players}
              viewportWidth={viewportDimensions.width}
              viewportHeight={viewportDimensions.height}
              onPointerDown={(e) => handlePointerDown(e, card.id)}
              onPointerMove={(e) => handlePointerMove(e, card.id)}
              onPointerUp={(e) => handlePointerUp(e, card.id)}
            />
          )
        })}
      </div>

      {/* Activity Feed (collaborative mode only, hidden for spectators) */}
      {state.gameMode === 'collaborative' && !isSpectating && activityFeed.length > 0 && (
        <div
          className={css({
            position: 'fixed',
            bottom: '24px',
            right: '24px',
            display: 'flex',
            flexDirection: 'column',
            gap: '8px',
            zIndex: 150,
            maxWidth: '320px',
          })}
        >
          {activityFeed.map((notification) => {
            const age = Date.now() - notification.timestamp
            const opacity = Math.max(0, 1 - age / 3000) // Fade out over 3 seconds

            return (
              <div
                key={notification.id}
                className={css({
                  padding: '12px 16px',
                  background: 'rgba(255, 255, 255, 0.95)',
                  border: '2px solid rgba(99, 102, 241, 0.3)',
                  borderRadius: '12px',
                  boxShadow: '0 4px 12px rgba(0, 0, 0, 0.15)',
                  fontSize: '14px',
                  fontWeight: 500,
                  color: '#1f2937',
                  display: 'flex',
                  alignItems: 'center',
                  gap: '8px',
                  transition: 'all 0.3s ease',
                })}
                style={{
                  opacity,
                  transform: `translateY(${(1 - opacity) * 20}px)`,
                }}
              >
                <span style={{ fontSize: '20px' }}>{notification.playerEmoji}</span>
                <span>
                  <strong>{notification.playerName}</strong> {notification.action}
                </span>
              </div>
            )
          })}
        </div>
      )}
    </div>
  )
}