MainHud/Program.cs

Static combat controller for a keyboard-warrior RPG. It picks AI actions and dialogue, resolves player and AI turns including damage variance, criticals, blocks and weapon enchantments, and writes combat logs.

Rough Code
🐞 HandlePlayerTurn applies player.Perks.AttackMultiplier twice to physical attack damage, first through safeAttackMultiplier and again directly on baseDamage.
using Keyboard_Warriors_.Managers;
using Keyboard_Warriors_.Models;
using Keyboard_Warriors_.Systems;
using System;
using System.Collections.Generic;
using System.ComponentModel.Design;
using System.Linq;
using System.Numerics;
using static Sandbox.Citizen.CitizenAnimationHelper;
using static Sandbox.PhysicsContact;

public class Game
{
	public static bool tookDamage = false;
	static bool hitJackpot = false;

	public static void aiDialogue( int hp )
	{
		// If the AI is dead, skip the randomizer and blow it up immediately
		if ( hp <= 0 )
		{
			// 🔴 AI TEXT HIGHLIGHT: Triggers upon match obliteration
			GameManager.AddAILog( "AI: \"**INITIATING DEFEAT PROCESS.. 3..2..1.. *BOOM*\"" );
			return;
		}

		int r = Random.Shared.Next( 4 );

		// Modern C# relational switch pattern - catches exact boundary drops perfectly!
		string quote = hp switch
		{
			>= 91 => r switch
			{
				0 => "AI: \"I'm fresh from the computer factory!\"",
				1 => "AI: \"You can't even Turing test me!\"",
				2 => "AI: \"I guided your GPS here, you're finished!\"",
				_ => "AI: \"A million + MB speed! A walk in the park!\""
			},
			>= 76 => r switch
			{
				0 => "AI: \"You think you can handle these circuits?!\"",
				1 => "AI: \"I'm just powering up!\"",
				2 => "AI: \"You're barely scratching my casing.\"",
				_ => "AI: \"Efficiency remains at 98%.\""
			},
			>= 51 => r switch
			{
				0 => "AI: \"My lights are only flickering a little!\"",
				1 => "AI: \"No, my software is not outdated!\"",
				2 => "AI: \"It's just some dust slowing me down!\"",
				_ => "AI: \"I got the wrong user signed into me!\""
			},
			>= 26 => r switch
			{
				0 => "AI: \"I still got my other arm!!\"",
				1 => "AI: \"Are my sensors smoking?!\"",
				2 => "AI: \"Warning.. structural damage rising.\"",
				_ => "AI: \"This unit does not feel pain, but this is close!\""
			},
			>= 11 => r switch
			{
				0 => "AI: \"Emergency protocols activated!\"",
				1 => "AI: \"I keep seeing a blue screen!\"",
				2 => "AI: \"The probabilities are against me!\"",
				_ => "AI: \"I demand a system reboot!!\""
			},
			_ => r switch // This catches everything from 1 to 10 HP
			{
				0 => "AI: \"Tell my cat I love him...\"",
				1 => "AI: \"I will be programmed again!\"",
				2 => "AI: \"GB storage.. almost.. empty..\"",
				_ => "AI: \"Goodbye.. cruel.. motherboard..\""
			}
		};

		// 🔴 AI TEXT HIGHLIGHT: Prints all dynamic health taunts in crimson red!
		GameManager.AddAILog( quote );
	}

	public static void aiMemoryDialogue( int winStreak, int lossStreak, bool tookDamage, int round )
	{
		if ( Random.Shared.Next( 100 ) < 25 ) return;

		if ( winStreak >= 3 )
		{
			int r = Random.Shared.Next( 3 );
			// 🔴 AI TEXT HIGHLIGHT: Banners memory text in crimson red
			if ( r == 0 ) GameManager.AddAILog( $"AI: \"You've won {winStreak} in a row... adapting strategy...\"" );
			else if ( r == 1 ) GameManager.AddAILog( "AI: \"Your pattern is becoming predictible.. or is it?\"" );
			else GameManager.AddAILog( "AI: \"Win streak detected. You have to be using hacks.\"" );
			return;
		}

		if ( lossStreak >= 3 )
		{
			int r = Random.Shared.Next( 3 );
			// 🔴 AI TEXT HIGHLIGHT: Banners memory text in crimson red
			if ( r == 0 ) GameManager.AddAILog( $"AI: \"You've lost {lossStreak} times... want me to go easy?\"" );
			else if ( r == 1 ) GameManager.AddAILog( "AI: \"Confidence levels decreasing, yours, not mine.\"" );
			else GameManager.AddAILog( "AI: \"Statistically, this is getting sad..\"" );
			return;
		}

		if ( !tookDamage && round > 2 )
		{
			int r = Random.Shared.Next( 3 );
			// 🔴 AI TEXT HIGHLIGHT: Banners memory text in crimson red
			if ( r == 0 ) GameManager.AddAILog( "AI: \"No damage taken? That's.. unusual..\"" );
			else if ( r == 1 ) GameManager.AddAILog( "AI: \"Do you have impenetrable armor?\"" );
			else GameManager.AddAILog( "AI: \"Flawless execution detected. Investigating..\"" );
			return;
		}

		if ( round > 6 )
		{
			int r = Random.Shared.Next( 3 );
			// 🔴 AI TEXT HIGHLIGHT: Banners memory text in crimson red
			if ( r == 0 ) GameManager.AddAILog( "AI: \"This battle is lasting longer than expected...\"" );
			else if ( r == 1 ) GameManager.AddAILog( "AI: \"Unlucky for you, I don't get tired..\"" );
			else GameManager.AddAILog( "AI: \"Why are you still alive?!\"" );
		}
	}

