All files / components/screens/combat CombatScreen3D.tsx

42.8% Statements 324/757
27.51% Branches 137/498
48.52% Functions 66/136
42.58% Lines 313/735

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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221                                                                                                                                                                                                                                                                                                                                                                                                                        1x                           60x     60x     60x                           60x 30x 30x       60x     60x 30x 30x 30x 30x 30x                   60x       60x               60x 30x   1x   1x   26x       2x               60x       60x 30x   30x                   60x                     60x     30x           60x                     60x     30x       60x             60x 60x     60x       60x 60x 60x 60x   60x       60x 60x                         60x 60x 60x         60x               60x 60x     60x 60x     60x                                 60x       60x       60x 60x 60x 60x         60x                       60x     60x         60x         60x                                                                                                                           60x                                                                                                                                                                                           60x                       60x 30x 30x                 60x 30x         60x     30x     60x 30x             60x   60x 30x 30x 30x       60x     60x     60x       60x         60x             60x               60x 30x 30x     30x         30x           30x               30x           30x         30x                 30x     30x   30x             60x 30x         30x   30x         60x   30x   30x 30x 30x   30x 30x             60x 60x 30x 30x                 60x     60x           60x     60x           60x 60x       60x 30x   30x 30x           60x   30x 30x 30x     30x       29x 29x             60x                   60x 30x                       60x 60x             60x       60x             60x                                               60x 30x                         30x 30x 30x 30x 30x         60x     60x         60x           60x 60x       60x 60x     60x       60x             60x 60x                                                                                 60x         60x 60x     60x                                     60x 60x 60x   60x 60x   60x                                                         60x       60x 30x       60x 60x 60x 60x       60x     60x                     60x         60x       60x 30x                   30x   30x   30x             60x 60x 30x 30x             60x   120x                                 60x                                       60x         60x 30x         60x 30x               60x 60x 60x 60x 60x       60x   30x 30x           60x                                                               60x 60x 60x         60x   60x                                   60x                                         60x   60x 60x 30x     30x 30x     30x 30x 30x 30x                           60x     60x 30x 30x 30x 29x           30x 30x 30x 30x             60x 30x         60x                                 60x             60x                                       60x                           60x                               60x                                                                                                                 60x                                             60x 60x           60x                                                                                                                                                 60x 30x 30x     30x       60x     60x 60x 30x       60x                                                           60x 60x     60x 60x 60x 60x 60x   60x                                                           60x                     60x 60x 60x 60x 60x   60x                     60x                     60x                                       60x                                                                       60x                       60x                                                                                                                                                                                                                 60x 60x                                   60x                                                                                                                           60x         60x                   60x                     60x                                                                     60x           60x                         60x 60x   58x                                                                           60x                     60x                                               60x 30x         60x   30x 30x                                                                                             60x                                                                                                                                                                                                                                                                                                                                                                 60x 60x       60x 30x                                         60x 60x   60x 60x   60x                                                           60x 60x       60x 60x                                                                                                                                                 60x 60x                                     60x 30x               30x             30x               60x 30x               30x             30x               60x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              
/**
 * CombatScreen3D - Three.js-based combat screen
 *
 * Maintains all existing combat logic and state management
 * Uses Html overlays for UI and 3D meshes for game objects
 */
 
import { Canvas } from "@react-three/fiber";
import { Html } from "@react-three/drei";
import {
  Bloom,
  EffectComposer,
  Noise,
  Vignette,
} from "@react-three/postprocessing";
import React, {
  useCallback,
  useEffect,
  useMemo,
  useRef,
  useState,
} from "react";
import { useAudio } from "../../../audio/AudioProvider";
import { useActionFeedback } from "../../../hooks/useActionFeedback";
import { useCombatTimer } from "../../../hooks/useCombatTimer";
import { useKeyboardControls } from "../../../hooks/useKeyboardControls";
import { usePlayerAnimation } from "../../../hooks/usePlayerAnimation";
import { useRoundTransition } from "../../../hooks/useRoundTransition";
import { useTechniqueSelection } from "../../../hooks/useTechniqueSelection";
import { useWebGLContextLossHandler } from "../../../hooks/useWebGLContextLossHandler";
import { useCombatAttackMovement } from "./hooks/useCombatAttackMovement";
import { HitEffect, PlayerState } from "../../../systems";
import { CombatSystem } from "../../../systems/CombatSystem";
import {
  AdaptiveDifficulty,
  getPersonalityByArchetype,
} from "../../../systems/ai";
import {
  AnimationEvents,
  AnimationState,
  AnimationType,
  determineRecoveryType,
  getAnimation,
  getAnimationForTechnique,
  getRecoveryAnimationState,
} from "../../../systems/animation";
import { BalanceSystem } from "../../../systems/combat/BalanceSystem";
import type { BalancePlayerState } from "../../../systems/combat/BalanceSystem";
import { HitEffectType } from "../../../systems/effects";
import { injuryMovementModifier } from "../../../systems/movement/InjuryMovementModifier";
import { TRIGRAM_STANCES_ORDER } from "../../../systems/trigram/types";
import type { KoreanTechnique } from "../../../systems/vitalpoint/types";
import {
  CombatState,
  GameMode,
  PlayerArchetype,
  Position,
  TrigramStance,
} from "../../../types";
import { Injury, InjuryType } from "../../../types/injury";
import { Z_INDEX } from "../../../types/LayoutTypes";
import {
  FONT_FAMILY,
  getPerformanceSettings,
  KOREAN_COLORS,
  ROUND_ANNOUNCEMENT_TIMINGS,
} from "@/types/constants";
import { getAnimationTypeForTechnique } from "../../../data/techniqueMappings";
import { toHexColor } from "../../../utils/colorHelpers";
import { usePlayerMovement } from "../../../utils/inputSystem";
import { PerformanceOverlay3D } from "../../../utils/performance";
import { createPlayerFromArchetype } from "../../../utils/playerUtils";
import { createCameraConfig } from "../../../utils/sharedPhysicsConfig";
import { useAdaptiveQuality } from "../../shared/three/optimization";
import { useKoreanTheme } from "../../shared/base/useKoreanTheme";
import {
  ActionFeedback,
  TechniqueName,
} from "../../shared/three/effects/ActionFeedback";
import { DamageNumbers } from "../../shared/three/effects/DamageNumbers";
import HitEffects3D from "../../shared/three/effects/HitEffects3D";
import { VitalPointMarkers3D } from "../../shared/three/effects/VitalPointMarkers3D";
import { StanceChangeIndicator } from "../../shared/three/indicators/StanceChangeIndicator";
import { CombatArena3D } from "../../shared/three/scene/CombatArena3D";
import { BreathingIndicator } from "../../shared/three/ui/BreathingIndicator";
import { ComboCounter } from "../../shared/three/ui/ComboCounter";
import { VitalPointOverlayControlsHtml } from "../../shared/three/ui/VitalPointOverlayControlsHtml";
import { KeyboardHints } from "./components/controls/KeyboardHints";
import { MatchCountdown } from "./components/feedback/MatchCountdown";
import { RoundAnnouncement } from "./components/feedback/RoundAnnouncementOverlayHtml";
import { RoundDisplayStatus } from "./components/feedback/RoundDisplayStatus";
import { RoundStartAnnouncement } from "./components/feedback/RoundStartAnnouncementOverlayHtml";
import { InputBufferDisplay } from "./components/indicators/InputBufferDisplay";
import { GestureEvent } from "../../../hooks/useTouchControls";
import {
  MovementType,
  SpeedModifierSystem,
} from "../../../systems/physics/SpeedModifierSystem";
import { Technique } from "../../../types";
import {
  animationStateToPlayerAnimation,
  convertPlayerStateToProps,
  getBalanceState,
} from "../../../utils/player3DHelpers";
import {
  GestureRecognizerPure,
  MobileControlsOverlay,
  StanceWheelPure,
} from "../../shared/mobile";
import { ButtonEventType } from "../../shared/mobile/ActionButtons";
import { Direction, DPadEventType } from "../../shared/mobile/VirtualDPad";
import { Player3DWithTransitions } from "../../shared/three/models/Player3DWithTransitions";
import { PauseMenu } from "./components/controls/PauseMenu";
import { TraumaOverlay3D } from "./components/effects/TraumaOverlay3D";
import { CombatParticleEffects3D } from "./components/effects/CombatParticleEffects3D";
import {
  CombatBottomHUD,
  CombatLeftHUD,
  CombatRightHUD,
  CombatTopHUD,
} from "./components/hud";
import { FPSMonitor } from "./components/hud/FPSMonitor";
import { PlayerStateOverlayHtml } from "./components/hud/PlayerStateOverlayHtml";
import { BalanceIndicatorOverlayHtml } from "../../ui/combat/BalanceIndicatorOverlayHtml";
import {
  ANNOUNCEMENT_FADE_OUT_DELAY,
  calculateAccuracy,
  STANCE_INDEX_MAP,
} from "./helpers";
import { AnimationUpdater } from "./helpers/AnimationUpdater";
import { AccelerationUpdater } from "../../../systems/movement/helpers/AccelerationUpdater";
import { isRunningSpeed } from "../../../systems/movement/helpers/accelerationUtils";
import { useAICombat } from "./hooks/useAICombat";
import { useCombatActions } from "./hooks/useCombatActions";
import { useCombatAudio } from "./hooks/useCombatAudio";
import { useCombatLayout } from "./hooks/useCombatLayout";
import { useCombatState } from "./hooks/useCombatState";
 
/**
 * Props for the CombatScreen3D component.
 * Provides all state and callbacks required for the 3D combat screen.
 */
export interface CombatScreen3DProps {
  /**
   * Array of player states (expects exactly 2 players).
   * Each PlayerState contains all combat and status information for a player.
   */
  readonly players: readonly PlayerState[];
  /**
   * Callback to update a player's state by index.
   * @param playerIndex - Index of the player to update (0 or 1).
   * @param updates - Partial PlayerState with updated fields.
   */
  readonly onPlayerUpdate: (
    playerIndex: number,
    updates: Partial<PlayerState>,
  ) => void;
  /**
   * Current round number (1-based).
   */
  readonly currentRound: number;
  /**
   * Remaining time in seconds for the current round.
   */
  readonly timeRemaining: number;
  /**
   * Whether combat is currently paused.
   */
  readonly isPaused: boolean;
  /**
   * Callback when the user exits to the menu.
   */
  readonly onReturnToMenu: () => void;
  /**
   * Callback when the match ends, with the winner's index (0 or 1).
   * @param winner - Index of the winning player.
   */
  readonly onGameEnd: (winner: number) => void;
  /**
   * Optional game mode (affects rules/behavior).
   */
  readonly gameMode?: GameMode;
  /**
   * Canvas width in pixels. Defaults to 1200.
   */
  readonly width?: number;
  /**
   * Canvas height in pixels. Defaults to 800.
   */
  readonly height?: number;
  /**
   * Enable adaptive quality adjustment (default: true on mobile)
   */
  readonly enableAdaptiveQuality?: boolean;
  /**
   * Show performance overlay in dev mode (default: import.meta.env.DEV)
   */
  readonly showPerformanceOverlay?: boolean;
}
 
/**
 * CombatScreen3D Component
 * Three.js-based combat screen with 3D characters and effects
 */
