Decompiled source of L A T E v1.1.0

L.A.T.E.dll

Decompiled 2 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using ExitGames.Client.Photon;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using MonoMod.RuntimeDetour;
using Photon.Pun;
using Photon.Realtime;
using UnityEngine;
using UnityEngine.SceneManagement;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("L.A.T.E")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+9fdc763dc1430ac2c3f00aa35f05e090974f0f69")]
[assembly: AssemblyProduct("L.A.T.E")]
[assembly: AssemblyTitle("L.A.T.E")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
}
namespace L.A.T.E
{
	internal static class ConfigManager
	{
		private const string SectionGeneral = "General";

		private const string SectionLateJoinBehavior = "Late Join Behavior";

		private const string SectionAdvanced = "Advanced (Use With Caution)";

		private const string SectionDebug = "Debugging";

		internal static ConfigEntry<bool> AllowInShop { get; private set; }

		internal static ConfigEntry<bool> AllowInTruck { get; private set; }

		internal static ConfigEntry<bool> AllowInLevel { get; private set; }

		internal static ConfigEntry<bool> AllowInArena { get; private set; }

		internal static ConfigEntry<bool> KillIfPreviouslyDead { get; private set; }

		internal static ConfigEntry<bool> SpawnAtLastPosition { get; private set; }

		internal static ConfigEntry<bool> LockLobbyOnLevelGenerationFailure { get; private set; }

		internal static ConfigEntry<bool> ForceReloadOnLateJoin { get; private set; }

		internal static ConfigEntry<LogLevel> ModLogLevel { get; private set; }

		private static ManualLogSource Log => LateJoinEntry.Log;

		internal static void Initialize(ConfigFile cfg)
		{
			//IL_0108: Unknown result type (might be due to invalid IL or missing references)
			Log.LogDebug((object)"[Config] Binding entries...");
			AllowInShop = Bind(cfg, "General", "Allow in shop", defaultValue: true, "Allow players to join while the host is in the shop.");
			AllowInTruck = Bind(cfg, "General", "Allow in truck", defaultValue: true, "Allow players to join while the host is in the truck.");
			AllowInLevel = Bind(cfg, "General", "Allow in level", defaultValue: true, "Allow players to join while the host is in an active level.");
			AllowInArena = Bind(cfg, "General", "Allow in arena", defaultValue: true, "Allow players to join while the host is in the arena.");
			KillIfPreviouslyDead = Bind(cfg, "Late Join Behavior", "Kill If Previously Dead", defaultValue: true, "Automatically kill late-joining players who already died in the same level.");
			SpawnAtLastPosition = Bind(cfg, "Late Join Behavior", "Spawn At Last Position", defaultValue: true, "Spawn re-joining players at their last known position (or death head).");
			LockLobbyOnLevelGenerationFailure = Bind(cfg, "Late Join Behavior", "Lock Lobby On Level Generation Failure", defaultValue: true, "Controls if the lobby is automatically locked if a level (especially modded) reports a generation failure.\nVanilla levels rarely fail, but modded ones might sometimes report failure even if they load.\nSet to 'false' to keep the lobby open based on scene type, even on reported failure (unless it's a real crash to Arena).\nDefault: true (locks lobby on non-Arena failure).");
			ForceReloadOnLateJoin = Bind(cfg, "Advanced (Use With Caution)", "Force Level Reload on Late Join", defaultValue: false, "!! HIGHLY DISRUPTIVE !! Forces the host to reload the level for EVERYONE when a player joins late.");
			ModLogLevel = cfg.Bind<LogLevel>("Debugging", "Log Level", (LogLevel)16, "Minimum log level for L.A.T.E.\nChange on the fly to reduce spam or get more detail.\nValues: Fatal, Error, Warning, Message, Info, Debug, All, None");
			ApplyLogLevel(ModLogLevel.Value);
			ModLogLevel.SettingChanged += delegate
			{
				//IL_0005: Unknown result type (might be due to invalid IL or missing references)
				ApplyLogLevel(ModLogLevel.Value);
			};
			Log.LogDebug((object)"[Config] All entries bound");
		}

		private static ConfigEntry<bool> Bind(ConfigFile cfg, string section, string key, bool defaultValue, string description)
		{
			return cfg.Bind<bool>(section, key, defaultValue, description);
		}

		private static void ApplyLogLevel(LogLevel newLevel)
		{
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			PropertyInfo property = typeof(ManualLogSource).GetProperty("Level", BindingFlags.Instance | BindingFlags.Public);
			if (property != null && property.CanWrite)
			{
				property.SetValue(Log, newLevel);
			}
			else
			{
				FieldInfo field = typeof(ManualLogSource).GetField("level", BindingFlags.Instance | BindingFlags.NonPublic);
				if (field != null)
				{
					field.SetValue(Log, newLevel);
				}
			}
			Log.LogInfo((object)$"[Config] Runtime log level set to <{newLevel}>");
		}
	}
	internal static class DestructionManager
	{
		private static readonly HashSet<int> _destroyedViewIDs = new HashSet<int>();

		private static readonly HashSet<int> _brokenHingeViewIDs = new HashSet<int>();

		private const float HingeCacheRefreshInterval = 2f;

		private static PhysGrabHinge[] _hingeCache = Array.Empty<PhysGrabHinge>();

		private static float _hingeCacheLastRefreshTime;

		public static void MarkObjectAsDestroyed(int viewID)
		{
			if (_destroyedViewIDs.Add(viewID))
			{
				LateJoinEntry.Log.LogDebug((object)$"[DestructionManager] Marking ViewID {viewID} as destroyed.");
			}
			else
			{
				LateJoinEntry.Log.LogDebug((object)$"[DestructionManager] Duplicate destroy mark for ViewID {viewID} ignored.");
			}
			_brokenHingeViewIDs.Remove(viewID);
		}

		public static void MarkHingeAsBroken(PhysGrabHinge hingeInstance, PhotonView pv)
		{
			if ((Object)(object)pv == (Object)null)
			{
				LateJoinEntry.Log.LogWarning((object)"[DestructionManager] MarkHingeAsBroken called with null PhotonView.");
			}
			else if (_destroyedViewIDs.Contains(pv.ViewID))
			{
				LateJoinEntry.Log.LogDebug((object)$"[DestructionManager] Skipped break-mark – object {pv.ViewID} already destroyed.");
			}
			else if (_brokenHingeViewIDs.Add(pv.ViewID))
			{
				LateJoinEntry.Log.LogDebug((object)$"[DestructionManager] Marking hinge ViewID {pv.ViewID} as broken.");
			}
		}

		public static void ResetState()
		{
			LateJoinEntry.Log.LogDebug((object)"[DestructionManager] Clearing destruction/broken tracking & hinge cache.");
			_destroyedViewIDs.Clear();
			_brokenHingeViewIDs.Clear();
			_hingeCache = Array.Empty<PhysGrabHinge>();
			_hingeCacheLastRefreshTime = 0f;
		}

		public static void SyncHingeStatesForPlayer(Player targetPlayer)
		{
			if (!Utilities.IsRealMasterClient() || targetPlayer == null || !PhotonNetwork.InRoom || SemiFunc.RunIsLobbyMenu() || !PhotonNetwork.CurrentRoom.Players.ContainsKey(targetPlayer.ActorNumber) || (_destroyedViewIDs.Count == 0 && _brokenHingeViewIDs.Count == 0))
			{
				return;
			}
			string text = targetPlayer.NickName ?? $"ActorNr {targetPlayer.ActorNumber}";
			FieldInfo pghBrokenField = Utilities.pghBrokenField;
			FieldInfo pghClosedField = Utilities.pghClosedField;
			if (pghBrokenField == null || pghClosedField == null)
			{
				LateJoinEntry.Log.LogError((object)"[DestructionManager] Reflection field 'broken' or 'closed' missing – cannot sync hinge states.");
				return;
			}
			PhysGrabHinge[] cachedHinges = GetCachedHinges();
			LateJoinEntry.Log.LogInfo((object)$"[DestructionManager] Syncing ALL hinge states to {text} (Total hinges: {cachedHinges.Length}).");
			int num = 0;
			int num2 = 0;
			int num3 = 0;
			PhysGrabHinge[] array = cachedHinges;
			foreach (PhysGrabHinge val in array)
			{
				if ((Object)(object)val == (Object)null || (Object)(object)((Component)val).gameObject == (Object)null)
				{
					continue;
				}
				PhotonView photonView = Utilities.GetPhotonView((Component)(object)val);
				if ((Object)(object)photonView == (Object)null)
				{
					continue;
				}
				int viewID = photonView.ViewID;
				if (_destroyedViewIDs.Contains(viewID))
				{
					LateJoinEntry.Log.LogDebug((object)$"[DestructionManager] Skipping hinge {viewID} sync: Marked as destroyed.");
					continue;
				}
				bool flag;
				bool flag2;
				try
				{
					flag = (bool)(pghBrokenField.GetValue(val) ?? ((object)false));
					flag2 = (bool)(pghClosedField.GetValue(val) ?? ((object)true));
				}
				catch (Exception arg)
				{
					LateJoinEntry.Log.LogError((object)$"[DestructionManager] Reflection failed getting state for hinge {viewID}: {arg}");
					continue;
				}
				if (flag)
				{
					if (_brokenHingeViewIDs.Add(viewID))
					{
						LateJoinEntry.Log.LogDebug((object)$"[DestructionManager] Marking hinge {viewID} as broken during sync.");
					}
					LateJoinEntry.Log.LogDebug((object)$"[DestructionManager] Sending HingeBreakRPC for broken hinge {viewID} to {text}.");
					photonView.RPC("HingeBreakRPC", targetPlayer, Array.Empty<object>());
					num++;
					continue;
				}
				_brokenHingeViewIDs.Remove(viewID);
				if (!flag2)
				{
					LateJoinEntry.Log.LogDebug((object)$"[DestructionManager] Sending OpenImpulseRPC for OPEN hinge {viewID} to {text}.");
					photonView.RPC("OpenImpulseRPC", targetPlayer, Array.Empty<object>());
					num2++;
				}
				else
				{
					num3++;
					LateJoinEntry.Log.LogDebug((object)$"[DestructionManager] Hinge {viewID} is CLOSED on host, no RPC needed for {text}.");
				}
			}
			LateJoinEntry.Log.LogInfo((object)$"[DestructionManager] Hinge sync to {text} finished – Synced: {num} Broken, {num2} Opened, {num3} Confirmed Closed.");
		}

		private static PhysGrabHinge[] GetCachedHinges()
		{
			if (_hingeCache.Length == 0 || Time.unscaledTime - _hingeCacheLastRefreshTime > 2f)
			{
				_hingeCache = Object.FindObjectsOfType<PhysGrabHinge>();
				_hingeCacheLastRefreshTime = Time.unscaledTime;
			}
			return _hingeCache;
		}
	}
	internal static class EnemyManager
	{
		private static bool IsMaster()
		{
			return Utilities.IsRealMasterClient();
		}

		private static void ForEachEnemy(Action<Enemy, PhotonView?> action)
		{
			Enemy[] array = Object.FindObjectsOfType<Enemy>();
			LateJoinEntry.Log.LogDebug((object)$"[EnemyManager] ForEachEnemy found {array.Length} active enemies.");
			Enemy[] array2 = array;
			foreach (Enemy val in array2)
			{
				if ((Object)(object)val == (Object)null || (Object)(object)((Component)val).gameObject == (Object)null)
				{
					continue;
				}
				PhotonView val2 = null;
				try
				{
					if (Utilities.enemyPhotonViewField != null)
					{
						object? value = Utilities.enemyPhotonViewField.GetValue(val);
						val2 = (PhotonView)((value is PhotonView) ? value : null);
					}
				}
				catch (Exception ex)
				{
					LateJoinEntry.Log.LogWarning((object)("[EnemyManager] Error reflecting Enemy.photonView for '" + ((Object)((Component)val).gameObject).name + "': " + ex.Message));
				}
				if ((Object)(object)val2 == (Object)null)
				{
					val2 = ((Component)val).GetComponent<PhotonView>();
					if ((Object)(object)val2 == (Object)null)
					{
						LateJoinEntry.Log.LogWarning((object)("[EnemyManager] Could not get PhotonView for active enemy '" + ((Object)((Component)val).gameObject).name + "' via reflection or GetComponent. Skipping action."));
						continue;
					}
				}
				try
				{
					action(val, val2);
				}
				catch (Exception arg)
				{
					ManualLogSource log = LateJoinEntry.Log;
					GameObject gameObject = ((Component)val).gameObject;
					log.LogError((object)string.Format("[EnemyManager] Enemy action failed on '{0}' (ViewID: {1}): {2}", ((gameObject != null) ? ((Object)gameObject).name : null) ?? "NULL", (val2 != null) ? val2.ViewID : 0, arg));
				}
			}
		}

