All files / components/screens/training TrainingScreen3D.tsx

61.12% Statements 206/337
29.37% Branches 42/143
58.75% Functions 47/80
60.97% Lines 200/328

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                                                                                                                                                                                                                                                                          1x     72x       72x                                                 1x                               72x     72x     72x       72x           72x               72x 24x   2x   1x   19x       2x             72x 72x           72x     72x 72x       72x 72x 72x 72x   72x         72x         72x 72x             72x 72x 72x                 72x     72x                               72x       72x             72x                         72x 24x                 72x                 72x 24x                         72x 72x       72x         72x       72x                                 72x     24x             72x 24x         72x 24x                 72x 24x         72x       72x 24x             24x 24x 24x         72x 24x                   72x     72x 72x     72x 24x   24x 24x 24x                       24x     24x 24x                                         72x                 72x                     72x         72x 72x                                                           72x         72x 72x                 72x 24x           72x         72x                 72x 48x                                                                                             72x 48x   48x           48x           48x               48x             48x     48x   48x                 72x 72x               72x   24x 24x                           72x                   72x               72x       72x                                                         72x 24x 24x 24x     24x                     72x                                                 72x 72x       72x 72x         72x                             72x 72x 72x   72x 72x 72x 72x   72x                                     72x                             72x 24x 24x     24x         72x 24x 24x 24x             24x 24x             24x   24x   24x         24x                         72x 24x               72x     72x     72x                                                                                                                           72x         72x                   72x                                                             72x                     72x 72x                                                 72x 72x               72x   72x 72x   72x 72x   72x 72x                 72x   72x 72x 19x   19x             72x 72x 24x 24x                     72x 48x 24x 24x         72x 48x   24x           24x               72x     72x 72x 72x     72x 48x       72x 72x   72x 72x 72x     72x   24x 24x 24x 24x                                                                                   72x                     72x               72x                             72x 24x                 72x 24x         72x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    
/**
 * TrainingScreen3D - Three.js-based training screen
 *
 * Refactored to use consolidated hooks matching CombatScreen architecture.
 * Provides 3D training dummy with vital point targeting and UI overlays.
 *
 * UI Rendering: All HUD elements are rendered in an absolute-positioned div
 * OUTSIDE the Canvas, matching CombatScreen's reliable rendering pattern.
 * This eliminates the need for Html overlays inside Three.js and ensures
 * HUDs appear immediately without waiting for Canvas initialization.
 *
 * Architecture (Consolidated in PR #1394 + Issue #1398):
 * - TrainingLeftHUD: Anatomy controls, guard indicator
 * - TrainingRightHUD: Training stats, mode selector, vital point selection
 * - TrainingTopHUD: Training controls, archetype selector, return button
 * - TrainingBottomHUD: Technique bar, feedback messages, mobile controls
 * - VitalPointOverlayControlsPure: Vital point overlay controls (pure DOM)
 *
 * All UI components render as pure DOM in the HUD overlay div (lines 1230+).
 * NO Html components from @react-three/drei are used inside the Canvas.
 * This ensures clean separation of 3D rendering and UI layers.
 *
 * @korean 훈련화면3D - 훈련 상태 훅을 사용한 리팩토링된 3D 훈련 화면
 */
 
// UI renders outside Canvas in absolute-positioned div - no Html needed
import { Canvas, useFrame } from "@react-three/fiber";
import { AccelerationUpdater } from "../../../systems/movement/helpers/AccelerationUpdater";
import {
  isRunningSpeed,
  STEP_DISTANCE_THRESHOLDS,
} from "../../../systems/movement/helpers/accelerationUtils";
import {
  Bloom,
  EffectComposer,
  Noise,
  Vignette,
} from "@react-three/postprocessing";
import * as THREE from "three";
import React, {
  useCallback,
  useEffect,
  useMemo,
  useRef,
  useState,
} from "react";
import { useAudio } from "../../../audio/AudioProvider";
import { useCombatAudio } from "../../screens/combat/hooks/useCombatAudio";
import { getArchetypePhysicalAttributes } from "../../../data/archetypePhysicalAttributes";
import { usePlayerAnimation } from "../../../hooks/usePlayerAnimation";
import { useTechniqueSelection } from "../../../hooks/useTechniqueSelection";
import { GestureEvent } from "../../../hooks/useTouchControls";
import { useWebGLContextLossHandler } from "../../../hooks/useWebGLContextLossHandler";
import { PlayerState } from "../../../systems";
import {
  AnimationEvents,
  AnimationState,
  AnimationType,
  getAnimationForTechnique,
} from "../../../systems/animation";
import { getAnimationForTechniqueOrDefault } from "../../../systems/animation/core/TechniqueAnimationMapping";
import { physicalReachCalculator } from "../../../systems/physics";
import {
  MovementType,
  SpeedModifierSystem,
} from "../../../systems/physics/SpeedModifierSystem";
import { TRIGRAM_STANCES_ORDER } from "../../../systems/trigram/types";
import {
  CombatState,
  PlayerArchetype,
  Position,
  Technique,
  TrigramStance,
} from "../../../types";
import { getPerformanceSettings } from "../../../types/constants";
import { getMobileControlsBottom } from "../../../types/constants/layout";
import { Z_INDEX } from "../../../types/LayoutTypes";
import { DEFAULT_BODY_RADIUS_METERS } from "../../../types/physicsConstants";
import { usePlayerMovement } from "../../../utils/inputSystem";
import { calculateDistance3D } from "../../../utils/math";
import { createCameraConfig } from "../../../utils/sharedPhysicsConfig";
import {
  animationStateToPlayerAnimation,
  convertPlayerStateToProps,
} from "../../../utils/player3DHelpers";
import { useKoreanTheme } from "../../shared/base/useKoreanTheme";
import {
  GestureRecognizerPure,
  StanceWheelPure,
} from "../../shared/mobile";
import {
  MobileControlsOverlay,
  type ButtonEventType,
  type Direction,
  type DPadEventType,
} from "../../shared/mobile/MobileControlsPure";
import {
  Player3DWithTransitions,
  VitalPointMarkers3D,
  type BodyRegionFilter,
} from "../../shared/three";
import { StanceChangeIndicator } from "../../shared/three/indicators/StanceChangeIndicator";
import { CombatArena3D } from "../../shared/three/scene/CombatArena3D";
import { VitalPointOverlayControlsPure } from "../../shared/ui/VitalPointOverlayControlsPure";
import AnatomyOverlay3D, {
  type AnatomyLayer,
} from "./components/AnatomyOverlay3D";
import FootPlacementMarkers3D from "./components/FootPlacementMarkers3D";
import HitFeedbackEffect3D from "./components/HitFeedbackEffect3D";
import type { DifficultyMode } from "./components/TrainingDummy3D";
import TrainingDummy3D from "./components/TrainingDummy3D";
// HUD Components - Organized UI layout
import {
  TrainingBottomHUD,
  TrainingLeftHUD,
  TrainingRightHUD,
  TrainingTopHUD,
} from "./components/hud";
// Attack movement hook for player forward momentum
import { useAttackMovement } from "./hooks/useAttackMovement";
import useTrainingActions from "./hooks/useTrainingActions";
import { useTrainingLayout } from "./hooks/useTrainingLayout";
import useTrainingState from "./hooks/useTrainingState";
 