export const CombatScreen3D: React.FC<CombatScreen3DProps> = ({
  players,
  onPlayerUpdate,
  currentRound,
  timeRemaining,
  isPaused,
  onReturnToMenu,
  onGameEnd,
  width = 1200,
  height = 800,
  enableAdaptiveQuality,
  showPerformanceOverlay = import.meta.env.DEV,
}) => {
  // Track when content is ready to render (prevents flash of empty content)
  const [contentReady, setContentReady] = useState(false);
 
  // Track context loss count for debugging
  const contextLossCountRef = useRef(0);
 
  // Handle WebGL context loss and restoration
  useWebGLContextLossHandler({
    onContextLost: () => {
      console.warn("⚠️ WebGL context lost in CombatScreen");
      contextLossCountRef.current += 1;
      setContentReady(false);
    },
    onContextRestored: () => {
      // Context restored - re-enable content after short delay
      setTimeout(() => setContentReady(true), 100);
    },
    autoRestore: true,
  });
 
  // Ensure content renders after component is mounted and stable
  useEffect(() => {
    const timer = setTimeout(() => setContentReady(true), 50);
    return () => clearTimeout(timer);
  }, []);
 
  // Audio context for button interactions
  const audio = useAudio();
 
  // Performance marks - only in dev mode and memoized
  useEffect(() => {
    Eif (import.meta.env.DEV) {
      performance.mark("combat-3d-render-start");
      return () => {
        performance.mark("combat-3d-render-end");
        performance.measure(
          "combat-3d-render",
          "combat-3d-render-start",
          "combat-3d-render-end",
        );
      };
    }
  }, []);
 
  // Layout calculations
  const { arenaBounds, isMobile, screenSize, layoutConstants } =
    useCombatLayout(width, height);
 
  // Use Korean theme hook for consistent theming
  const theme = useKoreanTheme({
    variant: "primary",
    size: "md",
    isMobile,
  });
 
  // Screen size scaling for 4K and large displays
  // Uses SPACING_SCALE_MAP values: mobile=0.5, tablet=0.75, desktop=1.0, large=1.25, xlarge=1.5
  const positionScale = useMemo(() => {
    switch (screenSize) {
      case "mobile":
        return 1.0; // Mobile already has special handling
      case "tablet":
        return 1.0;
      case "desktop":
        return 1.0;
      case "large":
        return 1.25;
      case "xlarge":
        return 1.5; // 4K displays need 1.5x offsets
      default:
        return 1.0;
    }
  }, [screenSize]);
 
  // Camera and rendering configuration based on device
  // Use shared physics config for consistent camera setup across screens
  const cameraConfig = useMemo(() => createCameraConfig(isMobile), [isMobile]);
 
  // Rendering quality based on device (optimize for 60fps on mobile)
  // Uses performance tier system for extra-small, mobile, and desktop devices
  const renderConfig = useMemo(() => {
    const performanceSettings = getPerformanceSettings(width, isMobile);
 
    return {
      shadowMapSize: performanceSettings.shadowMapSize,
      dpr: performanceSettings.dpr,
      antialias: performanceSettings.antialias,
      maxParticles: performanceSettings.maxParticles,
      postProcessing: performanceSettings.postProcessing,
    };
  }, [isMobile, width]);
 
  // Adaptive quality - default to enabled on mobile, optional on desktop
  const shouldEnableAdaptiveQuality = enableAdaptiveQuality ?? isMobile;
 
  /**
   * AdaptiveQualityWrapper - Internal component to use adaptive quality hook
   * Must be inside Canvas to use useFrame from @react-three/fiber
   *
   * Memoized with useMemo so the component type is stable across renders.
   * Note: renderConfig is intentionally NOT in dependencies to prevent
   * component recreation when performance settings change, which would
   * reset the internal state of useAdaptiveQuality hook.
   */
  const AdaptiveQualityWrapper = useMemo<
    React.FC<{ children: React.ReactNode }>
  >(() => {
    const Component: React.FC<{ children: React.ReactNode }> = ({
      children,
    }) => {
      // Monitor FPS and adjust quality dynamically
      // Quality settings are logged but not currently applied to rendering
      // Future: Pass quality settings to child components for dynamic adjustments
      useAdaptiveQuality(
        shouldEnableAdaptiveQuality,
        isMobile,
        (newQuality) => {
          if (import.meta.env.DEV) {
            console.log(`[CombatScreen3D] Quality adjusted to: ${newQuality}`);
          }
        },
      );
 
      // Quality monitoring is active - quality changes logged in dev mode
      return <>{children}</>;
    };
 
    return Component;
  }, [shouldEnableAdaptiveQuality, isMobile]);
 
  // Combat state management
  const { state: combatState, actions: combatActions } = useCombatState();
 
  // ═══════════════════════════════════════════════════════════════════════════
  // Vital Point Overlay Controls State
  // ═══════════════════════════════════════════════════════════════════════════
 
  // Vital point overlay state (for both players)
  const [overlayVisible, setOverlayVisible] = useState(false);
  const [severityFilters, setSeverityFilters] = useState<
    import("../../../types/common").VitalPointSeverity[]
  >([]);
  const [regionFilter, setRegionFilter] =
    useState<
      import("../../shared/three/ui/VitalPointOverlayControlsHtml").BodyRegionFilter
    >("all");
  const [searchQuery, setSearchQuery] = useState("");
  const [showLabels, setShowLabels] = useState(true);
  const [animated, setAnimated] = useState(true);
  const [scale, setScale] = useState(1.2); // Larger scale for better visibility in combat
  // Performance monitor visibility toggle (F9 key)
  const [showPerformanceMonitor, setShowPerformanceMonitor] = useState(false);
 
  // Keyboard shortcut for toggling overlay (V key) and performance monitor (F9)
  // Ctrl key removed - running now acceleration-based
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === "v" || e.key === "V") {
        setOverlayVisible((prev) => !prev);
        audio.playSFX("menu_select");
      }
      // F9 key toggles performance monitor (development only)
      // Note: P key is reserved for Philosophy screen
      if (e.key === "F9" && import.meta.env.DEV) {
        e.preventDefault();
        setShowPerformanceMonitor((prev) => !prev);
      }
    };
 
    window.addEventListener("keydown", handleKeyDown);
    return () => {
      window.removeEventListener("keydown", handleKeyDown);
    };
  }, [audio]);
 
  // Action feedback system for damage numbers, combo counter, and technique names
  const { state: feedbackState, actions: feedbackActions } = useActionFeedback({
    damageNumberDuration: 1500,
    actionFeedbackDuration: 1200,
    techniqueDuration: 2000,
    comboResetTime: 2000,
  });
 
  // Combat audio
  const combatAudio = useCombatAudio();
  const { playStanceChangeSound } = combatAudio;
 
  // Match score tracking - use ref for internal updates, state for rendering
  const [matchScore, setMatchScore] = useState({ player1: 0, player2: 0 });
  const matchScoreRef = useRef(matchScore);
 
  // Helper to update match score without triggering setState in effects
  const updateMatchScore = useCallback((winner: 0 | 1) => {
    const newScore = {
      player1:
        winner === 0
          ? matchScoreRef.current.player1 + 1
          : matchScoreRef.current.player1,
      player2:
        winner === 1
          ? matchScoreRef.current.player2 + 1
          : matchScoreRef.current.player2,
    };
    matchScoreRef.current = newScore;
    // Use setTimeout to defer the setState call outside the effect
    setTimeout(() => setMatchScore(newScore), 0);
  }, []);
 
  // Internal round tracking (since parent may always pass currentRound=1)
  const [internalRound, setInternalRound] = useState(currentRound);
 
  // Current time for balance indicators and other time-dependent UI
  // Updated every 200ms to avoid calling Date.now() on every render (60fps)
  const [currentTime, setCurrentTime] = useState(Date.now());
 
  // Match countdown state - DISABLED: skip countdown and start combat immediately
  // Using state for hasShownMatchCountdown to avoid ref access during render
  const [hasShownMatchCountdown, setHasShownMatchCountdown] = useState(true); // Already shown (skipped)
  const [showMatchCountdown, setShowMatchCountdown] = useState(false); // Don't show
  const [showRoundStart, setShowRoundStart] = useState(false);
  const [matchCountdownComplete, setMatchCountdownComplete] = useState(true); // Already complete (skipped)
 
  // Player 1 position in METERS (relative to arena center)
  // Player 1 starts at 10% left of center for realistic combat distance (~1.6m apart)
  // Allows kicks to land with 1-2 steps, punches with 2-3 steps (realistic fighting)
  const [player1Position, setPlayer1Position] = useState<Position>({
    x: arenaBounds.worldWidthMeters * -0.1, // 10% left of center (~0.8m for 8m arena)
    y: 0, // Centered
  });
 
  // Pause menu state - local state for pause menu visibility
  // Local state for pause menu UI visibility
  // Note: isPaused (prop) controls game pause from parent, showPauseMenu (state) controls menu UI
  // Both need to be checked because:
  // - isPaused: External pause state (e.g., from parent component or global game state)
  // - showPauseMenu: Local UI state for pause menu overlay
  // They can be out of sync intentionally (e.g., parent pauses game but menu not shown)
  const [showPauseMenu, setShowPauseMenu] = useState(false);
 
  // Pause menu handlers
  const handlePause = useCallback(() => {
    setShowPauseMenu(true);
    audio.playSFX("menu_select");
  }, [audio]);
 
  const handleResume = useCallback(() => {
    setShowPauseMenu(false);
    audio.playSFX("menu_select");
  }, [audio]);
 
  const handleRestart = useCallback(() => {
    // Note: React 19 automatically batches all these state updates into a single render
    // This ensures atomic state transitions without race conditions
 
    // Reset to first round
    setInternalRound(1);
    setMatchScore({ player1: 0, player2: 0 });
    matchScoreRef.current = { player1: 0, player2: 0 };
 
    // Reset combat state
    combatActions.setRoundEnded(false);
    combatActions.setRoundStarted(false);
    combatActions.setRoundDisplayStatus(null);
 
    // Reset player health, resources, combat state, and visual state
    // Includes consciousness, pain, balance, combatState to clear any blur/vignette effects
    // and reset from fallen/stunned states
    onPlayerUpdate(0, {
      health: 100,
      stamina: 100,
      ki: 100,
      consciousness: 100,
      pain: 0,
      balance: 100,
      combatState: CombatState.IDLE,
      isStunned: false,
      isBlocking: false,
    });
    onPlayerUpdate(1, {
      health: 100,
      stamina: 100,
      ki: 100,
      consciousness: 100,
      pain: 0,
      balance: 100,
      combatState: CombatState.IDLE,
      isStunned: false,
      isBlocking: false,
    });
 
    // Reset player positions to starting positions for rematch
    // Use meter-based positions for physics-first system consistency
    setPlayer1Position({
      x: arenaBounds.worldWidthMeters * -0.1, // 10% left of center in meters
      y: 0, // Centered
    });
    onPlayerUpdate(1, {
      position: {
        x: arenaBounds.worldWidthMeters * 0.1, // 10% right of center in meters
        y: 0, // Centered
      },
    });
 
    // Close pause menu and start first round
    // The timer will reset automatically via the initialTime prop when round starts
    setShowPauseMenu(false);
    setShowRoundStart(true);
 
    audio.playSFX("menu_select");
  }, [audio, combatActions, onPlayerUpdate, arenaBounds, setPlayer1Position]);
 
  // Round transition complete handler - checks for match end or starts next round
  const handleRoundTransitionComplete = useCallback(() => {
    if (import.meta.env.DEV) {
      console.log("[DEV] Round transition complete, checking match status");
    }
    // Check if match is over (best of 3 - first to 2 wins)
    const currentScore = matchScoreRef.current;
    if (currentScore.player1 >= 2 || currentScore.player2 >= 2) {
      // Match is over - call onGameEnd instead of starting next round
      const matchWinner = currentScore.player1 >= 2 ? 0 : 1;
      if (import.meta.env.DEV) {
        console.log("[DEV] Match over, winner:", matchWinner);
      }
      onGameEnd(matchWinner);
      return; // Don't start next round
    }
 
    // Reset all combat state for next round (combos, hit effects, messages cleared)
    combatActions.resetRoundState();
 
    // Increment internal round counter for next round
    // Use the updater function to get the new value and trigger announcement
    setInternalRound((prev) => {
      const nextRound = prev + 1;
      if (import.meta.env.DEV) {
        console.log("[DEV] Incrementing round from", prev, "to", nextRound);
      }
      // Wait for transition duration plus fade-out to complete before showing next round announcement
      setTimeout(() => {
        if (import.meta.env.DEV) {
          console.log(
            "[DEV] Showing round start announcement for round",
            nextRound,
          );
        }
        setShowRoundStart(true);
      }, ANNOUNCEMENT_FADE_OUT_DELAY);
      return nextRound;
    });
 
    // Reset player health, resources, combat state, and visual state for next round
    // Includes consciousness, pain, balance, combatState to clear any blur/vignette effects
    // and reset from fallen/stunned states
    onPlayerUpdate(0, {
      health: 100,
      stamina: 100,
      ki: 100,
      consciousness: 100,
      pain: 0,
      balance: 100,
      combatState: CombatState.IDLE,
      isStunned: false,
      isBlocking: false,
    });
    onPlayerUpdate(1, {
      health: 100,
      stamina: 100,
      ki: 100,
      consciousness: 100,
      pain: 0,
      balance: 100,
      combatState: CombatState.IDLE,
      isStunned: false,
      isBlocking: false,
    });
 
    // Reset player positions to starting positions for new round
    // Use meter-based positions for physics-first system consistency
    setPlayer1Position({
      x: arenaBounds.worldWidthMeters * -0.1, // 10% left of center in meters
      y: 0, // Centered
    });
    // Player 2 position is reset via onPlayerUpdate
    onPlayerUpdate(1, {
      position: {
        x: arenaBounds.worldWidthMeters * 0.1, // 10% right of center in meters
        y: 0, // Centered
      },
    });
  }, [
    combatActions,
    onGameEnd,
    onPlayerUpdate,
    arenaBounds,
    // Note: setPlayer1Position is a stable React setState function and won't cause unnecessary re-renders
    setPlayer1Position,
  ]);
 
  // Round transition management
  const {
    showAnnouncement,
    roundWinner,
    currentRoundNumber: transitionRoundNumber,
    skipCountdown,
    startTransition,
  } = useRoundTransition(
    {
      announcementDuration: ROUND_ANNOUNCEMENT_TIMINGS.ANNOUNCEMENT_DURATION,
      countdownDuration: ROUND_ANNOUNCEMENT_TIMINGS.COUNTDOWN_DURATION,
      transitionDuration: ROUND_ANNOUNCEMENT_TIMINGS.TRANSITION_DURATION,
    },
    handleRoundTransitionComplete,
  );
 
  // Player 2 position in METERS (relative to arena center) - AI-controlled
  // Player 2 starts at 10% right of center for realistic combat distance (~1.6m apart)
  // Allows kicks to land with 1-2 steps, punches with 2-3 steps (realistic fighting)
  const player2Position = useMemo<Position>(() => {
    Eif (players.length >= 2 && players[1].position) {
      return players[1].position;
    }
    return {
      x: arenaBounds.worldWidthMeters * 0.1, // 10% right of center (~0.8m for 8m arena)
      y: 0, // Centered
    };
  }, [players, arenaBounds]);
 
  // Combined positions for backward compatibility with existing code
  const playerPositions = useMemo<Position[]>(() => {
    return [player1Position, player2Position];
  }, [player1Position, player2Position]);
 
  // Physics-first: positions are already in METERS
  // Direct conversion to 3D world coordinates - no pixel math needed
  const player1Position3D: [number, number, number] = useMemo(() => {
    // playerPosition.x is lateral position in meters (- = left, + = right)
    // playerPosition.y is forward/backward position in meters (- = toward camera, + = away)
    return [playerPositions[0].x, 0, playerPositions[0].y];
  }, [playerPositions]);
 
  const player2Position3D: [number, number, number] = useMemo(() => {
    return [playerPositions[1].x, 0, playerPositions[1].y];
  }, [playerPositions]);
 
  // Calculate dynamic rotations so players always face each other
  // atan2(dx, dz) gives the Y-axis rotation needed to face direction (dx, dz)
  // This is the standard formula for rotating around Y to point at a target
  // NOTE: player1Rotation is calculated after usePlayerMovement below
  const player1LastRotationRef = useRef<number>(0);
 
  const player2Rotation = useMemo(() => {
    const dx = player1Position3D[0] - player2Position3D[0];
    const dz = player1Position3D[2] - player2Position3D[2];
    return Math.atan2(dx, dz);
  }, [player1Position3D, player2Position3D]);
 
  // Combat system
  const combatSystem = useMemo(() => new CombatSystem(), []);
 
  // Balance system for recovery mechanics
  const balanceSystem = useMemo(() => new BalanceSystem(), []);
 
  // Speed Modifier System for dynamic movement speed calculations
  const speedModifierSystem = useMemo(() => new SpeedModifierSystem(), []);
 
  // Track speed modifiers for HUD display
  // Initial values match SpeedModifierSystem.BASE_WALKING_SPEED and BASE_ACCELERATION
  const [player1SpeedModifiers, setPlayer1SpeedModifiers] = useState({
    finalSpeed: 6.0, // BASE_WALK_SPEED (6.0 m/s)
    baseSpeed: 6.0,
    finalAcceleration: 12.0, // BASE_ACCELERATION (12.0 m/s²)
  });
  const [player2SpeedModifiers, setPlayer2SpeedModifiers] = useState({
    finalSpeed: 6.0, // BASE_WALK_SPEED (6.0 m/s)
    baseSpeed: 6.0,
    finalAcceleration: 12.0, // BASE_ACCELERATION (12.0 m/s²)
  });
 
  // Track walk/run speeds for acceleration interpolation (archetype-aware)
  const [player1WalkRunSpeeds, setPlayer1WalkRunSpeeds] = useState({
    walkSpeed: 6.0,
    runSpeed: 10.0,
  });
 
  // Calculate speed modifiers for both players when state changes
  // Updates at 5Hz (every 200ms) to balance responsiveness and performance
  // Get both walk and run speeds for acceleration interpolation
  useEffect(() => {
    const updateSpeedModifiers = () => {
      Eif (players.length >= 2) {
        // Player 1 speed modifiers - calculate both walk and run
        const player1WalkModifiers =
          speedModifierSystem.calculateSpeedModifiers(
            players[0],
            MovementType.WALKING,
            false, // isCrouching
          );
        const player1RunModifiers = speedModifierSystem.calculateSpeedModifiers(
          players[0],
          MovementType.RUNNING,
          false, // isCrouching
        );
 
        setPlayer1SpeedModifiers({
          finalSpeed: player1WalkModifiers.finalSpeed,
          baseSpeed: player1WalkModifiers.baseSpeed,
          finalAcceleration: player1WalkModifiers.finalAcceleration,
        });
 
        // Store walk/run speeds for acceleration interpolation
        // These account for archetype speeds and stance modifiers
        setPlayer1WalkRunSpeeds({
          walkSpeed: player1WalkModifiers.finalSpeed,
          runSpeed: player1RunModifiers.finalSpeed,
        });
 
        // Player 2 speed modifiers
        const player2Modifiers = speedModifierSystem.calculateSpeedModifiers(
          players[1],
          MovementType.WALKING,
          false,
        );
        setPlayer2SpeedModifiers({
          finalSpeed: player2Modifiers.finalSpeed,
          baseSpeed: player2Modifiers.baseSpeed,
          finalAcceleration: player2Modifiers.finalAcceleration,
        });
      }
    };
 
    // Initial calculation
    updateSpeedModifiers();
 
    // Update every 200ms (5Hz) for responsive feedback without excessive re-renders
    const intervalId = setInterval(updateSpeedModifiers, 200);
 
    return () => clearInterval(intervalId);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [players]); // speedModifierSystem is memoized and never changes
 
  // Update current time for balance indicators at 5Hz (200ms)
  // This avoids calling Date.now() on every render (60fps = 60 times/second)
  // Instead, we update 5 times/second, which is sufficient for UI feedback
  useEffect(() => {
    const updateTime = () => {
      setCurrentTime(Date.now());
    };
 
    // Update every 200ms (5Hz) - same rate as speed modifiers
    const intervalId = setInterval(updateTime, 200);
 
    return () => clearInterval(intervalId);
  }, []);
 
  // Calculate leg injury factor for physics-based movement
  // Averages left and right leg health to determine speed penalty
  const calculateLegInjuryFactor = useCallback(
    (player: PlayerState): number => {
      Iif (!player.bodyPartHealth) return 0;
 
      const leftLeg = player.bodyPartHealth.legLeft ?? player.maxHealth;
      const rightLeg = player.bodyPartHealth.legRight ?? player.maxHealth;
      const maxHealth = player.maxHealth;
 
      const averageLegHealth = (leftLeg + rightLeg) / (2 * maxHealth);
      return Math.max(0, Math.min(1, 1.0 - averageLegHealth)); // 0 = healthy, 1 = critical
    },
    [],
  );
 
  // Get player1 data for movement physics
  // Memoize based on player1 reference (React Compiler prefers less specific dependencies)
  const player1 = players.length > 0 ? players[0] : undefined;
  const player1Data = useMemo(() => {
    const p1 = player1 ?? createPlayerFromArchetype(PlayerArchetype.MUSA, 0);
    return {
      currentStance: p1.currentStance,
      legInjuryFactor: calculateLegInjuryFactor(p1),
    };
  }, [player1, calculateLegInjuryFactor]);
 
  // Track current attack animation for each player
  // Used to determine which skeletal animation to play during attacks
  // 각 플레이어의 현재 공격 애니메이션 추적
  const [player1AttackAnimation, setPlayer1AttackAnimation] = useState<
    string | undefined
  >(undefined);
  const [player2AttackAnimation, setPlayer2AttackAnimation] = useState<
    string | undefined
  >(undefined);
 
  // Track current technique ID for enum-based animation lookup
  // 열거형 기반 애니메이션 조회를 위한 현재 기술 ID 추적
  const [player1TechniqueId, setPlayer1TechniqueId] = useState<
    string | undefined
  >(undefined);
  const [player2TechniqueId, setPlayer2TechniqueId] = useState<
    string | undefined
  >(undefined);
 
  // Track injuries for trauma visualization (TraumaOverlay3D)
  // 외상 시각화를 위한 부상 추적
  const [player1Injuries, setPlayer1Injuries] = useState<readonly Injury[]>([]);
  const [player2Injuries, setPlayer2Injuries] = useState<readonly Injury[]>([]);
 
  // Clear injuries when component unmounts or when a new match starts
  // 컴포넌트 언마운트 시 또는 새 매치 시작 시 부상 초기화
  useEffect(() => {
    return () => {
      // Clear injury state on unmount to avoid leaking injuries across screens
      setPlayer1Injuries([]);
      setPlayer2Injuries([]);
    };
  }, []);
 
  // Clear injuries when a new match starts (both players at full health)
  // 새 매치 시작 시 부상 초기화 (양 플레이어 모두 최대 체력)
  useEffect(() => {
    // Only clear if we have valid players with health data
    Eif (players.length >= 2) {
      const player1 = players[0];
      const player2 = players[1];
 
      // Check if both players are at max health (indicates new match start)
      if (
        player1?.health === player1?.maxHealth &&
        player2?.health === player2?.maxHealth
      ) {
        setPlayer1Injuries([]);
        setPlayer2Injuries([]);
      }
    }
  }, [players]);
 
  // CRITICAL FIX: Memoize onPositionChange to prevent usePlayerMovement callback recreation
  // Without this, a new function is created every render, causing animation frame cancellation
  const handlePlayer1PositionChange = useCallback(
    (newPosition: Position) => {
      setPlayer1Position(newPosition);
      onPlayerUpdate(0, { position: newPosition });
    },
    [onPlayerUpdate],
  );
 
  // CRITICAL FIX: Memoize bounds object to prevent usePlayerMovement callback recreation
  // Without this, a new object reference is created every render, causing animation frame cancellation
  const movementBounds = useMemo(
    () => ({
      worldWidthMeters: arenaBounds.worldWidthMeters,
      worldDepthMeters: arenaBounds.worldDepthMeters,
    }),
    [arenaBounds.worldWidthMeters, arenaBounds.worldDepthMeters],
  );
 
  // ═══════════════════════════════════════════════════════════════════════════
  // Acceleration-Based Running System for Player 1
  // ═══════════════════════════════════════════════════════════════════════════
 
  // Track continuous movement time for acceleration-based running
  const player1MovementTimeRef = useRef(0);
  const player1LastDirectionRef = useRef<{ x: number; y: number }>({
    x: 0,
    y: 0,
  });
 
  // Track acceleration-based speed (interpolated between walk and run speeds)
  // This applies archetype speeds and stance modifiers
  const [player1AccelerationBasedSpeed, setPlayer1AccelerationBasedSpeed] =
    useState(player1WalkRunSpeeds.walkSpeed);
 
  // Determine if currently running using utility function with archetype run speed
  const player1IsRunning = isRunningSpeed(
    player1AccelerationBasedSpeed,
    player1WalkRunSpeeds.runSpeed,
  );
 
  // Player movement with physics-based acceleration and stance modifiers
  // All positions in METERS - no pixel conversions
  const { isMoving: player1IsMoving, velocity: player1Velocity } =
    usePlayerMovement({
      enabled:
        !isPaused &&
        combatState.roundStarted &&
        !combatState.roundEnded &&
        matchCountdownComplete &&
        !showRoundStart,
      bounds: movementBounds, // Use memoized bounds object
      onPositionChange: handlePlayer1PositionChange, // Use memoized callback
      initialPositionMeters: player1Position,
      // Physics parameters for realistic movement (always enabled)
      currentStance: player1Data.currentStance,
      legInjuryFactor: player1Data.legInjuryFactor,
      isRunning: player1IsRunning, // Use computed acceleration-based running state
      useTacticalSteps: false,
      // Use interpolated speed between modifier-aware walk/run speeds
      // This preserves archetype speeds and stance modifiers
      maxSpeedOverride: player1AccelerationBasedSpeed,
      accelerationOverride: player1SpeedModifiers.finalAcceleration,
    });
 
  // Player 1 rotation: face movement direction when moving, opponent when idle
  // 이동 중에는 이동 방향을, 정지 시에는 상대를 향함
  const player1Rotation = useMemo(() => {
    Iif (
      player1IsMoving &&
      player1Velocity &&
      (player1Velocity.x !== 0 || player1Velocity.y !== 0)
    ) {
      // When moving: face movement direction
      // velocity.x is lateral (left/right), velocity.y is forward/backward (Z in 3D)
      // Use velocity.y directly (not negated) so down arrow faces correctly
      const movementRotation = Math.atan2(player1Velocity.x, player1Velocity.y);
      player1LastRotationRef.current = movementRotation;
      return movementRotation;
    } else {
      // When idle: face opponent
      const dx = player2Position3D[0] - player1Position3D[0];
      const dz = player2Position3D[2] - player1Position3D[2];
      const targetRotation = Math.atan2(dx, dz);
      player1LastRotationRef.current = targetRotation;
      return targetRotation;
    }
  }, [player1IsMoving, player1Velocity, player1Position3D, player2Position3D]);
 
  // Use ref to store attack handler to avoid circular dependencies
  const handleAttackRef = useRef<(() => void) | null>(null);
 
  // Ref for player1Animation to avoid circular dependencies in animation events
  const player1AnimationRef = useRef<ReturnType<
    typeof usePlayerAnimation
  > | null>(null);
 
  // Ref for validPlayers to avoid circular dependencies
  const validPlayersRefForAnimation = useRef<[PlayerState, PlayerState] | null>(
    null,
  );
 
  // Tracks the frame at which the attack hit should fire (set per-technique)
  // and whether it has already been fired for the current attack
  const player1HitTriggerFrameRef = useRef<number>(6);
  const player1AttackHitFiredRef = useRef<boolean>(false);
 
  // Track attack animation durations for physics synchronization
  // 물리 동기화를 위한 공격 애니메이션 지속시간 추적
  const player1AttackDurationRef = useRef<number>(0.55);
  const player2AttackDurationRef = useRef<number>(0.55);
 
  // Refs to clear attack animations after completion
  const clearPlayer1AttackAnimation = useRef<() => void>(() => {
    setPlayer1AttackAnimation(undefined);
    setPlayer1TechniqueId(undefined);
  });
  const clearPlayer2AttackAnimation = useRef<() => void>(() => {
    setPlayer2AttackAnimation(undefined);
    setPlayer2TechniqueId(undefined);
  });
 
  // Player animation state machines - manages animation transitions at 60fps
  // Memoize events object to maintain stability (required by usePlayerAnimation)
  const player1AnimationEvents = useMemo<AnimationEvents>(
    () => ({
      onFrame: (frame, state) => {
        // Execute attack when strike reaches peak extension
        // The hit trigger frame is set dynamically when attack starts
        // 공격 히트 트리거 프레임은 공격 시작 시 동적으로 설정됨
        if (
          state === AnimationState.ATTACK &&
          frame >= player1HitTriggerFrameRef.current &&
          !player1AttackHitFiredRef.current
        ) {
          player1AttackHitFiredRef.current = true;
          handleAttackRef.current?.();
        }
      },
      onAnimationComplete: (state) => {
        // Handle animation completion
        if (
          state === AnimationState.ATTACK ||
          state === AnimationState.DEFEND
        ) {
          combatActions.setExecutingTechnique(false);
          // Clear attack animation when attack completes
          // 공격 완료 시 공격 애니메이션 초기화
          if (state === AnimationState.ATTACK) {
            clearPlayer1AttackAnimation.current();
          }
        } else if (state === AnimationState.STANCE_CHANGE) {
          // Stance change animation completed - transition to stance guard
          // 자세 변경 완료 - 자세 가드로 전환
          audio.playSFX("menu_select");
          const players = validPlayersRefForAnimation.current;
          const currentStance = players?.[0]?.currentStance;
          if (currentStance && player1AnimationRef.current) {
            player1AnimationRef.current.transitionToStanceGuard(currentStance);
          }
        }
      },
    }),
    [combatActions, audio],
  );
 
  const player1Animation = usePlayerAnimation({
    events: player1AnimationEvents,
  });
 
  // Store animation ref for use in event callbacks
  useEffect(() => {
    player1AnimationRef.current = player1Animation;
  }, [player1Animation]);
 
  const player2Animation = usePlayerAnimation({
    events: {
      onFrame: (frame, state) => {
        if (state === AnimationState.ATTACK && frame === 6) {
          // AI attack hit detection
        }
      },
      onAnimationComplete: (state) => {
        // Clear AI attack animation when attack completes
        // AI 공격 완료 시 공격 애니메이션 초기화
        if (state === AnimationState.ATTACK) {
          clearPlayer2AttackAnimation.current();
        }
      },
    },
  });
 
  // Sync movement with player 1 animation (avoid circular dependency)
  // 플레이어 1 이동-애니메이션 동기화
  const prevPlayer1IsMovingRef = useRef<boolean>(player1IsMoving);
  const prevPlayer1IsRunningRef = useRef<boolean>(player1IsRunning);
  useEffect(() => {
    // Check for movement or running state changes
    const movementChanged = prevPlayer1IsMovingRef.current !== player1IsMoving;
    const runningChanged = prevPlayer1IsRunningRef.current !== player1IsRunning;
 
    Iif (movementChanged || runningChanged) {
      if (player1IsMoving) {
        // Transition to RUN or WALK based on speed
        const targetState = player1IsRunning
          ? AnimationState.RUN
          : AnimationState.WALK;
        if (player1Animation.currentState !== targetState) {
          player1Animation.transitionTo(targetState);
        }
      } else if (
        player1Animation.currentState === AnimationState.WALK ||
        player1Animation.currentState === AnimationState.RUN
      ) {
        // When stopping movement, transition to stance-specific guard animation
        // 이동 중지 시 자세별 가드 애니메이션으로 전환
        player1Animation.transitionToStanceGuard(player1Data.currentStance);
      }
      prevPlayer1IsMovingRef.current = player1IsMoving;
      prevPlayer1IsRunningRef.current = player1IsRunning;
    }
  }, [
    player1IsMoving,
    player1IsRunning,
    player1Animation,
    player1Data.currentStance,
  ]);
 
  // Movement detection threshold for AI animation sync (in pixels)
  // Lower values = more sensitive to small movements, higher values = smoother transitions
  const MOVEMENT_DETECTION_THRESHOLD = 0.5;
 
  // Get player 2 stance for animation transitions
  // 플레이어 2 자세 (애니메이션 전환용)
  const player2Stance = useMemo(() => {
    return players[1]?.currentStance ?? TrigramStance.GEON;
  }, [players]);
 
  // Sync movement with player 2 animation (AI movement detection)
  const prevPlayer2PositionRef = useRef(player2Position);
  useEffect(() => {
    const currentPos = playerPositions[1];
    const prevPos = prevPlayer2PositionRef.current;
 
    // Detect if Player2 (AI) is moving by comparing positions
    const isMoving =
      Math.abs(currentPos.x - prevPos.x) > MOVEMENT_DETECTION_THRESHOLD ||
      Math.abs(currentPos.y - prevPos.y) > MOVEMENT_DETECTION_THRESHOLD;
 
    Iif (isMoving) {
      // AI is moving - transition to walk animation
      if (
        player2Animation.currentState !== AnimationState.WALK &&
        player2Animation.currentState !== AnimationState.ATTACK
      ) {
        player2Animation.transitionTo(AnimationState.WALK);
      }
    } else {
      // AI stopped - transition to stance-specific guard animation
      // AI 이동 중지 - 자세별 가드 애니메이션으로 전환
      Iif (player2Animation.currentState === AnimationState.WALK) {
        player2Animation.transitionToStanceGuard(player2Stance);
      }
    }
 
    prevPlayer2PositionRef.current = currentPos;
  }, [playerPositions, player2Animation, player2Stance]);
 
  // Valid players with complete state
  const validPlayers = useMemo((): [PlayerState, PlayerState] => {
    Iif (players.length === 0) {
      const player1 = createPlayerFromArchetype(PlayerArchetype.MUSA, 0);
      const player2 = createPlayerFromArchetype(PlayerArchetype.AMSALJA, 1);
 
      return [
        { ...player1, position: playerPositions[0] },
        { ...player2, position: playerPositions[1] },
      ];
    }
 
    const player1 = players[0];
    const player2 =
      players[1] ?? createPlayerFromArchetype(PlayerArchetype.AMSALJA, 1);
 
    return [
      { ...player1, position: playerPositions[0] },
      { ...player2, position: playerPositions[1] },
    ];
  }, [players, playerPositions]);
 
  // Use ref to access latest player health without causing re-renders
  const validPlayersRef = useRef<[PlayerState, PlayerState]>(validPlayers);
  useEffect(() => {
    validPlayersRef.current = validPlayers;
    validPlayersRefForAnimation.current = validPlayers;
  }, [validPlayers]);
 
  // Helper function to get AnimationType from technique ID
  // Uses enum-based mapping for type safety and proper technique support
  // 기술 ID에서 AnimationType을 가져오는 헬퍼 함수
  // 타입 안전성과 적절한 기술 지원을 위해 열거형 기반 매핑 사용
  const getTechniqueAnimationType = useCallback(
    (techniqueId: string | undefined): AnimationType | undefined => {
      Eif (!techniqueId) return undefined;
 
      // Use enum-based lookup for all techniques
      // This properly handles stance-specific techniques like "geon_heaven_strike"
      // 모든 기술에 대해 열거형 기반 조회 사용
      // "geon_heaven_strike"와 같은 자세별 기술을 올바르게 처리
      return getAnimationTypeForTechnique(techniqueId);
    },
    [],
  );
 
  // Attack movement integration - track attack states for physics-based forward movement
  // 공격 이동 통합 - 물리 기반 전방 이동을 위한 공격 상태 추적
  // Note: Must be called after validPlayers, player animations, and 3D positions are defined
  const {
    player1Position: player1PositionWithAttackMovement,
    player2Position: player2PositionWithAttackMovement,
  } = useCombatAttackMovement({
    player1Attacking: player1Animation.currentState === AnimationState.ATTACK,
    player1AnimationType: getTechniqueAnimationType(player1TechniqueId),
    player1Stance: player1Data.currentStance,
    player1BasePosition: player1Position3D,
    player1AnimationDuration: player1AttackDurationRef.current,
    player2Attacking: player2Animation.currentState === AnimationState.ATTACK,
    player2AnimationType: getTechniqueAnimationType(player2TechniqueId),
    player2Stance: validPlayers[1].currentStance,
    player2BasePosition: player2Position3D,
    player2AnimationDuration: player2AttackDurationRef.current,
  });
 
  // ═══════════════════════════════════════════════════════════════════════════
  // Local stance state for Player 1 - Enables immediate technique bar updates
  // ═══════════════════════════════════════════════════════════════════════════
  // The player stance from props requires a round-trip through App.tsx, causing
  // the technique bar to update with a delay. This local state updates immediately
  // when stance changes, then syncs with the parent state.
  // (이 로컬 상태는 자세 변경 시 즉시 업데이트되어 기술바가 바로 반응함)
  const [player1LocalStance, setPlayer1LocalStance] = useState<TrigramStance>(
    validPlayers[0].currentStance,
  );
 
  // Sync local stance with prop when it changes (e.g., on round restart)
  useEffect(() => {
    setPlayer1LocalStance(validPlayers[0].currentStance);
  }, [validPlayers]);
 
  // Create player object with local stance for immediate technique bar updates
  // This ensures useTechniqueSelection gets the updated stance synchronously
  const player1WithLocalStance = useMemo(
    (): PlayerState => ({
      ...validPlayers[0],
      currentStance: player1LocalStance,
    }),
    [validPlayers, player1LocalStance],
  );
 
  // Use refs for stable access to startTransition and internalRound
  const startTransitionRef = useRef(startTransition);
  const internalRoundRef = useRef(internalRound);
  useEffect(() => {
    startTransitionRef.current = startTransition;
    internalRoundRef.current = internalRound;
  }, [startTransition, internalRound]);
 
  // Combat messages
  const addCombatMessage = useCallback(
    (korean: string, english: string) => {
      const message = `${korean} | ${english}`;
      combatActions.addCombatMessage(message);
    },
    [combatActions],
  );
 
  // Combat timer with warnings and time up handler
  const handleTimeUp = useCallback(() => {
    // End round when time runs out
    if (!combatState.roundEnded) {
      combatActions.setRoundEnded(true);
      addCombatMessage("시간 종료!", "Time's Up!");
 
      // Use refs to get latest values without dependency issues
      const currentPlayers = validPlayersRef.current;
      const player1Health = currentPlayers[0].health;
      const player2Health = currentPlayers[1].health;
 
      if (player1Health > player2Health) {
        // Player 1 wins - update match score
        updateMatchScore(0);
        startTransitionRef.current(currentPlayers[0], internalRoundRef.current); // Player 1 wins round
      } else if (player2Health > player1Health) {
        // Player 2 wins - update match score
        updateMatchScore(1);
        startTransitionRef.current(currentPlayers[1], internalRoundRef.current); // Player 2 wins round
      } else {
        // Tie - no winner for this round, no score update
        startTransitionRef.current(null, internalRoundRef.current);
      }
    }
  }, [
    combatState.roundEnded,
    combatActions,
    addCombatMessage,
    updateMatchScore,
  ]);
 
  // Ref pattern to stabilize onTimeUp callback for timer
  const handleTimeUpRef = useRef(handleTimeUp);
  useEffect(() => {
    handleTimeUpRef.current = handleTimeUp;
  }, [handleTimeUp]);
 
  // Create a unique key for timer reset based on round number
  // This forces the timer to reset when a new round starts
  const timerResetKey = `round-${internalRound}`;
 
  const timerState = useCombatTimer({
    initialTime: Math.max(0, timeRemaining),
    isPaused:
      isPaused ||
      !combatState.roundStarted ||
      combatState.roundEnded ||
      !matchCountdownComplete ||
      showRoundStart,
    onTimeUp: useCallback(() => handleTimeUpRef.current(), []),
    warningThreshold: 10,
    urgentThreshold: 5,
    // Pass round number to force timer reset on new rounds
    resetKey: timerResetKey,
  });
 
  // Shared round start logic - forces round to start regardless of current state
  // This is called after state has been reset, so we trust the caller
  // Note: Using useCallback with complete dependencies to ensure closure has latest state
  const startRound = useCallback(() => {
    // Always start the round when this is called - the caller is responsible
    // for ensuring this is the right time to start
    if (import.meta.env.DEV) {
      console.log("[DEV] Starting round, setting roundStarted=true");
    }
    combatActions.setRoundStarted(true);
    combatActions.setRoundEnded(false); // Ensure roundEnded is false
    addCombatMessage("라운드 시작!", "Round Start!");
 
    const player = validPlayers[0];
    if (player?.archetype) {
      const playerArchetype = player.archetype.toLowerCase();
      combatAudio.playArchetypeMusic(playerArchetype, 2000);
    } else {
      combatAudio.playCombatMusic(2000);
    }
  }, [combatActions, addCombatMessage, validPlayers, combatAudio]);
 
  // Auto-start first round since countdown is disabled
  // Use a separate ref for the timer to avoid cleanup canceling the start
  const hasAutoStartedRef = useRef(false);
 
  useEffect(() => {
    if (matchCountdownComplete && !hasAutoStartedRef.current) {
      hasAutoStartedRef.current = true;
      // Directly set roundStarted=true without going through startRound callback
      // This avoids dependency issues with the callback reference
      combatActions.setRoundStarted(true);
      addCombatMessage("라운드 시작!", "Round Start!");
 
      // Start music
      const player = validPlayers[0];
      if (player?.archetype) {
        const playerArchetype = player.archetype.toLowerCase();
        combatAudio.playArchetypeMusic(playerArchetype, 2000);
      } else E{
        combatAudio.playCombatMusic(2000);
      }
    }
  }, [
    matchCountdownComplete,
    combatActions,
    addCombatMessage,
    validPlayers,
    combatAudio,
  ]);
 
  // AI systems
  const adaptiveDifficulty = useMemo(() => new AdaptiveDifficulty(), []);
 
  // Persist AI difficulty metrics
  useEffect(() => {
    try {
      const savedMetrics = localStorage.getItem("ai_difficulty_metrics");
      if (savedMetrics) {
        adaptiveDifficulty.importMetrics(savedMetrics);
      }
    } catch (err) {
      console.warn("Failed to load AI difficulty metrics:", err);
    }
 
    return () => {
      try {
        const metrics = adaptiveDifficulty.exportMetrics();
        localStorage.setItem("ai_difficulty_metrics", metrics);
      } catch (err) {
        console.warn("Failed to save AI difficulty metrics:", err);
      }
    };
  }, [adaptiveDifficulty]);
 
  const aiPersonality = useMemo(
    () => getPersonalityByArchetype(validPlayers[1].archetype),
    [validPlayers],
  );
 
  // AI stance change handler
  const handleAIStanceChange = useCallback(
    (stance: TrigramStance) => {
      const currentStance = validPlayers[1].currentStance;
 
      // Start stance-specific transition animation for AI
      player2Animation.transitionToStanceChange(currentStance, stance);
 
      onPlayerUpdate(1, { currentStance: stance });
      addCombatMessage(
        `AI 자세 변경: ${stance}`,
        `AI Stance Change: ${stance}`,
      );
    },
    [validPlayers, player2Animation, onPlayerUpdate, addCombatMessage],
  );
 
  // Hit effect handlers
  const handleEffectComplete = useCallback(
    (effectId: string) => {
      combatActions.removeHitEffect(effectId);
    },
    [combatActions],
  );
 
  const createHitEffect = useCallback(
    (
      id: string,
      type: HitEffectType,
      position: Position,
      intensity: number,
    ): HitEffect => ({
      id,
      type,
      attackerId: "player1",
      defenderId: "player2",
      timestamp: Date.now(),
      duration: 1000,
      position,
      intensity,
      startTime: Date.now(),
    }),
    [],
  );
 
  const addHitEffect = useCallback(
    (type: HitEffectType, position: Position, intensity: number = 1) => {
      const effect = createHitEffect(
        `effect_${Date.now()}`,
        type,
        position,
        intensity,
      );
      combatActions.addHitEffect(effect);
    },
    [createHitEffect, combatActions],
  );
 
  // Callback for updating player positions after knockback
  const handlePlayerPositionUpdate = useCallback(
    (playerIndex: number, position: Position) => {
      if (playerIndex === 0) {
        setPlayer1Position(position);
        onPlayerUpdate(0, { position });
      } else if (playerIndex === 1) {
        // For AI, update position through onPlayerUpdate
        // This will be reflected in player2Position which is derived from players prop
        onPlayerUpdate(1, { position });
      }
    },
    [onPlayerUpdate, setPlayer1Position],
  );
 
  // Callback for creating injuries from combat damage with progressive bruising
  // 전투 피해로부터 부상 생성 콜백 (점진적 타박상 포함)
  const handleInjuryCreated = useCallback(
    (injury: Injury, targetPlayerIndex: number) => {
      const updateInjuries = (prev: readonly Injury[]): readonly Injury[] => {
        // Check for recent hits to the same body region (within 5 seconds)
        const recentHitTime = 5000; // 5 seconds
        const now = Date.now();
 
        const recentHit = prev.find(
          (existing) =>
            existing.region === injury.region &&
            now - existing.timestamp < recentHitTime &&
            existing.type === InjuryType.BRUISE &&
            injury.type === InjuryType.BRUISE,
        );
 
        if (recentHit) {
          // Progressive bruising: increase hit count and severity
          const newHitCount = recentHit.hitCount + 1;
          const escalatedSeverity = Math.min(1.0, recentHit.severity + 0.15);
 
          // Update the existing injury with increased severity and hit count
          // Only update existing injury, do not add a duplicate
          return prev.map((existing) =>
            existing.id === recentHit.id
              ? {
                  ...existing,
                  hitCount: newHitCount,
                  severity: escalatedSeverity,
                  timestamp: now, // Update timestamp for progressive tracking
                }
              : existing,
          );
        }
 
        // No recent hit to same region - add as new injury
        return [...prev, injury];
      };
 
      if (targetPlayerIndex === 0) {
        setPlayer1Injuries(updateInjuries);
      } else if (targetPlayerIndex === 1) {
        setPlayer2Injuries(updateInjuries);
      }
    },
    [],
  );
 
  // Combat action handlers
  const {
    handleAttack,
    handleDefend,
    handleStanceSwitch,
    handleStanceSideSwitch,
    handleAIAttack,
    handleAIDefend,
    handleAITechnique,
    moveAIPlayer,
  } = useCombatActions({
    validPlayers,
    playerPositions: [playerPositions[0], playerPositions[1]],
    combatState,
    combatActions,
    combatSystem,
    onPlayerUpdate,
    onPlayerPositionUpdate: handlePlayerPositionUpdate,
    onLateralityUpdate: (playerIndex, laterality) => {
      combatActions.setPlayerLateralityIndex(playerIndex as 0 | 1, laterality);
    },
    onInjuryCreated: handleInjuryCreated,
    addCombatMessage,
    addHitEffect,
    arenaBounds,
    combatAudio,
    playerAnimations: {
      player1: player1Animation,
      player2: player2Animation,
    },
  });
 
  // Store handleAttack in ref for animation callback (avoid circular dependency)
  useEffect(() => {
    handleAttackRef.current = handleAttack;
  }, [handleAttack]);
 
  // Technique selection and execution
  // Uses player1WithLocalStance for immediate technique bar updates when stance changes
  // (자세 변경 시 기술바가 즉시 업데이트되도록 로컬 자세 상태 사용)
  const techniqueSelection = useTechniqueSelection({
    player: player1WithLocalStance,
    enabled:
      !isPaused &&
      combatState.roundStarted &&
      !combatState.roundEnded &&
      matchCountdownComplete &&
      !showRoundStart,
    onTechniqueExecute: useCallback(
      (technique: Technique) => {
        // Show technique name in action feedback
        feedbackActions.showTechnique(
          technique.name.korean,
          technique.name.english,
        );
 
        // Set attack animation based on technique
        // 기술에 따른 공격 애니메이션 설정
        const animationName = getAnimationForTechnique(
          technique.name.english || technique.id,
        );
        setPlayer1AttackAnimation(animationName);
 
        // Store technique ID for enum-based AnimationType lookup
        // 열거형 기반 AnimationType 조회를 위한 기술 ID 저장
        setPlayer1TechniqueId(technique.id);
 
        // Get the actual skeletal animation duration for this technique
        // so the state machine stays in ATTACK for the full animation.
        // 기술의 실제 스켈레탈 애니메이션 지속시간을 가져와서
        // 상태 머신이 전체 애니메이션 동안 ATTACK 상태를 유지하도록 함
        const skeletalAnim = getAnimation(animationName);
        const attackDuration = skeletalAnim?.duration ?? 0.55;
 
        // Trigger attack animation transition with technique-matched duration
        // 기술 매칭 지속시간으로 공격 애니메이션 전환 트리거
        const attackFrames = Math.max(1, Math.round(attackDuration * 60));
        // Trigger hit at ~40% of the attack (when strike reaches peak extension)
        player1HitTriggerFrameRef.current = Math.round(attackFrames * 0.4);
        player1AttackHitFiredRef.current = false;
        // Store duration for physics hook
        player1AttackDurationRef.current = attackDuration;
        player1Animation.transitionToAttack(attackDuration);
        combatActions.setExecutingTechnique(true);
 
        // Deduct resources
        onPlayerUpdate(0, {
          stamina: Math.max(0, validPlayers[0].stamina - technique.staminaCost),
          ki: Math.max(0, validPlayers[0].ki - technique.kiCost),
        });
 
        // Execute attack WITH the selected technique (not basic attack)
        handleAttack(technique);
 
        // Add combat message
        addCombatMessage(
          `${technique.name.korean} 사용!`,
          `Used ${technique.name.english}!`,
        );
      },
      [
        validPlayers,
        onPlayerUpdate,
        feedbackActions,
        handleAttack,
        addCombatMessage,
        player1Animation,
        combatActions,
      ],
    ),
  });
 
  // Convert cooldowns to Map for TechniqueBar
  const cooldownsMap = useMemo(() => {
    const map = new Map<string, number>();
    techniqueSelection.activeCooldowns.forEach((cd) => {
      map.set(cd.techniqueId, cd.remaining);
    });
    return map;
  }, [techniqueSelection.activeCooldowns]);
 
  // Track previous stance for visual feedback
  const [previousStance, setPreviousStance] = useState<number>(0);
 
  // Get current stance index for visual feedback using optimized lookup
  const currentPlayerStance = validPlayers[0].currentStance;
  const currentStanceIndex = useMemo(() => {
    return STANCE_INDEX_MAP.get(currentPlayerStance) ?? 0;
  }, [currentPlayerStance]);
 
  // Handler for stance changes with animation integration
  const handleStanceChangeWithAnimation = useCallback(
    (newStance: TrigramStance) => {
      const currentStance = validPlayers[0].currentStance;
 
      // Transition directly to stance guard (skip transitional animation)
      // The transitional STANCE_CHANGE animation uses idle_stance which loops forever
      // and never completes, so we go directly to the target stance guard
      const success = player1Animation.transitionToStanceGuard(newStance);
 
      if (success) {
        // Capture previous stance for visual feedback
        const prevStance = STANCE_INDEX_MAP.get(currentStance) ?? 0;
        setPreviousStance(prevStance);
 
        // Update local stance immediately for instant technique bar update
        // This ensures the technique bar updates before the prop round-trip completes
        // (기술바가 즉시 업데이트되도록 로컬 자세 상태를 먼저 변경)
        setPlayer1LocalStance(newStance);
 
        // Update combat state (triggers prop update through App.tsx)
        handleStanceSwitch(newStance);
 
        // Play stance change sound
        playStanceChangeSound();
      }
    },
    [validPlayers, player1Animation, handleStanceSwitch, playStanceChangeSound],
  );
 
  // Extract player health values for dependency arrays
  const player1Health = validPlayers[0].health;
  const player2Health = validPlayers[1].health;
 
  // Watch for player 2 health decrease to trigger damage feedback
  const lastPlayer2HealthRef = useRef(player2Health);
  useEffect(() => {
    const currentHealth = player2Health;
    const previousHealth = lastPlayer2HealthRef.current;
    const damageDone = previousHealth - currentHealth;
 
    Iif (damageDone > 0 && combatState.roundStarted && !combatState.roundEnded) {
      // Determine damage type based on amount
      const getDamageType = (): "critical" | "vital" | "normal" => {
        if (damageDone >= 25) return "critical";
        if (damageDone >= 20) return "vital";
        return "normal";
      };
      const damageType = getDamageType();
 
      // Add damage number at opponent position
      feedbackActions.addDamageNumber(
        Math.round(damageDone),
        playerPositions[1],
        damageType,
      );
 
      // Increment combo
      feedbackActions.incrementCombo();
 
      // Add action feedback for critical hits
      if (damageType === "critical") {
        feedbackActions.addActionFeedback(
          "critical",
          "Critical!",
          "치명타!",
          playerPositions[0],
        );
      }
    }
 
    lastPlayer2HealthRef.current = currentHealth;
  }, [
    player2Health,
    validPlayers,
    playerPositions,
    feedbackActions,
    combatState.roundStarted,
    combatState.roundEnded,
  ]);
 
  // Watch for player 1 health decrease (AI attacks player)
  const lastPlayer1HealthRef = useRef(player1Health);
  useEffect(() => {
    const currentHealth = player1Health;
    const previousHealth = lastPlayer1HealthRef.current;
    const damageDone = previousHealth - currentHealth;
 
    Iif (damageDone > 0 && combatState.roundStarted && !combatState.roundEnded) {
      // Add damage number at player position for AI hits
      const damageType =
        damageDone >= 20 ? ("critical" as const) : ("normal" as const);
      feedbackActions.addDamageNumber(
        Math.round(damageDone),
        playerPositions[0],
        damageType,
      );
    }
 
    lastPlayer1HealthRef.current = currentHealth;
  }, [
    player1Health,
    validPlayers,
    playerPositions,
    feedbackActions,
    combatState.roundStarted,
    combatState.roundEnded,
  ]);
 
  // Create enhanced attack handler with action feedback and animation
  const handleAttackWithFeedback = useCallback(() => {
    // Set default attack animation for basic attacks (without specific technique)
    // 기본 공격 애니메이션 설정 (잽)
    setPlayer1AttackAnimation("jab");
 
    // Try to transition to attack animation
    const success = player1Animation.transitionTo(AnimationState.ATTACK);
    if (success) {
      // Attack execution will happen at frame 6 in onFrame callback
      combatActions.setExecutingTechnique(true);
    } else {
      // Fallback: animation transition failed, execute attack logic immediately
      console.warn(
        "Attack animation transition failed; executing attack logic directly.",
      );
      handleAttack();
    }
  }, [player1Animation, combatActions, handleAttack]);
 
  // Create enhanced defend handler with action feedback and animation
  const handleDefendWithFeedback = useCallback(() => {
    const defenderPos = playerPositions[0];
    // Try to transition to defend animation
    const success = player1Animation.transitionTo(AnimationState.DEFEND);
    if (success) {
      handleDefend();
      feedbackActions.addActionFeedback(
        "blocked",
        "Blocked",
        "방어!",
        defenderPos,
      );
    } else {
      // Fallback: animation transition failed, execute defend logic immediately
      console.warn(
        "Defend animation transition failed; executing defend logic directly.",
      );
      handleDefend();
      feedbackActions.addActionFeedback(
        "blocked",
        "Blocked",
        "방어!",
        defenderPos,
      );
    }
  }, [handleDefend, playerPositions, feedbackActions, player1Animation]);
 
  /**
   * Helper function to execute fallback recovery animation
   * when a specific recovery type cannot be performed.
   *
   * Determines the appropriate recovery type based on ground state
   * and transitions to that animation.
   *
   * @korean 대체회복실행
   */
  const executeFallbackRecovery = useCallback(() => {
    const groundState = balanceSystem.getGroundState(
      player1Animation.currentState,
    );
    if (groundState) {
      const recoveryType = determineRecoveryType(groundState);
      const animationState = getRecoveryAnimationState(recoveryType);
      player1Animation.transitionTo(animationState as AnimationState);
    }
  }, [balanceSystem, player1Animation]);
 
  // Use keyboard controls hook for enhanced input handling with visual feedback
  const { queuedInputs, showHints } = useKeyboardControls({
    onStanceChange: useCallback(
      (stanceIndex: number) => {
        const stance = TRIGRAM_STANCES_ORDER[stanceIndex];
        if (stance) {
          // Use integrated stance transition animation
          handleStanceChangeWithAnimation(stance);
        }
      },
      [handleStanceChangeWithAnimation],
    ),
    onAction: useCallback(
      (action: string) => {
        switch (action) {
          case "attack":
            // Execute currently selected technique via technique selection system
            techniqueSelection.executeTechnique();
            break;
          case "block":
            handleDefendWithFeedback();
            break;
          // Recovery actions (기상 액션)
          case "recovery_quick": {
            // Quick recovery: determine type based on ground state
            executeFallbackRecovery();
            break;
          }
          case "recovery_roll": {
            // Roll recovery: costs stamina but fastest
            const player1 = players[0];
            if (balanceSystem.canRecoverWithType(player1, "roll_recovery")) {
              const updatedPlayer = balanceSystem.applyRecoveryCost(
                player1,
                "roll_recovery",
              );
              onPlayerUpdate(0, { stamina: updatedPlayer.stamina });
              player1Animation.transitionTo(AnimationState.RECOVERY_ROLL);
            } else {
              // Not enough stamina, fallback to quick recovery
              audio.playSFX("menu_error");
              const player1Pos = playerPositions[0];
              feedbackActions.addActionFeedback(
                "blocked",
                "Not enough stamina!",
                "체력 부족!",
                player1Pos,
              );
              executeFallbackRecovery();
            }
            break;
          }
          case "recovery_defensive": {
            // Defensive getup: slow but protected
            player1Animation.transitionTo(AnimationState.RECOVERY_DEFENSIVE);
            break;
          }
 
          // Footwork pattern actions
          case "footwork_circular_left":
          case "footwork_circular_right":
          case "footwork_slide_forward":
          case "footwork_slide_back":
          case "footwork_pivot_left":
          case "footwork_pivot_right":
          case "footwork_shuffle":
            // Execute footwork animation
            player1Animation.transitionTo(action as AnimationState);
            break;
 
          // Stance side switch
          case "stance_side_switch":
            // Switch front foot (mirror stance)
            player1Animation.transitionTo(AnimationState.STANCE_SIDE_SWITCH);
            break;
 
          // Movement and other actions handled by existing system
        }
      },
      [
        techniqueSelection,
        handleDefendWithFeedback,
        executeFallbackRecovery,
        balanceSystem,
        player1Animation,
        players,
        onPlayerUpdate,
        audio,
        feedbackActions,
        playerPositions,
      ],
    ),
    enabled:
      !isPaused &&
      !showPauseMenu &&
      combatState.roundStarted &&
      !combatState.roundEnded &&
      matchCountdownComplete &&
      !showRoundStart &&
      !combatState.isExecutingTechnique,
    currentStance: currentStanceIndex,
    playSFX: audio.playSFX,
    currentAnimationState: player1Animation.currentState,
  });
 
  // Mobile touch control state - stance wheel for mobile stance changes
  const [stanceWheelExpanded, setStanceWheelExpanded] = useState(false);
  const activeMobileKeyRef = useRef<string | null>(null);
 
  /**
   * Mobile touch control handler - Converts VirtualDPad touch inputs to keyboard events
   *
   * Dispatches synthetic KeyboardEvents with proper properties to ensure compatibility
   * with usePlayerMovement hook. The synthetic events include:
   * - key: The character key (w/a/s/d)
   * - code: The physical key code (KeyW/KeyA/KeyS/KeyD)
   * - bubbles: true - Allows event to propagate through DOM
   * - cancelable: true - Allows event to be prevented
   *
   * These properties are essential for the keyboard event listeners in inputSystem.ts
   * to properly recognize and process the movement commands.
   *
   * @param direction - The D-pad direction or null
   * @param eventType - 'start' for press, 'end' for release
   */
  const handleMobileMove = useCallback(
    (direction: Direction | null, eventType: DPadEventType) => {
      // Map D-pad directions to movement keys (WASD)
      const directionMap: Record<Direction, string> = {
        up: "w",
        "up-right": "w", // Diagonal simplified to primary direction
        right: "d",
        "down-right": "s",
        down: "s",
        "down-left": "s",
        left: "a",
        "up-left": "w",
      };
 
      if (eventType === "start" && direction) {
        // Release previous key if different (prevents stuck keys)
        if (
          activeMobileKeyRef.current &&
          activeMobileKeyRef.current !== directionMap[direction]
        ) {
          const prevKey = activeMobileKeyRef.current;
          window.dispatchEvent(
            new KeyboardEvent("keyup", {
              key: prevKey,
              code: `Key${prevKey.toUpperCase()}`,
              bubbles: true,
              cancelable: true,
            }),
          );
        }
 
        // Press new key with proper keyboard event properties
        // These properties ensure usePlayerMovement recognizes the synthetic event
        const key = directionMap[direction];
        activeMobileKeyRef.current = key;
        window.dispatchEvent(
          new KeyboardEvent("keydown", {
            key,
            code: `Key${key.toUpperCase()}`,
            bubbles: true,
            cancelable: true,
          }),
        );
      } else if (eventType === "end") {
        // Release active key when D-pad released
        if (activeMobileKeyRef.current) {
          const key = activeMobileKeyRef.current;
          window.dispatchEvent(
            new KeyboardEvent("keyup", {
              key,
              code: `Key${key.toUpperCase()}`,
              bubbles: true,
              cancelable: true,
            }),
          );
          activeMobileKeyRef.current = null;
        }
      }
    },
    [],
  );
 
  const handleMobileAttack = useCallback(() => {
    // Execute currently selected technique via technique selection system
    techniqueSelection.executeTechnique();
  }, [techniqueSelection]);
 
  const handleMobileBlock = useCallback(
    (eventType: ButtonEventType) => {
      if (eventType === "start") {
        handleDefendWithFeedback();
      }
    },
    [handleDefendWithFeedback],
  );
 
  // Mobile stance wheel and gesture controls
  const handleMobileStanceChange = useCallback(
    (stanceIndex: number) => {
      const stance = TRIGRAM_STANCES_ORDER[stanceIndex];
      if (stance) {
        // Use integrated stance transition animation
        handleStanceChangeWithAnimation(stance);
      }
    },
    [handleStanceChangeWithAnimation],
  );
 
  const handleMobileGesture = useCallback(
    (gesture: GestureEvent) => {
      switch (gesture.type) {
        case "swipe-right":
          // Advance toward opponent - dispatch keydown then keyup to prevent stuck movement
          window.dispatchEvent(new KeyboardEvent("keydown", { key: "d" }));
          setTimeout(() => {
            window.dispatchEvent(new KeyboardEvent("keyup", { key: "d" }));
          }, 100);
          break;
        case "swipe-left":
          // Retreat from opponent - dispatch keydown then keyup to prevent stuck movement
          window.dispatchEvent(new KeyboardEvent("keydown", { key: "a" }));
          setTimeout(() => {
            window.dispatchEvent(new KeyboardEvent("keyup", { key: "a" }));
          }, 100);
          break;
        case "swipe-up":
          // High attack mode - execute selected technique
          techniqueSelection.executeTechnique();
          break;
        case "swipe-down":
          // Low attack mode - execute selected technique
          techniqueSelection.executeTechnique();
          break;
        case "two-finger-tap":
          // Activate vital point targeting mode
          // TODO: Implement vital point mode toggle
          audio.playSFX("menu_select");
          break;
      }
    },
    [techniqueSelection, audio],
  );
 
  const toggleStanceWheel = useCallback(() => {
    setStanceWheelExpanded((prev) => !prev);
  }, []);
 
  // Check if mobile controls should be enabled
  const mobileControlsEnabled =
    isMobile &&
    !isPaused &&
    !showPauseMenu &&
    combatState.roundStarted &&
    !combatState.roundEnded &&
    matchCountdownComplete &&
    !showRoundStart &&
    !combatState.isExecutingTechnique;
 
  // Note: Player 1 position is updated via the onPositionChange callback
  // in usePlayerMovement config above, not via useEffect
 
  // Round management
  useEffect(() => {
    if (isPaused) return;
 
    Iif (timeRemaining <= 0 && !combatState.roundEnded) {
      combatActions.setRoundEnded(true);
      combatActions.setRoundStarted(false);
      combatActions.setRoundDisplayStatus("end");
 
      combatAudio.stopCombatMusic(1000);
 
      const winner = validPlayers[0].health > validPlayers[1].health ? 0 : 1;
      const roundWinner = validPlayers[winner];
 
      // Update match score using deferred callback
      updateMatchScore(winner);
 
      addCombatMessage("라운드 종료!", "Round Over!");
 
      // Start round transition instead of immediately ending game
      setTimeout(() => {
        startTransition(roundWinner, internalRound);
      }, 1500);
    }
    // Note: Round start is now triggered by MatchCountdown and RoundStartAnnouncement components
    // via their onComplete callbacks to ensure proper sequencing with countdown animations
  }, [
    timeRemaining,
    combatState.roundEnded,
    combatState.roundStarted,
    validPlayers,
    onGameEnd,
    addCombatMessage,
    internalRound,
    isPaused,
    combatActions,
    combatAudio,
    startTransition,
    updateMatchScore,
  ]);
 
  // Create a ref for the callback to avoid circular dependency
  const executeAIActionCallbackRef = useRef<
    | ((
        action: string,
        targetPos?: Position,
        selectedTechnique?: KoreanTechnique,
        targetVitalPoint?: string,
      ) => void)
    | undefined
  >(undefined);
 
  // AI Combat System - connects AI decisions to executeAIActionCallbackRef via onExecuteAction (action/technique/vital point params)
  const { updateDifficultyTarget } = useAICombat({
    player: validPlayers[1],
    opponent: validPlayers[0],
    personality: aiPersonality,
    adaptiveDifficulty,
    isPaused,
    roundStarted: combatState.roundStarted,
    roundEnded: combatState.roundEnded,
    arenaBounds,
    onExecuteAction: (action, targetPos, selectedTechnique, targetVitalPoint) =>
      executeAIActionCallbackRef.current?.(
        action,
        targetPos,
        selectedTechnique,
        targetVitalPoint,
      ),
    onStanceChange: handleAIStanceChange,
    onLateralityChange: () => handleStanceSideSwitch(1), // AI player (index 1)
    playerLaterality: combatState.playerLaterality[1], // AI's own laterality
    opponentLaterality: combatState.playerLaterality[0], // Opponent (human) laterality
  });
 
  // Calculate current difficulty tier for display
  // Force recalculation when the adaptive difficulty system changes
  const currentDifficultyTier = useMemo(
    () => adaptiveDifficulty.getDifficultyTier(),
    [adaptiveDifficulty],
  );
 
  // Adaptive difficulty adjustment every 2-3 rounds after round ends
  useEffect(() => {
    // Only adjust after round ends (not during round or at start)
    Eif (!combatState.roundEnded || internalRound < 1) {
      return;
    }
 
    // Adjust every 2 rounds (after rounds 2, 4, 6, etc.)
    // This ensures at least 2 rounds between adjustments for smooth progression
    const roundsCompleted = internalRound;
    if (roundsCompleted % 2 === 0) {
      // Update AI skill metrics based on player performance.
      // NOTE (Phase 1 adaptive difficulty):
      // - Only hits/attacks/damage metrics are currently sourced from PlayerState.
      // - Combo, block, reaction-time, vital-point, and stance-change metrics are
      //   intentionally stubbed here (0 or constant) until PlayerState and telemetry
      //   are extended in a follow-up phase.
      //   This keeps the system functional while we iterate on richer skill tracking.
      const player1 = validPlayersRef.current[0];
 
      adaptiveDifficulty.updateSkillMetrics({
        hitsLanded: player1.hitsLanded ?? 0,
        totalAttacks: (player1.hitsLanded ?? 0) + (player1.misses ?? 0),
        combosExecuted: 0, // TODO (Phase 2): Track combo count in PlayerState
        perfectBlockCount: 0, // TODO (Phase 2): Track perfect blocks in PlayerState
        avgReactionTimeMs: 600, // TODO (Phase 2): Track player reaction time
        vitalPointsHit: 0, // TODO (Phase 2): Track vital point hits
        effectiveStanceChanges: 0, // TODO (Phase 2): Track stance changes
        damageDealt: player1.totalDamageDealt ?? 0,
        damageTaken: player1.totalDamageReceived ?? 0,
      });
 
      // Get new difficulty parameters and update AI
      const newParams = adaptiveDifficulty.getDifficultyParameters();
      updateDifficultyTarget(newParams);
 
      if (import.meta.env.DEV) {
        const tier = adaptiveDifficulty.getDifficultyTier();
        console.log(
          `[DEV] Difficulty adjusted after round ${roundsCompleted}, new tier: ${tier}`,
        );
      }
    }
  }, [
    combatState.roundEnded,
    internalRound,
    adaptiveDifficulty,
    updateDifficultyTarget,
  ]);
 
  // AI action execution - receives technique and vital point directly
  const executeAIActionCallback = useCallback(
    (
      action: string,
      targetPos?: Position,
      selectedTechnique?: KoreanTechnique,
      targetVitalPoint?: string,
    ) => {
      switch (action) {
        case "attack":
          // Set AI attack animation based on technique
          // AI 공격 애니메이션 설정
          if (
            selectedTechnique?.name?.english ||
            selectedTechnique?.englishName
          ) {
            const techName =
              selectedTechnique.name?.english ??
              selectedTechnique.englishName ??
              "jab";
            const p2AttackAnimName = getAnimationForTechnique(techName);
            setPlayer2AttackAnimation(p2AttackAnimName);
 
            // Store technique ID for enum-based AnimationType lookup
            // 열거형 기반 AnimationType 조회를 위한 기술 ID 저장
            if (selectedTechnique?.id) {
              setPlayer2TechniqueId(selectedTechnique.id);
            }
            const p2AttackAnim = getAnimation(p2AttackAnimName);
            const p2AttackDur = p2AttackAnim?.duration ?? 0.55;
            player2AttackDurationRef.current = p2AttackDur;
            player2Animation.transitionToAttack(p2AttackDur);
          } else {
            setPlayer2AttackAnimation("jab");
            player2AttackDurationRef.current = 0.55;
            player2Animation.transitionToAttack(0.55);
          }
          handleAIAttack(selectedTechnique, targetVitalPoint);
          break;
        case "defend":
          player2Animation.transitionTo(AnimationState.DEFEND);
          handleAIDefend();
          break;
        case "technique":
        case "combo":
          // Set AI attack animation based on technique
          // AI 기술 애니메이션 설정
          if (
            selectedTechnique?.name?.english ||
            selectedTechnique?.englishName
          ) {
            const techName =
              selectedTechnique.name?.english ??
              selectedTechnique.englishName ??
              "cross";
            const p2TechAnimName = getAnimationForTechnique(techName);
            setPlayer2AttackAnimation(p2TechAnimName);
 
            // Store technique ID for enum-based AnimationType lookup
            // 열거형 기반 AnimationType 조회를 위한 기술 ID 저장
            if (selectedTechnique?.id) {
              setPlayer2TechniqueId(selectedTechnique.id);
            }
            const p2TechAnim = getAnimation(p2TechAnimName);
            const p2TechDur = p2TechAnim?.duration ?? 0.6;
            player2AttackDurationRef.current = p2TechDur;
            player2Animation.transitionToAttack(p2TechDur);
          } else {
            setPlayer2AttackAnimation("cross");
            player2AttackDurationRef.current = 0.6;
            player2Animation.transitionToAttack(0.6);
          }
          handleAITechnique(selectedTechnique, targetVitalPoint);
          break;
        case "approach":
        case "retreat":
        case "circle":
          if (targetPos) {
            moveAIPlayer(targetPos);
          }
          break;
        case "feint":
          {
            const playerPos = validPlayers[0].position;
            // Feint offset in METERS (about half a meter of random movement)
            const feintOffsetMeters = 0.5;
            const feintPos = {
              x: playerPos.x + (Math.random() - 0.5) * feintOffsetMeters,
              y: playerPos.y + (Math.random() - 0.5) * feintOffsetMeters,
            };
            moveAIPlayer(feintPos);
            addCombatMessage("AI 페인트", "AI Feint");
 
            setTimeout(() => {
              if (
                !combatState.roundEnded &&
                combatState.roundStarted &&
                validPlayers.length >= 2
              ) {
                const currentPlayerPos = validPlayers[0].position;
                const currentAiPos = validPlayers[1].position;
                const dx = currentAiPos.x - currentPlayerPos.x;
                const dy = currentAiPos.y - currentPlayerPos.y;
                const dist = Math.sqrt(dx * dx + dy * dy) || 1;
                // Retreat distance in METERS (about 0.8 meters back)
                const retreatDistanceMeters = 0.8;
                // Use world meter bounds instead of pixel bounds
                const halfWidth = arenaBounds.worldWidthMeters / 2;
                const halfDepth = arenaBounds.worldDepthMeters / 2;
                const retreatPos = {
                  x: Math.max(
                    -halfWidth + 0.5, // 0.5m from edge
                    Math.min(
                      halfWidth - 0.5,
                      currentPlayerPos.x + (dx / dist) * retreatDistanceMeters,
                    ),
                  ),
                  y: Math.max(
                    -halfDepth + 0.5, // 0.5m from edge
                    Math.min(
                      halfDepth - 0.5,
                      currentPlayerPos.y + (dy / dist) * retreatDistanceMeters,
                    ),
                  ),
                };
                moveAIPlayer(retreatPos);
              }
            }, 200);
          }
          break;
        case "counter":
          // Set AI attack animation for counter attack
          // AI 반격 애니메이션 설정
          if (
            selectedTechnique?.name?.english ||
            selectedTechnique?.englishName
          ) {
            const techName =
              selectedTechnique.name?.english ??
              selectedTechnique.englishName ??
              "cross";
            const p2CounterAnimName = getAnimationForTechnique(techName);
            setPlayer2AttackAnimation(p2CounterAnimName);
 
            // Store technique ID for enum-based AnimationType lookup
            // 열거형 기반 AnimationType 조회를 위한 기술 ID 저장
            if (selectedTechnique?.id) {
              setPlayer2TechniqueId(selectedTechnique.id);
            }
            const p2CounterAnim = getAnimation(p2CounterAnimName);
            const p2CounterDur = p2CounterAnim?.duration ?? 0.6;
            player2AttackDurationRef.current = p2CounterDur;
            player2Animation.transitionToAttack(p2CounterDur);
          } else {
            setPlayer2AttackAnimation("cross");
            player2AttackDurationRef.current = 0.6;
            player2Animation.transitionToAttack(0.6);
          }
          handleAIAttack(selectedTechnique, targetVitalPoint);
          addCombatMessage("AI 반격!", "AI Counter!");
          break;
      }
    },
    [
      handleAIAttack,
      handleAIDefend,
      handleAITechnique,
      moveAIPlayer,
      addCombatMessage,
      validPlayers,
      arenaBounds,
      combatState.roundEnded,
      combatState.roundStarted,
      player2Animation,
    ],
  );
 
  // Update the ref
  useEffect(() => {
    executeAIActionCallbackRef.current = executeAIActionCallback;
  }, [executeAIActionCallback]);
 
  // Update adaptive difficulty metrics
  useEffect(() => {
    Iif (combatState.roundEnded && validPlayers.length === 2) {
      const player = validPlayers[0];
      const totalAttacks = (player.hitsLanded ?? 0) + (player.hitsTaken ?? 0);
 
      if (totalAttacks === 0) return;
 
      adaptiveDifficulty.updateSkillMetrics({
        hitsLanded: player.hitsLanded ?? 0,
        totalAttacks,
        combosExecuted: player.comboCount ?? 0,
        perfectBlockCount: 0,
        avgReactionTimeMs: 500,
        vitalPointsHit: player.vitalPointHits ?? 0,
        effectiveStanceChanges: 0,
        damageDealt: player.totalDamageDealt ?? 0,
        damageTaken: player.totalDamageReceived ?? 0,
      });
    }
  }, [combatState.roundEnded, adaptiveDifficulty, validPlayers]);
 
  // Check game end conditions
  const checkGameEnd = useCallback(() => {
    Iif (combatState.roundEnded) return;
 
    const p1Defeated = validPlayers[0].health <= 0;
    const p2Defeated = validPlayers[1].health <= 0;
 
    Iif (p1Defeated || p2Defeated) {
      combatActions.setRoundEnded(true);
      combatActions.setRoundStarted(false);
      combatActions.setRoundDisplayStatus("ko");
      const winner = p1Defeated ? 1 : 0;
      const roundWinner = validPlayers[winner];
 
      // Update match score using deferred callback
      updateMatchScore(winner);
 
      addCombatMessage(
        p1Defeated ? "플레이어 1 패배" : "플레이어 1 승리!",
        p1Defeated ? "Player 1 Defeated" : "Player 1 Victory!",
      );
 
      // Start round transition
      setTimeout(() => {
        startTransition(roundWinner, internalRound);
      }, 1500);
    }
  }, [
    validPlayers,
    addCombatMessage,
    combatState.roundEnded,
    combatActions,
    internalRound,
    startTransition,
    updateMatchScore,
  ]);
 
  useEffect(() => {
    checkGameEnd();
  }, [player1Health, player2Health, checkGameEnd]);
 
  // Keyboard input handling
  useEffect(() => {
    const handleCombatInput = (event: KeyboardEvent) => {
      // ESC key toggles pause menu (unless pause menu is already open)
      if (event.key === "Escape") {
        event.preventDefault();
        if (showPauseMenu) {
          handleResume();
        } else {
          handlePause();
        }
        return;
      }
 
      // Block all other combat inputs when paused or during pause menu
      // isPaused: External pause state from parent component
      // showPauseMenu: Local pause menu UI is visible
      // Both conditions block input to prevent combat actions while game is paused
      if (isPaused || showPauseMenu) {
        return;
      }
 
      // Block all combat inputs during countdown or round start announcement
      if (!matchCountdownComplete || showRoundStart) {
        return;
      }
 
      if (
        !combatState.roundStarted ||
        combatState.roundEnded ||
        combatState.isExecutingTechnique
      ) {
        return;
      }
 
      const key = event.key.toLowerCase();
 
      if (key >= "1" && key <= "8") {
        const stanceIndex = parseInt(key) - 1;
        const stances: TrigramStance[] = [
          TrigramStance.GEON,
          TrigramStance.TAE,
          TrigramStance.LI,
          TrigramStance.JIN,
          TrigramStance.SON,
          TrigramStance.GAM,
          TrigramStance.GAN,
          TrigramStance.GON,
        ];
        handleStanceSwitch(stances[stanceIndex]);
        event.preventDefault();
      }
 
      if (key === " ") {
        handleAttackWithFeedback();
        event.preventDefault();
      }
 
      if (event.key === "Shift") {
        handleDefendWithFeedback();
        event.preventDefault();
      }
 
      // F key for stance side switching (laterality)
      // Using "F" (Flip/Footwork) because:
      // - Tab conflicts with browser navigation and accessibility
      // - Q-W-E-R-T-Y-U-Y are reserved for combat techniques
      // - Shift is already used for blocking
      // - CapsLock has inconsistent key events across browsers/OSes
      if (event.key === "f" || event.key === "F") {
        handleStanceSideSwitch(0); // Human player
        event.preventDefault();
      }
    };
 
    window.addEventListener("keydown", handleCombatInput);
    return () => window.removeEventListener("keydown", handleCombatInput);
  }, [
    combatState.roundStarted,
    combatState.roundEnded,
    combatState.isExecutingTechnique,
    matchCountdownComplete,
    showRoundStart,
    isPaused,
    showPauseMenu,
    handleStanceSwitch,
    handleStanceSideSwitch,
    handleAttackWithFeedback,
    handleDefendWithFeedback,
    handlePause,
    handleResume,
  ]);
 
  // Calculate movement state for visual feedback using InjuryMovementModifier
  // This provides bilingual status text and injury severity information
  const player1MovementState = useMemo(() => {
    Iif (!validPlayers[0]?.bodyPartHealth) {
      return {
        statusText: { korean: "정상", english: "Normal" },
        isLimping: false,
        isSevereLimp: false,
      };
    }
 
    const result = injuryMovementModifier.calculateMovementSpeed(
      1.0,
      validPlayers[0].bodyPartHealth,
      validPlayers[0].currentStance ?? TrigramStance.GEON,
      validPlayers[0].pain ?? 0,
    );
 
    return {
      statusText: result.statusText,
      isLimping: result.isLimping,
      isSevereLimp: result.isSevereLimp,
      speedMultiplier: result.speedMultiplier,
    };
  }, [validPlayers]);
 
  const player2MovementState = useMemo(() => {
    Iif (!validPlayers[1]?.bodyPartHealth) {
      return {
        statusText: { korean: "정상", english: "Normal" },
        isLimping: false,
        isSevereLimp: false,
      };
    }
 
    const result = injuryMovementModifier.calculateMovementSpeed(
      1.0,
      validPlayers[1].bodyPartHealth,
      validPlayers[1].currentStance ?? TrigramStance.GEON,
      validPlayers[1].pain ?? 0,
    );
 
    return {
      statusText: result.statusText,
      isLimping: result.isLimping,
      isSevereLimp: result.isSevereLimp,
      speedMultiplier: result.speedMultiplier,
    };
  }, [validPlayers]);
 
  return (
    <div
      style={{
        width: `${width}px`,
        height: `${height}px`,
        position: "relative",
        backgroundColor: "#0a0a0a",
        overflow: "hidden", // Prevent content from extending beyond container
      }}
      data-testid="combat-screen"
    >
      {/* Three.js Canvas for 3D rendering */}
      <Canvas
        style={{ width: `${width}px`, height: `${height}px` }}
        camera={{
          position: cameraConfig.position,
          fov: cameraConfig.fov,
          near: cameraConfig.near,
          far: cameraConfig.far,
        }}
        gl={{
          antialias: renderConfig.antialias,
          alpha: false,
          powerPreference: "high-performance",
          // Add failIfMajorPerformanceCaveat to detect GPU issues
          failIfMajorPerformanceCaveat: false,
        }}
        dpr={renderConfig.dpr}
        shadows={false} // Temporarily disable shadows
        onCreated={({ gl }) => {
          gl.setClearColor(theme.colors.UI_BACKGROUND_DARK, 1);
        }}
      >
        {/* Lighting - CombatArena3D provides ambient, we add directional for shadows */}
        <ambientLight intensity={0.6} />
        <directionalLight position={[10, 10, 5]} intensity={1.2} />
 
        {/* Adaptive Quality Wrapper monitors FPS and adjusts quality */}
        <AdaptiveQualityWrapper>
          {/* Performance overlay (dev mode) - controlled by showPerformanceOverlay prop */}
          {showPerformanceOverlay && !showPerformanceMonitor && (
            <PerformanceOverlay3D />
          )}
 
          {/* Combat Arena 3D Environment - uses physics-based world dimensions */}
          <CombatArena3D
            lighting="cyberpunk"
            scale={arenaBounds.scale}
            worldWidthMeters={arenaBounds.worldWidthMeters}
            worldDepthMeters={arenaBounds.worldDepthMeters}
          />
 
          {/* Animation updater - updates both player animations at 60fps */}
          <AnimationUpdater
            player1Animation={player1Animation}
            player2Animation={player2Animation}
          />
 
          {/* Acceleration updater - tracks player 1 movement time and updates speed */}
          <AccelerationUpdater
            isMoving={player1IsMoving}
            velocity={player1Velocity}
            movementTimeRef={player1MovementTimeRef}
            lastDirectionRef={player1LastDirectionRef}
            onSpeedUpdate={setPlayer1AccelerationBasedSpeed}
            walkSpeed={player1WalkRunSpeeds.walkSpeed}
            runSpeed={player1WalkRunSpeeds.runSpeed}
          />
 
          {/* Player 1 (Human) */}
          <Player3DWithTransitions
            {...convertPlayerStateToProps(
              validPlayers[0],
              player1PositionWithAttackMovement,
              player1Rotation,
              {
                isMobile,
                facing: "right",
                enableFacialExpressions: true,
                enableEyeTracking: true,
                opponentPosition: player2PositionWithAttackMovement,
              },
            )}
            currentAnimation={animationStateToPlayerAnimation(
              player1Animation.currentState,
            )}
            attackAnimation={player1AttackAnimation}
            laterality={combatState.playerLaterality[0]}
            enableTransitionEffects={!isMobile}
            enableStanceSymbol={!isMobile}
            enableStanceAudio={true}
          />
 
          {/* Player 2 (AI) */}
          <Player3DWithTransitions
            {...convertPlayerStateToProps(
              validPlayers[1],
              player2PositionWithAttackMovement,
              player2Rotation,
              {
                isMobile,
                facing: "right",
                enableFacialExpressions: true,
                enableEyeTracking: true,
                opponentPosition: player1PositionWithAttackMovement,
              },
            )}
            currentAnimation={animationStateToPlayerAnimation(
              player2Animation.currentState,
            )}
            attackAnimation={player2AttackAnimation}
            laterality={combatState.playerLaterality[1]}
            enableTransitionEffects={!isMobile}
            enableStanceSymbol={!isMobile}
            enableStanceAudio={true}
          />
 
          {/* Movement Status Indicators - Korean/English Bilingual */}
          {/* Player 1 Movement Status */}
          {(player1MovementState.isLimping ||
            player1MovementState.isSevereLimp) && (
            <Html
              position={[
                player1Position3D[0],
                player1Position3D[1] + 2.5,
                player1Position3D[2],
              ]}
              center
              data-testid="player1-movement-status"
            >
              <div
                style={{
                  fontSize: isMobile ? "12px" : "14px",
                  color: player1MovementState.isSevereLimp
                    ? toHexColor(KOREAN_COLORS.TEXT_ERROR)
                    : toHexColor(KOREAN_COLORS.ACCENT_GOLD),
                  fontFamily: FONT_FAMILY.KOREAN,
                  fontWeight: "bold",
                  textShadow: "0 0 4px rgba(0,0,0,0.8)",
                  background: "rgba(0, 0, 0, 0.6)",
                  padding: "4px 8px",
                  borderRadius: "4px",
                  whiteSpace: "nowrap",
                }}
              >
                {player1MovementState.statusText.korean} |{" "}
                {player1MovementState.statusText.english}
              </div>
            </Html>
          )}
 
          {/* Player 2 Movement Status */}
          {(player2MovementState.isLimping ||
            player2MovementState.isSevereLimp) && (
            <Html
              position={[
                player2Position3D[0],
                player2Position3D[1] + 2.5,
                player2Position3D[2],
              ]}
              center
              data-testid="player2-movement-status"
            >
              <div
                style={{
                  fontSize: isMobile ? "12px" : "14px",
                  color: player2MovementState.isSevereLimp
                    ? toHexColor(KOREAN_COLORS.TEXT_ERROR)
                    : toHexColor(KOREAN_COLORS.ACCENT_GOLD),
                  fontFamily: FONT_FAMILY.KOREAN,
                  fontWeight: "bold",
                  textShadow: "0 0 4px rgba(0,0,0,0.8)",
                  background: "rgba(0, 0, 0, 0.6)",
                  padding: "4px 8px",
                  borderRadius: "4px",
                  whiteSpace: "nowrap",
                }}
              >
                {player2MovementState.statusText.korean} |{" "}
                {player2MovementState.statusText.english}
              </div>
            </Html>
          )}
 
          {/* Trauma Overlays - Injury Visualization (외상 오버레이 - 부상 시각화) */}
          {/* Player 1 Injuries */}
          <TraumaOverlay3D
            playerId="player"
            health={validPlayers[0].health}
            injuries={player1Injuries}
            characterPosition={player1Position3D}
            isMobile={isMobile}
            showFractures={true}
          />
 
          {/* Player 2 Injuries */}
          <TraumaOverlay3D
            playerId="enemy"
            health={validPlayers[1].health}
            injuries={player2Injuries}
            characterPosition={player2Position3D}
            isMobile={isMobile}
            showFractures={true}
          />
 
          {/* Hit Effects */}
          <HitEffects3D
            effects={combatState.hitEffects}
            onEffectComplete={handleEffectComplete}
            arenaBounds={arenaBounds}
          />
 
          {/* Combat Particle Effects - Blood viscosity, organ damage, audio (전투 입자 효과) */}
          <CombatParticleEffects3D
            hitEffects={combatState.hitEffects}
            enabled={true}
            isMobile={isMobile}
          />
 
          {/* Vital Point Overlay - Show on both players when V is pressed */}
          {overlayVisible && (
            <>
              {/* Player 1 Vital Points */}
              <VitalPointMarkers3D
                position={player1Position3D}
                visible={overlayVisible}
                severityFilter={severityFilters}
                regionFilter={regionFilter}
                searchQuery={searchQuery}
                showLabels={showLabels}
                scale={scale}
                animated={animated}
                onPointClick={() => {
                  // Optional: Add point targeting in combat
                }}
              />
 
              {/* Player 2 Vital Points */}
              <VitalPointMarkers3D
                position={player2Position3D}
                visible={overlayVisible}
                severityFilter={severityFilters}
                regionFilter={regionFilter}
                searchQuery={searchQuery}
                showLabels={showLabels}
                scale={scale}
                animated={animated}
                onPointClick={() => {
                  // Optional: Add point targeting in combat
                }}
              />
 
              {/* Vital Point Overlay Controls - only visible when overlay is active */}
              <VitalPointOverlayControlsHtml
                screenPosition={{
                  top: `${layoutConstants.hudHeight + layoutConstants.padding}px`,
                  left: `${layoutConstants.padding}px`,
                }}
                visible={overlayVisible}
                onVisibleChange={setOverlayVisible}
                severityFilters={severityFilters}
                onSeverityFiltersChange={setSeverityFilters}
                regionFilter={regionFilter}
                onRegionFilterChange={setRegionFilter}
                searchQuery={searchQuery}
                onSearchQueryChange={setSearchQuery}
                showLabels={showLabels}
                onShowLabelsChange={setShowLabels}
                animated={animated}
                onAnimatedChange={setAnimated}
                scale={scale}
                onScaleChange={setScale}
                isMobile={isMobile}
              />
            </>
          )}
 
          {/* Action Feedback - Damage Numbers */}
          <DamageNumbers
            damages={feedbackState.damageNumbers}
            isMobile={isMobile}
            arenaBounds={arenaBounds}
          />
 
          {/* Action Feedback - Action Indicators */}
          <ActionFeedback
            feedbacks={feedbackState.actionFeedbacks}
            isMobile={isMobile}
            arenaBounds={arenaBounds}
          />
 
          {/* Combo Counter */}
          <ComboCounter combo={feedbackState.comboCount} isMobile={isMobile} />
 
          {/* Technique Name Display */}
          {feedbackState.currentTechnique && (
            <TechniqueName
              korean={feedbackState.currentTechnique.korean}
              english={feedbackState.currentTechnique.english}
              isMobile={isMobile}
              onComplete={() => feedbackActions.hideTechnique()}
            />
          )}
 
          {/* Performance Overlay (Development Only) - Toggle with P key */}
          {import.meta.env.DEV && showPerformanceMonitor && (
            <PerformanceOverlay3D position={[-9, -2, 5]} visible={true} />
          )}
 
          {/* Visual Feedback Components for Keyboard Controls */}
          <StanceChangeIndicator
            currentStance={currentStanceIndex}
            previousStance={previousStance}
            isMobile={isMobile}
          />
 
          <KeyboardHints
            visible={showHints}
            currentStance={currentStanceIndex}
            isMobile={isMobile}
          />
 
          <InputBufferDisplay queuedInputs={queuedInputs} isMobile={isMobile} />
 
          {/* 3D Balance Indicators - Positioned below top HUD, to the right of side HUDs */}
          {/* Player 1 Balance Indicator - Upper left area, below top HUD */}
          {validPlayers[0] && (
            <BalanceIndicatorOverlayHtml
              player={validPlayers[0] as BalancePlayerState}
              currentTime={currentTime}
              position={[
                -2.5, // Left side of arena (to the right of left HUD in 3D space)
                2.5, // Upper area (below top HUD)
                -1.0, // Slightly forward toward camera
              ]}
              isMobile={isMobile}
            />
          )}
 
          {/* Player 2 Balance Indicator - Upper right area, below top HUD */}
          {validPlayers[1] && (
            <BalanceIndicatorOverlayHtml
              player={validPlayers[1] as BalancePlayerState}
              currentTime={currentTime}
              position={[
                2.5, // Right side of arena (to the left of right HUD in 3D space)
                2.5, // Upper area (below top HUD)
                -1.0, // Slightly forward toward camera
              ]}
              isMobile={isMobile}
            />
          )}
 
          {/* Mobile Touch Controls moved outside Canvas - using MobileControlsOverlay for reliable touch events */}
 
          {/* Performance Monitoring - FPS display (dev mode, toggle with P key) */}
          {process.env.NODE_ENV === "development" && showPerformanceMonitor && (
            <FPSMonitor
              enabled={true}
              warningThreshold={50}
              criticalThreshold={30}
            />
          )}
        </AdaptiveQualityWrapper>
 
        {/* Post-processing Effects - lightweight only */}
        {isMobile ? (
          <EffectComposer multisampling={0}>
            <Bloom
              luminanceThreshold={0.9}
              luminanceSmoothing={0.9}
              mipmapBlur
              intensity={0.8}
              radius={0.4}
            />
            <Noise opacity={0.03} />
            <Vignette eskil={false} offset={0.1} darkness={0.3} />
          </EffectComposer>
        ) : (
          <EffectComposer multisampling={4}>
            <Bloom
              luminanceThreshold={0.9}
              luminanceSmoothing={0.9}
              mipmapBlur
              intensity={0.8}
              radius={0.4}
            />
            <Noise opacity={0.03} />
            <Vignette eskil={false} offset={0.1} darkness={0.3} />
          </EffectComposer>
        )}
      </Canvas>
 
      {/* Html UI Overlays (positioned absolutely over Canvas) */}
      <div
        style={{
          position: "absolute",
          top: 0,
          left: 0,
          width: "100%",
          height: "100%",
          pointerEvents: "none",
          zIndex: Z_INDEX.HUD,
          // Use 'clip' for pure clipping without creating a scroll container
          // Note: Both 'clip' and 'hidden' will clip box/text shadows; ensure
          // any required shadow space is handled via padding on parent containers
          overflow: "clip",
        }}
      >
        {/* Top HUD - Round info, timer, return to menu */}
        <CombatTopHUD
          width={width}
          height={height}
          isMobile={isMobile}
          positionScale={positionScale}
          currentRound={internalRound}
          totalRounds={3}
          timerState={timerState}
          showTimer={
            combatState.roundStarted &&
            !combatState.roundEnded &&
            matchCountdownComplete &&
            !showRoundStart
          }
          onReturnToMenu={onReturnToMenu}
          isPaused={isPaused || showPauseMenu}
        />
 
        {/* Left HUD - Player 1 stats */}
        <CombatLeftHUD
          width={width}
          height={height}
          isMobile={isMobile}
          positionScale={positionScale}
          player={validPlayers[0]}
          laterality={combatState.playerLaterality[0]}
          isInGuard={player1Animation.isInStanceGuard()}
          speedModifiers={player1SpeedModifiers}
        />
 
        {/* Right HUD - Player 2/AI stats with difficulty indicator */}
        <CombatRightHUD
          width={width}
          height={height}
          isMobile={isMobile}
          positionScale={positionScale}
          player={validPlayers[1]}
          laterality={combatState.playerLaterality[1]}
          speedModifiers={player2SpeedModifiers}
          difficultyTier={currentDifficultyTier}
        />
 
        {/* Bottom HUD - Technique bar, volume, messages */}
        <CombatBottomHUD
          width={width}
          height={height}
          isMobile={isMobile}
          positionScale={positionScale}
          visible={
            combatState.roundStarted &&
            !combatState.roundEnded &&
            matchCountdownComplete &&
            !showRoundStart
          }
          techniques={techniqueSelection.availableTechniques}
          player={validPlayers[0]}
          selectedIndex={techniqueSelection.selectedIndex}
          cooldowns={cooldownsMap}
          onTechniqueSelect={techniqueSelection.selectTechnique}
          combatMessages={combatState.combatMessages}
        />
 
        {/* Player State Visual Indicators */}
        {/* Player 1 State Overlay - includes consciousness blur, pain vignette, etc. */}
        <PlayerStateOverlayHtml
          pain={validPlayers[0].pain}
          balanceState={getBalanceState(validPlayers[0].balance)}
          position="left"
          consciousness={validPlayers[0].consciousness}
          bloodLoss={0} // FIXME: bloodLoss property not yet added to PlayerState interface - overlay will not display until implemented
          stamina={validPlayers[0].stamina}
          isMobile={isMobile}
        />
 
        {/* Note: Player 2 (AI) does not get fullscreen state overlays like consciousness blur */}
        {/* as those effects would incorrectly affect the player's view */}
 
        {/* Breathing Disruption Indicators */}
        {/* Player 1 Breathing Indicator - positioned near left HUD */}
        <div
          style={{
            position: "absolute",
            left: isMobile ? "10px" : "20px",
            top: isMobile ? "120px" : "160px",
            zIndex: Z_INDEX.HUD + 1,
            pointerEvents: "none",
          }}
          data-testid="player1-breathing-indicator-container"
        >
          <BreathingIndicator player={validPlayers[0]} isMobile={isMobile} />
        </div>
 
        {/* Player 2 Breathing Indicator - positioned near right HUD */}
        <div
          style={{
            position: "absolute",
            right: isMobile ? "10px" : "20px",
            top: isMobile ? "120px" : "160px",
            zIndex: Z_INDEX.HUD + 1,
            pointerEvents: "none",
          }}
          data-testid="player2-breathing-indicator-container"
        >
          <BreathingIndicator player={validPlayers[1]} isMobile={isMobile} />
        </div>
 
        {/* Pause Menu Overlay */}
        {(isPaused || showPauseMenu) && (
          <PauseMenu
            onResume={handleResume}
            onRestart={handleRestart}
            onReturnToMenu={onReturnToMenu}
            isMobile={isMobile}
          />
        )}
      </div>
 
      {/* Round Announcement Overlay */}
      {showAnnouncement && roundWinner && (
        <RoundAnnouncement
          roundNumber={transitionRoundNumber}
          roundWinner={roundWinner}
          currentScore={matchScore}
          roundStats={{
            damageDealt: roundWinner.totalDamageDealt ?? 0,
            hitsLanded: roundWinner.hitsLanded ?? 0,
            vitalPointsHit: roundWinner.vitalPointHits ?? 0,
            accuracy: calculateAccuracy(roundWinner),
          }}
          onCountdownComplete={() => {
            // Check if match is over (best of 3)
            if (matchScore.player1 >= 2 || matchScore.player2 >= 2) {
              const winner = matchScore.player1 >= 2 ? 0 : 1;
              onGameEnd(winner);
            } else {
              // Match continues - trigger transition to next round
              skipCountdown();
            }
          }}
          onSkip={() => {
            // Check if match is over (best of 3) before skipping
            if (matchScore.player1 >= 2 || matchScore.player2 >= 2) {
              const winner = matchScore.player1 >= 2 ? 0 : 1;
              onGameEnd(winner);
            } else {
              skipCountdown();
            }
          }}
          isMobile={isMobile}
          totalRounds={3}
        />
      )}
 
      {/* Match Start Countdown Overlay - only shows once at match start */}
      {showMatchCountdown && !hasShownMatchCountdown && (
        <MatchCountdown
          onComplete={() => {
            setHasShownMatchCountdown(true);
            setShowMatchCountdown(false);
            setMatchCountdownComplete(true);
            // Start the first round after countdown
            startRound();
          }}
          isMobile={isMobile}
          showSkip={false}
        />
      )}
 
      {/* Round Start Announcement for subsequent rounds */}
      {/* Note: showRoundStart is only set to true after round 1 ends, so no need for internalRound > 1 check */}
      {showRoundStart && (
        <RoundStartAnnouncement
          roundNumber={internalRound}
          duration={2}
          onComplete={() => {
            if (import.meta.env.DEV) {
              console.log(
                "[DEV] Round start announcement complete for round",
                internalRound,
              );
            }
            setShowRoundStart(false);
            // Start combat for this round
            startRound();
          }}
          isMobile={isMobile}
        />
      )}
 
      {/* Round Display Status - Brief status messages */}
      {contentReady && combatState.roundDisplayStatus && (
        <RoundDisplayStatus
          status={combatState.roundDisplayStatus}
          isMobile={isMobile}
        />
      )}
 
      {/* Mobile Controls - Pure DOM, rendered OUTSIDE Canvas for reliable touch events */}
      {/* Uses pure DOM handlers instead of drei's Html which can block touch events on mobile */}
      {isMobile && (
        <>
          <MobileControlsOverlay
            onMove={handleMobileMove}
            onAttack={handleMobileAttack}
            onBlock={handleMobileBlock}
          />
 
          <StanceWheelPure
            currentStance={currentStanceIndex}
            onStanceChange={handleMobileStanceChange}
            expanded={stanceWheelExpanded}
            onToggle={toggleStanceWheel}
            disabled={!mobileControlsEnabled}
            opacity={0.8}
          />
 
          <GestureRecognizerPure
            onGesture={handleMobileGesture}
            enabled={mobileControlsEnabled}
            showFeedback={true}
            minSwipeDistance={50}
          />
        </>
      )}
    </div>
  );
};
 
export default CombatScreen3D;