		public static void NotifyEnemiesOfNewPlayer(Player newPlayer, PlayerAvatar newPlayerAvatar)
		{
			if (newPlayer == null)
			{
				LateJoinEntry.Log.LogWarning((object)"[EnemyManager] NotifyEnemiesOfNewPlayer called with null player.");
				return;
			}
			if (!IsMaster())
			{
				LateJoinEntry.Log.LogDebug((object)("[EnemyManager] Not MasterClient, skipping new-player notification for " + (((newPlayer != null) ? newPlayer.NickName : null) ?? "<null>") + "."));
				return;
			}
			if ((Object)(object)newPlayerAvatar == (Object)null)
			{
				LateJoinEntry.Log.LogError((object)("[EnemyManager] newPlayerAvatar is null for " + newPlayer.NickName + ". Aborting."));
				return;
			}
			PhotonView photonView = Utilities.GetPhotonView((Component)(object)newPlayerAvatar);
			if ((Object)(object)photonView == (Object)null)
			{
				LateJoinEntry.Log.LogError((object)("[EnemyManager] Could not get PhotonView for " + newPlayer.NickName + "'s Avatar."));
				return;
			}
			int avatarViewId = photonView.ViewID;
			LateJoinEntry.Log.LogInfo((object)$"[EnemyManager] Notifying ACTIVE enemies about new player {newPlayer.NickName} (ViewID {avatarViewId}).");
			int updated = 0;
			ForEachEnemy(delegate(Enemy enemy, PhotonView? enemyPv)
			{
				try
				{
					enemy.PlayerAdded(avatarViewId);
					updated++;
					LateJoinEntry.Log.LogDebug((object)$"[EnemyManager] PlayerAdded({avatarViewId}) called on ACTIVE enemy '{((Object)((Component)enemy).gameObject).name}' (Enemy ViewID: {((enemyPv != null) ? enemyPv.ViewID : 0)}).");
				}
				catch (Exception ex)
				{
					LateJoinEntry.Log.LogError((object)("[EnemyManager] Error calling PlayerAdded on '" + ((Object)((Component)enemy).gameObject).name + "': " + ex.Message));
				}
			});
			LateJoinEntry.Log.LogInfo((object)$"[EnemyManager] Finished notifying {updated} active enemies about {newPlayer.NickName}.");
		}

		public static void NotifyEnemiesOfLeavingPlayer(Player leavingPlayer)
		{
			if (leavingPlayer == null)
			{
				LateJoinEntry.Log.LogWarning((object)"[EnemyManager] NotifyEnemiesOfLeavingPlayer called with null player.");
				return;
			}
			if (!IsMaster())
			{
				LateJoinEntry.Log.LogDebug((object)("[EnemyManager] Not MasterClient, skipping leaving-notification for " + (((leavingPlayer != null) ? leavingPlayer.NickName : null) ?? "<null>") + "."));
				return;
			}
			PlayerAvatar val = Utilities.FindPlayerAvatar(leavingPlayer);
			PhotonView val2 = null;
			if ((Object)(object)val != (Object)null)
			{
				val2 = Utilities.GetPhotonView((Component)(object)val);
			}
			if ((Object)(object)val2 == (Object)null)
			{
				LateJoinEntry.Log.LogWarning((object)("[EnemyManager] Could not resolve Avatar ViewID for leaving player " + leavingPlayer.NickName + ". Skipping enemy notification (player likely gone)."));
				return;
			}
			int avatarViewId = val2.ViewID;
			LateJoinEntry.Log.LogInfo((object)$"[EnemyManager] Notifying ACTIVE enemies that {leavingPlayer.NickName} (ViewID {avatarViewId}) left.");
			int updated = 0;
			ForEachEnemy(delegate(Enemy enemy, PhotonView? enemyPv)
			{
				Utilities.TryGetEnemyTargetViewIdReflected(enemy, out var targetViewId);
				bool flag = targetViewId == avatarViewId;
				try
				{
					enemy.PlayerRemoved(avatarViewId);
					updated++;
					LateJoinEntry.Log.LogDebug((object)$"[EnemyManager] PlayerRemoved({avatarViewId}) called on ACTIVE enemy '{((Object)((Component)enemy).gameObject).name}' (Enemy ViewID: {((enemyPv != null) ? enemyPv.ViewID : 0)}). WasTarget: {flag}");
				}
				catch (Exception ex)
				{
					LateJoinEntry.Log.LogError((object)("[EnemyManager] Error calling PlayerRemoved on '" + ((Object)((Component)enemy).gameObject).name + "': " + ex.Message));
				}
			});
			LateJoinEntry.Log.LogInfo((object)$"[EnemyManager] Finished notifying {updated} active enemies about {leavingPlayer.NickName} leaving.");
		}

