All files / components/screens/combat/hooks useAICombat.ts

70.57% Statements 271/384
43.24% Branches 128/296
84.21% Functions 48/57
70.13% Lines 263/375

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                                                                                                                                                            3x 3x                                                                         15x         15x       15x 107x   107x     107x 107x                                                     107x   107x   107x     15x 15x 28x   42x       15x 51x 51x   51x 51x   51x 51x   51x 51x   51x                                                 4x       4x   4x 280x     4x               4x   4x 148x       4x   4x 420x     420x       420x       420x         420x 420x   420x     4x                               840x   840x                                             840x                                           24x 24x 24x     24x   24x                                                                                                                       4x 4x   4x   4x 4x       4x   4x 4x 4x 4x 4x       4x                                         20x 6x     14x 20x 20x                                             4x       4x 20x       4x   4x         20x   4x 4x 20x 20x 20x                                                                             26x   26x 28x 28x 28x 28x                                   100x                                                             4x 4x                                                                                 15x                                                                                           15x               15x     15x   15x 11x     11x     15x 15x 11x 11x   171x           11x       11x   11x     15x 4x 24x     4x   4x 4x         4x 4x   4x           4x         4x                 11x                                                                                                                                                                                                                                                                                                                                                     195x   195x 195x   195x 114x       195x 195x 114x 114x 88x 88x       195x 89x   195x 89x   195x 195x 195x   195x 89x 89x                         195x 195x 195x 195x 195x 195x 195x 195x   195x             195x   195x 89x 1756x     195x       195x   195x 123x 81x 81x 81x 81x   81x         81x             81x         195x 124x 47x     77x               195x 124x 47x       77x   77x 44x   44x 44x 44x   44x                 44x 44x       77x   77x 77x 77x         195x 89x                   195x             3749x                     195x                                 195x 3747x 3747x 3747x   3747x       3747x   3747x   3747x                                                             195x 195x 47x     148x 18631x   18631x 14884x     3747x   3747x   3747x           3747x 3747x                 3747x   3747x 3747x 3747x       3747x     4x               4x 4x 4x   4x 4x           4x         4x         4x         4x 4x     4x       11x               11x 11x 11x   11x                                           11x       11x     1x 1x     1x                     1x 1x   1x                         8x 8x 8x 8x     743x 743x 743x 743x     10x 10x 10x 10x                                 2970x 2970x 2970x     3747x                                 3747x       18631x   18631x 3747x 3747x 4x 4x         3747x                         18631x     148x                                         195x                    
/**
 * useAICombat Hook - AI Combat System Integration
 *
 * Custom hook for AI combat behavior with strategic decision-making.
 *
 * Manages AI opponent behavior including:
 * - Strategic decision-making via DecisionTree
 * - Combo attack sequences
 * - Adaptive difficulty based on player skill
 * - Performance monitoring (<10ms target for decisions)
 *
 * Side effects:
 * - Manages internal state for AI actions and aggression
 * - Sets up intervals/timers for AI action scheduling
 * - Updates state in response to combat events and round status
 *
 * @param config Configuration object for AI combat behavior.
 * @param config.player The AI-controlled player state.
 * @param config.opponent The opponent player state.
 * @param config.personality The AI's personality archetype.
 * @param config.adaptiveDifficulty Adaptive difficulty system instance.
 * @param config.arenaBounds Arena boundaries for movement validation.
 * @param config.roundStarted Whether the combat round has started.
 * @param config.roundEnded Whether the combat round has ended.
 * @param config.isPaused Whether the game is paused.
 * @param config.onExecuteAction Callback to execute AI actions.
 * @param config.onStanceChange Callback to handle stance changes.
 *
 * @returns AI combat state and control functions
 *
 * @example
 * ```typescript
 * const { aiState } = useAICombat({
 *   player: aiPlayer,
 *   opponent: humanPlayer,
 *   personality: AI_PERSONALITIES.AGGRESSIVE_STRIKER,
 *   adaptiveDifficulty,
 *   arenaBounds,
 *   roundStarted,
 *   roundEnded,
 *   isPaused,
 *   onExecuteAction: handleAction,
 *   onStanceChange: handleStanceChange,
 * });
 * ```
 */
 
import { getArchetypePhysicalAttributes } from "@/data/archetypePhysicalAttributes";
import {
  AdaptiveDifficulty,
  AIActionType,
  AIComboSystem,
  AIDecisionTree,
  AIPersonality,
  CombatContext,
  DifficultyParameters,
  getArchetypeBehavior,
  getNextComboTechnique,
  getSignatureMove,
  interpolateDifficultyParameters,
  shouldExecuteSignatureMove,
} from "@/systems/ai";
import { physicalReachCalculator } from "@/systems/physics";
import { PlayerState } from "@/systems/player";
import { KoreanTechniquesSystem } from "@/systems/trigram/KoreanTechniques";
import { KOREAN_VITAL_POINTS } from "@/systems/vitalpoint/KoreanVitalPoints";
import { KoreanTechnique } from "@/systems/vitalpoint/types";
import {
  CombatAttackType,
  DamageType,
  PlayerArchetype,
  Position,
  TrigramStance,
} from "@/types";
import { STANCE_REACH_MODIFIERS } from "@/types/physics";
import { getBalanceState } from "@/utils/player3DHelpers";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
 
const AI_DECISION_THRESHOLD_MS = 10; // Threshold for slow decision warnings
const WARNING_THROTTLE_MS = 5000; // Throttle performance warnings to every 5 seconds
 
/**
 * Technique range system (physics-first: meters)
 * All distances and ranges are in meters - no pixel conversions for game logic
 *
 * Each technique has a reachConfig with baseExtension multiplier
 * Applied to archetype's limb length: reach = (limbLength/100) × baseExtension × stanceModifier
 *
 * @korean 기술 범위 시스템 (물리 우선: 미터)
 */
 
