All files / systems CombatSystem.ts

84.7% Statements 227/268
69.43% Branches 209/301
90.9% Functions 30/33
84.7% Lines 227/268

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                                                                                                                                                            209x 209x     209x 209x 209x 209x 209x 209x 209x 209x 209x 209x                                                                 4x                                                                 2x                                                                   22x             22x 1x     21x     21x                       21x     21x                                                                               166x     166x 58x                                 108x                                     108x 18x     18x 3x                                 15x     15x                     15x                   15x     15x           15x     15x 11x                                   94x           94x 94x 94x   94x 23x                                 71x 49x                 49x       49x                                   22x 22x 3x                 22x                         166x 166x     166x     166x           166x                                                                       71x         71x             71x 71x 71x   71x             71x       71x     71x       71x   71x                                   71x                                                     49x     49x             49x   33x                                 16x                                         49x           49x       49x     49x         1x       48x         48x                                                                                                                                         3x                 3x                                       3x               3x   1x                             2x   2x                                               29x 29x   29x   23x 23x       23x           23x     23x 21x       23x 1x             23x 10x             10x     10x     3x                 23x 23x       23x       23x 23x             23x                       23x       21x   21x   21x                 29x                           23x                       23x                       23x 3x     3x     3x 3x       20x                                       23x                                                                                 23x                       3x     3x     3x 3x             3x     3x 3x 1x 1x         3x                           38x 38x   38x   31x         31x                   31x 30x 30x               31x               31x 4x       31x 4x             31x 1x               38x                 38x                           31x   6x     25x         31x     31x               1x       24x                   24x                         24x                     24x                 10x       14x                         14x             21x     21x 143x                     309x                               2x 2x             4x             10011x     10011x     10011x     10011x     10011x 2x                   10011x 4x     4x       4x             10011x       10002x             10011x             10011x 10011x               10011x                       3x                                 3x   3x 1x                 2x                                                                                       17x 3x           14x 14x     14x 14x     14x       14x       14x 6x 8x     4x 4x     4x                               2x 2x 2x   2x 1x                                 1x             1x             1x                                                               34x     34x     34x 34x   8x                 8x       34x     34x 34x           34x   34x                                       8x                               8x        
import * as THREE from "three";
import { getArchetypePhysicalAttributes } from "../data/archetypePhysicalAttributes";
import { getTechniqueById } from "../data/techniques";
import { BodyRegion, CombatAttackType, CombatState, DamageType, GrappleTarget } from "../types";
import { VitalPointCategory, VitalPointSeverity } from "../types/common";
import { BASE_STAMINA_REGEN_RATE } from "../types/physicsConstants";
import { Technique } from "../types/technique";
import { calculateDistance3D } from "../utils/math";
import { calculateBodyRadius } from "../utils/skeletonScaling";
import type { DefensiveAnimationType } from "./animation";
import {
  AnimationType,
  calculateSpeedModifierForDamage,
  determineAnimationTypeForTechnique,
  getAdjustedAnimationDuration,
  getAnimationNameForType,
  isWithinHitWindow,
} from "./animation";
import { applyDamageToBodyParts } from "./bodypart/BodyPartDamageIntegration";
import { playerInjuryManager } from "./bodypart";
import {
  applyBreathingDisruptionFromVitalPoint,
  applyBreathingDisruptionFromTorsoDamage,
  BreathingDisruptionSystem,
  causesBreathingDisruption,
  updateBreathingDisruption,
} from "./breathing";
import BalanceSystem from "./combat/BalanceSystem";
import ConsciousnessSystem from "./combat/ConsciousnessSystem";
import {
  extractVitalPointCategory,
  isHeadTraumaHit,
} from "./combat/painConsciousnessUtils";
import PainResponseSystem, {
  ShockPainEffect,
} from "./combat/PainResponseSystem";
import { CombatResult, CombatSystemInterface } from "./combat/types";
import {
  CollisionDetection,
  KnockbackPhysics,
  physicalReachCalculator,
  type KnockbackConfig,
} from "./physics";
import { PlayerState } from "./player";
import {
  addEffectsToPlayer,
  getEffectModifiers,
  removeExpiredEffects,
} from "./PlayerEffectManager";
import { TRIGRAM_TECHNIQUES } from "./trigram";
import { TrigramSystem } from "./TrigramSystem";
import { StatusEffect } from "./types";
import { KoreanTechnique, VitalPointHitResult } from "./vitalpoint/types";
import { VitalPointSystem } from "./VitalPointSystem";
import { GrappleSystem } from "./combat/GrappleSystem";
 
/**
 * Enhanced Combat System with Pain Response and Consciousness integration.
 *
 * Integrates realistic pain accumulation and consciousness tracking for
 * progressive combat impairment.
 */
export class CombatSystem implements CombatSystemInterface {
  private vitalPointSystem: VitalPointSystem;
  protected trigramSystem: TrigramSystem;
  private painSystem: PainResponseSystem;
  private consciousnessSystem: ConsciousnessSystem;
  private balanceSystem: BalanceSystem;
  private knockbackPhysics: KnockbackPhysics;
  private collisionDetection: CollisionDetection;
  private grappleSystem: GrappleSystem;
 
  // Track shock pain effects per player
  private shockPainEffects: Map<string, ShockPainEffect>;
  // Track last head trauma time per player for consciousness recovery
  private lastHeadTraumaTime: Map<string, number>;
 
  // Vital point severity thresholds
  private readonly SEVERITY_MAJOR_THRESHOLD = 30;
  private readonly SEVERITY_MODERATE_THRESHOLD = 20;
 
  constructor() {
    this.vitalPointSystem = new VitalPointSystem();
    this.trigramSystem = new TrigramSystem();
    this.painSystem = new PainResponseSystem();
    this.consciousnessSystem = new ConsciousnessSystem();
    this.balanceSystem = new BalanceSystem();
    this.knockbackPhysics = new KnockbackPhysics();
    this.collisionDetection = new CollisionDetection();
    this.grappleSystem = new GrappleSystem();
    this.shockPainEffects = new Map();
    this.lastHeadTraumaTime = new Map();
  }
 
  /**
   * Cleanup per-player combat state.
   *
   * Call this when a player permanently leaves the match or when
   * match-level cleanup is performed to avoid unbounded Map growth.
   *
   * @param playerId - ID of the player to cleanup
   *
   * @public
   * @korean 플레이어데이터정리
   */
  public cleanupPlayerData(playerId: string): void {
    this.shockPainEffects.delete(playerId);
    this.lastHeadTraumaTime.delete(playerId);
  }
 