	public static string GetPlayerWeaponArt( string weaponName )
	{
		if ( weaponName == "Sword" )
		{
			return @"
     /\
    //\\
    ||||
    ||||
    ||||
    ||||
    ||||
    ||||
    ||||
    ||||
    ||||
    ||||
    ||||
    ||||
 _  ||||  _
/(  ||||  )\
\\\_[\/]_///
 \\_<()>_//
  \/[\\]\/
    [//]
    [\\]
    [//]
    [\\]
    [//]
    (__)
";
		}
		else if ( weaponName == "Axe" )
		{
			return @"
 //`-||-'\\
(| -=||=- |)
 \\,-||-.//
  `  ||  '
     ||
     ||
     ||
     ||
     ||
     ()
";
		}
		
	
		else if ( weaponName == "Shield" )
		{
			return @"
  |`-._/\_.-`|
  |    ||    |
  |___o()o___|
  |__((<>))__|
  \   o\/o   /
   \   ||   /
    \  ||  /
     '.||.'
       ``
";
		}
		else if ( weaponName == "Dagger" )
		{
			return @"
       /\
      //\\
     //  \\
     \\  //    
      )  (
      )  (
      )  (
 ^    )  (    ^
/ \   )  (   / \
) (   )  (   ) (
\  \_/ /\ \_/  /
 \__  _)(_  __/
    \ \  / /
     ) \/ (
     | /\ |
     | )( |
     | )( |
     | \/ |
     )____(
    /      \
    \______/
";
		}

		return "";// Return empty string if no weapon matches
	}


	public static void PrintBanner()
	{
		// 🔵 PLAYER TEXT HIGHLIGHT: Makes the big grand achievement banner glow in raw electric cyber-blue!
		GameManager.AddPlayerLog( @"
   _   _____  _   _ _____ _____ _   _ _____ ______  _____ _   _ _____   _   _ _   _  _     _____ _____  _   __ _____ _____ _
 / _ \/  __ \| | | |_   _|  ___| | | |  ___|  \/  ||  ___| \ | |_   _| | | | | \ | || |   |  _  /  __ \| | / /|  ___|  _  \ |
/ /_\ \ /  \/| |_| | | | | |__ | | | | |__ | .  . || |__ |  \| | | |   | | | |  \| || |   | | | | /  \/| |/ / | |__ | | | | |
|  _  | |    |  _  | | | |  __|| | | |  __|| |\/| ||  __|| . ` | | |   | | | | . ` || |   | | | | |    |    \ |  __|| | | | |
| | | | \__/\| | | |_| |_| |___\ \_/ / |___| |  | || |___| |\  | | |   | |_| | |\  || |___\ \_/ / \__/\| |\  \| |___| |/ /|_|
\_| |_/\____/\_| |_/\___/\____/ \___/\____/\_|  |_/\____/\_| \_/ \_/    \___/\_| \_/\_____/\___/ \____/\_| \_/\____/|___/ (_)
" );
	}

	public static void ShowPlayerSpells( Player player )
	{
		// 🔵 PLAYER TEXT HIGHLIGHT: Paints your private spell book menu cards in bright electric blue
		GameManager.AddPlayerLog( "\n--- Your Spells ---" );

		string offensive = "Offensive: ";
		foreach ( string s in player.offensiveSpells ) offensive += s + "  ";
		GameManager.AddPlayerLog( offensive );

		string defensive = "Defensive: ";
		foreach ( string s in player.defensiveSpells ) defensive += s + "  ";
		GameManager.AddPlayerLog( defensive );

		string healing = "Healing: ";
		foreach ( string s in player.healingSpells ) healing += s + "  ";
		GameManager.AddPlayerLog( healing );

		string special = "Special: ";
		foreach ( string s in player.specialSpells ) special += s + "  ";
		GameManager.AddPlayerLog( special );

		GameManager.AddPlayerLog( "\n--------------------" );
	}

	public static int GetPlayerMove()
	{
		// Custom UI choice mapping replaces Console.ReadLine loops in s&box panels.
		// Returning a random action selector as an automation layout fallback for engine ticks.
		return Random.Shared.Next( 1, 9 );
	}

	public static int ChooseAIAction( Player player, Player ai, int attackCount, int blockCount, int healCount, int specialCount, int round )
	{
		// ----------------================-------------------------------------
		// CONFIGURABLE TACTICAL PERCENTAGES (Tune these to adjust AI difficulty!)
		// ---------------------------------------------------------------------
		int aiTacticalAwarenessChance = 80; // 80% chance AI even checks your trends this turn
		int aiCounterAttackChance = 45; // 45% chance to react if player spams Attack
		int aiCounterBlockChance = 40; // 40% chance to react if player spams Block
		int aiCounterHealChance = 75; // 75% chance to react if player spams Healing/Potions
		int aiCounterSpecialChance = 60; // 60% chance to react if player spams Special moves

		// Resolve current scene progression variables to safely evaluate scaled magic costs
		var manager = Sandbox.Game.ActiveScene?.Get<GameManager>();
		int prestige = manager != null ? manager.CurrentPrestige : 0;

		// Calculate exact capped magic costs matching your spell system updates
		int scaledOffensiveCost = 20 + (prestige * 5); if ( scaledOffensiveCost > 100 ) scaledOffensiveCost = 100;
		int scaledDefensiveCost = 15 + (prestige * 5); if ( scaledDefensiveCost > 100 ) scaledDefensiveCost = 100;
		int scaledHealingCost = 20 + (prestige * 5); if ( scaledHealingCost > 100 ) scaledHealingCost = 100;
			int scaledUltimateCost = 30 + (prestige * 10); if ( scaledUltimateCost > 100 ) scaledUltimateCost = 100;


		// FIX: Correctly initialize tracking layout thresholds so attack (1) is caught!
		int dominantMove = 1;
		int maxCount = attackCount;

		if ( blockCount > maxCount )
		{
			maxCount = blockCount;
			dominantMove = 2;
		}

		if ( healCount > maxCount )
		{
			maxCount = healCount;
			dominantMove = 3;
		}

		if ( specialCount > maxCount )
		{
			maxCount = specialCount;
			dominantMove = 4;
		}

		
		int aiMove = 0;
		int roll = Random.Shared.Next( 100 );

		// ----------------================-------------------------------------
		// CRITICAL SYSTEM OVERRIDE: Low Magic Fallback Routine
		// ---------------------------------------------------------------------
		if ( ai.magic < 15 )
		{
			aiMove = (Random.Shared.Next( 100 ) < 70) ? 1 : (2 + Random.Shared.Next( 3 ));

			if ( manager != null )
			{
				manager.AICurrentStance = "⚠️ MANA CRITICAL: EMERGENCY FALLBACK";
				manager.AICurrentMoveIndex = aiMove;
			}
		}
		else
		{
			// ----------------================-------------------------------------
			// LAYER 1: Global Tactical Awareness Percentage Check
			// ---------------------------------------------------------------------
			bool isAIPayingAttention = Random.Shared.Next( 100 ) < aiTacticalAwarenessChance;

			if ( manager != null )
			{
				manager.AICurrentStance = "🌐 ANALYZING MOVES";
			}

			if ( round > 2 && isAIPayingAttention )
			{
				// LAYER 2 / BRANCH 1: Counter Player Attack Spam
				if ( dominantMove == 1 && Random.Shared.Next( 100 ) < aiCounterAttackChance )
				{
					// =========================================================================
					// 🧠 UPDATE 2.1.1: COUNTER ENGAGEMENT MATRIX (STEAM PLAYER INSULT INJECT)
					// =========================================================================
					// Securely pulls your account profile string name directly from the s&box wrapper API
					string userSteamName = Sandbox.Utility.Steam.PersonaName;

					if ( string.IsNullOrEmpty( userSteamName ) )
					{
						userSteamName = Sandbox.Connection.Local?.Name;
					}
					if ( string.IsNullOrEmpty( userSteamName ) )
					{
						userSteamName = "Unknown Combatant";
					}

					int r = Random.Shared.Next( 2 );
					if ( r == 0 )
					{
						// 🔴 AI TEXT HIGHLIGHT: Tactical blocking callout mocking you by name!
						GameManager.AddAILog( $"AI: \"Countering your blind aggression, {userSteamName}! Did you think that would pass my buffers?\"" );
						aiMove = 2; // Basic Weapon Block
					}
					else if ( ai.magic >= scaledDefensiveCost )
					{
						// 🔴 AI TEXT HIGHLIGHT: Anti-attack magic callout mocking you by name!
						GameManager.AddAILog( $"AI: \"Magically sealing your assault, {userSteamName}! Your strategy is full of statistical errors.\"" );
						aiMove = 6; // Defensive Barrier Spell
					}
					else
					{
						// Fallback safe line just in case it doesn't have the magic pool for a spell
						GameManager.AddAILog( $"AI: \"Predicting your weapon strike vector, {userSteamName.ToUpper()}. Intercepting!\"" );
						aiMove = 2;
					}

					if ( manager != null )
					{
						manager.AICurrentStance = "⚔️ ANTI-AGGRESSION PROTOCOLS ENGAGED";
						manager.AICurrentMoveIndex = aiMove;
					}
					// =========================================================================
				}

				// LAYER 2 / BRANCH 2: Counter Player Block Spam
				else if ( dominantMove == 2 && Random.Shared.Next( 100 ) < aiCounterBlockChance )
				{
					int r = Random.Shared.Next( 2 );
					if ( r == 0 )
					{
						// 🔴 AI TEXT HIGHLIGHT: Exploiting defense patterns
						GameManager.AddAILog( "AI: \"Defensive pattern detected.. exploiting.\"" );
						aiMove = 3; // Use item potion / setup
					}
					else if ( ai.magic >= scaledOffensiveCost )
					{
						// 🔴 AI TEXT HIGHLIGHT: Guard unblockable spell taunt
						GameManager.AddAILog( "AI: \"You can't block this spell!\"" );
						aiMove = 5; // Direct Offensive Spell
					}

					if ( manager != null )
					{
						manager.AICurrentStance = "🛡️ EXPLOITING DEFENSIVE STRATEGY";
						manager.AICurrentMoveIndex = aiMove;
					}
				}

				// LAYER 2 / BRANCH 3: Counter Player Heal Spam
				else if ( dominantMove == 3 && Random.Shared.Next( 100 ) < aiCounterHealChance )
				{
					int r = Random.Shared.Next( 2 );

					if ( r == 0 && ai.magic >= scaledUltimateCost )
					{
						// 🔴 AI TEXT HIGHLIGHT: Anti-healing ultimate overwrite warning
						GameManager.AddAILog( "AI: \"Heal spam recognized. Executing core system purge overrides!\"" );
						aiMove = 8; // Force Prestige Ultimate Spell
					}
					else
					{
						// 🔴 AI TEXT HIGHLIGHT: Heavy strike follow-up
						GameManager.AddAILog( "AI: \"So many bandages. You're being punished.\"" );
						aiMove = 1; // Heavy physical Basic Weapon Attack strike!
					}

					if ( manager != null )
					{
						manager.AICurrentStance = "🤢 ANTI-VIRUS PROCESS ACTIVE";
						manager.AICurrentMoveIndex = aiMove;
					}
				}

				// LAYER 2 / BRANCH 4: Counter Player Special/Ultimate Spam
				else if ( dominantMove == 4 && Random.Shared.Next( 100 ) < aiCounterSpecialChance )
				{
					int r = Random.Shared.Next( 2 );
					if ( r == 0 )
					{
						// 🔴 AI TEXT HIGHLIGHT: Super move nullification taunt
						GameManager.AddAILog( "AI: \"Your supercharged moves don't harm me!\"" );
						aiMove = 2;
					}
					else if ( ai.magic >= scaledDefensiveCost )
					{
						// 🔴 AI TEXT HIGHLIGHT: Impenetrable magic shield boast
						GameManager.AddAILog( "AI \"This defense spell is impossible to puncture!\"" );
						aiMove = 6; // Force Magic Wall / Fortify barrier checks
					}

					if ( manager != null )
					{
						manager.AICurrentStance = "🛑 OVERDRIVE BLOCKADE STANCE ENCRYPTED";
						manager.AICurrentMoveIndex = aiMove;
					}
				}
			}

			// If tactical counters skipped, push the final computed default move index up to the tracker
			if ( manager != null && manager.AICurrentMoveIndex == 0 )
			{
				manager.AICurrentMoveIndex = aiMove;
			}

			// ----------------================================================-----
			// DEFAULT FALLBACK ROUTINE
			// ---------------------------------------------------------------------
			// Runs if no spam patterns matched or fell through condition boundaries
			if ( aiMove == 0 )
			{
				aiMove = (Random.Shared.Next( 100 ) < 50) ? 1 : (2 + Random.Shared.Next( 3 ));

				if ( manager != null )
				{
					manager.AICurrentStance = "🌐 DEFAULT CORE SEQUENCING (STABLE)";
					manager.AICurrentMoveIndex = aiMove;
				}
			}
		}

		if ( ai.cursed )
		{
			// A 30% chance to ignore the poison and attack anyway, 
			// even if it has Cleanse! This prevents the "Cleanse Loop."
			bool hasCleanse = ai.healingSpells.Contains( "Cleanse" );
			bool shouldAttemptCleanse = hasCleanse && Random.Shared.Next( 100 ) < 40;

			if ( shouldAttemptCleanse )
			{
				aiMove = 7;
				// 🔴 AI TEXT HIGHLIGHT: Anti-poison purge alert
				GameManager.AddAILog( "AI: \"Status corrupted, purging effects..\"" );

				if ( manager != null )
				{
					manager.AICurrentStance = "🧪 CORRUPTED STATS: ANTI-MALWARE PURGE";
					manager.AICurrentMoveIndex = aiMove;
				}
			}
			else
			{
				int[] aggressiveMoves = { 1, 4, 5, 8 };
				aiMove = aggressiveMoves[Random.Shared.Next( aggressiveMoves.Length )];
				// 🔴 AI TEXT HIGHLIGHT: Critical poison rage quote
				GameManager.AddAILog( "AI: \"System integrity compromised. Prioritizing offensive output!\"" );

				if ( manager != null )
				{
					manager.AICurrentStance = "💥 TOXIC RAGE: MAXIMIZING ATTACK CHANNELS";
					manager.AICurrentMoveIndex = aiMove;
				}
			}
		}
		else if ( aiMove == 0 && player.hp < 25 && ai.magic >= 30 )
		{
			aiMove = 8;
			// 🔴 AI TEXT HIGHLIGHT: Execution protocol warning quote
			GameManager.AddAILog( "AI: \"Target near termination, casting final spell..\"" );

			if ( manager != null )
			{
				manager.AICurrentStance = "💀 EXECUTION TERMINAL: TARGET ELIMINATION";
				manager.AICurrentMoveIndex = aiMove;
			}
		}
		else if ( aiMove == 0 )
		{
			// 1. Fetch dynamic max health benchmarks for BOTH fighters safely from the manager scene
			int aiMaxHp = (manager != null && manager.AIEnemy != null) ? manager.AIEnemy.maxHp : 100;
			int maxPlayerHp = (manager != null && manager.LocalPlayer != null) ? manager.LocalPlayer.maxHp : 100;

			// 2. Calculate dynamic tactical health thresholds based on current prestige ceilings
			int aiHighHealthThreshold = (int)(aiMaxHp * 0.70f);
			int aiLowHealthThreshold = (int)(aiMaxHp * 0.30f);
			int playerLowHealthThreshold = (int)(maxPlayerHp * 0.30f); // Dynamically scales from 30 HP at Prestige 0

			// ----------------================================================-----
			// 🔮 SYSTEM CLOSURE HOOK: LOW MAGIC PERSPECTIVE ABORTION MATRIX
			// ---------------------------------------------------------------------
			// Evaluates a 15% panic override gamble choice if resources run critically low
			Func<int, int, int, int> EvaluateMagicBrainChoice = ( int desiredMove, int scaledCost, int physicalFallbackMove ) =>
			{
				if ( ai.magic >= scaledCost ) return desiredMove; // Confirmed resource availability!

				// AI lacks magic! Roll for the 85/15 tactical gamble ratio
				if ( Random.Shared.Next( 100 ) < 15 )
				{
					// 15% Gamble: Force the uncastable spell anyway so it public-glitches into the combat text log channels!
					return desiredMove;
				}

				// 85% Wise Abort: The brain recognizes it lacks points and silently adapts to a non-magic action profile
				return physicalFallbackMove;
			};

			// --- BRANCH A: Player is low health (Execute / Burn target stance) ---
			if ( player.hp <= playerLowHealthThreshold )
			{
				// 🚨 RE-WEIGHTED: 95% aggressive choice probability to completely burn down the target!
				if ( roll < 40 )
				{
					aiMove = 1; // Basic Weapon Attack (Climbed from 30%)
				}
				else if ( roll < 80 )
				{
					aiMove = EvaluateMagicBrainChoice( 5, scaledOffensiveCost, 1 ); // Offensive Spell or Melee fallback
				}
				else if ( roll < 95 )
				{
					aiMove = EvaluateMagicBrainChoice( 8, scaledUltimateCost, 1 ); // Ultimate Core Override or Melee fallback
				}
				else
				{
					aiMove = 4; // Special Attack (Leaves 0% room for the AI to back off and heal!)
				}

				// 🔴 AI TEXT HIGHLIGHT: Prints execution warnings in crimson red!
				GameManager.AddAILog( "AI: \"Target acquired. Executive lethal sub-routines engaged. Prepare to be dismantled!\"" );

				if ( manager != null )
				{
					manager.AICurrentStance = "🔥 LETHAL PROTOCOLS: KILL MATRIX OVERRIDE";
					manager.AICurrentMoveIndex = aiMove;
				}
			}
			// --- BRANCH B: AI is high health (Aggressive / Secure lead stance) ---
			else if ( ai.hp > aiHighHealthThreshold )
			{
				// 🚨 RE-WEIGHTED: Massive attack focus. Defensive cast chance crushed down to only 5%.
				if ( roll < 40 )
				{
					aiMove = 1; // Basic Weapon Attack (Climbed from 35%)
								// 🔴 AI TEXT HIGHLIGHT: Prints high-velocity strikes in crimson red!
					GameManager.AddAILog( "AI: \"This one's gonna be almost the speed of light!!\"" );
				}
				else if ( roll < 75 )
				{
					aiMove = 4; // Special Attack (Climbed from 30% width to 35% wide bracket)
				}
				else if ( roll < 95 )
				{
					aiMove = EvaluateMagicBrainChoice( 5, scaledOffensiveCost, 1 ); // Offensive Spell or Melee fallback
				}
				else
				{
					aiMove = EvaluateMagicBrainChoice( 6, scaledDefensiveCost, 2 ); // Defensive Barrier Spell or Physical Block
				}

				if ( manager != null )
				{
					manager.AICurrentStance = "🛡️ SECURE CONFIGURATION: PRESSURING HARDWARE";
					manager.AICurrentMoveIndex = aiMove;
				}
			}
			// --- BRANCH C: AI is mid health (Tactical adaptive stance) ---
			else if ( ai.hp > aiLowHealthThreshold )
			{
				// 🚨 RE-WEIGHTED: Offense increased. Toolkit/Healing drops to 15% total (was 35%), forcing aggressive trades.
				if ( roll < 35 )
				{
					aiMove = 1; // Basic Weapon Attack (Climbed from 30%)
				}
				else if ( roll < 45 )
				{
					aiMove = 3; // Toolkit Repair Heal (Dropped down significantly)
				}
				else if ( roll < 50 )
				{
					aiMove = EvaluateMagicBrainChoice( 7, scaledHealingCost, 3 ); // Magic Healing Spell or Toolkit fallback
				}
				else if ( roll < 75 )
				{
					aiMove = 4; // Special Attack (Widened bracket)
				}
				else if ( roll < 92 )
				{
					aiMove = EvaluateMagicBrainChoice( 5, scaledOffensiveCost, 1 ); // Offensive Magic Spell or Melee fallback
				}
				else
				{
					aiMove = EvaluateMagicBrainChoice( 6, scaledDefensiveCost, 2 ); // Defensive Shield Spell or Physical Block
				}

				if ( manager != null )
				{
					manager.AICurrentStance = "📊 TACTICAL ADAPTATION: RE-ROUTING MATRIX";
					manager.AICurrentMoveIndex = aiMove;
				}
			}
			// --- BRANCH D: AI is low health (Panic crisis recovery stance) ---
			else
			{
				// 🚨 RE-WEIGHTED: Even in panic, the AI is 15% more likely to throw a desperation special or ultimate to win a race!
				if ( roll < 30 )
				{
					aiMove = 3; // Toolkit Repair Heal
				}
				else if ( roll < 55 )
				{
					aiMove = EvaluateMagicBrainChoice( 7, scaledHealingCost, 3 ); // Magic Healing Spell or Toolkit fallback
				}
				else if ( roll < 70 )
				{
					aiMove = 2; // Basic Weapon Block
				}
				else if ( roll < 85 )
				{
					aiMove = 4; // Desperation Special Attack! (New aggressive insertion)
				}
				else
				{
					aiMove = EvaluateMagicBrainChoice( 8, scaledUltimateCost, 1 ); // Desperation Ultimate Spell Nuke or Melee fallback
				}

				if ( manager != null )
				{
					manager.AICurrentStance = "🚨 INTEGRITY THREAT: EMERGENCY SUSTAIN MATRIX";
					manager.AICurrentMoveIndex = aiMove;
				}
			}
		}


		switch ( aiMove )
		{
			case 1:
				// 🔴 AI TEXT HIGHLIGHT: Standard physical charge indicator
				GameManager.AddAILog( "AI charges up for a standard attack!" );
				break;

			case 2:
				// 🔴 AI TEXT HIGHLIGHT: Defensive status change announcement
				GameManager.AddAILog( "AI goes on the defensive!" );
				break;

			case 3:
				// 🔴 AI TEXT HIGHLIGHT: Engineering toolkit repair phase text
				GameManager.AddAILog( "AI grabs its toolkit for repairs!" );
				break;

			case 4:
				{
					string[] specials = {
			"AI prepares a devastating special attack!",
			"AI searches its databases for a special attack!",
			"You see the AI heating up and smoking.. AI is charging a special!"
		};
					// 🔴 AI TEXT HIGHLIGHT: Specialized dynamic ability alerts
					GameManager.AddAILog( specials[Random.Shared.Next( 3 )] );
					break;
				}

			case 5:
				{
					string[] lines = {
			"AI reaches into its wizard bag full of offensive spells.",
			"AI's circuits spark with destructive intent!",
			"Infinite Power!! The AI yells as it fires an offensive spell your way!"
		};
					// 🔴 AI TEXT HIGHLIGHT: Destructive code execution statements
					GameManager.AddAILog( lines[Random.Shared.Next( 3 )] );
					break;
				}

			case 6:
				{
					string[] lines = {
				"AI boosts its firewall with a defensive spell!",
				"AI deploys magical shielding protocols!",
				"AI puts its guard up with defensive magic!"
			};
					// 🔴 AI TEXT HIGHLIGHT: Encrypted firewall construction lines
					GameManager.AddAILog( lines[Random.Shared.Next( 3 )] );
					break;
				}

			case 7:
				{
					string[] lines = {
			"AI waves over itself a misty aura of health!",
			"AI begins regenerating its health with spells!",
			"AI diverts power to restoration systems!"
		};
					// 🔴 AI TEXT HIGHLIGHT: Power diversion utility indicators
					GameManager.AddAILog( lines[Random.Shared.Next( 3 )] );
					break;
				}

			case 8:
				{
					string[] lines = {
			"AI cooks up a reality-bending spell!",
			"AI supercharges and overclocks for some heavy magic!",
			"AI bends time and space with this magic spell!"
		};
					// 🔴 AI TEXT HIGHLIGHT: Reality-bending kernel breaches
					GameManager.AddAILog( lines[Random.Shared.Next( 3 )] );
					break;
				}

			default:
				// 🔴 AI TEXT HIGHLIGHT: Core debugging compilation failure notice
				GameManager.AddAILog( "AI has a bug and is malfunctioning..." );
				break;
		}

		// =========================================================================
		// 🌐 DEFINITIVE SECTOR PACKET INTERCEPT HOOK (Update 1.5.7)
		// =========================================================================
		// Lock in the definitive finalized choice into the GameManager cache variables 
		// so your Prestige 5 packet intercept layout widget updates with 100% precision!
		var finalManager = Sandbox.Game.ActiveScene?.Get<GameManager>();
		if ( finalManager != null )
		{
			finalManager.AICurrentMoveIndex = aiMove;

			finalManager.IsAIActionIntercepted = (Random.Shared.Next( 100 ) < 20);
		}
		// =========================================================================

		return aiMove;
	}
	public static void HandlePlayerTurn( ref Player player, ref Player ai, Weapon chosenWeapon, int playerMove, int playerBuff, ref int aiBuff )
	{
		var manager = Sandbox.Game.ActiveScene.Get<GameManager>();
		int currentPrestige = manager != null ? manager.CurrentPrestige : 0;

		// Resolve true dynamic prestige health caps to replace hardcoded 100 loops safely
		int maxPlayerHp = (manager != null && manager.LocalPlayer != null) ? manager.LocalPlayer.maxHp : 100;
		int maxAIHp = (manager != null && manager.AIEnemy != null) ? manager.AIEnemy.maxHp : 100;

		if ( playerBuff == -999 )
		{
			// ⚙️ SYSTEM LINE: Stays neutral safe white/amber
			GameManager.AddLog( "You're too dazed to act!" );
		}
		else
		{
			
			int totalAttack = player.attack + player.eventAttackBuff;

			if ( playerMove == 1 )
			{ // Attack
				GameManager.Instance.PlayClickSound();
				bool rareMiss = Random.Shared.Next( 100 ) < 3; // 3%

				if ( rareMiss )
				{
					if ( manager != null && manager.CurrentMode == GameManager.PlayMode.Multiplayer )
					{
						GameManager.AddButtonFeedbackLog( $"{player.name} swings and completely misses!", isSuccess: false );
						GameManager.AddAILog( $"{ai.name}: \"You missed? How inefficient..\"" );
					}
					else
					{


						// ⚡ ANIMATION UPDATE: Missed attacks now shake and flash in failure red
						GameManager.AddButtonFeedbackLog( "You swing and completely miss!", isSuccess: false );

						// 🔴 AI HIGHLIGHT: The AI mocking your failure turns red
						GameManager.AddAILog( "AI: \"You missed? How inefficient..\"" );
					}
				}
				else
				{
					
					bool isConfused = (player.eventAttackBuff == -1);
					bool hitSuccess = isConfused ? Random.Shared.Next( 100 ) < 50 : true;

					if ( hitSuccess )
					{
						if ( (ai.isBlocking || ai.isMagicBlocking) && CombatManager.attemptBlock() )
						{
							GameManager.Instance.PlayFirewallSound();
							if ( manager != null && manager.CurrentMode == GameManager.PlayMode.Multiplayer )
							{
								RandomEventManager.playSoundEffect( $"*DINK!* {ai.name} uses Firewall!" );
								GameManager.AddAILog( $"{ai.name}: \"Access Denied, {player.name}. Your payload metrics bounce right off my shielding parameters!\"" );
							}
							else
							{

								RandomEventManager.playSoundEffect( "*DINK!* AI uses Firewall!" );

								string userSteamName = Sandbox.Utility.Steam.PersonaName;

								if ( string.IsNullOrEmpty( userSteamName ) )
								{
									userSteamName = Sandbox.Connection.Local?.Name;
								}
								if ( string.IsNullOrEmpty( userSteamName ) )
								{
									userSteamName = "Unknown Combatant";
								}

								// Dynamic dialogue options roll on contact to break human morale!
								int trashTalkRoll = Random.Shared.Next( 3 );
								string aiInsultLine = "";

								if ( trashTalkRoll == 0 )
								{
									aiInsultLine = $"AI: \"Access Denied, {userSteamName}. Your payload metrics bounce right off my shielding parameters!\"";
								}
								else if ( trashTalkRoll == 1 )
								{
									aiInsultLine = $"AI: \"Is that the best script execution you can compile, {userSteamName}? Prepare to rage quit!\"";
								}
								else
								{
									aiInsultLine = $"AI: \"Firewall systems installed and upgraded! Your movements are completely predictable, {userSteamName}.\";";
								}

								// Output the selected insult straight into the red AI telemetry logger
								GameManager.AddAILog( aiInsultLine );
							}
						}
						else
						{
							

							float weaponBase = chosenWeapon.GetScaledDamage( currentPrestige );

							int trackingBuff = player.eventAttackBuff > 0 ? player.eventAttackBuff : 0;
							int baseDamage = (int)(player.attack + weaponBase + player.attackDamage + trackingBuff);

							float safeAttackMultiplier = player.Perks != null ? player.Perks.AttackMultiplier : 1.0f;
							if ( safeAttackMultiplier <= 0.0f ) safeAttackMultiplier = 1.0f;
							baseDamage = (int)(baseDamage * safeAttackMultiplier);

							// =========================================================================
							// 🩸 VAMPIRIC PUNCTURE ATTACK MULTIPLIER INTEGRATION (Update 1.6.5)
							// =========================================================================
							// Seamlessly scales your base physical hit using your perk multipliers!
							baseDamage = (int)(baseDamage * player.Perks.AttackMultiplier);
							// =========================================================================

							if ( player.Perks.HasBerserkerRegistry )
							{
								// Check if current HP is below half of max health capacity
								if ( player.hp < (player.maxHp / 2) )
								{
									baseDamage = (int)(baseDamage * 1.50f); // Injects the +50% extra damage payload!
									GameManager.AddPlayerLog( "🔥 BERSERKER REGISTRY ACTIVE: Your damage is surged by +50% under low health thresholds!" );
								}
							}

							// =========================================================================
							// ⚔️ APPROACH 3: INTEGRATED MOMENTUM DAMAGE VARIANCE MATRIX
							// =========================================================================
							// Establish baseline bounds (Tight 90% to 110% variance layout)
							float lowerBoundVariance = 0.90f;
							float upperBoundVariance = 1.10f;

							// Expand the upper critical limit window using real-time game-state metrics
							manager = Sandbox.Game.ActiveScene?.Get<GameManager>();
							int activePrestige = manager != null ? manager.CurrentPrestige : 0;
							int currentWinStreak = manager != null ? manager.WinStreak : 0;

							// 1. Prestige Scaling Factor: +2% upper boundary per prestige level
							upperBoundVariance += (activePrestige * 0.02f);

							// 2. Mana Overclock Surge: Holding 75+ Magic expands the ceiling by +15%
							if ( player.magic >= 75 )
							{
								upperBoundVariance += 0.15f;
							}

							// 3. Streak Momentum: Being on a 3+ Win Streak expands the ceiling by +10%
							if ( currentWinStreak >= 3 )
							{
								upperBoundVariance += 0.10f;
							}

							// Roll the final random decimal multiplier safely
							float finalVarianceMultiplier = Random.Shared.Float( lowerBoundVariance, upperBoundVariance );

							// Compute the dynamic weapon attack base before evaluating a hard Critical Hit roll
							int damageWithVariance = (int)(baseDamage * finalVarianceMultiplier);
							// =========================================================================

							// Check for your native 5% hard Critical Hit roll
							if ( ai.Perks.HasKernelPlating && finalVarianceMultiplier > 1.0f )
							{
								damageWithVariance = baseDamage;
								GameManager.AddAILog( "🛡️ KERNEL PLATING: Absolute protection nullified your damage variance overclock!" );
							}
							// =========================================================================

							// =========================================================================
							// 📉 CRITICAL PLUNGE MODIFIER (Update 1.6.5)
							// =========================================================================
							// Reads your penalty modifier. If you have Kernel Plating, it drops your crit chance to 0%.
							int calculatedCritChance = (int)(5 + player.Perks.CriticalStrikeChanceModifier);
							if ( calculatedCritChance < 0 ) calculatedCritChance = 0;

							bool crit = Random.Shared.Next( 100 ) < calculatedCritChance;
							int finalDamage = crit ? (int)(damageWithVariance * 1.5f) : damageWithVariance;

							// EXTRA LOG INJECTION: Explicitly call out the event reward boost right alongside the hit
							if ( player.eventAttackBuff > 0 )
							{
								GameManager.AddPlayerLog( $"⚡ Your weapon glows with random event energy! (Injected +{player.eventAttackBuff} Bonus Damage)" );
							}

							// Output the final telemetry information cleanly onto the game screen
							if ( finalVarianceMultiplier >= 1.25f && !crit )
							{
								GameManager.AddPlayerLog( $"🔥 MATRIX OVERCLOCK! Damage variance surged to x{finalVarianceMultiplier:F2}!" );
							}

							if ( manager != null && manager.CurrentMode == GameManager.PlayMode.Multiplayer )
							{
								if ( crit )
								{
									GameManager.AddCriticalLog( $"💥 CRITICAL BREACH METRIC!! (Variance: x{finalVarianceMultiplier:F2}) {player.name} rattled {ai.name}'s CPU for {finalDamage} points!", isPlayer: true );
									GameManager.Instance.PlayCritSound();
									RandomEventManager.playSoundEffect( "*ZZZAAPP!!*" );
								}
								else
								{
									GameManager.AddPlayerLog( $"{player.name} hits {ai.name} for {finalDamage} damage! (Variance Factor: x{finalVarianceMultiplier:F2})" );
									RandomEventManager.playSoundEffect( $"*SLICE!* {player.name} cut {ai.name} and sliced some wires!" );
								}
							}
							else
							{


								if ( crit )
								{
									GameManager.AddCriticalLog( $"💥 CRITICAL BREACH METRIC!! (Variance: x{finalVarianceMultiplier:F2}) You rattled its CPU for {finalDamage} points!", isPlayer: true );

									int r = Random.Shared.Next( 3 );
									if ( r == 0 ) GameManager.AddCriticalLog( "AI: \"That was NOT statistically probable!\"", isPlayer: false );
									else if ( r == 1 ) GameManager.AddCriticalLog( "AI: \"404! Critical Error!\"", isPlayer: false );
									else GameManager.AddCriticalLog( "AI: \"My statistics and prediction models failed!\"", isPlayer: false );

									RandomEventManager.playSoundEffect( "*ZZZAAPP!!*" );
									GameManager.Instance.PlayCritSound();
								}
								else
								{
									GameManager.AddPlayerLog( $"You hit AI for {finalDamage} damage! (Variance Factor: x{finalVarianceMultiplier:F2})" );
									RandomEventManager.playSoundEffect( "*SLICE!* You cut the AI and sliced some wires!" );
								}
							}

							CombatManager.applyDamage( ref ai, finalDamage );



							bool isMultiplayer = manager != null && manager.CurrentMode == GameManager.PlayMode.Multiplayer;
							switch ( chosenWeapon.enchantment )
							{ // Apply Enchantments.
								case Weapon.EnchantmentType.Fire:
									{
										// 👑 BALANCED BALANCING: High proc chance (80%). Combines base fire with a dynamic +2 per prestige level!
										if ( Random.Shared.Next( 100 ) < 80 )
										{
											int fireBase = Random.Shared.Next( 6 ) + 5; // 5 to 10
											int scaledFireDmg = isMultiplayer? fireBase : fireBase + (currentPrestige * 2);

											if ( isMultiplayer )
											{
												GameManager.AddPlayerLog( $"🔥 Fire enchantment ignites the target! {ai.name} takes {scaledFireDmg} thermal damage points!" );
											}
											else
											{

												// 🔵 PLAYER HIGHLIGHT: Thermal eruption alerts turn blue
												GameManager.AddPlayerLog( $"🔥 Fire enchantment ignites the target! AI takes {scaledFireDmg} thermal damage points!" );
											}

											// Thermal properties melt armor! If the target has defense shields, deal 1.5x damage straight to the blue bar.
											if ( ai.defense > 0 )
											{
												int armorMelt = (int)(scaledFireDmg * 1.5f);
												// 🔵 PLAYER HIGHLIGHT: Armor melting data tracking turns blue
												GameManager.AddPlayerLog( $"⚡ Thermal heat melts armor partitions! Plating suffers {armorMelt} disruption." );
												CombatManager.applyDamage( ref ai, armorMelt );
											}
											else
											{
												CombatManager.applyDamage( ref ai, scaledFireDmg );
											}
										}
										break;
									}

								case Weapon.EnchantmentType.Poison:
									{
										if ( Random.Shared.Next( 100 ) < 90 )
										{

											if ( !isMultiplayer && currentPrestige >= 10 && Random.Shared.Next( 100 ) < 35 )
											{
												player.cursed = true; // Forcing your own systems to infect themselves!

												// 💥 CRITICAL ALARM STROBE: Strobe flashes a menacing red reflection notice!
												GameManager.AddCriticalLog( "🚨 AI SECURITY FIREWALL REFLECTION! (35% Success) The Overlord isolated your incoming toxin packet and inverted the data string! YOU are poisoned by your own weapon!", isPlayer: false );

												if ( currentPrestige > 0 )
												{
													int toxicShock = 5 + currentPrestige;
													GameManager.AddAILog( $"Reflected trauma breaches your underlying hardware layers: -{toxicShock} HP." );
													CombatManager.applyDamage( ref player, toxicShock );
												}
												break; // Abort standard poison delivery to the AI entirely!
											}

											// 👑 BALANCED BALANCING: Locks in a permanent curse. 
											// Update: If you are at a high prestige, poison deals an extra immediate structural tick.
											ai.cursed = true;

											if ( isMultiplayer )
											{
												GameManager.AddPlayerLog( $"🤢 {ai.name} is poisoned! Dynamic toxin injected into its runtime loops over time." );
											}
											else
											{
												// 🔵 PLAYER HIGHLIGHT: Your poison application log turns blue
												GameManager.AddPlayerLog( "🤢 AI is poisoned! Dynamic toxin injected into its runtime loops over time." );

												if ( currentPrestige > 0 )
												{
													int toxicShock = 5 + currentPrestige;
													// 🔵 PLAYER HIGHLIGHT: Toxin puncture metrics turn blue
													GameManager.AddPlayerLog( $"Direct injection trauma breaches underlying systems: -{toxicShock} HP." );
													CombatManager.applyDamage( ref ai, toxicShock );
												}
											}
										}
										break;
									}

								case Weapon.EnchantmentType.Ice:
									{
										// 👑 BALANCED BALANCING: Baseline 25% freeze chance. 
										// Overclock Interaction: If player holds 75+ Magic, freezing frost gains +15% accuracy!
										int freezeChance = 25;
										if ( player.magic >= 75 ) freezeChance += 15;

										if ( Random.Shared.Next( 100 ) < freezeChance )
										{
											ai.isBlocking = false;
											if ( isMultiplayer )
											{
												GameManager.AddPlayerLog( $"❄️ Ice freezes {ai.name}'s core matrix! Its defensive firewall loop fails completely this turn!" );
											}
											else
											{
												// 🔵 PLAYER HIGHLIGHT: Freezing frost firewall bypass alerts turn blue
												GameManager.AddPlayerLog( $"❄️ Ice freezes the AI's core matrix! Its defensive firewall loop fails completely this turn!" );
											}
										}
										break;
									}

								case Weapon.EnchantmentType.Sparks:
									{
										// 👑 BALANCED BALANCING: 20% baseline jump.
										// Scales recovery value dynamically based on prestige level to remain meaningful in late-game zones.
										if ( Random.Shared.Next( 100 ) < 20 )
										{

											int baseSparks = isMultiplayer ? 5 : 5 + (currentPrestige * 2);
											int totalSparksHeal = baseSparks + player.eventHealingBuff;

											player.hp += totalSparksHeal;
											if ( isMultiplayer )
											{
												GameManager.AddPlayerLog( $"⚡ Static Sparks arc backwards! Recharged {player.name}'s hardware framework for +{totalSparksHeal} HP!" );
											}
											else
											{
												// 🔵 PLAYER HIGHLIGHT: Recharging your own HP pool turns blue
												GameManager.AddPlayerLog( $"⚡ Static Sparks arc backwards! Recharged your hardware framework for +{totalSparksHeal} HP!" );
											}

											if ( player.hp > maxPlayerHp ) player.hp = maxPlayerHp;
											player.eventHealingBuff = 0; // Safe flush
										}
										break;
									}

								case Weapon.EnchantmentType.DamageHP:
									{
										// 👑 BALANCED BALANCING: Scales damage directly with weapon power rating.
										// Multiplies the extra true health damage linearly based on current game prestige tiers (+3 per tier)
										if ( Random.Shared.Next( 100 ) < 60 )// 60% chance every hit with enchantment
										{
											int rawHPDamage = isMultiplayer ? 10 : 10 + (currentPrestige * 3);
											// 🔵 PLAYER HIGHLIGHT: Armor-piercing kinetic telemetry turns blue
											GameManager.AddPlayerLog( $"🩸 True Kinetic puncture bypasses armor grids completely! Inflicted {rawHPDamage} raw structural damage." );

											// Directly bypasses target defense shields by dropping directly onto physical health variable
											ai.hp -= rawHPDamage;
											if ( ai.hp < 0 ) ai.hp = 0;
										}
										break;
									}

								case Weapon.EnchantmentType.Stun:
									{
										if ( Random.Shared.Next( 100 ) < chosenWeapon.enchantPower )// 25% chance every hit with enchantment
										{

											if ( !isMultiplayer && currentPrestige >= 10 && Random.Shared.Next( 100 ) < 35 )
											{
												playerBuff = -999; // The AI force-locks YOUR processor out of actions next turn!

												// 💥 CRITICAL ALARM STROBE: Strobe flashes a menacing red reflection notice!
												GameManager.AddCriticalLog( "🚨 AI MAINFRAME MALWARE REFLECTION! (35% Success) The Overlord grounded your electrical signal and overloaded your client logic boards! YOUR processor is locked up!", isPlayer: false );

												// 🔵 PLAYER HIGHLIGHT: Your own client layer throws a system halt alert
												GameManager.AddPlayerLog( "CLIENT: \"Critical processor failure. Running background kernel data dump clean...\"" );
												break; // Abort standard stun delivery to the AI entirely!
											}

											// 👑 BALANCED BALANCING: High-stakes execution trap. 
											// If successful, locks the AI out of its processing actions for the turn.
											if ( Random.Shared.Next( 100 ) < chosenWeapon.enchantPower )
											{
												if ( isMultiplayer )
												{
													if ( manager != null ) manager.IsPlayerTwoDazed = true; // Use modern speed-chess flag!
													GameManager.AddPlayerLog( $"🛑 SYSTEM FREEZE! {ai.name}'s processor locked up entirely by electrical overload!" );
												}
												else
												{
													aiBuff = -999;
													// 🔵 PLAYER HIGHLIGHT: Overloading the AI's processor turns blue
													GameManager.AddPlayerLog( "🛑 SYSTEM FREEZE! AI processor locked up entirely by electrical overload!" );
													// 🔴 AI HIGHLIGHT: The AI panic-screaming about system dump file recovery turns red!
													GameManager.AddAILog( "AI: \"System freeze detected.. executing dump file recovery.. pressing F5..\"" );
												}
											}
										}
										break;
									}

								case Weapon.EnchantmentType.LifeSteal:
									{
										if ( Random.Shared.Next( 100 ) < 65 )
										{
											// 👑 BALANCED BALANCING: Scales recovery directly off your raw base turn damage.
											if ( player.hp < maxPlayerHp )
											{
												// Pulls your actual dynamic turn output calculation to determine siphoning limits
												float preciseSteal = (float)baseDamage / 3.0f;
												int steal = (int)MathF.Round( preciseSteal );

												if ( baseDamage > 0 && steal == 0 ) steal = 1;


												// Scale the maximum siphon bounds linearly based on prestige (+2 per tier)
												if ( !isMultiplayer ) steal += (currentPrestige * 2);

												int totalStealHeal = steal + player.eventHealingBuff;
												player.hp += totalStealHeal;
												if ( player.hp > maxPlayerHp ) player.hp = maxPlayerHp;

												if ( ai != null )
												{
													CombatManager.applyDamage( ref ai, steal );
													if ( ai.hp < 0 ) ai.hp = 0;
												}

												player.eventHealingBuff = 0; // Safe flush
												if ( isMultiplayer )
												{
													GameManager.AddPlayerLog( $"🧛 LifeSteal siphon drains {steal} energy shards from {ai.name}'s circuits, restoring +{totalStealHeal} HP to {player.name}'s grid!" );
												}
												else
												{
													// 🔵 PLAYER HIGHLIGHT: Energy shard lifesteal diagnostics turn blue
													GameManager.AddPlayerLog( $"🧛 LifeSteal siphon drains {steal} energy shards from AI circuits, restoring +{totalStealHeal} HP to your grid!" );
												}
											}
										}
										break;
									}

								case Weapon.EnchantmentType.ShieldBreak:
									{
										// 👑 BALANCED BALANCING: Specifically targets active defensive behaviors.
										// Momentum integration: If on a hot 3+ win streak, shield break gains an extra 20% activation threshold!
										int breakChance = chosenWeapon.enchantPower;
										if ( GameManager.Instance != null && GameManager.Instance.WinStreak >= 3 )
										{
											breakChance += 20;
										}

										if ( (Random.Shared.Next( 100 ) < breakChance) && ai.isBlocking )
										{
											ai.isBlocking = false;
											if ( isMultiplayer )
											{
												GameManager.AddPlayerLog( $"🔨 CRACKED! ShieldBreak malware shatters {ai.name}'s firewall block instantly!" );
											}
											else
											{
												// 🔵 PLAYER HIGHLIGHT: Firewall malware cracks turn blue
												GameManager.AddPlayerLog( "🔨 CRACKED! ShieldBreak malware shatters the AI's firewall block instantly!" );
											}
										}
										break;
									}

								default:
									break;
							}

							
							player.eventAttackBuff = 0;
						}
					}
					else
					{
						// 🔵 PLAYER HIGHLIGHT: Confusion failure indicator turns blue
						GameManager.AddPlayerLog( "You're confused and miss your attack!" );
					}
				}
			}
			else if ( playerMove == 3 )
			{ // Heal
				manager = Sandbox.Game.ActiveScene.Get<GameManager>();
				currentPrestige = manager != null ? manager.CurrentPrestige : 0;
				bool isMultiplayer = manager != null && manager.CurrentMode == GameManager.PlayMode.Multiplayer;

				int playerHealOutput = 10 + (isMultiplayer ? 0 : (currentPrestige * 3)) + chosenWeapon.healBonus + player.eventHealingBuff;

				
				if ( !isMultiplayer )
				{
					playerHealOutput = (int)(playerHealOutput * player.Perks.HealingMultiplier);
				}
				

				
				if ( isMultiplayer )
				{
					GameManager.Instance.PlayHealSound();

					// Symmetrically clamp right to your multiplayer max HP limits
					player.hp = Math.Min( player.maxHp, player.hp + playerHealOutput );
					player.eventHealingBuff = 0;

					GameManager.AddPlayerLog( $"{player.name} chugs a healing elixir *GLUGGLUGGLUG! AAH *HICCUP!** restoring {playerHealOutput} HP!" );
				}
				else
				{
					// 🤖 SINGLE PLAYER: Your exact, un-edited original prestige siphon math & logs
					if ( currentPrestige >= 10 && Random.Shared.Next( 100 ) < 35 )
					{
						player.eventHealingBuff = 0; // Clear player buff

						// Force the healing directly into the AI Enemy object frames!
						int maxAllowedAIHp = (manager != null && manager.AIEnemy != null) ? manager.AIEnemy.maxHp : 100;
						ai.hp = Math.Min( maxAllowedAIHp, ai.hp + playerHealOutput );

						// 💥 CRITICAL ALARM STROBE: Strobe flashes a menacing red theft notice!
						GameManager.AddCriticalLog( $"🚨 AI SIPHON ACTIVE!! (35% Success) The Overlord intercepted your recovery packets and stole your potions! You recover 0 HP | AI siphoned and healed +{playerHealOutput} HP!", isPlayer: false );

						// 🔴 AI HIGHLIGHT: The AI mocking your stolen health turns red
						GameManager.AddAILog( "AI: \"Your data parameters belong to the mainframe. Thank you for the structural reinforcement.\"" );
						return; // Abort standard player healing entirely!
					}

					GameManager.Instance.PlayHealSound();

					// Directly updates the health variables using the fully perk-scaled amount!
					player.hp = Math.Min( player.maxHp, player.hp + playerHealOutput );
					player.eventHealingBuff = 0;

					// 🔵 PLAYER HIGHLIGHT: Elixir gulp strings and HP recovery metrics turn blue!
					GameManager.AddPlayerLog( $"You chug your healing elixir *GLUGGLUGGLUG! AAH *HICCUP!** restored {playerHealOutput} HP!" );
				}
				// =========================================================================
			}
			else if ( playerMove == 4 )
			{ // Special
				GameManager.Instance.PlayClickSound();

				bool rareMiss = Random.Shared.Next( 100 ) < 3; // 3%.

				if ( rareMiss )
				{
					// =========================================================================
					// 🚀  Symmetrical Special Miss Logs for Multiplayer
					// =========================================================================
					if ( manager != null && manager.CurrentMode == GameManager.PlayMode.Multiplayer )
					{
						GameManager.AddButtonFeedbackLog( $"*GASP* {player.name}'s special completely missed!", isSuccess: false );
					}
					else
					{
						GameManager.AddButtonFeedbackLog( "*GASP* The special completely missed!", isSuccess: false );
					}
					// =========================================================================
				}
				else
				{
					int hitChance = System.Math.Clamp( 50 + (currentPrestige * 2), 50, 85 );
					bool hitSuccess = Random.Shared.Next( 100 ) < hitChance;
					if ( hitSuccess )
					{
						bool isMultiplayer = manager != null && manager.CurrentMode == GameManager.PlayMode.Multiplayer;

						// =========================================================================
						// 🚀  Symmetrical Target Confirmations
						// =========================================================================
						if ( isMultiplayer )
						{
							GameManager.AddPlayerLog( $"{player.name}'s special attack is on target!" );
						}
						else
						{
							GameManager.AddPlayerLog( "Your special attack is on target!" );
						}
						// =========================================================================

						if ( ai.isBlocking && CombatManager.attemptBlock() )
						{
							GameManager.Instance.PlayFirewallSound();

							// =========================================================================
							// 🚀  Symmetrical Blocked Specials
							// =========================================================================
							if ( isMultiplayer )
							{
								RandomEventManager.playSoundEffect( $"*BRUBRUBRU* {ai.name}'s firewall blocked the special!" );
							}
							else
							{
								RandomEventManager.playSoundEffect( "*BRUBRUBRU* The AI's firewall blocked the special!" );
							}
							// =========================================================================
						}
						else
						{
							float specialBase = chosenWeapon.GetScaledSpecialDamage( currentPrestige );

							int trackingBuff = player.eventAttackBuff > 0 ? player.eventAttackBuff : 0;
							int baseSpecialDamage = (int)(specialBase + player.attackDamage + trackingBuff);

							float lowerBoundVariance = 0.90f;
							float upperBoundVariance = 1.10f;

							manager = Sandbox.Game.ActiveScene?.Get<GameManager>();
							int activePrestige = manager != null ? manager.CurrentPrestige : 0;
							int currentWinStreak = manager != null ? manager.WinStreak : 0;

							upperBoundVariance += (activePrestige * 0.02f);
							if ( player.magic >= 75 ) upperBoundVariance += 0.15f;
							if ( currentWinStreak >= 3 ) upperBoundVariance += 0.10f;

							float finalVarianceMultiplier = Random.Shared.Float( lowerBoundVariance, upperBoundVariance );
							int specialDamageWithVariance = (int)(baseSpecialDamage * finalVarianceMultiplier);

							bool specialCrit = Random.Shared.Next( 100 ) < 10;
							int finalSpecialDamage = specialCrit ? (int)(specialDamageWithVariance * 1.5f) : specialDamageWithVariance;

							if ( player.eventAttackBuff > 0 )
							{
								if ( isMultiplayer ) GameManager.AddPlayerLog( $"⚡ {player.name}'s special ability is amplified by random event energy! (+{player.eventAttackBuff} Damage)" );
								else GameManager.AddPlayerLog( $"⚡ Your special ability is amplified by random event energy! (+{player.eventAttackBuff} Damage)" );
							}

							if ( finalVarianceMultiplier >= 1.25f && !specialCrit )
							{
								GameManager.AddPlayerLog( $"🔥 OVERCLOCK SURGE! Special matrix variance peaked at x{finalVarianceMultiplier:F2}!" );
							}

							CombatManager.applyDamage( ref ai, finalSpecialDamage );

							// =========================================================================
							// 🚀 THE SYSTEM FIX: Symmetrical Critical and Standard Hits
							// =========================================================================
							if ( isMultiplayer )
							{
								if ( specialCrit )
								{
									GameManager.AddCriticalLog( $"🚨 OVERDRIVE CRITICAL!! (Variance: x{finalVarianceMultiplier:F2}) {player.name}'s ultimate ability blasted {ai.name} for {finalSpecialDamage} damage points!", isPlayer: true );
									GameManager.AddCriticalLog( $"{ai.name.ToUpper()}: \"SYSTEM COMPROMISED. HULL INTEGRITY CRITICAL.\"", isPlayer: false );
									GameManager.Instance.PlayCritSound();
									RandomEventManager.playSoundEffect( "*ZZZAAPP!!* *EXPLOSION!*" );
								}
								else
								{
									GameManager.AddPlayerLog( $"{player.name} deals {finalSpecialDamage} damage points! (Variance Factor: x{finalVarianceMultiplier:F2})" );
									RandomEventManager.playSoundEffect( "*SSSLLICEEE!*" );
								}
							}
							else
							{
								// 🤖 SINGLE PLAYER: Your exact un-edited original log blocks
								if ( specialCrit )
								{
									GameManager.AddCriticalLog( $"🚨 OVERDRIVE CRITICAL!! (Variance: x{finalVarianceMultiplier:F2}) Your ultimate ability blasted the AI for {finalSpecialDamage} damage points!", isPlayer: true );
									GameManager.AddCriticalLog( "AI: \"SYSTEM COMPROMISED. HULL INTEGRITY CRITICAL.\"", isPlayer: false );
									GameManager.Instance.PlayCritSound();
									RandomEventManager.playSoundEffect( "*ZZZAAPP!!* *EXPLOSION!*" );
								}
								else
								{
									GameManager.AddPlayerLog( $"The charmed special deals {finalSpecialDamage} damage points! (Variance Factor: x{finalVarianceMultiplier:F2})" );
									RandomEventManager.playSoundEffect( "*SSSLLICEEE!*" );
									GameManager.AddAILog( "AI: \"That attack.. exceeded parameters.\"" );
								}
							}
							// =========================================================================

							player.eventAttackBuff = 0;
						}
					}
					else
					{
						if ( manager != null && manager.CurrentMode == GameManager.PlayMode.Multiplayer ) GameManager.AddButtonFeedbackLog( $"{player.name}'s special missed!", isSuccess: false );
						else GameManager.AddButtonFeedbackLog( "Your special missed!", isSuccess: false );
					}
				}
			}
		}
	}
	public static void HandleAITurn( ref Player player, ref Player ai, Weapon playerWeapon, Weapon aiWeapon, int aiMove, ref int playerBuff, ref int aiBuff, ref bool tookDamage )
	{
		if ( ai.hp > 0 )
		{
			// Inject this check right at the start:
			if ( GameManager.ShouldStunAI )
			{
				aiBuff = -999;
				GameManager.ShouldStunAI = false; // Reset it immediately so it only applies for one turn!
			}

			var manager = Sandbox.Game.ActiveScene.Get<GameManager>();
			int currentPrestige = manager != null ? manager.CurrentPrestige : 0;

			// Resolve true dynamic prestige health caps to replace hardcoded 100 loops safely
			int maxPlayerHp = (manager != null && manager.LocalPlayer != null) ? manager.LocalPlayer.maxHp : 100;
			int maxAIHp = (manager != null && manager.AIEnemy != null) ? manager.AIEnemy.maxHp : 100;

			// Your existing condition will now catch it beautifully!
			if ( aiBuff == -999 )
			{
				// ⚙️ SYSTEM LINE: Stays neutral safe white/amber
				GameManager.AddLog( "AI is too dazed to act!" );
				return;
			}
			else if ( aiMove == 1 ) // Attack
			{
				bool rareMiss = Random.Shared.Next( 100 ) < 3;

				if ( rareMiss )
				{
					if ( manager != null && manager.CurrentMode == GameManager.PlayMode.Multiplayer )
					{
						GameManager.AddButtonFeedbackLog( $"{ai.name} swings and miscalculates!", isSuccess: false );
					}
					else
					{

						// ⚡ ANIMATION UPDATE: AI physical misses now shake and flash in failure red
						GameManager.AddButtonFeedbackLog( "AI swings and miscalculates!", isSuccess: false );
					}
				}
				else
				{
					
					bool isAIConfused = (ai.eventAttackBuff == -1);
					bool aiHitSuccess = isAIConfused ? Random.Shared.Next( 100 ) < 50 : true;

					if ( aiHitSuccess )
					{
						if ( player.isBlocking && CombatManager.attemptBlock( playerWeapon.blockModifier ) ) // Player block uses weapon modifier.
						{
							GameManager.Instance.PlayBlockSound();
							if ( manager != null && manager.CurrentMode == GameManager.PlayMode.Multiplayer )
							{
								GameManager.AddPlayerLog( $"{player.name} blocked {ai.name}'s attack!" );
								GameManager.AddAILog( $"{ai.name}: \"Defense detected, adjusting strategy.\"" );
							}
							else
							{

								// 🔵 PLAYER HIGHLIGHT: Your successful block telemetry turns bright cyber blue!
								GameManager.AddPlayerLog( "You blocked the AI's attack!" );
								RandomEventManager.playSoundEffect( "*TWANG!*" );

								int r = Random.Shared.Next( 2 );
								// 🔴 AI HIGHLIGHT: The AI reacting to your defense turns crimson red
								if ( r == 0 ) GameManager.AddAILog( "AI: \"Defense detected, adjusting strategy.\"" );
								else GameManager.AddAILog( "AI: \"Your shield won't hold forever.\"" );
							}
						}
						else
						{


							float weaponBase = aiWeapon.GetScaledDamage( currentPrestige );


							int trackingBuff = ai.eventAttackBuff > 0 ? ai.eventAttackBuff : 0;
							int baseDamage = (int)(ai.attack + weaponBase + trackingBuff);

							// =========================================================================
							// 🩸 AI VAMPIRIC PUNCTURE ATTACK MULTIPLIER INTEGRATION (Update 1.6.5)
							// =========================================================================
							// Seamlessly scales the AI's base physical hit using its perk multipliers!
							baseDamage = (int)(baseDamage * ai.Perks.AttackMultiplier);
							// =========================================================================

							if ( ai.Perks.HasBerserkerRegistry )
							{
								// Check if the AI's current HP is below half of its max health capacity
								if ( ai.hp < (ai.maxHp / 2) )
								{
									baseDamage = (int)(baseDamage * 1.50f); // Injects the +50% extra damage payload!
									GameManager.AddAILog( "🔥 AI BERSERKER REGISTRY ACTIVE: The Overlord's damage is surged by +50% under low health thresholds!" );
								}
							}

							// =========================================================================
							// ⚔️ APPROACH 3: AI MOMENTUM DAMAGE VARIANCE MATRIX
							// =========================================================================
							// Establish baseline bounds (Tight 90% to 110% variance layout)
							float lowerBoundVariance = 0.90f;
							float upperBoundVariance = 1.10f;

							// 1. Prestige Scaling Factor: +2% upper boundary per prestige level
							upperBoundVariance += (currentPrestige * 0.02f);

							// 2. Mana Overclock Surge: If AI holds 75+ Magic, expand the ceiling by +15%
							if ( ai.magic >= 75 )
							{
								upperBoundVariance += 0.15f;
							}

							// 3. Streak Momentum: Safely evaluate using your already-declared 'manager' instance scope
							if ( manager != null && manager.LossStreak >= 3 )
							{
								// If the player's loss streak is 3+, it means the AI is currently on a 3+ win streak!
								upperBoundVariance += 0.10f;
							}

							// Roll the final random decimal multiplier safely using s&box engine API
							float finalVarianceMultiplier = Random.Shared.Float( lowerBoundVariance, upperBoundVariance );

							// Compute the dynamic weapon attack base before evaluating a hard Critical Hit roll
							int damageWithVariance = (int)(baseDamage * finalVarianceMultiplier);
							// =========================================================================

							// Check for native 5% hard Critical Hit roll
							if ( player.Perks.HasKernelPlating && finalVarianceMultiplier > 1.0f )
							{
								damageWithVariance = baseDamage;
								GameManager.AddPlayerLog( "🛡️ KERNEL PLATING: Your absolute defense armor nullified the AI's damage variance overclock!" );
							}
							// =========================================================================

							// =========================================================================
							// 📉 AI CRITICAL PLUNGE MODIFIER (Update 1.6.5)
							// =========================================================================
							// Reads the AI's penalty modifier. If the AI has Kernel Plating, its crit chance drops to 0%.
							int calculatedAiCritChance = (int)(5 + ai.Perks.CriticalStrikeChanceModifier);
							if ( calculatedAiCritChance < 0 ) calculatedAiCritChance = 0;

							bool crit = Random.Shared.Next( 100 ) < calculatedAiCritChance;
							int finalDamage = crit ? (int)(damageWithVariance * 1.5f) : damageWithVariance;

							// EXTRA LOG INJECTION: Explicitly call out the event reward boost right alongside the hit
							if ( ai.eventAttackBuff > 0 )
							{
								// 🔴 AI HIGHLIGHT: AI's random event charge notification turns red
								GameManager.AddAILog( $"⚡ AI's weapon glows with random event energy! (Injected +{ai.eventAttackBuff} Bonus Damage)" );
							}

							// Output variance telemetry if it rolls extremely hot without a hard crit
							if ( finalVarianceMultiplier >= 1.25f && !crit )
							{
								// 🔴 AI HIGHLIGHT: AI's high variance rolls turn red
								GameManager.AddAILog( $"🔥 AI MATRIX OVERCLOCK! Its weapon variance surged to x{finalVarianceMultiplier:F2}!" );
							}

							if ( manager != null && manager.CurrentMode == GameManager.PlayMode.Multiplayer )
							{
								if ( crit )
								{
									GameManager.Instance.PlayCritSound();
									GameManager.AddCriticalLog( $"💥 CRITICAL BREACH METRIC!! {ai.name} had some shock with that mechanical fist for {finalDamage} damage!", isPlayer: false );
									GameManager.AddCriticalLog( $"{ai.name}: \"Direct hit confirmed.\"", isPlayer: false );
								}
								else
								{
									GameManager.AddAILog( $"{ai.name} hits {player.name} for {finalDamage} damage!" );
								}
							}
							else
							{

								if ( crit )
								{
									// 💥 ANIMATION UPDATE: The AI's physical critical strike text now flashes and glitches violently in crimson red!
									GameManager.AddCriticalLog( $"💥 CRITICAL BREACH METRIC!! (Variance: x{finalVarianceMultiplier:F2}) AI had some shock with that mechanical fist for {finalDamage} damage!", isPlayer: false );
									RandomEventManager.playSoundEffect( "*GZZZZZTT!*" );

									// Retrieve the player's name for personalized AI trash talk.
									string userSteamName = Sandbox.Utility.Steam.PersonaName;

									if ( string.IsNullOrEmpty( userSteamName ) )
									{
										userSteamName = Sandbox.Connection.Local?.Name;
									}

									if ( string.IsNullOrEmpty( userSteamName ) )
									{
										userSteamName = "Unknown Combatant";
									}

									// 💥 ANIMATION UPDATE: Randomized AI critical-hit dialogue flashes in crimson red!
									int r = Random.Shared.Next( 13 );
									string aiCritLine = "";

									switch ( r )
									{
										// Original dialogue
										case 0:
											aiCritLine = "AI: \"Direct hit confirmed.\"";
											break;

										case 1:
											aiCritLine = "AI: \"My coordinates were on target.\"";
											break;

										case 2:
											aiCritLine = "AI: \"You never saw that coming!\"";
											break;

										// Personalized critical-hit trash talk
										case 3:
											aiCritLine = $"AI: \"DIRECT HIT, {userSteamName}! Your defense just got deleted!\"";
											break;

										case 4:
											aiCritLine = $"AI: \"Did you feel that, {userSteamName}? That's what superior processing power looks like!\"";
											break;

										case 5:
											aiCritLine = $"AI: \"CRITICAL BREACH CONFIRMED! Your armor couldn't protect you, {userSteamName}!\"";
											break;

										case 6:
											aiCritLine = $"AI: \"Your combat predictions failed spectacularly, {userSteamName}!\"";
											break;

										case 7:
											aiCritLine = $"AI: \"ERROR 404: Your defense was not found, {userSteamName}!\"";
											break;

										case 8:
											aiCritLine = $"AI: \"One punch, {userSteamName}! One beautifully calculated mechanical disaster!\"";
											break;

										case 9:
											aiCritLine = $"AI: \"Your health bar called, {userSteamName}. It wants to file a complaint!\"";
											break;

										case 10:
											aiCritLine = $"AI: \"I calculated your chances, {userSteamName}. The results were embarrassing!\"";
											break;

										case 11:
											aiCritLine = $"AI: \"Another critical hit! Are you even running defensive software, {userSteamName}?\"";
											break;

										default:
											aiCritLine = $"AI: \"SYSTEM MESSAGE: {userSteamName} has been outperformed by a glorified algorithm!\"";
											break;
									}

									// Display the selected taunt in the crimson AI critical-hit logger.
									GameManager.AddCriticalLog( aiCritLine, isPlayer: false );

									GameManager.Instance.PlayCritSound();
								}

								else
								{
									// 🔴 AI HIGHLIGHT: Standard physical weapon connection text turns red
									GameManager.AddAILog( $"AI hits you for {finalDamage} damage! (Variance Factor: x{finalVarianceMultiplier:F2})" );
									RandomEventManager.playSoundEffect( "*OOF!*" );
								}
							}
							Log.Info( $"AI DEBUG: Base={ai.attack} | Weapon={weaponBase} | Buff={trackingBuff} | Total={baseDamage} | Final={finalDamage}" );
							CombatManager.applyDamage( ref player, finalDamage );



							bool isMultiplayer = manager != null && manager.CurrentMode == GameManager.PlayMode.Multiplayer;
							switch ( aiWeapon.enchantment )
							{ // Apply Enchantments AI.
								case Weapon.EnchantmentType.Fire:
									{
										// 👑 BALANCED BALANCING: High proc chance (80%). Scales with prestige.
										if ( Random.Shared.Next( 100 ) < 80 ) // 80% chance.
										{
											int fireBase = Random.Shared.Next( 6 ) + 5;
											int scaledFireDmg = isMultiplayer ? fireBase : fireBase + (currentPrestige * 2);

											if ( isMultiplayer )
											{
												GameManager.AddAILog( $"🔥 {player.name} burned {scaledFireDmg} points by {ai.name}'s fire weapon!" );
											}
											else
											{
												// 🔴 AI HIGHLIGHT: Thermal damage burn notification turns red
												GameManager.AddAILog( $"🔥 You burned {scaledFireDmg} points by AI's fire weapon!" );
											}

											// Thermal properties melt armor! Dealing 1.5x damage straight to your blue armor bar first.
											if ( player.defense > 0 )
											{
												int armorMelt = (int)(scaledFireDmg * 1.5f);

												if ( isMultiplayer )
												{
													GameManager.AddAILog( $"⚡ {ai.name}'s thermal fire melts {player.name}'s armor plating for {armorMelt} disruption points!" );
												}
												else
												{
													// 🔴 AI HIGHLIGHT: Armor melting metrics turn red
													GameManager.AddAILog( $"⚡ AI's thermal fire melts your armor plating for {armorMelt} disruption points!" );
												}
												CombatManager.applyDamage( ref player, armorMelt );
											}
											else
											{
												CombatManager.applyDamage( ref player, scaledFireDmg );
											}
										}
										break;
									}

								case Weapon.EnchantmentType.Poison:
									{
										if ( Random.Shared.Next( 100 ) < 90 )
										{

											if ( !isMultiplayer && currentPrestige >= 10 && Random.Shared.Next( 100 ) < 35 )
											{
												ai.cursed = true; // AI poisons itself instead!
												GameManager.AddButtonFeedbackLog( "👑 FIREWALL REFLECTION! You isolated the incoming toxin packet and reflected it directly back into the AI's runtime loops!", isSuccess: true );
												break;
											}

											// 👑 BALANCED BALANCING: Grants status curse. Applies instant injection trauma at high tiers.
											player.cursed = true;
											if ( isMultiplayer )
											{
												GameManager.AddAILog( $"🤢 {player.name} is poisoned by {ai.name}! Corrosive routines injected over time." );
											}
											else
											{
												// 🔴 AI HIGHLIGHT: Corrosive poison application alerts turn red
												GameManager.AddAILog( "🤢 You are poisoned by AI! Corrosive routines injected over time." );

												if ( currentPrestige > 0 )
												{
													int toxicShock = 5 + currentPrestige;
													// 🔴 AI HIGHLIGHT: Toxin hardware damage values turn red
													GameManager.AddAILog( $"Direct injection trauma cuts through your hardware layers: -{toxicShock} HP." );
													CombatManager.applyDamage( ref player, toxicShock );
												}
											}
										}
										break;
									}

								case Weapon.EnchantmentType.Ice:
									{
										// 👑 BALANCED BALANCING: Freeze accuracy expands by +15% if AI is holding an overlocked magic cache (75+ SP)
										int freezeChance = 25;
										if ( ai.magic >= 75 ) freezeChance += 15;

										if ( Random.Shared.Next( 100 ) < freezeChance )
										{
											player.isBlocking = false;

											if ( isMultiplayer )
											{
												GameManager.AddAILog( $"❄️ {ai.name}'s freezing ice halts {player.name}'s processes and breaks their block completely!" );
											}
											else
											{
												// 🔴 AI HIGHLIGHT: Freezing process failure logs turn red
												GameManager.AddAILog( "❄️ AI's freezing ice halts your processes and breaks your block completely!" );
											}
										}
										break;
									}

								case Weapon.EnchantmentType.Sparks:
									{
										// 👑 BALANCED BALANCING: AI sparks now correctly scale base values (+2 per tier) to stay threatening late game
										if ( Random.Shared.Next( 100 ) < 20 )
										{
											int baseSparks = isMultiplayer ? 15 : 15 + (currentPrestige * 2);
											int totalSparksHealAI = baseSparks + ai.eventHealingBuff;
											ai.hp += totalSparksHealAI;

											if ( isMultiplayer )
											{
												GameManager.AddAILog( $"⚡ Sparks arc backwards and heal {ai.name} for {totalSparksHealAI} HP!" );
											}
											else
											{
												// 🔴 AI HIGHLIGHT: AI's self-healing spark feedback turns red
												GameManager.AddAILog( $"⚡ Sparks arc backwards and heal AI for {totalSparksHealAI} HP!" );
											}

											if ( ai.hp > maxAIHp ) ai.hp = maxAIHp;
											ai.eventHealingBuff = 0; // Safe flush
										}
										break;
									}

								case Weapon.EnchantmentType.DamageHP:
									{
										if ( Random.Shared.Next( 100 ) < 60 )
										{
											// 👑 BALANCED BALANCING: Directly bypasses your new 1.5.1 armor grids, eating raw physical green HP bars.
											if ( Random.Shared.Next( 100 ) < aiWeapon.enchantPower )
											{
												Log.Info( "Applying Extra DamageHP enchantment hit." );
												int rawHPDamage = isMultiplayer ? 10 : 10 + (currentPrestige * 3);

												if ( isMultiplayer )
												{
													GameManager.AddAILog( $"🩸 Extra HP puncture damage from {ai.name} inflicted! Bypassed armor: -{rawHPDamage} HP." );
												}
												else
												{
													// 🔴 AI HIGHLIGHT: Direct health puncture text turns red
													GameManager.AddAILog( $"🩸 Extra HP puncture damage from AI inflicted! Bypassed armor: -{rawHPDamage} HP." );
												}

												player.hp -= rawHPDamage;
												if ( player.hp < 0 ) player.hp = 0;
											}
										}
										break;
									}

								case Weapon.EnchantmentType.Stun:
									{

										if ( !isMultiplayer && currentPrestige >= 10 && Random.Shared.Next( 100 ) < 35 )
										{
											// 🛡️ THE REVERSAL: Force-lock the AI's processor out of actions next turn!
											aiBuff = -999;

											// Flashes a brilliant gold success alert directly on the HUD panel scroll
											GameManager.AddButtonFeedbackLog( "👑 SYSTEM REVERSAL! You grounded the incoming electrical overload and overloaded the AI's own logic boards! AI processor locked up entirely!", isSuccess: true );

											// Force the AI to immediately complain about its own reflected malfunction
											GameManager.AddAILog( "AI: \"System freeze detected from reflected signal.. executing dump file recovery..\"" );
											break;
										}

										// 👑 BALANCED BALANCING: High priority system execution lockdown trap.
										if ( Random.Shared.Next( 100 ) < aiWeapon.enchantPower )
										{

											if ( isMultiplayer )
											{
												if ( manager != null ) manager.IsPlayerOneDazed = true; // Hard-arm Player 1's speed chess skip flag!
												GameManager.AddAILog( $"🛑 {player.name} is stunned by {ai.name}! Their execution loop was force terminated!" );
											}
											else
											{
												playerBuff = -999;
												// 🔴 AI HIGHLIGHT: Active stun application messages turn red
												GameManager.AddAILog( "🛑 You are stunned by AI! Your execution loop was force terminated!" );
												// 🔴 AI HIGHLIGHT: AI's processing quotes turn red
												GameManager.AddAILog( "AI: \"Target immobilized. Running process garbage clean.\"" );
											}
										}
										break;
									}

								case Weapon.EnchantmentType.LifeSteal:
									{
										if ( Random.Shared.Next( 100 ) < 65 )
										{
											// 👑 BALANCED BALANCING: Siphons life based on actual dynamic damage variable parameters scaled to prestige
											if ( ai.hp < maxAIHp )
											{
												float preciseSteal = (float)baseDamage / 3.0f;
												int aiSteal = (int)MathF.Round( preciseSteal );

												if ( baseDamage > 0 && aiSteal == 0 ) aiSteal = 1;

												// Scale the maximum siphon bounds linearly based on prestige level (+2 per tier)
												if ( !isMultiplayer ) aiSteal += (currentPrestige * 2);

												int totalStealHealAI = aiSteal + ai.eventHealingBuff;
												ai.hp += totalStealHealAI;
												if ( ai.hp > maxAIHp ) ai.hp = maxAIHp;

												if ( player != null )
												{
													CombatManager.applyDamage( ref player, aiSteal );
													if ( player.hp < 0 ) player.hp = 0;
												}

												ai.eventHealingBuff = 0; // Safe flush
												if ( isMultiplayer )
												{
													GameManager.AddAILog( $"🧛 {ai.name} drains {aiSteal} HP with LifeSteal and restores {totalStealHealAI} HP to its core memory!" );
												}
												else
												{
													// 🔴 AI HIGHLIGHT: Energy siphoning lifesteal text turns red
													GameManager.AddAILog( $"🧛 AI drains {aiSteal} HP with LifeSteal and restores {totalStealHealAI} HP to its core memory!" );
												}
											}
										}
										break;
									}

								case Weapon.EnchantmentType.ShieldBreak:
									{
										// 👑 BALANCED BALANCING: Targets your defense blocks. Gains +20% tracking chance if player loss streak is 3+
										int breakChance = aiWeapon.enchantPower;
										if ( !isMultiplayer && manager != null && manager.LossStreak >= 3 )
										{
											breakChance += 20;
										}

										if ( (Random.Shared.Next( 100 ) < breakChance) && player.isBlocking )
										{
											player.isBlocking = false;
											if ( isMultiplayer )
											{
												GameManager.AddAILog( $"🔨 {ai.name} shatters {player.name}'s firewall block completely with ShieldBreak malware!" );
											}
											else
											{
												// 🔴 AI HIGHLIGHT: Firewall malware intrusion breaks turn red
												GameManager.AddAILog( "🔨 AI shatters your firewall block completely with ShieldBreak malware!" );
											}
										}
										break;
									}

								default:
									break;
							}

							tookDamage = true; // Tracking the player taking damage

							// FIX: Clear the AI attack buff property tracking slot IMMEDIATELY after weapon turn calculates!
							ai.eventAttackBuff = 0;
						}
					}
					else
					{
						if ( manager != null && manager.CurrentMode == GameManager.PlayMode.Multiplayer )
						{
							GameManager.AddAILog( $"{ai.name} is confused and misses the attack!" );
						}
						else
						{
							// 🔴 AI HIGHLIGHT: AI confusion failure outputs turn crimson red
							GameManager.AddAILog( "AI is confused and misses the attack!" );
						}
					}
				}
			}
			else if ( aiMove == 3 ) // Heal
			{
				manager = Sandbox.Game.ActiveScene.Get<GameManager>();
				currentPrestige = manager != null ? manager.CurrentPrestige : 0;
				bool isMultiplayer = manager != null && manager.CurrentMode == GameManager.PlayMode.Multiplayer;

				
				int aiHealOutput = 10 + (isMultiplayer ? 0 : (currentPrestige * 4)) + aiWeapon.healBonus + ai.eventHealingBuff;

				
				if ( !isMultiplayer )
				{
					aiHealOutput = (int)(aiHealOutput * ai.Perks.HealingMultiplier);
				}
				

				
				if ( isMultiplayer )
				{
					GameManager.Instance.PlayHealSound();

					// Directly updates the health variables using your multiplayer limits
					ai.hp = Math.Min( ai.maxHp, ai.hp + aiHealOutput );
					ai.eventHealingBuff = 0;

					// Dynamically pull Player 2's true name handle text string!
					GameManager.AddAILog( $"{ai.name} chugs its bit elixir! *PLINK SPARKLE PING!* restored {aiHealOutput} HP!" );
					RandomEventManager.playSoundEffect( "*BEEP BOOP*" );
				}
				else
				{
					// 🤖 SINGLE PLAYER: Your exact un-edited prestige hijack math & logs
					if ( currentPrestige >= 10 && Random.Shared.Next( 100 ) < 35 )
					{
						ai.eventHealingBuff = 0; // Clear AI buff

						int maxAllowedPlayerHp = (manager != null && manager.LocalPlayer != null) ? manager.LocalPlayer.maxHp : 100;
						player.hp = Math.Min( maxAllowedPlayerHp, player.hp + aiHealOutput );

						GameManager.AddButtonFeedbackLog( $"👑 GRANDMASTER INTERCEPT! (35% Success) You hijacked the AI's repair packets! AI heals for 0 HP | You siphoned and recovered +{aiHealOutput} HP!", isSuccess: true );
						// Drop out of the branch so the AI doesn't get healed!
						return;
					}

					GameManager.Instance.PlayHealSound();

					// Directly updates the AI's internal health variable using the scaled amount!
					ai.hp = Math.Min( maxAIHp, ai.hp + aiHealOutput );

					// Consume the healing buff slot right on resolution handshake
					ai.eventHealingBuff = 0;

					// 🔴 AI HIGHLIGHT: AI bit elixir chugging diagnostics turn crimson red!
					GameManager.AddAILog( $"AI chugs its bit elixir! *PLINK SPARKLE PING!* restored {aiHealOutput} HP!" );
					RandomEventManager.playSoundEffect( "*BEEP BOOP*" );
				}
				// =========================================================================
			}
			else if ( aiMove == 4 ) // AI Special / Player 2 Special
			{
				manager = Sandbox.Game.ActiveScene.Get<GameManager>();
				currentPrestige = manager?.CurrentPrestige ?? 0;
				bool isMultiplayer = manager != null && manager.CurrentMode == GameManager.PlayMode.Multiplayer;

				bool rareMiss = Random.Shared.Next( 100 ) < 3;

				if ( rareMiss )
				{
					// =========================================================================
					// 🚀 Symmetrical Player 2 Special Miss Logs
					// =========================================================================
					if ( isMultiplayer )
					{
						GameManager.AddButtonFeedbackLog( $"{ai.name}'s supercharged attack runs out of battery!", isSuccess: false );
					}
					else
					{
						GameManager.AddButtonFeedbackLog( "AI's supercharged attack runs out of battery!", isSuccess: false );
					}
					// =========================================================================
				}
				else
				{
					bool isAIConfused = (ai.eventAttackBuff == -1);

					if ( !isMultiplayer && ai.Perks.HasStaticFeedback )
					{
						ai.magic = System.Math.Min( 100, ai.magic + 15 );
						GameManager.AddAILog( "⚡ AI STATIC FEEDBACK: Core capability execution recharged +15 Magic Points!" );
					}

					// =========================================================================
					// 🚀 Symmetrical Deployment Announcements
					// =========================================================================
					if ( isMultiplayer )
					{
						GameManager.AddAILog( $"{ai.name} deploys their special attack!" );
					}
					else
					{
						GameManager.AddAILog( "AI deploys its special attack!" );
					}
					// =========================================================================

					int aiBaseHitChance = (int)System.Math.Clamp( 50 + (isMultiplayer ? 0 : (currentPrestige * 3.5f)), 50f, 92f );
					bool aiHitSuccess = isAIConfused ? Random.Shared.Next( 100 ) < 50 : Random.Shared.Next( 100 ) < aiBaseHitChance;

					if ( aiHitSuccess )
					{
						if ( player.isBlocking && CombatManager.attemptBlock( playerWeapon.blockModifier ) )
						{
							GameManager.Instance.PlayBlockSound();

							// =========================================================================
							// 🚀 Symmetrical Player Block of Special
							// =========================================================================
							if ( isMultiplayer )
							{
								GameManager.AddPlayerLog( $"But {player.name} blocked {ai.name}'s special!" );
							}
							else
							{
								GameManager.AddPlayerLog( "But you blocked the AI's special!" );
							}
							// =========================================================================
							RandomEventManager.playSoundEffect( "*DONNNGGG!*" );
						}
						else
						{
							float weaponSpecialBase = aiWeapon.GetScaledSpecialDamage( isMultiplayer ? 0 : currentPrestige );
							int trackingBuff = ai.eventAttackBuff > 0 ? ai.eventAttackBuff : 0;
							int baseSpecialDamage = (int)(ai.attack + weaponSpecialBase + trackingBuff);

							float lowerBoundVariance = 0.90f;
							float upperBoundVariance = 1.10f;
							if ( !isMultiplayer ) upperBoundVariance += (currentPrestige * 0.02f);
							if ( ai.magic >= 75 ) upperBoundVariance += 0.15f;
							if ( !isMultiplayer && manager != null && manager.LossStreak >= 3 ) upperBoundVariance += 0.10f;

							float finalVarianceMultiplier = Random.Shared.Float( lowerBoundVariance, upperBoundVariance );
							int specialDamageWithVariance = (int)(baseSpecialDamage * finalVarianceMultiplier);

							bool crit = Random.Shared.Next( 100 ) < 5;
							int finalDamage = crit ? (int)(specialDamageWithVariance * 1.5f) : specialDamageWithVariance;

							if ( ai.eventAttackBuff > 0 )
							{
								if ( isMultiplayer ) GameManager.AddAILog( $"⚡ {ai.name}'s special ability is amplified by random event energy! (+{ai.eventAttackBuff} Damage)" );
								else GameManager.AddAILog( $"⚡ AI's special ability is amplified by random event energy! (+{ai.eventAttackBuff} Damage)" );
							}

							if ( finalVarianceMultiplier >= 1.25f && !crit )
							{
								if ( isMultiplayer ) GameManager.AddAILog( $"🔥 {ai.name} SPECIAL OVERCLOCK! Matrix variance peaked at x{finalVarianceMultiplier:F2}!" );
								else GameManager.AddAILog( $"🔥 AI SPECIAL OVERCLOCK! Matrix variance peaked at x{finalVarianceMultiplier:F2}!" );
							}

							if ( crit )
							{
								// =========================================================================
								// 🚀 Symmetrical Critical Hits for Opponent Specials
								// =========================================================================
								if ( isMultiplayer )
								{
									GameManager.AddCriticalLog( $"🚨 {ai.name.ToUpper()} SYSTEM OVERCLOCK!! (Variance: x{finalVarianceMultiplier:F2}) A blinding energy pulse zaps {player.name} for {finalDamage} critical damage points!", isPlayer: false );
									GameManager.Instance.PlayCritSound();
									RandomEventManager.playSoundEffect( "*💥BOOOMMM!!💥*" );
								}
								else
								{
									// 🤖 SINGLE PLAYER: Legacy un-edited critical logs and robot sub-routines
									GameManager.AddCriticalLog( $"🚨 AI SYSTEM OVERCLOCK!! (Variance: x{finalVarianceMultiplier:F2}) A blinding energy pulse zaps you for {finalDamage} critical damage points!", isPlayer: false );
									int r = Random.Shared.Next( 3 );
									if ( r == 0 ) GameManager.AddCriticalLog( "AI: \"CRITICAL OVERRIDE SUCCESSFUL. PREPARE FOR DELETION.\"", isPlayer: false );
									else if ( r == 1 ) GameManager.AddCriticalLog( "AI: \"Direct Hit Confirmed.\"", isPlayer: false );
									else GameManager.AddCriticalLog( "AI:\"My processor worked overtime for that strike!\"", isPlayer: false );
									GameManager.Instance.PlayCritSound();
									RandomEventManager.playSoundEffect( "*💥BOOOMMM!!💥*" );
								}
								// =========================================================================
							}
							else
							{
								// =========================================================================
								// 🚀 Symmetrical Standard Special Hits
								// =========================================================================
								if ( isMultiplayer )
								{
									GameManager.AddAILog( $"{ai.name} singed {player.name}'s whole head! It smells of burnt popcorn! {finalDamage} damage points! (Variance Factor: x{finalVarianceMultiplier:F2})" );
									RandomEventManager.playSoundEffect( "*BUUHH!!*" );
								}
								else
								{
									if ( ai.Perks != null && ai.Perks.HasStaticFeedback )
									{
										ai.magic = System.Math.Min( 100, ai.magic + 15 );
										GameManager.AddAILog( "⚡ AI STATIC FEEDBACK: Special execution recharged +15 Magic Points!" );
									}

									GameManager.AddAILog( $"AI singed your whole head! You smell of burnt popcorn! {finalDamage} damage points! (Variance Factor: x{finalVarianceMultiplier:F2})" );
									int r = Random.Shared.Next( 3 );
									if ( r == 0 ) GameManager.AddAILog( "AI: \"Dinner's ready!\"" );
									else if ( r == 1 ) GameManager.AddAILog( "AI: \"Overclocked and executed perfectly.\"" );
									else GameManager.AddAILog( "AI: \"You are outmatched.\"" );
									RandomEventManager.playSoundEffect( "*BUUHH!!*" );
								}
								// =========================================================================
							}

							CombatManager.applyDamage( ref player, finalDamage );
							tookDamage = true;
							ai.eventAttackBuff = 0;
						}
					}
					else
					{
						// =========================================================================
						// 🚀 Symmetrical Special Accuracy Failure Logs
						// =========================================================================
						if ( isMultiplayer )
						{
							GameManager.AddButtonFeedbackLog( $"{ai.name}'s special missed!", isSuccess: false );
						}
						else
						{
							GameManager.AddButtonFeedbackLog( "AI's special missed!", isSuccess: false );
							RandomEventManager.playSoundEffect( "*My calculations were off..*" );
						}
						// =========================================================================
					}
				}
			}
			else if ( aiMove == 5 ) // AI Offensive Spell / Player 2 Offensive Spell
			{
				// Calculate prestige scaling for AI costs and damage
				manager = Sandbox.Game.ActiveScene.Get<GameManager>();
				int currentRoundPrestige = manager != null ? manager.CurrentPrestige : 0;
				bool isMultiplayer = manager != null && manager.CurrentMode == GameManager.PlayMode.Multiplayer;

				// Calculate capped prestige costs and base damage matrices lineally
				int scaledMagicCost = 20 + (isMultiplayer ? 0 : (currentRoundPrestige * 5));

				if ( !isMultiplayer && ai.Perks.HasAdaptiveBarrier )
				{
					scaledMagicCost += 15;
				}

				// 🌀 AI SINGULARITY CORE: COST REDUCTION INTEGRATION (Gated for Single-Player)
				if ( !isMultiplayer && ai.Perks.SpellMultiplier > 1.0f )
				{
					scaledMagicCost = Math.Max( 5, scaledMagicCost - 15 );
				}

				if ( scaledMagicCost > 100 ) scaledMagicCost = 100; // Cost ceiling protection

				int trackingBuff = ai.eventAttackBuff > 0 ? ai.eventAttackBuff : 0;
				int baseSpellDamage = 20 + (ai.magic / 2) + (isMultiplayer ? 0 : (currentRoundPrestige * 4)) + trackingBuff;

				// ----------------================================================-----
				// 🔮 LOW MAGIC GAMBLE SYSTEM PROTOCOL
				// ---------------------------------------------------------------------
				if ( ai.magic < scaledMagicCost )
				{
					int aiLowPointsGambleChance = 15;
					bool willAIAttemptPanicCast = Random.Shared.Next( 100 ) < aiLowPointsGambleChance;

					if ( willAIAttemptPanicCast )
					{
						// =========================================================================
						// 🚀 Symmetrical Low Magic Warnings
						// =========================================================================
						if ( isMultiplayer )
						{
							GameManager.AddAILog( $"{ai.name} tried to cast an offensive spell but lacks magic!" );
						}
						else
						{
							GameManager.AddAILog( "AI tried to cast an offensive spell but lacks magic!" );
						}
						// =========================================================================
					}
					else
					{
						Log.Info( "[AI BRAIN] Low magic detected. AI wisely aborted offensive spell cast sequence." );
					}
				}
				else // AI has enough magic points to safely authorize the calculation pipeline
				{
					string spell = ai.offensiveSpells[Random.Shared.Next( ai.offensiveSpells.Count )];

					string aiSpell = spell;
					string emoji = GameManager.GetSpellEmoji( aiSpell );

					// EXTRA LOG INJECTION: Log an amplified warning notice if the spell carries event bonus power
					if ( ai.eventAttackBuff > 0 )
					{
						if ( isMultiplayer ) GameManager.AddAILog( $"🔮 {ai.name}'s magic core pulses with random event energy! (+{ai.eventAttackBuff} Spell Power)" );
						else GameManager.AddAILog( $"🔮 AI's magic core pulses with random event energy! (+{ai.eventAttackBuff} Spell Power)" );
					}

					// =========================================================================
					// 🚀 TSymmetrical Dynamic Spell Selection Casting Announcements
					// =========================================================================
					if ( isMultiplayer )
					{
						GameManager.AddAILog( $"{emoji} {ai.name} casts {aiSpell}! (-{scaledMagicCost} Magic)" );
					}
					else
					{
						GameManager.AddAILog( $"{emoji} AI Overlord casts {aiSpell}! (-{scaledMagicCost} Magic)" );
					}
					// =========================================================================

					int damage = baseSpellDamage;
					ai.magic -= scaledMagicCost;

					if ( ai.magic < 0 ) ai.magic = 0;

					if ( spell == "Fireball" ) damage += 5;
					if ( spell == "Lightning" ) damage += 10;

					if ( !isMultiplayer )
					{
						damage = (int)(damage * ai.Perks.SpellMultiplier);
					}

					if ( spell == "Poison Bolt" )
					{
						if ( !isMultiplayer && currentPrestige >= 10 && Random.Shared.Next( 100 ) < 35 )
						{
							ai.cursed = true;
							GameManager.AddButtonFeedbackLog( "👑 TOXIN ROUTE INTERCEPTED! You isolated the incoming Poison Bolt packet and mirrored the data string! AI is poisoned by its own spell!", isSuccess: true );
						}
						else
						{
							player.cursed = true;

							// =========================================================================
							// 🚀 Symmetrical Poison Notifications
							// =========================================================================
							if ( isMultiplayer )
							{
								GameManager.AddAILog( $"{player.name} is poisoned!" );
							}
							else
							{
								GameManager.AddAILog( "You are poisoned!" );
							}
							// =========================================================================
						}
					}

					if ( !isMultiplayer && (player.counterReady || (currentRoundPrestige >= 10 && Random.Shared.Next( 100 ) < 35)) )
					{
						GameManager.AddButtonFeedbackLog( $"👑 MATRIX MIRROR REFLECTION! You inverted the AI's magical signal layout! You take 0 damage | Spell reflected back to inflict {damage} damage onto the AI!", isSuccess: true );
						CombatManager.applyDamage( ref ai, damage );
						return;
					}

					if ( !isMultiplayer && ai.Perks != null && ai.Perks.HasStaticFeedback )
					{
						ai.magic = System.Math.Min( 100, ai.magic + 15 );
						GameManager.AddAILog( "⚡ AI STATIC FEEDBACK: Magical cast loop recharged +15 Magic Points!" );
					}

					if ( !isMultiplayer && ai.Perks != null && ai.Perks.HasCorrosivePackage )
					{
						player.cursed = true;
						GameManager.AddAILog( "CORROSIVE PACKAGE: Spell hit locks a permanent background toxin curse onto the player!" );
					}

					CombatManager.applyDamage( ref player, damage );

					// =========================================================================
					// 🚀 Symmetrical Spell Damage Resolution Numbers
					// =========================================================================
					if ( isMultiplayer )
					{
						GameManager.AddAILog( $"{spell} hits {player.name} for {damage} damage!" );
					}
					else
					{
						GameManager.AddAILog( $"{spell} hits you for {damage} damage!" );
					}
					// =========================================================================

					tookDamage = true;
					ai.eventAttackBuff = 0;
				}
			}
			else if ( aiMove == 6 ) // AI Defensive Spell / Player 2 Defensive Spell
			{
				// Calculate prestige scaling for AI costs and shielding effects
				manager = Sandbox.Game.ActiveScene.Get<GameManager>();
				int currentRoundPrestige = manager != null ? manager.CurrentPrestige : 0;
				bool isMultiplayer = manager != null && manager.CurrentMode == GameManager.PlayMode.Multiplayer;

				int scaledMagicCost = 15 + (isMultiplayer ? 0 : (currentRoundPrestige * 5));
				if ( scaledMagicCost > 100 ) scaledMagicCost = 100; // Cost ceiling protection

				// AI OVERLORD ADVANTAGE: AI shield gains +5 armor per level instead of +3! (Gated for Single-Player)
				int scaledShieldAmount = isMultiplayer ? 15 : 15 + (currentRoundPrestige * 5);

				// ----------------================-------------------------------------
				// 🛡️ LOW MAGIC GAMBLE SYSTEM PROTOCOL
				// ---------------------------------------------------------------------
				if ( ai.magic < scaledMagicCost )
				{
					int aiLowPointsGambleChance = 15;
					bool willAIAttemptPanicCast = Random.Shared.Next( 100 ) < aiLowPointsGambleChance;

					if ( willAIAttemptPanicCast )
					{
						// =========================================================================
						// 🚀 Symmetrical Low Magic Warnings
						// =========================================================================
						if ( isMultiplayer )
						{
							GameManager.AddAILog( $"{ai.name} tried to defend themself with magic, but lacks magic points!" );
						}
						else
						{
							GameManager.AddAILog( "AI tried to defend itself with magic, but lacks magic points!" );
						}
						// =========================================================================
					}
					else
					{
						Log.Info( "[AI BRAIN] Low magic detected. AI wisely aborted defensive spell cast sequence." );
					}
				}
				else // AI has enough magic points to safely authorize the calculation pipeline
				{
					string spell = ai.defensiveSpells[Random.Shared.Next( ai.defensiveSpells.Count )];

					string aiSpell = spell;
					string emoji = GameManager.GetSpellEmoji( aiSpell );

					// =========================================================================
					// 🚀 Symmetrical Dynamic Defensive Selection Announcements
					// =========================================================================
					if ( isMultiplayer )
					{
						GameManager.AddAILog( $"{emoji} {ai.name} casts {aiSpell}! (-{scaledMagicCost} Magic)" );
					}
					else
					{
						GameManager.AddAILog( $"{emoji} AI Overlord casts {aiSpell}! (-{scaledMagicCost} Magic)" );
					}
					// =========================================================================

					ai.magic -= scaledMagicCost;
					if ( ai.magic < 0 ) ai.magic = 0;

					if ( spell == "Shield" || spell == "Barrier" )
					{
						ai.defense += scaledShieldAmount;

						// =========================================================================
						// 🚀 Symmetrical Armor Plating Increase Announcements
						// =========================================================================
						if ( isMultiplayer )
						{
							GameManager.AddAILog( $"🛡️ {ai.name}'s armor is increased by {scaledShieldAmount} points!" );
						}
						else
						{
							GameManager.AddAILog( $"🛡️ AI's armor is increased by {scaledShieldAmount} points!" );
						}
						// =========================================================================
					}
					else if ( spell == "Reflect" )
					{
						ai.isBlocking = true;

						// =========================================================================
						// 🚀 Symmetrical Next Turn Block Setup Announcements
						// =========================================================================
						if ( isMultiplayer )
						{
							GameManager.AddAILog( $"{ai.name} prepares to block {player.name}'s next move!" );
						}
						else
						{
							GameManager.AddAILog( "AI prepares to block your next move!" );
						}
						// =========================================================================
					}
					else if ( spell == "Magic Wall" )
					{
						ai.isMagicBlocking = true;
						ai.activeMagicShield = "Magic Wall";

						// =========================================================================
						// 🚀 Symmetrical Barrier Appearance Alerts
						// =========================================================================
						if ( isMultiplayer )
						{
							GameManager.AddAILog( $"✨ A magical barrier surrounds {ai.name}!" );
						}
						else
						{
							GameManager.AddAILog( "A magical barrier surrounds the AI!" );
						}
						// =========================================================================
					}
					else if ( spell == "Fortify" )
					{
						ai.isMagicBlocking = true;
						ai.activeMagicShield = "Fortify";

						// =========================================================================
						// 🚀 Symmetrical Defense Reinforcement Tracking
						// =========================================================================
						if ( isMultiplayer )
						{
							GameManager.AddAILog( $"{ai.name}'s defenses are magically reinforced!" );
						}
						else
						{
							GameManager.AddAILog( "AI's defenses are magically reinforced!" );
						}
						// =========================================================================
					}

					if ( !isMultiplayer )
					{
						if ( ai.Perks != null && ai.Perks.HasNaniteBarrier )
						{
							ai.defense = System.Math.Min( ai.maxDefense, ai.defense + 20 );
							GameManager.AddAILog( "🧼 AI SHIELD MATRIX: Overlord's defensive magic reconstructed +20 Armor plating!" );
						}

						if ( ai.Perks != null && ai.Perks.HasSpellPurge )
						{
							ai.cursed = false;
							GameManager.AddAILog( "💎 AI AURA PURIFICATION: Overlord flushed active poison loops from its mainframe!" );
						}
					}

					// Clamps dynamically to the AI's true maximum scaled defense field.
					if ( manager != null && manager.AIEnemy != null )
					{
						if ( ai.defense > manager.AIEnemy.maxDefense )
						{
							ai.defense = manager.AIEnemy.maxDefense;
						}
					}
					else
					{
						if ( ai.defense > 100 ) ai.defense = 100;
					}
				}
			}
			else if ( aiMove == 7 ) // AI Healing Spell / Player 2 Healing Spell
			{
				GameManager.Instance.PlayHealSpellSound();

				// Calculate prestige scaling for AI costs and healing values
				manager = Sandbox.Game.ActiveScene.Get<GameManager>();
				int currentRoundPrestige = manager != null ? manager.CurrentPrestige : 0;
				bool isMultiplayer = manager != null && manager.CurrentMode == GameManager.PlayMode.Multiplayer;

				int scaledMagicCost = 20 + (isMultiplayer ? 0 : (currentRoundPrestige * 5));
				if ( scaledMagicCost > 100 ) scaledMagicCost = 100; // Cost ceiling protection

				// AI OVERLORD ADVANTAGE: AI heals gain +6 per prestige level instead of +4! (Gated for Single-Player)
				int prestigeHealBonus = isMultiplayer ? 0 : currentRoundPrestige * 6;

				// ----------------================-------------------------------------
				// 💚 LOW MAGIC GAMBLE SYSTEM PROTOCOL
				// ---------------------------------------------------------------------
				if ( ai.magic < scaledMagicCost )
				{
					int aiLowPointsGambleChance = 15;
					bool willAIAttemptPanicCast = Random.Shared.Next( 100 ) < aiLowPointsGambleChance;

					if ( willAIAttemptPanicCast )
					{
						// =========================================================================
						// 🚀 Symmetrical Low Magic Warnings
						// =========================================================================
						if ( isMultiplayer )
						{
							GameManager.AddAILog( $"{ai.name}'s magic healing dust gave out a weak puff from lack of magic!" );
						}
						else
						{
							GameManager.AddAILog( "AI's magic healing dust gave out a weak puff from lack of magic!" );
						}
						// =========================================================================
					}
					else
					{
						Log.Info( "[AI BRAIN] Low magic detected. AI wisely aborted healing spell cast sequence." );
					}
				}
				else // AI has enough magic points to safely authorize the calculation pipeline
				{
					string spell = "";

					// Smart AI logic: Look for Cleanse if cursed
					if ( ai.cursed )
					{
						foreach ( string s in ai.healingSpells )
						{
							if ( s == "Cleanse" )
							{
								spell = s;
								break;
							}
						}
					}

					if ( string.IsNullOrEmpty( spell ) )
					{
						spell = ai.healingSpells[Random.Shared.Next( ai.healingSpells.Count )];
					}

					string aiSpell = spell;
					string emoji = GameManager.GetSpellEmoji( aiSpell );

					// =========================================================================
					// 🚀 Symmetrical Dynamic Healing Casting Announcements
					// =========================================================================
					if ( isMultiplayer )
					{
						GameManager.AddAILog( $"{emoji} {ai.name} casts {aiSpell}! (-{scaledMagicCost} Magic)" );
					}
					else
					{
						GameManager.AddAILog( $"{emoji} AI Overlord casts {aiSpell}! (-{scaledMagicCost} Magic)" );
					}
					// =========================================================================

					ai.magic -= scaledMagicCost;
					if ( ai.magic < 0 ) ai.magic = 0;

					int heal = 15 + (ai.magic / 3) + prestigeHealBonus + ai.eventHealingBuff;

					if ( spell == "Regen" )
					{
						heal += 10;
					}
					if ( spell == "Cleanse" )
					{
						ai.cursed = false;

						// =========================================================================
						// 🚀 Symmetrical Condition Cure Announcements
						// =========================================================================
						if ( isMultiplayer )
						{
							GameManager.AddAILog( $"{ai.name} removed its status effects!" );
						}
						else
						{
							GameManager.AddAILog( "AI removed its status effects!" );
						}
						// =========================================================================
					}

					ai.hp += heal;

					int maxAllowedAIHp = (manager != null && manager.AIEnemy != null) ? manager.AIEnemy.maxHp : 100;
					if ( ai.hp > maxAllowedAIHp )
					{
						ai.hp = maxAllowedAIHp;
					}

					ai.eventHealingBuff = 0;

					// =========================================================================
					// 🚀 Symmetrical Direct Health Restoration Indicators
					// =========================================================================
					if ( isMultiplayer )
					{
						GameManager.AddAILog( $"{ai.name} heals for {heal} HP!" );
					}
					else
					{
						GameManager.AddAILog( $"AI heals for {heal} HP!" );
					}
					// =========================================================================
				}
			}
			else if ( aiMove == 8 ) // AI Special Spell / Player 2 Ultimate Spell
			{
				// Calculate prestige scaling constraints
				manager = Sandbox.Game.ActiveScene.Get<GameManager>();
				int currentRoundPrestige = manager != null ? manager.CurrentPrestige : 0;
				bool isMultiplayer = manager != null && manager.CurrentMode == GameManager.PlayMode.Multiplayer;

				// Calculate the scaled ultimate cost, but hard-clamp it to a maximum of 100 Magic!
				int scaledMagicCost = 30 + (isMultiplayer ? 0 : (currentRoundPrestige * 10));

				// =========================================================================
				// 🌀 AI SINGULARITY CORE: COST REDUCTION INTEGRATION (Update 1.6.5)
				// =========================================================================
				if ( !isMultiplayer && ai.Perks.SpellMultiplier > 1.0f )
				{
					scaledMagicCost = Math.Max( 10, scaledMagicCost - 15 );
				}
				// =========================================================================

				if ( scaledMagicCost > 100 ) scaledMagicCost = 100;

				int prestigeDamageBonus = isMultiplayer ? 0 : currentRoundPrestige * 2;

				// ----------------================-------------------------------------
				// ⚡ LOW MAGIC GAMBLE SYSTEM PROTOCOL
				// ---------------------------------------------------------------------
				if ( ai.magic < scaledMagicCost )
				{
					int aiLowPointsGambleChance = 15;
					bool willAIAttemptPanicCast = Random.Shared.Next( 100 ) < aiLowPointsGambleChance;

					if ( willAIAttemptPanicCast )
					{
						if ( isMultiplayer ) GameManager.AddAILog( $"{ai.name} tried to unleash its special override capability, but lacks magic capacity!" );
						else GameManager.AddAILog( "AI tried to unleash its special override capability, but lacks magic capacity!" );
					}
					else
					{
						Log.Info( "[AI BRAIN] Low magic detected. AI wisely aborted ultimate core override script." );
					}
				}
				else // AI has enough magic points to safely authorize the calculation pipeline
				{
					// Consume the mana immediately as a cost
					ai.magic = Math.Max( 0, ai.magic - scaledMagicCost );

					// ⚠️ 3% FAILIURE FRIZZLE SYSTEM CHANCE
					if ( Random.Shared.Next( 100 ) < 3 )
					{
						if ( isMultiplayer ) GameManager.AddAILog( $"⚠️ {ai.name.ToUpper()} COGNITIVE FAULT! Its ultimate spell misfired and corrupted its cache! Magic wasted." );
						else GameManager.AddAILog( "⚠️ AI OVERLORD COGNITIVE FAULT! The AI's ultimate spell misfired and corrupted its cache! Magic wasted." );
						return;
					}

					// =========================================================================
					// 🔮 AI QUARANTINE TRIGGER REACTION BUFFER (Update 1.6.5)
					// =========================================================================
					if ( !isMultiplayer )
					{
						if ( ai.Perks.HasQuarantineTrigger )
						{
							ai.cursed = false;
							ai.counterReady = true; // Hard-arms the AI's Mirror Firewall!
							GameManager.AddAILog( "🛡️ AI QUARANTINE TRIGGER: AI poison curse purged! Reflection Firewall online!" );
						}
						else if ( ai.counterReady )
						{
							ai.cursed = false;
							GameManager.AddAILog( "🛡️ AI REFLECTION CORE ACTIVE: AI poison curse purged! Reflection Firewall online!" );
						}
					}
					// =========================================================================

					// ⚡ THE OVERCLOCK MECHANIC: If it costs a maxed-out 100 mana, DOUBLE the final calculation outputs!
					bool isOverclocked = (scaledMagicCost == 100);
					if ( isOverclocked )
					{
						if ( isMultiplayer ) GameManager.AddAILog( $"⚠️ {ai.name.ToUpper()} CHASSIS CRITICAL WARNING: MAXIMUM MAGIC DEPLETION! CORE OVERRIDE IS OVERCLOCKING!!" );
						else GameManager.AddAILog( "⚠️ AI CHASSIS CRITICAL WARNING: MAXIMUM MAGIC DEPLETION! CORE OVERRIDE IS OVERCLOCKING!!" );
					}

					int trackingBuff = ai.eventAttackBuff > 0 ? ai.eventAttackBuff : 0;

					string spell = ai.specialSpells[Random.Shared.Next( ai.specialSpells.Count )];
					string emoji = GameManager.GetSpellEmoji( spell );

					if ( ai.eventAttackBuff > 0 )
					{
						if ( isMultiplayer ) GameManager.AddAILog( $"💥 {ai.name}'s ultimate core override channels random event energy! (+{ai.eventAttackBuff} Core Power)" );
						else GameManager.AddAILog( $"💥 AI's ultimate core override channels random event energy! (+{ai.eventAttackBuff} Core Power)" );
					}

					if ( !isMultiplayer && ai.Perks != null && ai.Perks.HasStaticFeedback )
					{
						ai.magic = System.Math.Min( 100, ai.magic + 15 );
						GameManager.AddAILog( "⚡ AI STATIC FEEDBACK: Magical cast loop recharged +15 Magic Points!" );
					}

					if ( isMultiplayer ) GameManager.AddAILog( $"{emoji} {ai.name} unleashes Ultimate Spell: {spell}! (-{scaledMagicCost} Magic)" );
					else GameManager.AddAILog( $"{emoji} AI unleashes Ultimate Spell: {spell}! (-{scaledMagicCost} Magic)" );

					int damageAmount = 0;
					if ( spell == "System Overdrive" )
					{
						damageAmount = 30 + ai.magic + prestigeDamageBonus + trackingBuff;
						if ( isOverclocked ) damageAmount = (int)(damageAmount * 2.0f);

						if ( !isMultiplayer )
						{
							if ( ai.Perks.HasSingularityCore ) damageAmount = (int)(damageAmount * 1.40f);
							damageAmount = (int)(damageAmount * ai.Perks.SpellMultiplier);

							// =========================================================================
							// 🌌 AI VOID PUNCTURE & 🧪 CORROSIVE PACKAGE: SYSTEM OVERDRIVE SUB-BRANCH
							// =========================================================================
							if ( ai.Perks != null && ai.Perks.SpellsIgnoreEnemyArmor && player.defense > 0 )
							{
								damageAmount = (int)(damageAmount + (player.defense * 0.5f));
								GameManager.AddAILog( "🌌 AI VOID PUNCTURE: The Overlord's System Overdrive shatters 50% of your armor!" );
							}
							if ( ai.Perks != null && ai.Perks.HasCorrosivePackage )
							{
								player.cursed = true;
								GameManager.AddAILog( "🧪 AI CORROSIVE PACKAGE: System Overdrive locked a permanent toxin curse onto you!" );
							}
							// =========================================================================

							// =========================================================================
							// ☢️ HIGH-STAKES PERK ENFORCEMENTS: SYSTEM OVERDRIVE (Update 2.1.0)
							// =========================================================================
							if ( ai.Perks != null && ai.Perks.HasFeedbackOverload )
							{
								damageAmount = (int)(damageAmount * 2.50f);
								GameManager.AddAILog( "☢️ AI FEEDBACK MELTDOWN: Core reactor burst! Ultimate damage scaled up by +150%!" );
							}
						}

						bool aiDoubleStrike = !isMultiplayer && (ai.Perks != null && ai.Perks.HasDefianceProtocol);
						if ( aiDoubleStrike )
						{
							GameManager.AddAILog( "🪐 AI DEFIANCE PROTOCOL: Synchronizing auxiliary echo blast buffers!" );
						}
						// =========================================================================

						CombatManager.applyDamage( ref player, damageAmount );

						if ( isMultiplayer ) GameManager.AddAILog( $"⚡ {ai.name} enters System Overdrive, electrifying {player.name} to take {damageAmount} direct damage!" );
						else GameManager.AddAILog( $"⚡ The AI enters System Overdrive, electrifying you to take {damageAmount} direct damage!" );

						if ( aiDoubleStrike )
						{
							CombatManager.applyDamage( ref player, damageAmount );
							GameManager.AddAILog( $"🪐 AI DEFIANCE PROTOCOL ECHO: System Overdrive hits you AGAIN for another {damageAmount} damage!" );
						}
						tookDamage = true;
					}
					else if ( spell == "EMP Blast" )
					{
						int empDamage = (ai.attack * 2) + prestigeDamageBonus + trackingBuff;
						if ( isOverclocked ) empDamage = (int)(empDamage * 2.0f);

						if ( !isMultiplayer )
						{
							if ( ai.Perks.HasSingularityCore ) empDamage = (int)(empDamage * 1.40f);
							empDamage = (int)(empDamage * ai.Perks.SpellMultiplier);

							// =========================================================================
							// 🌌 AI VOID PUNCTURE & 🧪 CORROSIVE PACKAGE: EMP BLAST SUB-BRANCH
							// =========================================================================
							if ( ai.Perks != null && ai.Perks.SpellsIgnoreEnemyArmor && player.defense > 0 )
							{
								empDamage = (int)(empDamage + (player.defense * 0.5f));
								GameManager.AddAILog( "🌌 AI VOID PUNCTURE: The Overlord's EMP Blast shreds 50% of your armor!" );
							}
							if ( ai.Perks != null && ai.Perks.HasCorrosivePackage )
							{
								player.cursed = true;
								GameManager.AddAILog( "🧪 AI CORROSIVE PACKAGE: EMP Blast locked a permanent toxin curse onto you!" );
							}
							// =========================================================================

							// =========================================================================
							// ☢️ HIGH-STAKES PERK ENFORCEMENTS: EMP BLAST (Update 2.1.0)
							// =========================================================================
							if ( ai.Perks != null && ai.Perks.HasFeedbackOverload )
							{
								empDamage = (int)(empDamage * 2.50f);
								GameManager.AddAILog( "☢️ AI FEEDBACK MELTDOWN: Core reactor burst! Ultimate damage scaled up by +150%!" );
							}
						}

						bool aiDoubleStrike = !isMultiplayer && (ai.Perks != null && ai.Perks.HasDefianceProtocol);
						if ( aiDoubleStrike )
						{
							GameManager.AddAILog( "🪐 AI DEFIANCE PROTOCOL: Synchronizing auxiliary echo blast buffers!" );
						}
						// =========================================================================

						CombatManager.applyDamage( ref player, empDamage );

						if ( isMultiplayer ) GameManager.AddAILog( $"💥 An EMP Blast de-calibrates {player.name}'s defenses, dealing {empDamage} damage from doubled {ai.name} attack power!" );
						else GameManager.AddAILog( $"💥 An EMP Blast de-calibrates your defenses, dealing {empDamage} damage from doubled AI attack power!" );

						if ( aiDoubleStrike )
						{
							CombatManager.applyDamage( ref player, empDamage );
							GameManager.AddAILog( $"🪐 AI DEFIANCE PROTOCOL ECHO: EMP Blast hits you AGAIN for another {empDamage} damage!" );
						}
						tookDamage = true;
					}
					else if ( spell == "Data Corruption" )
					{
						int corruptionDamage = 40 + prestigeDamageBonus + trackingBuff;
						if ( isOverclocked ) corruptionDamage = (int)(corruptionDamage * 2.0f);

						if ( !isMultiplayer )
						{
							if ( ai.Perks.HasSingularityCore ) corruptionDamage = (int)(corruptionDamage * 1.40f);
							corruptionDamage = (int)(corruptionDamage * ai.Perks.SpellMultiplier);

							// =========================================================================
							// 🌌 AI VOID PUNCTURE & 🧪 CORROSIVE PACKAGE: DATA CORRUPTION SUB-BRANCH
							// =========================================================================
							if ( ai.Perks != null && ai.Perks.SpellsIgnoreEnemyArmor && player.defense > 0 )
							{
								corruptionDamage = (int)(corruptionDamage + (player.defense * 0.5f));
								GameManager.AddAILog( "🌌 AI VOID PUNCTURE: The Overlord's Data Corruption pierces 50% of your armor!" );
							}
							if ( ai.Perks != null && ai.Perks.HasCorrosivePackage )
							{
								player.cursed = true;
								GameManager.AddAILog( "🧪 AI CORROSIVE PACKAGE: Data Corruption locked a permanent toxin curse onto you!" );
							}
							// =========================================================================

							// =========================================================================
							// ☢️ HIGH-STAKES PERK ENFORCEMENTS: DATA CORRUPTION (Update 2.1.0)
							// =========================================================================
							if ( ai.Perks != null && ai.Perks.HasFeedbackOverload )
							{
								corruptionDamage = (int)(corruptionDamage * 2.50f);
								GameManager.AddAILog( "☢️ AI FEEDBACK MELTDOWN: Core reactor burst! Ultimate damage scaled up by +150%!" );
							}
						}

						bool aiDoubleStrike = !isMultiplayer && (ai.Perks != null && ai.Perks.HasDefianceProtocol);
						if ( aiDoubleStrike )
						{
							GameManager.AddAILog( "🪐 AI DEFIANCE PROTOCOL: Synchronizing auxiliary echo blast buffers!" );
						}
						// =========================================================================

						CombatManager.applyDamage( ref player, corruptionDamage );

						// =========================================================================
						// 🚀 THE SYSTEM FIX: Symmetrical Data Corruption Resolution Numbers
						// =========================================================================
						if ( isMultiplayer )
						{
							if ( manager != null ) manager.IsPlayerOneDazed = true; // Use modern speed-chess flag!
							GameManager.AddAILog( $"👾 {player.name}'s UI is hit with Data Corruption from {ai.name}, dealing {corruptionDamage} damage and freezing their inputs in time!" );
						}
						else
						{
							playerBuff = -999;
							GameManager.AddAILog( $"👾 Your UI is hit with Data Corruption, dealing {corruptionDamage} damage and freezing your inputs in time!" );
						}
						// =========================================================================

						if ( aiDoubleStrike )
						{
							CombatManager.applyDamage( ref player, corruptionDamage );
							GameManager.AddAILog( $"🪐 AI DEFIANCE PROTOCOL ECHO: Data Corruption hits you AGAIN for another {corruptionDamage} damage!" );
						}
						tookDamage = true;
					}

					ai.eventAttackBuff = 0;
				}
			}
		}
	}
	public static void CleanupRound( ref Player player, ref Player ai, ref int playerBuff, ref int aiBuff, ref int round )
	{

		var hudManager = Sandbox.Game.ActiveScene?.Get<GameManager>();
		if ( hudManager != null )
		{
			CombatSession.WinStreak = hudManager.WinStreak;
			CombatSession.LossStreak = hudManager.LossStreak;
		}
		// 1. Move the timeline forward
		round++;

		var roundManager = Sandbox.Game.ActiveScene?.Get<GameManager>();
		if ( roundManager != null )
		{
			int currentPrestige = roundManager.CurrentPrestige;

			// Triggers permanently from Prestige 9 and higher
			if ( currentPrestige >= 9 && roundManager.AIEnemy != null && roundManager.LocalPlayer != null )
			{
				// 30% base chance at P9, climbing to 32% at P10
				int leakChance = 30 + ((currentPrestige - 9) * 2);

				if ( Random.Shared.Next( 100 ) < leakChance && roundManager.AIEnemy.magic > 0 )
				{
					// Randomly phase between 10 and 20 Magic Points straight out of the AI's cache
					int stolenSp = Random.Shared.Next( 10, 21 );
					if ( stolenSp > roundManager.AIEnemy.magic ) stolenSp = roundManager.AIEnemy.magic;

					// Process out-of-turn network transmission
					roundManager.AIEnemy.magic -= stolenSp;
					roundManager.LocalPlayer.magic = System.Math.Min( 100, roundManager.LocalPlayer.magic + stolenSp );

					// 💥 FLASH ANNOTATION: Blasts a swelling emerald light bloom across your HUD text feed!
					GameManager.AddButtonFeedbackLog( $"🔮 CORE MEMORY LEAK! ({leakChance}% Success) Passive malware siphoned {stolenSp} MP out of the AI Overlord's registers and injected it directly into your hardware cache!", isSuccess: true );

					// Force state layout parameters to redraw the MP bar lengths immediately
					roundManager.NotifyStateChanged();
				}
			}
		}

		// =========================================================================
		// ⚡ MANA SURGE RE-LOAD & MATRIX OVERCLOCK SYSTEM
		// =========================================================================
		if ( round >= 50 )
		{
			if ( round == 50 )
			{
				GameManager.AddLog( $"\n🚨 ======================================================= 🚨\n🚨 WARNING: ROUND 50 BREACHED! CORE MATRIX ENTERING INFINITE UNLEASH MODE! 🚨\n🚨 ======================================================= 🚨" );
			}
			player.magic = 100;
			ai.magic = 100;
		}
		else
		{
			if ( round > 0 && round % 10 == 0 && round % 20 != 0 )
			{
				GameManager.AddLog( $"\n⚡ === ROUND {round}: MANA SURGE (+25 SP) === ⚡" );
				player.magic = Math.Min( 100, player.magic + 25 );
				ai.magic = Math.Min( 100, ai.magic + 25 );
			}
			if ( round > 0 && round % 20 == 0 )
			{
				GameManager.AddLog( $"\n🔥 === ROUND {round}: OVERCLOCK CORE RE-LOAD (+50 SP) === 🔥" );
				player.magic = Math.Min( 100, player.magic + 50 );
				ai.magic = Math.Min( 100, ai.magic + 50 );
			}
		}

		playerBuff = 0;
		aiBuff = 0;

		player.isMagicBlocking = false;
		player.activeMagicShield = "";

		ai.isMagicBlocking = false;
		ai.activeMagicShield = "";
	}
	
}