/**
 * Get viable techniques based on distance, stance, and stamina
 *
 * Filters techniques that:
 * - Match current stance
 * - Are within effective range of opponent
 * - Have sufficient stamina to execute
 * - Applies selection bias against recently used techniques (avoid >70% repetition)
 *
 * @korean 거리, 자세, 체력에 따른 실행 가능한 기술 선택
 *
 * @param distance - Distance to opponent in meters (physics-first)
 * @param stance - Current trigram stance
 * @param stamina - Available stamina
 * @param archetype - Player archetype for specialized techniques
 * @param recentTechniques - Array of recently used technique IDs (for variation)
 * @returns Array of viable techniques sorted by effectiveness with variation bias
 */
function getViableTechniques(
  distance: number,
  stance: TrigramStance,
  stamina: number,
  archetype: PlayerState["archetype"],
  recentTechniques: string[] = [],
): readonly KoreanTechnique[] {
  const stanceTechniques = KoreanTechniquesSystem.getAllAvailableTechniques(
    stance,
    archetype,
  );
 
  Iif (stanceTechniques.length === 0) {
    return [];
  }
 
  const viableTechniques = stanceTechniques.filter((tech) => {
    const physicalAttributes = getArchetypePhysicalAttributes(archetype);
 
    const animType = tech.animationType;
    let maxReach: number;
 
    if (animType) {
      maxReach = physicalReachCalculator.calculateMaxReach(
        physicalAttributes,
        animType,
        stance,
      );
    } else E{
      const limbLength =
        tech.reachConfig.bodyPart === "leg"
          ? physicalAttributes.legLength
          : physicalAttributes.armLength;
 
      let bodyPivot: number;
      if (tech.reachConfig.bodyPart === "leg") {
        bodyPivot = 0.25; // meters for kicks
      } else {
        const shoulderOffset = physicalAttributes.shoulderWidth / 2 / 100;
        const torsoRotation = 0.1;
        bodyPivot = shoulderOffset + torsoRotation;
      }
 
      const stanceModifier = STANCE_REACH_MODIFIERS[stance];
      maxReach =
        (limbLength / 100 + bodyPivot) *
        tech.reachConfig.baseExtension *
        stanceModifier;
    }
 
    const inRange = distance <= maxReach;
 
    const hasStamina = stamina >= tech.staminaCost;
 
    return inRange && hasStamina;
  });
 
  const recentUseCounts = new Map<string, number>();
  for (const tech of viableTechniques) {
    recentUseCounts.set(
      tech.id,
      recentTechniques.filter((id) => id === tech.id).length,
    );
  }
 
  return viableTechniques.sort((a, b) => {
    const baseEffectivenessA = (a.damage ?? 0) * (a.accuracy ?? 0.8);
    const baseEffectivenessB = (b.damage ?? 0) * (b.accuracy ?? 0.8);
 
    const recentUsesA = recentUseCounts.get(a.id) ?? 0;
    const recentUsesB = recentUseCounts.get(b.id) ?? 0;
 
    const penaltyA = Math.min(0.6, recentUsesA * 0.2);
    const penaltyB = Math.min(0.6, recentUsesB * 0.2);
 
    const finalEffectivenessA = baseEffectivenessA * (1 - penaltyA);
    const finalEffectivenessB = baseEffectivenessB * (1 - penaltyB);
 
    return finalEffectivenessB - finalEffectivenessA;
  });
}
 
/**
 * Select optimal vital point for attack based on stance compatibility and archetype priority
 *
 * Prioritizes vital points by:
 * 1. Archetype vital target priority (health/pain/consciousness/balanced)
 * 2. Stance compatibility (must be in effectiveStances array)
 * 3. Base damage threshold (>25 damage preferred)
 * 4. Targeting difficulty vs AI skill level
 *
 * @korean 자세 효과 및 원형 우선순위에 따른 최적 급소 선택
 *
 * @param stance - Current trigram stance
 * @param difficultyLevel - AI difficulty level (0.0-1.0)
 * @param archetype - Player archetype for priority targeting
 * @returns Vital point ID or null if no suitable target
 */
function selectOptimalVitalPoint(
  stance: TrigramStance,
  difficultyLevel: number,
  archetype: PlayerState["archetype"],
): string | null {
  Iif (KOREAN_VITAL_POINTS.length === 0) {
    return null;
  }
 
  const behavior = getArchetypeBehavior(archetype);
 
  const effectivePoints = KOREAN_VITAL_POINTS.filter((point) =>
    point.effectiveStances?.includes(stance),
  );
 
  Iif (effectivePoints.length === 0) {
    const fallbackPoint =
      KOREAN_VITAL_POINTS[
        Math.floor(Math.random() * KOREAN_VITAL_POINTS.length)
      ];
    return fallbackPoint?.id ?? null;
  }
 
  const HIGH_DAMAGE_THRESHOLD = 25;
 
  const highDamagePoints = effectivePoints.filter(
    (point) => (point.baseDamage ?? 0) > HIGH_DAMAGE_THRESHOLD,
  );
 
  const targetPoints =
    highDamagePoints.length > 0 ? highDamagePoints : effectivePoints;
 
  const sortedPoints = [...targetPoints].sort((a, b) => {
    const baseSuitabilityA =
      (a.baseDamage ?? 0) *
      (1 - Math.abs(difficultyLevel - a.targetingDifficulty));
    const baseSuitabilityB =
      (b.baseDamage ?? 0) *
      (1 - Math.abs(difficultyLevel - b.targetingDifficulty));
 
    const priorityMultiplierA = getVitalPointPriorityScore(
      a,
      behavior.vitalTargetPriority,
    );
    const priorityMultiplierB = getVitalPointPriorityScore(
      b,
      behavior.vitalTargetPriority,
    );
 
    const finalSuitabilityA = baseSuitabilityA * priorityMultiplierA;
    const finalSuitabilityB = baseSuitabilityB * priorityMultiplierB;
 
    return finalSuitabilityB - finalSuitabilityA;
  });
 
  return sortedPoints[0]?.id ?? null;
}
 
/**
 * Calculate priority score for vital point based on archetype targeting preference
 *
 * @korean 원형 타격 우선순위 점수 계산
 *
 * @param vitalPoint - Vital point to score
 * @param priority - Archetype vital target priority
 * @returns Priority multiplier (1.0 = neutral, >1.0 = preferred, <1.0 = deprioritized)
 */