  /**
   * Dispose of all combat system resources.
   *
   * **Korean**: 전투 시스템 자원 정리
   *
   * Cleans up Three.js resources (geometries, raycaster) used by the collision
   * detection system to prevent memory leaks. Should be called when the
   * CombatSystem is destroyed or reinitialized.
   *
   * @public
   * @korean 전투시스템자원정리
   */
  public dispose(): void {
    // Dispose collision detection resources (cached geometries, raycaster)
    this.collisionDetection.dispose();
  }
 
  /**
   * Get the balance system instance for fall checking.
   *
   * @returns BalanceSystem instance
   * @public
   * @korean 균형시스템가져오기
   */
  public getBalanceSystem(): BalanceSystem {
    return this.balanceSystem;
  }
 
  /**
   * Get the consciousness system instance for fall checking.
   *
   * @returns ConsciousnessSystem instance
   * @public
   * @korean 의식시스템가져오기
   */
  public getConsciousnessSystem(): ConsciousnessSystem {
    return this.consciousnessSystem;
  }
 
  /**
   * Get the collision detection system instance.
   *
   * @returns CollisionDetection instance
   * @public
   * @korean 충돌감지시스템가져오기
   */
  public getCollisionDetection(): CollisionDetection {
    return this.collisionDetection;
  }
 
  /**
   * Calculate knockback physics for combat hit.
   *
   * **Korean**: 밀침 계산 (Calculate Knockback)
   *
   * Determines knockback displacement, duration, and fall state based on:
   * - Attack damage amount
   * - Defender's balance state
   * - Defender's stance resistance
   * - Attack direction vector
   *
   * @param attacker - Attacking player state
   * @param defender - Defending player state
   * @param damage - Total damage dealt
   * @returns Knockback information or undefined if no knockback
   *
   * @example
   * ```typescript
   * const knockback = this.calculateKnockback(attacker, defender, 80);
   * // Returns: { displacement: {x:2.5,y:0,z:0}, duration:0.8, recoveryWindow:0.7, shouldFall:false }
   * ```
   *
   * @private
   * @korean 밀침계산
   */
  private calculateKnockback(
    attacker: PlayerState,
    defender: PlayerState,
    damage: number,
  ): CombatResult["knockback"] {
    // Calculate attack direction vector (attacker → defender)
    const attackDirection = new THREE.Vector3(
      defender.position.x - attacker.position.x,
      0, // Keep knockback on horizontal plane
      defender.position.y - attacker.position.y,
    );
 
    // If attacker and defender are at the exact same position, skip knockback to avoid NaN direction
    if (attackDirection.lengthSq() === 0) {
      return undefined;
    }
 
    attackDirection.normalize();
 
    // Create knockback configuration
    const config: KnockbackConfig = {
      force: damage * 10, // Convert damage to force (arbitrary scaling)
      direction: attackDirection,
      duration: 0, // Will be calculated by physics engine
      balanceState: {
        current: defender.balance,
        max: 100, // Assuming max balance is always 100
      },
      currentStance: defender.currentStance,
    };
 
    // Calculate knockback result
    const result = this.knockbackPhysics.calculateKnockback(config, damage);
 
    // Convert Three.js Vector3 to plain object for serialization
    return {
      displacement: {
        x: result.displacement.x,
        y: result.displacement.y,
        z: result.displacement.z,
      },
      duration: result.duration,
      recoveryWindow: result.recoveryWindow,
      shouldFall: result.shouldFall,
    };
  }
 