		public static void SyncAllEnemyStatesForPlayer(Player targetPlayer)
		{
			//IL_0451: Unknown result type (might be due to invalid IL or missing references)
			//IL_0456: Unknown result type (might be due to invalid IL or missing references)
			//IL_0468: Unknown result type (might be due to invalid IL or missing references)
			//IL_0588: Unknown result type (might be due to invalid IL or missing references)
			//IL_058d: Unknown result type (might be due to invalid IL or missing references)
			//IL_059f: Unknown result type (might be due to invalid IL or missing references)
			//IL_06f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_06f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0709: Unknown result type (might be due to invalid IL or missing references)
			//IL_07fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0802: Unknown result type (might be due to invalid IL or missing references)
			//IL_0814: Unknown result type (might be due to invalid IL or missing references)
			//IL_08f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_08fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_0910: Unknown result type (might be due to invalid IL or missing references)
			//IL_0a04: Unknown result type (might be due to invalid IL or missing references)
			//IL_0a09: Unknown result type (might be due to invalid IL or missing references)
			//IL_0a1b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0b5b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0b60: Unknown result type (might be due to invalid IL or missing references)
			//IL_0b72: Unknown result type (might be due to invalid IL or missing references)
			//IL_0b92: Unknown result type (might be due to invalid IL or missing references)
			//IL_0be3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0be8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0bfa: Unknown result type (might be due to invalid IL or missing references)
			//IL_0cee: Unknown result type (might be due to invalid IL or missing references)
			//IL_0cf3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0d05: Unknown result type (might be due to invalid IL or missing references)
			//IL_0e5c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0e61: Unknown result type (might be due to invalid IL or missing references)
			//IL_0e73: Unknown result type (might be due to invalid IL or missing references)
			//IL_0fc6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0fcb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0fdd: Unknown result type (might be due to invalid IL or missing references)
			//IL_10c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_10c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_10d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_11cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_11d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_11e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_1310: Unknown result type (might be due to invalid IL or missing references)
			//IL_1315: Unknown result type (might be due to invalid IL or missing references)
			//IL_1327: Unknown result type (might be due to invalid IL or missing references)
			//IL_1415: Unknown result type (might be due to invalid IL or missing references)
			//IL_141a: Unknown result type (might be due to invalid IL or missing references)
			//IL_142c: Unknown result type (might be due to invalid IL or missing references)
			//IL_1511: Unknown result type (might be due to invalid IL or missing references)
			//IL_1516: Unknown result type (might be due to invalid IL or missing references)
			//IL_1528: Unknown result type (might be due to invalid IL or missing references)
			//IL_165e: Unknown result type (might be due to invalid IL or missing references)
			//IL_1663: Unknown result type (might be due to invalid IL or missing references)
			//IL_1675: Unknown result type (might be due to invalid IL or missing references)
			//IL_0537: Unknown result type (might be due to invalid IL or missing references)
			//IL_07ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_08a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_09b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0b0d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0c9d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0d32: Unknown result type (might be due to invalid IL or missing references)
			//IL_0d35: Invalid comparison between Unknown and I4
			//IL_1071: Unknown result type (might be due to invalid IL or missing references)
			//IL_117c: Unknown result type (might be due to invalid IL or missing references)
			//IL_12bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_13c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_14c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_160d: Unknown result type (might be due to invalid IL or missing references)
			//IL_1769: Unknown result type (might be due to invalid IL or missing references)
			//IL_06a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0aa2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0aa6: Invalid comparison between Unknown and I4
			//IL_0e0b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0d45: Unknown result type (might be due to invalid IL or missing references)
			//IL_0d4a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0d5c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0d73: Unknown result type (might be due to invalid IL or missing references)
			//IL_0d37: Unknown result type (might be due to invalid IL or missing references)
			//IL_0d3a: Invalid comparison between Unknown and I4
			//IL_0f75: Unknown result type (might be due to invalid IL or missing references)
			//IL_126b: Unknown result type (might be due to invalid IL or missing references)
			//IL_126e: Invalid comparison between Unknown and I4
			//IL_15af: Unknown result type (might be due to invalid IL or missing references)
			//IL_15b2: Invalid comparison between Unknown and I4
			//IL_170b: Unknown result type (might be due to invalid IL or missing references)
			//IL_170e: Invalid comparison between Unknown and I4
			//IL_0aa8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0aab: Invalid comparison between Unknown and I4
			//IL_15b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_15b7: Invalid comparison between Unknown and I4
			//IL_1710: Unknown result type (might be due to invalid IL or missing references)
			//IL_1713: Invalid comparison between Unknown and I4
			//IL_0aad: Unknown result type (might be due to invalid IL or missing references)
			//IL_0ab0: Invalid comparison between Unknown and I4
			//IL_15b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_15bc: Invalid comparison between Unknown and I4
			//IL_1715: Unknown result type (might be due to invalid IL or missing references)
			//IL_1718: Invalid comparison between Unknown and I4
			//IL_03c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_03e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_0400: Unknown result type (might be due to invalid IL or missing references)
			if (!IsMaster())
			{
				LateJoinEntry.Log.LogDebug((object)"[EnemyManager] Not MasterClient, skipping SyncAllEnemyStatesForPlayer.");
				return;
			}
			if (targetPlayer == null)
			{
				LateJoinEntry.Log.LogWarning((object)"[EnemyManager] SyncAllEnemyStatesForPlayer called with null targetPlayer.");
				return;
			}
			if (Utilities.enemy_EnemyParentField == null || Utilities.ep_SpawnedField == null)
			{
				LateJoinEntry.Log.LogError((object)"[EnemyManager] CRITICAL REFLECTION FAILURE: Cannot find required internal fields (Enemy.EnemyParent, EnemyParent.Spawned, EnemyParent.photonView). Aborting enemy sync.");
				return;
			}
			string text = targetPlayer.NickName ?? $"ActorNr {targetPlayer.ActorNumber}";
			LateJoinEntry.Log.LogInfo((object)("[EnemyManager] === Starting FULL enemy state sync for " + text + " using EnemyParent RPCs (with reflection) ==="));
			int num = 0;
			int num2 = 0;
			int num3 = 0;
			int num4 = 0;
			int num5 = 0;
			int num6 = 0;
			Enemy[] array = Object.FindObjectsOfType<Enemy>(true);
			LateJoinEntry.Log.LogDebug((object)$"[EnemyManager] Found {array.Length} total Enemy components (including inactive) for state sync.");
			Enemy[] array2 = array;
			foreach (Enemy val in array2)
			{
				num++;
				if ((Object)(object)val == (Object)null || (Object)(object)((Component)val).gameObject == (Object)null)
				{
					LateJoinEntry.Log.LogWarning((object)$"[EnemyManager] Encountered null enemy instance at index {num - 1}. Skipping.");
					continue;
				}
				string name = ((Object)((Component)val).gameObject).name;
				EnemyParent val2 = null;
				PhotonView val3 = null;
				try
				{
					object? value = Utilities.enemy_EnemyParentField.GetValue(val);
					val2 = (EnemyParent)((value is EnemyParent) ? value : null);
					if (!((Object)(object)val2 == (Object)null))
					{
						goto IL_0192;
					}
					val2 = ((Component)val).GetComponentInParent<EnemyParent>();
					if ((Object)(object)val2 == (Object)null)
					{
						LateJoinEntry.Log.LogWarning((object)("[EnemyManager] Enemy '" + name + "' has no EnemyParent component (checked reflection and hierarchy). Skipping sync."));
						continue;
					}
					LateJoinEntry.Log.LogDebug((object)("[EnemyManager] Used GetComponentInParent fallback for EnemyParent on '" + name + "'."));
					goto IL_0192;
					IL_0192:
					val3 = ((Component)val2).GetComponent<PhotonView>();
					if ((Object)(object)val3 == (Object)null)
					{
						LateJoinEntry.Log.LogWarning((object)("[EnemyManager] Could not get PhotonView component for EnemyParent of '" + name + "'. Skipping sync."));
						continue;
					}
					goto IL_01e6;
				}
				catch (Exception arg)
				{
					LateJoinEntry.Log.LogError((object)$"[EnemyManager] Reflection error getting EnemyParent for '{name}': {arg}. Skipping sync.");
				}
				continue;
				IL_01e6:
				PhotonView val4 = null;
				try
				{
					if (Utilities.enemyPhotonViewField != null)
					{
						object? value2 = Utilities.enemyPhotonViewField.GetValue(val);
						val4 = (PhotonView)((value2 is PhotonView) ? value2 : null);
					}
				}
				catch (Exception ex)
				{
					LateJoinEntry.Log.LogWarning((object)("[EnemyManager] Error reflecting Enemy.photonView for '" + name + "': " + ex.Message));
				}
				if ((Object)(object)val4 == (Object)null)
				{
					val4 = ((Component)val).GetComponent<PhotonView>();
					if ((Object)(object)val4 == (Object)null)
					{
						LateJoinEntry.Log.LogWarning((object)("[EnemyManager] Could not get Enemy's own PhotonView for '" + name + "'. Skipping detailed state sync."));
					}
					else
					{
						LateJoinEntry.Log.LogDebug((object)("[EnemyManager] Used GetComponent fallback for Enemy PhotonView on '" + name + "'."));
					}
				}
				try
				{
					bool flag = false;
					try
					{
						object value3 = Utilities.ep_SpawnedField.GetValue(val2);
						if (value3 is bool)
						{
							flag = (bool)value3;
						}
						else
						{
							LateJoinEntry.Log.LogWarning((object)$"[EnemyManager] Reflected EnemyParent.Spawned for '{name}' was not a bool (Type: {value3?.GetType()}). Assuming false.");
						}
					}
					catch (Exception arg2)
					{
						LateJoinEntry.Log.LogError((object)$"[EnemyManager] Reflection error getting EnemyParent.Spawned for '{name}': {arg2}. Assuming false.");
						flag = false;
					}
					if (flag)
					{
						LateJoinEntry.Log.LogDebug((object)$"[EnemyManager] Enemy '{name}' is SPAWNED on host. Sending SpawnRPC to {text}. (Parent PV: {val3.ViewID})");
						val3.RPC("SpawnRPC", targetPlayer, Array.Empty<object>());
						num2++;
						LateJoinEntry.Log.LogDebug((object)$"[EnemyManager] Syncing detailed state for spawned enemy '{name}' (Enemy PV: {((val4 != null) ? val4.ViewID : 0)})...");
						if ((Object)(object)val4 == (Object)null)
						{
							LateJoinEntry.Log.LogWarning((object)("[EnemyManager]   Skipping detailed sync for '" + name + "' because its own PhotonView is missing."));
							continue;
						}
						if (Utilities.TryGetEnemyTargetViewIdReflected(val, out var targetViewId) && targetViewId > 0)
						{
							LateJoinEntry.Log.LogDebug((object)$"[EnemyManager]   Enemy '{name}' TargetPlayerViewID {targetViewId} (Should be synced by base Enemy serialization).");
						}
						bool flag2 = false;
						EnemyAnimal component = ((Component)val).GetComponent<EnemyAnimal>();
						if ((Object)(object)component != (Object)null)
						{
							try
							{
								State currentState = component.currentState;
								val4.RPC("UpdateStateRPC", targetPlayer, new object[1] { currentState });
								num4++;
								flag2 = true;
								LateJoinEntry.Log.LogDebug((object)$"[EnemyManager]   Synced EnemyAnimal state '{currentState}'.");
							}
							catch (Exception ex2)
							{
								LateJoinEntry.Log.LogError((object)("[EnemyManager] Error syncing EnemyAnimal state for " + name + ": " + ex2.Message));
							}
						}
						EnemyBang component2 = ((Component)val).GetComponent<EnemyBang>();
						if ((Object)(object)component2 != (Object)null)
						{
							try
							{
								State currentState2 = component2.currentState;
								val4.RPC("UpdateStateRPC", targetPlayer, new object[1] { currentState2 });
								FieldInfo fieldInfo = AccessTools.Field(typeof(EnemyBang), "fuseActive");
								FieldInfo fieldInfo2 = AccessTools.Field(typeof(EnemyBang), "fuseLerp");
								if (fieldInfo != null && fieldInfo2 != null)
								{
									bool flag3 = (bool)fieldInfo.GetValue(component2);
									float num7 = (float)fieldInfo2.GetValue(component2);
									val4.RPC("FuseRPC", targetPlayer, new object[2] { flag3, num7 });
									LateJoinEntry.Log.LogDebug((object)$"[EnemyManager]   Synced EnemyBang fuse state: Active={flag3}, Lerp={num7:F2}");
									num6++;
								}
								num4++;
								flag2 = true;
								LateJoinEntry.Log.LogDebug((object)$"[EnemyManager]   Synced EnemyBang state '{currentState2}'.");
							}
							catch (Exception ex3)
							{
								LateJoinEntry.Log.LogError((object)("[EnemyManager] Error syncing EnemyBang state for " + name + ": " + ex3.Message));
							}
						}
						EnemyBeamer component3 = ((Component)val).GetComponent<EnemyBeamer>();
						if ((Object)(object)component3 != (Object)null)
						{
							try
							{
								State currentState3 = component3.currentState;
								val4.RPC("UpdateStateRPC", targetPlayer, new object[1] { currentState3 });
								FieldInfo fieldInfo3 = AccessTools.Field(typeof(EnemyBeamer), "moveFast");
								if (fieldInfo3 != null)
								{
									bool flag4 = (bool)fieldInfo3.GetValue(component3);
									val4.RPC("MoveFastRPC", targetPlayer, new object[1] { flag4 });
									LateJoinEntry.Log.LogDebug((object)$"[EnemyManager]   Synced EnemyBeamer moveFast state: {flag4}");
									num6++;
								}
								PlayerAvatar internalPlayerTarget = Utilities.GetInternalPlayerTarget(component3, Utilities.enemyBeamer_playerTargetField, "EnemyBeamer");
								if ((Object)(object)internalPlayerTarget != (Object)null && (Object)(object)internalPlayerTarget.photonView != (Object)null)
								{
									val4.RPC("UpdatePlayerTargetRPC", targetPlayer, new object[1] { internalPlayerTarget.photonView.ViewID });
									LateJoinEntry.Log.LogDebug((object)("[EnemyManager]   Synced EnemyBeamer target: " + ((Object)internalPlayerTarget).name));
									num6++;
								}
								num4++;
								flag2 = true;
								LateJoinEntry.Log.LogDebug((object)$"[EnemyManager]   Synced EnemyBeamer state '{currentState3}'.");
							}
							catch (Exception ex4)
							{
								LateJoinEntry.Log.LogError((object)("[EnemyManager] Error syncing EnemyBeamer state for " + name + ": " + ex4.Message));
							}
						}
						EnemyBowtie component4 = ((Component)val).GetComponent<EnemyBowtie>();
						if ((Object)(object)component4 != (Object)null)
						{
							try
							{
								State currentState4 = component4.currentState;
								val4.RPC("UpdateStateRPC", targetPlayer, new object[1] { currentState4 });
								PlayerAvatar internalPlayerTarget2 = Utilities.GetInternalPlayerTarget(component4, AccessTools.Field(typeof(EnemyBowtie), "playerTarget"), "EnemyBowtie");
								if ((Object)(object)internalPlayerTarget2 != (Object)null && (Object)(object)internalPlayerTarget2.photonView != (Object)null)
								{
									val4.RPC("NoticeRPC", targetPlayer, new object[1] { internalPlayerTarget2.photonView.ViewID });
									LateJoinEntry.Log.LogDebug((object)("[EnemyManager]   Synced EnemyBowtie notice for target: " + ((Object)internalPlayerTarget2).name));
									num6++;
								}
								num4++;
								flag2 = true;
								LateJoinEntry.Log.LogDebug((object)$"[EnemyManager]   Synced EnemyBowtie state '{currentState4}'.");
							}
							catch (Exception ex5)
							{
								LateJoinEntry.Log.LogError((object)("[EnemyManager] Error syncing EnemyBowtie state for " + name + ": " + ex5.Message));
							}
						}
						EnemyCeilingEye component5 = ((Component)val).GetComponent<EnemyCeilingEye>();
						if ((Object)(object)component5 != (Object)null)
						{
							try
							{
								State currentState5 = component5.currentState;
								val4.RPC("UpdateStateRPC", targetPlayer, new object[1] { currentState5 });
								PlayerAvatar internalPlayerTarget3 = Utilities.GetInternalPlayerTarget(component5, Utilities.enemyCeilingEye_targetPlayerField, "EnemyCeilingEye");
								if ((Object)(object)internalPlayerTarget3 != (Object)null && (Object)(object)internalPlayerTarget3.photonView != (Object)null)
								{
									val4.RPC("TargetPlayerRPC", targetPlayer, new object[1] { internalPlayerTarget3.photonView.ViewID });
									LateJoinEntry.Log.LogDebug((object)("[EnemyManager]   Synced EnemyCeilingEye target: " + ((Object)internalPlayerTarget3).name));
									num6++;
								}
								num4++;
								flag2 = true;
								LateJoinEntry.Log.LogDebug((object)$"[EnemyManager]   Synced EnemyCeilingEye state '{currentState5}'.");
							}
							catch (Exception ex6)
							{
								LateJoinEntry.Log.LogError((object)("[EnemyManager] Error syncing EnemyCeilingEye state for " + name + ": " + ex6.Message));
							}
						}
						EnemyDuck component6 = ((Component)val).GetComponent<EnemyDuck>();
						if ((Object)(object)component6 != (Object)null)
						{
							try
							{
								State currentState6 = component6.currentState;
								val4.RPC("UpdateStateRPC", targetPlayer, new object[1] { currentState6 });
								PlayerAvatar internalPlayerTarget4 = Utilities.GetInternalPlayerTarget(component6, AccessTools.Field(typeof(EnemyDuck), "playerTarget"), "EnemyDuck");
								if ((Object)(object)internalPlayerTarget4 != (Object)null && (Object)(object)internalPlayerTarget4.photonView != (Object)null)
								{
									val4.RPC("UpdatePlayerTargetRPC", targetPlayer, new object[1] { internalPlayerTarget4.photonView.ViewID });
									LateJoinEntry.Log.LogDebug((object)("[EnemyManager]   Synced EnemyDuck target: " + ((Object)internalPlayerTarget4).name));
									num6++;
								}
								num4++;
								flag2 = true;
								LateJoinEntry.Log.LogDebug((object)$"[EnemyManager]   Synced EnemyDuck state '{currentState6}'.");
							}
							catch (Exception ex7)
							{
								LateJoinEntry.Log.LogError((object)("[EnemyManager] Error syncing EnemyDuck state for " + name + ": " + ex7.Message));
							}
						}
						EnemyFloater component7 = ((Component)val).GetComponent<EnemyFloater>();
						if ((Object)(object)component7 != (Object)null)
						{
							try
							{
								State currentState7 = component7.currentState;
								val4.RPC("UpdateStateRPC", targetPlayer, new object[1] { currentState7 });
								PlayerAvatar internalPlayerTarget5 = Utilities.GetInternalPlayerTarget(component7, Utilities.enemyFloater_targetPlayerField, "EnemyFloater");
								if ((Object)(object)internalPlayerTarget5 != (Object)null && (Object)(object)internalPlayerTarget5.photonView != (Object)null)
								{
									val4.RPC("TargetPlayerRPC", targetPlayer, new object[1] { internalPlayerTarget5.photonView.ViewID });
									LateJoinEntry.Log.LogDebug((object)("[EnemyManager]   Synced EnemyFloater target: " + ((Object)internalPlayerTarget5).name));
									num6++;
									if ((int)currentState7 != 9 && (int)currentState7 != 7 && (int)currentState7 != 8)
									{
										val4.RPC("NoticeRPC", targetPlayer, new object[1] { internalPlayerTarget5.photonView.ViewID });
										LateJoinEntry.Log.LogDebug((object)("[EnemyManager]   Synced EnemyFloater notice RPC for target: " + ((Object)internalPlayerTarget5).name));
										num6++;
									}
								}
								num4++;
								flag2 = true;
								LateJoinEntry.Log.LogDebug((object)$"[EnemyManager]   Synced EnemyFloater state '{currentState7}'.");
							}
							catch (Exception ex8)
							{
								LateJoinEntry.Log.LogError((object)("[EnemyManager] Error syncing EnemyFloater state for " + name + ": " + ex8.Message));
							}
						}
						EnemyGnome component8 = ((Component)val).GetComponent<EnemyGnome>();
						if ((Object)(object)component8 != (Object)null)
						{
							try
							{
								State currentState8 = component8.currentState;
								val4.RPC("UpdateStateRPC", targetPlayer, new object[1] { currentState8 });
								num4++;
								flag2 = true;
								LateJoinEntry.Log.LogDebug((object)$"[EnemyManager]   Synced EnemyGnome state '{currentState8}'.");
							}
							catch (Exception ex9)
							{
								LateJoinEntry.Log.LogError((object)("[EnemyManager] Error syncing EnemyGnome state for " + name + ": " + ex9.Message));
							}
						}
						EnemyHidden component9 = ((Component)val).GetComponent<EnemyHidden>();
						if ((Object)(object)component9 != (Object)null)
						{
							try
							{
								State currentState9 = component9.currentState;
								val4.RPC("UpdateStateRPC", targetPlayer, new object[1] { currentState9 });
								PlayerAvatar internalPlayerTarget6 = Utilities.GetInternalPlayerTarget(component9, AccessTools.Field(typeof(EnemyHidden), "playerTarget"), "EnemyHidden");
								if ((Object)(object)internalPlayerTarget6 != (Object)null && (Object)(object)internalPlayerTarget6.photonView != (Object)null)
								{
									val4.RPC("UpdatePlayerTargetRPC", targetPlayer, new object[1] { internalPlayerTarget6.photonView.ViewID });
									LateJoinEntry.Log.LogDebug((object)("[EnemyManager]   Synced EnemyHidden target: " + ((Object)internalPlayerTarget6).name));
									num6++;
								}
								num4++;
								flag2 = true;
								LateJoinEntry.Log.LogDebug((object)$"[EnemyManager]   Synced EnemyHidden state '{currentState9}'.");
							}
							catch (Exception ex10)
							{
								LateJoinEntry.Log.LogError((object)("[EnemyManager] Error syncing EnemyHidden state for " + name + ": " + ex10.Message));
							}
						}
						EnemyHunter component10 = ((Component)val).GetComponent<EnemyHunter>();
						if ((Object)(object)component10 != (Object)null)
						{
							try
							{
								State currentState10 = component10.currentState;
								val4.RPC("UpdateStateRPC", targetPlayer, new object[1] { currentState10 });
								FieldInfo fieldInfo4 = AccessTools.Field(typeof(EnemyHunter), "investigatePoint");
								if (fieldInfo4 != null && ((int)currentState10 == 3 || (int)currentState10 == 5))
								{
									Vector3 val5 = (Vector3)fieldInfo4.GetValue(component10);
									val4.RPC("UpdateInvestigationPoint", targetPlayer, new object[1] { val5 });
									LateJoinEntry.Log.LogDebug((object)$"[EnemyManager]   Synced EnemyHunter investigate point: {val5}");
									num6++;
								}
								FieldInfo fieldInfo5 = AccessTools.Field(typeof(EnemyHunter), "moveFast");
								if (fieldInfo5 != null)
								{
									bool flag5 = (bool)fieldInfo5.GetValue(component10);
									val4.RPC("MoveFastRPC", targetPlayer, new object[1] { flag5 });
									LateJoinEntry.Log.LogDebug((object)$"[EnemyManager]   Synced EnemyHunter moveFast: {flag5}");
									num6++;
								}
								num4++;
								flag2 = true;
								LateJoinEntry.Log.LogDebug((object)$"[EnemyManager]   Synced EnemyHunter state '{currentState10}'.");
							}
							catch (Exception ex11)
							{
								LateJoinEntry.Log.LogError((object)("[EnemyManager] Error syncing EnemyHunter state for " + name + ": " + ex11.Message));
							}
						}
						EnemyRobe component11 = ((Component)val).GetComponent<EnemyRobe>();
						if ((Object)(object)component11 != (Object)null)
						{
							try
							{
								State currentState11 = component11.currentState;
								val4.RPC("UpdateStateRPC", targetPlayer, new object[1] { currentState11 });
								PlayerAvatar internalPlayerTarget7 = Utilities.GetInternalPlayerTarget(component11, Utilities.enemyRobe_targetPlayerField, "EnemyRobe");
								if ((Object)(object)internalPlayerTarget7 != (Object)null && (Object)(object)internalPlayerTarget7.photonView != (Object)null)
								{
									val4.RPC("TargetPlayerRPC", targetPlayer, new object[1] { internalPlayerTarget7.photonView.ViewID });
									LateJoinEntry.Log.LogDebug((object)("[EnemyManager]   Synced EnemyRobe target: " + ((Object)internalPlayerTarget7).name));
									num6++;
								}
								FieldInfo fieldInfo6 = AccessTools.Field(typeof(EnemyRobe), "isOnScreen");
								if (fieldInfo6 != null)
								{
									bool flag6 = (bool)fieldInfo6.GetValue(component11);
									val4.RPC("UpdateOnScreenRPC", targetPlayer, new object[1] { flag6 });
									LateJoinEntry.Log.LogDebug((object)$"[EnemyManager]   Synced EnemyRobe isOnScreen: {flag6}");
									num6++;
								}
								num4++;
								flag2 = true;
								LateJoinEntry.Log.LogDebug((object)$"[EnemyManager]   Synced EnemyRobe state '{currentState11}'.");
							}
							catch (Exception ex12)
							{
								LateJoinEntry.Log.LogError((object)("[EnemyManager] Error syncing EnemyRobe state for " + name + ": " + ex12.Message));
							}
						}
						EnemyRunner component12 = ((Component)val).GetComponent<EnemyRunner>();
						if ((Object)(object)component12 != (Object)null)
						{
							try
							{
								State currentState12 = component12.currentState;
								val4.RPC("UpdateStateRPC", targetPlayer, new object[1] { currentState12 });
								PlayerAvatar internalPlayerTarget8 = Utilities.GetInternalPlayerTarget(component12, Utilities.enemyRunner_targetPlayerField, "EnemyRunner");
								if ((Object)(object)internalPlayerTarget8 != (Object)null && (Object)(object)internalPlayerTarget8.photonView != (Object)null)
								{
									val4.RPC("UpdatePlayerTargetRPC", targetPlayer, new object[1] { internalPlayerTarget8.photonView.ViewID });
									LateJoinEntry.Log.LogDebug((object)("[EnemyManager]   Synced EnemyRunner target: " + ((Object)internalPlayerTarget8).name));
									num6++;
								}
								num4++;
								flag2 = true;
								LateJoinEntry.Log.LogDebug((object)$"[EnemyManager]   Synced EnemyRunner state '{currentState12}'.");
							}
							catch (Exception ex13)
							{
								LateJoinEntry.Log.LogError((object)("[EnemyManager] Error syncing EnemyRunner state for " + name + ": " + ex13.Message));
							}
						}
						EnemySlowMouth component13 = ((Component)val).GetComponent<EnemySlowMouth>();
						if ((Object)(object)component13 != (Object)null)
						{
							try
							{
								State currentState13 = component13.currentState;
								val4.RPC("UpdateStateRPC", targetPlayer, new object[1] { currentState13 });
								PlayerAvatar internalPlayerTarget9 = Utilities.GetInternalPlayerTarget(component13, AccessTools.Field(typeof(EnemySlowMouth), "playerTarget"), "EnemySlowMouth");
								if ((Object)(object)internalPlayerTarget9 != (Object)null && (Object)(object)internalPlayerTarget9.photonView != (Object)null)
								{
									val4.RPC("UpdatePlayerTargetRPC", targetPlayer, new object[1] { internalPlayerTarget9.photonView.ViewID });
									LateJoinEntry.Log.LogDebug((object)("[EnemyManager]   Synced EnemySlowMouth target: " + ((Object)internalPlayerTarget9).name));
									num6++;
								}
								num4++;
								flag2 = true;
								LateJoinEntry.Log.LogDebug((object)$"[EnemyManager]   Synced EnemySlowMouth state '{currentState13}'.");
							}
							catch (Exception ex14)
							{
								LateJoinEntry.Log.LogError((object)("[EnemyManager] Error syncing EnemySlowMouth state for " + name + ": " + ex14.Message));
							}
						}
						EnemySlowWalker component14 = ((Component)val).GetComponent<EnemySlowWalker>();
						if ((Object)(object)component14 != (Object)null)
						{
							try
							{
								State currentState14 = component14.currentState;
								val4.RPC("UpdateStateRPC", targetPlayer, new object[1] { currentState14 });
								PlayerAvatar internalPlayerTarget10 = Utilities.GetInternalPlayerTarget(component14, Utilities.enemySlowWalker_targetPlayerField, "EnemySlowWalker");
								if ((Object)(object)internalPlayerTarget10 != (Object)null && (Object)(object)internalPlayerTarget10.photonView != (Object)null)
								{
									val4.RPC("TargetPlayerRPC", targetPlayer, new object[1] { internalPlayerTarget10.photonView.ViewID });
									LateJoinEntry.Log.LogDebug((object)("[EnemyManager]   Synced EnemySlowWalker target: " + ((Object)internalPlayerTarget10).name));
									num6++;
									if ((int)currentState14 == 4)
									{
										val4.RPC("NoticeRPC", targetPlayer, new object[1] { internalPlayerTarget10.photonView.ViewID });
										LateJoinEntry.Log.LogDebug((object)"[EnemyManager]   Synced EnemySlowWalker notice RPC.");
										num6++;
									}
								}
								num4++;
								flag2 = true;
								LateJoinEntry.Log.LogDebug((object)$"[EnemyManager]   Synced EnemySlowWalker state '{currentState14}'.");
							}
							catch (Exception ex15)
							{
								LateJoinEntry.Log.LogError((object)("[EnemyManager] Error syncing EnemySlowWalker state for " + name + ": " + ex15.Message));
							}
						}
						EnemyThinMan component15 = ((Component)val).GetComponent<EnemyThinMan>();
						if ((Object)(object)component15 != (Object)null)
						{
							try
							{
								State currentState15 = component15.currentState;
								val4.RPC("UpdateStateRPC", targetPlayer, new object[1] { currentState15 });
								PlayerAvatar internalPlayerTarget11 = Utilities.GetInternalPlayerTarget(component15, Utilities.enemyThinMan_playerTargetField, "EnemyThinMan");
								if ((Object)(object)internalPlayerTarget11 != (Object)null && (Object)(object)internalPlayerTarget11.photonView != (Object)null)
								{
									val4.RPC("SetTargetRPC", targetPlayer, new object[2]
									{
										internalPlayerTarget11.photonView.ViewID,
										true
									});
									LateJoinEntry.Log.LogDebug((object)("[EnemyManager]   Synced EnemyThinMan target: " + ((Object)internalPlayerTarget11).name));
									num6++;
								}
								num4++;
								flag2 = true;
								LateJoinEntry.Log.LogDebug((object)$"[EnemyManager]   Synced EnemyThinMan state '{currentState15}'.");
							}
							catch (Exception ex16)
							{
								LateJoinEntry.Log.LogError((object)("[EnemyManager] Error syncing EnemyThinMan state for " + name + ": " + ex16.Message));
							}
						}
						EnemyTumbler component16 = ((Component)val).GetComponent<EnemyTumbler>();
						if ((Object)(object)component16 != (Object)null)
						{
							try
							{
								State currentState16 = component16.currentState;
								val4.RPC("UpdateStateRPC", targetPlayer, new object[1] { currentState16 });
								PlayerAvatar internalPlayerTarget12 = Utilities.GetInternalPlayerTarget(component16, Utilities.enemyTumbler_targetPlayerField, "EnemyTumbler");
								if ((Object)(object)internalPlayerTarget12 != (Object)null && (Object)(object)internalPlayerTarget12.photonView != (Object)null)
								{
									val4.RPC("TargetPlayerRPC", targetPlayer, new object[1] { internalPlayerTarget12.photonView.ViewID });
									LateJoinEntry.Log.LogDebug((object)("[EnemyManager]   Synced EnemyTumbler target: " + ((Object)internalPlayerTarget12).name));
									num6++;
								}
								num4++;
								flag2 = true;
								LateJoinEntry.Log.LogDebug((object)$"[EnemyManager]   Synced EnemyTumbler state '{currentState16}'.");
							}
							catch (Exception ex17)
							{
								LateJoinEntry.Log.LogError((object)("[EnemyManager] Error syncing EnemyTumbler state for " + name + ": " + ex17.Message));
							}
						}
						EnemyUpscream component17 = ((Component)val).GetComponent<EnemyUpscream>();
						if ((Object)(object)component17 != (Object)null)
						{
							try
							{
								State currentState17 = component17.currentState;
								val4.RPC("UpdateStateRPC", targetPlayer, new object[1] { currentState17 });
								PlayerAvatar internalPlayerTarget13 = Utilities.GetInternalPlayerTarget(component17, Utilities.enemyUpscream_targetPlayerField, "EnemyUpscream");
								if ((Object)(object)internalPlayerTarget13 != (Object)null && (Object)(object)internalPlayerTarget13.photonView != (Object)null)
								{
									val4.RPC("TargetPlayerRPC", targetPlayer, new object[1] { internalPlayerTarget13.photonView.ViewID });
									LateJoinEntry.Log.LogDebug((object)("[EnemyManager]   Synced EnemyUpscream target: " + ((Object)internalPlayerTarget13).name));
									num6++;
									if ((int)currentState17 == 4 || (int)currentState17 == 5 || (int)currentState17 == 6)
									{
										val4.RPC("NoticeSetRPC", targetPlayer, new object[1] { internalPlayerTarget13.photonView.ViewID });
										LateJoinEntry.Log.LogDebug((object)"[EnemyManager]   Synced EnemyUpscream notice RPC.");
										num6++;
									}
								}
								num4++;
								flag2 = true;
								LateJoinEntry.Log.LogDebug((object)$"[EnemyManager]   Synced EnemyUpscream state '{currentState17}'.");
							}
							catch (Exception ex18)
							{
								LateJoinEntry.Log.LogError((object)("[EnemyManager] Error syncing EnemyUpscream state for " + name + ": " + ex18.Message));
							}
						}
						EnemyValuableThrower component18 = ((Component)val).GetComponent<EnemyValuableThrower>();
						if ((Object)(object)component18 != (Object)null)
						{
							try
							{
								State currentState18 = component18.currentState;
								val4.RPC("UpdateStateRPC", targetPlayer, new object[1] { currentState18 });
								PlayerAvatar internalPlayerTarget14 = Utilities.GetInternalPlayerTarget(component18, AccessTools.Field(typeof(EnemyValuableThrower), "playerTarget"), "EnemyValuableThrower");
								if ((Object)(object)internalPlayerTarget14 != (Object)null && (Object)(object)internalPlayerTarget14.photonView != (Object)null)
								{
									val4.RPC("UpdatePlayerTargetRPC", targetPlayer, new object[1] { internalPlayerTarget14.photonView.ViewID });
									LateJoinEntry.Log.LogDebug((object)("[EnemyManager]   Synced EnemyValuableThrower target: " + ((Object)internalPlayerTarget14).name));
									num6++;
									if ((int)currentState18 == 4 || (int)currentState18 == 5 || (int)currentState18 == 6)
									{
										val4.RPC("NoticeRPC", targetPlayer, new object[1] { internalPlayerTarget14.photonView.ViewID });
										LateJoinEntry.Log.LogDebug((object)"[EnemyManager]   Synced EnemyValuableThrower notice RPC.");
										num6++;
									}
								}
								num4++;
								flag2 = true;
								LateJoinEntry.Log.LogDebug((object)$"[EnemyManager]   Synced EnemyValuableThrower state '{currentState18}'.");
							}
							catch (Exception ex19)
							{
								LateJoinEntry.Log.LogError((object)("[EnemyManager] Error syncing EnemyValuableThrower state for " + name + ": " + ex19.Message));
							}
						}
						if (!flag2)
						{
							LateJoinEntry.Log.LogDebug((object)("[EnemyManager]   No specific enemy type found or synced for '" + name + "'. Base state from EnemyParent: Spawned."));
						}
						if (val.FreezeTimer > 0f)
						{
							try
							{
								val4.RPC("FreezeRPC", targetPlayer, new object[1] { val.FreezeTimer });
								num5++;
								LateJoinEntry.Log.LogDebug((object)$"[EnemyManager]   Synced FreezeTimer ({val.FreezeTimer:F1}s).");
							}
							catch (Exception ex20)
							{
								LateJoinEntry.Log.LogError((object)("[EnemyManager] Error sending FreezeRPC for " + name + ": " + ex20.Message));
							}
						}
					}
					else
					{
						LateJoinEntry.Log.LogDebug((object)$"[EnemyManager] Enemy '{name}' is DESPAWNED on host. Sending DespawnRPC to {text}. (Parent PV: {val3.ViewID})");
						val3.RPC("DespawnRPC", targetPlayer, Array.Empty<object>());
						num3++;
					}
				}
				catch (Exception arg3)
				{
					LateJoinEntry.Log.LogError((object)$"[EnemyManager] CRITICAL error processing enemy '{name}' (Parent PV: {((val3 != null) ? val3.ViewID : 0)}) for state sync: {arg3}");
				}
			}
			LateJoinEntry.Log.LogInfo((object)("[EnemyManager] === Finished FULL enemy state sync for " + text + ". ==="));
			LateJoinEntry.Log.LogInfo((object)$"    Processed: {num}, SpawnRPCs Sent: {num2}, DespawnRPCs Sent: {num3}");
			LateJoinEntry.Log.LogInfo((object)$"    SpecificStates Synced (for Spawned): {num4}, Freezes Synced: {num5}, OtherStates Synced: {num6}");
		}
	}
	internal enum GameVersion
	{
		Unknown,
		Stable,
		Beta
	}
	internal static class GameVersionSupport
	{
		private static GameVersion _detectedVersion;