function getVitalPointPriorityScore(
  vitalPoint: (typeof KOREAN_VITAL_POINTS)[0],
  priority: import("@/systems/ai/AIPersonality").VitalTargetPriority,
): number {
  const effects = vitalPoint.effects ?? [];
 
  switch (priority) {
    case "health":
      return (vitalPoint.baseDamage ?? 0) > 30 ? 1.5 : 1.0;
 
    case "pain":
      const hasPainEffect = effects.some(
        (e) =>
          String(e).toLowerCase().includes("pain") ||
          String(e).toLowerCase().includes("disorientation"),
      );
      return hasPainEffect ? 1.5 : 1.0;
 
    case "consciousness":
      const hasConsciousnessEffect = effects.some(
        (e) =>
          String(e).toLowerCase().includes("unconscious") ||
          String(e).toLowerCase().includes("stun") ||
          String(e).toLowerCase().includes("breathless"),
      );
      return hasConsciousnessEffect ? 1.5 : 1.0;
 
    case "balanced":
    default:
      return 1.0;
  }
}
 
/**
 * Check if a technique is a signature move for the given archetype
 *
 * Signature techniques are identified by:
 * - Damage type and attack type matching archetype preferences
 * - Ki/Stamina costs indicating advanced techniques
 * - Specific technique characteristics (e.g., nerve strikes for Amsalja)
 *
 * @korean 원형 대표 기술 확인
 *
 * @param technique - Technique to check
 * @param archetype - Player archetype
 * @returns True if technique is signature for the archetype
 */
function isSignatureTechnique(
  technique: KoreanTechnique,
  archetype: PlayerState["archetype"],
): boolean {
  const damageType = technique.damageType;
  const attackType = technique.type;
  const isAdvanced =
    (technique.kiCost ?? 0) >= 10 || (technique.staminaCost ?? 0) >= 15;
 
  switch (archetype) {
    case PlayerArchetype.MUSA:
      return (
        damageType === DamageType.JOINT ||
        damageType === DamageType.CRUSHING ||
        (damageType === DamageType.BLUNT && isAdvanced)
      );
 
    case PlayerArchetype.AMSALJA:
      return (
        damageType === DamageType.NERVE ||
        damageType === DamageType.PRESSURE ||
        attackType === CombatAttackType.NERVE_STRIKE ||
        attackType === CombatAttackType.PRESSURE_POINT
      );
 
    case PlayerArchetype.HACKER:
      return (
        damageType === DamageType.INTERNAL ||
        damageType === DamageType.NERVE ||
        (isAdvanced && (technique.accuracy ?? 0) >= 0.8) // High accuracy represents calculation
      );
 
    case PlayerArchetype.JEONGBO_YOWON:
      return (
        damageType === DamageType.PRESSURE ||
        damageType === DamageType.JOINT ||
        attackType === CombatAttackType.GRAPPLE
      );
 
    case PlayerArchetype.JOJIK_POKRYEOKBAE:
      return (
        (technique.damage ?? 0) >= 30 || // High raw damage
        damageType === DamageType.SLASHING || // Brutal cutting
        damageType === DamageType.PIERCING // Dirty stabbing techniques
      );
 
    default:
      return false;
  }
}
 
/**
 * Update technique usage frequency and rotation queue
 *
 * Tracks technique usage for diversity enforcement:
 * 1. Updates usage frequency counter
 * 2. Adds to recent techniques queue (last 5)
 * 3. Marks as used in current match
 * 4. Resets "all used" when all 4 archetype techniques completed
 *
 * @korean 기술 사용 빈도 및 순환 큐 업데이트
 *
 * @param techniqueId - ID of technique just used
 * @param rotationQueue - Technique rotation tracking object
 * @param archetypeTechniqueIds - All technique IDs for this archetype (for reset detection)
 */
function updateTechniqueRotation(
  techniqueId: string,
  rotationQueue: TechniqueRotationQueue,
  archetypeTechniqueIds: Set<string>,
): void {
  const current = rotationQueue.frequency.get(techniqueId) ?? 0;
  rotationQueue.frequency.set(techniqueId, current + 1);
 
  rotationQueue.totalAttacks++;
 
  rotationQueue.used.push(techniqueId);
  Iif (rotationQueue.used.length > 5) {
    rotationQueue.used.shift(); // Keep only last 5
  }
 
  rotationQueue.allUsed.add(techniqueId);
 
  let allTechniquesUsed = true;
  for (const techId of archetypeTechniqueIds) {
    Eif (!rotationQueue.allUsed.has(techId)) {
      allTechniquesUsed = false;
      break;
    }
  }
 
  Iif (allTechniquesUsed) {
    rotationQueue.allUsed.clear();
  }
}
 
/**
 * Check if technique is overused (exceeds 40% threshold)
 *
 * Enforces variety by identifying techniques that have been
 * used more than 40% of total attacks.
 *
 * @korean 기술 과다 사용 확인 (40% 임계값)
 *
 * @param techniqueId - Technique ID to check
 * @param rotationQueue - Technique rotation tracking object
 * @returns True if technique exceeds 40% usage threshold
 */
function isOverused(
  techniqueId: string,
  rotationQueue: TechniqueRotationQueue,
): boolean {
  if (rotationQueue.totalAttacks === 0) {
    return false;
  }
 
  const uses = rotationQueue.frequency.get(techniqueId) ?? 0;
  const percentage = uses / rotationQueue.totalAttacks;
  return percentage > 0.4; // >40% threshold
}
 
/**
 * Select technique with rotation bias for diversity
 *
 * Prioritizes techniques in this order:
 * 1. Never used in this match (highest priority)
 * 2. Not used in last 5 techniques (avoid repetition)
 * 3. Any viable technique (fallback)
 *
 * Within each priority tier, selects by effectiveness (damage × accuracy).
 *
 * @korean 다양성을 위한 순환 편향 기술 선택
 *
 * @param viableTechniques - Techniques that are viable (range, stamina, stance)
 * @param rotationQueue - Technique rotation tracking object
 * @returns Best technique with rotation bias applied
 */