  /**
   * Fix: Update resolveAttack to match interface signature and add animation-aware hit detection
   *
   * **Korean**: 공격 해결 (애니메이션 인식)
   *
   * Integrates animation timing and physical reach calculation for reality-based hit detection.
   * Hits only register when:
   * 1. Animation is in hit window (extension phase)
   * 2. Attacker is within effective reach based on limb length and animation
   * 3. Existing accuracy and stance checks pass
   *
   * @param attacker - Attacking player state
   * @param defender - Defending player state
   * @param technique - Technique being executed
   * @param targetedVitalPointId - Optional specific vital point target
   * @param animationContext - Optional animation timing context for reality-based hit detection
   * @returns Combat result with hit/miss and damage information
   */
  resolveAttack(
    attacker: PlayerState,
    defender: PlayerState,
    technique: KoreanTechnique,
    targetedVitalPointId?: string,
    animationContext?: {
      animationType: AnimationType;
      currentTime: number;
    },
  ): CombatResult {
    const timestamp = Date.now();
 
    // Check if attacker can execute the technique
    if (!this.canExecuteTechnique(attacker, technique)) {
      return {
        hit: false,
        damage: 0,
        criticalHit: false,
        vitalPointHit: false,
        effects: [],
        timestamp,
        technique,
        attacker,
        defender,
        success: false,
        isCritical: false,
        isBlocked: false,
      };
    }
 
    // Check if attacker is being grappled - cannot attack while controlled
    Iif (attacker.combatState === CombatState.GRAPPLED) {
      return {
        hit: false,
        damage: 0,
        criticalHit: false,
        vitalPointHit: false,
        effects: [],
        timestamp,
        technique,
        attacker,
        defender,
        success: false,
        isCritical: false,
        isBlocked: false,
      };
    }
 
    // === ANIMATION-AWARE HIT DETECTION ===
    // If animation context provided, validate timing and reach
    if (animationContext) {
      const { animationType, currentTime } = animationContext;
 
      // Check if within hit window (extension phase)
      if (!isWithinHitWindow(animationType, currentTime)) {
        return {
          hit: false,
          damage: 0,
          criticalHit: false,
          vitalPointHit: false,
          effects: [],
          timestamp,
          technique,
          attacker,
          defender,
          success: false,
          isCritical: false,
          isBlocked: false,
        };
      }
 
      // Calculate effective reach based on physical attributes and animation
      const attackerPhysical = getArchetypePhysicalAttributes(
        attacker.archetype,
      );
      const reachResult = physicalReachCalculator.calculateReach(
        attackerPhysical,
        animationType,
        currentTime,
        attacker.currentStance,
        technique.reachConfig, // Pass reachConfig for hybrid reach calculation
      );
 
      // Check distance to defender using 3D Euclidean distance
      // Physics-first: Position type is 2D in METERS
      // No conversion needed - positions are already in meters
      const centerToCenterDistance = calculateDistance3D(
        [attacker.position.x, attacker.position.y, 0],
        [defender.position.x, defender.position.y, 0],
      );
 
      // Calculate body radii
      // Note: PhysicalReachCalculator already includes attacker body pivot/offset in reach calculation
      // (shoulder offset for punches, hip rotation for kicks), so we only subtract defender radius
      // to avoid double-counting the attacker's body dimension.
      // 타격 거리 계산: 수비자 몸체 반경만 제외 (공격자 몸체 오프셋은 이미 도달 거리에 포함됨)
      const defenderPhysical = getArchetypePhysicalAttributes(
        defender.archetype,
      );
      const defenderBodyRadius = calculateBodyRadius(defenderPhysical);
 
      // Effective distance = center-to-center minus defender body radius only
      // Reach is calculated from attacker center to striking limb surface (includes body pivot),
      // so we measure from attacker center to defender surface (subtracting defender radius only).
      // 유효 거리 = 중심간 거리 - 수비자 몸체 반경
      const distance = Math.max(0, centerToCenterDistance - defenderBodyRadius);
 
      // If out of reach, miss
      if (distance > reachResult.effectiveReach) {
        return {
          hit: false,
          damage: 0,
          criticalHit: false,
          vitalPointHit: false,
          effects: [],
          timestamp,
          technique,
          attacker,
          defender,
          success: false,
          isCritical: false,
          isBlocked: false,
        };
      }
    }
 
    // Fix: Use correct method signature
    const stanceEffectiveness = this.trigramSystem.calculateStanceEffectiveness(
      attacker.currentStance,
      defender.currentStance,
    );
 
    // Calculate base hit chance
    const baseAccuracy = technique.accuracy * stanceEffectiveness;
    const hitRoll = Math.random();
    const hit = hitRoll <= baseAccuracy;
 
    if (!hit) {
      return {
        hit: false,
        damage: 0,
        criticalHit: false,
        vitalPointHit: false,
        effects: [],
        timestamp,
        technique,
        attacker,
        defender,
        success: false,
        isCritical: false,
        isBlocked: false,
      };
    }
 
    // Special handling for grapple techniques
    if (technique.type === CombatAttackType.GRAPPLE) {
      const grappleResult = this.handleGrappleTechnique(
        attacker,
        defender,
        technique,
        timestamp
      );
 
      // Grapples don't deal immediate damage, they establish control
      // Small damage on successful grapple to represent the initial impact
      const grappleDamage = grappleResult.grappleSuccess
        ? technique.damage * 0.3
        : 0;
 
      return {
        hit: grappleResult.grappleSuccess,
        damage: grappleDamage,
        criticalHit: false,
        vitalPointHit: false,
        effects: [],
        timestamp,
        technique,
        attacker: grappleResult.updatedAttacker,
        defender: grappleResult.updatedDefender,
        success: grappleResult.grappleSuccess,
        isCritical: false,
        isBlocked: false,
        animation: this.getAnimationInfoForTechnique(technique),
      };
    }
 
    // Process vital point hit if targeted (with archetype parameters)
    let vitalPointResult: VitalPointHitResult | null = null;
    if (targetedVitalPointId) {
      vitalPointResult = this.processVitalPointHit(
        targetedVitalPointId,
        technique.damage ?? 15,
        attacker,
        defender,
      );
    }
 
    // Calculate damage using the interface method
    const damageResult = this.calculateDamage(
      technique,
      attacker,
      defender,
      vitalPointResult ?? {
        hit: false,
        damage: 0,
        effects: [],
        severity: VitalPointSeverity.MINOR,
      },
    );
 
    // Check for critical hit
    const critRoll = Math.random();
    const isCritical = critRoll <= (technique.critChance ?? 0.1);
 
    // Determine animation information for technique
    const animationInfo = this.getAnimationInfoForTechnique(technique);
 
    // Calculate knockback physics (밀침 물리)
    const knockbackInfo = this.calculateKnockback(
      attacker,
      defender,
      damageResult.totalDamage,
    );
 
    return {
      hit: true,
      damage: damageResult.totalDamage,
      criticalHit: isCritical,
      vitalPointHit: vitalPointResult?.hit ?? false,
      effects: damageResult.effectsApplied,
      timestamp,
      technique,
      attacker,
      defender,
      success: true,
      isCritical: vitalPointResult?.hit ?? false,
      isBlocked: false,
      targetedVitalPointId, // Pass through the targeted vital point ID
      animation: animationInfo, // Add animation information
      knockback: knockbackInfo, // Add knockback information
    };
  }
 
  /**
   * Get animation information for a technique
   *
   * Determines the skeletal animation to play, duration, and speed modifier
   * based on technique configuration or automatic determination.
   *
   * @param technique - Korean technique to execute
   * @returns Animation information or undefined
   *
   * @private
   * @korean 기술애니메이션정보가져오기
   */
  private getAnimationInfoForTechnique(
    technique: KoreanTechnique,
  ): CombatResult["animation"] {
    // Check if technique has explicit animation config (from Technique interface)
    // KoreanTechnique may not have animation field, so check the technique data
    const techniqueData = this.getTechniqueData(technique);
 
    let animationType;
    let speedModifier;
 
    Iif (techniqueData?.animation) {
      // Use explicit animation configuration
      animationType = techniqueData.animation.type;
      speedModifier = techniqueData.animation.speedModifier;
    } else {
      // Auto-determine animation from technique characteristics
      const techniqueName =
        technique.name?.english || technique.englishName || "";
      const techniqueId = technique.id || "";
      const damageType = technique.damageType || "";
 
      animationType = determineAnimationTypeForTechnique(
        techniqueName,
        techniqueId,
        damageType,
      );
 
      // Calculate speed modifier based on technique damage
      speedModifier = calculateSpeedModifierForDamage(technique.damage || 15);
    }
 
    // Get base animation name from animation type
    const animationName = getAnimationNameForType(animationType);
 
    // Calculate adjusted duration
    const duration = getAdjustedAnimationDuration(animationName, speedModifier);
 
    // Get Korean technique name for display
    const techniqueDisplayName =
      technique.name?.korean || technique.koreanName || technique.id;
 
    return {
      animationName,
      duration,
      speedModifier,
      techniqueDisplayName,
    };
  }
 
  /**
   * Get Technique data if this KoreanTechnique has an associated Technique definition
   *
   * @param technique - Korean technique
   * @returns Technique data or null
   *
   * @private
   * @korean 기술데이터가져오기
   */
  private getTechniqueData(technique: KoreanTechnique): Technique | null {
    return getTechniqueById(technique.id) ?? null;
  }
 