/**
 * AnimationUpdater - Component that updates player animation at 60fps
 *
 * @korean 훈련애니메이션업데이터 - 60fps로 플레이어 애니메이션을 업데이트하는 컴포넌트
 */
interface TrainingAnimationUpdaterProps {
  readonly playerAnimation: ReturnType<typeof usePlayerAnimation>;
}
 
const TrainingAnimationUpdater: React.FC<TrainingAnimationUpdaterProps> = ({
  playerAnimation,
}) => {
  useFrame((_state, delta) => {
    playerAnimation.update(delta);
  });
 
  return null;
};
 
/**
 * Props for the TrainingScreen3D component
 */
export interface TrainingScreen3DProps {
  /** Callback to update player state */
  readonly onPlayerUpdate: (updates: Partial<PlayerState>) => void;
  /** Callback when returning to menu */
  readonly onReturnToMenu: () => void;
  /** Canvas width in pixels. Defaults to 1200 */
  readonly width?: number;
  /** Canvas height in pixels. Defaults to 800 */
  readonly height?: number;
  /** Initial archetype from IntroScreen selection. Defaults to MUSA */
  readonly initialArchetype?: PlayerArchetype;
}
 
/**
 * TrainingScreen3D Component
 * Three.js-based training screen with 3D dummy and Html UI
 *
 * Uses consolidated hooks for state management matching CombatScreen architecture.
 */