function selectTechniqueWithRotation(
  viableTechniques: readonly KoreanTechnique[],
  rotationQueue: TechniqueRotationQueue,
): KoreanTechnique | undefined {
  Iif (viableTechniques.length === 0) {
    return undefined;
  }
 
  const balancedTechniques = viableTechniques.filter(
    (t) => !isOverused(t.id, rotationQueue),
  );
 
  const candidates =
    balancedTechniques.length > 0 ? balancedTechniques : viableTechniques;
 
  Iif (balancedTechniques.length === 0 && rotationQueue.totalAttacks > 0) {
    rotationQueue.frequency.clear();
    rotationQueue.totalAttacks = 0;
  }
 
  const neverUsed = candidates.filter((t) => !rotationQueue.allUsed.has(t.id));
 
  Eif (neverUsed.length > 0) {
    return [...neverUsed].sort((a, b) => {
      const effA = (a.damage ?? 0) * (a.accuracy ?? 0.8);
      const effB = (b.damage ?? 0) * (b.accuracy ?? 0.8);
      return effB - effA;
    })[0];
  }
 
  const unusedRecently = candidates.filter(
    (t) => !rotationQueue.used.includes(t.id),
  );
 
  if (unusedRecently.length > 0) {
    return [...unusedRecently].sort((a, b) => {
      const effA = (a.damage ?? 0) * (a.accuracy ?? 0.8);
      const effB = (b.damage ?? 0) * (b.accuracy ?? 0.8);
      return effB - effA;
    })[0];
  }
 
  return [...candidates].sort((a, b) => {
    const effA = (a.damage ?? 0) * (a.accuracy ?? 0.8);
    const effB = (b.damage ?? 0) * (b.accuracy ?? 0.8);
    return effB - effA;
  })[0];
}
 
/**
 * Filter techniques by cooldown availability
 *
 * Returns only techniques that are off cooldown and ready to use.
 * If all techniques are on cooldown, returns empty array.
 *
 * @korean 재사용 대기시간별 기술 필터링
 *
 * @param techniques - Techniques to filter
 * @param cooldownMap - Map of technique ID to last use timestamp
 * @returns Techniques that are off cooldown
 */
function filterByCooldown(
  techniques: readonly KoreanTechnique[],
  cooldownMap: TechniqueCooldownMap,
): readonly KoreanTechnique[] {
  const now = Date.now();
 
  return techniques.filter((t) => {
    const lastUsed = cooldownMap.get(t.id) ?? 0;
    const cooldown = (t.recoveryTime ?? 0) + (t.executionTime ?? 0); // Total cooldown time
    const timeSinceUse = now - lastUsed;
    return timeSinceUse >= cooldown;
  });
}
 
/**
 * Get all techniques for an archetype (for cross-stance usage)
 *
 * Returns all 4 techniques available to the archetype,
 * regardless of stance requirements.
 *
 * @korean 원형의 모든 기술 가져오기 (교차 자세 사용)
 *
 * @param archetype - Player archetype
 * @returns All techniques for the archetype
 */
function getAllArchetypeTechniques(
  archetype: PlayerState["archetype"],
): readonly KoreanTechnique[] {
  return KoreanTechniquesSystem.getTechniquesByArchetype(archetype);
}
 
/**
 * Apply cross-stance damage modifier to technique
 *
 * Creates a modified copy of the technique with 80% damage for cross-stance usage.
 * This prevents mutation of the original technique object.
 *
 * **Design Rationale for 80% Effectiveness:**
 * Cross-stance techniques are performed from a non-optimal stance, reducing
 * power generation and body mechanics efficiency. The 80% modifier reflects:
 * - Suboptimal weight transfer and leverage
 * - Reduced muscle engagement from non-ideal positioning
 * - Decreased stability and balance during execution
 *
 * This is consistent with Korean martial arts philosophy where proper stance
 * (자세) is fundamental to technique effectiveness. Other properties like
 * accuracy and execution time remain unchanged as the technique mechanics
 * themselves are unchanged, only the power generation is affected.
 *
 * @korean 교차 자세 피해 배율 적용 (80% 효과)
 *
 * @param technique - Original technique
 * @param isCrossStance - Whether technique is from different stance
 * @returns Modified technique with 80% damage if cross-stance, original otherwise
 */
function applyCrossStanceDamageModifier(
  technique: KoreanTechnique,
  isCrossStance: boolean,
): KoreanTechnique {
  Eif (!isCrossStance || !technique.damage) {
    return technique;
  }
 
  return {
    ...technique,
    damage: Math.floor(technique.damage * 0.8),
  };
}
 
/**
 * Helper to select technique for AI action with rotation and cooldown awareness
 *
 * Enhanced technique selection with:
 * - Technique rotation queue for diversity (prevents >70% repetition → targets <40%)
 * - Cooldown-aware filtering (prioritizes ready techniques)
 * - Cross-stance fallback (uses other techniques at 80% effectiveness)
 * - Archetype signature bias (maintains 40%+ signature technique usage)
 *
 * @korean 순환 및 재사용 대기시간을 고려한 기술 선택
 *
 * @param isSpecialTechnique - Whether to filter for high-cost special techniques
 * @param context - Current combat context
 * @param player - AI player state
 * @param adaptiveDifficulty - Adaptive difficulty system
 * @param rotationQueue - Technique rotation tracking object
 * @param cooldownMap - Technique cooldown tracking map
 * @returns Selected technique, vital point, action type, and cross-stance flag
 */