  /**
   * Handle grapple technique execution.
   *
   * **Korean**: 잡기 기술 처리 (Handle Grapple Technique)
   *
   * Initiates or transitions grapple control based on technique.
   *
   * @param attacker - Player executing grapple
   * @param defender - Target player
   * @param technique - Grapple technique being used
   * @param currentTime - Current game time in milliseconds
   * @returns Updated player states with grapple control
   */
  handleGrappleTechnique(
    attacker: PlayerState,
    defender: PlayerState,
    technique: KoreanTechnique,
    currentTime: number
  ): {
    updatedAttacker: PlayerState;
    updatedDefender: PlayerState;
    grappleSuccess: boolean;
  } {
    // Determine grapple target from technique
    const target = this.getGrappleTargetFromTechnique(technique);
 
    // Attempt grapple
    const result = this.grappleSystem.attemptGrapple(
      attacker,
      defender,
      target,
      currentTime
    );
 
    if (result.success && result.grappleControl) {
      // Grapple succeeded - update both players
      return {
        updatedAttacker: {
          ...attacker,
          combatState: CombatState.GRAPPLING,
          grappleControl: result.grappleControl,
          stamina: Math.max(0, attacker.stamina - result.staminaCost),
        },
        updatedDefender: {
          ...defender,
          combatState: CombatState.GRAPPLED,
          grappleControl: result.grappleControl,
        },
        grappleSuccess: true,
      };
    }
 
    // Grapple failed
    return {
      updatedAttacker: {
        ...attacker,
        stamina: Math.max(0, attacker.stamina - result.staminaCost),
      },
      updatedDefender: defender,
      grappleSuccess: false,
    };
  }
 
  /**
   * Determine grapple target from technique characteristics.
   *
   * **Korean**: 기술에서 잡기 목표 결정 (Determine Grapple Target from Technique)
   *
   * @private
   */
  private getGrappleTargetFromTechnique(
    technique: KoreanTechnique
  ): GrappleTarget {
    // Check technique name/ID for hints (both English and Korean)
    const techName = (
      technique.name?.english ||
      technique.englishName ||
      ""
    ).toLowerCase();
    const techNameKorean = (
      technique.name?.korean ||
      technique.koreanName ||
      ""
    );
    const techId = technique.id.toLowerCase();
 
    // Check for wrist/hand - 손목 (sonmok)
    if (
      techName.includes("wrist") ||
      techId.includes("wrist") ||
      techNameKorean.includes("손목")
    ) {
      return GrappleTarget.HAND;
    }
 
    // Check for arm - 팔 (pal)
    Eif (
      techName.includes("arm") ||
      techId.includes("arm") ||
      techNameKorean.includes("팔")
    ) {
      return GrappleTarget.ARM;
    }
 
    // Check for leg - 다리 (dari)
    if (
      techName.includes("leg") ||
      techId.includes("leg") ||
      techNameKorean.includes("다리")
    ) {
      return GrappleTarget.LEG;
    }
 
    // Check for neck - 목 (mok)
    if (
      techName.includes("neck") ||
      techId.includes("neck") ||
      techNameKorean.includes("목")
    ) {
      return GrappleTarget.NECK;
    }
 
    // Check for both arms - 양팔 (yangpal)
    if (
      techName.includes("both") ||
      techName.includes("double") ||
      techId.includes("both") ||
      techNameKorean.includes("양팔") ||
      techNameKorean.includes("쌍")
    ) {
      return GrappleTarget.BOTH_ARMS;
    }
 
    // Check for torso/body/hip - 몸통 (momtong), 허리 (heori), 몸 (mom)
    if (
      techName.includes("torso") ||
      techName.includes("body") ||
      techName.includes("hip") ||
      techId.includes("torso") ||
      techNameKorean.includes("몸통") ||
      techNameKorean.includes("허리") ||
      techNameKorean.includes("몸")
    ) {
      return GrappleTarget.TORSO;
    }
 
    // Default to arm for unspecified grapples
    return GrappleTarget.ARM;
  }
 
  /**
   * Update grapple state for players over time.
   *
   * **Korean**: 잡기 상태 업데이트 (Update Grapple State)
   *
   * @param controller - Player maintaining control
   * @param target - Player being controlled
   * @param deltaTime - Time elapsed in seconds
   * @param currentTime - Current game time in milliseconds
   * @returns Updated player states
   */
  updateGrappleState(
    controller: PlayerState,
    target: PlayerState,
    deltaTime: number,
    currentTime: number
  ): {
    updatedController: PlayerState;
    updatedTarget: PlayerState;
  } {
    Iif (!controller.grappleControl) {
      // No active grapple
      return {
        updatedController: controller,
        updatedTarget: target,
      };
    }
 
    // Validate grapple control consistency
    Iif (
      controller.grappleControl.controllerId !== controller.id ||
      controller.grappleControl.targetId !== target.id
    ) {
      // Inconsistent state - break grapple
      return {
        updatedController: {
          ...controller,
          combatState: CombatState.IDLE,
          grappleControl: null,
        },
        updatedTarget: {
          ...target,
          combatState: CombatState.IDLE,
          grappleControl: null,
        },
      };
    }
 
    // Update grapple control
    const updatedControl = this.grappleSystem.updateGrapple(
      controller.grappleControl,
      controller,
      target,
      deltaTime,
      currentTime
    );
 
    if (!updatedControl) {
      // Grapple broken - reset both players
      return {
        updatedController: {
          ...controller,
          combatState: CombatState.IDLE,
          grappleControl: null,
        },
        updatedTarget: {
          ...target,
          combatState: CombatState.IDLE,
          grappleControl: null,
        },
      };
    }
 
    // Deduct stamina from controller
    const staminaCost = updatedControl.staminaCostPerSecond * deltaTime;
 
    return {
      updatedController: {
        ...controller,
        grappleControl: updatedControl,
        stamina: Math.max(0, controller.stamina - staminaCost),
      },
      updatedTarget: {
        ...target,
        grappleControl: updatedControl,
      },
    };
  }
 