		private static MethodInfo? _unlockLobbyMethod;

		private static MethodInfo? _lockLobbyMethod;

		private static bool _reflectionChecked;

		private static ManualLogSource Log => LateJoinEntry.Log;

		public static GameVersion DetectVersion()
		{
			if (_detectedVersion != 0)
			{
				return _detectedVersion;
			}
			Log.LogInfo((object)"[VersionDetect] Attempting to detect game version via SteamManager signatures...");
			MethodInfo methodInfo = AccessTools.Method(typeof(SteamManager), "UnlockLobby", new Type[1] { typeof(bool) }, (Type[])null);
			if (methodInfo != null)
			{
				Log.LogInfo((object)"[VersionDetect] Found UnlockLobby(bool) signature. Assuming BETA version.");
				_detectedVersion = GameVersion.Beta;
				_unlockLobbyMethod = methodInfo;
				_lockLobbyMethod = AccessTools.Method(typeof(SteamManager), "LockLobby", Type.EmptyTypes, (Type[])null);
			}
			else
			{
				MethodInfo methodInfo2 = AccessTools.Method(typeof(SteamManager), "UnlockLobby", Type.EmptyTypes, (Type[])null);
				if (methodInfo2 != null)
				{
					Log.LogInfo((object)"[VersionDetect] Found parameterless UnlockLobby() signature. Assuming STABLE version.");
					_detectedVersion = GameVersion.Stable;
					_unlockLobbyMethod = methodInfo2;
					_lockLobbyMethod = AccessTools.Method(typeof(SteamManager), "LockLobby", Type.EmptyTypes, (Type[])null);
				}
				else
				{
					Log.LogError((object)"[VersionDetect] CRITICAL: Could not find UnlockLobby() OR UnlockLobby(bool) in SteamManager! Version detection failed.");
					_detectedVersion = GameVersion.Unknown;
				}
			}
			if (_lockLobbyMethod == null && _detectedVersion != 0)
			{
				Log.LogWarning((object)$"[VersionDetect] Could not find LockLobby() method for detected version {_detectedVersion}. Locking might fail.");
			}
			_reflectionChecked = true;
			return _detectedVersion;
		}