function selectTechniqueForAction(
  isSpecialTechnique: boolean,
  context: CombatContext,
  player: PlayerState,
  adaptiveDifficulty: AdaptiveDifficulty,
  rotationQueue: TechniqueRotationQueue,
  cooldownMap: TechniqueCooldownMap,
): {
  technique?: KoreanTechnique;
  vitalPoint?: string;
  actionType: string;
  isCrossStance?: boolean;
} {
  Iif (shouldExecuteSignatureMove(player.archetype, context)) {
    const signatureMoveId = getSignatureMove(player.archetype);
    const allTechniques = getAllArchetypeTechniques(player.archetype);
    const signatureTechnique = allTechniques.find(
      (t) => t.id === signatureMoveId,
    );
 
    if (signatureTechnique) {
      const now = Date.now();
      const lastUsed = cooldownMap.get(signatureMoveId) ?? 0;
 
      const techniqueCooldown =
        (signatureTechnique.recoveryTime ?? 0) +
        (signatureTechnique.executionTime ?? 0);
      const cooldownRemaining = Math.max(
        0,
        techniqueCooldown - (now - lastUsed),
      );
 
      if (
        cooldownRemaining === 0 &&
        player.stamina >= signatureTechnique.staminaCost &&
        player.ki >= signatureTechnique.kiCost
      ) {
        console.log(
          `[AI] Executing signature move: ${signatureMoveId} for ${player.archetype}`,
        );
 
        const difficultyLevel = adaptiveDifficulty.calculatePlayerSkill();
        const vitalPoint =
          selectOptimalVitalPoint(
            player.currentStance,
            difficultyLevel,
            player.archetype,
          ) ?? undefined;
 
        return {
          technique: signatureTechnique,
          vitalPoint,
          actionType: "signature_move",
          isCrossStance: signatureTechnique.stance !== player.currentStance,
        };
      }
    }
  }
 
  const viableTechniques = getViableTechniques(
    context.distanceToOpponent,
    player.currentStance,
    player.stamina,
    player.archetype,
    rotationQueue.used, // Pass recent techniques for penalty
  );
 
  const readyTechniques = filterByCooldown(viableTechniques, cooldownMap);
 
  let candidates =
    readyTechniques.length > 0 ? readyTechniques : viableTechniques;
 
  if (isSpecialTechnique) {
    const specialCandidates = candidates.filter(
      (tech) => tech.kiCost >= 10 || tech.staminaCost >= 15,
    );
    candidates = specialCandidates.length > 0 ? specialCandidates : candidates;
  }
 
  let isCrossStance = false;
  if (candidates.length === 0) {
    const allTechniques = getAllArchetypeTechniques(player.archetype);
    const crossStanceTechniques = allTechniques.filter(
      (t) =>
        t.stance !== player.currentStance &&
        context.distanceToOpponent <= (t.reachConfig?.baseExtension ?? 1.0) &&
        player.stamina >= t.staminaCost &&
        !isOverused(t.id, rotationQueue), // Apply rotation diversity to cross-stance
    );
 
    const readyCrossStance = filterByCooldown(
      crossStanceTechniques,
      cooldownMap,
    );
    candidates =
      readyCrossStance.length > 0 ? readyCrossStance : crossStanceTechniques;
    isCrossStance = candidates.length > 0;
  }
 
  if (candidates.length > 0) {
    const signatureTechniques = candidates.filter((tech) =>
      isSignatureTechnique(tech, player.archetype),
    );
 
    const useSignature = signatureTechniques.length > 0 && Math.random() < 0.6;
 
    const selectedCandidates = useSignature ? signatureTechniques : candidates;
    const technique = selectTechniqueWithRotation(
      selectedCandidates,
      rotationQueue,
    );
 
    Eif (technique) {
      const difficultyLevel = adaptiveDifficulty.calculatePlayerSkill();
      const vitalPoint =
        selectOptimalVitalPoint(
          player.currentStance,
          difficultyLevel,
          player.archetype,
        ) ?? undefined;
 
      const finalTechnique = applyCrossStanceDamageModifier(
        technique,
        isCrossStance,
      );
 
      return {
        technique: finalTechnique,
        vitalPoint,
        actionType: isSpecialTechnique ? "technique" : "attack",
        isCrossStance,
      };
    }
  }
 
  return { actionType: "idle" };
}
 
/**
 * Determine if AI should switch stance laterality based on personality and tactical situation.
 *
 * Strategic laterality decisions in Korean martial arts:
 * - **Aggressive personality**: Prefers matched stances (same laterality) for offensive advantage
 *   Matched stances expose centerlines, creating attack opportunities
 * - **Defensive personality**: Prefers mismatched stances (opposite laterality) for protection
 *   Mismatched stances naturally guard centerlines with lead hand
 * - **Health-based modifier**: Low health increases defensive preference
 *
 * @param aiLaterality - AI's current stance laterality
 * @param opponentLaterality - Opponent's stance laterality
 * @param personality - AI personality archetype
 * @param aiHealth - AI's current health (0-100)
 * @param lastSwitchTime - Timestamp of last laterality switch
 * @param currentTime - Current timestamp for cooldown check
 * @returns true if AI should switch laterality, false otherwise
 *
 * @korean AI 측면성 전환 결정
 */
function shouldAISwitchLaterality(
  aiLaterality: "left" | "right",
  opponentLaterality: "left" | "right",
  personality: AIPersonality,
  aiHealth: number,
  lastSwitchTime: number,
  currentTime: number,
): boolean {
  const LATERALITY_COOLDOWN = 3000;
  if (currentTime - lastSwitchTime < LATERALITY_COOLDOWN) {
    return false;
  }
 
  const isMatched = aiLaterality === opponentLaterality;
 
  const aggressionFactor = personality.aggressionLevel;
  const defenseFactor = personality.defensePreference;
 
  const healthFactor = aiHealth / 100;
  const effectiveAggression = aggressionFactor * Math.max(0.3, healthFactor);
  const effectiveDefense = defenseFactor * (1.2 - healthFactor * 0.2);
 
  if (effectiveAggression > 0.6 && !isMatched) {
    return Math.random() < 0.3; // 30% chance to switch to matched
  }
 
  if (effectiveDefense > 0.6 && isMatched) {
    return Math.random() < 0.25; // 25% chance to switch to mismatched
  }
 
  if (aiHealth < 30 && isMatched) {
    return Math.random() < 0.4; // 40% chance when critically low health
  }
 
  return false;
}
 
/**
 * AI state management
 */
interface AIState {
  nextAction: number;
  targetPosition: Position;
  lastActionType: string;
  consecutiveAttacks: number;
  actionCooldown: number;
  aggressionLevel: number;
  selectedTechnique?: KoreanTechnique;
  targetVitalPoint?: string;
  recentTechniques: string[]; // Track last 5 techniques for variation
}
 