  /**
   * Fix: Make applyCombatResult non-static instance method with effect application
   * Enhanced with Pain Response and Consciousness System integration
   */
  applyCombatResult(
    result: CombatResult,
    attacker: PlayerState,
    defender: PlayerState,
  ): { updatedAttacker: PlayerState; updatedDefender: PlayerState } {
    // Start with base result
    const { updatedAttacker, updatedDefender: initialDefender } =
      CombatSystem.applyCombatResult(result, attacker, defender);
    let updatedDefender = initialDefender;
 
    if (result.hit && result.damage > 0) {
      // Determine vital point category and severity from hit result
      const category = this.getVitalPointCategory(result);
      const severity = this.getVitalPointSeverity(result);
 
      // Apply pain from damage
      const { player: defenderWithPain, shockEffect: newShockEffect } =
        this.painSystem.applyPain(
          updatedDefender,
          result.damage,
          severity,
          category,
        );
      updatedDefender = defenderWithPain;
 
      // Store shock pain effect if triggered
      if (newShockEffect) {
        this.shockPainEffects.set(updatedDefender.id, newShockEffect);
      }
 
      // Check for pain overload stun
      if (this.painSystem.shouldTriggerStun(updatedDefender)) {
        updatedDefender = {
          ...updatedDefender,
          isStunned: true,
        };
      }
 
      // Apply consciousness damage for head/neurological hits
      if (this.isHeadTrauma(result, category)) {
        updatedDefender = this.consciousnessSystem.applyDamage(
          updatedDefender,
          result.damage,
          category,
        );
 
        // Track head trauma time for recovery gating
        this.lastHeadTraumaTime.set(updatedDefender.id, Date.now());
 
        // Check incapacitation threshold
        if (
          this.consciousnessSystem.isAtIncapacitationThreshold(updatedDefender)
        ) {
          updatedDefender = {
            ...updatedDefender,
            isStunned: true,
            // Could add helpless duration tracking here if needed
          };
        }
      }
 
      // Apply pain and consciousness effects to stats
      const currentShockEffect = this.shockPainEffects.get(updatedDefender.id);
      updatedDefender = this.painSystem.applyEffects(
        updatedDefender,
        currentShockEffect,
      );
      updatedDefender = this.consciousnessSystem.applyEffects(updatedDefender);
 
      // Apply balance disruption from the hit
      // Determine body region from vital point or use default
      const bodyRegion = this.getBodyRegionFromResult(result);
      updatedDefender = this.balanceSystem.disruptBalance(
        updatedDefender,
        result.damage,
        bodyRegion,
      );
 
      // Apply breathing disruption for torso strikes
      Iif (result.vitalPointHit && result.targetedVitalPointId) {
        // Vital point strike to torso
        const vitalPoint = this.vitalPointSystem.getVitalPointById(
          result.targetedVitalPointId,
        );
        if (vitalPoint && causesBreathingDisruption(vitalPoint.id)) {
          updatedDefender = applyBreathingDisruptionFromVitalPoint(
            updatedDefender,
            vitalPoint,
            Date.now(),
          );
        }
      } else if (bodyRegion === BodyRegion.TORSO && result.damage >= 10) {
        // General torso damage (non-vital point hits)
        // Apply breathing disruption if damage is significant enough
        // Note: Solar plexus detection is best-effort; vital point system is primary mechanism
        const techniqueId = (result.technique?.id ?? "").toLowerCase();
        const isSolarPlexusArea = 
          techniqueId.includes("solar") ||
          techniqueId.includes("myeongchi");
        updatedDefender = applyBreathingDisruptionFromTorsoDamage(
          updatedDefender,
          result.damage,
          isSolarPlexusArea,
          Date.now(),
        );
      }
    }
 
    return { updatedAttacker, updatedDefender };
  }
 
  /**
   * Determines if a hit caused head trauma (affects consciousness).
   *
   * @param result - Combat result
   * @param category - Vital point category
   * @returns True if hit should affect consciousness
   */
  private isHeadTrauma(
    result: CombatResult,
    category?: VitalPointCategory,
  ): boolean {
    return isHeadTraumaHit(result, category);
  }
 
  /**
   * Extracts vital point category from combat result.
   *
   * @param result - Combat result
   * @returns Vital point category if available
   */
  private getVitalPointCategory(
    result: CombatResult,
  ): VitalPointCategory | undefined {
    return extractVitalPointCategory(result);
  }
 
  /**
   * Extracts vital point severity from combat result.
   *
   * @param result - Combat result
   * @returns Vital point severity if critical hit
   */
  private getVitalPointSeverity(
    result: CombatResult,
  ): VitalPointSeverity | undefined {
    if (result.vitalPointHit) {
      Iif (result.isCritical) {
        return VitalPointSeverity.CRITICAL;
      }
      Iif (result.damage > this.SEVERITY_MAJOR_THRESHOLD) {
        return VitalPointSeverity.MAJOR;
      }
      Eif (result.damage > this.SEVERITY_MODERATE_THRESHOLD) {
        return VitalPointSeverity.MODERATE;
      }
      return VitalPointSeverity.MINOR;
    }
    return undefined;
  }
 
  /**
   * Determines body region from combat result for balance disruption.
   *
   * Maps vital points to body regions for balance system integration.
   * Uses string matching on vital point IDs as a pragmatic heuristic since
   * VitalPoint interface doesn't currently include a bodyRegion property.
   *
   * Future improvement: Add bodyRegion: BodyRegion to VitalPoint interface
   * for more robust region mapping without string pattern matching.
   *
   * @param result - Combat result
   * @returns Body region that was struck
   * @private
   * @korean 신체부위결정
   */
  private getBodyRegionFromResult(result: CombatResult): BodyRegion {
    // If we have a targeted vital point, try to determine region
    Iif (result.targetedVitalPointId) {
      const vitalPoint = this.vitalPointSystem.getVitalPointById(
        result.targetedVitalPointId,
      );
 
      if (vitalPoint) {
        const pointId = vitalPoint.id.toLowerCase();
 
        // Check for leg/lower body targets
        if (
          pointId.includes("leg") ||
          pointId.includes("knee") ||
          pointId.includes("ankle") ||
          pointId.includes("thigh")
        ) {
          return BodyRegion.LEFT_LEG; // Generic leg for balance disruption
        }
 
        // Check for head targets
        if (
          pointId.includes("head") ||
          pointId.includes("temple") ||
          pointId.includes("jaw") ||
          pointId.includes("nose")
        ) {
          return BodyRegion.HEAD;
        }
 
        // Check for arm targets
        if (
          pointId.includes("arm") ||
          pointId.includes("elbow") ||
          pointId.includes("wrist") ||
          pointId.includes("shoulder")
        ) {
          return BodyRegion.LEFT_ARM;
        }
      }
    }
 
    // Default to torso for general strikes
    return BodyRegion.TORSO;
  }
 