		public static void UnlockSteamLobby(bool makePublicForBeta = true)
		{
			if (!_reflectionChecked)
			{
				DetectVersion();
			}
			if (_unlockLobbyMethod == null || (Object)(object)SteamManager.instance == (Object)null)
			{
				Log.LogError((object)string.Format("[SteamHelper] Cannot unlock lobby: {0}. Detected Version: {1}", ((Object)(object)SteamManager.instance == (Object)null) ? "SteamManager instance is null" : "UnlockLobby method not found", _detectedVersion));
				return;
			}
			try
			{
				if (_detectedVersion == GameVersion.Beta)
				{
					Log.LogDebug((object)$"[SteamHelper] Invoking BETA UnlockLobby(bool) with parameter: {makePublicForBeta}");
					_unlockLobbyMethod.Invoke(SteamManager.instance, new object[1] { makePublicForBeta });
				}
				else if (_detectedVersion == GameVersion.Stable)
				{
					Log.LogDebug((object)"[SteamHelper] Invoking STABLE UnlockLobby()");
					_unlockLobbyMethod.Invoke(SteamManager.instance, null);
				}
				else
				{
					Log.LogError((object)"[SteamHelper] Cannot unlock lobby: Game version is Unknown.");
				}
			}
			catch (Exception arg)
			{
				Log.LogError((object)$"[SteamHelper] Exception invoking UnlockLobby for version {_detectedVersion}: {arg}");
			}
		}

		public static void LockSteamLobby()
		{
			if (!_reflectionChecked)
			{
				DetectVersion();
			}
			if (_lockLobbyMethod == null || (Object)(object)SteamManager.instance == (Object)null)
			{
				Log.LogError((object)string.Format("[SteamHelper] Cannot lock lobby: {0}. Detected Version: {1}", ((Object)(object)SteamManager.instance == (Object)null) ? "SteamManager instance is null" : "LockLobby method not found", _detectedVersion));
				return;
			}
			try
			{
				Log.LogDebug((object)"[SteamHelper] Invoking LockLobby()");
				_lockLobbyMethod.Invoke(SteamManager.instance, null);
			}
			catch (Exception arg)
			{
				Log.LogError((object)$"[SteamHelper] Exception invoking LockLobby: {arg}");
			}
		}
	}
	[BepInPlugin("nilaier.late", "L.A.T.E", "1.1.0")]
	internal sealed class LateJoinEntry : BaseUnityPlugin
	{
		private static readonly List<Hook> _hooks = new List<Hook>();

		private static MonoBehaviour? _coroutineRunner;

		private static readonly (Type TargetType, string TargetMethod, Type HookType, string HookMethod)[] _monoModHooks = new(Type, string, Type, string)[3]
		{
			(typeof(RunManager), "ChangeLevel", typeof(Patches), "RunManager_ChangeLevelHook"),
			(typeof(PlayerAvatar), "Spawn", typeof(Patches), "PlayerAvatar_SpawnHook"),
			(typeof(PlayerAvatar), "Start", typeof(Patches), "PlayerAvatar_StartHook")
		};

		private static readonly (Type TargetType, string TargetMethod, Type PatchType, string PatchMethod, Type[]? Args, bool Postfix)[] _explicitHarmonyPatches = new(Type, string, Type, string, Type[], bool)[2]
		{
			(typeof(NetworkManager), "OnPlayerEnteredRoom", typeof(Patches), "NetworkManager_OnPlayerEnteredRoom_Postfix", new Type[1] { typeof(Player) }, true),
			(typeof(NetworkManager), "OnPlayerLeftRoom", typeof(Patches), "NetworkManager_OnPlayerLeftRoom_Postfix", new Type[1] { typeof(Player) }, true)
		};

		internal static ManualLogSource Log { get; private set; } = null;


		internal static Harmony HarmonyInstance { get; private set; } = null;


		internal static MonoBehaviour? CoroutineRunner => _coroutineRunner ?? (_coroutineRunner = Utilities.FindCoroutineRunner());

		private void Awake()
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Expected O, but got Unknown
			Log = ((BaseUnityPlugin)this).Logger;
			HarmonyInstance = new Harmony("nilaier.late");
			Log.LogInfo((object)"L.A.T.E v1.1.0 is loading…");
			GameVersion gameVersion = GameVersionSupport.DetectVersion();
			Log.LogInfo((object)$"Detected Game Version: {gameVersion}");
			if (gameVersion == GameVersion.Unknown)
			{
				Log.LogError((object)"Failed to determine game version. Mod features related to Steam lobby management might not work correctly.");
			}
			ConfigManager.Initialize(((BaseUnityPlugin)this).Config);
			ApplyMonoModHooks();
			ApplyHarmonyPatches();
			Log.LogInfo((object)"L.A.T.E finished loading!");
		}

		private static void ApplyMonoModHooks()
		{
			Log.LogInfo((object)"Applying MonoMod hooks…");
			(Type, string, Type, string)[] monoModHooks = _monoModHooks;
			for (int i = 0; i < monoModHooks.Length; i++)
			{
				var (targetType, targetMethodName, hookType, hookMethodName) = monoModHooks[i];
				TryApplyMonoModHook(targetType, targetMethodName, hookType, hookMethodName);
			}
			Log.LogInfo((object)"MonoMod hook application finished.");
		}

		private static void TryApplyMonoModHook(Type targetType, string targetMethodName, Type hookType, string hookMethodName)
		{
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Expected O, but got Unknown
			MethodInfo methodInfo = FindMethod(targetType, targetMethodName);
			MethodInfo methodInfo2 = FindMethod(hookType, hookMethodName);
			if (methodInfo == null)
			{
				Log.LogError((object)("[MonoMod] Target not found: " + targetType.FullName + "." + targetMethodName));
				return;
			}
			if (methodInfo2 == null)
			{
				Log.LogError((object)("[MonoMod] Hook not found: " + hookType.FullName + "." + hookMethodName));
				return;
			}
			try
			{
				_hooks.Add(new Hook((MethodBase)methodInfo, methodInfo2));
				Log.LogDebug((object)("[MonoMod] Hooked " + targetType.Name + "." + targetMethodName));
			}
			catch (Exception arg)
			{
				Log.LogError((object)$"[MonoMod] Exception while hooking {targetType.Name}.{targetMethodName}: {arg}");
			}
		}

		private static void ApplyHarmonyPatches()
		{
			Log.LogInfo((object)"Applying Harmony patches…");
			try
			{
				HarmonyInstance.PatchAll(typeof(Patches));
				HarmonyInstance.PatchAll(typeof(NetworkConnect_Patches));
				HarmonyInstance.PatchAll(typeof(TruckScreenText_ChatBoxState_EarlyLock_Patches));
				(Type, string, Type, string, Type[], bool)[] explicitHarmonyPatches = _explicitHarmonyPatches;
				for (int i = 0; i < explicitHarmonyPatches.Length; i++)
				{
					var (targetType, targetMethodName, patchType, patchMethodName, arguments, postfix) = explicitHarmonyPatches[i];
					TryApplyHarmonyPatch(targetType, targetMethodName, patchType, patchMethodName, arguments, postfix);
				}
				Log.LogInfo((object)"Harmony patches applied successfully.");
			}
			catch (Exception arg)
			{
				Log.LogError((object)$"Failed to apply Harmony patches: {arg}");
			}
		}