/**
 * Technique rotation queue for enforcing variety
 *
 * Tracks technique usage to prevent repetitive patterns:
 * - Last 5 techniques used (for immediate variation)
 * - All techniques used in current match (for full arsenal tracking)
 * - Usage frequency per technique (for 40% threshold enforcement)
 * - Total attacks counter (for percentage calculation)
 *
 * @korean 기술 순환 큐 (다양성 강화)
 */
interface TechniqueRotationQueue {
  used: string[]; // Last 5 technique IDs (FIFO)
  allUsed: Set<string>; // All techniques used this match
  frequency: Map<string, number>; // Usage count per technique ID
  totalAttacks: number; // Total attack count for percentage calculation
}
 
/**
 * Technique cooldown tracking
 *
 * Maps technique ID to timestamp of last use
 * Used for cooldown-aware technique selection
 *
 * @korean 기술 재사용 대기시간 추적
 */
type TechniqueCooldownMap = Map<string, number>;
 
/**
 * AI combat hook configuration
 */
interface UseAICombatConfig {
  readonly player: PlayerState;
  readonly opponent: PlayerState;
  readonly personality: AIPersonality;
  readonly adaptiveDifficulty: AdaptiveDifficulty;
  readonly isPaused: boolean;
  readonly roundStarted: boolean;
  readonly roundEnded: boolean;
  readonly arenaBounds: {
    readonly x: number;
    readonly y: number;
    readonly width: number;
    readonly height: number;
    readonly scale?: number;
    readonly worldWidthMeters: number; // Arena width in meters for physics calculations
    readonly worldDepthMeters: number; // Arena depth in meters for physics calculations
  };
  readonly onExecuteAction: (
    action: string,
    targetPosition?: Position,
    selectedTechnique?: KoreanTechnique,
    targetVitalPoint?: string,
  ) => void;
  readonly onStanceChange?: (stance: TrigramStance) => void;
  readonly onLateralityChange?: () => void;
  readonly playerLaterality?: "left" | "right";
  readonly opponentLaterality?: "left" | "right";
}
 
/**
 * AI combat hook return type
 */
interface UseAICombatReturn {
  readonly aiState: AIState;
  readonly comboSystem: AIComboSystem;
  readonly decisionTree: AIDecisionTree;
  readonly adjustedPersonality: AIPersonality;
  readonly executeAIAction: (
    action: string,
    targetPosition?: Position,
    selectedTechnique?: KoreanTechnique,
    targetVitalPoint?: string,
  ) => void;
  readonly currentDifficultyParams: DifficultyParameters;
  readonly updateDifficultyTarget: (newParams: DifficultyParameters) => void;
}
 
/**
 * Custom hook for AI combat behavior
 */