  /**
   * Updates player states for recovery (pain dissipation, consciousness recovery, balance recovery).
   * Call this regularly in game loop.
   *
   * @param player - Player to update
   * @param deltaTime - Time elapsed since last update (ms)
   * @returns Updated player state
   */
  applyRecovery(player: PlayerState, deltaTime: number): PlayerState {
    let updatedPlayer = player;
 
    // Apply pain recovery
    updatedPlayer = this.painSystem.applyDissipation(updatedPlayer, deltaTime);
 
    // Apply consciousness recovery (only if enough time since head trauma)
    const lastTrauma = this.lastHeadTraumaTime.get(player.id);
    updatedPlayer = this.consciousnessSystem.applyRecovery(
      updatedPlayer,
      deltaTime,
      lastTrauma,
    );
 
    // Apply balance recovery
    updatedPlayer = this.balanceSystem.applyRecovery(updatedPlayer, deltaTime);
 
    // Clean up expired shock pain effects
    const shockEffect = this.shockPainEffects.get(player.id);
    if (shockEffect) {
      const elapsed = Date.now() - shockEffect.startTime;
      Iif (elapsed >= shockEffect.duration) {
        this.shockPainEffects.delete(player.id);
      }
    }
 
    return updatedPlayer;
  }
 
  /**
   * Static version for backwards compatibility with comprehensive effect application
   * Enhanced with Pain Response and Consciousness System integration
   * Updated to apply damage to body parts for 8-body-part health visualization
   */
  static applyCombatResult(
    result: CombatResult,
    attacker: PlayerState,
    defender: PlayerState,
  ): { updatedAttacker: PlayerState; updatedDefender: PlayerState } {
    // Apply damage and effects
    let updatedDefender = defender;
    let updatedAttacker = attacker;
 
    if (result.hit) {
      // Determine body region from technique or use random distribution
      const bodyRegion = CombatSystem.getBodyRegionFromTechnique(
        result.technique,
      );
 
      // Apply damage to body parts (this also updates aggregate health)
      updatedDefender = applyDamageToBodyParts(
        defender,
        result.damage,
        bodyRegion,
      );
 
      // Record injury for trauma visualization (외상 시각화)
      // Use per-player injury tracking to prevent mixing injuries between characters
      // Automatically tracks bruising, cuts, and blood effects based on damage type
      // Records injury even without specific technique (defaults to BRUISE)
      if (result.damage > 0) {
        const defenderInjuryIntegration = playerInjuryManager.getIntegrationForPlayer(defender.id);
        defenderInjuryIntegration.recordCombatDamage({
          damage: result.damage,
          bodyRegion,
          damageType: (result.technique?.damageType as DamageType) || undefined,
        });
      }
 
      // Update tracking stats (applyDamageToBodyParts already sets health)
      updatedDefender = {
        ...updatedDefender,
        totalDamageReceived:
          updatedDefender.totalDamageReceived + result.damage,
        hitsTaken: updatedDefender.hitsTaken + 1,
      };
 
      // Apply status effects from vital point hit
      if (result.effects && result.effects.length > 0) {
        updatedDefender = addEffectsToPlayer(updatedDefender, result.effects);
      }
 
      // Track vital point hits
      if (result.vitalPointHit) {
        updatedAttacker = {
          ...updatedAttacker,
          vitalPointHits: attacker.vitalPointHits + 1,
        };
      }
 
      // Track perfect strikes (high accuracy)
      if (result.isCritical) {
        updatedAttacker = {
          ...updatedAttacker,
          perfectStrikes: attacker.perfectStrikes + 1,
        };
      }
    }
 
    // Apply technique costs to attacker
    updatedAttacker = {
      ...updatedAttacker,
      ki: Math.max(0, attacker.ki - 5),
      stamina: Math.max(0, attacker.stamina - 10),
      totalDamageDealt:
        attacker.totalDamageDealt + (result.hit ? result.damage : 0),
      hitsLanded: attacker.hitsLanded + (result.hit ? 1 : 0),
    };
 
    return { updatedAttacker, updatedDefender };
  }
 
  /**
   * Determine body region from technique name or type
   *
   * **Korean**: 기술에서 신체 영역 결정
   *
   * @param technique - The technique used in the attack
   * @returns Body region to apply damage to
   */
  private static getBodyRegionFromTechnique(
    technique?: KoreanTechnique,
  ): BodyRegion {
    if (!technique) {
      // Default to torso if no technique specified
      return BodyRegion.TORSO;
    }
 
    const techniqueName = (
      technique.name?.english ||
      technique.englishName ||
      ""
    ).toLowerCase();
    const techniqueId = technique.id?.toLowerCase() || "";
 
    // Head/face targeting techniques
    if (
      techniqueName.includes("head") ||
      techniqueName.includes("temple") ||
      techniqueName.includes("jaw") ||
      techniqueName.includes("face") ||
      techniqueId.includes("head") ||
      techniqueId.includes("skull")
    ) {
      return BodyRegion.HEAD;
    }
 
    // Neck targeting techniques
    Iif (
      techniqueName.includes("neck") ||
      techniqueName.includes("throat") ||
      techniqueName.includes("choke") ||
      techniqueId.includes("neck")
    ) {
      return BodyRegion.NECK;
    }
 
    // Leg targeting techniques
    Iif (
      techniqueName.includes("kick") ||
      techniqueName.includes("sweep") ||
      techniqueName.includes("leg") ||
      techniqueName.includes("knee") ||
      techniqueId.includes("kick") ||
      techniqueId.includes("leg")
    ) {
      // Randomly choose left or right leg
      return Math.random() < 0.5 ? BodyRegion.LEFT_LEG : BodyRegion.RIGHT_LEG;
    }
 
    // Arm targeting techniques
    Iif (
      techniqueName.includes("arm") ||
      techniqueName.includes("shoulder") ||
      techniqueName.includes("elbow") ||
      techniqueId.includes("arm")
    ) {
      // Randomly choose left or right arm
      return Math.random() < 0.5 ? BodyRegion.LEFT_ARM : BodyRegion.RIGHT_ARM;
    }
 
    // Punch/strike techniques typically target torso
    if (
      techniqueName.includes("punch") ||
      techniqueName.includes("strike") ||
      techniqueName.includes("jab") ||
      techniqueName.includes("cross") ||
      techniqueName.includes("hook") ||
      techniqueName.includes("uppercut")
    ) {
      // Mix of torso and head for punches
      return Math.random() < 0.7 ? BodyRegion.TORSO : BodyRegion.HEAD;
    }
 
    // Body/core targeting techniques
    Iif (
      techniqueName.includes("body") ||
      techniqueName.includes("solar") ||
      techniqueName.includes("liver") ||
      techniqueName.includes("ribs") ||
      techniqueName.includes("abdomen") ||
      techniqueId.includes("torso") ||
      techniqueId.includes("core")
    ) {
      return BodyRegion.TORSO;
    }
 
    // Default to torso for unmatched techniques
    return BodyRegion.TORSO;
  }
 