export const TrainingScreen3D: React.FC<TrainingScreen3DProps> = ({
  onPlayerUpdate,
  onReturnToMenu,
  width = 1200,
  height = 800,
  initialArchetype = PlayerArchetype.MUSA,
}) => {
  // ═══════════════════════════════════════════════════════════════════════════
  // SECTION 1: Core State Management (Hooks)
  // ═══════════════════════════════════════════════════════════════════════════
 
  // UI overlays now render outside Canvas in absolute-positioned div
  // This matches CombatScreen pattern for reliable, immediate rendering
  // No mount delay needed - UI is not dependent on Three.js render loop
 
  // Consolidated training state management (matches useCombatState pattern)
  const { state: trainingState, actions: trainingActions } = useTrainingState();
 
  // Audio context
  const audio = useAudio();
  
  // Combat audio for bone impact sounds
  const { playBoneImpactSound, playAttackSound, playStanceChangeSound } =
    useCombatAudio();
 
  // Responsive detection and layout (using dedicated training layout hook)
  const { trainingAreaBounds, isMobile, screenSize } = useTrainingLayout(
    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 = React.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]);
 
  // Training difficulty and vital point configuration
  const difficulty: DifficultyMode = "normal";
  const vitalPointCount = 70; // Show all 70 vital points
 
  // Archetype selection for training (allows testing different body types)
  // 원형 선택 - 다양한 체형 테스트 가능
  // Uses initialArchetype from IntroScreen selection, can be changed locally
  const [selectedArchetype, setSelectedArchetype] =
    React.useState<PlayerArchetype>(initialArchetype);
 
  // Vital point overlay state
  const [overlayVisible, setOverlayVisible] = React.useState(false);
  const [severityFilters, setSeverityFilters] = React.useState<
    import("../../../types/common").VitalPointSeverity[]
  >([]);
  const [regionFilter, setRegionFilter] =
    React.useState<BodyRegionFilter>("all");
  const [searchQuery, setSearchQuery] = React.useState("");
  const [showLabels, setShowLabels] = React.useState(true);
  const [animated, setAnimated] = React.useState(true);
  // Use combat-consistent scale (1.2) for better visibility across screens
  const [scale, setScale] = React.useState(1.2);
 
 
  // Track current attack animation for technique-specific animations
  // 기술별 애니메이션을 위한 현재 공격 애니메이션 추적
  const [attackAnimation, setAttackAnimation] = React.useState<
    string | undefined
  >(undefined);
 
  // Keyboard shortcut for toggling overlay (V key only - Ctrl removed)
  React.useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === "v" || e.key === "V") {
        setOverlayVisible((prev) => !prev);
        audio.playSFX("menu_select");
      }
    };
 
    window.addEventListener("keydown", handleKeyDown);
    return () => {
      window.removeEventListener("keydown", handleKeyDown);
    };
  }, [audio]);
 
  // ═══════════════════════════════════════════════════════════════════════════
  // SECTION 2: WebGL Context Management
  // ═══════════════════════════════════════════════════════════════════════════
 
  // Track context loss for recovery
  const contextLossCountRef = useRef(0);
 
  // Handle WebGL context loss and restoration (for 3D scene only)
  useWebGLContextLossHandler({
    onContextLost: () => {
      console.warn("⚠️ WebGL context lost in TrainingScreen");
      contextLossCountRef.current += 1;
    },
    onContextRestored: () => {
      console.log("✓ WebGL context restored in TrainingScreen");
    },
    autoRestore: true,
  });
 
  // ═══════════════════════════════════════════════════════════════════════════
  // SECTION 2B: Speed Modifier System (matching CombatScreen pattern)
  // ═══════════════════════════════════════════════════════════════════════════
 
  // Speed Modifier System for dynamic movement speed calculations
  const speedModifierSystem = useMemo(() => new SpeedModifierSystem(), []);
 
  // Track speed modifiers for movement (simplified for training - no injuries)
  // Updated dynamically based on acceleration-based running
  const [speedModifiers, setSpeedModifiers] = useState({
    finalSpeed: 6.0, // BASE_WALK_SPEED (6.0 m/s for responsive combat)
    baseSpeed: 6.0,
    finalAcceleration: 12.0, // BASE_ACCELERATION (12.0 m/s² for quick response)
  });
 
  // Track walk/run speeds for acceleration interpolation (archetype-aware)
  const [walkRunSpeeds, setWalkRunSpeeds] = useState({
    walkSpeed: 6.0,
    runSpeed: 10.0,
  });
 
  // ═══════════════════════════════════════════════════════════════════════════
  // SECTION 3: Movement & Position Management
  // ═══════════════════════════════════════════════════════════════════════════
 
  // Initial player position in pixel space (left side of arena, centered vertically)
  // Physics-first: initial position in METERS (relative to arena center)
  // 0% from center (centered laterally) creates ~1.2m distance to dummy
  // This allows most kicks to land immediately, punches require 1-2 steps (realistic)
  const initialPositionMeters = useMemo<Position>(
    () => ({
      x: trainingAreaBounds.worldWidthMeters * 0.0, // Centered laterally
      y: 0, // Centered vertically
    }),
    [trainingAreaBounds],
  );
 
  // CRITICAL FIX: Memoize onPositionChange to prevent usePlayerMovement callback recreation
  // Without this, a new function is created every render, causing animation frame cancellation
  const handlePositionChange = useCallback(
    (newPosition: Position) => {
      onPlayerUpdate({ 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: trainingAreaBounds.worldWidthMeters,
      worldDepthMeters: trainingAreaBounds.worldDepthMeters,
    }),
    [trainingAreaBounds.worldWidthMeters, trainingAreaBounds.worldDepthMeters],
  );
 
  // ═══════════════════════════════════════════════════════════════════════════
  // SECTION 3A: Acceleration-Based Running System
  // ═══════════════════════════════════════════════════════════════════════════
  
  // Track continuous movement time for acceleration-based running
  // 가속 기반 달리기를 위한 연속 이동 시간 추적
  const movementTimeRef = useRef(0);
  const lastDirectionRef = 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 [accelerationBasedSpeed, setAccelerationBasedSpeed] = useState(
    walkRunSpeeds.walkSpeed
  );
  
  // Determine if currently running using utility function with archetype run speed
  const isRunning = isRunningSpeed(accelerationBasedSpeed, walkRunSpeeds.runSpeed);
 
  // Player movement with physics-based acceleration and stance modifiers
  // All positions are in METERS - no pixel conversions
  const { playerPosition, isMoving, velocity } = usePlayerMovement({
    enabled: true, // Always allow movement in training screen
    bounds: movementBounds, // Use memoized bounds object
    onPositionChange: handlePositionChange, // Use memoized callback
    initialPositionMeters,
    // Physics parameters for realistic training movement (always enabled)
    currentStance: TRIGRAM_STANCES_ORDER[trainingState.currentStanceIndex],
    legInjuryFactor: 0, // No injury in training mode
    isRunning, // Use computed acceleration-based running state
    // Use interpolated speed between modifier-aware walk/run speeds
    // This preserves archetype speeds and stance modifiers
    maxSpeedOverride: accelerationBasedSpeed,
    accelerationOverride: speedModifiers.finalAcceleration,
  });
 
  // Physics-first: playerPosition is already in METERS (x = lateral, y = forward/backward)
  // Direct conversion to 3D world coordinates - no pixel math needed
  const player3DPosition = useMemo<[number, number, number]>(() => {
    // playerPosition.x is lateral position in meters (- = left, + = right)
    // playerPosition.y is forward/backward position in meters (- = toward camera, + = away)
    return [playerPosition.x, 0, playerPosition.y];
  }, [playerPosition]);
 
  // Dummy position in meters (right side, creating optimal training distance)
  // Positioned at 15% from center to give ~1.2-1.6m distance depending on archetype
  // Allows kicks to hit from starting position, punches with slight approach
  // Uses world dimensions for physics-consistent positioning
  const dummyPosition = useMemo<[number, number, number]>(
    () => [trainingAreaBounds.worldWidthMeters * 0.15, 0, 0],
    [trainingAreaBounds.worldWidthMeters],
  );
 
  // Calculate center-to-center distance to dummy in meters
  const centerToCenterDistance = useMemo(
    () => calculateDistance3D(player3DPosition, dummyPosition),
    [player3DPosition, dummyPosition],
  );
 
  // Calculate effective distance (adjusted for body radius)
  // Attacks hit the body surface, not the center point
  // Training dummy uses DEFAULT_BODY_RADIUS_METERS since it has no archetype
  // For combat between players, use calculateBodyRadius(targetPhysicalAttributes)
  // 실제 타격거리 = 중심간거리 - 목표체 반경
  const distanceToDummy = useMemo(
    () => Math.max(0, centerToCenterDistance - DEFAULT_BODY_RADIUS_METERS),
    [centerToCenterDistance],
  );
 
  // Track last facing rotation for when movement stops
  const lastFacingRotationRef = useRef<number>(0);
 
  // Calculate rotation: face movement direction when moving, face dummy when idle
  // 이동 중에는 이동 방향을, 정지 시에는 더미를 향함
  const playerRotation = useMemo(() => {
    Iif (isMoving && velocity && (velocity.x !== 0 || velocity.y !== 0)) {
      // When moving: face the direction of movement
      // 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
      return Math.atan2(velocity.x, velocity.y);
    } else {
      // When idle: face the dummy (target)
      const dx = dummyPosition[0] - player3DPosition[0];
      const dz = dummyPosition[2] - player3DPosition[2];
      return Math.atan2(dx, dz);
    }
  }, [isMoving, velocity, player3DPosition, dummyPosition]);
 
  // Update ref in effect to avoid updating during render
  useEffect(() => {
    lastFacingRotationRef.current = playerRotation;
  }, [playerRotation]);
 
  // ═══════════════════════════════════════════════════════════════════════════
  // SECTION 3B: Foot Laterality Alternation (발바닥 교대)
  // ═══════════════════════════════════════════════════════════════════════════
 
  // Track current laterality (which foot is forward)
  // Alternates with each step during walking/running for realistic footwork
  // 왼발서기 (left) ↔ 오른발서기 (right)
  const [currentLaterality, setCurrentLaterality] = useState<"left" | "right">("right");
  
  // Track step counter for alternating feet
  const stepCounterRef = useRef(0);
  const lastPositionRef = useRef<Position>(playerPosition);
  
  // Alternate laterality based on movement distance
  useEffect(() => {
    Eif (!isMoving) {
      // Reset step counter when not moving and sync last position
      stepCounterRef.current = 0;
      lastPositionRef.current = playerPosition;
      return;
    }
 
    // Calculate distance traveled since last check
    const dx = playerPosition.x - lastPositionRef.current.x;
    const dy = playerPosition.y - lastPositionRef.current.y;
    const distanceMoved = Math.sqrt(dx * dx + dy * dy);
    
    // Accumulate distance into step counter
    const stepThreshold = isRunning 
      ? STEP_DISTANCE_THRESHOLDS.RUN 
      : STEP_DISTANCE_THRESHOLDS.WALK;
    stepCounterRef.current += distanceMoved;
    
    // Determine how many step thresholds were crossed in this update
    const stepsCrossed = Math.floor(stepCounterRef.current / stepThreshold);
    Iif (stepsCrossed > 0) {
      // Net laterality change depends on whether the number of steps is odd or even
      // Odd steps = toggle once, even steps = no net change
      if (stepsCrossed % 2 === 1) {
        setCurrentLaterality(prev => prev === "right" ? "left" : "right");
      }
      // Preserve remainder distance after accounting for full steps
      stepCounterRef.current -= stepsCrossed * stepThreshold;
    }
    
    // Update last position
    lastPositionRef.current = playerPosition;
  }, [playerPosition, isMoving, isRunning]);
 
  // ═══════════════════════════════════════════════════════════════════════════
  // SECTION 4: Player Animation State Machine
  // ═══════════════════════════════════════════════════════════════════════════
 
  // Reference for pending attack (executed at animation frame 6)
  // Includes animationType and startTime for distance-based hit detection
  // matching CombatSystem behavior
  const pendingAttackRef = useRef<{
    accuracy: number;
    vitalPoint: string;
    animationType?: AnimationType;
    startTime?: number;
    techniqueId?: string;
  } | null>(null);
 
  // Forward ref for handleDummyHit (defined in actions hook)
  const handleDummyHitRef = useRef<
    (
      vitalPointId: string,
      attackContext?: {
        animationType?: AnimationType;
        techniqueId?: string;
      },
    ) => boolean
  >(() => false);
 
  // Ref for playerAnimation to avoid circular dependencies in animation events
  const playerAnimationRef = useRef<ReturnType<
    typeof usePlayerAnimation
  > | null>(null);
 
  // Player animation events (matches CombatScreen pattern)
  const playerAnimationEvents = useMemo<AnimationEvents>(
    () => ({
      onFrame: (frame, state) => {
        // Execute attack at midpoint of animation (frame 6 of 12)
        if (state === "attack" && frame === 6 && pendingAttackRef.current) {
          const attackData = pendingAttackRef.current;
          // Pass attack context to handleDummyHit before clearing the ref
          // This ensures animationType and techniqueId are available for reach calculation
          handleDummyHitRef.current(attackData.vitalPoint, {
            animationType: attackData.animationType,
            techniqueId: attackData.techniqueId,
          });
          pendingAttackRef.current = null;
        }
      },
      onAnimationComplete: (state) => {
        if (state === "stance_change") {
          // Stance change animation completed - transition to stance guard
          // 자세 변경 완료 - 자세 가드로 전환
          playStanceChangeSound();
          const currentStance =
            TRIGRAM_STANCES_ORDER[trainingState.currentStanceIndex];
          if (currentStance && playerAnimationRef.current) {
            playerAnimationRef.current.transitionToStanceGuard(currentStance);
          }
        }
      },
    }),
    [playStanceChangeSound, trainingState.currentStanceIndex],
  );
 
  const playerAnimation = usePlayerAnimation({
    events: playerAnimationEvents,
  });
 
  // Store animation ref for use in event callbacks
  useEffect(() => {
    playerAnimationRef.current = playerAnimation;
  }, [playerAnimation]);
 
  // ═══════════════════════════════════════════════════════════════════════════
  // SECTION 5: Training Actions (Hook-based)
  // ═══════════════════════════════════════════════════════════════════════════
 
  // Get current stance for animation transitions (needed before useTrainingActions)
  // 현재 자세 (애니메이션 전환용)
  const currentStance = useMemo(
    () => TRIGRAM_STANCES_ORDER[trainingState.currentStanceIndex],
    [trainingState.currentStanceIndex],
  );
 
  // Track previous stance for visual feedback (StanceChangeIndicator)
  // 이전 자세 추적 - 자세 변경 표시기 시각적 피드백용
  const [previousStanceIndex, setPreviousStanceIndex] = useState<number>(0);
 
  // Ref to track current technique's animation type (updated by technique selection)
  // This allows useTrainingActions to access the current technique's animation type
  // without creating circular dependencies
  const currentTechniqueAnimationTypeRef = useRef<AnimationType>(
    AnimationType.JAB,
  );
 
  // ═══════════════════════════════════════════════════════════════════════════
  // SECTION 7: Training Player State (Visual Display)
  // ═══════════════════════════════════════════════════════════════════════════
 
  // Training player state for visualization
  const trainingPlayerState = useMemo<PlayerState>(() => {
    return {
      id: "training-player",
      name: { korean: "훈련생", english: "Trainee" },
      archetype: selectedArchetype,
      health: 100,
      maxHealth: 100,
      ki: 100,
      maxKi: 100,
      stamina: 100,
      maxStamina: 100,
      energy: 100,
      maxEnergy: 100,
      attackPower: 10,
      defense: 10,
      speed: 10,
      technique: 10,
      pain: 0,
      consciousness: 100,
      balance: 100,
      momentum: 0,
      currentStance: TRIGRAM_STANCES_ORDER[trainingState.currentStanceIndex],
      combatState: CombatState.IDLE,
      position: playerPosition,
      isBlocking: false,
      isStunned: false,
      isCountering: false,
      lastActionTime: 0,
      recoveryTime: 0,
      lastStanceChangeTime: 0,
      statusEffects: [],
      activeEffects: [],
      vitalPoints: [],
      totalDamageReceived: 0,
      totalDamageDealt: 0,
      hitsTaken: 0,
      hitsLanded: trainingState.stats.hits,
      perfectStrikes: trainingState.perfectStrikes,
      vitalPointHits: 0,
      misses: trainingState.stats.misses,
      accuracy: trainingState.stats.accuracy,
      comboCount: trainingState.stats.combo,
    };
  }, [playerPosition, trainingState, selectedArchetype]);
 
  // Calculate speed modifiers when player state changes
  // Updates at 5Hz (every 200ms) matching CombatScreen pattern
  // Get both walk and run speeds for acceleration interpolation
  useEffect(() => {
    const updateSpeedModifiers = () => {
      // Calculate modifiers for both walking and running to get archetype-aware speeds
      const walkModifiers = speedModifierSystem.calculateSpeedModifiers(
        trainingPlayerState,
        MovementType.WALKING,
        false, // isCrouching
      );
 
      const runModifiers = speedModifierSystem.calculateSpeedModifiers(
        trainingPlayerState,
        MovementType.RUNNING,
        false, // isCrouching
      );
 
      setSpeedModifiers({
        finalSpeed: walkModifiers.finalSpeed,
        baseSpeed: walkModifiers.baseSpeed,
        finalAcceleration: walkModifiers.finalAcceleration,
      });
 
      // Store walk/run speeds for acceleration interpolation
      // These account for archetype speeds and stance modifiers
      setWalkRunSpeeds({
        walkSpeed: walkModifiers.finalSpeed,
        runSpeed: runModifiers.finalSpeed,
      });
    };
 
    // 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
  }, [trainingPlayerState]); // speedModifierSystem is memoized and never changes
 
  // ═══════════════════════════════════════════════════════════════════════════
  // SECTION 5: Player Attack Movement (Forward Momentum)
  // ═══════════════════════════════════════════════════════════════════════════
 
  // Determine if player is currently attacking based on animation state
  const isPlayerAttacking = useMemo(
    () => playerAnimation?.currentState === "attack",
    [playerAnimation],
  );
 
  // Calculate attack direction (toward dummy)
  // Note: Direction is calculated on every position change to ensure attacks
  // always target the current dummy position, even if the player is moving.
  // This is intentional for responsive gameplay where attacks can be initiated mid-movement.
  const attackDirection = useMemo(() => {
    // Only calculate if attacking to avoid unnecessary work
    Eif (!isPlayerAttacking) {
      return new THREE.Vector3(0, 0, 1); // Default forward direction
    }
    const dx = dummyPosition[0] - player3DPosition[0];
    const dz = dummyPosition[2] - player3DPosition[2];
    return new THREE.Vector3(dx, 0, dz).normalize();
  }, [dummyPosition, player3DPosition, isPlayerAttacking]);
 
  // Apply attack movement physics to player position
  // Note: currentTechniqueAnimationTypeRef.current is intentionally a ref to avoid
  // unnecessary re-renders. The animation type is read at attack start (in useAttackMovement's
  // internal effect) and doesn't need to be reactive. It's always set before isPlayerAttacking
  // becomes true via the handleAttack action.
  const {
    currentPosition: player3DPositionWithAttackMovement,
  } = useAttackMovement({
    isAttacking: isPlayerAttacking,
    animationType: currentTechniqueAnimationTypeRef.current,
    currentStance: trainingPlayerState.currentStance,
    basePosition: player3DPosition,
    attackDirection,
    animationDuration: 0.4,
  });
 
  // Use position with attack movement for rendering
  const finalPlayer3DPosition = isPlayerAttacking
    ? player3DPositionWithAttackMovement
    : player3DPosition;
 
  // ═══════════════════════════════════════════════════════════════════════════
 
  // Ref to store handleAttack for use in useTechniqueSelection callback
  // This breaks circular dependency between useTechniqueSelection and useTrainingActions
  const handleAttackRef = useRef<(() => void) | null>(null);
 
  // Technique selection and execution for training
  // Moved before useTrainingActions to provide selectedTechniqueId
  const techniqueSelection = useTechniqueSelection({
    player: trainingPlayerState,
    enabled: trainingState.isTraining,
    onTechniqueExecute: useCallback(
      (technique: Technique) => {
        // Show technique usage feedback
        trainingActions.setFeedback(
          `${technique.name.korean} 사용! | Used ${technique.name.english}!`,
        );
 
        // Set attack animation based on technique
        // 기술에 따른 공격 애니메이션 설정
        const animationName = getAnimationForTechnique(
          technique.name.english || technique.id,
        );
        setAttackAnimation(animationName);
 
        // In training mode, do not deduct resources to allow continuous practice
        // Resources are displayed for educational purposes only
 
        // Execute attack with technique (visual feedback)
        // Use ref to avoid circular dependency
        handleAttackRef.current?.();
      },
      [trainingActions],
    ),
  });
 
  // Derive selected technique ID for intensity-based attack sounds
  const selectedTechniqueId = useMemo(() => {
    const techniques = techniqueSelection.availableTechniques;
    const selectedIdx = techniqueSelection.selectedIndex;
    Iif (techniques.length === 0 || selectedIdx < 0 || selectedIdx >= techniques.length) {
      return undefined;
    }
    return techniques[selectedIdx]?.id;
  }, [techniqueSelection.availableTechniques, techniqueSelection.selectedIndex]);
 
  // Training actions hook (matches useCombatActions pattern)
  const {
    handleStartTraining,
    handleStopTraining,
    handleDummyHit,
    handleDummyDefeated,
    handleStanceChange,
    handleAttack,
  } = useTrainingActions({
    state: trainingState,
    actions: trainingActions,
    playerPosition,
    player3DPosition,
    dummyPosition,
    playerArchetype: selectedArchetype,
    playerStance: currentStance,
    currentTechniqueAnimationTypeRef, // Ref for technique's animation type
    audio,
    playBoneImpactSound, // Pass bone impact audio function from useCombatAudio
    playAttackSound, // Pass attack sound function from useCombatAudio
    selectedTechniqueId, // Pass selected technique ID for intensity-based attack sounds
    onPlayerUpdate: (updates) => {
      onPlayerUpdate(updates);
    },
    playerAnimation: {
      transitionTo: playerAnimation.transitionTo,
      transitionToStanceGuard: playerAnimation.transitionToStanceGuard,
      currentState: playerAnimation.currentState,
    },
    pendingAttackRef, // Share the ref with animation events
  });
 
  // Update handleAttack ref for useTechniqueSelection callback
  useEffect(() => {
    handleAttackRef.current = handleAttack;
  }, [handleAttack]);
 
  // Update the ref so animation events can call handleDummyHit
  useEffect(() => {
    handleDummyHitRef.current = handleDummyHit;
  }, [handleDummyHit]);
 
  // Wrapped stance change handler with visual feedback tracking
  // 시각적 피드백 추적을 포함한 자세 변경 핸들러 래퍼
  const handleStanceChangeWithVisualFeedback = useCallback(
    (stanceIndex: number) => {
      // Capture previous stance before the change for visual indicator
      setPreviousStanceIndex(trainingState.currentStanceIndex);
      // Execute the actual stance change
      handleStanceChange(stanceIndex);
    },
    [handleStanceChange, trainingState.currentStanceIndex],
  );
 
  // ═══════════════════════════════════════════════════════════════════════════
  // SECTION 6: Movement-Animation Synchronization
  // ═══════════════════════════════════════════════════════════════════════════
 
  // Sync movement with animation (matches CombatScreen pattern)
  const prevIsMovingRef = useRef<boolean>(isMoving);
  const prevIsRunningRef = useRef<boolean>(isRunning);
  const prevStanceRef = useRef<TrigramStance>(currentStance);
  
  useEffect(() => {
    const isMovingChanged = prevIsMovingRef.current !== isMoving;
    const isRunningChanged = prevIsRunningRef.current !== isRunning;
    const stanceChanged = prevStanceRef.current !== currentStance;
    
    Iif (isMovingChanged || isRunningChanged) {
      if (isMoving) {
        // Transition to running or walking animation based on state
        if (isRunning) {
          playerAnimation.transitionTo(AnimationState.RUN);
        } else {
          playerAnimation.transitionTo(AnimationState.WALK);
        }
      } else if (playerAnimation.currentState === AnimationState.WALK || 
                 playerAnimation.currentState === AnimationState.RUN) {
        // When stopping movement, transition to stance-specific guard animation
        // 이동 중지 시 자세별 가드 애니메이션으로 전환
        playerAnimation.transitionToStanceGuard(currentStance);
      }
      prevIsMovingRef.current = isMoving;
      prevIsRunningRef.current = isRunning;
    }
    
    // Update idle/guard animation when stance changes
    Iif (stanceChanged && !isMoving) {
      // If idle, update to new stance guard
      if (playerAnimation.currentState === AnimationState.IDLE || 
          playerAnimation.isInStanceGuard()) {
        playerAnimation.transitionToStanceGuard(currentStance);
      }
      prevStanceRef.current = currentStance;
    }
  }, [isMoving, isRunning, currentStance, playerAnimation]);
 
  // ═══════════════════════════════════════════════════════════════════════════
  // SECTION 7B: Technique Selection System (Moved earlier - see before useTrainingActions)
  // ═══════════════════════════════════════════════════════════════════════════
 
  // 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]);
 
  // Calculate effective reach based on selected technique (matches CombatSystem)
  // 선택된 기술에 따른 유효 사정거리 계산 (전투 시스템과 동일)
  const { currentTechniqueReach, currentAnimationType } = useMemo(() => {
    const techniques = techniqueSelection.availableTechniques;
    const selectedIdx = techniqueSelection.selectedIndex;
    Iif (techniques.length === 0) {
      return {
        currentTechniqueReach: 0.7,
        currentAnimationType: AnimationType.JAB,
      };
    }
    const currentTechnique =
      techniques[Math.min(selectedIdx, techniques.length - 1)];
    Iif (!currentTechnique) {
      return {
        currentTechniqueReach: 0.7,
        currentAnimationType: AnimationType.JAB,
      };
    }
    // Get animation type from technique ID
    const animConfig = getAnimationForTechniqueOrDefault(currentTechnique.id);
    // Calculate max reach using physical attributes and stance
    const physicalAttributes =
      getArchetypePhysicalAttributes(selectedArchetype);
    const reach = physicalReachCalculator.calculateMaxReach(
      physicalAttributes,
      animConfig.type,
      currentStance,
    );
    return {
      currentTechniqueReach: reach,
      currentAnimationType: animConfig.type,
    };
  }, [
    techniqueSelection.availableTechniques,
    techniqueSelection.selectedIndex,
    selectedArchetype,
    currentStance,
  ]);
 
  // Update the animation type ref in an effect (not during render)
  // 렌더링 중이 아닌 effect에서 ref 업데이트
  useEffect(() => {
    currentTechniqueAnimationTypeRef.current = currentAnimationType;
  }, [currentAnimationType]);
 
  // ═══════════════════════════════════════════════════════════════════════════
  // SECTION 8: Mobile Touch Controls
  // ═══════════════════════════════════════════════════════════════════════════
 
  // Reference for tracking active mobile movement key (prevents stuck keys)
  const activeMobileKeyRef = useRef<string | null>(null);
 
  // Enable mobile controls always in training (allow movement even before starting training)
  const mobileControlsEnabled = isMobile;
 
  // Mobile D-pad movement handler (matches CombatScreen implementation)
  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",
        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
        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;
        }
      }
    },
    [],
  );
 
  // Mobile attack handler - uses the same handleAttack from training actions
  const handleMobileAttack = useCallback(() => {
    handleAttack();
  }, [handleAttack]);
 
  // Mobile block handler
  const handleMobileBlock = useCallback(
    (eventType: ButtonEventType) => {
      if (eventType === "start") {
        audio.playSFX("block");
      }
    },
    [audio],
  );
 
  // Mobile gesture handler
  const handleMobileGesture = useCallback(
    (gesture: GestureEvent) => {
      switch (gesture.type) {
        case "swipe-right":
          window.dispatchEvent(new KeyboardEvent("keydown", { key: "d" }));
          break;
        case "swipe-left":
          window.dispatchEvent(new KeyboardEvent("keydown", { key: "a" }));
          break;
        case "swipe-up":
          if (trainingState.isTraining) {
            window.dispatchEvent(new KeyboardEvent("keydown", { key: " " }));
          }
          break;
        case "swipe-down":
          trainingActions.resetDummy();
          break;
        case "two-finger-tap":
          trainingActions.setTrainingMode(
            trainingState.trainingMode === "vital_point"
              ? "basics"
              : "vital_point",
          );
          audio.playSFX("menu_select");
          break;
      }
    },
    [trainingState, trainingActions, audio],
  );
 
  // Mobile stance change handler
  const handleMobileStanceChange = useCallback(
    (stanceIndex: number) => {
      handleStanceChangeWithVisualFeedback(stanceIndex);
    },
    [handleStanceChangeWithVisualFeedback],
  );
 
  // ═══════════════════════════════════════════════════════════════════════════
  // SECTION 9: Keyboard Input Handling
  // ═══════════════════════════════════════════════════════════════════════════
 
  useEffect(() => {
    const handleKeyDown = (event: KeyboardEvent) => {
      const key = event.key.toLowerCase();
 
      // ESC key - return to menu
      if (key === "escape") {
        onReturnToMenu();
        return;
      }
 
      // Handle stance changes (1-8) - always available for exploration
      if (key >= "1" && key <= "8") {
        const stanceIndex = parseInt(key) - 1;
        handleStanceChangeWithVisualFeedback(stanceIndex);
        event.preventDefault();
        return;
      }
 
      // Handle attacks (Space key) - always available for exploration
      if (key === " ") {
        handleAttack();
        event.preventDefault();
        return;
      }
    };
 
    window.addEventListener("keydown", handleKeyDown);
    return () => window.removeEventListener("keydown", handleKeyDown);
  }, [onReturnToMenu, handleStanceChangeWithVisualFeedback, handleAttack]);
 
  // ═══════════════════════════════════════════════════════════════════════════
  // SECTION 10: Audio Lifecycle Management & Auto-Start Training
  // ═══════════════════════════════════════════════════════════════════════════
 
  // Track if component has mounted to enable auto-start once
  const hasMountedRef = useRef(false);
 
  useEffect(() => {
    let audioStarted = false;
 
    const startMusic = async () => {
      try {
        // Start training music with a smooth 2s fade-in for better UX
        await audio.fadeIn("cyberpunk_fusion", 2000);
        audioStarted = true;
      } catch (err) {
        console.warn("Failed to start training music:", err);
        trainingActions.setFeedback(
          "오디오 초기화 실패 | Audio initialization failed",
        );
      }
    };
 
    void startMusic();
 
    return () => {
      if (audioStarted) {
        void audio
          .fadeOut(2000)
          .then(() => audio.stopMusic())
          .catch((err) => console.warn("Failed to stop training music:", err));
      }
    };
  }, [audio, trainingActions]);
 
  // Auto-start training on mount (only once) - separate effect to avoid re-runs
  useEffect(() => {
    if (!hasMountedRef.current) {
      hasMountedRef.current = true;
      handleStartTraining();
    }
  }, [handleStartTraining]);
 
  // ═══════════════════════════════════════════════════════════════════════════
  // SECTION 11: Feedback & Session Timer Effects
  // ═══════════════════════════════════════════════════════════════════════════
 
  // Hide feedback after delay - 1500ms provides adequate time for bilingual text readability
  // IMPORTANT: We depend on BOTH showFeedback AND feedback message so the timer resets
  // when a new message arrives (even if showFeedback was already true)
  useEffect(() => {
    if (trainingState.showFeedback) {
      const timer = setTimeout(() => trainingActions.hideFeedback(), 1500);
      return () => clearTimeout(timer);
    }
  }, [trainingState.showFeedback, trainingState.feedback, trainingActions]);
 
  // Update session duration
  useEffect(() => {
    if (!trainingState.isTraining || !trainingState.sessionStartTime) return;
 
    const interval = setInterval(() => {
      trainingActions.updateSessionDuration(
        Math.floor((Date.now() - (trainingState.sessionStartTime ?? 0)) / 1000),
      );
    }, 1000);
 
    return () => clearInterval(interval);
  }, [
    trainingState.isTraining,
    trainingState.sessionStartTime,
    trainingActions,
  ]);
 
  // Auto-restart training when mode changes
  const prevTrainingModeRef = useRef<typeof trainingState.trainingMode>(
    trainingState.trainingMode,
  );
  const isFirstModeEffectRef = useRef<boolean>(true);
  const isTrainingRef = useRef<boolean>(trainingState.isTraining);
  const modeChangeTimerRef = useRef<NodeJS.Timeout | null>(null);
 
  // Keep a ref in sync with the latest training state for use inside timeouts
  useEffect(() => {
    isTrainingRef.current = trainingState.isTraining;
  }, [trainingState.isTraining]);
 
  // Store callbacks in refs to avoid effect re-runs when they change
  const handleStartTrainingRef = useRef(handleStartTraining);
  const handleStopTrainingRef = useRef(handleStopTraining);
 
  useEffect(() => {
    handleStartTrainingRef.current = handleStartTraining;
    handleStopTrainingRef.current = handleStopTraining;
  }, [handleStartTraining, handleStopTraining]);
 
  useEffect(() => {
    // Explicitly skip the first execution on initial mount
    Eif (isFirstModeEffectRef.current) {
      isFirstModeEffectRef.current = false;
      prevTrainingModeRef.current = trainingState.trainingMode;
      return;
    }
 
    const previousMode = prevTrainingModeRef.current;
    const modeChanged = previousMode !== trainingState.trainingMode;
 
    if (!modeChanged) {
      return;
    }
 
    // Update previous mode only when an actual change is detected
    prevTrainingModeRef.current = trainingState.trainingMode;
 
    // Clear any existing timer to prevent stale callbacks
    if (modeChangeTimerRef.current) {
      clearTimeout(modeChangeTimerRef.current);
      modeChangeTimerRef.current = null;
    }
 
    // Restart training on mode change (matches UI message "Auto-restarts on mode change")
    if (isTrainingRef.current) {
      handleStopTrainingRef.current();
    }
 
    // Small delay to allow state to settle, then (re)start training unconditionally
    modeChangeTimerRef.current = setTimeout(() => {
      handleStartTrainingRef.current();
      modeChangeTimerRef.current = null;
    }, 100);
 
    return () => {
      if (modeChangeTimerRef.current) {
        clearTimeout(modeChangeTimerRef.current);
        modeChangeTimerRef.current = null;
      }
    };
  }, [trainingState.trainingMode]); // Only depend on training mode to avoid unnecessary re-runs
 
  // ═══════════════════════════════════════════════════════════════════════════
  // SECTION 12: Hit Effect Management
  // ═══════════════════════════════════════════════════════════════════════════
 
  const handleEffectComplete = useCallback(
    (effectId: number) => {
      trainingActions.removeHitEffect(effectId);
    },
    [trainingActions],
  );
 
  // ═══════════════════════════════════════════════════════════════════════════
  // SECTION 13: Anatomy Layer Toggle
  // ═══════════════════════════════════════════════════════════════════════════
 
  const handleAnatomyLayerToggle = useCallback(
    (layer: AnatomyLayer) => {
      trainingActions.toggleAnatomyLayer(layer);
      audio.playSFX("menu_click");
    },
    [trainingActions, audio],
  );
 
  const handleVitalPointClick = useCallback(
    (pointId: string) => {
      trainingActions.setSelectedVitalPoint(pointId);
      audio.playSFX("menu_select");
    },
    [trainingActions, audio],
  );
 
  // ═══════════════════════════════════════════════════════════════════════════
  // SECTION 14: Camera Configuration
  // ═══════════════════════════════════════════════════════════════════════════
 
  // Use shared physics config for consistent camera setup across screens
  // Mobile: tighter FOV and closer camera for better framing
  // Desktop: wider FOV and further camera for full view
  const cameraConfig = useMemo(
    () => createCameraConfig(isMobile),
    [isMobile],
  );
 
  // ═══════════════════════════════════════════════════════════════════════════
  // SECTION 15: RENDER
  // ═══════════════════════════════════════════════════════════════════════════
 
  // Performance settings based on device tier
  const performanceSettings = useMemo(() => {
    return getPerformanceSettings(width, isMobile);
  }, [width, isMobile]);
 
  // SSAO removed - was causing WebGL context loss without NormalPass
 
  return (
    <div
      style={{
        width: `${width}px`,
        height: `${height}px`,
        position: "relative",
        overflow: "hidden", // Prevent content from extending beyond container
      }}
      data-testid="training-screen-3d"
    >
      <Canvas
        style={{ width: `${width}px`, height: `${height}px` }}
        gl={{
          antialias: performanceSettings.antialias,
          alpha: false,
          powerPreference: "high-performance",
          failIfMajorPerformanceCaveat: false, // Don't fail in software renderer
          preserveDrawingBuffer: true, // Help with context stability
        }}
        dpr={performanceSettings.dpr}
        shadows={false} // Temporarily disable shadows
        onCreated={({ gl }) => {
          gl.setClearColor(theme.colors.UI_BACKGROUND_DARK, 1);
          // Disable fog temporarily for debugging
        }}
        camera={cameraConfig}
      >
        {/* Lighting - base lighting, arena provides additional */}
        <ambientLight intensity={0.6} />
        <directionalLight position={[10, 10, 5]} intensity={1.2} />
 
        {/* Combat Arena 3D Environment - uses physics-based world dimensions */}
        <CombatArena3D
          lighting="cyberpunk"
          scale={trainingAreaBounds.scale}
          worldWidthMeters={trainingAreaBounds.worldWidthMeters}
          worldDepthMeters={trainingAreaBounds.worldDepthMeters}
        />
 
        {/* Animation updater - 60fps updates */}
        <TrainingAnimationUpdater playerAnimation={playerAnimation} />
 
        {/* Acceleration updater - tracks movement time and updates speed */}
        <AccelerationUpdater
          isMoving={isMoving}
          velocity={velocity}
          movementTimeRef={movementTimeRef}
          lastDirectionRef={lastDirectionRef}
          onSpeedUpdate={setAccelerationBasedSpeed}
          walkSpeed={walkRunSpeeds.walkSpeed}
          runSpeed={walkRunSpeeds.runSpeed}
        />
 
        {/* Training dummy at fixed position */}
        <TrainingDummy3D
          position={dummyPosition}
          selectedVitalPoint={trainingState.selectedVitalPoint}
          isTraining={trainingState.isTraining}
          health={trainingState.dummyHealth}
          onVitalPointHit={handleDummyHit}
          onDefeated={handleDummyDefeated}
          difficulty={difficulty}
          vitalPointCount={vitalPointCount}
          isMobile={isMobile}
        />
 
        {/* Anatomy overlay for educational visualization */}
        {trainingState.visibleAnatomyLayers.length > 0 && (
          <AnatomyOverlay3D
            position={dummyPosition}
            visibleLayers={trainingState.visibleAnatomyLayers}
            opacity={0.6}
            isMobile={isMobile}
          />
        )}
 
        {/* Vital Point Overlay - Show all 70 points on dummy */}
        {overlayVisible && (
          <VitalPointMarkers3D
            position={dummyPosition}
            visible={overlayVisible}
            severityFilter={severityFilters}
            regionFilter={regionFilter}
            searchQuery={searchQuery}
            showLabels={showLabels}
            scale={scale}
            animated={animated}
            selectedPoint={trainingState.selectedVitalPoint}
            onPointClick={handleVitalPointClick}
          />
        )}
 
        {/* Player model */}
        <Player3DWithTransitions
          {...convertPlayerStateToProps(
            trainingPlayerState,
            finalPlayer3DPosition,
            playerRotation,
            {
              isMobile,
              facing: "right",
              enableFacialExpressions: true,
              enableEyeTracking: true,
              opponentPosition: dummyPosition,
            },
          )}
          currentAnimation={animationStateToPlayerAnimation(
            playerAnimation.currentState,
          )}
          attackAnimation={attackAnimation}
          laterality={currentLaterality}
          enableTransitionEffects={!isMobile}
          enableStanceSymbol={true}
          enableStanceAudio={true}
        />
 
        {/* Foot Placement Markers for Footwork Drills */}
        {trainingState.trainingMode === "footwork" &&
          trainingState.footworkDrillActive && (
            <FootPlacementMarkers3D
              centerPosition={dummyPosition}
              pattern={
                trainingState.footworkDrillType === "free_practice"
                  ? "none"
                  : trainingState.footworkDrillType
              }
              currentStep={trainingState.footworkDrillStep}
              visible={true}
              scale={1.0}
              animated={true}
            />
          )}
 
        {/* Hit effects */}
        {trainingState.hitEffects.map((effect) => (
          <HitFeedbackEffect3D
            key={effect.id}
            position={effect.position}
            type={effect.type}
            damage={effect.damage}
            visible={effect.visible}
            onComplete={() => handleEffectComplete(effect.id)}
            isMobile={isMobile}
          />
        ))}
 
        {/* Stance Change Visual Indicator */}
        <StanceChangeIndicator
          currentStance={trainingState.currentStanceIndex}
          previousStance={previousStanceIndex}
          isMobile={isMobile}
        />
 
        {/* NOTE: Mobile controls moved OUTSIDE Canvas for reliable touch events */}
        {/* See MobileControlsPure component rendered after HUDs */}
 
        {/* 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) - matches CombatScreen pattern */}
      <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",
        }}
        data-testid="training-hud-overlay"
      >
        {/* Left HUD - Anatomy Controls, Guard Indicator */}
        <TrainingLeftHUD
          width={width}
          height={height}
          isMobile={isMobile}
          positionScale={positionScale}
          visibleAnatomyLayers={trainingState.visibleAnatomyLayers}
          onAnatomyLayerToggle={handleAnatomyLayerToggle}
          currentStanceIndex={trainingState.currentStanceIndex}
          isInGuard={playerAnimation.isInStanceGuard()}
        />
 
        {/* Top HUD - Training Controls, Archetype Selector, Return Button */}
        <TrainingTopHUD
          width={width}
          height={height}
          isMobile={isMobile}
          positionScale={positionScale}
          isTraining={trainingState.isTraining}
          onStartTraining={handleStartTraining}
          onStopTraining={handleStopTraining}
          selectedArchetype={selectedArchetype}
          onArchetypeSelect={setSelectedArchetype}
          overlayVisible={overlayVisible}
          onReturnToMenu={onReturnToMenu}
          onPlaySFX={(sound) => audio.playSFX(sound)}
        />
 
        {/* Right HUD - Mode Selector, Stats, Vital Point Selection */}
        <TrainingRightHUD
          width={width}
          height={height}
          isMobile={isMobile}
          positionScale={positionScale}
          trainingMode={trainingState.trainingMode}
          onModeChange={trainingActions.setTrainingMode}
          stats={{
            ...trainingState.stats,
            sessionDuration: trainingState.sessionDuration,
            bestCombo: trainingState.bestCombo,
            perfectStrikes: trainingState.perfectStrikes,
          }}
          distanceToDummy={distanceToDummy}
          effectiveReach={currentTechniqueReach}
          selectedVitalPoint={trainingState.selectedVitalPoint}
          onVitalPointSelect={trainingActions.setSelectedVitalPoint}
          footworkDrillType={trainingState.footworkDrillType}
          footworkDrillStep={trainingState.footworkDrillStep}
          footworkDrillActive={trainingState.footworkDrillActive}
          onStartFootworkDrill={trainingActions.startFootworkDrill}
          onStopFootworkDrill={trainingActions.stopFootworkDrill}
          onAdvanceFootworkStep={trainingActions.advanceFootworkStep}
        />
 
        {/* Bottom HUD - Technique Bar, Feedback Messages, Mobile Controls */}
        <TrainingBottomHUD
          width={width}
          height={height}
          isMobile={isMobile}
          positionScale={positionScale}
          techniques={techniqueSelection.availableTechniques}
          player={trainingPlayerState}
          selectedIndex={techniqueSelection.selectedIndex}
          cooldowns={cooldownsMap}
          onTechniqueSelect={techniqueSelection.selectTechnique}
          showFeedback={trainingState.showFeedback}
          feedbackMessage={trainingState.feedback}
          selectedArchetype={selectedArchetype}
          onArchetypeSelect={setSelectedArchetype}
          onPlaySFX={(sound) => audio.playSFX(sound)}
        />
 
        {/* Vital Point Overlay Controls - Pure DOM overlay (outside Canvas) */}
        {overlayVisible && (
          <VitalPointOverlayControlsPure
            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}
            screenPosition={{ top: "180px", left: "20px" }}
            isMobile={isMobile}
          />
        )}
 
        {/* Mobile Controls - Pure DOM overlay (outside Canvas for reliable touch) */}
        {isMobile && (
          <>
            <MobileControlsOverlay
              onMove={handleMobileMove}
              onAttack={handleMobileAttack}
              onBlock={handleMobileBlock}
              disabled={!mobileControlsEnabled}
              bottom={getMobileControlsBottom()}
              opacity={0.85}
            />
 
            <StanceWheelPure
              currentStance={trainingState.currentStanceIndex}
              onStanceChange={handleMobileStanceChange}
              expanded={trainingState.stanceWheelExpanded}
              onToggle={trainingActions.toggleStanceWheel}
              disabled={!mobileControlsEnabled}
              opacity={0.8}
            />
 
            <GestureRecognizerPure
              onGesture={handleMobileGesture}
              enabled={mobileControlsEnabled}
              showFeedback={true}
              minSwipeDistance={50}
            />
          </>
        )}
      </div>
    </div>
  );
};
 
export default TrainingScreen3D;