		private static void TryApplyHarmonyPatch(Type targetType, string targetMethodName, Type patchType, string patchMethodName, Type[]? arguments, bool postfix)
		{
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Expected O, but got Unknown
			MethodInfo methodInfo = FindMethod(targetType, targetMethodName, arguments);
			MethodInfo methodInfo2 = FindMethod(patchType, patchMethodName);
			if (methodInfo == null)
			{
				Log.LogError((object)("[Harmony] Target not found: " + targetType.FullName + "." + targetMethodName));
				return;
			}
			if (methodInfo2 == null)
			{
				Log.LogError((object)("[Harmony] Patch not found: " + patchType.FullName + "." + patchMethodName));
				return;
			}
			HarmonyMethod val = new HarmonyMethod(methodInfo2);
			if (postfix)
			{
				HarmonyInstance.Patch((MethodBase)methodInfo, (HarmonyMethod)null, val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			else
			{
				HarmonyInstance.Patch((MethodBase)methodInfo, val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			Log.LogDebug((object)("[Harmony] Patched " + targetType.Name + "." + targetMethodName + " (" + (postfix ? "postfix" : "prefix") + ")"));
		}

		private static MethodInfo? FindMethod(Type type, string methodName, Type[]? arguments = null)
		{
			if (arguments != null)
			{
				return AccessTools.Method(type, methodName, arguments, (Type[])null);
			}
			return AccessTools.Method(type, methodName, (Type[])null, (Type[])null);
		}

		internal static void ClearCoroutineRunnerCache()
		{
			Log.LogDebug((object)"Clearing cached CoroutineRunner.");
			_coroutineRunner = null;
		}
	}
	internal static class LateJoinManager
	{
		[CompilerGenerated]
		private sealed class <ResyncExtractionPointItems>d__20 : IEnumerator<object>, IEnumerator, IDisposable
		{
			private int <>1__state;

			private object <>2__current;

			public Player targetPlayer;

			public ExtractionPoint epToSync;

			private string <targetNickname>5__2;

			private string <epName>5__3;

			private Dictionary<int, (Vector3 pos, Quaternion rot)> <originalTransforms>5__4;

			private List<PhysGrabObject> <validPhysObjects>5__5;

			object IEnumerator<object>.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			object IEnumerator.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			[DebuggerHidden]
			public <ResyncExtractionPointItems>d__20(int <>1__state)
			{
				this.<>1__state = <>1__state;
			}

			[DebuggerHidden]
			void IDisposable.Dispose()
			{
				<targetNickname>5__2 = null;
				<epName>5__3 = null;
				<originalTransforms>5__4 = null;
				<validPhysObjects>5__5 = null;
				<>1__state = -2;
			}

			private bool MoveNext()
			{
				//IL_048a: Unknown result type (might be due to invalid IL or missing references)
				//IL_0494: Expected O, but got Unknown
				//IL_03c4: Unknown result type (might be due to invalid IL or missing references)
				//IL_03d0: Unknown result type (might be due to invalid IL or missing references)
				//IL_0415: Unknown result type (might be due to invalid IL or missing references)
				//IL_041d: Unknown result type (might be due to invalid IL or missing references)
				//IL_05cd: Unknown result type (might be due to invalid IL or missing references)
				//IL_05e5: Unknown result type (might be due to invalid IL or missing references)
				//IL_05ec: Unknown result type (might be due to invalid IL or missing references)
				//IL_011f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0134: Unknown result type (might be due to invalid IL or missing references)
				//IL_014f: Unknown result type (might be due to invalid IL or missing references)
				switch (<>1__state)
				{
				default:
					return false;
				case 0:
				{
					<>1__state = -1;
					Player obj = targetPlayer;
					<targetNickname>5__2 = ((obj != null) ? obj.NickName : null) ?? "<Unknown>";
					ExtractionPoint obj2 = epToSync;
					<epName>5__3 = ((obj2 != null) ? ((Object)obj2).name : null) ?? "<Unknown EP>";
					LateJoinEntry.Log.LogInfo((object)("[LateJoinManager][Item Resync] Starting for " + <targetNickname>5__2 + " in EP '" + <epName>5__3 + "'"));
					if (targetPlayer == null || (Object)(object)epToSync == (Object)null || !Utilities.IsRealMasterClient())
					{
						LateJoinEntry.Log.LogWarning((object)"[LateJoinManager][Item Resync] Aborting: Invalid state.");
						return false;
					}
					if (PhotonNetwork.CurrentRoom == null || !PhotonNetwork.CurrentRoom.Players.ContainsKey(targetPlayer.ActorNumber))
					{
						LateJoinEntry.Log.LogWarning((object)("[LateJoinManager][Item Resync] Aborting: Player " + <targetNickname>5__2 + " left."));
						return false;
					}
					bool num = SemiFunc.RunIsShop();
					Vector3 val = default(Vector3);
					((Vector3)(ref val))..ctor(((Component)epToSync).transform.position.x, ((Component)epToSync).transform.position.y + 500f, ((Component)epToSync).transform.position.z);
					List<GameObject> list = new List<GameObject>();
					if (num)
					{
						LateJoinEntry.Log.LogDebug((object)"[LateJoinManager][Item Resync] Identifying items from ShopManager.");
						if ((Object)(object)ShopManager.instance != (Object)null && Utilities.smShoppingListField != null)
						{
							try
							{
								if (Utilities.smShoppingListField.GetValue(ShopManager.instance) is List<ItemAttributes> list2)
								{
									foreach (ItemAttributes item in list2)
									{
										if ((Object)(object)item != (Object)null && (Object)(object)((Component)item).gameObject != (Object)null)
										{
											list.Add(((Component)item).gameObject);
										}
									}
								}
								else
								{
									LateJoinEntry.Log.LogWarning((object)"[LateJoinManager][Item Resync] Reflected shoppingList is null or not a List<ItemAttributes>.");
								}
							}
							catch (Exception arg2)
							{
								LateJoinEntry.Log.LogError((object)$"[LateJoinManager][Item Resync] Error reflecting or accessing ShopManager.shoppingList: {arg2}");
							}
						}
						else
						{
							LateJoinEntry.Log.LogWarning((object)"[LateJoinManager][Item Resync] ShopManager instance or shoppingList reflection field is null.");
						}
					}
					else
					{
						LateJoinEntry.Log.LogDebug((object)"[LateJoinManager][Item Resync] Identifying items from RoundDirector.dollarHaulList.");
						if ((Object)(object)RoundDirector.instance != (Object)null && RoundDirector.instance.dollarHaulList != null)
						{
							list = RoundDirector.instance.dollarHaulList.Where((GameObject go) => (Object)(object)go != (Object)null).ToList();
						}
						else
						{
							LateJoinEntry.Log.LogWarning((object)"[LateJoinManager][Item Resync] RoundDirector instance or dollarHaulList is null.");
						}
					}
					if (list.Count == 0)
					{
						LateJoinEntry.Log.LogInfo((object)("[LateJoinManager][Item Resync] No items identified in EP '" + <epName>5__3 + "'."));
						return false;
					}
					LateJoinEntry.Log.LogInfo((object)$"[LateJoinManager][Item Resync] Found {list.Count} items in '{<epName>5__3}' for {<targetNickname>5__2}.");
					<originalTransforms>5__4 = new Dictionary<int, (Vector3, Quaternion)>();
					<validPhysObjects>5__5 = new List<PhysGrabObject>();
					foreach (GameObject item2 in list)
					{
						PhysGrabObject component = item2.GetComponent<PhysGrabObject>();
						PhotonView photonViewFromPGO2 = Utilities.GetPhotonViewFromPGO(component);
						if ((Object)(object)component == (Object)null || (Object)(object)photonViewFromPGO2 == (Object)null)
						{
							LateJoinEntry.Log.LogWarning((object)("[LateJoinManager][Item Resync] Item '" + ((Object)item2).name + "' missing PGO/PV. Skipping."));
							continue;
						}
						if (!photonViewFromPGO2.IsMine)
						{
							LateJoinEntry.Log.LogDebug((object)$"[LateJoinManager][Item Resync] Requesting ownership of {((Object)item2).name} (ViewID: {photonViewFromPGO2.ViewID}).");
							photonViewFromPGO2.RequestOwnership();
						}
						<originalTransforms>5__4[photonViewFromPGO2.ViewID] = (item2.transform.position, item2.transform.rotation);
						<validPhysObjects>5__5.Add(component);
						try
						{
							LateJoinEntry.Log.LogDebug((object)$"[LateJoinManager][Item Resync] Teleporting {((Object)item2).name} (ViewID: {photonViewFromPGO2.ViewID}) AWAY.");
							component.Teleport(val, item2.transform.rotation);
						}
						catch (Exception arg3)
						{
							LateJoinEntry.Log.LogError((object)$"[LateJoinManager][Item Resync] Error teleporting {((Object)item2).name} AWAY: {arg3}");
						}
					}
					LateJoinEntry.Log.LogInfo((object)$"[LateJoinManager][Item Resync] Waiting {itemResyncDelay}s...");
					<>2__current = (object)new WaitForSeconds(itemResyncDelay);
					<>1__state = 1;
					return true;
				}
				case 1:
					<>1__state = -1;
					if (PhotonNetwork.CurrentRoom == null || !PhotonNetwork.CurrentRoom.Players.ContainsKey(targetPlayer.ActorNumber))
					{
						LateJoinEntry.Log.LogWarning((object)("[LateJoinManager][Item Resync] Aborting teleport BACK: Player " + <targetNickname>5__2 + " left."));
						return false;
					}
					LateJoinEntry.Log.LogInfo((object)$"[LateJoinManager][Item Resync] Teleporting {<validPhysObjects>5__5.Count} items back for {<targetNickname>5__2}.");
					foreach (PhysGrabObject item3 in <validPhysObjects>5__5)
					{
						if ((Object)(object)item3 == (Object)null || (Object)(object)((Component)item3).gameObject == (Object)null)
						{
							continue;
						}
						PhotonView photonViewFromPGO = Utilities.GetPhotonViewFromPGO(item3);
						if ((Object)(object)photonViewFromPGO == (Object)null)
						{
							continue;
						}
						int viewID = photonViewFromPGO.ViewID;
						if (<originalTransforms>5__4.TryGetValue(viewID, out (Vector3, Quaternion) value))
						{
							if (!photonViewFromPGO.IsMine)
							{
								LateJoinEntry.Log.LogWarning((object)("[LateJoinManager][Item Resync] Lost ownership of " + ((Object)((Component)item3).gameObject).name + "?"));
							}
							try
							{
								LateJoinEntry.Log.LogDebug((object)$"[LateJoinManager][Item Resync] Teleporting {((Object)((Component)item3).gameObject).name} (ViewID: {viewID}) BACK to {value.Item1}.");
								item3.Teleport(value.Item1, value.Item2);
							}
							catch (Exception arg)
							{
								LateJoinEntry.Log.LogError((object)$"[LateJoinManager][Item Resync] Error teleporting {((Object)((Component)item3).gameObject).name} BACK: {arg}");
							}
						}
						else
						{
							LateJoinEntry.Log.LogWarning((object)$"[LateJoinManager][Item Resync] No original transform for ViewID {viewID}.");
						}
					}
					LateJoinEntry.Log.LogInfo((object)("[LateJoinManager][Item Resync] Finished item resync sequence for " + <targetNickname>5__2 + " in EP '" + <epName>5__3 + "'."));
					return false;
				}
			}

			bool IEnumerator.MoveNext()
			{
				//ILSpy generated this explicit interface implementation from .override directive in MoveNext
				return this.MoveNext();
			}

			[DebuggerHidden]
			void IEnumerator.Reset()
			{
				throw new NotSupportedException();
			}
		}

		private static readonly float itemResyncDelay = 0.2f;

		private static readonly HashSet<int> _playersNeedingLateJoinSync = new HashSet<int>();

		private static readonly HashSet<int> _playersJoinedLateThisScene = new HashSet<int>();

		public static void ResetSceneTracking()
		{
			LateJoinEntry.Log.LogDebug((object)"[LateJoinManager] Clearing late join tracking sets for new scene.");
			_playersNeedingLateJoinSync.Clear();
			_playersJoinedLateThisScene.Clear();
		}

		public static void HandlePlayerJoined(Player newPlayer)
		{
			if (newPlayer == null)
			{
				LateJoinEntry.Log.LogWarning((object)"[LateJoinManager] HandlePlayerJoined called with null player.");
				return;
			}
			int actorNumber = newPlayer.ActorNumber;
			string text = newPlayer.NickName ?? $"ActorNr {actorNumber}";
			if (Utilities.IsModLogicActive())
			{
				if (_playersNeedingLateJoinSync.Add(actorNumber))
				{
					LateJoinEntry.Log.LogInfo((object)("[LateJoinManager] Player " + text + " marked as needing late join DATA sync (awaiting LoadingCompleteRPC)."));
				}
				if (_playersJoinedLateThisScene.Add(actorNumber))
				{
					LateJoinEntry.Log.LogInfo((object)("[LateJoinManager] Player " + text + " marked as JOINED LATE THIS SCENE."));
				}
			}
			else
			{
				LateJoinEntry.Log.LogInfo((object)("[LateJoinManager] Player " + text + " joined during INACTIVE scene. Not marked as late-joiner."));
			}
			if (Utilities.IsRealMasterClient())
			{
				VoiceManager.TriggerDelayedSync("Player " + text + " joined room", 0.5f);
			}
		}

		internal static bool IsPlayerNeedingSync(int actorNumber)
		{
			return _playersNeedingLateJoinSync.Contains(actorNumber);
		}

		internal static bool DidPlayerJoinLateThisScene(int actorNumber)
		{
			return _playersJoinedLateThisScene.Contains(actorNumber);
		}

		internal static void MarkPlayerSyncTriggeredAndClearNeed(int actorNumber)
		{
			if (_playersNeedingLateJoinSync.Remove(actorNumber))
			{
				LateJoinEntry.Log.LogDebug((object)$"[LateJoinManager] Sync triggered for ActorNr {actorNumber}. Removed from 'NeedingSync' list.");
			}
		}

		internal static void ClearPlayerTracking(int actorNumber)
		{
			bool num = _playersNeedingLateJoinSync.Remove(actorNumber);
			bool flag = _playersJoinedLateThisScene.Remove(actorNumber);
			if (num || flag)
			{
				ManualLogSource log = LateJoinEntry.Log;
				if (log != null)
				{
					log.LogDebug((object)$"[LateJoinManager] Cleared all sync tracking for ActorNr {actorNumber}.");
				}
			}
		}

		public static void SyncAllStateForPlayer(Player targetPlayer, PlayerAvatar playerAvatar)
		{
			int actorNumber = targetPlayer.ActorNumber;
			string text = targetPlayer.NickName ?? $"ActorNr {actorNumber}";
			LateJoinEntry.Log.LogInfo((object)("[LateJoinManager] === Executing SyncAllStateForPlayer for " + text + " ==="));
			try
			{
				SyncLevelState(targetPlayer);
				SyncModuleConnectionStatesForPlayer(targetPlayer);
				SyncExtractionPointsForPlayer(targetPlayer);
				bool flag = SemiFunc.RunIsShop();
				if (flag)
				{
					SyncAllShopItemsForPlayer(targetPlayer);
				}
				else
				{
					SyncAllValuablesForPlayer(targetPlayer);
					DestructionManager.SyncHingeStatesForPlayer(targetPlayer);
				}
				TriggerPropSwitchSetup(targetPlayer);
				EnemyManager.SyncAllEnemyStatesForPlayer(targetPlayer);
				EnemyManager.NotifyEnemiesOfNewPlayer(targetPlayer, playerAvatar);
				SyncPlayerDeathState(targetPlayer, playerAvatar);
				SyncTruckScreenForPlayer(targetPlayer);
				SyncAllItemStatesForPlayer(targetPlayer);
				if (SemiFunc.RunIsArena())
				{
					SyncArenaStateForPlayer(targetPlayer);
				}
				if (Utilities.IsRealMasterClient())
				{
					LateJoinEntry.Log.LogDebug((object)("[LateJoinManager] Host preparing to potentially resync EP items for " + text + "."));
					ExtractionPoint val = null;
					if (flag)
					{
						ExtractionPoint[] array = Object.FindObjectsOfType<ExtractionPoint>();
						foreach (ExtractionPoint val2 in array)
						{
							if ((Object)(object)val2 == (Object)null || Utilities.epIsShopField == null)
							{
								continue;
							}
							try
							{
								if ((bool)(Utilities.epIsShopField.GetValue(val2) ?? ((object)false)))
								{
									val = val2;
									LateJoinEntry.Log.LogDebug((object)("[LateJoinManager] Found Shop EP '" + ((Object)val2).name + "' for item resync."));
									break;
								}
							}
							catch (Exception ex)
							{
								LateJoinEntry.Log.LogWarning((object)("[LateJoinManager] Error checking isShop field on EP '" + (((val2 != null) ? ((Object)val2).name : null) ?? "NULL") + "': " + ex.Message));
							}
						}
						if ((Object)(object)val == (Object)null)
						{
							LateJoinEntry.Log.LogWarning((object)"[LateJoinManager] Could not find Shop EP for item resync.");
						}
					}
					else if ((Object)(object)RoundDirector.instance != (Object)null && Utilities.rdExtractionPointCurrentField != null)
					{
						try
						{
							object? value = Utilities.rdExtractionPointCurrentField.GetValue(RoundDirector.instance);
							val = (ExtractionPoint)((value is ExtractionPoint) ? value : null);
							if ((Object)(object)val != (Object)null)
							{
								LateJoinEntry.Log.LogDebug((object)("[LateJoinManager] Found active Level EP '" + ((Object)val).name + "' for item resync."));
							}
							else
							{
								LateJoinEntry.Log.LogDebug((object)"[LateJoinManager] No active Level EP found (RoundDirector.extractionPointCurrent is null). Skipping item resync.");
							}
						}
						catch (Exception arg)
						{
							LateJoinEntry.Log.LogError((object)$"[LateJoinManager] Error getting current EP from RoundDirector: {arg}");
						}
					}
					else
					{
						LateJoinEntry.Log.LogWarning((object)"[LateJoinManager] RoundDirector instance or rdExtractionPointCurrentField is null. Cannot get active EP for resync.");
					}
					if ((Object)(object)val != (Object)null)
					{
						LateJoinEntry.Log.LogInfo((object)("[LateJoinManager] Starting ResyncExtractionPointItems coroutine for " + text + " in EP '" + ((Object)val).name + "'."));
						MonoBehaviour coroutineRunner = LateJoinEntry.CoroutineRunner;
						if ((Object)(object)coroutineRunner != (Object)null)
						{
							coroutineRunner.StartCoroutine(ResyncExtractionPointItems(targetPlayer, val));
						}
						else
						{
							LateJoinEntry.Log.LogError((object)"[LateJoinManager] Cannot start ResyncExtractionPointItems: LateJoinEntry.CoroutineRunner is null! Ensure Utilities.FindCoroutineRunner() can find an active MonoBehaviour.");
						}
					}
					else
					{
						LateJoinEntry.Log.LogInfo((object)("[LateJoinManager] No suitable EP identified for item resync for " + text + "."));
					}
				}
				else
				{
					LateJoinEntry.Log.LogDebug((object)"[LateJoinManager] Not Master Client, skipping EP item resync trigger.");
				}
			}
			catch (Exception arg2)
			{
				LateJoinEntry.Log.LogError((object)$"[LateJoinManager] CRITICAL ERROR during SyncAllStateForPlayer for {text}: {arg2}");
				ClearPlayerTracking(actorNumber);
			}
			finally
			{
				LateJoinEntry.Log.LogInfo((object)("[LateJoinManager] === SyncAllStateForPlayer Finished for " + text + " ==="));
			}
		}

		private static void SyncModuleConnectionStatesForPlayer(Player targetPlayer)
		{
			string text = targetPlayer.NickName ?? $"ActorNr {targetPlayer.ActorNumber}";
			LateJoinEntry.Log.LogInfo((object)("[LateJoinManager][Module Sync] Starting Module connection sync for " + text + "."));
			if (Utilities.modSetupDoneField == null || Utilities.modConnectingTopField == null || Utilities.modConnectingBottomField == null || Utilities.modConnectingRightField == null || Utilities.modConnectingLeftField == null || Utilities.modFirstField == null)
			{
				LateJoinEntry.Log.LogError((object)"[LateJoinManager][Module Sync] Critical reflection failure: Required Module fields not found in Utilities. Aborting sync.");
				return;
			}
			Module[] array = Object.FindObjectsOfType<Module>(true);
			if (array == null || array.Length == 0)
			{
				LateJoinEntry.Log.LogWarning((object)"[LateJoinManager][Module Sync] Found 0 Module components. Skipping sync.");
				return;
			}
			int num = 0;
			int num2 = 0;
			Module[] array2 = array;
			foreach (Module val in array2)
			{
				if ((Object)(object)val == (Object)null)
				{
					LateJoinEntry.Log.LogWarning((object)"[LateJoinManager][Module Sync] Encountered null module instance. Skipping.");
					num2++;
					continue;
				}
				PhotonView photonView = Utilities.GetPhotonView((Component)(object)val);
				if ((Object)(object)photonView == (Object)null)
				{
					ManualLogSource log = LateJoinEntry.Log;
					GameObject gameObject = ((Component)val).gameObject;
					log.LogWarning((object)("[LateJoinManager][Module Sync] Module '" + (((gameObject != null) ? ((Object)gameObject).name : null) ?? "NULL") + "' is missing PhotonView. Skipping."));
					num2++;
					continue;
				}
				try
				{
					if (!(bool)(Utilities.modSetupDoneField.GetValue(val) ?? ((object)false)))
					{
						ManualLogSource log2 = LateJoinEntry.Log;
						GameObject gameObject2 = ((Component)val).gameObject;
						log2.LogDebug((object)string.Format("[LateJoinManager][Module Sync] Skipping module '{0}' (ViewID: {1}): Not SetupDone on host.", ((gameObject2 != null) ? ((Object)gameObject2).name : null) ?? "NULL GameObject", photonView.ViewID));
						num2++;
						continue;
					}
					bool flag = (bool)(Utilities.modConnectingTopField.GetValue(val) ?? ((object)false));
					bool flag2 = (bool)(Utilities.modConnectingBottomField.GetValue(val) ?? ((object)false));
					bool flag3 = (bool)(Utilities.modConnectingRightField.GetValue(val) ?? ((object)false));
					bool flag4 = (bool)(Utilities.modConnectingLeftField.GetValue(val) ?? ((object)false));
					bool flag5 = (bool)(Utilities.modFirstField.GetValue(val) ?? ((object)false));
					ManualLogSource log3 = LateJoinEntry.Log;
					object[] array3 = new object[8];
					GameObject gameObject3 = ((Component)val).gameObject;
					array3[0] = ((gameObject3 != null) ? ((Object)gameObject3).name : null) ?? "NULL GameObject";
					array3[1] = photonView.ViewID;
					array3[2] = text;
					array3[3] = flag;
					array3[4] = flag2;
					array3[5] = flag3;
					array3[6] = flag4;
					array3[7] = flag5;
					log3.LogDebug((object)string.Format("[LateJoinManager][Module Sync] Syncing module '{0}' (ViewID: {1}) state to {2}: T={3}, B={4}, R={5}, L={6}, First={7}", array3));
					photonView.RPC("ModuleConnectionSetRPC", targetPlayer, new object[5] { flag, flag2, flag3, flag4, flag5 });
					num++;
				}
				catch (Exception ex)
				{
					ManualLogSource log4 = LateJoinEntry.Log;
					object[] array4 = new object[4];
					GameObject gameObject4 = ((Component)val).gameObject;
					array4[0] = ((gameObject4 != null) ? ((Object)gameObject4).name : null) ?? "NULL";
					array4[1] = photonView.ViewID;
					array4[2] = text;
					array4[3] = ex;
					log4.LogError((object)string.Format("[LateJoinManager][Module Sync] Error processing or sending ModuleConnectionSetRPC for module '{0}' (ViewID: {1}) to {2}: {3}", array4));
					num2++;
				}
			}
			LateJoinEntry.Log.LogInfo((object)$"[LateJoinManager][Module Sync] Finished Module connection sync for {text}. Synced: {num}, Skipped: {num2} (Out of {array.Length} total).");
		}

		private static void SyncLevelState(Player targetPlayer)
		{
			string text = targetPlayer.NickName ?? $"ActorNr {targetPlayer.ActorNumber}";
			RunManager instance = RunManager.instance;
			if ((Object)(object)instance == (Object)null || (Object)(object)instance.levelCurrent == (Object)null)
			{
				LateJoinEntry.Log.LogError((object)"[LateJoinManager][Level Sync] Null RunManager/levelCurrent.");
				return;
			}
			if (Utilities.rmRunManagerPUNField == null || Utilities.rmpPhotonViewField == null || Utilities.rmGameOverField == null)
			{
				LateJoinEntry.Log.LogError((object)"[LateJoinManager][Level Sync] Null reflection fields.");
				return;
			}
			LevelGenerator instance2 = LevelGenerator.Instance;
			try
			{
				object? value = Utilities.rmRunManagerPUNField.GetValue(instance);
				RunManagerPUN val = (RunManagerPUN)((value is RunManagerPUN) ? value : null);
				if ((Object)(object)val == (Object)null)
				{
					throw new Exception("Null RunManagerPUN");
				}
				object? value2 = Utilities.rmpPhotonViewField.GetValue(val);
				PhotonView val2 = (PhotonView)((value2 is PhotonView) ? value2 : null);
				if ((Object)(object)val2 == (Object)null)
				{
					throw new Exception("Null RunManagerPUN PV");
				}
				string name = ((Object)instance.levelCurrent).name;
				int levelsCompleted = instance.levelsCompleted;
				bool flag = (bool)(Utilities.rmGameOverField.GetValue(instance) ?? ((object)false));
				LateJoinEntry.Log.LogInfo((object)$"[LateJoinManager][Level Sync] Sending UpdateLevelRPC to {text}. Lvl:{name}, Comp:{levelsCompleted}, Over:{flag}");
				val2.RPC("UpdateLevelRPC", targetPlayer, new object[3] { name, levelsCompleted, flag });
			}
			catch (Exception arg)
			{
				LateJoinEntry.Log.LogError((object)$"[LateJoinManager][Level Sync] Error sending UpdateLevelRPC: {arg}");
				return;
			}
			if ((Object)(object)instance2 != (Object)null && (Object)(object)instance2.PhotonView != (Object)null)
			{
				try
				{
					LateJoinEntry.Log.LogInfo((object)("[LateJoinManager][Level Sync] Sending GenerateDone RPC to " + text + "."));
					instance2.PhotonView.RPC("GenerateDone", targetPlayer, Array.Empty<object>());
					return;
				}
				catch (Exception arg2)
				{
					LateJoinEntry.Log.LogError((object)$"[LateJoinManager][Level Sync] Error sending GenerateDone RPC: {arg2}");
					return;
				}
			}
			LateJoinEntry.Log.LogWarning((object)"[LateJoinManager][Level Sync] Skipped GenerateDone RPC.");
		}

		private static void SyncAllItemStatesForPlayer(Player targetPlayer)
		{
			string text = targetPlayer.NickName ?? $"ActorNr {targetPlayer.ActorNumber}";
			LateJoinEntry.Log.LogInfo((object)("[LateJoinManager][Item State Sync] Starting FULL item state sync for " + text + "."));
			int num = 0;
			int num2 = 0;
			int num3 = 0;
			int num4 = 0;
			int num5 = 0;
			int num6 = 0;
			int num7 = 0;
			int num8 = 0;
			int num9 = 0;
			ItemToggle[] array = Array.Empty<ItemToggle>();
			try
			{
				array = Object.FindObjectsOfType<ItemToggle>();
				LateJoinEntry.Log.LogDebug((object)$"[LateJoinManager][Item State Sync] Found {array.Length} ItemToggles for State/Disabled sync.");
				ItemToggle[] array2 = array;
				foreach (ItemToggle val in array2)
				{
					if (!((Object)(object)val == (Object)null))
					{
						PhotonView component = ((Component)val).GetComponent<PhotonView>();
						if (!((Object)(object)component == (Object)null))
						{
							bool toggleState = val.toggleState;
							component.RPC("ToggleItemRPC", targetPlayer, new object[2] { toggleState, -1 });
							num++;
						}
					}
				}
				LateJoinEntry.Log.LogInfo((object)$"[LateJoinManager][Item State Sync] Synced {num} ItemToggle ON/OFF states for {text}.");
			}
			catch (Exception arg)
			{
				LateJoinEntry.Log.LogError((object)$"[LateJoinManager][Item State Sync] Error syncing ItemToggle ON/OFF states: {arg}");
			}
			try
			{
				FieldInfo itDisabledField = Utilities.itDisabledField;
				if (itDisabledField == null)
				{
					LateJoinEntry.Log.LogError((object)"[LateJoinManager][Item State Sync] Reflection failed: ItemToggle.disabled field not found. Skipping disabled sync.");
				}
				else
				{
					ItemToggle[] array2 = array;
					foreach (ItemToggle val2 in array2)
					{
						if ((Object)(object)val2 == (Object)null)
						{
							continue;
						}
						PhotonView component2 = ((Component)val2).GetComponent<PhotonView>();
						if ((Object)(object)component2 == (Object)null)
						{
							continue;
						}
						try
						{
							object value = itDisabledField.GetValue(val2);
							if (value != null && (bool)value)
							{
								component2.RPC("ToggleDisableRPC", targetPlayer, new object[1] { true });
								num2++;
							}
						}
						catch (Exception arg2)
						{
							LateJoinEntry.Log.LogError((object)$"[LateJoinManager][Item State Sync] Reflection error getting ItemToggle.disabled for '{((Object)((Component)val2).gameObject).name}': {arg2}");
						}
					}
					LateJoinEntry.Log.LogInfo((object)$"[LateJoinManager][Item State Sync] Synced {num2} ItemToggle DISABLED states for {text}.");
				}
			}
			catch (Exception arg3)
			{
				LateJoinEntry.Log.LogError((object)$"[LateJoinManager][Item State Sync] Error syncing ItemToggle DISABLED states: {arg3}");
			}
			try
			{
				ItemBattery[] array3 = Object.FindObjectsOfType<ItemBattery>();
				LateJoinEntry.Log.LogDebug((object)$"[LateJoinManager][Item State Sync] Found {array3.Length} ItemBatteries.");
				ItemBattery[] array4 = array3;
				foreach (ItemBattery val3 in array4)
				{
					if ((Object)(object)val3 == (Object)null)
					{
						continue;
					}
					PhotonView component3 = ((Component)val3).GetComponent<PhotonView>();
					if (!((Object)(object)component3 == (Object)null))
					{
						float batteryLife = val3.batteryLife;
						int num10 = 0;
						if (batteryLife > 0f)
						{
							num10 = (int)Mathf.Round(batteryLife / 16.6f);
						}
						component3.RPC("BatteryFullPercentChangeRPC", targetPlayer, new object[2] { num10, false });
						num3++;
					}
				}
				LateJoinEntry.Log.LogInfo((object)$"[LateJoinManager][Item State Sync] Synced {num3} ItemBattery levels for {text}.");
			}
			catch (Exception arg4)
			{
				LateJoinEntry.Log.LogError((object)$"[LateJoinManager][Item State Sync] Error syncing ItemBattery levels: {arg4}");
			}
			try
			{
				ItemMine[] array5 = Object.FindObjectsOfType<ItemMine>();
				LateJoinEntry.Log.LogDebug((object)$"[LateJoinManager][Item State Sync] Found {array5.Length} ItemMines.");
				ItemMine[] array6 = array5;
				foreach (ItemMine val4 in array6)
				{
					if ((Object)(object)val4 == (Object)null)
					{
						continue;
					}
					PhotonView component4 = ((Component)val4).GetComponent<PhotonView>();
					if ((Object)(object)component4 == (Object)null)
					{
						continue;
					}
					FieldInfo imStateField = Utilities.imStateField;
					if (imStateField == null)
					{
						LateJoinEntry.Log.LogError((object)"[LateJoinManager][Item State Sync] Reflection failed: ItemMine.state field not found.");
						continue;
					}
					try
					{
						object value2 = imStateField.GetValue(val4);
						if (value2 != null)
						{
							int num11 = (int)value2;
							component4.RPC("StateSetRPC", targetPlayer, new object[1] { num11 });
							num4++;
						}
					}
					catch (Exception arg5)
					{
						LateJoinEntry.Log.LogError((object)$"[LateJoinManager][Item State Sync] Reflection error getting ItemMine state for '{((Object)((Component)val4).gameObject).name}': {arg5}");
					}
				}
				LateJoinEntry.Log.LogInfo((object)$"[LateJoinManager][Item State Sync] Synced {num4} ItemMine states for {text}.");
			}
			catch (Exception arg6)
			{
				LateJoinEntry.Log.LogError((object)$"[LateJoinManager][Item State Sync] Error syncing ItemMine states: {arg6}");
			}
			try
			{
				ItemMelee[] array7 = Object.FindObjectsOfType<ItemMelee>();
				LateJoinEntry.Log.LogDebug((object)$"[LateJoinManager][Item State Sync] Found {array7.Length} ItemMelees.");
				ItemMelee[] array8 = array7;
				foreach (ItemMelee val5 in array8)
				{
					if ((Object)(object)val5 == (Object)null)
					{
						continue;
					}
					PhotonView component5 = ((Component)val5).GetComponent<PhotonView>();
					if ((Object)(object)component5 == (Object)null)
					{
						continue;
					}
					ItemBattery component6 = ((Component)val5).GetComponent<ItemBattery>();
					PhysGrabObject component7 = ((Component)val5).GetComponent<PhysGrabObject>();
					if ((Object)(object)component6 == (Object)null || (Object)(object)component7 == (Object)null)
					{
						LateJoinEntry.Log.LogWarning((object)("[LateJoinManager][Item State Sync] Skipping melee item '" + ((Object)((Component)val5).gameObject).name + "' - missing components."));
						continue;
					}
					FieldInfo pgoIsMeleeField = Utilities.pgoIsMeleeField;
					if (pgoIsMeleeField == null)
					{
						LateJoinEntry.Log.LogError((object)"[LateJoinManager][Item State Sync] Reflection failed: PhysGrabObject.isMelee field not found.");
						continue;
					}
					try
					{
						bool flag = component6.batteryLife <= 0f;
						object value3 = pgoIsMeleeField.GetValue(component7);
						if (value3 != null)
						{
							bool flag2 = (bool)value3;
							if (flag && flag2)
							{
								component5.RPC("MeleeBreakRPC", targetPlayer, Array.Empty<object>());
								num5++;
							}
							else if (!flag && !flag2)
							{
								component5.RPC("MeleeFixRPC", targetPlayer, Array.Empty<object>());
								num5++;
							}
						}
					}
					catch (Exception arg7)
					{
						LateJoinEntry.Log.LogError((object)$"[LateJoinManager][Item State Sync] Reflection error getting PhysGrabObject.isMelee for '{((Object)((Component)component7).gameObject).name}': {arg7}");
					}
				}
				LateJoinEntry.Log.LogInfo((object)$"[LateJoinManager][Item State Sync] Synced {num5} ItemMelee broken states for {text}.");
			}
			catch (Exception arg8)
			{
				LateJoinEntry.Log.LogError((object)$"[LateJoinManager][Item State Sync] Error syncing ItemMelee states: {arg8}");
			}
			try
			{
				ItemDrone[] array9 = Object.FindObjectsOfType<ItemDrone>();
				LateJoinEntry.Log.LogDebug((object)$"[LateJoinManager][Item State Sync] Found {array9.Length} ItemDrones.");
				ItemDrone[] array10 = array9;
				foreach (ItemDrone val6 in array10)
				{
					if ((Object)(object)val6 == (Object)null)
					{
						continue;
					}
					PhotonView component8 = ((Component)val6).GetComponent<PhotonView>();
					if (!((Object)(object)component8 == (Object)null))
					{
						ItemToggle component9 = ((Component)val6).GetComponent<ItemToggle>();
						if ((Object)(object)component9 != (Object)null && component9.toggleState)
						{
							component8.RPC("ButtonToggleRPC", targetPlayer, new object[1] { true });
							num6++;
						}
					}
				}
				LateJoinEntry.Log.LogInfo((object)$"[LateJoinManager][Item State Sync] Synced {num6} ItemDrone ACTIVATED states for {text}.");
			}
			catch (Exception arg9)
			{
				LateJoinEntry.Log.LogError((object)$"[LateJoinManager][Item State Sync] Error syncing ItemDrone activated states: {arg9}");
			}
			try
			{
				ItemHealthPack[] array11 = Object.FindObjectsOfType<ItemHealthPack>();
				LateJoinEntry.Log.LogDebug((object)$"[LateJoinManager][Item State Sync] Found {array11.Length} ItemHealthPacks.");
				ItemHealthPack[] array12 = array11;
				foreach (ItemHealthPack val7 in array12)
				{
					if ((Object)(object)val7 == (Object)null)
					{
						continue;
					}
					PhotonView component10 = ((Component)val7).GetComponent<PhotonView>();
					if ((Object)(object)component10 == (Object)null)
					{
						continue;
					}
					FieldInfo ihpUsedField = Utilities.ihpUsedField;
					if (ihpUsedField == null)
					{
						LateJoinEntry.Log.LogError((object)"[LateJoinManager][Item State Sync] Reflection failed: ItemHealthPack.used field not found.");
						continue;
					}
					try
					{
						object value4 = ihpUsedField.GetValue(val7);
						if (value4 != null && (bool)value4)
						{
							component10.RPC("UsedRPC", targetPlayer, Array.Empty<object>());
							num9++;
						}
					}
					catch (Exception arg10)
					{
						LateJoinEntry.Log.LogError((object)$"[LateJoinManager][Item State Sync] Reflection error getting ItemHealthPack.used for '{((Object)((Component)val7).gameObject).name}': {arg10}");
					}
				}
				LateJoinEntry.Log.LogInfo((object)$"[LateJoinManager][Item State Sync] Synced {num9} USED ItemHealthPack states for {text}.");
			}
			catch (Exception arg11)
			{
				LateJoinEntry.Log.LogError((object)$"[LateJoinManager][Item State Sync] Error syncing ItemHealthPack used states: {arg11}");
			}
			try
			{
				ItemGrenade[] array13 = Object.FindObjectsOfType<ItemGrenade>();
				LateJoinEntry.Log.LogDebug((object)$"[LateJoinManager][Item State Sync] Found {array13.Length} ItemGrenades.");
				ItemGrenade[] array14 = array13;
				foreach (ItemGrenade val8 in array14)
				{
					if ((Object)(object)val8 == (Object)null)
					{
						continue;
					}
					PhotonView component11 = ((Component)val8).GetComponent<PhotonView>();
					if ((Object)(object)component11 == (Object)null)
					{
						continue;
					}
					FieldInfo igIsActiveField = Utilities.igIsActiveField;
					if (igIsActiveField == null)
					{
						LateJoinEntry.Log.LogError((object)"[LateJoinManager][Item State Sync] Reflection failed: ItemGrenade.isActive field not found.");
						continue;
					}
					try
					{
						object value5 = igIsActiveField.GetValue(val8);
						if (value5 != null && (bool)value5)
						{
							component11.RPC("TickStartRPC", targetPlayer, Array.Empty<object>());
							num7++;
						}
					}
					catch (Exception arg12)
					{
						LateJoinEntry.Log.LogError((object)$"[LateJoinManager][Item State Sync] Reflection error getting ItemGrenade.isActive for '{((Object)((Component)val8).gameObject).name}': {arg12}");
					}
				}
				LateJoinEntry.Log.LogInfo((object)$"[LateJoinManager][Item State Sync] Synced {num7} ItemGrenade active states (Active Only) for {text}.");
			}
			catch (Exception arg13)
			{
				LateJoinEntry.Log.LogError((object)$"[LateJoinManager][Item State Sync] Error syncing ItemGrenade active states: {arg13}");
			}
			try
			{
				ItemTracker[] array15 = Object.FindObjectsOfType<ItemTracker>();
				LateJoinEntry.Log.LogDebug((object)$"[LateJoinManager][Item State Sync] Found {array15.Length} ItemTrackers.");
				ItemTracker[] array16 = array15;
				foreach (ItemTracker val9 in array16)
				{
					if ((Object)(object)val9 == (Object)null)
					{
						continue;
					}
					PhotonView component12 = ((Component)val9).GetComponent<PhotonView>();
					if ((Object)(object)component12 == (Object)null)
					{
						continue;
					}
					FieldInfo itCurrentTargetField = Utilities.itCurrentTargetField;
					if (itCurrentTargetField == null)
					{
						LateJoinEntry.Log.LogError((object)"[LateJoinManager][Item State Sync] Reflection failed: ItemTracker.currentTarget field not found.");
						continue;
					}
					try
					{
						object? value6 = itCurrentTargetField.GetValue(val9);
						Transform val10 = (Transform)((value6 is Transform) ? value6 : null);
						if (val10 != null && (Object)(object)val10 != (Object)null)
						{
							PhotonView componentInParent = ((Component)val10).GetComponentInParent<PhotonView>();
							if ((Object)(object)componentInParent != (Object)null)
							{
								int viewID = componentInPar