  /**
   * Fix: Add missing getAvailableTechniques method required by interface
   */
  getAvailableTechniques(player: PlayerState): readonly KoreanTechnique[] {
    const allTechniques = TRIGRAM_TECHNIQUES[player.currentStance] ?? [];
 
    // Filter techniques based on available resources using canExecuteTechnique
    return allTechniques.filter((technique) =>
      this.canExecuteTechnique(player, technique as KoreanTechnique),
    ) as readonly KoreanTechnique[];
  }
 
  /**
   * Check if attacker can execute technique
   */
  private canExecuteTechnique(
    player: PlayerState,
    technique: KoreanTechnique,
  ): boolean {
    return (
      player.ki >= technique.kiCost &&
      player.stamina >= technique.staminaCost &&
      player.currentStance === technique.stance &&
      !player.isStunned
    );
  }
 
  /**
   * Static methods for backwards compatibility
   */
  static resolveAttack(
    attacker: PlayerState,
    defender: PlayerState,
    technique: KoreanTechnique,
  ): CombatResult {
    const instance = new CombatSystem();
    return instance.executeAttack(attacker, defender, technique);
  }
 
  /**
   * Check if a player is defeated
   */
  isPlayerDefeated(player: PlayerState): boolean {
    return player.health <= 0 || player.consciousness <= 0;
  }
 
  /**
   * Update player state over time with effect management
   */
  updatePlayerState(player: PlayerState, deltaTime: number): PlayerState {
    let updatedPlayer = { ...player };
 
    // Remove expired effects first
    updatedPlayer = removeExpiredEffects(updatedPlayer);
 
    // Get effect modifiers for resource regeneration
    const effectModifiers = getEffectModifiers(updatedPlayer);
 
    // Apply natural regeneration with effect modifiers
    const regenRate = deltaTime / 1000; // Convert to seconds
 
    // Ki regeneration (slower during combat) - affected by effects
    if (updatedPlayer.ki < updatedPlayer.maxKi) {
      updatedPlayer.ki = Math.min(
        updatedPlayer.maxKi,
        updatedPlayer.ki + regenRate * 2 * effectModifiers.kiRegen,
      );
    }
 
    // Stamina regeneration - affected by effects and breathing disruption
    // Uses BASE_STAMINA_REGEN_RATE constant for better gameplay
    // Allows players to move around and attack frequently without running out
    // 체력 재생 속도 - 더 활발한 전투를 위해
    if (updatedPlayer.stamina < updatedPlayer.maxStamina) {
      const baseStaminaRegen = regenRate * BASE_STAMINA_REGEN_RATE * effectModifiers.staminaRegen;
      // Apply breathing disruption system's stamina regen modifier
      const modifiedStaminaRegen =
        BreathingDisruptionSystem.calculateStaminaRegen(
          updatedPlayer,
          baseStaminaRegen,
        );
      updatedPlayer.stamina = Math.min(
        updatedPlayer.maxStamina,
        updatedPlayer.stamina + modifiedStaminaRegen,
      );
    }
 
    // Health regeneration (very slow)
    if (
      updatedPlayer.health < updatedPlayer.maxHealth &&
      updatedPlayer.health > 0
    ) {
      updatedPlayer.health = Math.min(
        updatedPlayer.maxHealth,
        updatedPlayer.health + regenRate * 0.5,
      );
    }
 
    // Update breathing disruption effects (gradual recovery if torso health > 50%)
    updatedPlayer = updateBreathingDisruption(
      updatedPlayer,
      deltaTime,
      Date.now(),
    );
 
    // Clear temporary combat states
    const currentTime = Date.now();
    Iif (
      updatedPlayer.lastActionTime &&
      currentTime - updatedPlayer.lastActionTime > updatedPlayer.recoveryTime
    ) {
      updatedPlayer.isStunned = false;
      updatedPlayer.isCountering = false;
    }
 
    return updatedPlayer;
  }
 
  /**
   * Get combat statistics
   */
  getCombatStatistics(player: PlayerState): {
    healthPercent: number;
    kiPercent: number;
    staminaPercent: number;
    balancePercent: number;
  } {
    return {
      healthPercent: (player.health / player.maxHealth) * 100,
      kiPercent: (player.ki / player.maxKi) * 100,
      staminaPercent: (player.stamina / player.maxStamina) * 100,
      balancePercent: player.balance,
    };
  }
 
  /**
   * Fix: Integrate processVitalPointHit into the combat system with archetype parameters
   */
  private processVitalPointHit(
    vitalPointId: string,
    _baseDamage: number, // Unused but kept for interface compatibility
    attacker: PlayerState,
    defender: PlayerState,
  ): VitalPointHitResult {
    const vitalPoint = this.vitalPointSystem.getVitalPointById(vitalPointId);
 
    if (!vitalPoint) {
      return {
        hit: false,
        damage: 0,
        effects: [],
        severity: VitalPointSeverity.MINOR,
      };
    }
 
    // Use VitalPointSystem's processHit with full archetype support
    return this.vitalPointSystem.processHit(
      vitalPoint.position, // Use vital point position for hit calculation
      { width: 10, height: 10 }, // Standard hit box
      vitalPointId, // Targeted vital point
      undefined, // Use current hour from system
      attacker.archetype, // Attacker archetype for offensive modifiers
      defender.archetype, // Defender archetype for defensive modifiers
    );
  }
 