export function useAICombat(config: UseAICombatConfig): UseAICombatReturn {
  const {
    player,
    opponent,
    personality,
    adaptiveDifficulty,
    isPaused,
    roundStarted,
    roundEnded,
    arenaBounds,
    onExecuteAction,
    onStanceChange,
    onLateralityChange,
    playerLaterality,
    opponentLaterality,
  } = config;
 
  const comboSystem = useMemo(() => new AIComboSystem(), []);
  const decisionTree = useMemo(() => new AIDecisionTree(), []);
 
  const adjustedPersonality = useMemo(
    () => adaptiveDifficulty.adjustAIPersonality(personality),
    [adaptiveDifficulty, personality],
  );
 
  const lastSkillLevelRef = useRef(0.5);
  useEffect(() => {
    const newSkillLevel = adaptiveDifficulty.calculatePlayerSkill();
    if (Math.abs(newSkillLevel - lastSkillLevelRef.current) > 0.01) {
      lastSkillLevelRef.current = newSkillLevel;
      decisionTree.setDifficultyLevel(newSkillLevel);
    }
  }, [adaptiveDifficulty, decisionTree]);
 
  const [currentParams, setCurrentParams] = useState<DifficultyParameters>(() =>
    adaptiveDifficulty.getDifficultyParameters(),
  );
  const [targetParams, setTargetParams] = useState<DifficultyParameters>(() =>
    adaptiveDifficulty.getDifficultyParameters(),
  );
  const startParamsRef = useRef<DifficultyParameters>(currentParams);
  const transitionStartTimeRef = useRef<number>(0);
  const transitionDurationMs = 10000; // 10 seconds for smooth transition
 
  const [aiState, setAiState] = useState<AIState>(() => {
    const now = Date.now();
    return {
      nextAction: now,
      targetPosition: player.position,
      lastActionType: "idle",
      consecutiveAttacks: 0,
      actionCooldown: 500,
      aggressionLevel: adjustedPersonality.aggressionLevel,
      selectedTechnique: undefined,
      targetVitalPoint: undefined,
      recentTechniques: [],
    };
  });
 
  const lastDecisionTimeRef = useRef(0);
  const [initialMatchTime] = useState(() => Date.now());
  const matchStartTimeRef = useRef(initialMatchTime);
  const previousDamageRef = useRef(0);
  const [initialActionTime] = useState(() => Date.now());
  const nextActionRef = useRef(initialActionTime);
  const lastWarningTimeRef = useRef(0);
  const lastLateralitySwitchRef = useRef(0); // Track last laterality switch for cooldown
 
  const techniqueRotationQueueRef = useRef<TechniqueRotationQueue>({
    used: [],
    allUsed: new Set(),
    frequency: new Map(),
    totalAttacks: 0,
  });
 
  const techniqueCooldownMapRef = useRef<TechniqueCooldownMap>(new Map());
 
  const archetypeTechniqueIds = useMemo(() => {
    const allTechs = getAllArchetypeTechniques(player.archetype);
    return new Set(allTechs.map((t) => t.id));
  }, [player.archetype]);
 
  const [initialStanceFatigue] = useState(() => ({
    currentStance: player.currentStance,
    lastSwitchTime: Date.now(),
  }));
  const stanceFatigueRef = useRef(initialStanceFatigue);
 
  useEffect(() => {
    if (roundStarted) {
      matchStartTimeRef.current = Date.now();
      previousDamageRef.current = player.totalDamageReceived;
      decisionTree.reset();
      comboSystem.resetCombo();
 
      stanceFatigueRef.current = {
        currentStance: player.currentStance,
        lastSwitchTime: Date.now(),
      };
 
      techniqueRotationQueueRef.current = {
        used: [],
        allUsed: new Set(),
        frequency: new Map(),
        totalAttacks: 0,
      };
 
      techniqueCooldownMapRef.current.clear();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [roundStarted, decisionTree, comboSystem]);
 
  useEffect(() => {
    if (!roundStarted || roundEnded || isPaused) {
      return;
    }
 
    Iif (player.currentStance !== stanceFatigueRef.current.currentStance) {
      stanceFatigueRef.current = {
        currentStance: player.currentStance,
        lastSwitchTime: Date.now(),
      };
    }
  }, [player.currentStance, roundStarted, roundEnded, isPaused]);
 
  useEffect(() => {
    if (isPaused || !roundStarted || roundEnded) {
      return;
    }
 
    let animationFrameId: number;
    let isComplete = false;
 
    const animate = () => {
      Iif (isComplete) return;
 
      const now = Date.now();
      const elapsed = now - transitionStartTimeRef.current;
      const progress = Math.min(1.0, elapsed / transitionDurationMs);
 
      Iif (progress < 1.0) {
        const interpolated = interpolateDifficultyParameters(
          startParamsRef.current,
          targetParams,
          progress,
        );
        setCurrentParams(interpolated);
        animationFrameId = requestAnimationFrame(animate);
      } else {
        setCurrentParams(targetParams);
        isComplete = true;
      }
    };
 
    animationFrameId = requestAnimationFrame(animate);
 
    return () => {
      Eif (animationFrameId) {
        cancelAnimationFrame(animationFrameId);
      }
    };
  }, [isPaused, roundStarted, roundEnded, targetParams, transitionDurationMs]);
 
  useEffect(() => {
    decisionTree.setDifficultyParameters(currentParams);
  }, [decisionTree, currentParams]);
 
  /**
   * Execute AI action callback
   *
   * Passes technique and vital point directly to avoid React state async issues
   *
   * @korean AI 행동 실행 콜백
   */
  const executeAIAction = useCallback(
    (
      action: string,
      targetPosition?: Position,
      selectedTechnique?: KoreanTechnique,
      targetVitalPoint?: string,
    ) => {
      onExecuteAction(action, targetPosition, selectedTechnique, targetVitalPoint);
    },
    [onExecuteAction],
  );
 
  /**
   * Update difficulty target parameters
   * Triggers smooth interpolation to new difficulty level
   *
   * @korean 난이도 목표 매개변수 업데이트
   */
  const updateDifficultyTarget = useCallback(
    (newParams: DifficultyParameters) => {
      startParamsRef.current = currentParams;
      transitionStartTimeRef.current = Date.now();
      setTargetParams(newParams);
    },
    [currentParams],
  );
 
  /**
   * Build combat context for decision-making.
   *
   * **Physics-first**: Positions are now in METERS, so distance is already in meters.
   * No scale conversion needed - direct physics-based calculations.
   *
   * @korean 전투 컨텍스트 구축
   */
  const buildCombatContext = useCallback((): CombatContext => {
    const dx = player.position.x - opponent.position.x;
    const dy = player.position.y - opponent.position.y;
    const distanceInMeters = Math.sqrt(dx * dx + dy * dy);
 
    const recentDamageTaken = Math.max(
      0,
      player.totalDamageReceived - previousDamageRef.current,
    );
    previousDamageRef.current = player.totalDamageReceived;
 
    const opponentBalance = getBalanceState(opponent.balance);
 
    return {
      playerPosition: player.position,
      opponentPosition: opponent.position,
      playerHealth: player.health,
      playerMaxHealth: player.maxHealth,
      playerKi: player.ki,
      playerMaxKi: player.maxKi,
      playerStamina: player.stamina,
      playerMaxStamina: player.maxStamina,
      opponentHealth: opponent.health,
      opponentStance: opponent.currentStance,
      playerStance: player.currentStance,
      distanceToOpponent: distanceInMeters, // Physics-first: distance in meters
      timeInMatch: Date.now() - matchStartTimeRef.current,
      isOpponentAttacking: opponent.combatState === "attacking",
      recentDamageTaken,
      opponentBalance, // Added for kill mode detection
      opponentStamina: opponent.stamina, // Added for vulnerability exploitation (Issue #enhance-intelligence-operative-ai)
      opponentMaxStamina: opponent.maxStamina, // Added for vulnerability exploitation
      opponentKi: opponent.ki, // Added for vulnerability exploitation (Issue #enhance-intelligence-operative-ai)
      opponentMaxKi: opponent.maxKi, // Added for vulnerability exploitation
      stanceFatigue: {
        timeInStance: Date.now() - stanceFatigueRef.current.lastSwitchTime,
      },
      arenaBounds,
    };
  }, [player, opponent, arenaBounds]);
 
  /**
   * AI decision loop (fixed memory leak - issue #2529466989)
   */
  useEffect(() => {
    if (isPaused || !roundStarted || roundEnded) {
      return;
    }
 
    const aiInterval = setInterval(() => {
      const now = Date.now();
 
      if (now < nextActionRef.current) {
        return;
      }
 
      const decisionStart = performance.now();
 
      const context = buildCombatContext();
 
      const decision = decisionTree.makeDecision(
        context,
        adjustedPersonality,
        comboSystem,
      );
 
      const decisionTime = performance.now() - decisionStart;
      Iif (decisionTime > AI_DECISION_THRESHOLD_MS) {
        const now = Date.now();
        if (now - lastWarningTimeRef.current > WARNING_THROTTLE_MS) {
          console.warn(
            `AI decisions running slow: ${decisionTime.toFixed(2)}ms`,
          );
          lastWarningTimeRef.current = now;
        }
      }
      lastDecisionTimeRef.current = decisionTime;
 
      let actionType = "idle";
      let newTargetPosition = aiState.targetPosition;
      let newConsecutiveAttacks = aiState.consecutiveAttacks;
      let selectedTechnique: KoreanTechnique | undefined;
      let targetVitalPoint: string | undefined;
 
      switch (decision.action) {
        case AIActionType.ATTACK:
          {
            const result = selectTechniqueForAction(
              false,
              context,
              player,
              adaptiveDifficulty,
              techniqueRotationQueueRef.current,
              techniqueCooldownMapRef.current,
            );
            selectedTechnique = result.technique;
            targetVitalPoint = result.vitalPoint;
            actionType = result.actionType;
 
            Eif (selectedTechnique) {
              updateTechniqueRotation(
                selectedTechnique.id,
                techniqueRotationQueueRef.current,
                archetypeTechniqueIds,
              );
 
              techniqueCooldownMapRef.current.set(
                selectedTechnique.id,
                Date.now(),
              );
 
              const nextComboTechnique = getNextComboTechnique(
                selectedTechnique.id,
                player.archetype,
              );
 
              Iif (nextComboTechnique) {
                comboSystem.startCombo(player, opponent, adjustedPersonality);
              }
            }
 
            Eif (actionType === "attack") {
              newConsecutiveAttacks++;
            }
          }
          break;
 
        case AIActionType.TECHNIQUE:
          {
            const result = selectTechniqueForAction(
              true,
              context,
              player,
              adaptiveDifficulty,
              techniqueRotationQueueRef.current,
              techniqueCooldownMapRef.current,
            );
            selectedTechnique = result.technique;
            targetVitalPoint = result.vitalPoint;
            actionType = result.actionType;
 
            Iif (selectedTechnique) {
              updateTechniqueRotation(
                selectedTechnique.id,
                techniqueRotationQueueRef.current,
                archetypeTechniqueIds,
              );
 
              techniqueCooldownMapRef.current.set(
                selectedTechnique.id,
                Date.now(),
              );
 
              const nextComboTechnique = getNextComboTechnique(
                selectedTechnique.id,
                player.archetype,
              );
 
              if (nextComboTechnique) {
                comboSystem.startCombo(player, opponent, adjustedPersonality);
              }
            }
 
            Iif (actionType === "attack" || actionType === "technique") {
              newConsecutiveAttacks++;
            }
          }
          break;
 
        case AIActionType.COMBO:
          Eif (!comboSystem.isComboActive()) {
            comboSystem.startCombo(player, opponent, adjustedPersonality);
          }
 
          Iif (
            comboSystem.shouldContinueCombo(
              player,
              opponent,
              adjustedPersonality,
            )
          ) {
            const technique = comboSystem.getNextComboTechnique();
            actionType = technique ? "technique" : "attack";
            newConsecutiveAttacks++;
          } else {
            comboSystem.resetCombo();
            actionType = "idle";
          }
          break;
 
        case AIActionType.DEFEND:
          actionType = "defend";
          newConsecutiveAttacks = 0;
          break;
 
        case AIActionType.COUNTER:
          actionType = "counter";
          newConsecutiveAttacks = 0;
          break;
 
        case AIActionType.RETREAT:
          actionType = "retreat";
          newTargetPosition = decision.targetPosition ?? aiState.targetPosition;
          newConsecutiveAttacks = 0;
          break;
 
        case AIActionType.APPROACH:
          actionType = "approach";
          newTargetPosition = decision.targetPosition ?? opponent.position;
          newConsecutiveAttacks = 0;
          break;
 
        case AIActionType.CIRCLE:
          actionType = "circle";
          newTargetPosition = decision.targetPosition ?? aiState.targetPosition;
          newConsecutiveAttacks = 0;
          break;
 
        case AIActionType.STANCE_CHANGE:
          if (decision.targetStance && onStanceChange) {
            onStanceChange(decision.targetStance);
          }
          actionType = "idle";
          newConsecutiveAttacks = 0;
          break;
 
        case AIActionType.FEINT:
          actionType = "feint";
          newConsecutiveAttacks = 0;
          break;
 
        case AIActionType.WAIT:
        default:
          actionType = "idle";
          newConsecutiveAttacks = 0;
          break;
      }
 
      Iif (onLateralityChange && playerLaterality && opponentLaterality) {
        const shouldSwitch = shouldAISwitchLaterality(
          opponentLaterality, // Laterality for player index 1 (AI-controlled in this hook)
          playerLaterality, // Laterality for player index 0 (human-controlled in this hook)
          adjustedPersonality,
          player.health,
          lastLateralitySwitchRef.current,
          now,
        );
 
        if (shouldSwitch) {
          onLateralityChange();
          lastLateralitySwitchRef.current = now;
        }
      }
 
      const actionCooldown =
        actionType === "attack" || actionType === "technique"
          ? 200 + Math.random() * 150 // 200-350ms for attacks
          : 150 + Math.random() * 150; // 150-300ms for movement/defense
 
      nextActionRef.current = now + actionCooldown;
 
      setAiState((prevState) => {
        let updatedRecentTechniques = [...prevState.recentTechniques];
        if (selectedTechnique) {
          updatedRecentTechniques.push(selectedTechnique.id);
          Iif (updatedRecentTechniques.length > 5) {
            updatedRecentTechniques = updatedRecentTechniques.slice(-5);
          }
        }
 
        return {
          nextAction: nextActionRef.current,
          targetPosition: newTargetPosition,
          lastActionType: actionType,
          consecutiveAttacks: newConsecutiveAttacks,
          actionCooldown,
          aggressionLevel: adjustedPersonality.aggressionLevel,
          selectedTechnique,
          targetVitalPoint,
          recentTechniques: updatedRecentTechniques,
        };
      });
 
      executeAIAction(actionType, newTargetPosition, selectedTechnique, targetVitalPoint);
    }, 50); // 50ms loop for responsive AI
 
    return () => clearInterval(aiInterval);
  }, [
    isPaused,
    roundStarted,
    roundEnded,
    buildCombatContext,
    decisionTree,
    adjustedPersonality,
    comboSystem,
    executeAIAction,
    onStanceChange,
    onLateralityChange,
    player,
    opponent,
    aiState,
    playerLaterality,
    opponentLaterality,
    adaptiveDifficulty,
    archetypeTechniqueIds,
  ]);
 
  return {
    aiState,
    comboSystem,
    decisionTree,
    adjustedPersonality,
    executeAIAction,
    currentDifficultyParams: currentParams,
    updateDifficultyTarget,
  };
}