MainHud/Program.cs

Game UI/logic helper class for the turn-based combat HUD. It contains AI dialogue and decision logic, player banners/ASCII art, spell display, AI action chooser, and handlers for player and AI turns including damage, enchantments and logs.

NetworkingNative Interop
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 )
				{
					// ⚡ 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();
							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 ( 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 );

							
							

							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 = fireBase + (currentPrestige * 2);

											// 🔵 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 ( 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;
											// 🔵 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;
											// 🔵 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 = 5 + (currentPrestige * 2);
											int totalSparksHeal = baseSparks + player.eventHealingBuff;

											player.hp += totalSparksHeal;
											// 🔵 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 = 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 ( 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 )
											{
												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)
												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
																			 // 🔵 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;
											// 🔵 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;

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

				// =========================================================================
				// 🧬 RECOVERY MULTIPLIER INTEGRATION (Update 1.6.5)
				// =========================================================================
				// Amplifies your potion recovery by +25% with Chassis Inflation, 
				// or reduces it by -30% if you drafted Vampiric Puncture!
				playerHealOutput = (int)(playerHealOutput * player.Perks.HealingMultiplier);
				// =========================================================================

				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();

				// =========================================================================
				// 🩹 DIRECT PERK HEAL INJECTION (Update 1.6.5)
				// =========================================================================
				// Directly updates the health variables using the fully perk-scaled amount!
				player.hp = Math.Min( player.maxHp, player.hp + playerHealOutput );
				// =========================================================================

				// Consume the healing buff slot
				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 )
				{
					// ⚡ ANIMATION UPDATE: Rare special failures now shake and flash warning red!
					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 )
					{
						// 🔵 PLAYER HIGHLIGHT: Target confirmation turns blue
						GameManager.AddPlayerLog( "Your special attack is on target!" );

						if ( ai.isBlocking && CombatManager.attemptBlock() )
						{
							GameManager.Instance.PlayFirewallSound();
							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);

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

							// Expand the upper limits using active game-state variables
							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 window 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 using s&box engine API
							float finalVarianceMultiplier = Random.Shared.Float( lowerBoundVariance, upperBoundVariance );

							// Compute the dynamic special attack base before checking for a native Crit
							int specialDamageWithVariance = (int)(baseSpecialDamage * finalVarianceMultiplier);
							// =========================================================================

							// Check for your native 10% hard Special Critical Hit roll
							bool specialCrit = Random.Shared.Next( 100 ) < 10;
							int finalSpecialDamage = specialCrit ? (int)(specialDamageWithVariance * 1.5f) : specialDamageWithVariance;

							// EXTRA LOG INJECTION: Notice prints out to call out event rewards on a special strike
							if ( player.eventAttackBuff > 0 )
							{
								// 🔵 PLAYER HIGHLIGHT: Event amplification text turns blue
								GameManager.AddPlayerLog( $"⚡ Your special ability is amplified by random event energy! (+{player.eventAttackBuff} Damage)" );
							}

							// Output variance telemetry if it rolls extremely hot without a hard crit
							if ( finalVarianceMultiplier >= 1.25f && !specialCrit )
							{
								// 🔵 PLAYER HIGHLIGHT: Overclock telemetry turns blue
								GameManager.AddPlayerLog( $"🔥 OVERCLOCK SURGE! Special matrix variance peaked at x{finalVarianceMultiplier:F2}!" );
							}

							CombatManager.applyDamage( ref ai, finalSpecialDamage );

							if ( specialCrit )
							{
								// 💥 ANIMATION UPDATE: Overdrive critical hit text flashes and glitches violently in electric blue!
								GameManager.AddCriticalLog( $"🚨 OVERDRIVE CRITICAL!! (Variance: x{finalVarianceMultiplier:F2}) Your ultimate ability blasted the AI for {finalSpecialDamage} damage points!", isPlayer: true );

								// 💥 ANIMATION UPDATE: The AI's structural collapse emergency warnings flash in crimson red!
								GameManager.AddCriticalLog( "AI: \"SYSTEM COMPROMISED. HULL INTEGRITY CRITICAL.\"", isPlayer: false );
								GameManager.Instance.PlayCritSound();
								RandomEventManager.playSoundEffect( "*ZZZAAPP!!* *EXPLOSION!*" );
							}
							else
							{
								// 🔵 PLAYER HIGHLIGHT: Standard special strike connection text turns blue
								GameManager.AddPlayerLog( $"The charmed special deals {finalSpecialDamage} damage points! (Variance Factor: x{finalVarianceMultiplier:F2})" );
								RandomEventManager.playSoundEffect( "*SSSLLICEEE!*" );

								// 🔴 AI HIGHLIGHT: AI parameter overload responses turn red!
								GameManager.AddAILog( "AI: \"That attack.. exceeded parameters.\"" );
							}

							
							player.eventAttackBuff = 0;
						}
					}
					else
					{
						// ⚡ ANIMATION UPDATE: Evasion special misses now shake and flash warning red!
						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 )
				{
					// ⚡ 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();
							// 🔵 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 ( 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!*" );

								int r = Random.Shared.Next( 3 );
								// 💥 ANIMATION UPDATE: The AI's triumphant dialogue streams flash and strobe in matching crimson red!
								if ( r == 0 ) GameManager.AddCriticalLog( "AI: \"Direct hit confirmed.\"", isPlayer: false );
								else if ( r == 1 ) GameManager.AddCriticalLog( "AI: \"My coordinates were on target.\"", isPlayer: false );
								else GameManager.AddCriticalLog( "AI: \"You never saw that coming!\"", 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 );

							

							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 = fireBase + (currentPrestige * 2);

											// 🔴 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);
												// 🔴 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 ( 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;
											// 🔴 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;
											// 🔴 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 = 15 + (currentPrestige * 2);
											int totalSparksHealAI = baseSparks + ai.eventHealingBuff;
											ai.hp += totalSparksHealAI;
											// 🔴 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 = 10 + (currentPrestige * 3);
												// 🔴 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 ( 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 )
										{
											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)
												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
																		 // 🔴 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 ( manager != null && manager.LossStreak >= 3 )
										{
											breakChance += 20;
										}

										if ( (Random.Shared.Next( 100 ) < breakChance) && player.isBlocking )
										{
											player.isBlocking = false;
											// 🔴 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
					{
						// 🔴 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;

				// FIX: Integrate the new active AI event healing buff into the elixir recovery pool calculation!
				int aiHealOutput = 10 + (currentPrestige * 4) + aiWeapon.healBonus + ai.eventHealingBuff;

				// =========================================================================
				// 🧬 AI RECOVERY MULTIPLIER INTEGRATION (Update 1.6.5)
				// =========================================================================
				// Amplifies the AI's elixir recovery by +25% with Chassis Inflation,
				// or scales it down by -30% if they selected Vampiric Puncture!
				aiHealOutput = (int)(aiHealOutput * ai.Perks.HealingMultiplier);
				// =========================================================================

				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();

				// =========================================================================
				// 🩹 DIRECT AI PERK HEAL INJECTION (Update 1.6.5)
				// =========================================================================
				// Directly updates the AI's internal health variable using the scaled amount!
				// Note: If your AI max health variable is named ai.maxHp, change 'maxAIHp' to 'ai.maxHp'
				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
			{
				manager = Sandbox.Game.ActiveScene.Get<GameManager>();
				currentPrestige = manager?.CurrentPrestige ?? 0;

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

				if ( rareMiss )
				{
					// ⚡ ANIMATION UPDATE: AI battery drainage failures now shake and flash failure red!
					GameManager.AddButtonFeedbackLog( "AI's supercharged attack runs out of battery!", isSuccess: false );
				}
				else
				{
					
					bool isAIConfused = (ai.eventAttackBuff == -1);

					// =========================================================================
					// ⚡ AI STATIC FEEDBACK TRIGGER (Update 1.6.5)
					// =========================================================================
					// If the AI holds the Static Feedback perk chip, instantly recover +15 MP!
					if ( ai.Perks.HasStaticFeedback )
					{
						ai.magic = System.Math.Min( 100, ai.magic + 15 );
						GameManager.AddAILog( "⚡ AI STATIC FEEDBACK: Core capability execution recharged +15 Magic Points!" );
					}
					// =========================================================================

					// 🔴 AI HIGHLIGHT: AI special deployment notification turns crimson red
					GameManager.AddAILog( "AI deploys its special attack!" );

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

					if ( aiHitSuccess )
					{
						if ( player.isBlocking && CombatManager.attemptBlock( playerWeapon.blockModifier ) ) // Player block uses weapon modifier.
						{
							GameManager.Instance.PlayBlockSound();
							// 🔵 PLAYER HIGHLIGHT: Your spectacular block of the AI's special turns bright cyber blue!
							GameManager.AddPlayerLog( "But you blocked the AI's special!" );
							RandomEventManager.playSoundEffect( "*DONNNGGG!*" );
						}
						else
						{
							float weaponSpecialBase = aiWeapon.GetScaledSpecialDamage( currentPrestige );

							
							int trackingBuff = ai.eventAttackBuff > 0 ? ai.eventAttackBuff : 0;
							int baseSpecialDamage = (int)(ai.attack + weaponSpecialBase + trackingBuff);

							// =========================================================================
							// ⚔️ APPROACH 3: AI SPECIAL MOVE 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 special attack base before checking for a native Crit
							int specialDamageWithVariance = (int)(baseSpecialDamage * finalVarianceMultiplier);
							// =========================================================================

							// Check for native 5% hard Critical Hit roll
							bool crit = Random.Shared.Next( 100 ) < 5;
							int finalDamage = crit ? (int)(specialDamageWithVariance * 1.5f) : specialDamageWithVariance;

							// EXTRA LOG INJECTION: Notice prints out to call out event rewards on an AI special strike
							if ( ai.eventAttackBuff > 0 )
							{
								// 🔴 AI HIGHLIGHT: AI's random event charge notification turns red
								GameManager.AddAILog( $"⚡ AI's special ability is amplified by random event energy! (+{ai.eventAttackBuff} Damage)" );
							}

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

							if ( crit )
							{
								// 💥 ANIMATION UPDATE: AI's massive critical special pulse now flashes and glitches violently in crimson red!
								GameManager.AddCriticalLog( $"🚨 AI SYSTEM OVERCLOCK!! (Variance: x{finalVarianceMultiplier:F2}) A blinding energy pulse zaps you for {finalDamage} critical damage points!", isPlayer: false );
								RandomEventManager.playSoundEffect( "*💥BOOOMMM!!💥*" );

								int r = Random.Shared.Next( 3 );
								// 💥 ANIMATION UPDATE: AI deletion sub-routines and quotes strobe violently in matching crimson red!
								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();
							}
							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!" );
								}

								// 🔴 AI HIGHLIGHT: Standard special weapon connection text turns red
								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 );
								// 🔴 AI HIGHLIGHT: Direct system dialogue lines turn red
								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; // Tracking the player taking damage.

							
							ai.eventAttackBuff = 0;
						}
					}
					else
					{
						// ⚡ ANIMATION UPDATE: AI missing its special accuracy check now shakes and flashes failure red!
						GameManager.AddButtonFeedbackLog( "AI's special missed!", isSuccess: false );
						RandomEventManager.playSoundEffect( "*My calculations were off..*" );
					}
				}
			}
			else if ( aiMove == 5 ) // AI Offensive Spell.
			{
				// Calculate prestige scaling for AI costs and damage
				
				manager = Sandbox.Game.ActiveScene.Get<GameManager>();
				int currentRoundPrestige = manager != null ? manager.CurrentPrestige : 0;

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

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

				// =========================================================================
				// 🌀 AI SINGULARITY CORE: COST REDUCTION INTEGRATION (Update 1.6.5)
				// =========================================================================
				// If Singularity Core or Overclocked Core is active, drop AI costs by -15 MP flat!
				if ( 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) + (currentRoundPrestige * 4) + trackingBuff;

				// ----------------================================================-----
				// 🔮 LOW MAGIC GAMBLE SYSTEM PROTOCOL
				// ----------------================-------------------------------------
				if ( ai.magic < scaledMagicCost )
				{
					// 15% chance the AI panics or miscalculates its pool and attempts the cast anyway!
					int aiLowPointsGambleChance = 15;
					bool willAIAttemptPanicCast = Random.Shared.Next( 100 ) < aiLowPointsGambleChance;

					if ( willAIAttemptPanicCast )
					{
						// The small percentage where it tries anyway and publicly prints your failure message:
						// 🔴 AI HIGHLIGHT: Panic-cast failure message glows red
						GameManager.AddAILog( "AI tried to cast an offensive spell but lacks magic!" );
					}
					else
					{
						// 85% of the time, the AI realizes it's out of mana and doesn't even bother to print anything.
						// It silently drops out of the block to let the turn safely conclude!
						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 )];

					// Find chosen spell safely
					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 )
					{
						// 🔴 AI HIGHLIGHT: Event weapon amplification logs turn red
						GameManager.AddAILog( $"🔮 AI's magic core pulses with random event energy! (+{ai.eventAttackBuff} Spell Power)" );
					}

					// 🔴 AI HIGHLIGHT: Dynamic spell selection casting announcements turn red
					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;

					// =========================================================================
					// ☄️ AI AURA MELTDOWN & MAGIC SPELL MULTIPLIER (Update 1.6.5)
					// =========================================================================
					// Hyper-scales the AI's final spell damage points using its own perk slots!
					damage = (int)(damage * ai.Perks.SpellMultiplier);
					// =========================================================================

					if ( spell == "Poison Bolt" )
					{
						if ( currentPrestige >= 10 && Random.Shared.Next( 100 ) < 35 )
						{
							ai.cursed = true; // Force the AI to infect its own runtime code loops instead!

							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;
							// 🔴 AI HIGHLIGHT: Direct poison status notifications turn red
							GameManager.AddAILog( "You are poisoned!" );
						}
					}

					if ( 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 ( ai.Perks != null && ai.Perks.HasStaticFeedback )// Static Feedback Perk
					{
						ai.magic = System.Math.Min( 100, ai.magic + 15 );
						GameManager.AddAILog( "⚡ AI STATIC FEEDBACK: Magical cast loop recharged +15 Magic Points!" );
					}

					if (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 );
					// 🔴 AI HIGHLIGHT: Direct spell damage resolution numbers turn red
					GameManager.AddAILog( $"{spell} hits you for {damage} damage!" );

					tookDamage = true;

					// CRITICAL RESET FLUSH: Clear the attack buff property tracking slot immediately after the spell resolves!
					ai.eventAttackBuff = 0;
				}
			}
			else if ( aiMove == 6 ) // AI Defensive Spell.
			{
				// Calculate prestige scaling for AI costs and shielding effects
				manager = Sandbox.Game.ActiveScene.Get<GameManager>();
				int currentRoundPrestige = manager != null ? manager.CurrentPrestige : 0;

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

				// AI OVERLORD ADVANTAGE: AI shield gains +5 armor per level instead of +3!
				int scaledShieldAmount = 15 + (currentRoundPrestige * 5);

				// ----------------================================================-----
				// 🛡️ LOW MAGIC GAMBLE SYSTEM PROTOCOL
				// ---------------------------------------------------------------------
				if ( ai.magic < scaledMagicCost )
				{
					// 15% chance the AI panics or miscalculates its pool and attempts the defensive cast anyway!
					int aiLowPointsGambleChance = 15;
					bool willAIAttemptPanicCast = Random.Shared.Next( 100 ) < aiLowPointsGambleChance;

					if ( willAIAttemptPanicCast )
					{
						// The small percentage where it tries anyway and publicly prints your failure message:
						// 🔴 AI HIGHLIGHT: Panic defensive-cast failure message glows red
						GameManager.AddAILog( "AI tried to defend itself with magic, but lacks magic points!" );
					}
					else
					{
						// 85% of the time, the AI realizes it's out of mana and doesn't even bother to print anything.
						// It silently drops out of the block to let the turn safely conclude!
						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 );

					// 🔴 AI HIGHLIGHT: Dynamic defensive selection announcements turn red
					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;
						// 🔴 AI HIGHLIGHT: Armor point metrics turn red
						GameManager.AddAILog( $"🛡️ AI's armor is increased by {scaledShieldAmount} points!" );
					}
					else if ( spell == "Reflect" )
					{
						ai.isBlocking = true;
						// 🔴 AI HIGHLIGHT: Next turn block setup text turns red
						GameManager.AddAILog( "AI prepares to block your next move!" );
					}
					else if ( spell == "Magic Wall" )
					{
						ai.isMagicBlocking = true;
						ai.activeMagicShield = "Magic Wall";
						// 🔴 AI HIGHLIGHT: Barrier appearance alerts turn red
						GameManager.AddAILog( "A magical barrier surrounds the AI!" );
					}
					else if ( spell == "Fortify" )
					{
						ai.isMagicBlocking = true;
						ai.activeMagicShield = "Fortify";
						// 🔴 AI HIGHLIGHT: Defense reinforcement tracking lines turn red
						GameManager.AddAILog( "AI's defenses are magically reinforced!" );
					}

					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!" );
					}

					// FIX: Removed hardcoded '> 100' cap! Now 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.
			{
				GameManager.Instance.PlayHealSpellSound();

				// Calculate prestige scaling for AI costs and healing values
				// FIX: Reused outer parent variables instead of illegally redeclaring 'manager'!
				manager = Sandbox.Game.ActiveScene.Get<GameManager>();
				int currentRoundPrestige = manager != null ? manager.CurrentPrestige : 0;

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

				// AI OVERLORD ADVANTAGE: AI heals gain +6 per prestige level instead of +4!
				int prestigeHealBonus = currentRoundPrestige * 6;

				// ----------------================================================-----
				// 💚 LOW MAGIC GAMBLE SYSTEM PROTOCOL
				// ----------------================================================-----
				if ( ai.magic < scaledMagicCost )
				{
					// 15% chance the AI panics or miscalculates its pool and attempts the healing cast anyway!
					int aiLowPointsGambleChance = 15;
					bool willAIAttemptPanicCast = Random.Shared.Next( 100 ) < aiLowPointsGambleChance;

					if ( willAIAttemptPanicCast )
					{
						// The small percentage where it tries anyway and publicly prints your failure message:
						// 🔴 AI HIGHLIGHT: Panic healing-cast failure message glows red
						GameManager.AddAILog( "AI's magic healing dust gave out a weak puff from lack of magic!" );
					}
					else
					{
						// 85% of the time, the AI realizes it's out of mana and doesn't even bother to print anything.
						// It silently drops out of the block to let the turn safely conclude!
						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 )];
					}

					// Find chosen spell safely for the custom emoji readout
					string aiSpell = spell;
					string emoji = GameManager.GetSpellEmoji( aiSpell );

					// 🔴 AI HIGHLIGHT: Dynamic healing casting announcements turn red
					GameManager.AddAILog( $"{emoji} AI Overlord casts {aiSpell}! (-{scaledMagicCost} Magic)" );

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

					// FIX: Integrate the AI's active event healing buff into its core healing formula!
					int heal = 15 + (ai.magic / 3) + prestigeHealBonus + ai.eventHealingBuff;

					if ( spell == "Regen" )
					{
						heal += 10;
					}
					if ( spell == "Cleanse" )
					{
						ai.cursed = false;
						// 🔴 AI HIGHLIGHT: Condition cure announcements turn red
						GameManager.AddAILog( "AI removed its status effects!" );
					}

					ai.hp += heal;

					// FIX: Removed the hardcoded '> 100' health limitation! Clamps to AI maxHp fields
					int maxAllowedAIHp = (manager != null && manager.AIEnemy != null) ? manager.AIEnemy.maxHp : 100;
					if ( ai.hp > maxAllowedAIHp )
					{
						ai.hp = maxAllowedAIHp;
					}

					
					ai.eventHealingBuff = 0;

					// 🔴 AI HIGHLIGHT: Direct health restoration indicators turn red
					GameManager.AddAILog( $"AI heals for {heal} HP!" );
				}
			}
			else if ( aiMove == 8 ) // AI Special Spell.
			{
				// Calculate prestige scaling constraints
				manager = Sandbox.Game.ActiveScene.Get<GameManager>();
				int currentRoundPrestige = manager != null ? manager.CurrentPrestige : 0;

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

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

				if ( scaledMagicCost > 100 ) scaledMagicCost = 100;

				int prestigeDamageBonus = currentRoundPrestige * 2;

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

					if ( willAIAttemptPanicCast )
					{
						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 )
					{
						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 ( 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 )
					{
						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 )
					{
						GameManager.AddAILog( $"💥 AI's ultimate core override channels random event energy! (+{ai.eventAttackBuff} Core Power)" );
					}

					if ( 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!" );
					}

					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 ( 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 = (ai.Perks != null && ai.Perks.HasDefianceProtocol);
						if ( aiDoubleStrike )
						{
							GameManager.AddAILog( "🪐 AI DEFIANCE PROTOCOL: Synchronizing auxiliary echo blast buffers!" );
						}
						// =========================================================================

						CombatManager.applyDamage( ref player, damageAmount );
						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 ( 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 = (ai.Perks != null && ai.Perks.HasDefianceProtocol);
						if ( aiDoubleStrike )
						{
							GameManager.AddAILog( "🪐 AI DEFIANCE PROTOCOL: Synchronizing auxiliary echo blast buffers!" );
						}
						// =========================================================================

						CombatManager.applyDamage( ref player, empDamage );
						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 ( 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 = (ai.Perks != null && ai.Perks.HasDefianceProtocol);
						if ( aiDoubleStrike )
						{
							GameManager.AddAILog( "🪐 AI DEFIANCE PROTOCOL: Synchronizing auxiliary echo blast buffers!" );
						}
						// =========================================================================

						CombatManager.applyDamage( ref player, corruptionDamage );
						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 = "";
	}
	
}