  /**
   * Process defensive action and determine animation type.
   *
   * Determines the appropriate defensive animation based on:
   * - Defender's balance and stamina (defensive power)
   * - Attacker's technique power
   * - Combat readiness state
   *
   * **Korean**: 방어 행동 처리
   *
   * @param defender - Defending player state
   * @param attacker - Attacking player state (unused but kept for future enhancements)
   * @param attackPower - Power of the incoming attack
   * @returns Defensive animation type to play (parry_deflect, block_success, or guard_break)
   *
   * @example
   * ```typescript
   * const animType = combatSystem.processDefensiveAction(
   *   defender,
   *   attacker,
   *   technique.damage
   * );
   * // Returns: 'parry_deflect', 'block_success', or 'guard_break'
   * ```
   *
   * @public
   * @korean 방어행동처리
   */
  public processDefensiveAction(
    defender: PlayerState,
    _attacker: PlayerState,
    attackPower: number,
  ): Exclude<DefensiveAnimationType, "guard_recovery"> {
    // Guard Break: Check balance threshold first (highest priority condition)
    if (defender.balance < 30) {
      return "guard_break";
    }
 
    // Calculate defensive power based on balance and stamina
    // Balance represents physical stability (0-100)
    // Stamina represents energy reserves (0-100)
    const balanceFactor = defender.balance / 100;
    const staminaFactor = defender.stamina / 100;
 
    // Apply defensive modifiers from effects
    const effectModifiers = getEffectModifiers(defender);
    const defenseMultiplier = effectModifiers.defense;
 
    // Defense stat provides moderate bonus (normalized to 0.5-1.5 range for typical 5-15 defense)
    const defenseBonus = Math.max(0.5, Math.min(1.5, defender.defense / 10));
 
    // Calculate final defensive power
    const defensePower =
      balanceFactor * staminaFactor * 100 * defenseMultiplier * defenseBonus;
 
    // Determine defensive outcome based on power ratio
    // Parry: Strong defense (1.8x attack power or more) - Perfect deflection
    if (defensePower >= attackPower * 1.8) {
      return "parry_deflect";
    }
    // Block Success: Adequate defense (1.0x to 1.8x attack power) - Absorb impact
    else if (defensePower >= attackPower) {
      return "block_success";
    }
    // Guard Break: Defense insufficient against powerful attack (<60% of attack power)
    else if (defensePower < attackPower * 0.6) {
      return "guard_break";
    }
    // Block Success: Marginal defense (60-100% of attack power) - barely hold
    else E{
      return "block_success";
    }
  }
 
  /**
   * Execute attack with technique
   */
  protected executeAttack(
    attacker: PlayerState,
    defender: PlayerState,
    technique: KoreanTechnique,
  ): CombatResult {
    const hitRoll = Math.random();
    const accuracy = technique.accuracy || 0.8;
    const hit = hitRoll <= accuracy;
 
    if (!hit) {
      return {
        hit: false,
        damage: 0,
        criticalHit: false,
        vitalPointHit: false,
        effects: [],
        timestamp: Date.now(),
        technique,
        attacker,
        defender,
        success: false,
        isCritical: false,
        isBlocked: false,
      };
    }
 
    // Calculate damage using the interface method
    const vitalPointHit: VitalPointHitResult = {
      hit: false,
      damage: 0,
      effects: [],
      severity: VitalPointSeverity.MINOR, // Use the enum directly
    };
 
    const damageResult = this.calculateDamage(
      technique,
      attacker,
      defender,
      vitalPointHit,
    );
 
    return {
      hit: true,
      damage: damageResult.totalDamage,
      criticalHit: Math.random() < (technique.critChance || 0.1),
      vitalPointHit: false,
      effects: damageResult.effectsApplied,
      timestamp: Date.now(),
      technique,
      attacker,
      defender,
      success: true,
      isCritical: false,
      isBlocked: false,
    };
  }
 
  /**
   * Fix: Add missing calculateDamage method required by interface
   */
  calculateDamage(
    technique: KoreanTechnique,
    attacker: PlayerState,
    defender: PlayerState,
    hitResult: VitalPointHitResult,
  ): {
    baseDamage: number;
    modifierDamage: number;
    totalDamage: number;
    effectsApplied: readonly StatusEffect[];
    finalDefenderState?: Partial<PlayerState>;
  } {
    // Calculate base damage from technique
    const baseDamage = technique.damage || 15;
 
    // Apply attacker modifiers
    const attackerBonus = attacker.attackPower * 0.1;
 
    // Apply vital point modifiers if hit
    let vitalPointMultiplier = 1.0;
    if (hitResult.hit && hitResult.vitalPointHit) {
      // Use the correct property name
      const severityMultipliers: Record<VitalPointSeverity, number> = {
        [VitalPointSeverity.MINOR]: 1.1,
        [VitalPointSeverity.MODERATE]: 1.3,
        [VitalPointSeverity.MAJOR]: 1.6,
        [VitalPointSeverity.CRITICAL]: 2.0,
        [VitalPointSeverity.LETHAL]: 3.0,
      };
 
      // Use the severity property directly
      vitalPointMultiplier = severityMultipliers[hitResult.severity] ?? 1.0;
    }
 
    // Calculate total modifier damage
    const modifierDamage = attackerBonus * vitalPointMultiplier;
 
    // Apply defense reduction
    const defenseReduction = defender.defense * 0.05;
    const totalDamage = Math.max(
      1,
      baseDamage + modifierDamage - defenseReduction,
    );
 
    // Combine effects from technique and vital point hit
    const effectsApplied = [...technique.effects, ...hitResult.effects];
 
    return {
      baseDamage,
      modifierDamage,
      totalDamage: Math.floor(totalDamage),
      effectsApplied,
      finalDefenderState: {
        health: Math.max(0, defender.health - totalDamage),
      },
    };
  }
}
 
/**
 * Creates a standardized CombatResult with all required fields
 * Ensures both 'critical' and 'criticalHit' are present for API compatibility
 */
export function createCombatResult(
  partialResult: Partial<CombatResult>,
): CombatResult {
  // Set default values
  const result: CombatResult = {
    success: partialResult.success ?? false,
    damage: partialResult.damage ?? 0,
    isCritical: partialResult.isCritical ?? partialResult.criticalHit ?? false,
    hit: partialResult.hit ?? partialResult.success ?? false,
    isBlocked: partialResult.isBlocked ?? false,
    vitalPointHit: partialResult.vitalPointHit ?? false,
    effects: partialResult.effects ?? [],
    attacker: partialResult.attacker,
    defender: partialResult.defender,
    technique: partialResult.technique,
    // Always set criticalHit to match critical for consistency
    criticalHit: partialResult.isCritical ?? partialResult.criticalHit ?? false,
    timestamp: Date.now(),
  };
 
  return result;
}
 
export default CombatSystem;