Decompiled source of Aurora Season 2 v2.8.0

BepInEx/plugins/Aurora Berserkir/Berserkir.dll

Decompiled 2 weeks ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;
using UnityEngine.Networking;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyCompany("Berserkir")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("Berserkir")]
[assembly: AssemblyTitle("Berserkir")]
[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 Berserkir
{
	[Serializable]
	public class BerserkData
	{
		private const string SaveKey = "Berserkir_v1";

		public float RageProgress;

		public int RageCheckpoint;

		public bool IsUnlocked;

		public int ZerkCharges;

		public float RageFloor => (float)RageCheckpoint * 20f;

		public int FilledSegments => Mathf.FloorToInt(RageProgress / 20f);

		public float CurrentSegmentFill => RageProgress % 20f / 20f;

		public string Serialize()
		{
			return JsonUtility.ToJson((object)this);
		}

		public static BerserkData Load(Player player)
		{
			if ((Object)(object)player == (Object)null)
			{
				return new BerserkData();
			}
			if (player.m_customData.TryGetValue("Berserkir_v1", out var value))
			{
				try
				{
					BerserkData berserkData = JsonUtility.FromJson<BerserkData>(value);
					if (berserkData != null)
					{
						return berserkData;
					}
				}
				catch (Exception ex)
				{
					BerserkPlugin.Log.LogWarning((object)("[Berserkir] Failed to parse save data: " + ex.Message));
				}
			}
			return new BerserkData();
		}

		public void Save(Player player)
		{
			if (!((Object)(object)player == (Object)null))
			{
				player.m_customData["Berserkir_v1"] = Serialize();
			}
		}
	}
	public class BerserkHUD : MonoBehaviour
	{
		private BerserkData _data = new BerserkData();

		private Player? _trackedPlayer;

		private bool _isBerserking;

		private float _berserkTimer;

		private float _holdTimer;

		private float _lastCombatTime = -999f;

		private float _lastFatigueMsg = -999f;

		private bool _showInfoWindow;

		private float _flashAlpha;

		private float[] _circleFlashTimers = new float[5];

		private float _allCirclesFlash;

		private const float RagePerKill = 0.75f;

		private const float RageDrainRate = 0.083f;

		private const float CombatTimeout = 6f;

		private const float ChargeChance = 0.05f;

		private const float HoldThreshold = 1f;

		private const float AnchorX = 85f;

		private const float AnchorY = 998f;

		private int _zerkCirclesLeft;

		private float _zerkElapsed;

		public static float ShakeMag;

		private bool _zerkFadingOut;

		private float _zerkFadeTimer;

		private bool _stylesReady;

		private int _lastScreenH;

		private GUIStyle? _styleTitle;

		private GUIStyle? _styleBody;

		private GUIStyle? _styleCentered;

		private GUIStyle? _styleQE;

		private Texture2D? _texDark;

		private Texture2D? _texPink;

		private Texture2D? _texBorder;

		private Texture2D? _texSegEmpty;

		private Texture2D? _texCircleRing;

		private Texture2D? _texCircleFill;

		private Texture2D? _texCircleWhite;

		private Texture2D? _texFlash;

		private Sprite? _iconSprite;

		private bool _iconLoaded;

		public static BerserkHUD? Instance { get; private set; }

		public bool IsBerserking => _isBerserking;

		public static event Action? OnCircleFaded;

		private void Awake()
		{
			Instance = this;
		}

		private void OnDestroy()
		{
			if ((Object)(object)Instance == (Object)(object)this)
			{
				Instance = null;
			}
		}

		private void EnsurePlayer()
		{
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer == (Object)null)
			{
				_trackedPlayer = null;
			}
			else if (!((Object)(object)_trackedPlayer == (Object)(object)localPlayer))
			{
				_trackedPlayer = localPlayer;
				_data = BerserkData.Load(localPlayer);
			}
		}

		public void SaveData()
		{
			_data?.Save(_trackedPlayer);
		}

		public void AdminFill()
		{
			EnsurePlayer();
			if (!((Object)(object)_trackedPlayer == (Object)null))
			{
				_data.RageProgress = 100f;
				_data.RageCheckpoint = 5;
				_data.IsUnlocked = true;
				_data.ZerkCharges = 5;
				_data.Save(_trackedPlayer);
				_allCirclesFlash = 1f;
				SpawnGPEffect(_trackedPlayer);
			}
		}

		public static void TriggerShake(float mag)
		{
			ShakeMag = mag;
		}

		public void OnMonsterKilled(Character monster)
		{
			EnsurePlayer();
			if ((Object)(object)_trackedPlayer == (Object)null)
			{
				return;
			}
			_lastCombatTime = Time.time;
			if (!_data.IsUnlocked)
			{
				_data.RageProgress = Mathf.Min(100f, _data.RageProgress + 0.75f);
				int num = Mathf.FloorToInt(_data.RageProgress / 20f);
				if (num > _data.RageCheckpoint)
				{
					_data.RageCheckpoint = Mathf.Min(5, num);
				}
				if (_data.RageProgress >= 100f)
				{
					_data.IsUnlocked = true;
					_data.ZerkCharges = 5;
					_showInfoWindow = false;
					_allCirclesFlash = 1f;
					SpawnGPEffect(_trackedPlayer);
				}
			}
			else if (!_isBerserking && _data.ZerkCharges < 5 && Random.value < 0.05f)
			{
				_data.ZerkCharges++;
				_circleFlashTimers[_data.ZerkCharges - 1] = 0.6f;
				if (_data.ZerkCharges >= 5)
				{
					_allCirclesFlash = 1f;
					SpawnGPEffect(_trackedPlayer);
				}
			}
			_data.Save(_trackedPlayer);
		}

		private void SpawnGPEffect(Player player)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: 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_0067: Expected O, but got Unknown
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)player == (Object)null)
			{
				return;
			}
			Vector3 position = ((Component)player).transform.position + Vector3.up * 0.5f;
			ZNetScene instance = ZNetScene.instance;
			GameObject val = ((instance != null) ? instance.GetPrefab("fx_GP_Player") : null);
			if (!((Object)(object)val == (Object)null))
			{
				GameObject val2 = new GameObject("_gpHolder");
				val2.SetActive(false);
				GameObject val3 = Object.Instantiate<GameObject>(val, val2.transform);
				val3.transform.position = position;
				val3.transform.rotation = Quaternion.identity;
				ZNetView[] componentsInChildren = val3.GetComponentsInChildren<ZNetView>(true);
				foreach (ZNetView val4 in componentsInChildren)
				{
					Object.DestroyImmediate((Object)(object)val4);
				}
				ZSyncTransform[] componentsInChildren2 = val3.GetComponentsInChildren<ZSyncTransform>(true);
				foreach (ZSyncTransform val5 in componentsInChildren2)
				{
					Object.DestroyImmediate((Object)(object)val5);
				}
				ZSyncAnimation[] componentsInChildren3 = val3.GetComponentsInChildren<ZSyncAnimation>(true);
				foreach (ZSyncAnimation val6 in componentsInChildren3)
				{
					Object.DestroyImmediate((Object)(object)val6);
				}
				val3.transform.SetParent((Transform)null);
				Object.DestroyImmediate((Object)(object)val2);
				val3.SetActive(true);
				Object.Destroy((Object)(object)val3, 5f);
			}
		}

		private static void ShowMsg(string msg)
		{
			MessageHud instance = MessageHud.instance;
			if (instance != null)
			{
				instance.ShowMessage((MessageType)1, msg, 0, (Sprite)null, false);
			}
		}

		private void Update()
		{
			EnsurePlayer();
			if ((Object)(object)_trackedPlayer == (Object)null)
			{
				return;
			}
			TryLoadIcon();
			HandleRageDrain();
			HandleKeyInput();
			HandleBerserkCountdown();
			if (_flashAlpha > 0f)
			{
				_flashAlpha = Mathf.Max(0f, _flashAlpha - Time.deltaTime * 3f);
			}
			for (int i = 0; i < 5; i++)
			{
				if (_circleFlashTimers[i] > 0f)
				{
					_circleFlashTimers[i] = Mathf.Max(0f, _circleFlashTimers[i] - Time.deltaTime * 2.5f);
				}
			}
			if (_allCirclesFlash > 0f)
			{
				_allCirclesFlash = Mathf.Max(0f, _allCirclesFlash - Time.deltaTime * 1.8f);
			}
			if (_zerkFadingOut)
			{
				_zerkFadeTimer = Mathf.Max(0f, _zerkFadeTimer - Time.deltaTime);
				if (_zerkFadeTimer <= 0f)
				{
					_zerkFadingOut = false;
				}
			}
			if (ShakeMag > 0f)
			{
				ShakeMag = Mathf.Max(0f, ShakeMag - Time.deltaTime * 5f);
			}
		}

		private void TryLoadIcon()
		{
			if (!_iconLoaded && !((Object)(object)ObjectDB.instance == (Object)null))
			{
				GameObject itemPrefab = ObjectDB.instance.GetItemPrefab("TrophyBjorn");
				ItemDrop val = ((itemPrefab != null) ? itemPrefab.GetComponent<ItemDrop>() : null);
				if (val != null && val.m_itemData?.m_shared?.m_icons?.Length > 0)
				{
					_iconSprite = val.m_itemData.m_shared.m_icons[0];
				}
				_iconLoaded = true;
			}
		}

		private void HandleRageDrain()
		{
			if (!_data.IsUnlocked && !_isBerserking && !(Time.time - _lastCombatTime < 6f))
			{
				float rageFloor = _data.RageFloor;
				if (_data.RageProgress > rageFloor)
				{
					_data.RageProgress = Mathf.Max(rageFloor, _data.RageProgress - 0.083f * Time.deltaTime);
				}
			}
		}

		private void HandleKeyInput()
		{
			bool key = Input.GetKey((KeyCode)113);
			bool key2 = Input.GetKey((KeyCode)101);
			if (!_data.IsUnlocked)
			{
				if (key && key2)
				{
					if (_holdTimer >= 0f)
					{
						_holdTimer += Time.deltaTime;
						if (_holdTimer >= 0.3f)
						{
							_showInfoWindow = !_showInfoWindow;
							_holdTimer = -9999f;
						}
					}
				}
				else
				{
					_holdTimer = 0f;
				}
			}
			else if (_isBerserking || _data.ZerkCharges < 5)
			{
				_holdTimer = 0f;
			}
			else if (SE_Fatigue.HasFatigue((Character?)(object)_trackedPlayer))
			{
				_holdTimer = 0f;
				if (key && key2 && Time.time - _lastFatigueMsg > 3f)
				{
					_lastFatigueMsg = Time.time;
					MessageHud instance = MessageHud.instance;
					if (instance != null)
					{
						instance.ShowMessage((MessageType)2, "<color=#888888>You are too exhausted to rage...</color>", 0, (Sprite)null, false);
					}
				}
			}
			else if (key && key2)
			{
				_holdTimer += Time.deltaTime;
				if (_holdTimer >= 1f)
				{
					ActivateBerserk();
					_holdTimer = 0f;
				}
			}
			else
			{
				_holdTimer = 0f;
			}
		}

		private void HandleBerserkCountdown()
		{
			if (!_isBerserking)
			{
				return;
			}
			_berserkTimer -= Time.deltaTime;
			_zerkElapsed += Time.deltaTime;
			int num = 5 - Mathf.FloorToInt(_zerkElapsed / 12f);
			num = Mathf.Clamp(num, 0, 5);
			if (num < _zerkCirclesLeft)
			{
				_zerkCirclesLeft = num;
				for (int i = 0; i < _zerkCirclesLeft; i++)
				{
					_circleFlashTimers[i] = 0.5f;
				}
				BerserkHUD.OnCircleFaded?.Invoke();
			}
			bool flag = ((Character)_trackedPlayer).GetSEMan().HaveStatusEffect(SE_Berserk.EffectHash);
			if (_berserkTimer <= 0f || !flag)
			{
				EndBerserk();
			}
		}

		private void ActivateBerserk()
		{
			_isBerserking = true;
			_berserkTimer = 60f;
			_zerkCirclesLeft = 5;
			_zerkElapsed = 0f;
			_data.ZerkCharges = 0;
			_data.Save(_trackedPlayer);
			_flashAlpha = 0.85f;
			_allCirclesFlash = 1f;
			ObjectDB instance = ObjectDB.instance;
			StatusEffect val = ((instance != null) ? instance.GetStatusEffect(SE_Berserk.EffectHash) : null);
			if ((Object)(object)val != (Object)null)
			{
				((Character)_trackedPlayer).GetSEMan().AddStatusEffect(val, true, 0, 0f);
			}
			else
			{
				BerserkPlugin.Log.LogError((object)"[Berserkir] SE_Berserk not found in ObjectDB!");
			}
		}

		private void EndBerserk()
		{
			_isBerserking = false;
			_zerkFadingOut = true;
			_zerkFadeTimer = 2.2f;
			if (((Character)_trackedPlayer).GetSEMan().HaveStatusEffect(SE_Berserk.EffectHash))
			{
				((Character)_trackedPlayer).GetSEMan().RemoveStatusEffect(SE_Berserk.EffectHash, false);
			}
		}

		private void OnGUI()
		{
			//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_010f: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)_trackedPlayer == (Object)null))
			{
				if (!_stylesReady || Screen.height != _lastScreenH)
				{
					InitStyles();
				}
				float num = (float)Screen.height / 1080f;
				float num2 = 85f * num;
				float num3 = 998f * num;
				if (!_data.IsUnlocked)
				{
					DrawPreUnlock(num2, num3, num);
				}
				else
				{
					DrawPostUnlock(num2, num3, num);
				}
				if (_showInfoWindow && !_data.IsUnlocked)
				{
					DrawInfoWindow(num2, num3, num);
				}
				if (_flashAlpha > 0.001f)
				{
					GUI.color = new Color(1f, 0.35f, 0.05f, _flashAlpha * 0.55f);
					GUI.DrawTexture(new Rect(0f, 0f, (float)Screen.width, (float)Screen.height), (Texture)(object)_texFlash);
					GUI.color = Color.white;
				}
			}
		}

		private void DrawPreUnlock(float x, float y, float s)
		{
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
			float num = 54f * s;
			float num2 = 54f * s;
			float num3 = y - num2 * 0.5f;
			Rect val = default(Rect);
			((Rect)(ref val))..ctor(x, num3, num, num2);
			if ((Object)(object)_iconSprite != (Object)null)
			{
				GUI.color = new Color(1f, 0.2f, 0.2f, 1f);
				DrawSprite(_iconSprite, val);
				GUI.color = Color.white;
			}
			else
			{
				GUI.Label(val, "<color=#CC2222><size=36>☠</size></color>", _styleCentered);
			}
			if (GUI.Button(val, GUIContent.none, GUIStyle.none))
			{
				_showInfoWindow = !_showInfoWindow;
			}
			GUI.Label(new Rect(x - 6f * s, num3 + num2 + 2f * s, num + 12f * s, 18f * s), "Q + E", _styleQE);
		}

		private void DrawPostUnlock(float x, float y, float s)
		{
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_017a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0190: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_01df: Unknown result type (might be due to invalid IL or missing references)
			float num = 22f * s;
			float num2 = 4f * s;
			float num3 = 5f * num + 4f * num2;
			float num4 = y - num3;
			for (int i = 0; i < 5; i++)
			{
				float num5 = num4 + (float)i * (num + num2);
				bool flag = (_isBerserking ? (i < _zerkCirclesLeft) : (i < _data.ZerkCharges));
				float flash = Mathf.Max(_circleFlashTimers[i], _allCirclesFlash);
				DrawCircle(new Rect(x, num5, num, num), flag, flash, _isBerserking && flag);
			}
			if (!_isBerserking && _data.ZerkCharges >= 5)
			{
				float num6 = num4 + 5f * (num + num2) + 3f * s;
				GUI.Label(new Rect(x - 6f * s, num6, num + 12f * s, 18f * s), "Q + E", _styleQE);
			}
			if (!_isBerserking && _holdTimer > 0f && _data.ZerkCharges >= 5)
			{
				float num7 = Mathf.Clamp01(_holdTimer / 1f);
				float num8 = num4 + 5f * (num + num2) + 22f * s;
				GUI.color = new Color(0.06f, 0.03f, 0.03f, 0.85f);
				GUI.DrawTexture(new Rect(x, num8, num, 4f * s), (Texture)(object)_texDark);
				GUI.color = new Color(0.75f, 0.07f, 0.1f, 1f);
				GUI.DrawTexture(new Rect(x, num8, num * num7, 4f * s), (Texture)(object)_texPink);
				GUI.color = Color.white;
			}
		}

		private void DrawInfoWindow(float anchorX, float anchorY, float s)
		{
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fe: Unknown result type (might be due to invalid IL or missing references)
			float num = 470f * s;
			float num2 = 360f * s;
			float num3 = anchorY - num2 - 70f * s;
			num3 = Mathf.Max(4f, num3);
			Rect r = default(Rect);
			((Rect)(ref r))..ctor(anchorX, num3, num, num2);
			DrawWoodPanel(r, border: true);
			float num4 = 16f * s;
			float num5 = ((Rect)(ref r)).x + num4;
			float num6 = ((Rect)(ref r)).y + num4;
			float num7 = num - num4 * 2f;
			if (GUI.Button(new Rect(((Rect)(ref r)).xMax - 28f * s, ((Rect)(ref r)).y + 6f * s, 22f * s, 20f * s), "✕", _styleBody))
			{
				_showInfoWindow = false;
			}
			GUI.Label(new Rect(num5, num6, num7, 38f * s), "Berserkir", _styleTitle);
			num6 += 44f * s;
			string text = "Fill rage by killing monsters. Once you kill enough monsters, the bar will fill.\n\nWind down — the bar will fade until the checkpoint mark.\n\nFill all 5 bars to unlock Berserkir mode.\n\nActivate by holding <color=#FFD400><b>Q + E</b></color> at the same time.";
			GUI.Label(new Rect(num5, num6, num7, 170f * s), text, _styleBody);
			num6 += 175f * s;
			DrawRageBar(num5, num6, num7, 28f * s, s);
		}

		private void DrawRageBar(float x, float y, float w, float h, float s)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0131: Unknown result type (might be due to invalid IL or missing references)
			//IL_0140: Unknown result type (might be due to invalid IL or missing references)
			//IL_015a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0170: Unknown result type (might be due to invalid IL or missing references)
			//IL_018a: Unknown result type (might be due to invalid IL or missing references)
			//IL_019b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
			GUI.color = Color.white;
			GUI.DrawTexture(new Rect(x, y, w, h), (Texture)(object)_texDark);
			float num = Mathf.Clamp01(_data.RageProgress / 100f) * w;
			if (num >= 1f)
			{
				GUI.DrawTexture(new Rect(x, y, num, h), (Texture)(object)_texPink);
			}
			float num2 = 3f * s;
			for (int i = 1; i <= 4; i++)
			{
				float num3 = x + w / 5f * (float)i - num2 * 0.5f;
				if (_data.RageCheckpoint >= i)
				{
					GUI.color = new Color(0.9f, 0.65f, 0.1f, 1f);
				}
				else
				{
					GUI.color = new Color(0.75f, 0.73f, 0.71f, 1f);
				}
				GUI.DrawTexture(new Rect(num3, y, num2, h), (Texture)(object)_texBorder);
			}
			float num4 = 2f * s;
			GUI.color = new Color(0.72f, 0.48f, 0.08f, 1f);
			GUI.DrawTexture(new Rect(x, y, w, num4), (Texture)(object)_texBorder);
			GUI.DrawTexture(new Rect(x, y + h - num4, w, num4), (Texture)(object)_texBorder);
			GUI.DrawTexture(new Rect(x, y, num4, h), (Texture)(object)_texBorder);
			GUI.DrawTexture(new Rect(x + w - num4, y, num4, h), (Texture)(object)_texBorder);
			GUI.color = Color.white;
		}

		private void DrawWoodPanel(Rect r, bool border = false)
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_010a: Unknown result type (might be due to invalid IL or missing references)
			GUI.color = new Color(0.12f, 0.07f, 0.04f, 0.92f);
			GUI.DrawTexture(r, (Texture)(object)_texDark);
			GUI.color = Color.white;
			if (border)
			{
				float num = 2f;
				GUI.color = new Color(0.72f, 0.48f, 0.08f, 0.92f);
				GUI.DrawTexture(new Rect(((Rect)(ref r)).x, ((Rect)(ref r)).y, ((Rect)(ref r)).width, num), (Texture)(object)_texBorder);
				GUI.DrawTexture(new Rect(((Rect)(ref r)).x, ((Rect)(ref r)).yMax - num, ((Rect)(ref r)).width, num), (Texture)(object)_texBorder);
				GUI.DrawTexture(new Rect(((Rect)(ref r)).x, ((Rect)(ref r)).y, num, ((Rect)(ref r)).height), (Texture)(object)_texBorder);
				GUI.DrawTexture(new Rect(((Rect)(ref r)).xMax - num, ((Rect)(ref r)).y, num, ((Rect)(ref r)).height), (Texture)(object)_texBorder);
				GUI.color = Color.white;
			}
		}

		private void DrawCircle(Rect r, bool filled, float flash = 0f, bool zerkGlow = false)
		{
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0120: Unknown result type (might be due to invalid IL or missing references)
			//IL_012b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0139: Unknown result type (might be due to invalid IL or missing references)
			//IL_0158: Unknown result type (might be due to invalid IL or missing references)
			//IL_0163: Unknown result type (might be due to invalid IL or missing references)
			//IL_0170: Unknown result type (might be due to invalid IL or missing references)
			//IL_0201: Unknown result type (might be due to invalid IL or missing references)
			//IL_020c: Unknown result type (might be due to invalid IL or missing references)
			//IL_021a: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c1: Unknown result type (might be due to invalid IL or missing references)
			float num = ((Rect)(ref r)).width * 0.05f;
			Rect val = default(Rect);
			((Rect)(ref val))..ctor(((Rect)(ref r)).x + num, ((Rect)(ref r)).y + num, ((Rect)(ref r)).width - num * 2f, ((Rect)(ref r)).height - num * 2f);
			GUI.color = new Color(0.04f, 0.02f, 0.02f, 0.28f);
			GUI.DrawTexture(val, (Texture)(object)_texCircleFill);
			GUI.color = Color.white;
			GUI.color = new Color(0.72f, 0.48f, 0.08f, filled ? 1f : 0.4f);
			GUI.DrawTexture(r, (Texture)(object)_texCircleRing);
			GUI.color = Color.white;
			if (filled)
			{
				float num2 = ((Rect)(ref r)).width * 0.18f;
				Rect val2 = default(Rect);
				((Rect)(ref val2))..ctor(((Rect)(ref r)).x + num2, ((Rect)(ref r)).y + num2, ((Rect)(ref r)).width - num2 * 2f, ((Rect)(ref r)).height - num2 * 2f);
				GUI.color = new Color(0.8f, 0.05f, 0.08f, 1f);
				GUI.DrawTexture(val2, (Texture)(object)_texCircleFill);
				GUI.color = Color.white;
				GUI.color = new Color(1f, 0.4f, 0.1f, 0.55f);
				GUI.DrawTexture(r, (Texture)(object)_texCircleRing);
				GUI.color = Color.white;
			}
			if (zerkGlow)
			{
				float num3 = 0.55f + Mathf.Sin(Time.time * 3.5f) * 0.2f;
				float num4 = ((Rect)(ref r)).width * 0.18f;
				Rect val3 = default(Rect);
				((Rect)(ref val3))..ctor(((Rect)(ref r)).x - num4, ((Rect)(ref r)).y - num4, ((Rect)(ref r)).width + num4 * 2f, ((Rect)(ref r)).height + num4 * 2f);
				GUI.color = new Color(1f, 0.2f, 0.05f, num3);
				GUI.DrawTexture(val3, (Texture)(object)_texCircleWhite);
				GUI.color = Color.white;
			}
			if (flash > 0.01f)
			{
				float num5 = Mathf.Clamp01(flash) * 0.9f;
				float num6 = ((Rect)(ref r)).width * 0.25f * Mathf.Clamp01(flash);
				Rect val4 = default(Rect);
				((Rect)(ref val4))..ctor(((Rect)(ref r)).x - num6, ((Rect)(ref r)).y - num6, ((Rect)(ref r)).width + num6 * 2f, ((Rect)(ref r)).height + num6 * 2f);
				GUI.color = new Color(1f, 0.95f, 0.8f, num5);
				GUI.DrawTexture(val4, (Texture)(object)_texCircleWhite);
				GUI.color = Color.white;
			}
		}

		private static void DrawSprite(Sprite sprite, Rect rect)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			Rect textureRect = sprite.textureRect;
			Texture2D texture = sprite.texture;
			GUI.DrawTextureWithTexCoords(rect, (Texture)(object)texture, new Rect(((Rect)(ref textureRect)).x / (float)((Texture)texture).width, ((Rect)(ref textureRect)).y / (float)((Texture)texture).height, ((Rect)(ref textureRect)).width / (float)((Texture)texture).width, ((Rect)(ref textureRect)).height / (float)((Texture)texture).height));
		}

		private void InitStyles()
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fb: 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_01cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0203: Unknown result type (might be due to invalid IL or missing references)
			//IL_020f: Expected O, but got Unknown
			//IL_0234: Unknown result type (might be due to invalid IL or missing references)
			//IL_0239: Unknown result type (might be due to invalid IL or missing references)
			//IL_0242: Unknown result type (might be due to invalid IL or missing references)
			//IL_024a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0252: Unknown result type (might be due to invalid IL or missing references)
			//IL_025a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0262: Unknown result type (might be due to invalid IL or missing references)
			//IL_0268: Unknown result type (might be due to invalid IL or missing references)
			//IL_0274: Expected O, but got Unknown
			//IL_0299: Unknown result type (might be due to invalid IL or missing references)
			//IL_029e: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_02af: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_02bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_02cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_02da: Expected O, but got Unknown
			//IL_02ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0304: Unknown result type (might be due to invalid IL or missing references)
			//IL_0317: Unknown result type (might be due to invalid IL or missing references)
			//IL_031f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0327: Unknown result type (might be due to invalid IL or missing references)
			//IL_032f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0337: Unknown result type (might be due to invalid IL or missing references)
			//IL_034c: Unknown result type (might be due to invalid IL or missing references)
			//IL_035c: Expected O, but got Unknown
			_lastScreenH = Screen.height;
			float num = (float)Screen.height / 1080f;
			_texDark = MakeSolid(new Color(0.12f, 0.07f, 0.04f, 1f));
			_texPink = MakeSolid(new Color(0.75f, 0.07f, 0.1f, 1f));
			_texBorder = MakeSolid(new Color(0.72f, 0.48f, 0.08f, 1f));
			_texSegEmpty = MakeSolid(new Color(0.72f, 0.7f, 0.68f, 1f));
			_texCircleRing = MakeCircle(64, filled: false, new Color(0.72f, 0.48f, 0.08f, 0.95f));
			_texCircleFill = MakeCircle(64, filled: true, new Color(0.85f, 0.08f, 0.22f, 1f));
			_texCircleWhite = MakeCircle(64, filled: true, Color.white);
			_texFlash = MakeSolid(new Color(0.7f, 0.05f, 0.05f, 1f));
			Font val = ((IEnumerable<Font>)Resources.FindObjectsOfTypeAll<Font>()).FirstOrDefault((Func<Font, bool>)((Font f) => ((Object)f).name.Equals("Norsebold", StringComparison.OrdinalIgnoreCase) || ((Object)f).name.Equals("Norse Bold", StringComparison.OrdinalIgnoreCase)));
			Color textColor = default(Color);
			((Color)(ref textColor))..ctor(0.83f, 0.53f, 0.16f);
			Color textColor2 = default(Color);
			((Color)(ref textColor2))..ctor(0.78f, 0.66f, 0.51f);
			Color textColor3 = default(Color);
			((Color)(ref textColor3))..ctor(0.91f, 0.75f, 0.25f);
			int fontSize = Mathf.RoundToInt(24f * num);
			int fontSize2 = Mathf.RoundToInt(17f * num);
			int num2 = Mathf.RoundToInt(17f * num);
			GUIStyle val2 = new GUIStyle(GUI.skin.label)
			{
				fontSize = fontSize,
				fontStyle = (FontStyle)1,
				richText = true,
				wordWrap = false,
				alignment = (TextAnchor)3
			};
			val2.normal.textColor = textColor;
			_styleTitle = val2;
			if ((Object)(object)val != (Object)null)
			{
				_styleTitle.font = val;
			}
			GUIStyle val3 = new GUIStyle(GUI.skin.label)
			{
				fontSize = fontSize2,
				fontStyle = (FontStyle)0,
				richText = true,
				wordWrap = true,
				alignment = (TextAnchor)0
			};
			val3.normal.textColor = textColor2;
			_styleBody = val3;
			if ((Object)(object)val != (Object)null)
			{
				_styleBody.font = val;
			}
			GUIStyle val4 = new GUIStyle(GUI.skin.label)
			{
				fontSize = fontSize2,
				fontStyle = (FontStyle)1,
				richText = true,
				wordWrap = false,
				alignment = (TextAnchor)4
			};
			val4.normal.textColor = textColor3;
			_styleCentered = val4;
			if ((Object)(object)val != (Object)null)
			{
				_styleCentered.font = val;
			}
			GUIStyle val5 = new GUIStyle(GUI.skin.label)
			{
				fontSize = Mathf.RoundToInt(12f * num),
				fontStyle = (FontStyle)1,
				richText = true,
				wordWrap = false,
				alignment = (TextAnchor)4
			};
			val5.normal.textColor = new Color(1f, 0.85f, 0.1f);
			_styleQE = val5;
			_stylesReady = true;
		}

		private static Texture2D MakeSolid(Color c)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Expected O, but got Unknown
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			Texture2D val = new Texture2D(4, 4, (TextureFormat)4, false);
			Color[] array = (Color[])(object)new Color[16];
			for (int i = 0; i < 16; i++)
			{
				array[i] = c;
			}
			val.SetPixels(array);
			val.Apply();
			return val;
		}

		private static Texture2D MakeCircle(int size, bool filled, Color c)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Expected O, but got Unknown
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			Texture2D val = new Texture2D(size, size, (TextureFormat)4, false);
			float num = (float)size * 0.5f;
			float num2 = num - 1.5f;
			float num3 = num2 - 6f;
			for (int i = 0; i < size; i++)
			{
				for (int j = 0; j < size; j++)
				{
					float num4 = (float)j - num + 0.5f;
					float num5 = (float)i - num + 0.5f;
					float num6 = Mathf.Sqrt(num4 * num4 + num5 * num5);
					bool flag = (filled ? (num6 <= num2) : (num6 <= num2 && num6 >= num3));
					val.SetPixel(j, i, flag ? c : Color.clear);
				}
			}
			val.Apply();
			return val;
		}
	}
	public static class BerserkParticle
	{
		private static Material? _mat;

		public static void SpawnHitSplash(Vector3 worldPos, Vector3 hitDir)
		{
			//IL_0269: Unknown result type (might be due to invalid IL or missing references)
			//IL_026f: Expected O, but got Unknown
			//IL_0275: Unknown result type (might be due to invalid IL or missing references)
			//IL_027c: Unknown result type (might be due to invalid IL or missing references)
			//IL_027d: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_02cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0317: Unknown result type (might be due to invalid IL or missing references)
			//IL_0330: Unknown result type (might be due to invalid IL or missing references)
			//IL_037a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0393: Unknown result type (might be due to invalid IL or missing references)
			//IL_0293: Unknown result type (might be due to invalid IL or missing references)
			//IL_0294: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Expected O, but got Unknown
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0166: Unknown result type (might be due to invalid IL or missing references)
			//IL_016b: Unknown result type (might be due to invalid IL or missing references)
			//IL_016f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0174: Unknown result type (might be due to invalid IL or missing references)
			//IL_0178: Unknown result type (might be due to invalid IL or missing references)
			//IL_017d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0181: Unknown result type (might be due to invalid IL or missing references)
			//IL_0186: Unknown result type (might be due to invalid IL or missing references)
			//IL_018a: Unknown result type (might be due to invalid IL or missing references)
			//IL_018f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0193: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01be: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_01db: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0201: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)ZNetScene.instance != (Object)null)
			{
				string[] array = new string[4] { "vfx_BloodHit", "vfx_BloodDeath", "fx_bloodweapon_hit", "fx_TickBloodHit" };
				foreach (string text in array)
				{
					GameObject prefab = ZNetScene.instance.GetPrefab(text);
					if ((Object)(object)prefab == (Object)null)
					{
						continue;
					}
					try
					{
						GameObject val = new GameObject("_bloodHolder");
						val.SetActive(false);
						Quaternion rotation = ((hitDir != Vector3.zero) ? Quaternion.LookRotation(hitDir) : Quaternion.identity);
						GameObject val2 = Object.Instantiate<GameObject>(prefab, val.transform);
						val2.transform.position = worldPos;
						val2.transform.rotation = rotation;
						ZNetView[] componentsInChildren = val2.GetComponentsInChildren<ZNetView>(true);
						foreach (ZNetView val3 in componentsInChildren)
						{
							Object.DestroyImmediate((Object)(object)val3);
						}
						ZSyncTransform[] componentsInChildren2 = val2.GetComponentsInChildren<ZSyncTransform>(true);
						foreach (ZSyncTransform val4 in componentsInChildren2)
						{
							Object.DestroyImmediate((Object)(object)val4);
						}
						val2.transform.SetParent((Transform)null);
						Object.DestroyImmediate((Object)(object)val);
						val2.SetActive(true);
						ParticleSystem[] componentsInChildren3 = val2.GetComponentsInChildren<ParticleSystem>(true);
						foreach (ParticleSystem val5 in componentsInChildren3)
						{
							MainModule main = val5.main;
							MinMaxGradient startColor = ((MainModule)(ref main)).startColor;
							Color colorMin = ((MinMaxGradient)(ref startColor)).colorMin;
							startColor = ((MainModule)(ref main)).startColor;
							Color colorMax = ((MinMaxGradient)(ref startColor)).colorMax;
							((MainModule)(ref main)).startColor = new MinMaxGradient(new Color(Mathf.Max(colorMin.r, 0.8f), colorMin.g * 0.15f, colorMin.b * 0.1f, colorMin.a), new Color(Mathf.Max(colorMax.r, 0.95f), colorMax.g * 0.2f, colorMax.b * 0.1f, colorMax.a));
						}
						Object.Destroy((Object)(object)val2, 1.5f);
						return;
					}
					catch
					{
					}
				}
			}
			EnsureMaterial();
			if (!((Object)(object)_mat == (Object)null))
			{
				GameObject val6 = new GameObject("BerkHit");
				val6.transform.position = worldPos;
				if (hitDir != Vector3.zero)
				{
					val6.transform.rotation = Quaternion.LookRotation(hitDir);
				}
				ParticleSystem ps = AddBurst(val6, new Color(1f, 0.05f, 0.18f, 0.9f), new Color(0.8f, 0f, 0.32f, 1f), 12, 3f, 6f, 0.07f, 0.2f, 0.2f, 0.4f, 100f, 2f);
				ParticleSystem ps2 = AddBurst(val6, new Color(1f, 0.35f, 0.55f, 0.85f), new Color(1f, 0.1f, 0.28f, 0.9f), 20, 4f, 9f, 0.02f, 0.08f, 0.12f, 0.26f, 130f, 1.4f);
				ParticleSystem ps3 = AddBurst(val6, new Color(0.9f, 0.08f, 0.22f, 0.4f), new Color(1f, 0.03f, 0.38f, 0.55f), 6, 0.6f, 1.8f, 0.18f, 0.42f, 0.28f, 0.55f, 360f, 0.08f);
				ApplyMaterial(ps, (ParticleSystemRenderMode)1, 0.15f, 1.5f);
				ApplyMaterial(ps2, (ParticleSystemRenderMode)1, 0.1f, 1.2f);
				ApplyMaterial(ps3, (ParticleSystemRenderMode)0);
				Object.Destroy((Object)(object)val6, 0.7f);
			}
		}

		private static ParticleSystem AddBurst(GameObject parent, Color col1, Color col2, int count, float speed, float maxSpeed, float size, float maxSize, float lifetime, float maxLifetime, float spread, float gravity)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Expected O, but got Unknown
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_0092: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_011c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0121: Unknown result type (might be due to invalid IL or missing references)
			//IL_012c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0133: Expected O, but got Unknown
			//IL_013d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0143: Unknown result type (might be due to invalid IL or missing references)
			//IL_0148: 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)
			//IL_0155: Unknown result type (might be due to invalid IL or missing references)
			//IL_015a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0171: Unknown result type (might be due to invalid IL or missing references)
			//IL_0176: Unknown result type (might be due to invalid IL or missing references)
			//IL_0187: Unknown result type (might be due to invalid IL or missing references)
			//IL_018c: Unknown result type (might be due to invalid IL or missing references)
			//IL_019b: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01be: Expected O, but got Unknown
			//IL_01eb: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject("L");
			val.transform.SetParent(parent.transform, false);
			ParticleSystem val2 = val.AddComponent<ParticleSystem>();
			MainModule main = val2.main;
			((MainModule)(ref main)).loop = false;
			((MainModule)(ref main)).playOnAwake = true;
			((MainModule)(ref main)).duration = 0.05f;
			((MainModule)(ref main)).startLifetime = new MinMaxCurve(lifetime, maxLifetime);
			((MainModule)(ref main)).startSpeed = new MinMaxCurve(speed, maxSpeed);
			((MainModule)(ref main)).startSize = new MinMaxCurve(size, maxSize);
			((MainModule)(ref main)).startColor = new MinMaxGradient(col1, col2);
			((MainModule)(ref main)).gravityModifier = new MinMaxCurve(gravity);
			((MainModule)(ref main)).maxParticles = count + 4;
			((MainModule)(ref main)).simulationSpace = (ParticleSystemSimulationSpace)1;
			EmissionModule emission = val2.emission;
			((EmissionModule)(ref emission)).enabled = true;
			((EmissionModule)(ref emission)).rateOverTime = MinMaxCurve.op_Implicit(0f);
			((EmissionModule)(ref emission)).SetBurst(0, new Burst(0f, MinMaxCurve.op_Implicit((float)count)));
			ShapeModule shape = val2.shape;
			((ShapeModule)(ref shape)).shapeType = (ParticleSystemShapeType)4;
			((ShapeModule)(ref shape)).angle = spread * 0.5f;
			((ShapeModule)(ref shape)).radius = 0.04f;
			ColorOverLifetimeModule colorOverLifetime = val2.colorOverLifetime;
			((ColorOverLifetimeModule)(ref colorOverLifetime)).enabled = true;
			Gradient val3 = new Gradient();
			val3.SetKeys((GradientColorKey[])(object)new GradientColorKey[2]
			{
				new GradientColorKey(col1, 0f),
				new GradientColorKey(col2, 1f)
			}, (GradientAlphaKey[])(object)new GradientAlphaKey[2]
			{
				new GradientAlphaKey(1f, 0f),
				new GradientAlphaKey(0f, 1f)
			});
			((ColorOverLifetimeModule)(ref colorOverLifetime)).color = new MinMaxGradient(val3);
			SizeOverLifetimeModule sizeOverLifetime = val2.sizeOverLifetime;
			((SizeOverLifetimeModule)(ref sizeOverLifetime)).enabled = true;
			AnimationCurve val4 = new AnimationCurve();
			val4.AddKey(0f, 1f);
			val4.AddKey(1f, 0.08f);
			((SizeOverLifetimeModule)(ref sizeOverLifetime)).size = new MinMaxCurve(1f, val4);
			return val2;
		}

		private static void ApplyMaterial(ParticleSystem ps, ParticleSystemRenderMode mode, float vScale = 0f, float lScale = 1f)
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Invalid comparison between Unknown and I4
			ParticleSystemRenderer component = ((Component)ps).GetComponent<ParticleSystemRenderer>();
			((Renderer)component).material = _mat;
			component.renderMode = mode;
			if ((int)mode == 1)
			{
				component.velocityScale = vScale;
				component.lengthScale = lScale;
			}
			((Renderer)component).sortingOrder = 5;
		}

		private static void EnsureMaterial()
		{
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Expected O, but got Unknown
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e0: Expected O, but got Unknown
			if ((Object)(object)_mat != (Object)null)
			{
				return;
			}
			ParticleSystem[] array = Object.FindObjectsByType<ParticleSystem>((FindObjectsSortMode)0);
			foreach (ParticleSystem val in array)
			{
				ParticleSystemRenderer component = ((Component)val).GetComponent<ParticleSystemRenderer>();
				if (!((Object)(object)((component != null) ? ((Renderer)component).sharedMaterial : null) == (Object)null))
				{
					_mat = new Material(((Renderer)component).sharedMaterial)
					{
						name = "BerkHitMat"
					};
					return;
				}
			}
			string[] array2 = new string[4] { "Custom/Particle", "Particles/Standard Unlit", "Legacy Shaders/Particles/Additive", "Sprites/Default" };
			foreach (string text in array2)
			{
				Shader val2 = Shader.Find(text);
				if (!((Object)(object)val2 == (Object)null))
				{
					_mat = new Material(val2)
					{
						name = "BerkHitMat"
					};
					_mat.SetInt("_SrcBlend", 5);
					_mat.SetInt("_DstBlend", 1);
					_mat.SetInt("_ZWrite", 0);
					_mat.renderQueue = 3000;
					break;
				}
			}
		}
	}
	public class BerserkSwirl : MonoBehaviour
	{
		private ParticleSystem? _ring;

		private ParticleSystem? _halo;

		private ParticleSystem? _embers;

		private float _time;

		private Material? _mat;

		public static BerserkSwirl Attach(Character c)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Expected O, but got Unknown
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject("BerkAura");
			val.transform.SetParent(((Component)c).transform, false);
			val.transform.localPosition = Vector3.zero;
			BerserkSwirl berserkSwirl = val.AddComponent<BerserkSwirl>();
			berserkSwirl.Build();
			return berserkSwirl;
		}

		private void Build()
		{
			_mat = MakeGlowMat();
			_ring = MakeGroundRing(((Component)this).transform, _mat);
			_halo = MakeBodyHalo(((Component)this).transform, _mat);
			_embers = MakeEmbers(((Component)this).transform, _mat);
		}

		private void OnDestroy()
		{
			if ((Object)(object)_mat != (Object)null)
			{
				Object.Destroy((Object)(object)_mat);
			}
		}

		private void Update()
		{
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			_time += Time.deltaTime;
			if ((Object)(object)_halo != (Object)null)
			{
				EmissionModule emission = _halo.emission;
				((EmissionModule)(ref emission)).rateOverTime = new MinMaxCurve(8f + Mathf.Abs(Mathf.Sin(_time * 2.8f)) * 28f);
			}
			if ((Object)(object)_ring != (Object)null)
			{
				float num = Mathf.Pow(Mathf.Abs(Mathf.Sin(_time * 1.4f)), 3f);
				EmissionModule emission2 = _ring.emission;
				((EmissionModule)(ref emission2)).rateOverTime = new MinMaxCurve(3f + num * 35f);
			}
		}

		private static Material MakeGlowMat()
		{
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Expected O, but got Unknown
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Expected O, but got Unknown
			//IL_0142: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			Shader val = Shader.Find("Particles/Additive");
			if ((Object)(object)val == (Object)null)
			{
				val = Shader.Find("Mobile/Particles/Additive");
			}
			if ((Object)(object)val == (Object)null)
			{
				val = Shader.Find("Legacy Shaders/Particles/Additive");
			}
			Material val2 = new Material(val ?? Shader.Find("Sprites/Default"));
			Texture2D val3 = new Texture2D(64, 64, (TextureFormat)4, false);
			float num = 32f;
			for (int i = 0; i < 64; i++)
			{
				for (int j = 0; j < 64; j++)
				{
					float num2 = ((float)j - num + 0.5f) / num;
					float num3 = ((float)i - num + 0.5f) / num;
					float num4 = Mathf.Sqrt(num2 * num2 + num3 * num3);
					float num5 = Mathf.Clamp01(1f - num4);
					num5 *= num5;
					val3.SetPixel(j, i, new Color(1f, 1f, 1f, num5));
				}
			}
			val3.Apply();
			((Texture)val3).wrapMode = (TextureWrapMode)1;
			val2.mainTexture = (Texture)(object)val3;
			if (val2.HasProperty("_TintColor"))
			{
				val2.SetColor("_TintColor", new Color(0.9f, 0.1f, 0f, 0.6f));
			}
			return val2;
		}

		private static ParticleSystem MakeGroundRing(Transform parent, Material mat)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Expected O, but got Unknown
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0108: Unknown result type (might be due to invalid IL or missing references)
			//IL_010d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0116: Unknown result type (might be due to invalid IL or missing references)
			//IL_0123: Unknown result type (might be due to invalid IL or missing references)
			//IL_0128: Unknown result type (might be due to invalid IL or missing references)
			//IL_0167: Unknown result type (might be due to invalid IL or missing references)
			//IL_0182: Unknown result type (might be due to invalid IL or missing references)
			//IL_0196: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject("AuraRing");
			val.transform.SetParent(parent, false);
			val.transform.localPosition = new Vector3(0f, 0.05f, 0f);
			ParticleSystem val2 = val.AddComponent<ParticleSystem>();
			MainModule main = val2.main;
			((MainModule)(ref main)).loop = true;
			((MainModule)(ref main)).simulationSpace = (ParticleSystemSimulationSpace)1;
			((MainModule)(ref main)).startLifetime = new MinMaxCurve(0.5f, 0.9f);
			((MainModule)(ref main)).startSpeed = new MinMaxCurve(1.5f, 3f);
			((MainModule)(ref main)).startSize = new MinMaxCurve(0.14f, 0.26f);
			((MainModule)(ref main)).startColor = new MinMaxGradient(new Color(1f, 0.1f, 0f, 1f), new Color(0.8f, 0f, 0f, 0.8f));
			((MainModule)(ref main)).gravityModifier = MinMaxCurve.op_Implicit(0.3f);
			((MainModule)(ref main)).maxParticles = 250;
			((MainModule)(ref main)).stopAction = (ParticleSystemStopAction)0;
			EmissionModule emission = val2.emission;
			((EmissionModule)(ref emission)).rateOverTime = MinMaxCurve.op_Implicit(10f);
			ShapeModule shape = val2.shape;
			((ShapeModule)(ref shape)).enabled = true;
			((ShapeModule)(ref shape)).shapeType = (ParticleSystemShapeType)10;
			((ShapeModule)(ref shape)).radius = 0.05f;
			((ShapeModule)(ref shape)).radiusThickness = 1f;
			((ShapeModule)(ref shape)).rotation = new Vector3(-90f, 0f, 0f);
			ApplyFade(val2, new Color(1f, 0.1f, 0f), new Color(0.4f, 0f, 0f));
			ParticleSystemRenderer component = ((Component)val2).GetComponent<ParticleSystemRenderer>();
			component.renderMode = (ParticleSystemRenderMode)0;
			((Renderer)component).sharedMaterial = mat;
			val2.Play();
			return val2;
		}

		private static ParticleSystem MakeBodyHalo(Transform parent, Material mat)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Expected O, but got Unknown
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0108: Unknown result type (might be due to invalid IL or missing references)
			//IL_010d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0116: Unknown result type (might be due to invalid IL or missing references)
			//IL_0123: Unknown result type (might be due to invalid IL or missing references)
			//IL_0128: Unknown result type (might be due to invalid IL or missing references)
			//IL_0156: Unknown result type (might be due to invalid IL or missing references)
			//IL_015b: Unknown result type (might be due to invalid IL or missing references)
			//IL_016d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0188: Unknown result type (might be due to invalid IL or missing references)
			//IL_019c: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject("AuraHalo");
			val.transform.SetParent(parent, false);
			val.transform.localPosition = new Vector3(0f, 1f, 0f);
			ParticleSystem val2 = val.AddComponent<ParticleSystem>();
			MainModule main = val2.main;
			((MainModule)(ref main)).loop = true;
			((MainModule)(ref main)).simulationSpace = (ParticleSystemSimulationSpace)1;
			((MainModule)(ref main)).startLifetime = new MinMaxCurve(0.7f, 1.5f);
			((MainModule)(ref main)).startSpeed = new MinMaxCurve(0.5f, 1.4f);
			((MainModule)(ref main)).startSize = new MinMaxCurve(0.1f, 0.24f);
			((MainModule)(ref main)).startColor = new MinMaxGradient(new Color(1f, 0.1f, 0f, 0.9f), new Color(0.8f, 0f, 0f, 0.7f));
			((MainModule)(ref main)).gravityModifier = MinMaxCurve.op_Implicit(-0.05f);
			((MainModule)(ref main)).maxParticles = 180;
			((MainModule)(ref main)).stopAction = (ParticleSystemStopAction)0;
			EmissionModule emission = val2.emission;
			((EmissionModule)(ref emission)).rateOverTime = MinMaxCurve.op_Implicit(18f);
			ShapeModule shape = val2.shape;
			((ShapeModule)(ref shape)).enabled = true;
			((ShapeModule)(ref shape)).shapeType = (ParticleSystemShapeType)0;
			((ShapeModule)(ref shape)).radius = 0.65f;
			((ShapeModule)(ref shape)).radiusThickness = 0f;
			VelocityOverLifetimeModule velocityOverLifetime = val2.velocityOverLifetime;
			((VelocityOverLifetimeModule)(ref velocityOverLifetime)).enabled = true;
			((VelocityOverLifetimeModule)(ref velocityOverLifetime)).radial = new MinMaxCurve(1.2f);
			ApplyFade(val2, new Color(1f, 0.05f, 0f), new Color(0.3f, 0f, 0f));
			ParticleSystemRenderer component = ((Component)val2).GetComponent<ParticleSystemRenderer>();
			component.renderMode = (ParticleSystemRenderMode)0;
			((Renderer)component).sharedMaterial = mat;
			val2.Play();
			return val2;
		}

		private static ParticleSystem MakeEmbers(Transform parent, Material mat)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Expected O, but got Unknown
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0108: Unknown result type (might be due to invalid IL or missing references)
			//IL_010d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0116: Unknown result type (might be due to invalid IL or missing references)
			//IL_0123: Unknown result type (might be due to invalid IL or missing references)
			//IL_0128: Unknown result type (might be due to invalid IL or missing references)
			//IL_0167: Unknown result type (might be due to invalid IL or missing references)
			//IL_0182: Unknown result type (might be due to invalid IL or missing references)
			//IL_0196: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject("AuraEmbers");
			val.transform.SetParent(parent, false);
			val.transform.localPosition = new Vector3(0f, 0.1f, 0f);
			ParticleSystem val2 = val.AddComponent<ParticleSystem>();
			MainModule main = val2.main;
			((MainModule)(ref main)).loop = true;
			((MainModule)(ref main)).simulationSpace = (ParticleSystemSimulationSpace)1;
			((MainModule)(ref main)).startLifetime = new MinMaxCurve(1f, 2.2f);
			((MainModule)(ref main)).startSpeed = new MinMaxCurve(1.5f, 3.5f);
			((MainModule)(ref main)).startSize = new MinMaxCurve(0.04f, 0.1f);
			((MainModule)(ref main)).startColor = new MinMaxGradient(new Color(1f, 0.15f, 0f, 1f), new Color(0.8f, 0f, 0f, 0.8f));
			((MainModule)(ref main)).gravityModifier = MinMaxCurve.op_Implicit(-1.8f);
			((MainModule)(ref main)).maxParticles = 130;
			((MainModule)(ref main)).stopAction = (ParticleSystemStopAction)0;
			EmissionModule emission = val2.emission;
			((EmissionModule)(ref emission)).rateOverTime = MinMaxCurve.op_Implicit(22f);
			ShapeModule shape = val2.shape;
			((ShapeModule)(ref shape)).enabled = true;
			((ShapeModule)(ref shape)).shapeType = (ParticleSystemShapeType)10;
			((ShapeModule)(ref shape)).radius = 0.3f;
			((ShapeModule)(ref shape)).radiusThickness = 1f;
			((ShapeModule)(ref shape)).rotation = new Vector3(-90f, 0f, 0f);
			ApplyFade(val2, new Color(1f, 0.1f, 0f), new Color(0.3f, 0f, 0f));
			ParticleSystemRenderer component = ((Component)val2).GetComponent<ParticleSystemRenderer>();
			component.renderMode = (ParticleSystemRenderMode)0;
			((Renderer)component).sharedMaterial = mat;
			val2.Play();
			return val2;
		}

		private static void ApplyFade(ParticleSystem ps, Color from, Color to)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Expected O, but got Unknown
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			ColorOverLifetimeModule colorOverLifetime = ps.colorOverLifetime;
			((ColorOverLifetimeModule)(ref colorOverLifetime)).enabled = true;
			Gradient val = new Gradient();
			val.SetKeys((GradientColorKey[])(object)new GradientColorKey[2]
			{
				new GradientColorKey(from, 0f),
				new GradientColorKey(to, 1f)
			}, (GradientAlphaKey[])(object)new GradientAlphaKey[3]
			{
				new GradientAlphaKey(1f, 0f),
				new GradientAlphaKey(0.4f, 0.6f),
				new GradientAlphaKey(0f, 1f)
			});
			((ColorOverLifetimeModule)(ref colorOverLifetime)).color = MinMaxGradient.op_Implicit(val);
		}
	}
	public class BoneSync : MonoBehaviour
	{
		private struct WeaponClone
		{
			public MeshRenderer OriginalRenderer;

			public GameObject Clone;

			public Transform PlayerHand;

			public Transform ModelHand;
		}

		[CompilerGenerated]
		private sealed class <Setup>d__13 : IEnumerator<object>, IDisposable, IEnumerator
		{
			private int <>1__state;

			private object <>2__current;

			public BoneSync <>4__this;

			private AnimationClip[] <clips>5__1;

			private AnimationClip[] <>s__2;

			private int <>s__3;

			private AnimationClip <clip>5__4;

			private string <lower>5__5;

			private AnimatorControllerParameter[] <>s__6;

			private int <>s__7;

			private AnimatorControllerParameter <param>5__8;

			private SkinnedMeshRenderer[] <>s__9;

			private int <>s__10;

			private SkinnedMeshRenderer <smr>5__11;

			private Transform[] <>s__12;

			private int <>s__13;

			private Transform <t>5__14;

			private Transform[] <>s__15;

			private int <>s__16;

			private Transform <t>5__17;

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

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

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

			[DebuggerHidden]
			void IDisposable.Dispose()
			{
				<clips>5__1 = null;
				<>s__2 = null;
				<clip>5__4 = null;
				<lower>5__5 = null;
				<>s__6 = null;
				<param>5__8 = null;
				<>s__9 = null;
				<smr>5__11 = null;
				<>s__12 = null;
				<t>5__14 = null;
				<>s__15 = null;
				<t>5__17 = null;
				<>1__state = -2;
			}

			private bool MoveNext()
			{
				switch (<>1__state)
				{
				default:
					return false;
				case 0:
					<>1__state = -1;
					<>2__current = null;
					<>1__state = 1;
					return true;
				case 1:
					<>1__state = -1;
					if ((Object)(object)<>4__this._playerRoot == (Object)null || (Object)(object)<>4__this._modelRoot == (Object)null)
					{
						return false;
					}
					<>4__this._playerAnimator = ((Component)<>4__this._playerRoot).GetComponentInChildren<Animator>();
					<>4__this._modelAnimator = ((Component)<>4__this._modelRoot).GetComponentInChildren<Animator>();
					if ((Object)(object)<>4__this._playerAnimator == (Object)null)
					{
						BerserkPlugin.Log.LogError((object)"[BoneSync] Player animator not found!");
						return false;
					}
					if (<>4__this._isDemonMode)
					{
						if ((Object)(object)<>4__this._modelAnimator != (Object)null)
						{
							if ((Object)(object)<>4__this._modelAnimator.runtimeAnimatorController != (Object)null)
							{
								<clips>5__1 = <>4__this._modelAnimator.runtimeAnimatorController.animationClips;
								<>s__2 = <clips>5__1;
								for (<>s__3 = 0; <>s__3 < <>s__2.Length; <>s__3++)
								{
									<clip>5__4 = <>s__2[<>s__3];
									<lower>5__5 = ((Object)<clip>5__4).name.ToLower();
									if (<lower>5__5.Contains("idle") && !<lower>5__5.Contains("combat"))
									{
										<>4__this._demonIdleAnims.Add(((Object)<clip>5__4).name);
									}
									else if (<lower>5__5.Contains("attack") || <lower>5__5.Contains("combat") || <lower>5__5.Contains("slash") || <lower>5__5.Contains("hit"))
									{
										<>4__this._demonAttackAnims.Add(((Object)<clip>5__4).name);
									}
									else if (<lower>5__5.Contains("run") || <lower>5__5.Contains("walk") || <lower>5__5.Contains("move"))
									{
										<>4__this._demonMoveAnims.Add(((Object)<clip>5__4).name);
									}
									<lower>5__5 = null;
									<clip>5__4 = null;
								}
								<>s__2 = null;
								<clips>5__1 = null;
							}
							<>s__6 = <>4__this._modelAnimator.parameters;
							for (<>s__7 = 0; <>s__7 < <>s__6.Length; <>s__7++)
							{
								<param>5__8 = <>s__6[<>s__7];
								<param>5__8 = null;
							}
							<>s__6 = null;
							((Behaviour)<>4__this._modelAnimator).enabled = true;
							<>4__this._modelAnimator.applyRootMotion = false;
							<>4__this._modelAnimator.cullingMode = (AnimatorCullingMode)0;
							<>4__this._modelAnimator.speed = 1f;
							if (!<>4__this.TryPlayAnim("idlecombat00") && !<>4__this.TryPlayAnim("idle00"))
							{
								<>4__this.PlayDemonAnim(<>4__this._demonIdleAnims, "idle");
							}
						}
					}
					else if ((Object)(object)<>4__this._modelAnimator != (Object)null)
					{
						((Behaviour)<>4__this._modelAnimator).enabled = true;
						<>4__this._modelAnimator.runtimeAnimatorController = <>4__this._playerAnimator.runtimeAnimatorController;
						<>4__this._modelAnimator.applyRootMotion = false;
					}
					<>s__9 = ((Component)<>4__this._modelRoot).GetComponentsInChildren<SkinnedMeshRenderer>(true);
					for (<>s__10 = 0; <>s__10 < <>s__9.Length; <>s__10++)
					{
						<smr>5__11 = <>s__9[<>s__10];
						<smr>5__11.updateWhenOffscreen = true;
						<smr>5__11 = null;
					}
					<>s__9 = null;
					<>4__this._playerBones = new Dictionary<string, Transform>(StringComparer.OrdinalIgnoreCase);
					<>s__12 = ((Component)<>4__this._playerRoot).GetComponentsInChildren<Transform>(true);
					for (<>s__13 = 0; <>s__13 < <>s__12.Length; <>s__13++)
					{
						<t>5__14 = <>s__12[<>s__13];
						if (!<>4__this._playerBones.ContainsKey(((Object)<t>5__14).name))
						{
							<>4__this._playerBones[((Object)<t>5__14).name] = <t>5__14;
						}
						<t>5__14 = null;
					}
					<>s__12 = null;
					<>4__this._modelBones = new Dictionary<string, Transform>(StringComparer.OrdinalIgnoreCase);
					<>s__15 = ((Component)<>4__this._modelRoot).GetComponentsInChildren<Transform>(true);
					for (<>s__16 = 0; <>s__16 < <>s__15.Length; <>s__16++)
					{
						<t>5__17 = <>s__15[<>s__16];
						if (!<>4__this._modelBones.ContainsKey(((Object)<t>5__17).name))
						{
							<>4__this._modelBones[((Object)<t>5__17).name] = <t>5__17;
						}
						<t>5__17 = null;
					}
					<>s__15 = null;
					if (!<>4__this._isDemonMode)
					{
						<>4__this.RefreshWeaponClones();
					}
					<>4__this._ready = true;
					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 Transform? _playerRoot;

		private Transform? _modelRoot;

		private Animator? _playerAnimator;

		private Animator? _modelAnimator;

		private bool _ready;

		private bool _isDemonMode;

		private List<WeaponClone> _weaponClones = new List<WeaponClone>();

		private Dictionary<string, Transform> _modelBones = new Dictionary<string, Transform>();

		private Dictionary<string, Transform> _playerBones = new Dictionary<string, Transform>();

		private float _refreshTimer;

		private const float RefreshInterval = 0.3f;

		private List<string> _demonIdleAnims = new List<string>();

		private List<string> _demonAttackAnims = new List<string>();

		private List<string> _demonMoveAnims = new List<string>();

		private int _attackAnimIndex = 0;

		private float _attackAnimEndTime = 0f;

		private bool _isPlayingAttack = false;

		private bool _isCharging = false;

		private bool _wasMoving = false;

		private bool _wasRunning = false;

		private float _animRefreshTimer = 0f;

		public void Init(Transform playerRoot, Transform modelRoot)
		{
			_playerRoot = playerRoot;
			_modelRoot = modelRoot;
			_isDemonMode = (Object)(object)BerserkPlugin.DemonPrefab != (Object)null && ((Object)modelRoot).name.Contains("Demon");
			((MonoBehaviour)this).StartCoroutine(Setup());
		}

		[IteratorStateMachine(typeof(<Setup>d__13))]
		private IEnumerator Setup()
		{
			//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
			return new <Setup>d__13(0)
			{
				<>4__this = this
			};
		}

		private void PlayDemonAnim(List<string> anims, string fallbackPattern)
		{
			if ((Object)(object)_modelAnimator == (Object)null || TryPlayAnim(fallbackPattern + "00") || TryPlayAnim(fallbackPattern + "01") || TryPlayAnim(fallbackPattern))
			{
				return;
			}
			foreach (string anim in anims)
			{
				if (TryPlayAnim(anim))
				{
					break;
				}
			}
		}

		private bool TryPlayAnim(string animName, bool useBlend = true)
		{
			if ((Object)(object)_modelAnimator == (Object)null)
			{
				return false;
			}
			int num = Animator.StringToHash(animName);
			if (_modelAnimator.HasState(0, num))
			{
				if (useBlend)
				{
					_modelAnimator.CrossFadeInFixedTime(num, 0.15f, 0);
				}
				else
				{
					_modelAnimator.Play(num, 0, 0f);
				}
				return true;
			}
			int num2 = Animator.StringToHash("Base Layer." + animName);
			if (_modelAnimator.HasState(0, num2))
			{
				if (useBlend)
				{
					_modelAnimator.CrossFadeInFixedTime(num2, 0.15f, 0);
				}
				else
				{
					_modelAnimator.Play(num2, 0, 0f);
				}
				return true;
			}
			return false;
		}

		public void PlayAttackAnimation(float speedMult = 1f)
		{
			if ((Object)(object)_modelAnimator == (Object)null || !_isDemonMode)
			{
				return;
			}
			_isPlayingAttack = true;
			_attackAnimEndTime = Time.time + 0.7f / speedMult;
			_modelAnimator.speed = speedMult;
			string[] array = new string[3] { "attack00", "attack01", "attack02" };
			_attackAnimIndex = (_attackAnimIndex + 1) % array.Length;
			if (TryPlayAnim(array[_attackAnimIndex]))
			{
				return;
			}
			string[] array2 = array;
			foreach (string animName in array2)
			{
				if (TryPlayAnim(animName))
				{
					break;
				}
			}
		}

		public void PlaySlamAnimation()
		{
			if (!((Object)(object)_modelAnimator == (Object)null) && _isDemonMode)
			{
				_isPlayingAttack = true;
				_attackAnimEndTime = Time.time + 1.2f;
				if (!TryPlayAnim("attack02") && !TryPlayAnim("attack01") && !TryPlayAnim("attack00"))
				{
				}
			}
		}

		public void PlayChargeAnimation()
		{
			if ((Object)(object)_modelAnimator == (Object)null || !_isDemonMode)
			{
				return;
			}
			_isPlayingAttack = true;
			_attackAnimEndTime = Time.time + 30f;
			_isCharging = true;
			int num = Animator.StringToHash("attack01");
			if (_modelAnimator.HasState(0, num))
			{
				_modelAnimator.Play(num, 0, 0f);
				_modelAnimator.speed = 0.1f;
				return;
			}
			num = Animator.StringToHash("attack00");
			if (_modelAnimator.HasState(0, num))
			{
				_modelAnimator.Play(num, 0, 0f);
				_modelAnimator.speed = 0.1f;
			}
		}

		public void StopChargeAnimation()
		{
			_isPlayingAttack = false;
			_attackAnimEndTime = 0f;
			_isCharging = false;
			if ((Object)(object)_modelAnimator != (Object)null)
			{
				_modelAnimator.speed = 1f;
			}
		}

		private string? FindHandNameInParents(Transform t)
		{
			Transform parent = t.parent;
			int num = 0;
			while (num < 10 && (Object)(object)parent != (Object)null)
			{
				string text = ((Object)parent).name.ToLowerInvariant();
				if (text.Contains("righthand") || text.Contains("lefthand"))
				{
					return ((Object)parent).name;
				}
				num++;
				parent = parent.parent;
			}
			return null;
		}

		private void RefreshWeaponClones()
		{
			//IL_01d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01da: Expected O, but got Unknown
			if ((Object)(object)_playerRoot == (Object)null || (Object)(object)_modelRoot == (Object)null)
			{
				return;
			}
			for (int num = _weaponClones.Count - 1; num >= 0; num--)
			{
				WeaponClone weaponClone = _weaponClones[num];
				if ((Object)(object)weaponClone.OriginalRenderer == (Object)null || !((Component)weaponClone.OriginalRenderer).gameObject.activeInHierarchy)
				{
					if ((Object)(object)weaponClone.OriginalRenderer != (Object)null)
					{
						((Renderer)weaponClone.OriginalRenderer).enabled = true;
					}
					if ((Object)(object)weaponClone.Clone != (Object)null)
					{
						Object.Destroy((Object)(object)weaponClone.Clone);
					}
					_weaponClones.RemoveAt(num);
				}
			}
			MeshRenderer[] componentsInChildren = ((Component)_playerRoot).GetComponentsInChildren<MeshRenderer>(true);
			foreach (MeshRenderer val in componentsInChildren)
			{
				if (!((Component)val).gameObject.activeInHierarchy)
				{
					continue;
				}
				bool flag = false;
				foreach (WeaponClone weaponClone2 in _weaponClones)
				{
					if ((Object)(object)weaponClone2.OriginalRenderer == (Object)(object)val)
					{
						flag = true;
						break;
					}
				}
				if (flag)
				{
					continue;
				}
				string text = FindHandNameInParents(((Component)val).transform);
				if (text != null && _modelBones.TryGetValue(text, out Transform value) && _playerBones.TryGetValue(text, out Transform value2))
				{
					GameObject val2 = new GameObject("WeaponClone_" + ((Object)val).name);
					MeshFilter val3 = val2.AddComponent<MeshFilter>();
					MeshRenderer val4 = val2.AddComponent<MeshRenderer>();
					MeshFilter component = ((Component)val).GetComponent<MeshFilter>();
					if ((Object)(object)component != (Object)null)
					{
						val3.sharedMesh = component.sharedMesh;
					}
					((Renderer)val4).sharedMaterials = ((Renderer)val).sharedMaterials;
					_weaponClones.Add(new WeaponClone
					{
						OriginalRenderer = val,
						Clone = val2,
						PlayerHand = value2,
						ModelHand = value
					});
					((Renderer)val).enabled = false;
				}
			}
		}

		private void LateUpdate()
		{
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0269: Unknown result type (might be due to invalid IL or missing references)
			//IL_026e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0270: Unknown result type (might be due to invalid IL or missing references)
			//IL_0272: Unknown result type (might be due to invalid IL or missing references)
			//IL_0274: Unknown result type (might be due to invalid IL or missing references)
			//IL_0277: Unknown result type (might be due to invalid IL or missing references)
			//IL_028d: Expected I4, but got Unknown
			//IL_032c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0331: Unknown result type (might be due to invalid IL or missing references)
			//IL_043b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0447: Unknown result type (might be due to invalid IL or missing references)
			//IL_044c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0451: Unknown result type (might be due to invalid IL or missing references)
			//IL_045a: Unknown result type (might be due to invalid IL or missing references)
			//IL_045f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0464: Unknown result type (might be due to invalid IL or missing references)
			//IL_0466: Unknown result type (might be due to invalid IL or missing references)
			//IL_046b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0474: Unknown result type (might be due to invalid IL or missing references)
			//IL_0479: Unknown result type (might be due to invalid IL or missing references)
			//IL_048a: Unknown result type (might be due to invalid IL or missing references)
			//IL_048f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0494: Unknown result type (might be due to invalid IL or missing references)
			//IL_04a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_04b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_04ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_04bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_04c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_04df: Unknown result type (might be due to invalid IL or missing references)
			//IL_04e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_04e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0509: Unknown result type (might be due to invalid IL or missing references)
			if (!_ready || (Object)(object)_playerRoot == (Object)null || (Object)(object)_modelRoot == (Object)null)
			{
				return;
			}
			_modelRoot.position = _playerRoot.position;
			_modelRoot.rotation = _playerRoot.rotation;
			if (_isDemonMode)
			{
				if (_isPlayingAttack)
				{
					if (!(Time.time > _attackAnimEndTime))
					{
						return;
					}
					_isPlayingAttack = false;
					if ((Object)(object)_modelAnimator != (Object)null)
					{
						_modelAnimator.speed = 1f;
					}
				}
				if (!((Object)(object)_playerAnimator != (Object)null) || _isPlayingAttack)
				{
					return;
				}
				float num = 0f;
				try
				{
					num = _playerAnimator.GetFloat("forward_speed");
				}
				catch
				{
				}
				bool flag = Mathf.Abs(num) > 0.1f;
				bool flag2 = Mathf.Abs(num) > 3f;
				_animRefreshTimer -= Time.deltaTime;
				bool flag3 = _animRefreshTimer <= 0f;
				if (flag3)
				{
					_animRefreshTimer = 2f;
				}
				if (flag2 && (!_wasRunning || flag3))
				{
					TryPlayAnim("run00");
					_wasMoving = true;
					_wasRunning = true;
				}
				else if (flag && !flag2 && (!_wasMoving || flag3))
				{
					TryPlayAnim("run00");
					_wasMoving = true;
					_wasRunning = false;
				}
				else if (!flag && (_wasMoving || flag3))
				{
					if (!TryPlayAnim("idlecombat00"))
					{
						TryPlayAnim("idle00");
					}
					_wasMoving = false;
					_wasRunning = false;
				}
			}
			else
			{
				if ((Object)(object)_playerAnimator == (Object)null || (Object)(object)_modelAnimator == (Object)null)
				{
					return;
				}
				AnimatorControllerParameter[] parameters = _playerAnimator.parameters;
				foreach (AnimatorControllerParameter val in parameters)
				{
					try
					{
						AnimatorControllerParameterType type = val.type;
						AnimatorControllerParameterType val2 = type;
						switch (val2 - 1)
						{
						case 0:
							_modelAnimator.SetFloat(val.nameHash, _playerAnimator.GetFloat(val.nameHash));
							break;
						case 2:
							_modelAnimator.SetInteger(val.nameHash, _playerAnimator.GetInteger(val.nameHash));
							break;
						case 3:
							_modelAnimator.SetBool(val.nameHash, _playerAnimator.GetBool(val.nameHash));
							break;
						case 1:
							break;
						}
					}
					catch
					{
					}
				}
				for (int j = 0; j < _playerAnimator.layerCount; j++)
				{
					AnimatorStateInfo currentAnimatorStateInfo = _playerAnimator.GetCurrentAnimatorStateInfo(j);
					_modelAnimator.Play(((AnimatorStateInfo)(ref currentAnimatorStateInfo)).fullPathHash, j, ((AnimatorStateInfo)(ref currentAnimatorStateInfo)).normalizedTime);
				}
				_modelAnimator.speed = _playerAnimator.speed;
				_refreshTimer -= Time.deltaTime;
				if (_refreshTimer <= 0f)
				{
					_refreshTimer = 0.3f;
					RefreshWeaponClones();
				}
				foreach (WeaponClone weaponClone in _weaponClones)
				{
					if (!((Object)(object)weaponClone.Clone == (Object)null) && !((Object)(object)weaponClone.OriginalRenderer == (Object)null) && !((Object)(object)weaponClone.PlayerHand == (Object)null) && !((Object)(object)weaponClone.ModelHand == (Object)null))
					{
						Vector3 val3 = ((Component)weaponClone.OriginalRenderer).transform.position - weaponClone.PlayerHand.position;
						Vector3 val4 = Quaternion.Inverse(weaponClone.PlayerHand.rotation) * val3;
						Quaternion val5 = Quaternion.Inverse(weaponClone.PlayerHand.rotation) * ((Component)weaponClone.OriginalRenderer).transform.rotation;
						weaponClone.Clone.transform.position = weaponClone.ModelHand.position + weaponClone.ModelHand.rotation * val4;
						weaponClone.Clone.transform.rotation = weaponClone.ModelHand.rotation * val5;
						weaponClone.Clone.transform.localScale = ((Component)weaponClone.OriginalRenderer).transform.lossyScale;
					}
				}
			}
		}

		private void OnDestroy()
		{
			foreach (WeaponClone weaponClone in _weaponClones)
			{
				if ((Object)(object)weaponClone.OriginalRenderer != (Object)null)
				{
					((Renderer)weaponClone.OriginalRenderer).enabled = true;
				}
				if ((Object)(object)weaponClone.Clone != (Object)null)
				{
					Object.Destroy((Object)(object)weaponClone.Clone);
				}
			}
			_weaponClones.Clear();
		}
	}
	public class DemonSync : MonoBehaviour
	{
		private Transform? _playerRoot;

		private Transform? _demonRoot;

		private Animator? _playerAnimator;

		private Animator? _demonAnimator;

		private bool _ready;

		private bool _wasAttacking;

		private int _attackCombo;

		public void Init(Transform playerRoot, Transform demonRoot)
		{
			_playerRoot = playerRoot;
			_demonRoot = demonRoot;
			_playerAnimator = ((Component)playerRoot).GetComponentInChildren<Animator>();
			_demonAnimator = ((Component)demonRoot).GetComponentInChildren<Animator>();
			if ((Object)(object)_demonAnimator != (Object)null)
			{
				((Behaviour)_demonAnimator).enabled = true;
				_demonAnimator.cullingMode = (AnimatorCullingMode)0;
				_demonAnimator.Play("Idle", 0, 0f);
			}
			_ready = true;
		}

		private void LateUpdate()
		{
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			if (_ready && !((Object)(object)_playerRoot == (Object)null) && !((Object)(object)_demonRoot == (Object)null))
			{
				_demonRoot.position = _playerRoot.position;
				_demonRoot.rotation = _playerRoot.rotation;
				if ((Object)(object)_playerAnimator != (Object)null && (Object)(object)_demonAnimator != (Object)null)
				{
					SyncAnimationState();
				}
			}
		}

		private void SyncAnimationState()
		{
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)_playerAnimator == (Object)null || (Object)(object)_demonAnimator == (Object)null)
			{
				return;
			}
			AnimatorStateInfo currentAnimatorStateInfo = _playerAnimator.GetCurrentAnimatorStateInfo(0);
			bool flag = ((AnimatorStateInfo)(ref currentAnimatorStateInfo)).IsTag("attack") || ((AnimatorStateInfo)(ref currentAnimatorStateInfo)).IsName("Attack1") || ((AnimatorStateInfo)(ref currentAnimatorStateInfo)).IsName("Attack2") || ((AnimatorStateInfo)(ref currentAnimatorStateInfo)).IsName("Attack3") || ((AnimatorStateInfo)(ref currentAnimatorStateInfo)).IsName("swing_axe0") || ((AnimatorStateInfo)(ref currentAnimatorStateInfo)).IsName("swing_axe1") || ((AnimatorStateInfo)(ref currentAnimatorStateInfo)).IsName("swing_axe2") || ((AnimatorStateInfo)(ref currentAnimatorStateInfo)).IsName("swing_pickaxe") || ((AnimatorStateInfo)(ref currentAnimatorStateInfo)).IsName("swing_sledge") || ((AnimatorStateInfo)(ref currentAnimatorStateInfo)).IsName("swing_longsword0") || ((AnimatorStateInfo)(ref currentAnimatorStateInfo)).IsName("swing_longsword1") || ((AnimatorStateInfo)(ref currentAnimatorStateInfo)).IsName("swing_longsword2") || ((AnimatorStateInfo)(ref currentAnimatorStateInfo)).IsName("atgeir_attack0") || ((AnimatorStateInfo)(ref currentAnimatorStateInfo)).IsName("atgeir_attack1") || ((AnimatorStateInfo)(ref currentAnimatorStateInfo)).IsName("atgeir_attack2") || ((AnimatorStateInfo)(ref currentAnimatorStateInfo)).IsName("battleaxe_attack0") || ((AnimatorStateInfo)(ref currentAnimatorStateInfo)).IsName("battleaxe_attack1") || ((AnimatorStateInfo)(ref currentAnimatorStateInfo)).IsName("battleaxe_attack2") || ((AnimatorStateInfo)(ref currentAnimatorStateInfo)).IsName("knife_stab0") || ((AnimatorStateInfo)(ref currentAnimatorStateInfo)).IsName("knife_stab1") || ((AnimatorStateInfo)(ref currentAnimatorStateInfo)).IsName("knife_stab2") || ((AnimatorStateInfo)(ref currentAnimatorStateInfo)).IsName("mace_attack0") || ((AnimatorStateInfo)(ref currentAnimatorStateInfo)).IsName("mace_attack1") || ((AnimatorStateInfo)(ref currentAnimatorStateInfo)).IsName("mace_attack2") || ((AnimatorStateInfo)(ref currentAnimatorStateInfo)).IsName("spear_poke") || ((AnimatorStateInfo)(ref currentAnimatorStateInfo)).IsName("sword_attack0") || ((AnimatorStateInfo)(ref currentAnimatorStateInfo)).IsName("sword_attack1") || ((AnimatorStateInfo)(ref currentAnimatorStateInfo)).IsName("sword_attack2") || ((AnimatorStateInfo)(ref currentAnimatorStateInfo)).IsName("unarmed0") || ((AnimatorStateInfo)(ref currentAnimatorStateInfo)).IsName("unarmed1") || ((AnimatorStateInfo)(ref currentAnimatorStateInfo)).IsName("unarmed2");
			float num = 0f;
			try
			{
				num = _playerAnimator.GetFloat("forward_speed");
			}
			catch
			{
			}
			bool flag2 = num > 0.5f;
			bool flag3 = false;
			try
			{
				flag3 = !_playerAnimator.GetBool("inWater") && _playerAnimator.GetBool("jump");
			}
			catch
			{
			}
			if (flag && !_wasAttacking)
			{
				_attackCombo = (_attackCombo + 1) % 3;
				int attackCombo = _attackCombo;
				if (1 == 0)
				{
				}
				string text = attackCombo switch
				{
					0 => "Attack1", 
					1 => "Attack2", 
					_ => "Attack3", 
				};
				if (1 == 0)
				{
				}
				string text2 = text;
				TryPlayAnimation(text2, "Attack", "attack", "Punch", "Slash", "Hit");
			}
			else if (flag3)
			{
				TryPlayAnimation("Jump", "jump", "Jumping");
			}
			else if (flag2 && !flag)
			{
				TryPlayAnimation("Run", "run", "Running", "Walk", "walk");
			}
			else if (!flag && !flag2 && !flag3)
			{
				TryPlayAnimation("Idle", "idle", "Breathing Idle");
			}
			_wasAttacking = flag;
		}

		private void TryPlayAnimation(params string[] names)
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)_demonAnimator == (Object)null)
			{
				return;
			}
			foreach (string text in names)
			{
				if (HasAnimation(text))
				{
					AnimatorStateInfo currentAnimatorStateInfo = _demonAnimator.GetCurrentAnimatorStateInfo(0);
					if (!((AnimatorStateInfo)(ref currentAnimatorStateInfo)).IsName(text))
					{
						_demonAnimator.CrossFade(text, 0.1f, 0);
					}
					break;
				}
			}
		}

		private bool HasAnimation(string name)
		{
			if ((Object)(object)_demonAnimator == (Object)null || (Object)(object)_demonAnimator.runtimeAnimatorController == (Object)null)
			{
				return false;
			}
			AnimationClip[] animationClips = _demonAnimator.runtimeAnimatorController.animationClips;
			foreach (AnimationClip val in animationClips)
			{
				if (((Object)val).name == name || ((Object)val).name.ToLower().Contains(name.ToLower()))
				{
					return true;
				}
			}
			return false;
		}
	}
	[BepInPlugin("com.aurora.berserkir", "Berserkir", "1.1.0")]
	public class BerserkPlugin : BaseUnityPlugin
	{
		[CompilerGenerated]
		private sealed class <LoadAudio>d__21 : IEnumerator<object>, IDisposable, IEnumerator
		{
			private int <>1__state;

			private object <>2__current;

			public string relative;

			public Action<AudioClip> onLoaded;

			private string <full>5__1;

			private UnityWebRequest <req>5__2;

			private AudioClip <clip>5__3;

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

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

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

			[DebuggerHidden]
			void IDisposable.Dispose()
			{
				int num = <>1__state;
				if (num == -3 || num == 1)
				{
					try
					{
					}
					finally
					{
						<>m__Finally1();
					}
				}
				<full>5__1 = null;
				<req>5__2 = null;
				<clip>5__3 = null;
				<>1__state = -2;
			}

			private bool MoveNext()
			{
				//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
				//IL_00cb: Invalid comparison between Unknown and I4
				bool result;
				try
				{
					switch (<>1__state)
					{
					default:
						result = false;
						break;
					case 0:
						<>1__state = -1;
						<full>5__1 = Path.Combine(PluginFolder, relative);
						if (!File.Exists(<full>5__1))
						{
							Log.LogWarning((object)("[Berserkir] Audio not found: " + <full>5__1));
							result = false;
							break;
						}
						<req>5__2 = UnityWebRequestMultimedia.GetAudioClip("file://" + <full>5__1, (AudioType)14);
						<>1__state = -3;
						<>2__current = <req>5__2.SendWebRequest();
						<>1__state = 1;
						result = true;
						break;
					case 1:
						<>1__state = -3;
						if ((int)<req>5__2.result != 1)
						{
							Log.LogError((object)("[Berserkir] Audio load failed: " + <req>5__2.error));
							result = false;
						}
						else
						{
							<clip>5__3 = DownloadHandlerAudioClip.GetContent(<req>5__2);
							((Object)<clip>5__3).name = relative;
							onLoaded(<clip>5__3);
							result = false;
						}
						<>m__Finally1();
						break;
					}
				}
				catch
				{
					//try-fault
					((IDisposable)this).Dispose();
					throw;
				}
				return result;
			}

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

			private void <>m__Finally1()
			{
				<>1__state = -1;
				if (<req>5__2 != null)
				{
					((IDisposable)<req>5__2).Dispose();
				}
			}

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

		public const string PluginGUID = "com.aurora.berserkir";

		public const string PluginName = "Berserkir";

		public const string PluginVersion = "1.1.0";

		public const string PluginAuthor = "Freyja";

		internal static ManualLogSource Log;

		internal static BerserkPlugin Instance;

		internal static string PluginFolder;

		internal static AudioClip? ClipActivate;

		internal static AudioClip? ClipSlam;

		internal static AudioClip? ClipPulse;

		internal static AssetBundle? Bundle;

		internal static GameObject? FirePrefab;

		internal static AssetBundle? DemonBundle;

		internal static GameObject? DemonPrefab;

		private Harmony? _harmony;

		private bool _enabled = true;

		private void Awake()
		{
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Expected O, but got Unknown
			Instance = this;
			Log = ((BaseUnityPlugin)this).Logger;
			PluginFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
			ServerGuard.Init(this);
			if (_enabled)
			{
				_harmony = new Harmony("com.aurora.berserkir");
				_harmony.PatchAll();
				((MonoBehaviour)this).StartCoroutine(LoadAudio("sounds/zerk_activate.ogg", delegate(AudioClip clip)
				{
					ClipActivate = clip;
				}));
				((MonoBehaviour)this).StartCoroutine(LoadAudio("sounds/zerk_slam.ogg", delegate(AudioClip clip)
				{
					ClipSlam = clip;
				}));
				((MonoBehaviour)this).StartCoroutine(LoadAudio("sounds/zerk_pulse.ogg", delegate(AudioClip clip)
				{
					ClipPulse = clip;
				}));
				LoadBundle();
				LoadDemonBundle();
				Log.LogInfo((object)"Berserkir v1.1.0 by Freyja — AWAKENED!");
			}
		}

		private void LoadBundle()
		{
			string text = Path.Combine(PluginFolder, "berserkir");
			if (!File.Exists(text))
			{
				Log.LogWarning((object)("[Berserkir] berserkir bundle not found at: " + text));
				return;
			}
			Bundle = AssetBundle.LoadFromFile(text);
			if ((Object)(object)Bundle == (Object)null)
			{
				Log.LogError((object)"[Berserkir] Bundle load failed.");
				return;
			}
			FirePrefab = Bundle.LoadAsset<GameObject>("BerserkFire");
			if ((Object)(object)FirePrefab != (Object)null)
			{
				Log.LogInfo((object)"[Berserkir] BerserkFire loaded OK");
			}
			else
			{
				Log.LogWarning((object)"[Berserkir] BerserkFire not found in bundle.");
			}
		}

		private void LoadDemonBundle()
		{
			string text = Path.Combine(PluginFolder, "berserkir_demon");
			if (!File.Exists(text))
			{
				Log.LogInfo((object)"[Berserkir] Custom demon bundle not found - will use default skeleton.");
				return;
			}
			DemonBundle = AssetBundle.LoadFromFile(text);
			if ((Object)(object)DemonBundle == (Object)null)
			{
				Log.LogError((object)"[Berserkir] Demon bundle load failed!");
				return;
			}
			DemonPrefab = DemonBundle.LoadAsset<GameObject>("DemonGirl 1 Variant");
			if ((Object)(object)DemonPrefab != (Object)null)
			{
				Log.LogInfo((object)"[Berserkir] Custom DemonGirl loaded OK!");
				return;
			}
			Log.LogWarning((object)"[Berserkir] DemonGirl prefab not found. Assets in bundle:");
			string[] allAssetNames = DemonBundle.GetAllAssetNames();
			foreach (string text2 in allAssetNames)
			{
				Log.LogWarning((object)("  - " + text2));
			}
		}

		public void DisablePlugin()
		{
			_enabled = false;
		}

		private void OnDestroy()
		{
			Harmony? harmony = _harmony;
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
		}

		[IteratorStateMachine(typeof(<LoadAudio>d__21))]
		private static IEnumerator LoadAudio(string relative, Action<AudioClip> onLoaded)
		{
			//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
			return new <LoadAudio>d__21(0)
			{
				relative = relative,
				onLoaded = onLoaded
			};
		}
	}
	[HarmonyPatch]
	public static class BerserkPatches
	{
		[Serializable]
		[CompilerGenerated]
		private sealed class <>c
		{
			public static readonly <>c <>9 = new <>c();

			public static ConsoleEvent <>9__19_0;

			internal void <Terminal_InitTerminal>b__19_0(ConsoleEventArgs args)
			{
				BerserkHUD instance = BerserkHUD.Instance;
				if ((Object)(object)instance == (Object)null)
				{
					Terminal.Log((object)"Berserkir HUD not active.");
					return;
				}
				instance.AdminFill();
				Terminal.Log((object)"<color=#FF3300>Berserkir: all bars filled — RAGE READY!</color>");
			}
		}

		[CompilerGenerated]
		private sealed class <DelayedClawDamage>d__42 : IEnumerator<object>, IDisposable, IEnumerator
		{
			private int <>1__state;

			private object <>2__current;

			public Player player;

			public float delay;

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

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

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

			[DebuggerHidden]
			void IDisposable.Dispose()
			{
				<>1__state = -2;
			}

			private bool MoveNext()
			{
				//IL_0027: Unknown result type (might be due to invalid IL or missing references)
				//IL_0031: Expected O, but got Unknown
				switch (<>1__state)
				{
				default:
					return false;
				case 0:
					<>1__state = -1;
					<>2__current = (object)new WaitForSeconds(delay);
					<>1__state = 1;
					return true;
				case 1:
					<>1__state = -1;
					DealClawDamage(player);
					SE_Berserk.PlaySlam();
					BerserkHUD.TriggerShake(0.4f);
					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();
			}
		}

		[CompilerGenerated]
		private sealed class <DelayedSlamExplosion>d__46 : IEnumerator<object>, IDisposable, IEnumerator
		{
			private int <>1__state;

			private object <>2__current;

			public Player player;

			public float delay;

			public float hpCost;

			private Vector3 <pos>5__1;

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

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

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

			[DebuggerHidden]
			void IDisposable.Dispose()
			{
				<>1__state = -2;
			}

			private bool MoveNext()
			{
				//IL_0027: Unknown result type (might be due to invalid IL or missing references)
				//IL_0031: Expected O, but got Unknown
				//IL_004d: Unknown result type (might be due to invalid IL or missing references)
	

BepInEx/plugins/AuroraEventManager.dll

Decompiled 2 weeks ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using AuroraEventManager.Core;
using AuroraEventManager.Data;
using AuroraEventManager.Events;
using BepInEx;
using BepInEx.Configuration;
using HarmonyLib;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using Microsoft.CodeAnalysis;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyCompany("AuroraEventManager")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("AuroraEventManager")]
[assembly: AssemblyTitle("AuroraEventManager")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace AuroraEventManager
{
	[BepInPlugin("com.peepsquick.auroraeventmanager", "Aurora Event Manager", "2.0.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class AuroraEventManagerPlugin : BaseUnityPlugin
	{
		public const string PluginGUID = "com.peepsquick.auroraeventmanager";

		public const string PluginName = "Aurora Event Manager";

		public const string PluginVersion = "2.0.0";

		private static Harmony _harmony;

		public static ConfigEntry<string> ModPassword;

		private const string ValidPassword = "peaches";

		public static ConfigEntry<int> MinEventDelay;

		public static ConfigEntry<int> MaxEventDelay;

		public static ConfigEntry<int> TriviaAnswerTime;

		public static ConfigEntry<bool> EnableTrivia;

		public static ConfigEntry<int> MonsterEventDuration;

		public static ConfigEntry<bool> EnableTreasureGiant;

		public static ConfigEntry<bool> EnableTreasureSwarm;

		public static ConfigEntry<bool> EnableFavorGiant;

		public static ConfigEntry<bool> EnableFavorSwarm;

		public static ConfigEntry<bool> EnableMeatGiant;

		public static ConfigEntry<bool> EnableMeatSwarm;

		public static ConfigEntry<bool> EnableMosquitoGiant;

		public static ConfigEntry<bool> EnableMosquitoSwarm;

		public static ConfigEntry<bool> EnableBlessingRested;

		public static ConfigEntry<bool> EnableBlessingWeight;

		public static ConfigEntry<bool> EnableBlessingEikthyr;

		public static ConfigEntry<bool> EnableBlessingElder;

		public static ConfigEntry<bool> EnableBlessingBonemass;

		public static ConfigEntry<bool> EnableBlessingModer;

		public static ConfigEntry<bool> EnableBlessingYagluth;

		public static ConfigEntry<bool> EnableBlessingQueen;

		public static ConfigEntry<bool> EnableBlessingFader;

		public static ConfigEntry<bool> EnableBlessingDamage;

		public static ConfigEntry<bool> EnableBlessingDefense;

		public static ConfigEntry<bool> EnableGuessNumber;

		public static ConfigEntry<bool> EnableTeleportHaldor;

		public static ConfigEntry<bool> EnableTeleportHildir;

		public static ConfigEntry<bool> EnableTeleportChokepointA;

		public static ConfigEntry<bool> EnableTeleportChokepointB;

		public static ConfigEntry<bool> EnableTeleportChokepointC;

		public static ConfigEntry<bool> EnableReaction;

		public static ConfigEntry<bool> EnableActivityCrate;

		public static ConfigEntry<int> ActivityCratePayoutDay;

		public static ConfigEntry<int> ActivityCratePayoutHour;

		public static ConfigEntry<bool> EnableHiddenHaldor;

		public static ConfigEntry<bool> EnableDancingRitual;

		public static ConfigEntry<bool> EnablePraiseOdin;

		public static ConfigEntry<bool> EnableFreyjasFury;

		public static ConfigEntry<bool> EnableTyrsWoodenRain;

		public static ConfigEntry<bool> EnablePvPDuel;

		private void Awake()
		{
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Invalid comparison between Unknown and I4
			//IL_05e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_05ea: Expected O, but got Unknown
			ModPassword = ((BaseUnityPlugin)this).Config.Bind<string>("Security", "Password", "ashatasthvbahs", "Server authentication password (only checked on dedicated servers)");
			if ((int)SystemInfo.graphicsDeviceType == 4 && ModPassword.Value != "peaches")
			{
				Debug.LogError((object)"[AuroraEventManager] Invalid server password. Mod disabled.");
				((BaseUnityPlugin)this).Logger.LogError((object)"Aurora Event Manager: Invalid password. Mod will not load on this server.");
				return;
			}
			((BaseUnityPlugin)this).Logger.LogMessage((object)"═══════════════════════════════════════════════════");
			((BaseUnityPlugin)this).Logger.LogMessage((object)"Aurora Event Manager - The most advanced event system in Valheim");
			((BaseUnityPlugin)this).Logger.LogMessage((object)"═══════════════════════════════════════════════════");
			Debug.Log((object)"[AuroraEventManager] ═══════════════════════════════════════════════════");
			Debug.Log((object)"[AuroraEventManager] Aurora Event Manager - The most advanced event system in Valheim");
			Debug.Log((object)"[AuroraEventManager] ═══════════════════════════════════════════════════");
			MinEventDelay = ((BaseUnityPlugin)this).Config.Bind<int>("General", "MinEventDelay", 5, "Minimum minutes between events");
			MaxEventDelay = ((BaseUnityPlugin)this).Config.Bind<int>("General", "MaxEventDelay", 500, "Maximum minutes between events");
			TriviaAnswerTime = ((BaseUnityPlugin)this).Config.Bind<int>("Trivia", "AnswerTime", 60, "Seconds players have to answer trivia questions");
			EnableTrivia = ((BaseUnityPlugin)this).Config.Bind<bool>("Trivia", "EnableTrivia", true, "Enable the Trivia event");
			MonsterEventDuration = ((BaseUnityPlugin)this).Config.Bind<int>("MonsterEvents", "Duration", 60, "Seconds before event monsters despawn");
			EnableTreasureGiant = ((BaseUnityPlugin)this).Config.Bind<bool>("MonsterEvents", "EnableTreasureGiant", true, "Enable the Treasure Giant event");
			EnableTreasureSwarm = ((BaseUnityPlugin)this).Config.Bind<bool>("MonsterEvents", "EnableTreasureSwarm", true, "Enable the Treasure Swarm event");
			EnableFavorGiant = ((BaseUnityPlugin)this).Config.Bind<bool>("MonsterEvents", "EnableFavorGiant", true, "Enable the Favor Giant event");
			EnableFavorSwarm = ((BaseUnityPlugin)this).Config.Bind<bool>("MonsterEvents", "EnableFavorSwarm", true, "Enable the Favor Swarm event");
			EnableMeatGiant = ((BaseUnityPlugin)this).Config.Bind<bool>("MonsterEvents", "EnableMeatGiant", true, "Enable the Meat Giant event");
			EnableMeatSwarm = ((BaseUnityPlugin)this).Config.Bind<bool>("MonsterEvents", "EnableMeatSwarm", true, "Enable the Meat Swarm event");
			EnableMosquitoGiant = ((BaseUnityPlugin)this).Config.Bind<bool>("MonsterEvents", "EnableMosquitoGiant", true, "Enable the Giant Mosquito event");
			EnableMosquitoSwarm = ((BaseUnityPlugin)this).Config.Bind<bool>("MonsterEvents", "EnableMosquitoSwarm", true, "Enable the Mosquito Swarm event");
			EnableBlessingRested = ((BaseUnityPlugin)this).Config.Bind<bool>("BlessingEvents", "EnableBlessingRested", true, "Enable the Rested blessing (30 min)");
			EnableBlessingWeight = ((BaseUnityPlugin)this).Config.Bind<bool>("BlessingEvents", "EnableBlessingWeight", true, "Enable the Weight/Carry blessing (FreyjaWeightHour)");
			EnableBlessingEikthyr = ((BaseUnityPlugin)this).Config.Bind<bool>("BlessingEvents", "EnableBlessingEikthyr", true, "Enable the Eikthyr guardian power blessing (20 min)");
			EnableBlessingElder = ((BaseUnityPlugin)this).Config.Bind<bool>("BlessingEvents", "EnableBlessingElder", true, "Enable the Elder guardian power blessing (20 min)");
			EnableBlessingBonemass = ((BaseUnityPlugin)this).Config.Bind<bool>("BlessingEvents", "EnableBlessingBonemass", true, "Enable the Bonemass guardian power blessing (20 min)");
			EnableBlessingModer = ((BaseUnityPlugin)this).Config.Bind<bool>("BlessingEvents", "EnableBlessingModer", true, "Enable the Moder guardian power blessing (20 min)");
			EnableBlessingYagluth = ((BaseUnityPlugin)this).Config.Bind<bool>("BlessingEvents", "EnableBlessingYagluth", true, "Enable the Yagluth guardian power blessing (20 min)");
			EnableBlessingQueen = ((BaseUnityPlugin)this).Config.Bind<bool>("BlessingEvents", "EnableBlessingQueen", true, "Enable the Queen guardian power blessing (20 min)");
			EnableBlessingFader = ((BaseUnityPlugin)this).Config.Bind<bool>("BlessingEvents", "EnableBlessingFader", true, "Enable the Fader guardian power blessing (20 min)");
			EnableBlessingDamage = ((BaseUnityPlugin)this).Config.Bind<bool>("BlessingEvents", "EnableBlessingDamage", true, "Enable the Damage blessing (+50% damage, 30 min)");
			EnableBlessingDefense = ((BaseUnityPlugin)this).Config.Bind<bool>("BlessingEvents", "EnableBlessingDefense", true, "Enable the Defense blessing (+50% defense, 30 min)");
			EnableGuessNumber = ((BaseUnityPlugin)this).Config.Bind<bool>("MiniGameEvents", "EnableGuessNumber", true, "Enable the Guess the Number event");
			EnableTeleportHaldor = ((BaseUnityPlugin)this).Config.Bind<bool>("MiniGameEvents", "EnableTeleportHaldor", true, "Enable free teleport to Haldor");
			EnableTeleportHildir = ((BaseUnityPlugin)this).Config.Bind<bool>("MiniGameEvents", "EnableTeleportHildir", true, "Enable free teleport to Hildir");
			EnableTeleportChokepointA = ((BaseUnityPlugin)this).Config.Bind<bool>("MiniGameEvents", "EnableTeleportChokepointA", true, "Enable free teleport to Chokepoint A");
			EnableTeleportChokepointB = ((BaseUnityPlugin)this).Config.Bind<bool>("MiniGameEvents", "EnableTeleportChokepointB", true, "Enable free teleport to Chokepoint B");
			EnableTeleportChokepointC = ((BaseUnityPlugin)this).Config.Bind<bool>("MiniGameEvents", "EnableTeleportChokepointC", true, "Enable free teleport to Chokepoint C");
			EnableReaction = ((BaseUnityPlugin)this).Config.Bind<bool>("MiniGameEvents", "EnableReaction", true, "Enable the Reaction (type word first) event - requires 3+ players");
			EnableActivityCrate = ((BaseUnityPlugin)this).Config.Bind<bool>("ActivityCrate", "EnableActivityCrate", true, "Enable the Activity Crate system for weekly rewards");
			ActivityCratePayoutDay = ((BaseUnityPlugin)this).Config.Bind<int>("ActivityCrate", "PayoutDay", 0, "Day of week for payout (0=Sunday, 1=Monday, etc)");
			ActivityCratePayoutHour = ((BaseUnityPlugin)this).Config.Bind<int>("ActivityCrate", "PayoutHour", 18, "Hour for payout (24-hour format, 18 = 6PM)");
			EnableHiddenHaldor = ((BaseUnityPlugin)this).Config.Bind<bool>("SpecialEvents", "EnableHiddenHaldor", true, "Enable Hidden Haldor event - find the trader for treasure!");
			EnableDancingRitual = ((BaseUnityPlugin)this).Config.Bind<bool>("SpecialEvents", "EnableDancingRitual", true, "Enable Dancing Ritual event - dance together to clear weather!");
			EnablePraiseOdin = ((BaseUnityPlugin)this).Config.Bind<bool>("SpecialEvents", "EnablePraiseOdin", true, "Enable Praise Odin event - shout praise to smelt ores instantly!");
			EnableFreyjasFury = ((BaseUnityPlugin)this).Config.Bind<bool>("SpecialEvents", "EnableFreyjasFury", true, "Enable Freyja's Fury event - kills monsters around a player!");
			EnableTyrsWoodenRain = ((BaseUnityPlugin)this).Config.Bind<bool>("SpecialEvents", "EnableTyrsWoodenRain", true, "Enable Tyr's Wooden Rain event - rains random wood on a player!");
			EnablePvPDuel = ((BaseUnityPlugin)this).Config.Bind<bool>("SpecialEvents", "EnablePvPDuel", true, "Enable PvP Duel event - players can shout 'pvp?' to initiate duels!");
			CreatureManager.OnVanillaCreaturesAvailable += RegisterEventCreatures;
			_harmony = new Harmony("com.peepsquick.auroraeventmanager");
			_harmony.PatchAll();
			Debug.Log((object)"[AuroraEventManager] Harmony PatchAll completed");
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Aurora Event Manager 2.0.0 loaded!");
		}

		private void OnDestroy()
		{
			Harmony harmony = _harmony;
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
			CreatureManager.OnVanillaCreaturesAvailable -= RegisterEventCreatures;
			EventManagerCore.Shutdown();
		}

		private void RegisterEventCreatures()
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Expected O, but got Unknown
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Expected O, but got Unknown
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Expected O, but got Unknown
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Expected O, but got Unknown
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ea: Expected O, but got Unknown
			//IL_0103: Unknown result type (might be due to invalid IL or missing references)
			//IL_010a: Expected O, but got Unknown
			//IL_0126: Unknown result type (might be due to invalid IL or missing references)
			//IL_0154: Unknown result type (might be due to invalid IL or missing references)
			//IL_015b: Expected O, but got Unknown
			//IL_0174: Unknown result type (might be due to invalid IL or missing references)
			//IL_017b: Expected O, but got Unknown
			//IL_0197: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cc: Expected O, but got Unknown
			//IL_01e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ec: Expected O, but got Unknown
			//IL_0208: Unknown result type (might be due to invalid IL or missing references)
			//IL_0236: Unknown result type (might be due to invalid IL or missing references)
			//IL_023d: Expected O, but got Unknown
			//IL_0256: Unknown result type (might be due to invalid IL or missing references)
			//IL_025d: Expected O, but got Unknown
			//IL_0279: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ae: Expected O, but got Unknown
			//IL_02c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ce: Expected O, but got Unknown
			//IL_02ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_0318: Unknown result type (might be due to invalid IL or missing references)
			//IL_031f: Expected O, but got Unknown
			//IL_0338: Unknown result type (might be due to invalid IL or missing references)
			//IL_033f: Expected O, but got Unknown
			//IL_035b: Unknown result type (might be due to invalid IL or missing references)
			Debug.Log((object)"[AuroraEventManager] Registering custom event creatures via Jötunn CreatureManager...");
			try
			{
				CreatureConfig val = new CreatureConfig();
				val.Name = "Treasure Giant";
				CustomCreature val2 = new CustomCreature("AEM_TreasureGiant", "Goblin", val);
				ConfigureEventCreature(val2.Prefab, 5f, new Color(1f, 0.84f, 0f), 3000f, "Treasure Giant", isBoss: true);
				CreatureManager.Instance.AddCreature(val2);
				Debug.Log((object)"[AuroraEventManager] Registered: AEM_TreasureGiant");
				CreatureConfig val3 = new CreatureConfig();
				val3.Name = "Treasure Goblin";
				CustomCreature val4 = new CustomCreature("AEM_TreasureGoblin", "Goblin", val3);
				ConfigureEventCreature(val4.Prefab, 1f, new Color(1f, 0.84f, 0f), 50f, "Treasure Goblin", isBoss: false);
				CreatureManager.Instance.AddCreature(val4);
				Debug.Log((object)"[AuroraEventManager] Registered: AEM_TreasureGoblin");
				CreatureConfig val5 = new CreatureConfig();
				val5.Name = "Favor Dragon";
				CustomCreature val6 = new CustomCreature("AEM_FavorDragon", "Hatchling", val5);
				ConfigureEventCreature(val6.Prefab, 3f, new Color(0.3f, 0.5f, 1f), 5000f, "Favor Dragon", isBoss: true);
				CreatureManager.Instance.AddCreature(val6);
				Debug.Log((object)"[AuroraEventManager] Registered: AEM_FavorDragon");
				CreatureConfig val7 = new CreatureConfig();
				val7.Name = "Favor Drake";
				CustomCreature val8 = new CustomCreature("AEM_FavorDrake", "Hatchling", val7);
				ConfigureEventCreature(val8.Prefab, 1f, new Color(0.3f, 0.5f, 1f), 30f, "Favor Drake", isBoss: false);
				CreatureManager.Instance.AddCreature(val8);
				Debug.Log((object)"[AuroraEventManager] Registered: AEM_FavorDrake");
				CreatureConfig val9 = new CreatureConfig();
				val9.Name = "Meat Giant";
				CustomCreature val10 = new CustomCreature("AEM_MeatGiant", "Boar", val9);
				ConfigureEventCreature(val10.Prefab, 5f, new Color(1f, 0.4f, 0.5f), 2000f, "Meat Giant", isBoss: true);
				CreatureManager.Instance.AddCreature(val10);
				Debug.Log((object)"[AuroraEventManager] Registered: AEM_MeatGiant");
				CreatureConfig val11 = new CreatureConfig();
				val11.Name = "Meat Boar";
				CustomCreature val12 = new CustomCreature("AEM_MeatBoar", "Boar", val11);
				ConfigureEventCreature(val12.Prefab, 1f, new Color(1f, 0.4f, 0.5f), 30f, "Meat Boar", isBoss: false);
				CreatureManager.Instance.AddCreature(val12);
				Debug.Log((object)"[AuroraEventManager] Registered: AEM_MeatBoar");
				CreatureConfig val13 = new CreatureConfig();
				val13.Name = "Giant Mosquito";
				CustomCreature val14 = new CustomCreature("AEM_GiantMosquito", "Deathsquito", val13);
				ConfigureEventCreature(val14.Prefab, 5f, new Color(1f, 0.2f, 0.2f), 1500f, "Giant Mosquito", isBoss: true);
				CreatureManager.Instance.AddCreature(val14);
				Debug.Log((object)"[AuroraEventManager] Registered: AEM_GiantMosquito");
				CreatureConfig val15 = new CreatureConfig();
				val15.Name = "Void Mosquito";
				CustomCreature val16 = new CustomCreature("AEM_VoidMosquito", "Deathsquito", val15);
				ConfigureEventCreature(val16.Prefab, 1f, new Color(1f, 0.2f, 0.2f), 20f, "Void Mosquito", isBoss: false);
				CreatureManager.Instance.AddCreature(val16);
				Debug.Log((object)"[AuroraEventManager] Registered: AEM_VoidMosquito");
				Debug.Log((object)"[AuroraEventManager] Successfully registered 8 custom event creatures via Jötunn!");
			}
			catch (Exception ex)
			{
				Debug.LogError((object)("[AuroraEventManager] Failed to register creatures: " + ex.Message + "\n" + ex.StackTrace));
			}
			CreatureManager.OnVanillaCreaturesAvailable -= RegisterEventCreatures;
		}

		private void ConfigureEventCreature(GameObject prefab, float scale, Color glowColor, float health, string displayName, bool isBoss)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Expected O, but got Unknown
			//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0114: Unknown result type (might be due to invalid IL or missing references)
			prefab.transform.localScale = Vector3.one * scale;
			Character component = prefab.GetComponent<Character>();
			Humanoid component2 = prefab.GetComponent<Humanoid>();
			MonsterAI component3 = prefab.GetComponent<MonsterAI>();
			if ((Object)(object)component != (Object)null)
			{
				component.m_name = displayName;
				component.m_health = health;
				component.m_boss = isBoss;
			}
			CharacterDrop component4 = prefab.GetComponent<CharacterDrop>();
			if ((Object)(object)component4 != (Object)null)
			{
				component4.m_drops = new List<Drop>();
			}
			if ((Object)(object)component3 != (Object)null)
			{
				component3.m_attackPlayerObjects = false;
				component3.m_alertRange = 30f;
			}
			Transform val = prefab.transform.Find("AEM_Glow");
			if ((Object)(object)val == (Object)null)
			{
				GameObject val2 = new GameObject("AEM_Glow");
				val2.transform.SetParent(prefab.transform);
				val2.transform.localPosition = Vector3.up * (isBoss ? 3f : 1f);
				Light val3 = val2.AddComponent<Light>();
				val3.type = (LightType)2;
				val3.color = glowColor;
				val3.intensity = (isBoss ? 3f : 2f);
				val3.range = (isBoss ? 25f : 15f);
				val2.AddComponent<PulsingLight>();
			}
		}
	}
	public class PulsingLight : MonoBehaviour
	{
		private Light _light;

		private float _baseIntensity;

		private float _pulseSpeed = 2f;

		private float _pulseAmount = 0.5f;

		private void Start()
		{
			_light = ((Component)this).GetComponent<Light>();
			if ((Object)(object)_light != (Object)null)
			{
				_baseIntensity = _light.intensity;
			}
		}

		private void Update()
		{
			if ((Object)(object)_light != (Object)null)
			{
				float num = Mathf.Sin(Time.time * _pulseSpeed) * _pulseAmount + 1f;
				_light.intensity = _baseIntensity * num;
			}
		}
	}
	[HarmonyPatch(typeof(ZNetScene), "Awake")]
	public static class ZNetScene_Awake_Patch
	{
		[HarmonyPostfix]
		public static void Postfix(ZNetScene __instance)
		{
			if ((Object)(object)ZNet.instance != (Object)null && ZNet.instance.IsServer())
			{
				Debug.Log((object)"[AuroraEventManager] Initializing Aurora Event Manager on server...");
				EventManagerCore.Initialize();
				ActivityTracker.Initialize();
				ActivityCrateManager.Initialize();
				NewPlayerTracker.Initialize();
				PvPDuelEvent.Initialize();
			}
		}
	}
	[HarmonyPatch(typeof(Game), "Start")]
	public static class Game_Start_Patch
	{
		[HarmonyPostfix]
		public static void Postfix()
		{
			Debug.Log((object)"[AuroraEventManager] Registering client RPC handlers...");
			RewardHandler.RegisterClientRPCs();
			ActivityCrateUI.Initialize();
			ActivityCrateManager.Initialize();
		}
	}
	[HarmonyPatch(typeof(Hud), "Awake")]
	public static class Hud_Awake_Patch
	{
		[HarmonyPostfix]
		public static void Postfix(Hud __instance)
		{
			Debug.Log((object)"[AuroraEventManager] HUD initialized, setting up crate button...");
			ActivityCrateUI.Instance?.SetupCrateButton();
		}
	}
	[HarmonyPatch(typeof(ZRoutedRpc), "HandleRoutedRPC")]
	public static class ZRoutedRpc_HandleRoutedRPC_Patch
	{
	}
	[HarmonyPatch(typeof(Chat), "SendText")]
	public static class Chat_SendText_Patch
	{
		[HarmonyPostfix]
		public static void Postfix(Chat __instance, Type type, string text)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0003: Invalid comparison between Unknown and I4
			if ((int)type == 2)
			{
				string text2 = text?.Trim()?.ToLower();
				if (text2 == "pvp?" && ZRoutedRpc.instance != null && (Object)(object)Player.m_localPlayer != (Object)null)
				{
					string playerName = Player.m_localPlayer.GetPlayerName();
					long uID = ZNet.GetUID();
					ZRoutedRpc.instance.InvokeRoutedRPC(ZRoutedRpc.Everybody, "AEM_DuelRequest", new object[1] { playerName });
				}
			}
		}
	}
	[HarmonyPatch(typeof(Chat), "OnNewChatMessage")]
	public static class Chat_OnNewChatMessage_Patch
	{
		[HarmonyPostfix]
		public static void Postfix(GameObject go, long senderID, Vector3 pos, Type type, UserInfo sender, string text)
		{
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Invalid comparison between Unknown and I4
			if (!((Object)(object)ZNet.instance == (Object)null) && ZNet.instance.IsServer() && sender != null && !(sender.Name == "Event Manager") && (Object)(object)EventManagerCore.Instance != (Object)null && (int)type == 2)
			{
				EventManagerCore.Instance.OnPlayerChat(sender.Name, text);
			}
		}
	}
	[HarmonyPatch(typeof(Character), "Damage")]
	public static class Character_Damage_Patch
	{
		private static Random _random = new Random();

		[HarmonyPrefix]
		public static void Prefix(Character __instance, HitData hit)
		{
			if ((Object)(object)__instance == (Object)null || hit == null)
			{
				return;
			}
			Character attacker = hit.GetAttacker();
			if (!((Object)(object)attacker != (Object)null))
			{
				return;
			}
			string name = ((Object)((Component)attacker).gameObject).name;
			if (!IsEventMonster(((Component)attacker).gameObject))
			{
				return;
			}
			Debug.Log((object)("[AuroraEventManager] Event monster " + name + " attacking " + ((Object)__instance).name));
			Player val = (Player)(object)((__instance is Player) ? __instance : null);
			if (val != null)
			{
				ZNetView component = ((Component)attacker).GetComponent<ZNetView>();
				if (((component != null) ? component.GetZDO() : null) != null)
				{
					string @string = component.GetZDO().GetString("AEM_StatusEffect", "");
					if (!string.IsNullOrEmpty(@string))
					{
						ApplyStatusEffect(val, @string);
						Debug.Log((object)("[AuroraEventManager] Applied " + @string + " debuff to " + val.GetPlayerName()));
					}
					else
					{
						Debug.Log((object)("[AuroraEventManager] No status effect configured for " + name));
					}
				}
			}
			hit.m_damage.m_damage = 0f;
			hit.m_damage.m_blunt = 0f;
			hit.m_damage.m_slash = 0f;
			hit.m_damage.m_pierce = 0f;
			hit.m_damage.m_chop = 0f;
			hit.m_damage.m_pickaxe = 0f;
			hit.m_damage.m_fire = 0f;
			hit.m_damage.m_frost = 0f;
			hit.m_damage.m_lightning = 0f;
			hit.m_damage.m_poison = 0f;
			hit.m_damage.m_spirit = 0f;
			hit.m_pushForce = 0f;
			hit.m_backstabBonus = 0f;
			hit.m_staggerMultiplier = 0f;
		}

		[HarmonyPostfix]
		public static void Postfix(Character __instance, HitData hit)
		{
			//IL_01b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fd: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)__instance == (Object)null || hit == null)
			{
				return;
			}
			string name = ((Object)((Component)__instance).gameObject).name;
			if (!IsEventMonster(((Component)__instance).gameObject))
			{
				return;
			}
			Debug.Log((object)("[AuroraEventManager] Event monster " + name + " was hit!"));
			ZNetView component = ((Component)__instance).GetComponent<ZNetView>();
			if ((Object)(object)component == (Object)null)
			{
				Debug.LogWarning((object)("[AuroraEventManager] No ZNetView on " + name));
				return;
			}
			if (component.GetZDO() == null)
			{
				Debug.LogWarning((object)("[AuroraEventManager] No ZDO on " + name));
				return;
			}
			if (!component.IsOwner())
			{
				Debug.Log((object)("[AuroraEventManager] Not owner of " + name + ", skipping loot"));
				return;
			}
			ZDO zDO = component.GetZDO();
			float @float = zDO.GetFloat("AEM_LastHitTime", 0f);
			if (Time.time - @float < 0.5f)
			{
				Debug.Log((object)("[AuroraEventManager] Cooldown active for " + name));
				return;
			}
			zDO.Set("AEM_LastHitTime", Time.time);
			string @string = zDO.GetString("AEM_ItemPool", "");
			if (string.IsNullOrEmpty(@string))
			{
				Debug.LogWarning((object)("[AuroraEventManager] No item pool in ZDO for " + name));
				return;
			}
			int @int = zDO.GetInt("AEM_HitDropMin", 1);
			int int2 = zDO.GetInt("AEM_HitDropMax", 3);
			string[] array = @string.Split(new char[1] { ',' });
			string text = array[_random.Next(array.Length)];
			int num = _random.Next(@int, int2 + 1);
			Vector3 val = ((hit.m_point != Vector3.zero) ? hit.m_point : ((Component)__instance).transform.position);
			Debug.Log((object)$"[AuroraEventManager] HIT LOOT: {num}x {text} at {val}");
			RewardHandler.DropItemsAtPosition(text, num, val);
		}

		private static bool IsEventMonster(GameObject go)
		{
			if ((Object)(object)go == (Object)null)
			{
				return false;
			}
			string name = ((Object)go).name;
			if (name.Contains("AEM_"))
			{
				return true;
			}
			ZNetView component = go.GetComponent<ZNetView>();
			if (((component != null) ? component.GetZDO() : null) != null && component.GetZDO().GetBool("AEM_IsEventMonster", false))
			{
				return true;
			}
			return false;
		}

		private static void ApplyStatusEffect(Player player, string effectName)
		{
			if ((Object)(object)player == (Object)null || string.IsNullOrEmpty(effectName))
			{
				return;
			}
			try
			{
				SEMan sEMan = ((Character)player).GetSEMan();
				if (sEMan == null)
				{
					return;
				}
				if (ObjectDB.instance?.m_StatusEffects != null)
				{
					foreach (StatusEffect statusEffect in ObjectDB.instance.m_StatusEffects)
					{
						if ((Object)(object)statusEffect != (Object)null && ((Object)statusEffect).name == effectName)
						{
							StatusEffect val = sEMan.AddStatusEffect(statusEffect.NameHash(), true, 0, 0f);
							if ((Object)(object)val != (Object)null)
							{
								val.m_ttl = 1.5f;
							}
							return;
						}
					}
				}
				Debug.LogWarning((object)("[AuroraEventManager] Status effect '" + effectName + "' not found in ObjectDB"));
			}
			catch (Exception ex)
			{
				Debug.LogWarning((object)("[AuroraEventManager] Failed to apply status effect: " + ex.Message));
			}
		}
	}
	[HarmonyPatch(typeof(Character), "OnDeath")]
	public static class Character_OnDeath_Patch
	{
		private static Random _random = new Random();

		[HarmonyPrefix]
		public static void Prefix(Character __instance)
		{
			//IL_0197: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)__instance == (Object)null)
			{
				return;
			}
			string name = ((Object)((Component)__instance).gameObject).name;
			if (!name.Contains("AEM_"))
			{
				return;
			}
			Debug.Log((object)("[AuroraEventManager] Event monster dying: " + name));
			ZNetView component = ((Component)__instance).GetComponent<ZNetView>();
			if ((Object)(object)component == (Object)null || component.GetZDO() == null)
			{
				Debug.LogWarning((object)("[AuroraEventManager] No ZNetView/ZDO on dying " + name));
				return;
			}
			if (!component.IsOwner())
			{
				Debug.Log((object)("[AuroraEventManager] Not owner of dying " + name + ", skipping death loot"));
				return;
			}
			ZDO zDO = component.GetZDO();
			if (zDO.GetBool("AEM_DeathLootDropped", false))
			{
				Debug.Log((object)("[AuroraEventManager] Death loot already dropped for " + name));
				return;
			}
			zDO.Set("AEM_DeathLootDropped", true);
			string @string = zDO.GetString("AEM_ItemPool", "");
			if (string.IsNullOrEmpty(@string))
			{
				Debug.LogWarning((object)("[AuroraEventManager] No item pool in ZDO for dying " + name));
				return;
			}
			int @int = zDO.GetInt("AEM_KillDropMin", 10);
			int int2 = zDO.GetInt("AEM_KillDropMax", 20);
			string[] array = @string.Split(new char[1] { ',' });
			string text = array[_random.Next(array.Length)];
			int num = _random.Next(@int, int2 + 1);
			Debug.Log((object)$"[AuroraEventManager] DEATH LOOT: {num}x {text}");
			RewardHandler.DropItemsAtPosition(text, num, ((Component)__instance).transform.position);
		}
	}
	[HarmonyPatch(typeof(CharacterDrop), "OnDeath")]
	public static class CharacterDrop_OnDeath_Patch
	{
		[HarmonyPrefix]
		public static bool Prefix(CharacterDrop __instance)
		{
			string name = ((Object)((Component)__instance).gameObject).name;
			if (name.Contains("AEM_"))
			{
				Debug.Log((object)("[AuroraEventManager] Blocking vanilla loot for " + name));
				return false;
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(Character), "Start")]
	public static class Character_Start_Patch
	{
		[HarmonyPostfix]
		public static void Postfix(Character __instance)
		{
			if (!((Object)(object)__instance == (Object)null))
			{
				string name = ((Object)((Component)__instance).gameObject).name;
				if (name.Contains("AEM_"))
				{
					ZNetView component = ((Component)__instance).GetComponent<ZNetView>();
					bool flag = ((component != null) ? component.GetZDO() : null) != null;
					bool flag2 = component != null && component.IsOwner();
					Debug.Log((object)$"[AuroraEventManager] Event monster started: {name}, hasZDO={flag}, isOwner={flag2}");
				}
			}
		}
	}
	[HarmonyPatch(typeof(Trader), "Interact")]
	public static class Trader_Interact_Patch
	{
		[HarmonyPrefix]
		public static bool Prefix(Trader __instance, Humanoid character, bool hold, bool alt, ref bool __result)
		{
			if ((Object)(object)__instance == (Object)null || hold)
			{
				return true;
			}
			ZNetView component = ((Component)__instance).GetComponent<ZNetView>();
			if ((Object)(object)component == (Object)null || component.GetZDO() == null)
			{
				return true;
			}
			if (!component.GetZDO().GetBool("AEM_HiddenHaldor", false))
			{
				return true;
			}
			Player val = (Player)(object)((character is Player) ? character : null);
			if ((Object)(object)val != (Object)null)
			{
				string playerName = val.GetPlayerName();
				RewardHandler.NotifyHaldorFound(playerName);
				((Character)val).Message((MessageType)2, "You found Hidden Haldor!", 0, (Sprite)null);
				__result = true;
				return false;
			}
			return true;
		}
	}
}
namespace AuroraEventManager.Events
{
	public enum MonsterEventType
	{
		Giant,
		Swarm
	}
	public abstract class BaseMonsterEvent : BaseEvent
	{
		protected float _eventStartTime;

		protected float _eventDuration;

		protected string _eventInstanceId;

		protected int _spawnCount;

		protected List<ZDOID> _spawnedZDOIDs = new List<ZDOID>();

		protected abstract string CustomPrefabName { get; }

		protected abstract MonsterEventType EventType { get; }

		protected abstract string[] ItemPool { get; }

		protected abstract string StatusEffectOnHit { get; }

		protected abstract bool MonsterFlees { get; }

		protected virtual int HitDropMin => (EventType != 0) ? 1 : 2;

		protected virtual int HitDropMax => (EventType == MonsterEventType.Giant) ? 5 : 2;

		protected virtual int KillDropMin => (EventType == MonsterEventType.Giant) ? 30 : 8;

		protected virtual int KillDropMax => (EventType == MonsterEventType.Giant) ? 50 : 12;

		protected virtual int SwarmCount => 5;

		public BaseMonsterEvent()
		{
			Config = new EventConfig
			{
				Enabled = true,
				Weight = 10,
				MinPlayers = 1,
				IsGlobalEvent = false,
				RequiresTargetPlayer = true
			};
		}

		public override bool CanTrigger()
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			if (!base.CanTrigger())
			{
				return false;
			}
			if (base.TargetPosition != Vector3.zero && !BaseEvent.IsValidMonsterEventLocation(base.TargetPosition))
			{
				Debug.Log((object)("[AuroraEventManager] " + EventName + " cannot trigger - player too close to workbench"));
				return false;
			}
			return true;
		}

		protected override void OnEventStart()
		{
			_eventDuration = AuroraEventManagerPlugin.MonsterEventDuration.Value;
			_eventStartTime = Time.time;
			_eventInstanceId = $"{EventId}_{DateTime.UtcNow.Ticks}";
			_spawnCount = 0;
			_spawnedZDOIDs.Clear();
			string text = ((EventType == MonsterEventType.Giant) ? "GIANT" : "SWARM");
			string message = "<color=#00FFFF>[" + text + "]</color> A <color=#FFA500>" + EventName + "</color> has appeared near <color=#FFFF00>" + base.TargetPlayerName + "</color>! Hunt it down for loot!";
			SendEventShout(message);
			SpawnMonsters();
			Debug.Log((object)$"[AuroraEventManager] {EventName} started with {_spawnCount} monsters");
		}

		protected override void OnEventStop()
		{
			DespawnAllMonsters();
			EventManagerCore.Instance?.OnEventEnded(this);
			Debug.Log((object)("[AuroraEventManager] " + EventName + " ended"));
		}

		protected override void OnEventUpdate()
		{
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			if (Time.time - _eventStartTime < 3f)
			{
				return;
			}
			if (Time.time - _eventStartTime >= _eventDuration)
			{
				SendEventShout("<color=#FFA500>[EVENT]</color> The " + EventName + " has escaped! Time ran out.");
				Stop();
				return;
			}
			int num = 0;
			foreach (ZDOID spawnedZDOID in _spawnedZDOIDs)
			{
				if (spawnedZDOID != ZDOID.None)
				{
					ZDOMan instance = ZDOMan.instance;
					ZDO val = ((instance != null) ? instance.GetZDO(spawnedZDOID) : null);
					if (val != null)
					{
						num++;
					}
				}
			}
			if (num == 0 && _spawnCount > 0)
			{
				SendEventShout("<color=#00FF00>[EVENT]</color> All " + EventName + " creatures have been defeated!");
				Stop();
			}
		}

		protected virtual void SpawnMonsters()
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			int num = ((EventType == MonsterEventType.Giant) ? 1 : SwarmCount);
			for (int i = 0; i < num; i++)
			{
				Vector3 spawnPosition = GetSpawnPosition(i);
				ZDOID val = SpawnEventMonster(spawnPosition);
				if (val != ZDOID.None)
				{
					_spawnedZDOIDs.Add(val);
					_spawnCount++;
				}
			}
			Debug.Log((object)$"[AuroraEventManager] Spawned {_spawnCount}x {CustomPrefabName}");
		}

		protected Vector3 GetSpawnPosition(int index)
		{
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			if (index == 0)
			{
				return base.TargetPosition;
			}
			float num = 360f / (float)SwarmCount * (float)index * ((float)Math.PI / 180f);
			float num2 = 3f;
			return base.TargetPosition + new Vector3(Mathf.Cos(num) * num2, 0f, Mathf.Sin(num) * num2);
		}

		protected virtual ZDOID SpawnEventMonster(Vector3 position)
		{
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0092: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_0243: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0225: Unknown result type (might be due to invalid IL or missing references)
			//IL_022b: Unknown result type (might be due to invalid IL or missing references)
			//IL_023d: Unknown result type (might be due to invalid IL or missing references)
			//IL_023f: Unknown result type (might be due to invalid IL or missing references)
			ZNetScene instance = ZNetScene.instance;
			GameObject val = ((instance != null) ? instance.GetPrefab(CustomPrefabName) : null);
			if ((Object)(object)val == (Object)null)
			{
				Debug.LogError((object)("[AuroraEventManager] Custom prefab not found: " + CustomPrefabName));
				return ZDOID.None;
			}
			Quaternion val2 = Quaternion.Euler(0f, (float)Random.Range(0, 360), 0f);
			GameObject val3 = Object.Instantiate<GameObject>(val, position, val2);
			if ((Object)(object)val3 == (Object)null)
			{
				Debug.LogError((object)("[AuroraEventManager] Failed to instantiate: " + CustomPrefabName));
				return ZDOID.None;
			}
			ZNetView component = val3.GetComponent<ZNetView>();
			if ((Object)(object)component == (Object)null || component.GetZDO() == null)
			{
				Debug.LogError((object)"[AuroraEventManager] No ZNetView/ZDO on spawned monster");
				Object.Destroy((Object)(object)val3);
				return ZDOID.None;
			}
			ZDOID uid = component.GetZDO().m_uid;
			ZDO zDO = component.GetZDO();
			zDO.Set("AEM_IsEventMonster", true);
			zDO.Set("AEM_EventId", _eventInstanceId);
			zDO.Set("AEM_ItemPool", string.Join(",", ItemPool));
			zDO.Set("AEM_HitDropMin", HitDropMin);
			zDO.Set("AEM_HitDropMax", HitDropMax);
			zDO.Set("AEM_KillDropMin", KillDropMin);
			zDO.Set("AEM_KillDropMax", KillDropMax);
			zDO.Set("AEM_StatusEffect", StatusEffectOnHit ?? "");
			if (MonsterFlees)
			{
				MonsterAI component2 = val3.GetComponent<MonsterAI>();
				Character component3 = val3.GetComponent<Character>();
				if ((Object)(object)component2 != (Object)null)
				{
					component2.m_fleeIfLowHealth = 1f;
					component2.m_fleeIfNotAlerted = true;
					((BaseAI)component2).m_avoidFire = true;
				}
				if ((Object)(object)component3 != (Object)null)
				{
					component3.m_speed *= 1.1f;
					component3.m_runSpeed *= 1.1f;
				}
			}
			Debug.Log((object)$"[AuroraEventManager] Spawned {CustomPrefabName} at {position}, ZDOID: {uid}");
			return uid;
		}

		protected void DespawnAllMonsters()
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_011a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
			int num = 0;
			foreach (ZDOID spawnedZDOID in _spawnedZDOIDs)
			{
				if (spawnedZDOID == ZDOID.None)
				{
					continue;
				}
				ZDOMan instance = ZDOMan.instance;
				ZDO val = ((instance != null) ? instance.GetZDO(spawnedZDOID) : null);
				if (val == null)
				{
					Debug.Log((object)$"[AuroraEventManager] ZDO {spawnedZDOID} already gone");
					continue;
				}
				ZNetScene instance2 = ZNetScene.instance;
				ZNetView val2 = ((instance2 != null) ? instance2.FindInstance(val) : null);
				if ((Object)(object)val2 != (Object)null && (Object)(object)((Component)val2).gameObject != (Object)null)
				{
					try
					{
						val2.ClaimOwnership();
						ZNetScene.instance.Destroy(((Component)val2).gameObject);
						num++;
						Debug.Log((object)$"[AuroraEventManager] Destroyed via local instance: {spawnedZDOID}");
					}
					catch (Exception ex)
					{
						Debug.LogWarning((object)("[AuroraEventManager] Local destroy failed: " + ex.Message));
						goto IL_00f8;
					}
					continue;
				}
				goto IL_00f8;
				IL_00f8:
				try
				{
					val.SetOwner(ZDOMan.GetSessionID());
					ZDOMan.instance.DestroyZDO(val);
					num++;
					Debug.Log((object)$"[AuroraEventManager] Destroyed via ZDO: {spawnedZDOID}");
				}
				catch (Exception ex2)
				{
					Debug.LogWarning((object)("[AuroraEventManager] ZDO destroy failed: " + ex2.Message));
				}
			}
			_spawnedZDOIDs.Clear();
			Debug.Log((object)$"[AuroraEventManager] Despawned {num} monsters total");
		}
	}
	public abstract class BaseBlessingEvent : BaseEvent
	{
		private struct PlayerInfo
		{
			public string Name;

			public long UID;
		}

		private const float ALL_PLAYERS_CHANCE = 0.1f;

		protected abstract string BlessingName { get; }

		protected abstract string StatusEffectName { get; }

		protected abstract float Duration { get; }

		protected abstract Color AnnouncementColor { get; }

		public BaseBlessingEvent()
		{
			Config = new EventConfig
			{
				Enabled = true,
				Weight = 5,
				MinPlayers = 1,
				IsGlobalEvent = true,
				RequiresTargetPlayer = false
			};
		}

		protected override void OnEventStart()
		{
			if (Random.value < 0.1f)
			{
				ApplyToAllPlayers();
			}
			else
			{
				ApplyToRandomPlayer();
			}
			Stop();
		}

		protected override void OnEventStop()
		{
			EventManagerCore.Instance?.OnEventEnded(this);
		}

		protected override void OnEventUpdate()
		{
		}

		private void ApplyToAllPlayers()
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			string text = ColorUtility.ToHtmlStringRGB(AnnouncementColor);
			string message = "<color=#FFD700>[BLESSING]</color> <color=#" + text + ">" + BlessingName + "</color> has been bestowed upon <color=#00FF00>ALL VIKINGS</color>!";
			SendEventShout(message);
			ApplyBlessingViaRPC(toAll: true, 0L);
			Debug.Log((object)("[AuroraEventManager] Applied " + BlessingName + " to ALL players via RPC"));
		}

		private void ApplyToRandomPlayer()
		{
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			List<PlayerInfo> allPlayerInfos = GetAllPlayerInfos();
			if (allPlayerInfos.Count != 0)
			{
				PlayerInfo playerInfo = allPlayerInfos[Random.Range(0, allPlayerInfos.Count)];
				string name = playerInfo.Name;
				long uID = playerInfo.UID;
				string text = ColorUtility.ToHtmlStringRGB(AnnouncementColor);
				string message = "<color=#FFD700>[BLESSING]</color> <color=#" + text + ">" + BlessingName + "</color> has been bestowed upon <color=#FFFF00>" + name + "</color>!";
				SendEventShout(message);
				ApplyBlessingViaRPC(toAll: false, uID);
				Debug.Log((object)$"[AuroraEventManager] Applied {BlessingName} to {name} (UID: {uID}) via RPC");
			}
		}

		protected virtual void ApplyBlessingViaRPC(bool toAll, long playerUID)
		{
			if (string.IsNullOrEmpty(StatusEffectName))
			{
				Debug.LogWarning((object)("[AuroraEventManager] No status effect name for " + BlessingName));
			}
			else if (toAll)
			{
				RewardHandler.SendBlessingToAllPlayers(StatusEffectName, Duration);
			}
			else
			{
				RewardHandler.SendBlessingToPlayer(playerUID, StatusEffectName, Duration);
			}
		}

		private List<PlayerInfo> GetAllPlayerInfos()
		{
			List<PlayerInfo> list = new List<PlayerInfo>();
			if ((Object)(object)ZNet.instance == (Object)null)
			{
				return list;
			}
			List<ZNetPeer> peers = ZNet.instance.GetPeers();
			foreach (ZNetPeer item in peers)
			{
				if (item != null && item.m_uid != 0)
				{
					list.Add(new PlayerInfo
					{
						Name = item.m_playerName,
						UID = item.m_uid
					});
				}
			}
			return list;
		}
	}
	public class RestedBlessingEvent : BaseBlessingEvent
	{
		public override string EventId => "blessing_rested";

		public override string EventName => "Blessing of Rest";

		protected override string BlessingName => "Blessing of Rest";

		protected override string StatusEffectName => "Rested";

		protected override float Duration => 1800f;

		protected override Color AnnouncementColor => new Color(0.5f, 0.8f, 1f);

		public override bool CanStart()
		{
			return base.CanStart() && AuroraEventManagerPlugin.EnableBlessingRested.Value;
		}
	}
	public class WeightBlessingEvent : BaseBlessingEvent
	{
		public override string EventId => "blessing_weight";

		public override string EventName => "Blessing of Strength";

		protected override string BlessingName => "Blessing of Strength";

		protected override string StatusEffectName => "FreyjaWeightHour";

		protected override float Duration => 0f;

		protected override Color AnnouncementColor => new Color(1f, 0.6f, 0.2f);

		public override bool CanStart()
		{
			return base.CanStart() && AuroraEventManagerPlugin.EnableBlessingWeight.Value;
		}
	}
	public class EikthyrBlessingEvent : BaseBlessingEvent
	{
		public override string EventId => "blessing_eikthyr";

		public override string EventName => "Power of Eikthyr";

		protected override string BlessingName => "Power of Eikthyr";

		protected override string StatusEffectName => "GP_Eikthyr";

		protected override float Duration => 1200f;

		protected override Color AnnouncementColor => new Color(0.8f, 0.9f, 1f);

		public override bool CanStart()
		{
			return base.CanStart() && AuroraEventManagerPlugin.EnableBlessingEikthyr.Value;
		}
	}
	public class ElderBlessingEvent : BaseBlessingEvent
	{
		public override string EventId => "blessing_elder";

		public override string EventName => "Power of The Elder";

		protected override string BlessingName => "Power of The Elder";

		protected override string StatusEffectName => "GP_TheElder";

		protected override float Duration => 1200f;

		protected override Color AnnouncementColor => new Color(0.2f, 0.8f, 0.2f);

		public override bool CanStart()
		{
			return base.CanStart() && AuroraEventManagerPlugin.EnableBlessingElder.Value;
		}
	}
	public class BonemassBlessingEvent : BaseBlessingEvent
	{
		public override string EventId => "blessing_bonemass";

		public override string EventName => "Power of Bonemass";

		protected override string BlessingName => "Power of Bonemass";

		protected override string StatusEffectName => "GP_Bonemass";

		protected override float Duration => 1200f;

		protected override Color AnnouncementColor => new Color(0.6f, 0.8f, 0.2f);

		public override bool CanStart()
		{
			return base.CanStart() && AuroraEventManagerPlugin.EnableBlessingBonemass.Value;
		}
	}
	public class ModerBlessingEvent : BaseBlessingEvent
	{
		public override string EventId => "blessing_moder";

		public override string EventName => "Power of Moder";

		protected override string BlessingName => "Power of Moder";

		protected override string StatusEffectName => "GP_Moder";

		protected override float Duration => 1200f;

		protected override Color AnnouncementColor => new Color(0.7f, 0.9f, 1f);

		public override bool CanStart()
		{
			return base.CanStart() && AuroraEventManagerPlugin.EnableBlessingModer.Value;
		}
	}
	public class YagluthBlessingEvent : BaseBlessingEvent
	{
		public override string EventId => "blessing_yagluth";

		public override string EventName => "Power of Yagluth";

		protected override string BlessingName => "Power of Yagluth";

		protected override string StatusEffectName => "GP_Yagluth";

		protected override float Duration => 1200f;

		protected override Color AnnouncementColor => new Color(1f, 0.4f, 0.1f);

		public override bool CanStart()
		{
			return base.CanStart() && AuroraEventManagerPlugin.EnableBlessingYagluth.Value;
		}
	}
	public class QueenBlessingEvent : BaseBlessingEvent
	{
		public override string EventId => "blessing_queen";

		public override string EventName => "Power of The Queen";

		protected override string BlessingName => "Power of The Queen";

		protected override string StatusEffectName => "GP_Queen";

		protected override float Duration => 1200f;

		protected override Color AnnouncementColor => new Color(0.8f, 0.2f, 0.8f);

		public override bool CanStart()
		{
			return base.CanStart() && AuroraEventManagerPlugin.EnableBlessingQueen.Value;
		}
	}
	public class FaderBlessingEvent : BaseBlessingEvent
	{
		public override string EventId => "blessing_fader";

		public override string EventName => "Power of The Fader";

		protected override string BlessingName => "Power of The Fader";

		protected override string StatusEffectName => "GP_Fader";

		protected override float Duration => 1200f;

		protected override Color AnnouncementColor => new Color(0.9f, 0.9f, 0.5f);

		public override bool CanStart()
		{
			return base.CanStart() && AuroraEventManagerPlugin.EnableBlessingFader.Value;
		}
	}
	public class DamageBlessingEvent : BaseBlessingEvent
	{
		public override string EventId => "blessing_damage";

		public override string EventName => "Blessing of Fury";

		protected override string BlessingName => "Blessing of Fury (+50% Damage)";

		protected override string StatusEffectName => "CorpseRun";

		protected override float Duration => 1800f;

		protected override Color AnnouncementColor => new Color(1f, 0.2f, 0.2f);

		public override bool CanStart()
		{
			return base.CanStart() && AuroraEventManagerPlugin.EnableBlessingDamage.Value;
		}
	}
	public class DefenseBlessingEvent : BaseBlessingEvent
	{
		public override string EventId => "blessing_defense";

		public override string EventName => "Blessing of Iron Skin";

		protected override string BlessingName => "Blessing of Iron Skin (+50% Defense)";

		protected override string StatusEffectName => "GP_Bonemass";

		protected override float Duration => 1800f;

		protected override Color AnnouncementColor => new Color(0.6f, 0.6f, 0.7f);

		public override bool CanStart()
		{
			return base.CanStart() && AuroraEventManagerPlugin.EnableBlessingDefense.Value;
		}
	}
	public class GuessNumberEvent : BaseEvent
	{
		private int _targetNumber;

		private float _eventStartTime;

		private float _eventDuration = 60f;

		private Dictionary<string, int> _playerGuesses = new Dictionary<string, int>();

		private bool _jackpotWon = false;

		public override string EventId => "guess_number";

		public override string EventName => "Guess the Number";

		public GuessNumberEvent()
		{
			Config = new EventConfig
			{
				Enabled = true,
				Weight = 8,
				MinPlayers = 1,
				IsGlobalEvent = true,
				RequiresTargetPlayer = false
			};
		}

		public override bool CanStart()
		{
			return base.CanStart() && AuroraEventManagerPlugin.EnableGuessNumber.Value;
		}

		protected override void OnEventStart()
		{
			_targetNumber = Random.Range(1, 101);
			_eventStartTime = Time.time;
			_playerGuesses.Clear();
			_jackpotWon = false;
			string message = "<color=#FFD700>[GUESS THE NUMBER]</color> I'm thinking of a number between <color=#00FF00>1</color> and <color=#00FF00>100</color>! <color=#FFFF00>SHOUT your guess!</color> You have <color=#FF6600>60 seconds</color>! Jackpot for exact match: <color=#FFD700>5000 Coins + GoldIngot + 5 ReturnScroll!</color>";
			SendEventShout(message);
			Debug.Log((object)$"[AuroraEventManager] Guess the Number started. Target: {_targetNumber}");
		}

		protected override void OnEventStop()
		{
			if (!_jackpotWon)
			{
				DetermineWinner();
			}
			EventManagerCore.Instance?.OnEventEnded(this);
		}

		protected override void OnEventUpdate()
		{
			if (!_jackpotWon && Time.time - _eventStartTime >= _eventDuration)
			{
				SendEventShout($"<color=#FFD700>[GUESS THE NUMBER]</color> Time's up! The number was <color=#00FF00>{_targetNumber}</color>!");
				Stop();
			}
		}

		public override void OnPlayerChat(string playerName, string message)
		{
			if (_jackpotWon)
			{
				return;
			}
			string s = message.Trim();
			if (int.TryParse(s, out var result) && result >= 1 && result <= 100)
			{
				_playerGuesses[playerName] = result;
				Debug.Log((object)$"[AuroraEventManager] {playerName} guessed {result}");
				if (result == _targetNumber)
				{
					_jackpotWon = true;
					string message2 = $"<color=#FFD700>★★★ JACKPOT! ★★★</color> <color=#FFFF00>{playerName}</color> guessed the exact number <color=#00FF00>{_targetNumber}</color>! " + "Reward: <color=#FFD700>5000 Coins, 1 GoldIngot, 5 ReturnScroll!</color>";
					SendEventShout(message2);
					RewardHandler.GiveItemToPlayer(playerName, "Coins", 5000);
					RewardHandler.GiveItemToPlayer(playerName, "GoldIngot", 1);
					RewardHandler.GiveItemToPlayer(playerName, "ReturnScroll", 5);
					Stop();
				}
			}
		}

		private void DetermineWinner()
		{
			if (_playerGuesses.Count == 0)
			{
				SendEventShout("<color=#FFD700>[GUESS THE NUMBER]</color> No valid guesses were made!");
				return;
			}
			string text = null;
			int num = int.MaxValue;
			foreach (KeyValuePair<string, int> playerGuess in _playerGuesses)
			{
				int num2 = Math.Abs(playerGuess.Value - _targetNumber);
				if (num2 < num && num2 <= 5)
				{
					num = num2;
					text = playerGuess.Key;
				}
			}
			if (text == null)
			{
				SendEventShout($"<color=#FFD700>[GUESS THE NUMBER]</color> No one was close enough! The number was <color=#00FF00>{_targetNumber}</color>.");
				return;
			}
			int num3 = 0;
			switch (num)
			{
			case 1:
				num3 = 2000;
				break;
			case 2:
				num3 = 1000;
				break;
			case 3:
				num3 = 500;
				break;
			case 4:
				num3 = 200;
				break;
			case 5:
				num3 = 100;
				break;
			}
			if (num3 > 0)
			{
				int num4 = _playerGuesses[text];
				string message = $"<color=#FFD700>[GUESS THE NUMBER]</color> <color=#FFFF00>{text}</color> was closest with <color=#00FF00>{num4}</color>! " + $"(Number was {_targetNumber}, off by {num}) Reward: <color=#FFD700>{num3} Coins!</color>";
				SendEventShout(message);
				RewardHandler.GiveItemToPlayer(text, "Coins", num3);
			}
		}
	}
	public abstract class BaseTeleportEvent : BaseEvent
	{
		private float _eventStartTime;

		private float _eventDuration = 15f;

		private HashSet<string> _teleportedPlayers = new HashSet<string>();

		protected abstract string LocationName { get; }

		protected abstract Vector3 TeleportPosition { get; }

		public BaseTeleportEvent()
		{
			Config = new EventConfig
			{
				Enabled = true,
				Weight = 5,
				MinPlayers = 1,
				IsGlobalEvent = true,
				RequiresTargetPlayer = false
			};
		}

		protected override void OnEventStart()
		{
			_eventStartTime = Time.time;
			_teleportedPlayers.Clear();
			string message = "<color=#00FFFF>[FREE TELEPORT]</color> Free teleport to <color=#FFD700>" + LocationName + "</color>! <color=#FFFF00>SHOUT 'GO' to travel!</color> You have <color=#FF6600>15 seconds!</color>";
			SendEventShout(message);
			Debug.Log((object)("[AuroraEventManager] Free Teleport to " + LocationName + " started"));
		}

		protected override void OnEventStop()
		{
			SendEventShout($"<color=#00FFFF>[FREE TELEPORT]</color> Teleport to {LocationName} has ended. {_teleportedPlayers.Count} vikings traveled!");
			EventManagerCore.Instance?.OnEventEnded(this);
		}

		protected override void OnEventUpdate()
		{
			if (Time.time - _eventStartTime >= _eventDuration)
			{
				Stop();
			}
		}

		public override void OnPlayerChat(string playerName, string message)
		{
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			string text = message.Trim().ToUpperInvariant();
			if (text == "GO" && !_teleportedPlayers.Contains(playerName))
			{
				_teleportedPlayers.Add(playerName);
				TeleportPlayer(playerName, TeleportPosition);
				string message2 = "<color=#00FFFF>[TELEPORT]</color> <color=#FFFF00>" + playerName + "</color> has teleported to <color=#FFD700>" + LocationName + "</color>!";
				SendEventShout(message2);
				Debug.Log((object)$"[AuroraEventManager] Teleported {playerName} to {LocationName} at {TeleportPosition}");
			}
		}

		private void TeleportPlayer(string playerName, Vector3 position)
		{
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)ZNet.instance == (Object)null)
			{
				return;
			}
			foreach (ZNetPeer peer in ZNet.instance.GetPeers())
			{
				if (peer != null && peer.m_playerName == playerName)
				{
					RewardHandler.TeleportPlayer(peer.m_uid, position);
					break;
				}
			}
		}
	}
	public class TeleportHaldorEvent : BaseTeleportEvent
	{
		public override string EventId => "teleport_haldor";

		public override string EventName => "Free Teleport to Haldor";

		protected override string LocationName => "Haldor the Trader";

		protected override Vector3 TeleportPosition => new Vector3(1613f, 40f, -3722f);

		public override bool CanStart()
		{
			return base.CanStart() && AuroraEventManagerPlugin.EnableTeleportHaldor.Value;
		}
	}
	public class TeleportHildirEvent : BaseTeleportEvent
	{
		public override string EventId => "teleport_hildir";

		public override string EventName => "Free Teleport to Hildir";

		protected override string LocationName => "Hildir the Merchant";

		protected override Vector3 TeleportPosition => new Vector3(512f, 50f, 1472f);

		public override bool CanStart()
		{
			return base.CanStart() && AuroraEventManagerPlugin.EnableTeleportHildir.Value;
		}
	}
	public class TeleportChokepointAEvent : BaseTeleportEvent
	{
		public override string EventId => "teleport_chokepoint_a";

		public override string EventName => "Free Teleport to Chokepoint A";

		protected override string LocationName => "Chokepoint A";

		protected override Vector3 TeleportPosition => new Vector3(389f, 35f, -389f);

		public override bool CanStart()
		{
			return base.CanStart() && AuroraEventManagerPlugin.EnableTeleportChokepointA.Value;
		}
	}
	public class TeleportChokepointBEvent : BaseTeleportEvent
	{
		public override string EventId => "teleport_chokepoint_b";

		public override string EventName => "Free Teleport to Chokepoint B";

		protected override string LocationName => "Chokepoint B";

		protected override Vector3 TeleportPosition => new Vector3(356f, 31f, 5099f);

		public override bool CanStart()
		{
			return base.CanStart() && AuroraEventManagerPlugin.EnableTeleportChokepointB.Value;
		}
	}
	public class TeleportChokepointCEvent : BaseTeleportEvent
	{
		public override string EventId => "teleport_chokepoint_c";

		public override string EventName => "Free Teleport to Chokepoint C";

		protected override string LocationName => "Chokepoint C";

		protected override Vector3 TeleportPosition => new Vector3(389f, 46f, -3644f);

		public override bool CanStart()
		{
			return base.CanStart() && AuroraEventManagerPlugin.EnableTeleportChokepointC.Value;
		}
	}
	public class ReactionEvent : BaseEvent
	{
		private string _targetWord;

		private float _eventStartTime;

		private float _eventDuration = 30f;

		private bool _winnerFound = false;

		private static readonly string[] ReactionWords = new string[120]
		{
			"ENCYCLOPEDIA", "REVOLUTIONARY", "EXTRAORDINARY", "CONGRATULATIONS", "COMMUNICATION", "RESPONSIBILITY", "UNDERSTANDING", "INTERNATIONAL", "ENVIRONMENTAL", "REPRESENTATIVE",
			"UNFORTUNATELY", "ADMINISTRATION", "ARCHAEOLOGICAL", "AUTOBIOGRAPHY", "BIODEGRADABLE", "CARDIOVASCULAR", "CHOREOGRAPHER", "CIRCUMFERENCE", "CLAUSTROPHOBIC", "COMMERCIALIZE",
			"COMPREHENSIVE", "CONCENTRATION", "CONFEDERATION", "CONSCIOUSNESS", "CONSTELLATION", "CONTAMINATION", "CONTROVERSIAL", "CRYSTALLIZATION", "DEFORESTATION", "DEMONSTRATION",
			"DETERMINATION", "DISAPPOINTMENT", "DISCRIMINATORY", "ELECTROMAGNETIC", "ENCAPSULATION", "ENTERTAINMENT", "ESTABLISHMENT", "EXPERIMENTATION", "EXTRAVAGANZA", "FORTIFICATION",
			"GENERALIZATION", "HALLUCINATION", "HORTICULTURIST", "HOSPITALIZATION", "HYPERVENTILATE", "IDENTIFICATION", "IMMOBILIZATION", "IMPLEMENTATION", "IMPROVISATION", "INCARCERATION",
			"INDESCRIBABLE", "INDISPENSABLE", "INFRASTRUCTURE", "INITIALIZATION", "INSTRUMENTATION", "INTERCONTINENTAL", "INTERPRETATION", "INVESTIGATION", "JUSTIFICATION", "KALEIDOSCOPE",
			"KNOWLEDGEABLE", "MATHEMATICIAN", "MEDITERRANEAN", "METEOROLOGICAL", "MICROPROCESSOR", "MISCELLANEOUS", "MISUNDERSTANDING", "MULTIPLICATION", "NATIONALIZATION", "NEIGHBORHOOD",
			"OBJECTIFICATION", "ORGANIZATIONAL", "OUTSTANDINGLY", "OVERCOMPENSATE", "OVERWHELMING", "PARLIAMENTARIAN", "PHARMACEUTICAL", "PHOTOSYNTHESIS", "PHYSIOTHERAPIST", "POLITICIZATION",
			"PREDETERMINATION", "PROFESSIONALISM", "PROPORTIONALLY", "PSYCHOLOGICALLY", "QUADRILATERAL", "QUALIFICATIONS", "QUESTIONNAIRE", "RATIONALIZATION", "RECOMMENDATION", "RECONCILIATION",
			"REHABILITATION", "REIMBURSEMENT", "REINFORCEMENT", "REORGANIZATION", "REPRESENTATIVE", "STANDARDIZATION", "STEREOTYPICAL", "SUBCONSCIOUSLY", "SUPERINTENDENT", "SUPPLEMENTARY",
			"SYNCHRONIZATION", "TECHNOLOGICAL", "TELECOMMUNICATIONS", "TEMPERAMENTAL", "THERMODYNAMICS", "TRANSFORMATION", "TRANSLITERATION", "TRANSPORTATION", "TROUBLESHOOTING", "ULTRAVIOLET",
			"UNCOMFORTABLE", "UNDERESTIMATE", "UNPRECEDENTED", "UNQUESTIONABLE", "VASCULARIZATION", "VISUALIZATION", "VULNERABILITIES", "WEATHERIZATION", "WHISTLEBLOWER", "WORKMANSHIP"
		};

		public override string EventId => "reaction";

		public override string EventName => "Reaction Challenge";

		public ReactionEvent()
		{
			Config = new EventConfig
			{
				Enabled = true,
				Weight = 6,
				MinPlayers = 3,
				IsGlobalEvent = true,
				RequiresTargetPlayer = false
			};
		}

		public override bool CanStart()
		{
			if (!base.CanStart())
			{
				return false;
			}
			if (!AuroraEventManagerPlugin.EnableReaction.Value)
			{
				return false;
			}
			ZNet instance = ZNet.instance;
			int valueOrDefault = ((instance == null) ? null : instance.GetPeers()?.Count).GetValueOrDefault();
			return valueOrDefault >= 3;
		}

		protected override void OnEventStart()
		{
			_targetWord = ReactionWords[Random.Range(0, ReactionWords.Length)];
			_eventStartTime = Time.time;
			_winnerFound = false;
			string message = "<color=#FF00FF>[REACTION]</color> <color=#FFFF00>TYPE THIS WORD FIRST:</color> <color=#00FF00>" + _targetWord + "</color> <color=#AAAAAA>(SHOUT it!)</color>";
			SendEventShout(message);
			Debug.Log((object)("[AuroraEventManager] Reaction challenge started. Word: " + _targetWord));
		}

		protected override void OnEventStop()
		{
			if (!_winnerFound)
			{
				SendEventShout("<color=#FF00FF>[REACTION]</color> Time's up! No one typed <color=#00FF00>" + _targetWord + "</color> correctly!");
			}
			EventManagerCore.Instance?.OnEventEnded(this);
		}

		protected override void OnEventUpdate()
		{
			if (!_winnerFound && Time.time - _eventStartTime >= _eventDuration)
			{
				Stop();
			}
		}

		public override void OnPlayerChat(string playerName, string message)
		{
			if (!_winnerFound)
			{
				string text = message.Trim().ToUpperInvariant();
				if (text == _targetWord)
				{
					_winnerFound = true;
					float num = Time.time - _eventStartTime;
					string message2 = "<color=#FF00FF>[REACTION]</color> <color=#FFD700>★ WINNER ★</color> " + $"<color=#FFFF00>{playerName}</color> typed it first in <color=#00FF00>{num:F2}s</color>!";
					SendEventShout(message2);
					GiveReactionReward(playerName);
					Stop();
				}
			}
		}

		private void GiveReactionReward(string playerName)
		{
			string[] array = new string[6] { "Coins", "Amber", "AmberPearl", "Ruby", "SilverNecklace", "GoldNecklace" };
			int[] array2 = new int[6] { 500, 5, 3, 2, 1, 1 };
			int num = Random.Range(0, array.Length);
			string text = array[num];
			int num2 = array2[num];
			RewardHandler.GiveItemToPlayer(playerName, text, num2);
			Debug.Log((object)$"[AuroraEventManager] Reaction reward: {num2}x {text} to {playerName}");
		}
	}
	public class TreasureGiantEvent : BaseMonsterEvent
	{
		public override string EventId => "treasure_giant";

		public override string EventName => "Treasure Giant";

		protected override string CustomPrefabName => "AEM_TreasureGiant";

		protected override MonsterEventType EventType => MonsterEventType.Giant;

		protected override string StatusEffectOnHit => "Frost";

		protected override bool MonsterFlees => false;

		protected override string[] ItemPool => new string[5] { "Coins", "Amber", "AmberPearl", "Ruby", "SilverNecklace" };

		protected override int HitDropMin => 5;

		protected override int HitDropMax => 15;

		protected override int KillDropMin => 100;

		protected override int KillDropMax => 200;

		public override bool CanStart()
		{
			return base.CanStart() && AuroraEventManagerPlugin.EnableTreasureGiant.Value;
		}
	}
	public class TreasureSwarmEvent : BaseMonsterEvent
	{
		public override string EventId => "treasure_swarm";

		public override string EventName => "Treasure Swarm";

		protected override string CustomPrefabName => "AEM_TreasureGoblin";

		protected override MonsterEventType EventType => MonsterEventType.Swarm;

		protected override string StatusEffectOnHit => "";

		protected override bool MonsterFlees => true;

		protected override string[] ItemPool => new string[3] { "Coins", "Amber", "AmberPearl" };

		protected override int HitDropMin => 2;

		protected override int HitDropMax => 5;

		protected override int KillDropMin => 20;

		protected override int KillDropMax => 40;

		public override bool CanStart()
		{
			return base.CanStart() && AuroraEventManagerPlugin.EnableTreasureSwarm.Value;
		}
	}
	public class FavorGiantEvent : BaseMonsterEvent
	{
		public override string EventId => "favor_giant";

		public override string EventName => "Favor Dragon";

		protected override string CustomPrefabName => "AEM_FavorDragon";

		protected override MonsterEventType EventType => MonsterEventType.Giant;

		protected override string StatusEffectOnHit => "Frost";

		protected override bool MonsterFlees => false;

		protected override string[] ItemPool => new string[1] { "Favor" };

		protected override int HitDropMin => 1;

		protected override int HitDropMax => 3;

		protected override int KillDropMin => 20;

		protected override int KillDropMax => 40;

		public override bool CanStart()
		{
			return base.CanStart() && AuroraEventManagerPlugin.EnableFavorGiant.Value;
		}
	}
	public class FavorSwarmEvent : BaseMonsterEvent
	{
		public override string EventId => "favor_swarm";

		public override string EventName => "Favor Swarm";

		protected override string CustomPrefabName => "AEM_FavorDrake";

		protected override MonsterEventType EventType => MonsterEventType.Swarm;

		protected override string StatusEffectOnHit => "";

		protected override bool MonsterFlees => true;

		protected override string[] ItemPool => new string[1] { "Favor" };

		protected override int HitDropMin => 1;

		protected override int HitDropMax => 2;

		protected override int KillDropMin => 5;

		protected override int KillDropMax => 10;

		public override bool CanStart()
		{
			return base.CanStart() && AuroraEventManagerPlugin.EnableFavorSwarm.Value;
		}
	}
	public class MeatGiantEvent : BaseMonsterEvent
	{
		public override string EventId => "meat_giant";

		public override string EventName => "Meat Giant";

		protected override string CustomPrefabName => "AEM_MeatGiant";

		protected override MonsterEventType EventType => MonsterEventType.Giant;

		protected override string StatusEffectOnHit => "Burning";

		protected override bool MonsterFlees => false;

		protected override string[] ItemPool => new string[3] { "RawMeat", "CookedMeat", "LeatherScraps" };

		protected override int HitDropMin => 3;

		protected override int HitDropMax => 8;

		protected override int KillDropMin => 50;

		protected override int KillDropMax => 100;

		public override bool CanStart()
		{
			return base.CanStart() && AuroraEventManagerPlugin.EnableMeatGiant.Value;
		}
	}
	public class MeatSwarmEvent : BaseMonsterEvent
	{
		public override string EventId => "meat_swarm";

		public override string EventName => "Meat Swarm";

		protected override string CustomPrefabName => "AEM_MeatBoar";

		protected override MonsterEventType EventType => MonsterEventType.Swarm;

		protected override string StatusEffectOnHit => "";

		protected override bool MonsterFlees => true;

		protected override string[] ItemPool => new string[2] { "RawMeat", "LeatherScraps" };

		protected override int HitDropMin => 1;

		protected override int HitDropMax => 3;

		protected override int KillDropMin => 10;

		protected override int KillDropMax => 20;

		public override bool CanStart()
		{
			return base.CanStart() && AuroraEventManagerPlugin.EnableMeatSwarm.Value;
		}
	}
	public class MosquitoGiantEvent : BaseMonsterEvent
	{
		public override string EventId => "mosquito_giant";

		public override string EventName => "Giant Mosquito";

		protected override string CustomPrefabName => "AEM_GiantMosquito";

		protected override MonsterEventType EventType => MonsterEventType.Giant;

		protected override string StatusEffectOnHit => "Poison";

		protected override bool MonsterFlees => false;

		protected override string[] ItemPool => new string[2] { "VoidShardRed", "VoidShardBlue" };

		protected override int HitDropMin => 2;

		protected override int HitDropMax => 5;

		protected override int KillDropMin => 30;

		protected override int KillDropMax => 60;

		public override bool CanStart()
		{
			return base.CanStart() && AuroraEventManagerPlugin.EnableMosquitoGiant.Value;
		}
	}
	public class MosquitoSwarmEvent : BaseMonsterEvent
	{
		public override string EventId => "mosquito_swarm";

		public override string EventName => "Mosquito Swarm";

		protected override string CustomPrefabName => "AEM_VoidMosquito";

		protected override MonsterEventType EventType => MonsterEventType.Swarm;

		protected override string StatusEffectOnHit => "";

		protected override bool MonsterFlees => true;

		protected override string[] ItemPool => new string[2] { "VoidShardRed", "VoidShardBlue" };

		protected override int HitDropMin => 1;

		protected override int HitDropMax => 2;

		protected override int KillDropMin => 8;

		protected override int KillDropMax => 15;

		public override bool CanStart()
		{
			return base.CanStart() && AuroraEventManagerPlugin.EnableMosquitoSwarm.Value;
		}
	}
	public class PvPDuelEvent : MonoBehaviour
	{
		[CompilerGenerated]
		private sealed class <AnnounceLoserDelayed>d__29 : IEnumerator<object>, IDisposable, IEnumerator
		{
			private int <>1__state;

			private object <>2__current;

			public DuelParticipant loser;

			public PvPDuelEvent <>4__this;

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

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

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

			[DebuggerHidden]
			void IDisposable.Dispose()
			{
				<>1__state = -2;
			}

			private bool MoveNext()
			{
				//IL_0026: Unknown result type (might be due to invalid IL or missing references)
				//IL_0030: Expected O, but got Unknown
				switch (<>1__state)
				{
				default:
					return false;
				case 0:
					<>1__state = -1;
					<>2__current = (object)new WaitForSeconds(10f);
					<>1__state = 1;
					return true;
				case 1:
					<>1__state = -1;
					<>4__this.AnnounceGlobal("<color=#FF6600>[DEFEATED]</color> " + loser.Name + " receives a consolation prize: 1x Revive Potion!");
					<>4__this.GiveItemToPlayer(loser.UID, "RevivePotion", 1);
					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 PvPDuelEvent _instance;

		private static readonly Vector3 ColosseumPosition = new Vector3(-4591f, 105f, -16783f);

		private const float SEARCH_TIMEOUT = 120f;

		private const float PREP_TIME = 30f;

		private const float COOLDOWN_MINUTES = 60f;

		private bool _isSearching = false;

		private bool _isDueling = false;

		private float _searchStartTime;

		private float _prepStartTime;

		private float _lastDuelEndTime = -999999f;

		private bool _announcedCountdown3 = false;

		private bool _announcedCountdown2 = false;

		private bool _announcedCountdown1 = false;

		private bool _duelStarted = false;

		private DuelParticipant _player1;

		private DuelParticipant _player2;

		private static readonly string[] RewardItems = new string[10] { "Coins", "Ruby", "Amber", "AmberPearl", "SilverNecklace", "GoldNecklace", "VoidShardRed", "VoidShardBlue", "Crystal", "Favor" };

		public static PvPDuelEvent Instance => _instance;

		public bool IsActive => _isSearching || _isDueling;

		public static void Initialize()
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Expected O, but got Unknown
			if ((Object)(object)_instance != (Object)null)
			{
				return;
			}
			ZNet instance = ZNet.instance;
			if (instance == null || !instance.IsServer())
			{
				return;
			}
			GameObject val = new GameObject("AEM_PvPDuel");
			Object.DontDestroyOnLoad((Object)(object)val);
			_instance = val.AddComponent<PvPDuelEvent>();
			try
			{
				ZRoutedRpc.instance.Register<string>("AEM_DuelRequest", (Action<long, string>)RPC_OnDuelRequest);
				Debug.Log((object)"[AuroraEventManager] PvP Duel system initialized.");
			}
			catch (Exception ex)
			{
				Debug.Log((object)("[AuroraEventManager] Duel RPC registration: " + ex.Message));
			}
		}

		public static void Shutdown()
		{
			if ((Object)(object)_instance != (Object)null)
			{
				Object.Destroy((Object)(object)((Component)_instance).gameObject);
				_instance = null;
			}
		}

		private static void RPC_OnDuelRequest(long senderUID, string playerName)
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)_instance == (Object)null)
			{
				return;
			}
			Vector3 playerPosition = Vector3.zero;
			ZNet instance = ZNet.instance;
			List<ZNetPeer> list = ((instance != null) ? instance.GetPeers() : null);
			if (list != null)
			{
				foreach (ZNetPeer item in list)
				{
					if (item != null && item.m_uid == senderUID)
					{
						ZDOMan instance2 = ZDOMan.instance;
						ZDO val = ((instance2 != null) ? instance2.GetZDO(item.m_characterID) : null);
						if (val != null)
						{
							playerPosition = val.GetPosition();
						}
						break;
					}
				}
			}
			_instance.OnPlayerRequestDuel(playerName, senderUID, playerPosition);
		}

		private void Update()
		{
			ZNet instance = ZNet.instance;
			if (instance == null || !instance.IsServer())
			{
				return;
			}
			if (_isSearching && !_isDueling && Time.time - _searchStartTime > 120f)
			{
				CancelSearch();
			}
			if (!_isDueling || _player1 == null || _player2 == null)
			{
				return;
			}
			float num = Time.time - _prepStartTime;
			if (num < 30f)
			{
				float num2 = 30f - num;
				if (num2 <= 3f && num2 > 2f && !_announcedCountdown3)
				{
					AnnounceGlobal("<color=#FFFF00>[DUEL]</color> 3...");
					_announcedCountdown3 = true;
				}
				else if (num2 <= 2f && num2 > 1f && !_announcedCountdown2)
				{
					AnnounceGlobal("<color=#FFFF00>[DUEL]</color> 2...");
					_announcedCountdown2 = true;
				}
				else if (num2 <= 1f && !_announcedCountdown1)
				{
					AnnounceGlobal("<color=#FFFF00>[DUEL]</color> 1...");
					_announcedCountdown1 = true;
				}
			}
			else if (!_duelStarted)
			{
				_duelStarted = true;
				AnnounceGlobal("<color=#FF0000>[DUEL BEGINS]</color> " + _player1.Name + " vs " + _player2.Name + " - FIGHT!");
				SetPlayerImmunity(_player1.UID, enable: false);
				SetPlayerImmunity(_player2.UID, enable: false);
			}
			if (_duelStarted)
			{
				CheckForWinner();
			}
		}

		public void OnPlayerRequestDuel(string playerName, long playerUID, Vector3 playerPosition)
		{
			//IL_00ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0100: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			Debug.Log((object)$"[AuroraEventManager] Duel request from {playerName} (UID: {playerUID})");
			float num = Time.time - _lastDuelEndTime;
			float num2 = 3600f - num;
			if (num2 > 0f)
			{
				int num3 = Mathf.CeilToInt(num2 / 60f);
				RewardHandler.SendMessageToPlayer(playerUID, $"<color=#FFFF00>[DUEL]</color> Duel is on cooldown. {num3} minutes remaining.");
			}
			else if (_isDueling)
			{
				RewardHandler.SendMessageToPlayer(playerUID, "<color=#FFFF00>[DUEL]</color> A duel is already in progress!");
			}
			else if (_isSearching)
			{
				if (_player1 != null && _player1.UID == playerUID)
				{
					RewardHandler.SendMessageToPlayer(playerUID, "<color=#FFFF00>[DUEL]</color> You are already looking for an opponent!");
					return;
				}
				_player2 = new DuelParticipant
				{
					Name = playerName,
					UID = playerUID,
					OriginalPosition = playerPosition
				};
				StartDuel();
			}
			else
			{
				_player1 = new DuelParticipant
				{
					Name = playerName,
					UID = playerUID,
					OriginalPosition = playerPosition
				};
				_isSearching = true;
				_searchStartTime = Time.time;
				AnnounceGlobal("<color=#FFFF00>[DUEL]</color> <color=#00FFFF>" + playerName + "</color> is looking for a duel opponent! Shout 'pvp?' to accept!");
				Debug.Log((object)("[AuroraEventManager] Duel search started by " + playerName));
			}
		}

		private void StartDuel()
		{
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b8: Unknown result type (might be due to invalid IL or missing references)
			_isSearching = false;
			_isDueling = true;
			_prepStartTime = Time.time;
			_duelStarted = false;
			_announcedCountdown3 = false;
			_announcedCountdown2 = false;
			_announcedCountdown1 = false;
			AnnounceGlobal("<color=#FF00FF>[DUEL MATCHED]</color> " + _player1.Name + " vs " + _player2.Name + "! Teleporting to Colosseum...");
			TeleportPlayer(_player1.UID, ColosseumPosition);
			TeleportPlayer(_player2.UID, ColosseumPosition + new Vector3(10f, 0f, 0f));
			SetPlayerImmunity(_player1.UID, enable: true);
			SetPlayerImmunity(_player2.UID, enable: true);
			AnnounceGlobal("<color=#FFFF00>[DUEL]</color> 30 second preparation! Immunity active!");
			Debug.Log((object)("[AuroraEventManager] Duel started: " + _player1.Name + " vs " + _player2.Name));
		}

		private void CancelSearch()
		{
			if (_player1 != null)
			{
				AnnounceGlobal("<color=#FFFF00>[DUEL]</color> Search timed out. No opponent found for " + _player1.Name + ".");
			}
			ResetDuel(applyCooldown: false);
			Debug.Log((object)"[AuroraEventManager] Duel search timed out");
		}

		private void CheckForWinner()
		{
			bool flag = IsPlayerDead(_player1.UID);
			bool flag2 = IsPlayerDead(_player2.UID);
			if (flag && flag2)
			{
				EndDuel(null, null, isDraw: true);
			}
			else if (flag)
			{
				EndDuel(_player2, _player1, isDraw: false);
			}
			else if (flag2)
			{
				EndDuel(_player1, _player2, isDraw: false);
			}
		}

		private bool IsPlayerDead(long uid)
		{
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			ZNet instance = ZNet.instance;
			List<ZNetPeer> list = ((instance != null) ? instance.GetPeers() : null);
			if (list == null)
			{
				return true;
			}
			foreach (ZNetPeer item in list)
			{
				if (item != null && item.m_uid == uid)
				{
					ZDOMan instance2 = ZDOMan.instance;
					ZDO val = ((instance2 != null) ? instance2.GetZDO(item.m_characterID) : null);
					if (val != null)
					{
						float @float = val.GetFloat("health", 100f);
						return @float <= 0f;
					}
					return false;
				}
			}
			return true;
		}

		private void EndDuel(DuelParticipant winner, DuelParticipant loser, bool isDraw)
		{
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00da: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
			_isDueling = false;
			_lastDuelEndTime = Time.time;
			if (isDraw)
			{
				AnnounceGlobal("<color=#FFFF00>[DUEL]</color> It's a DRAW! Both warriors fell!");
				if (_player1 != null)
				{
					TeleportPlayer(_player1.UID, _player1.OriginalPosition);
				}
				if (_player2 != null)
				{
					TeleportPlayer(_player2.UID, _player2.OriginalPosition);
				}
			}
			else if (winner != null && loser != null)
			{
				AnnounceGlobal("<color=#00FF00>[VICTORY]</color> " + winner.Name + " has defeated " + loser.Name + "!");
				GiveWinnerReward(winner);
				TeleportPlayer(winner.UID, winner.OriginalPosition);
				TeleportPlayer(loser.UID, loser.OriginalPosition);
				((MonoBehaviour)this).StartCoroutine(AnnounceLoserDelayed(loser));
			}
			ResetDuel(applyCooldown: true);
			Debug.Log((object)"[AuroraEventManager] Duel ended");
		}

		[IteratorStateMachine(typeof(<AnnounceLoserDelayed>d__29))]
		private IEnumerator AnnounceLoserDelayed(DuelParticipant loser)
		{
			//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
			return new <AnnounceLoserDelayed>d__29(0)
			{
				<>4__this = this,
				loser = loser
			};
		}

		private void GiveWinnerReward(DuelParticipant winner)
		{
			string text = RewardItems[Random.Range(0, RewardItems.Length)];
			int num = Random.Range(10, 51);
			GiveItemToPlayer(winner.UID, text, num);
			RewardHandler.SendMessageToPlayer(winner.UID, $"<color=#FFD700>[REWARD]</color> You received {num}x {text}!");
		}

		private void GiveItemToPlayer(long uid, string prefabName, int amount)
		{
			ZRoutedRpc instance = ZRoutedRpc.instance;
			if (instance != null)
			{
				instance.InvokeRoutedRPC(uid, "AEM_GiveItem", new object[2] { prefabName, amount });
			}
		}

		private void TeleportPlayer(long uid, Vector3 position)
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			ZRoutedRpc instance = ZRoutedRpc.instance;
			if (instance != null)
			{
				instance.InvokeRoutedRPC(uid, "AEM_Teleport", new object[3] { position.x, position.y, position.z });
			}
		}

		private void SetPlayerImmunity(long uid, bool enable)
		{
			ZRoutedRpc instance = ZRoutedRpc.instance;
			if (instance != null)
			{
				instance.InvokeRoutedRPC(uid, "AEM_DuelImmunity", new object[1] { enable });
			}
		}

		private void ResetDuel(bool applyCooldown)
		{
			_isSearching = false;
			_isDueling = false;
			_duelStarted = false;
			_player1 = null;
			_player2 = null;
			if (!applyCooldown)
			{
				_lastDuelEndTime = -999999f;
			}
		}

		private void AnnounceGlobal(string message)
		{
			RewardHandler.SendGlobalMessage(message);
		}

		public float GetCooldownMinutesRemaining()
		{
			float num = Time.time - _lastDuelEndTime;
			float num2 = 3600f - num;
			return Mathf.Max(0f, num2 / 60f);
		}
	}
	public class DuelParticipant
	{
		public string Name;

		public long UID;

		public Vector3 OriginalPosition;
	}
	public class HiddenHaldorEvent : BaseEvent
	{
		private float _eventStartTime;

		private float _eventDuration = 180f;

		private ZDOID _haldorZDOID = ZDOID.None;

		private Vector3 _haldorPosition;

		private bool _found = false;

		private string _finderName = null;

		public override string EventId => "hidden_haldor";

		public override string EventName => "Hidden Haldor";

		public HiddenHaldorEvent()
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			Config = new EventConfig
			{
				Enabled = true,
				Weight = 6,
				MinPlayers = 1,
				IsGlobalEvent = false,
				RequiresTargetPlayer = true
			};
		}

		public override bool CanStart()
		{
			return base.CanStart() && AuroraEventManagerPlugin.EnableHiddenHaldor.Value;
		}

		protected override void OnEventStart()
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			_eventStartTime = Time.time;
			_found = false;
			_finderName = null;
			_haldorPosition = GetHaldorSpawnPosition();
			SpawnHiddenHaldor();
			string message = "<color=#FFD700>[HIDDEN HALDOR]</color> <color=#00FF00>Hidden Haldor</color> appeared near <color=#FFFF00>" + base.TargetPlayerName + "</color>! They have <color=#FF6600>3 minutes</color> to find him!";
			SendEventShout(message);
			Debug.Log((object)$"[AuroraEventManager] Hidden Haldor spawned at {_haldorPosition}, {Vector3.Distance(base.TargetPosition, _haldorPosition)}m from player");
		}

		protected override void OnEventStop()
		{
			DespawnHaldor();
			EventManagerCore.Instance?.OnEventEnded(this);
		}

		protected override void OnEventUpdate()
		{
			if (!_found && Time.time - _eventStartTime >= _eventDuration)
			{
				SendEventShout("<color=#FFD700>[HIDDEN HALDOR]</color> Time's up! Haldor vanished into the mist...");
				Stop();
			}
		}

		private Vector3 GetHaldorSpawnPosition()
		{
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_015a: Unknown result type (might be due to invalid IL or missing references)
			//IL_015b: Unknown result type (might be due to invalid IL or missing references)
			//IL_015f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0111: Unknown result type (might be due to invalid IL or missing references)
			//IL_0129: Unknown result type (might be due to invalid IL or missing references)
			float num = Random.Range(50f, 250f);
			float num2 = Random.Range(0f, 360f) * ((float)Math.PI / 180f);
			Vector3 val = default(Vector3);
			((Vector3)(ref val))..ctor(Mathf.Cos(num2) * num, 0f, Mathf.Sin(num2) * num);
			Vector3 val2 = base.TargetPosition + val;
			float y = default(float);
			if ((Object)(object)ZoneSystem.instance != (Object)null && ZoneSystem.instance.GetGroundHeight(val2, ref y))
			{
				val2.y = y;
			}
			float num3 = ZoneSystem.instance?.m_waterLevel ?? 30f;
			if (val2.y < num3 + 1f)
			{
				float y2 = default(float);
				for (int i = 0; i < 10; i++)
				{
					num2 = Random.Range(0f, 360f) * ((float)Math.PI / 180f);
					((Vector3)(ref val))..ctor(Mathf.Cos(num2) * num, 0f, Mathf.Sin(num2) * num);
					val2 = base.TargetPosition + val;
					if ((Object)(object)ZoneSystem.instance != (Object)null && ZoneSystem.instance.GetGroundHeight(val2, ref y2))
					{
						val2.y = y2;
						if (val2.y > num3 + 1f)
						{
							break;
						}
					}
				}
			}
			return val2;
		}

		private void SpawnHiddenHaldor()
		{
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			ZNetScene instance = ZNetScene.instance;
			GameObject val = ((instance != null) ? instance.GetPrefab("Haldor") : null);
			if ((Object)(object)val == (Object)null)
			{
				Debug.LogError((object)"[AuroraEventManager] Haldor prefab not found!");
				return;
			}
			GameObject val2 = Object.Instantiate<GameObject>(val, _haldorPosition, Quaternion.identity);
			ZNetView component = val2.GetComponent<ZNetView>();
			if ((Object)(object)component != (Object)null && component.GetZDO() != null)
			{
				_haldorZDOID = component.GetZDO().m_uid;
				component.GetZDO().Set("AEM_HiddenHaldor", true);
				component.GetZDO().Set("AEM_EventStartTime", _eventStartTime);
			}
			Debug.Log((object)$"[AuroraEventManager] Spawned Hidden Haldor at {_haldorPosition}");
		}

		private void DespawnHaldor()
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			if (!(_haldorZDOID == ZDOID.None))
			{
				ZDOMan instance = ZDOMan.instance;
				ZDO val = ((instance != null) ? instance.GetZDO(_haldorZDOID) : null);
				if (val != null)
				{
					ZDOMan.instance.DestroyZDO(val);
					Debug.Log((object)"[AuroraEventManager] Despawned Hidden Haldor");
				}
				_haldorZDOID = ZDOID.None;
			}
		}

		public void OnHaldorFound(string playerName)
		{
			if (!_found)
			{
				_found = true;
				_finderName = playerName;
				float num = Time.time - _eventStartTime;
				int num2 = 1;
				if (num <= 60f)
				{
					num2 = 3;
				}
				else if (num <= 120f)
				{
					num2 = 2;
				}
				int num3 = Random.Range(200, 1001) * num2;
				int num4 = Random.Range(20, 101) * num2;
				int num5 = Random.Range(20, 101) * num2;
				int num6 = Random.Range(20, 101) * num2;
				string text = playerName.ToLower().Trim();
				Debug.Log((object)$"[AuroraEventManager] Hidden Haldor rewards for '{text}': {num3} Coins, {num4} Ruby, {num5} Amber, {num6} AmberPearl");
				if ((Object)(object)ActivityCrateManager.Instance != (Object)null)
				{
					ActivityCrateManager.Instance.AddItemToCrate(text, "Coins", num3);
					ActivityCrateManager.Instance.AddItemToCrate(text, "Ruby", num4);
					ActivityCrateManager.Instance.AddItemToCrate(text, "Amber", num5);
					ActivityCrateManager.Instance.AddItemToCrate(text, "AmberPearl", num6);
					Debug.Log((object)("[AuroraEventManager] Rewards added to Activity Crate for " + playerName));
				}
				else
				{
					RewardHandler.GiveItemToPlayer(playerName, "Coins", num3);
					RewardHandler.GiveItemToPlayer(playerName, "Ruby", num4);
					RewardHandler.GiveItemToPlayer(playerName, "Amber", num5);
					RewardHandler.GiveItemToPlayer(playerName, "AmberPearl", num6);
				}
				string text2 = ((num <= 60f) ? "under a minute" : $"{num:F0} seconds");
				string text3 = ((num2 > 1) ? $" (<color=#00FF00>{num2}x bonus!</color>)" : "");
				string message = "<color=#FFD700>[HIDDEN HALDOR]</color> <color=#FFFF00>" + playerName + "</color> found Hidden Haldor in " + text2 + "!" + text3 + " Rewards in your <color=#00FFFF>Activity Crate</color>!";
				SendEventShout(message);
				Stop();
			}
		}
	}
	public class DancingRitualEvent : BaseEvent
	{
		private float _eventStartTime;

		private float _eventDuration = 60f;

		private float _lastCheckTime;

		private HashSet<string> _dancingPlayers = new HashSet<string>();

		private bool _ritualComplete = false;

		public override string EventId => "dancing_ritual";

		public override string EventName => "Dancing Ritual";

		public DancingRitualEvent()
		{
			Config = new EventConfig
			{
				Enabled = true,
				Weight = 5,
				MinPlayers = 3,
				IsGlobalEvent = true,
				RequiresTargetPlayer = false
			};
		}

		public override bool CanStart()
		{
			if (!base.CanStart())
			{
				return false;
			}
			if (!AuroraEventManagerPlugin.EnableDancingRitual.Value)
			{
				return false;
			}
			int activePlayerCount = GetActivePlayerCount();
			return activePlayerCount >= 3;
		}

		protected override void OnEventStart()
		{
			_eventStartTime = Time.time;
			_lastCheckTime = Time.time;
			_dancingPlayers.Clear();
			_ritualComplete = false;
			string message = "<color=#FF00FF>[DANCING RITUAL]</color> The gods demand a dance! <color=#FFFF00>All active players must dance</color> to clear the weather! Use <color=#00FF00>/dance</color> emote!";
			SendEventShout(message);
			Debug.Log((object)"[AuroraEventManager] Dancing Ritual started");
		}

		protected override void OnEventStop()
		{
			EventManagerCore.Instance?.OnEventEnded(this);
		}

		protected override void OnEventUpdate()
		{
			if (!_ritualComplete)
			{
				if (Time.time - _eventStartTime >= _eventDuration)
				{
					SendEventShout("<color=#FF00FF>[DANCING RITUAL]</color> The ritual failed! The gods are displeased...");
					Stop();
				}
				else if (Time.time - _lastCheckTime >= 2f)
				{
					_lastCheckTime = Time.time;
					CheckDancingStatus();
				}
			}
		}

		private void CheckDancingStatus()
		{
			_dancingPlayers.Clear();
			int num = 0;
			ZNet instance = ZNet.instance;
			List<ZNetPeer> list = ((instance != null) ? instance.GetPeers() : null);
			if (list == null)
			{
				return;
			}
			foreach (ZNetPeer item in list)
			{
				if (item != null && !PlayerBehaviorTracker.Instance.IsPlayerAFK(item.m_uid))
				{
					num++;
					if (IsPlayerDancing(item))
					{
						_dancingPlayers.Add(item.m_playerName);
					}
				}
			}
			if (num == 0)
			{
				return;
			}
			int count = _dancingPlayers.Count;
			if (count >= num)
			{
				_ritualComplete = true;
				ClearWeather();
				SendEventShout("<color=#FF00FF>[DANCING RITUAL]</color> <color=#00FF00>The ritual is complete!</color> The gods have blessed you with clear skies!");
				Stop();
			}
			else
			{
				float num2 = _eventDuration - (Time.time - _eventStartTime);
				if ((int)num2 % 15 == 0)
				{
					SendEventShout($"<color=#FF00FF>[DANCING RITUAL]</color> <color=#FFFF00>{count}/{num}</color> players are dancing. Come on, shake it! ({num2:F0}s left)");
				}
			}
		}

		private bool IsPlayerDancing(ZNetPeer peer)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			if (peer == null)
			{
				return false;
			}
			ZDOID characterID = peer.m_characterID;
			if (((ZDOID)(ref characterID)).IsNone())
			{
				return false;
			}
			ZDOMan instance = ZDOMan.instance;
			ZDO val = ((instance != null) ? instance.GetZDO(characterID) : null);
			if (val == null)
			{
				return false;
			}
			string @string = val.GetString("emote", "");
			int @int = val.GetInt("emoteID", 0);
			return @string.ToLower().Contains("dance") || @int == 4;
		}

		private void ClearWeather()
		{
			if ((Object)(object)EnvMan.instance != (Object)null)
			{
				EnvMan.instance.m_debugEnv = "Clear";
				Debug.Log((object)"[AuroraEventManager] Weather cleared by dancing ritual!");
			}
		}

		private int GetActivePlayerCount()
		{
			int num = 0;
			ZNet instance = ZNet.instance;
			List<ZNetPeer> list = ((instance != null) ? instance.GetPeers() : null);
			if (list == null)
			{
				return 0;
			}
			foreach (ZNetPeer item in list)
			{
				if (item != null && !PlayerBehaviorTracker.Instance.IsPlayerAFK(item.m_uid))
				{
					num++;
				}
			}
			return num

BepInEx/plugins/AuroraProjectButter.dll

Decompiled 2 weeks 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 HarmonyLib;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyCompany("AuroraProjectButter")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.3.0.0")]
[assembly: AssemblyInformationalVersion("1.3.0")]
[assembly: AssemblyProduct("AuroraProjectButter")]
[assembly: AssemblyTitle("AuroraProjectButter")]
[assembly: AssemblyVersion("1.3.0.0")]
namespace AuroraProjectButter;

[BepInPlugin("freyja.AuroraProjectButter", "AuroraProjectButter", "1.3.0")]
public class ButterPlugin : BaseUnityPlugin
{
	internal struct DeferredDungeon
	{
		public DungeonGenerator Generator;

		public Vector3 Position;
	}

	[Serializable]
	[CompilerGenerated]
	private sealed class <>c
	{
		public static readonly <>c <>9 = new <>c();

		public static ConsoleEvent <>9__27_0;

		public static Func<MethodInfo, bool> <>9__31_0;

		public static Func<MethodInfo, bool> <>9__31_1;

		public static Func<MethodInfo, bool> <>9__31_2;

		public static Func<MethodInfo, bool> <>9__31_3;

		public static Func<MethodInfo, bool> <>9__32_0;

		public static Func<ParameterInfo, string> <>9__32_1;

		public static Predicate<DeferredDungeon> <>9__37_0;

		internal void <Awake>b__27_0(ConsoleEventArgs args)
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			DungeonCleanup();
			Player localPlayer = Player.m_localPlayer;
			float num = ((localPlayer != null) ? ((Component)localPlayer).transform.position.y : float.NaN);
			bool flag = IsPlayerTeleporting();
			bool flag2 = IsInGracePeriod();
			args.Context.AddString("[AuroraProjectButter v1.3.0]");
			args.Context.AddString($"  Dungeon Deferral: {TotalDeferred} deferred, {TotalAllowed} allowed, {Deferred.Count} queued");
			args.Context.AddString($"  Sky Filter: {SkyObjectsBlocked} blocked, {SkyObjectsAllowed} allowed");
			args.Context.AddString($"  Player Y: {num:F1}  Teleporting: {flag}  Grace: {flag2}");
			args.Context.AddString($"  World radius: {WorldRadius.Value}");
		}

		internal bool <ApplyDungeonPatches>b__31_0(MethodInfo m)
		{
			return m.Name == "Generate" && !m.IsAbstract;
		}

		internal bool <ApplyDungeonPatches>b__31_1(MethodInfo mi)
		{
			return mi.Name == "Interact";
		}

		internal bool <ApplyDungeonPatches>b__31_2(MethodInfo mi)
		{
			return mi.Name == "HaveTarget";
		}

		internal bool <ApplyDungeonPatches>b__31_3(MethodInfo mi)
		{
			return mi.Name == "OnSpawned";
		}

		internal bool <ApplySkyFilterPatches>b__32_0(MethodInfo m)
		{
			return m.Name == "CreateObject" && !m.IsAbstract;
		}

		internal string <ApplySkyFilterPatches>b__32_1(ParameterInfo p)
		{
			return p.ParameterType.Name;
		}

		internal bool <DungeonCleanup>b__37_0(DeferredDungeon d)
		{
			return (Object)(object)d.Generator == (Object)null;
		}
	}

	public const string PluginGUID = "freyja.AuroraProjectButter";

	public const string PluginName = "AuroraProjectButter";

	public const string PluginVersion = "1.3.0";

	internal static ButterPlugin Instance;

	internal static ManualLogSource Logger;

	private Harmony _harmony;

	internal static readonly List<DeferredDungeon> Deferred = new List<DeferredDungeon>();

	internal static bool IsForceLoading;

	internal static bool IsTeleporting;

	internal static float PlayerSpawnTime = -1f;

	internal static float TeleportEndTime = -1f;

	internal static MethodInfo DG_AwakeMethod;

	internal static int TotalDeferred;

	internal static int TotalAllowed;

	internal static int SkyObjectsBlocked;

	internal static int SkyObjectsAllowed;

	public static ConfigEntry<bool> ModEnabled;

	public static ConfigEntry<bool> VerboseLogging;

	public static ConfigEntry<float> SearchRadius;

	public static ConfigEntry<float> TeleportDelay;

	public static ConfigEntry<bool> ShowLoadingMsg;

	public static ConfigEntry<float> SpawnGracePeriod;

	public static ConfigEntry<bool> SkyFilterEnabled;

	public static ConfigEntry<float> SkyThreshold;

	public static ConfigEntry<float> TeleportGracePeriod;

	public static ConfigEntry<float> WorldRadius;

	private void Awake()
	{
		//IL_0170: Unknown result type (might be due to invalid IL or missing references)
		//IL_017a: Expected O, but got Unknown
		//IL_01da: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c6: Unknown result type (might be due to invalid IL or missing references)
		//IL_01cb: Unknown result type (might be due to invalid IL or missing references)
		//IL_01d1: Expected O, but got Unknown
		Instance = this;
		Logger = ((BaseUnityPlugin)this).Logger;
		ModEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "Master toggle.");
		VerboseLogging = ((BaseUnityPlugin)this).Config.Bind<bool>("Debug", "VerboseLogging", false, "Extra logging.");
		SearchRadius = ((BaseUnityPlugin)this).Config.Bind<float>("DungeonDeferral", "SearchRadius", 300f, "Max distance from entrance to find deferred dungeon.");
		TeleportDelay = ((BaseUnityPlugin)this).Config.Bind<float>("DungeonDeferral", "TeleportDelay", 2.5f, "Seconds to wait after loading dungeon before teleport.");
		ShowLoadingMsg = ((BaseUnityPlugin)this).Config.Bind<bool>("DungeonDeferral", "ShowLoadingMessage", true, "Show 'Loading dungeon...' message.");
		SpawnGracePeriod = ((BaseUnityPlugin)this).Config.Bind<float>("DungeonDeferral", "SpawnGracePeriod", 2f, "Seconds after login to allow all loading.");
		SkyFilterEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("SkyFilter", "Enabled", true, "Skip creating GameObjects for dungeon interior objects while on surface.");
		SkyThreshold = ((BaseUnityPlugin)this).Config.Bind<float>("SkyFilter", "SkyThresholdY", 1000f, "Objects above this Y are considered dungeon interiors.");
		TeleportGracePeriod = ((BaseUnityPlugin)this).Config.Bind<float>("SkyFilter", "TeleportGracePeriod", 5f, "Seconds after ANY teleport where sky filter is disabled. Prevents loading screen freeze.");
		WorldRadius = ((BaseUnityPlugin)this).Config.Bind<float>("SkyFilter", "WorldRadius", 15000f, "Objects beyond this X/Z distance from world center are never filtered. Set higher than your world radius to protect custom sky zones. Default 15000 covers most Expand World Size configs.");
		_harmony = new Harmony("freyja.AuroraProjectButter");
		Logger.LogInfo((object)"── Dungeon Deferral patches ──");
		ApplyDungeonPatches();
		Logger.LogInfo((object)"── Sky Object Filter patches ──");
		ApplySkyFilterPatches();
		object obj = <>c.<>9__27_0;
		if (obj == null)
		{
			ConsoleEvent val = delegate(ConsoleEventArgs args)
			{
				//IL_001c: Unknown result type (might be due to invalid IL or missing references)
				DungeonCleanup();
				Player localPlayer = Player.m_localPlayer;
				float num = ((localPlayer != null) ? ((Component)localPlayer).transform.position.y : float.NaN);
				bool flag = IsPlayerTeleporting();
				bool flag2 = IsInGracePeriod();
				args.Context.AddString("[AuroraProjectButter v1.3.0]");
				args.Context.AddString($"  Dungeon Deferral: {TotalDeferred} deferred, {TotalAllowed} allowed, {Deferred.Count} queued");
				args.Context.AddString($"  Sky Filter: {SkyObjectsBlocked} blocked, {SkyObjectsAllowed} allowed");
				args.Context.AddString($"  Player Y: {num:F1}  Teleporting: {flag}  Grace: {flag2}");
				args.Context.AddString($"  World radius: {WorldRadius.Value}");
			};
			<>c.<>9__27_0 = val;
			obj = (object)val;
		}
		new ConsoleCommand("butter_status", "Show AuroraProjectButter stats", (ConsoleEvent)obj, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false);
		Logger.LogInfo((object)"=== AuroraProjectButter v1.3.0 loaded ===");
		Logger.LogInfo((object)"  Dungeon Deferral: ON");
		Logger.LogInfo((object)string.Format("  Sky Filter: {0} (Y > {1}, grace {2}s, radius {3})", SkyFilterEnabled.Value ? "ON" : "OFF", SkyThreshold.Value, TeleportGracePeriod.Value, WorldRadius.Value));
	}

	private void OnDestroy()
	{
		Harmony harmony = _harmony;
		if (harmony != null)
		{
			harmony.UnpatchSelf();
		}
	}

	internal static bool IsPlayerTeleporting()
	{
		if (IsTeleporting)
		{
			return true;
		}
		if (IsForceLoading)
		{
			return true;
		}
		Player localPlayer = Player.m_localPlayer;
		if ((Object)(object)localPlayer == (Object)null)
		{
			return false;
		}
		try
		{
			FieldInfo field = typeof(Player).GetField("m_teleporting", BindingFlags.Instance | BindingFlags.NonPublic);
			if (field != null)
			{
				return (bool)field.GetValue(localPlayer);
			}
		}
		catch
		{
		}
		return false;
	}

	internal static bool IsInGracePeriod()
	{
		float time = Time.time;
		if (PlayerSpawnTime > 0f && time - PlayerSpawnTime < SpawnGracePeriod.Value)
		{
			return true;
		}
		if (TeleportEndTime > 0f && time - TeleportEndTime < TeleportGracePeriod.Value)
		{
			return true;
		}
		return false;
	}

	private void ApplyDungeonPatches()
	{
		//IL_004f: Unknown result type (might be due to invalid IL or missing references)
		//IL_005d: Expected O, but got Unknown
		//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f0: Expected O, but got Unknown
		//IL_01a0: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ae: Expected O, but got Unknown
		//IL_0273: Unknown result type (might be due to invalid IL or missing references)
		//IL_0281: Expected O, but got Unknown
		//IL_0314: Unknown result type (might be due to invalid IL or missing references)
		//IL_0321: Expected O, but got Unknown
		//IL_03b9: Unknown result type (might be due to invalid IL or missing references)
		//IL_03c6: Expected O, but got Unknown
		try
		{
			DG_AwakeMethod = typeof(DungeonGenerator).GetMethod("Awake", BindingFlags.Instance | BindingFlags.NonPublic, null, Type.EmptyTypes, null);
			if (DG_AwakeMethod != null)
			{
				_harmony.Patch((MethodBase)DG_AwakeMethod, new HarmonyMethod(typeof(DungeonPatches), "Awake_Prefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				Logger.LogInfo((object)"  OK: DungeonGenerator.Awake()");
			}
			else
			{
				Logger.LogError((object)"  FAIL: DungeonGenerator.Awake()");
			}
		}
		catch (Exception arg)
		{
			Logger.LogError((object)$"  DG.Awake: {arg}");
		}
		try
		{
			MethodInfo method = typeof(DungeonGenerator).GetMethod("LoadRoomPrefabsAsync", BindingFlags.Instance | BindingFlags.NonPublic, null, Type.EmptyTypes, null);
			if (method != null)
			{
				_harmony.Patch((MethodBase)method, new HarmonyMethod(typeof(DungeonPatches), "LoadAsync_Prefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				Logger.LogInfo((object)"  OK: LoadRoomPrefabsAsync() (fallback)");
			}
		}
		catch (Exception ex)
		{
			Logger.LogWarning((object)("  LoadAsync: " + ex.Message));
		}
		try
		{
			List<MethodInfo> list = (from m in typeof(DungeonGenerator).GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
				where m.Name == "Generate" && !m.IsAbstract
				select m).ToList();
			MethodInfo method2 = typeof(DungeonPatches).GetMethod("Generate_Prefix", BindingFlags.Static | BindingFlags.Public);
			int num = 0;
			foreach (MethodInfo item in list)
			{
				try
				{
					_harmony.Patch((MethodBase)item, new HarmonyMethod(method2), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
					num++;
				}
				catch
				{
				}
			}
			Logger.LogInfo((object)$"  OK: {num} Generate overload(s)");
		}
		catch (Exception arg2)
		{
			Logger.LogError((object)$"  Generate: {arg2}");
		}
		try
		{
			MethodInfo methodInfo = typeof(Teleport).GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).FirstOrDefault((MethodInfo mi) => mi.Name == "Interact");
			if (methodInfo != null)
			{
				_harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(DungeonPatches), "Teleport_Interact_Prefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				Logger.LogInfo((object)"  OK: Teleport.Interact");
			}
		}
		catch (Exception arg3)
		{
			Logger.LogError((object)$"  Teleport.Interact: {arg3}");
		}
		try
		{
			MethodInfo methodInfo2 = typeof(Teleport).GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).FirstOrDefault((MethodInfo mi) => mi.Name == "HaveTarget");
			if (methodInfo2 != null)
			{
				_harmony.Patch((MethodBase)methodInfo2, (HarmonyMethod)null, new HarmonyMethod(typeof(DungeonPatches), "HaveTarget_Postfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				Logger.LogInfo((object)"  OK: Teleport.HaveTarget");
			}
		}
		catch (Exception ex2)
		{
			Logger.LogWarning((object)("  HaveTarget: " + ex2.Message));
		}
		try
		{
			MethodInfo methodInfo3 = typeof(Player).GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).FirstOrDefault((MethodInfo mi) => mi.Name == "OnSpawned");
			if (methodInfo3 != null)
			{
				_harmony.Patch((MethodBase)methodInfo3, (HarmonyMethod)null, new HarmonyMethod(typeof(DungeonPatches), "Player_OnSpawned_Postfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				Logger.LogInfo((object)"  OK: Player.OnSpawned");
			}
		}
		catch (Exception ex3)
		{
			Logger.LogWarning((object)("  Player.OnSpawned: " + ex3.Message));
		}
	}

	private void ApplySkyFilterPatches()
	{
		//IL_018b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0199: Expected O, but got Unknown
		//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00df: Expected O, but got Unknown
		if (!SkyFilterEnabled.Value)
		{
			Logger.LogInfo((object)"  Sky Filter DISABLED in config.");
			return;
		}
		try
		{
			List<MethodInfo> list = (from m in typeof(ZNetScene).GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
				where m.Name == "CreateObject" && !m.IsAbstract
				select m).ToList();
			MethodInfo method = typeof(SkyFilterPatches).GetMethod("CreateObject_Prefix", BindingFlags.Static | BindingFlags.Public);
			int num = 0;
			foreach (MethodInfo item in list)
			{
				ParameterInfo[] parameters = item.GetParameters();
				if (parameters.Length >= 1 && parameters[0].ParameterType == typeof(ZDO))
				{
					_harmony.Patch((MethodBase)item, new HarmonyMethod(method), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
					string text = string.Join(", ", parameters.Select((ParameterInfo p) => p.ParameterType.Name));
					Logger.LogInfo((object)("  OK: ZNetScene.CreateObject(" + text + ")"));
					num++;
				}
			}
			if (num == 0)
			{
				Logger.LogWarning((object)"  No ZDO-parameter CreateObject found. Trying all overloads...");
				foreach (MethodInfo item2 in list)
				{
					try
					{
						_harmony.Patch((MethodBase)item2, new HarmonyMethod(method), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
						num++;
					}
					catch
					{
					}
				}
			}
			if (num == 0)
			{
				Logger.LogError((object)"  FAIL: Could not patch any ZNetScene.CreateObject!");
			}
		}
		catch (Exception arg)
		{
			Logger.LogError((object)$"  ZNetScene.CreateObject: {arg}");
		}
	}

	internal static bool ShouldDefer(string caller, Vector3 genPos)
	{
		//IL_0084: Unknown result type (might be due to invalid IL or missing references)
		//IL_0089: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
		//IL_0056: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
		//IL_0178: Unknown result type (might be due to invalid IL or missing references)
		//IL_017e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0104: Unknown result type (might be due to invalid IL or missing references)
		//IL_014c: Unknown result type (might be due to invalid IL or missing references)
		if (!ModEnabled.Value)
		{
			return false;
		}
		if (IsForceLoading)
		{
			return false;
		}
		if ((Object)(object)Player.m_localPlayer == (Object)null)
		{
			if (VerboseLogging.Value)
			{
				Logger.LogInfo((object)$"[ALLOW:no-player] {caller} at {genPos:F0}");
			}
			TotalAllowed++;
			return false;
		}
		Vector3 position = ((Component)Player.m_localPlayer).transform.position;
		if (IsInGracePeriod())
		{
			if (VerboseLogging.Value)
			{
				Logger.LogInfo((object)$"[ALLOW:grace] {caller} at {genPos:F0}");
			}
			TotalAllowed++;
			return false;
		}
		if (position.y > 1000f)
		{
			if (VerboseLogging.Value)
			{
				Logger.LogInfo((object)$"[ALLOW:in-dungeon] {caller} at {genPos:F0}");
			}
			TotalAllowed++;
			return false;
		}
		if (IsPlayerTeleporting())
		{
			if (VerboseLogging.Value)
			{
				Logger.LogInfo((object)$"[ALLOW:teleporting] {caller} at {genPos:F0}");
			}
			TotalAllowed++;
			return false;
		}
		Logger.LogInfo((object)$"[DEFER] {caller} at {genPos:F0}, player Y={position.y:F0}");
		TotalDeferred++;
		return true;
	}

	internal static void DeferDungeon(DungeonGenerator gen)
	{
		//IL_0019: Unknown result type (might be due to invalid IL or missing references)
		//IL_001e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0057: Unknown result type (might be due to invalid IL or missing references)
		//IL_0058: Unknown result type (might be due to invalid IL or missing references)
		Vector3 position = ((Component)gen).transform.position;
		if (!Deferred.Any((DeferredDungeon d) => (Object)(object)d.Generator == (Object)(object)gen))
		{
			Deferred.Add(new DeferredDungeon
			{
				Generator = gen,
				Position = position
			});
		}
	}

	internal static DeferredDungeon? FindNearest(Vector3 origin, float maxDist)
	{
		//IL_002d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0037: Unknown result type (might be due to invalid IL or missing references)
		//IL_0041: Unknown result type (might be due to invalid IL or missing references)
		//IL_004b: Unknown result type (might be due to invalid IL or missing references)
		DungeonCleanup();
		DeferredDungeon? result = null;
		float num = float.MaxValue;
		foreach (DeferredDungeon item in Deferred)
		{
			float num2 = item.Position.x - origin.x;
			float num3 = item.Position.z - origin.z;
			float num4 = Mathf.Sqrt(num2 * num2 + num3 * num3);
			if (num4 < maxDist && num4 < num)
			{
				num = num4;
				result = item;
			}
		}
		return result;
	}

	internal static void RemoveDeferred(DungeonGenerator gen)
	{
		Deferred.RemoveAll((DeferredDungeon d) => (Object)(object)d.Generator == (Object)(object)gen || (Object)(object)d.Generator == (Object)null);
	}

	internal static void DungeonCleanup()
	{
		Deferred.RemoveAll((DeferredDungeon d) => (Object)(object)d.Generator == (Object)null);
	}

	internal static void ForceLoadDungeon(DungeonGenerator gen)
	{
		//IL_003a: Unknown result type (might be due to invalid IL or missing references)
		if (DG_AwakeMethod == null)
		{
			Logger.LogError((object)"[REPLAY] No Awake method!");
			return;
		}
		IsForceLoading = true;
		try
		{
			Logger.LogInfo((object)$"[REPLAY] Awake() at {((Component)gen).transform.position:F0}");
			DG_AwakeMethod.Invoke(gen, null);
		}
		finally
		{
			IsForceLoading = false;
		}
	}

	internal static Coroutine RunCoroutine(IEnumerator routine)
	{
		ButterPlugin instance = Instance;
		return (instance != null) ? ((MonoBehaviour)instance).StartCoroutine(routine) : null;
	}
}
internal static class SkyFilterPatches
{
	public static bool CreateObject_Prefix(ZDO __0)
	{
		//IL_0088: Unknown result type (might be due to invalid IL or missing references)
		//IL_008d: Unknown result type (might be due to invalid IL or missing references)
		//IL_008e: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
		//IL_0137: Unknown result type (might be due to invalid IL or missing references)
		if (!ButterPlugin.SkyFilterEnabled.Value)
		{
			return true;
		}
		if (__0 == null)
		{
			return true;
		}
		if ((Object)(object)Player.m_localPlayer == (Object)null)
		{
			return true;
		}
		if (ButterPlugin.IsPlayerTeleporting())
		{
			ButterPlugin.SkyObjectsAllowed++;
			return true;
		}
		if (ButterPlugin.IsInGracePeriod())
		{
			ButterPlugin.SkyObjectsAllowed++;
			return true;
		}
		Vector3 position = __0.GetPosition();
		float y = position.y;
		if (y <= ButterPlugin.SkyThreshold.Value)
		{
			return true;
		}
		float num = Mathf.Sqrt(position.x * position.x + position.z * position.z);
		if (num > ButterPlugin.WorldRadius.Value)
		{
			ButterPlugin.SkyObjectsAllowed++;
			if (ButterPlugin.VerboseLogging.Value)
			{
				ButterPlugin.Logger.LogInfo((object)$"[SkyFilter:ALLOW] Outside world radius: Y={y:F0} dist={num:F0}");
			}
			return true;
		}
		float y2 = ((Component)Player.m_localPlayer).transform.position.y;
		if (y2 > ButterPlugin.SkyThreshold.Value)
		{
			ButterPlugin.SkyObjectsAllowed++;
			return true;
		}
		ButterPlugin.SkyObjectsBlocked++;
		if (ButterPlugin.VerboseLogging.Value && ButterPlugin.SkyObjectsBlocked % 100 == 1)
		{
			ButterPlugin.Logger.LogInfo((object)$"[SkyFilter:BLOCK] #{ButterPlugin.SkyObjectsBlocked} Y={y:F0} dist={num:F0}");
		}
		return false;
	}
}
internal static class DungeonPatches
{
	[CompilerGenerated]
	private sealed class <LoadAndTeleport>d__5 : IEnumerator<object>, IDisposable, IEnumerator
	{
		private int <>1__state;

		private object <>2__current;

		public Teleport teleport;

		public ButterPlugin.DeferredDungeon deferred;

		public Humanoid character;

		private Exception <ex>5__1;

		private Exception <ex>5__2;

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

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

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

		[DebuggerHidden]
		void IDisposable.Dispose()
		{
			<ex>5__1 = null;
			<ex>5__2 = null;
			<>1__state = -2;
		}

		private bool MoveNext()
		{
			//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ef: Expected O, but got Unknown
			switch (<>1__state)
			{
			default:
				return false;
			case 0:
				<>1__state = -1;
				if (ButterPlugin.ShowLoadingMsg.Value)
				{
					Player localPlayer = Player.m_localPlayer;
					if (localPlayer != null)
					{
						((Character)localPlayer).Message((MessageType)2, "Loading dungeon...", 0, (Sprite)null);
					}
				}
				ButterPlugin.TeleportEndTime = Time.time;
				<>2__current = null;
				<>1__state = 1;
				return true;
			case 1:
				<>1__state = -1;
				if ((Object)(object)deferred.Generator != (Object)null)
				{
					try
					{
						ButterPlugin.ForceLoadDungeon(deferred.Generator);
					}
					catch (Exception ex)
					{
						<ex>5__1 = ex;
						ButterPlugin.Logger.LogError((object)$"[OnDemand] Failed: {<ex>5__1}");
					}
					ButterPlugin.RemoveDeferred(deferred.Generator);
				}
				<>2__current = (object)new WaitForSeconds(ButterPlugin.TeleportDelay.Value);
				<>1__state = 2;
				return true;
			case 2:
				<>1__state = -1;
				ButterPlugin.TeleportEndTime = Time.time;
				if ((Object)(object)teleport != (Object)null && (Object)(object)character != (Object)null)
				{
					ButterPlugin.IsTeleporting = true;
					try
					{
						teleport.Interact(character, false, false);
					}
					catch (Exception ex)
					{
						<ex>5__2 = ex;
						ButterPlugin.Logger.LogError((object)$"[OnDemand] Teleport: {<ex>5__2}");
					}
					finally
					{
						ButterPlugin.IsTeleporting = false;
					}
				}
				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();
		}
	}

	public static void Player_OnSpawned_Postfix(Player __instance)
	{
		//IL_0035: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)__instance == (Object)(object)Player.m_localPlayer)
		{
			ButterPlugin.PlayerSpawnTime = Time.time;
			ButterPlugin.TeleportEndTime = Time.time;
			ButterPlugin.Logger.LogInfo((object)$"[Spawn] Player at {((Component)__instance).transform.position:F0}");
		}
	}

	public static bool Awake_Prefix(DungeonGenerator __instance)
	{
		//IL_000c: Unknown result type (might be due to invalid IL or missing references)
		if (ButterPlugin.ShouldDefer("Awake", ((Component)__instance).transform.position))
		{
			ButterPlugin.DeferDungeon(__instance);
			return false;
		}
		return true;
	}

	public static bool LoadAsync_Prefix(DungeonGenerator __instance)
	{
		//IL_000c: Unknown result type (might be due to invalid IL or missing references)
		if (ButterPlugin.ShouldDefer("LoadAsync", ((Component)__instance).transform.position))
		{
			ButterPlugin.DeferDungeon(__instance);
			return false;
		}
		return true;
	}

	public static bool Generate_Prefix(DungeonGenerator __instance)
	{
		//IL_000c: Unknown result type (might be due to invalid IL or missing references)
		if (ButterPlugin.ShouldDefer("Generate", ((Component)__instance).transform.position))
		{
			ButterPlugin.DeferDungeon(__instance);
			return false;
		}
		return true;
	}

	public static bool Teleport_Interact_Prefix(Teleport __instance, Humanoid character, bool hold, bool alt)
	{
		//IL_0059: Unknown result type (might be due to invalid IL or missing references)
		//IL_0085: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
		if (!ButterPlugin.ModEnabled.Value)
		{
			return true;
		}
		if (ButterPlugin.IsTeleporting)
		{
			return true;
		}
		if ((Object)(object)character != (Object)(object)Player.m_localPlayer)
		{
			return true;
		}
		if (hold)
		{
			return true;
		}
		if (((Component)Player.m_localPlayer).transform.position.y > 1000f)
		{
			ButterPlugin.TeleportEndTime = Time.time;
			return true;
		}
		ButterPlugin.DeferredDungeon? deferredDungeon = ButterPlugin.FindNearest(((Component)__instance).transform.position, ButterPlugin.SearchRadius.Value);
		if (!deferredDungeon.HasValue)
		{
			ButterPlugin.TeleportEndTime = Time.time;
			return true;
		}
		ButterPlugin.Logger.LogInfo((object)$"[OnDemand] Entrance → loading dungeon at {deferredDungeon.Value.Position:F0}");
		ButterPlugin.RunCoroutine(LoadAndTeleport(__instance, deferredDungeon.Value, character));
		return false;
	}

	[IteratorStateMachine(typeof(<LoadAndTeleport>d__5))]
	private static IEnumerator LoadAndTeleport(Teleport teleport, ButterPlugin.DeferredDungeon deferred, Humanoid character)
	{
		//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
		return new <LoadAndTeleport>d__5(0)
		{
			teleport = teleport,
			deferred = deferred,
			character = character
		};
	}

	public static void HaveTarget_Postfix(Teleport __instance, ref bool __result)
	{
		//IL_002b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0055: Unknown result type (might be due to invalid IL or missing references)
		if (ButterPlugin.ModEnabled.Value && (!((Object)(object)Player.m_localPlayer != (Object)null) || !(((Component)Player.m_localPlayer).transform.position.y > 1000f)) && !__result && ButterPlugin.FindNearest(((Component)__instance).transform.position, ButterPlugin.SearchRadius.Value).HasValue)
		{
			__result = true;
		}
	}
}

BepInEx/plugins/AuroraQuickConnect.dll

Decompiled 2 weeks ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyCompany("AuroraQuickConnect")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.2.1.0")]
[assembly: AssemblyInformationalVersion("1.2.1")]
[assembly: AssemblyProduct("AuroraQuickConnect")]
[assembly: AssemblyTitle("AuroraQuickConnect")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.2.1.0")]
[module: UnverifiableCode]
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 AuroraQuickConnect
{
	[BepInPlugin("com.aurora.quickconnect", "AuroraQuickConnect", "1.2.1")]
	public sealed class AuroraQuickConnect : BaseUnityPlugin
	{
		private static class Joiner
		{
			public static bool TryJoin(FejdStartup fs, string host, int port, string password)
			{
				string text = $"{host}:{port}";
				Ui.TryFillJoinByIp(fs, text, password);
				if (SmartInvoke.TryInvokeFirstMatch(fs, new string[8] { "OnJoinIPConnect", "OnJoinIpConnect", "JoinServerIP", "JoinServerIp", "JoinServer", "ConnectToServer", "ConnectToIP", "ConnectToIp" }, SmartInvoke.Candidates(new object[0], new object[1] { text }, new object[2] { text, password }, new object[2] { host, port }, new object[3] { host, port, password })))
				{
					return true;
				}
				if (TryJoinViaMatchmaking(text))
				{
					return true;
				}
				if (TryJoinViaZNet(host, port, text))
				{
					return true;
				}
				return false;
			}

			private static bool TryJoinViaMatchmaking(string hostAndPort)
			{
				try
				{
					Type type = AccessTools.TypeByName("ZSteamMatchmaking");
					if (type == null)
					{
						return false;
					}
					object obj = AccessTools.Property(type, "instance")?.GetValue(null) ?? AccessTools.Field(type, "instance")?.GetValue(null);
					if (obj == null)
					{
						return false;
					}
					if (SmartInvoke.TryInvokeFirstMatch(obj, new string[6] { "QueueServerJoin", "JoinServer", "JoinServerByIp", "JoinServerByIP", "JoinIP", "JoinIp" }, SmartInvoke.Candidates(new object[1] { hostAndPort })))
					{
						Log.LogInfo((object)"Aurora QuickConnect: join triggered via ZSteamMatchmaking.");
						return true;
					}
				}
				catch (Exception ex)
				{
					Log.LogDebug((object)("TryJoinViaMatchmaking failed: " + ex.GetType().Name + ": " + ex.Message));
				}
				return false;
			}

			private static bool TryJoinViaZNet(string host, int port, string hostAndPort)
			{
				try
				{
					Type type = AccessTools.TypeByName("ZNet");
					if (type == null)
					{
						return false;
					}
					object obj = AccessTools.Property(type, "instance")?.GetValue(null) ?? AccessTools.Field(type, "instance")?.GetValue(null);
					if (obj == null)
					{
						return false;
					}
					IPEndPoint iPEndPoint = null;
					try
					{
						iPEndPoint = new IPEndPoint(IPAddress.Parse(host), port);
					}
					catch
					{
					}
					List<object[]> list = new List<object[]>();
					list.Add(new object[2] { host, port });
					list.Add(new object[1] { hostAndPort });
					List<object[]> list2 = list;
					if (iPEndPoint != null)
					{
						list2.Add(new object[1] { iPEndPoint });
					}
					if (SmartInvoke.TryInvokeFirstMatch(obj, new string[6] { "Connect", "StartClient", "StartClientConnect", "ConnectToServer", "ConnectToIP", "ConnectToIp" }, list2.ToArray()))
					{
						Log.LogInfo((object)"Aurora QuickConnect: join triggered via ZNet.");
						return true;
					}
				}
				catch (Exception ex)
				{
					Log.LogDebug((object)("TryJoinViaZNet failed: " + ex.GetType().Name + ": " + ex.Message));
				}
				return false;
			}

			public static void DumpJoinMethods(FejdStartup fs)
			{
				try
				{
					DumpTypeMethods("FejdStartup", ((object)fs).GetType(), "join");
					DumpTypeMethods("FejdStartup", ((object)fs).GetType(), "connect");
					Type type = AccessTools.TypeByName("ZSteamMatchmaking");
					if (type != null)
					{
						DumpTypeMethods("ZSteamMatchmaking", type, "join");
					}
					Type type2 = AccessTools.TypeByName("ZNet");
					if (type2 != null)
					{
						DumpTypeMethods("ZNet", type2, "connect");
					}
				}
				catch (Exception ex)
				{
					Log.LogWarning((object)("DumpJoinMethods failed: " + ex.GetType().Name + ": " + ex.Message));
				}
			}

			private static void DumpTypeMethods(string label, Type t, string filter)
			{
				string filter2 = filter;
				string[] array = (from m in (from m in t.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
						where m.Name.IndexOf(filter2, StringComparison.OrdinalIgnoreCase) >= 0
						orderby m.Name
						select m).Take(60)
					select m.Name + "(" + string.Join(", ", from p in m.GetParameters()
						select p.ParameterType.Name) + ")").ToArray();
				Log.LogInfo((object)("---- " + label + " methods matching '" + filter2 + "' (up to 60) ----"));
				string[] array2 = array;
				foreach (string text in array2)
				{
					Log.LogInfo((object)text);
				}
				Log.LogInfo((object)"--------------------------------------------------------");
			}
		}

		private static class SmartInvoke
		{
			public static object[][] Candidates(params object[][] candidates)
			{
				return candidates;
			}

			public static bool TryInvokeFirstMatch(object instance, string[] methodNames, object[][] candidates)
			{
				Type type = instance.GetType();
				MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				foreach (string name in methodNames)
				{
					foreach (MethodInfo item in methods.Where((MethodInfo x) => x.Name == name))
					{
						foreach (object[] candidate in candidates)
						{
							if (!TryBuildArgs(item, candidate, out object[] args))
							{
								continue;
							}
							try
							{
								item.Invoke(instance, args);
								Log.LogInfo((object)("Invoked " + type.Name + "." + item.Name + "(" + string.Join(", ", from p in item.GetParameters()
									select p.ParameterType.Name) + ")"));
								return true;
							}
							catch (Exception ex)
							{
								Log.LogDebug((object)("Invoke failed " + type.Name + "." + item.Name + ": " + ex.GetType().Name + ": " + ex.Message));
							}
						}
					}
				}
				return false;
			}

			private static bool TryBuildArgs(MethodInfo method, object[] candidate, out object[] args)
			{
				args = Array.Empty<object>();
				ParameterInfo[] parameters = method.GetParameters();
				if (parameters.Length != candidate.Length)
				{
					return false;
				}
				object[] array = new object[parameters.Length];
				for (int i = 0; i < parameters.Length; i++)
				{
					Type parameterType = parameters[i].ParameterType;
					object obj = candidate[i];
					if (obj == null)
					{
						if (parameterType.IsValueType)
						{
							return false;
						}
						array[i] = null;
						continue;
					}
					Type type = obj.GetType();
					if (parameterType.IsAssignableFrom(type))
					{
						array[i] = obj;
						continue;
					}
					if (parameterType == typeof(ushort) && obj is int num && num >= 0 && num <= 65535)
					{
						array[i] = (ushort)num;
						continue;
					}
					if (parameterType == typeof(int) && obj is ushort num2)
					{
						array[i] = (int)num2;
						continue;
					}
					if (parameterType == typeof(string))
					{
						array[i] = obj.ToString() ?? "";
						continue;
					}
					return false;
				}
				args = array;
				return true;
			}
		}

		private static class Ui
		{
			private const string AuroraButtonName = "AuroraQuickConnect__PlayAuroraButton";

			public static void HideMenuElements(FejdStartup fs, bool hideChangelog, bool hideMerchStore, bool hideModdedWarning)
			{
				if ((Object)(object)fs == (Object)null)
				{
					return;
				}
				try
				{
					Transform[] componentsInChildren = ((Component)fs).GetComponentsInChildren<Transform>(true);
					if (hideChangelog)
					{
						string[] array = new string[10] { "Changelog", "ChangeLog", "changelog", "PatchNotes", "patchnotes", "Patch Notes", "ChangelogPanel", "ChangeLogPanel", "UpdateLog", "Updates" };
						Transform[] array2 = componentsInChildren;
						foreach (Transform val in array2)
						{
							if ((Object)(object)val == (Object)null)
							{
								continue;
							}
							string[] array3 = array;
							foreach (string value in array3)
							{
								if (((Object)val).name.IndexOf(value, StringComparison.OrdinalIgnoreCase) >= 0)
								{
									((Component)val).gameObject.SetActive(false);
									Log.LogInfo((object)("Hidden changelog element: " + ((Object)val).name));
									break;
								}
							}
						}
					}
					if (hideMerchStore)
					{
						string[] array4 = new string[9] { "Merch", "merch", "MerchStore", "merchstore", "MerchPanel", "StorePanel", "ShopPanel", "MerchButton", "StoreButton" };
						Transform[] array5 = componentsInChildren;
						foreach (Transform val2 in array5)
						{
							if ((Object)(object)val2 == (Object)null)
							{
								continue;
							}
							string[] array6 = array4;
							foreach (string value2 in array6)
							{
								if (((Object)val2).name.IndexOf(value2, StringComparison.OrdinalIgnoreCase) >= 0)
								{
									((Component)val2).gameObject.SetActive(false);
									Log.LogInfo((object)("Hidden merch element: " + ((Object)val2).name));
									break;
								}
							}
						}
					}
					if (!hideModdedWarning)
					{
						return;
					}
					string[] array7 = new string[9] { "ModdedWarning", "moddedwarning", "BepInExWarning", "ModWarning", "ModdedPanel", "ModdedText", "ModdedNotice", "ModdedGameWarning", "modded_text" };
					string[] array8 = new string[10] { "Menu", "Canvas", "GUI", "StartGui", "MainMenu", "FejdStartup", "UIRoot", "UICanvas", "Panel", "Root" };
					Transform[] array9 = componentsInChildren;
					foreach (Transform val3 in array9)
					{
						if ((Object)(object)val3 == (Object)null)
						{
							continue;
						}
						string[] array10 = array7;
						foreach (string value3 in array10)
						{
							if (((Object)val3).name.Equals(value3, StringComparison.OrdinalIgnoreCase) || ((Object)val3).name.Equals("BetaText", StringComparison.OrdinalIgnoreCase))
							{
								((Component)val3).gameObject.SetActive(false);
								Log.LogInfo((object)("Hidden warning element: " + ((Object)val3).name));
								break;
							}
						}
					}
					try
					{
						Text[] componentsInChildren2 = ((Component)fs).GetComponentsInChildren<Text>(true);
						Text[] array11 = componentsInChildren2;
						foreach (Text val4 in array11)
						{
							if (!((Object)(object)val4 == (Object)null) && !string.IsNullOrEmpty(val4.text) && (val4.text.IndexOf("modded version", StringComparison.OrdinalIgnoreCase) >= 0 || val4.text.IndexOf("uninstall all mods", StringComparison.OrdinalIgnoreCase) >= 0))
							{
								((Component)val4).gameObject.SetActive(false);
								Log.LogInfo((object)("Hidden modded warning text: " + ((Object)((Component)val4).gameObject).name));
							}
						}
						Component[] componentsInChildren3 = ((Component)fs).GetComponentsInChildren<Component>(true);
						Component[] array12 = componentsInChildren3;
						foreach (Component val5 in array12)
						{
							if ((Object)(object)val5 == (Object)null)
							{
								continue;
							}
							string name = ((object)val5).GetType().Name;
							if (name != "TMP_Text" && name != "TextMeshProUGUI")
							{
								continue;
							}
							try
							{
								string text = ((object)val5).GetType().GetProperty("text", BindingFlags.Instance | BindingFlags.Public)?.GetValue(val5) as string;
								if (string.IsNullOrEmpty(text) || (text.IndexOf("modded version", StringComparison.OrdinalIgnoreCase) < 0 && text.IndexOf("uninstall all mods", StringComparison.OrdinalIgnoreCase) < 0))
								{
									continue;
								}
								Transform parent = val5.transform.parent;
								bool flag = (Object)(object)parent != (Object)null;
								if (flag)
								{
									string[] array13 = array8;
									foreach (string value4 in array13)
									{
										if (((Object)parent).name.IndexOf(value4, StringComparison.OrdinalIgnoreCase) >= 0)
										{
											flag = false;
											break;
										}
									}
								}
								if (flag && (Object)(object)parent != (Object)null)
								{
									((Component)parent).gameObject.SetActive(false);
									Log.LogInfo((object)("Hidden modded warning TMP (parent): " + ((Object)parent).name));
								}
								else
								{
									val5.gameObject.SetActive(false);
									Log.LogInfo((object)("Hidden modded warning TMP: " + ((Object)val5.gameObject).name));
								}
							}
							catch
							{
							}
						}
					}
					catch (Exception ex)
					{
						Log.LogDebug((object)("Text search for modded warning failed: " + ex.Message));
					}
				}
				catch (Exception ex2)
				{
					Log.LogWarning((object)("HideMenuElements failed: " + ex2.GetType().Name + ": " + ex2.Message));
				}
			}

			public static void TryInjectPlayAuroraButtonAboveStart(FejdStartup fs, Action onClick)
			{
				//IL_015f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0169: Expected O, but got Unknown
				//IL_0178: Unknown result type (might be due to invalid IL or missing references)
				//IL_0182: Expected O, but got Unknown
				if ((Object)(object)fs == (Object)null || ((Component)fs).GetComponentsInChildren<Transform>(true).Any((Transform t) => ((Object)t).name == "AuroraQuickConnect__PlayAuroraButton"))
				{
					return;
				}
				Button[] componentsInChildren = ((Component)fs).GetComponentsInChildren<Button>(true);
				if (componentsInChildren == null || componentsInChildren.Length == 0)
				{
					Log.LogWarning((object)"No UI Buttons found under FejdStartup. Can't inject Play Aurora.");
					return;
				}
				Button val = ((IEnumerable<Button>)componentsInChildren).FirstOrDefault((Func<Button, bool>)((Button b) => LabelContains(((Component)b).gameObject, "Start Game"))) ?? ((IEnumerable<Button>)componentsInChildren).FirstOrDefault((Func<Button, bool>)((Button b) => LabelContains(((Component)b).gameObject, "Start"))) ?? ((IEnumerable<Button>)componentsInChildren).FirstOrDefault((Func<Button, bool>)((Button b) => HasAnyLabel(((Component)b).gameObject))) ?? componentsInChildren[0];
				Transform parent = ((Component)val).transform.parent;
				GameObject val2 = Object.Instantiate<GameObject>(((Component)val).gameObject, parent);
				((Object)val2).name = "AuroraQuickConnect__PlayAuroraButton";
				val2.SetActive(true);
				val2.transform.SetSiblingIndex(0);
				SetButtonLabel(val2, _buttonText);
				Button component = val2.GetComponent<Button>();
				if ((Object)(object)component == (Object)null)
				{
					Object.Destroy((Object)(object)val2);
					return;
				}
				component.onClick = new ButtonClickedEvent();
				((UnityEvent)component.onClick).AddListener(new UnityAction(onClick.Invoke));
				Log.LogInfo((object)("Injected '" + _buttonText + "' button (template='" + ((Object)val).name + "')."));
			}

			public static bool TryInvokeVoidBestEffort(object instance, string methodName)
			{
				string methodName2 = methodName;
				try
				{
					Type type = instance.GetType();
					MethodInfo[] array = (from m in type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
						where m.Name == methodName2 && m.ReturnType == typeof(void)
						select m).ToArray();
					if (array.Length == 0)
					{
						return false;
					}
					MethodInfo methodInfo = array.FirstOrDefault((MethodInfo m) => m.GetParameters().Length == 0);
					if (methodInfo != null)
					{
						methodInfo.Invoke(instance, Array.Empty<object>());
						return true;
					}
					MethodInfo methodInfo2 = array.FirstOrDefault((MethodInfo m) => m.GetParameters().Length == 1);
					if (methodInfo2 != null)
					{
						Type parameterType = methodInfo2.GetParameters()[0].ParameterType;
						object obj = null;
						if (parameterType == typeof(bool))
						{
							obj = false;
						}
						else if (parameterType == typeof(int))
						{
							obj = 0;
						}
						else if (parameterType == typeof(float))
						{
							obj = 0f;
						}
						else
						{
							if (!(parameterType == typeof(string)))
							{
								return false;
							}
							obj = "";
						}
						methodInfo2.Invoke(instance, new object[1] { obj });
						return true;
					}
				}
				catch
				{
				}
				return false;
			}

			public static bool ClickButtonByLabel(FejdStartup fs, string[] include, string[] exclude)
			{
				Button val = FindButtonByLabel(fs, include, exclude);
				if ((Object)(object)val == (Object)null)
				{
					return false;
				}
				ButtonClickedEvent onClick = val.onClick;
				if (onClick != null)
				{
					((UnityEvent)onClick).Invoke();
				}
				return true;
			}

			private static Button? FindButtonByLabel(FejdStartup fs, string[] include, string[] exclude)
			{
				if ((Object)(object)fs == (Object)null)
				{
					return null;
				}
				Button[] componentsInChildren = ((Component)fs).GetComponentsInChildren<Button>(true);
				if (componentsInChildren == null)
				{
					return null;
				}
				Button[] array = componentsInChildren;
				foreach (Button val in array)
				{
					if ((Object)(object)val == (Object)null || !((Component)val).gameObject.activeInHierarchy)
					{
						continue;
					}
					string anyLabelText = GetAnyLabelText(((Component)val).gameObject);
					if (!string.IsNullOrEmpty(anyLabelText))
					{
						string lower = anyLabelText.ToLowerInvariant();
						if (!exclude.Any((string e) => lower.Contains(e.ToLowerInvariant())) && include.All((string i) => lower.Contains(i.ToLowerInvariant())))
						{
							return val;
						}
					}
				}
				return null;
			}

			public static void TryFillJoinByIp(FejdStartup fs, string hostAndPort, string password)
			{
				TrySetInputByFieldName(fs, new string[7] { "m_joinIPAddress", "m_joinIpAddress", "m_joinIP", "m_joinIp", "m_serverIP", "m_serverAddress", "m_serverHost" }, hostAndPort);
				if (!string.IsNullOrEmpty(password))
				{
					TrySetInputByFieldName(fs, new string[4] { "m_joinPassword", "m_password", "m_serverPassword", "m_joinServerPassword" }, password);
				}
			}

			private static void TrySetInputByFieldName(object instance, string[] fieldNames, string value)
			{
				foreach (string text in fieldNames)
				{
					try
					{
						FieldInfo fieldInfo = AccessTools.Field(instance.GetType(), text);
						if (fieldInfo == null)
						{
							continue;
						}
						object value2 = fieldInfo.GetValue(instance);
						if (value2 != null)
						{
							InputField val = (InputField)((value2 is InputField) ? value2 : null);
							if (val != null)
							{
								val.text = value;
								break;
							}
							Type type = value2.GetType();
							if (type.Name == "TMP_InputField")
							{
								type.GetProperty("text", BindingFlags.Instance | BindingFlags.Public)?.SetValue(value2, value);
								break;
							}
						}
					}
					catch
					{
					}
				}
			}

			private static bool LabelContains(GameObject go, string text)
			{
				string anyLabelText = GetAnyLabelText(go);
				return anyLabelText != null && anyLabelText.IndexOf(text, StringComparison.OrdinalIgnoreCase) >= 0;
			}

			private static bool HasAnyLabel(GameObject go)
			{
				return !string.IsNullOrEmpty(GetAnyLabelText(go));
			}

			private static string? GetAnyLabelText(GameObject go)
			{
				if ((Object)(object)go == (Object)null)
				{
					return null;
				}
				try
				{
					Component val = ((IEnumerable<Component>)go.GetComponentsInChildren<Component>(true)).FirstOrDefault((Func<Component, bool>)((Component c) => (Object)(object)c != (Object)null && (((object)c).GetType().Name == "TMP_Text" || ((object)c).GetType().Name == "TextMeshProUGUI")));
					if ((Object)(object)val != (Object)null)
					{
						string text = ((object)val).GetType().GetProperty("text", BindingFlags.Instance | BindingFlags.Public)?.GetValue(val) as string;
						if (!string.IsNullOrEmpty(text))
						{
							return text;
						}
					}
				}
				catch
				{
				}
				Text componentInChildren = go.GetComponentInChildren<Text>(true);
				if ((Object)(object)componentInChildren != (Object)null && !string.IsNullOrEmpty(componentInChildren.text))
				{
					return componentInChildren.text;
				}
				return null;
			}

			private static void SetButtonLabel(GameObject buttonGo, string label)
			{
				if ((Object)(object)buttonGo == (Object)null)
				{
					return;
				}
				try
				{
					Component val = ((IEnumerable<Component>)buttonGo.GetComponentsInChildren<Component>(true)).FirstOrDefault((Func<Component, bool>)((Component c) => (Object)(object)c != (Object)null && (((object)c).GetType().Name == "TMP_Text" || ((object)c).GetType().Name == "TextMeshProUGUI")));
					if ((Object)(object)val != (Object)null)
					{
						((object)val).GetType().GetProperty("text", BindingFlags.Instance | BindingFlags.Public)?.SetValue(val, label);
						return;
					}
				}
				catch
				{
				}
				Text componentInChildren = buttonGo.GetComponentInChildren<Text>(true);
				if ((Object)(object)componentInChildren != (Object)null)
				{
					componentInChildren.text = label;
				}
			}
		}

		[CompilerGenerated]
		private sealed class <ConnectToServerRoutine>d__40 : IEnumerator<object>, IDisposable, IEnumerator
		{
			private int <>1__state;

			private object <>2__current;

			public FejdStartup fs;

			private string <hostAndPort>5__1;

			private int <attempt>5__2;

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

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

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

			[DebuggerHidden]
			void IDisposable.Dispose()
			{
				<hostAndPort>5__1 = null;
				<>1__state = -2;
			}

			private bool MoveNext()
			{
				//IL_0061: Unknown result type (might be due to invalid IL or missing references)
				//IL_006b: Expected O, but got Unknown
				//IL_0123: Unknown result type (might be due to invalid IL or missing references)
				//IL_012d: Expected O, but got Unknown
				switch (<>1__state)
				{
				default:
					return false;
				case 0:
					<>1__state = -1;
					<>2__current = null;
					<>1__state = 1;
					return true;
				case 1:
					<>1__state = -1;
					if (_uiSettleDelay > 0f)
					{
						<>2__current = (object)new WaitForSecondsRealtime(_uiSettleDelay);
						<>1__state = 2;
						return true;
					}
					goto IL_007b;
				case 2:
					<>1__state = -1;
					goto IL_007b;
				case 3:
					{
						<>1__state = -1;
						<attempt>5__2++;
						break;
					}
					IL_007b:
					<hostAndPort>5__1 = $"{_host}:{_port}";
					Log.LogInfo((object)("Aurora QuickConnect: attempting direct join to " + <hostAndPort>5__1));
					<attempt>5__2 = 1;
					break;
				}
				if (<attempt>5__2 <= _joinAttempts)
				{
					Log.LogInfo((object)$"Join attempt {<attempt>5__2}/{_joinAttempts}");
					if (Joiner.TryJoin(fs, _host, _port, _password))
					{
						Log.LogInfo((object)"Aurora QuickConnect: join triggered successfully.");
						return false;
					}
					<>2__current = (object)new WaitForSecondsRealtime(_joinAttemptInterval);
					<>1__state = 3;
					return true;
				}
				Log.LogWarning((object)"Aurora QuickConnect: Failed to start connection (no compatible join method found).");
				if (_debugDumpOnFail)
				{
					Log.LogWarning((object)"Dumping join diagnostics (Debug.DumpJoinMethodsOnFail=true) ...");
					Joiner.DumpJoinMethods(fs);
				}
				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();
			}
		}

		[CompilerGenerated]
		private sealed class <HideUiElementsDelayed>d__36 : IEnumerator<object>, IDisposable, IEnumerator
		{
			private int <>1__state;

			private object <>2__current;

			public FejdStartup fs;

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

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

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

			[DebuggerHidden]
			void IDisposable.Dispose()
			{
				<>1__state = -2;
			}

			private bool MoveNext()
			{
				//IL_0048: Unknown result type (might be due to invalid IL or missing references)
				//IL_0052: Expected O, but got Unknown
				switch (<>1__state)
				{
				default:
					return false;
				case 0:
					<>1__state = -1;
					<>2__current = null;
					<>1__state = 1;
					return true;
				case 1:
					<>1__state = -1;
					<>2__current = (object)new WaitForSeconds(0.1f);
					<>1__state = 2;
					return true;
				case 2:
					<>1__state = -1;
					Ui.HideMenuElements(fs, _hideChangelog, _hideMerchStore, _hideModdedWarning);
					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();
			}
		}

		public const string PluginGuid = "com.aurora.quickconnect";

		public const string PluginName = "AuroraQuickConnect";

		public const string PluginVersion = "1.2.1";

		private static ManualLogSource Log = null;

		private static Harmony _harmony = null;

		private static bool _pending;

		private static Coroutine? _connectRoutine;

		private static string _host = "85.206.119.102";

		private static int _port = 2456;

		private static string _password = "";

		private static string _buttonText = "Play Aurora";

		private static int _joinAttempts = 10;

		private static float _joinAttemptInterval = 0.25f;

		private static float _uiSettleDelay = 0.15f;

		private static bool _debugDumpOnFail = true;

		private static bool _hideChangelog = true;

		private static bool _hideMerchStore = true;

		private static bool _hideModdedWarning = true;

		private ConfigEntry<string> _cfgHost = null;

		private ConfigEntry<int> _cfgPort = null;

		private ConfigEntry<string> _cfgPassword = null;

		private ConfigEntry<string> _cfgButtonText = null;

		private ConfigEntry<int> _cfgJoinAttempts = null;

		private ConfigEntry<float> _cfgJoinAttemptInterval = null;

		private ConfigEntry<float> _cfgUiSettleDelay = null;

		private ConfigEntry<bool> _cfgDebugDumpOnFail = null;

		private ConfigEntry<bool> _cfgHideChangelog = null;

		private ConfigEntry<bool> _cfgHideMerchStore = null;

		private ConfigEntry<bool> _cfgHideModdedWarning = null;

		private void Awake()
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Expected O, but got Unknown
			Log = ((BaseUnityPlugin)this).Logger;
			try
			{
				SetupConfig();
				_harmony = new Harmony("com.aurora.quickconnect");
				PatchSafe(typeof(FejdStartup), "Start", null, "FejdStartup_Start_Postfix");
				PatchSafe(typeof(FejdStartup), "OnCharacterStart", "FejdStartup_OnCharacterStart_Prefix");
				PatchSilent(typeof(FejdStartup), "ShowMenu", null, "FejdStartup_Back_Postfix");
				Log.LogInfo((object)string.Format("{0} {1} loaded. Target={2}:{3} (password={4}).", "AuroraQuickConnect", "1.2.1", _host, _port, string.IsNullOrEmpty(_password) ? "none" : "set"));
			}
			catch (Exception arg)
			{
				Log.LogError((object)string.Format("{0} failed to load: {1}", "AuroraQuickConnect", arg));
			}
		}

		private void OnDestroy()
		{
			try
			{
				Harmony harmony = _harmony;
				if (harmony != null)
				{
					harmony.UnpatchSelf();
				}
			}
			catch
			{
			}
		}

		private void SetupConfig()
		{
			_cfgHost = ((BaseUnityPlugin)this).Config.Bind<string>("Server", "Host", "85.206.119.102", "Server IP / hostname for Aurora.");
			_cfgPort = ((BaseUnityPlugin)this).Config.Bind<int>("Server", "Port", 2456, "Server port for Aurora.");
			_cfgPassword = ((BaseUnityPlugin)this).Config.Bind<string>("Server", "Password", "", "Server password (leave blank if none).");
			_cfgButtonText = ((BaseUnityPlugin)this).Config.Bind<string>("UI", "ButtonText", "Play Aurora", "Text shown on the main-menu button.");
			_cfgHideChangelog = ((BaseUnityPlugin)this).Config.Bind<bool>("UI", "HideChangelog", true, "Hide the changelog panel on the left side of the main menu.");
			_cfgHideMerchStore = ((BaseUnityPlugin)this).Config.Bind<bool>("UI", "HideMerchStore", true, "Hide the merch store panel on the right side of the main menu.");
			_cfgHideModdedWarning = ((BaseUnityPlugin)this).Config.Bind<bool>("UI", "HideModdedWarning", true, "Hide the 'You are playing a modded version' warning message.");
			_cfgJoinAttempts = ((BaseUnityPlugin)this).Config.Bind<int>("Connect", "JoinAttempts", 10, "How many times to try triggering a join (safe retries, no spam).");
			_cfgJoinAttemptInterval = ((BaseUnityPlugin)this).Config.Bind<float>("Connect", "AttemptIntervalSeconds", 0.25f, "Seconds between join attempts.");
			_cfgUiSettleDelay = ((BaseUnityPlugin)this).Config.Bind<float>("Connect", "UiSettleDelaySeconds", 0.15f, "Small delay after clicking Start, before we trigger the join.");
			_cfgDebugDumpOnFail = ((BaseUnityPlugin)this).Config.Bind<bool>("Debug", "DumpJoinMethodsOnFail", true, "If join cannot be triggered, print join/connect method info to the log.");
			ApplyConfigSnapshot();
			_cfgHost.SettingChanged += delegate
			{
				ApplyConfigSnapshot();
			};
			_cfgPort.SettingChanged += delegate
			{
				ApplyConfigSnapshot();
			};
			_cfgPassword.SettingChanged += delegate
			{
				ApplyConfigSnapshot();
			};
			_cfgButtonText.SettingChanged += delegate
			{
				ApplyConfigSnapshot();
			};
			_cfgJoinAttempts.SettingChanged += delegate
			{
				ApplyConfigSnapshot();
			};
			_cfgJoinAttemptInterval.SettingChanged += delegate
			{
				ApplyConfigSnapshot();
			};
			_cfgUiSettleDelay.SettingChanged += delegate
			{
				ApplyConfigSnapshot();
			};
			_cfgDebugDumpOnFail.SettingChanged += delegate
			{
				ApplyConfigSnapshot();
			};
			_cfgHideChangelog.SettingChanged += delegate
			{
				ApplyConfigSnapshot();
			};
			_cfgHideMerchStore.SettingChanged += delegate
			{
				ApplyConfigSnapshot();
			};
			_cfgHideModdedWarning.SettingChanged += delegate
			{
				ApplyConfigSnapshot();
			};
			try
			{
				((BaseUnityPlugin)this).Config.Save();
				Log.LogInfo((object)("Config ready: " + ((BaseUnityPlugin)this).Config.ConfigFilePath));
			}
			catch (Exception ex)
			{
				Log.LogWarning((object)("Could not save config file: " + ex.GetType().Name + ": " + ex.Message));
			}
		}

		private void ApplyConfigSnapshot()
		{
			_host = _cfgHost.Value?.Trim() ?? "85.206.119.102";
			_port = _cfgPort.Value;
			if (_port <= 0 || _port > 65535)
			{
				_port = 2456;
			}
			_password = _cfgPassword.Value ?? "";
			_buttonText = (string.IsNullOrWhiteSpace(_cfgButtonText.Value) ? "Play Aurora" : _cfgButtonText.Value);
			_joinAttempts = Mathf.Clamp(_cfgJoinAttempts.Value, 1, 50);
			_joinAttemptInterval = Mathf.Clamp(_cfgJoinAttemptInterval.Value, 0.05f, 5f);
			_uiSettleDelay = Mathf.Clamp(_cfgUiSettleDelay.Value, 0f, 5f);
			_debugDumpOnFail = _cfgDebugDumpOnFail.Value;
			_hideChangelog = _cfgHideChangelog.Value;
			_hideMerchStore = _cfgHideMerchStore.Value;
			_hideModdedWarning = _cfgHideModdedWarning.Value;
		}

		private void PatchSafe(Type type, string methodName, string? prefix = null, string? postfix = null)
		{
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				MethodInfo methodInfo = AccessTools.Method(type, methodName, (Type[])null, (Type[])null);
				if (methodInfo == null)
				{
					Log.LogWarning((object)("[Patch] " + type.Name + "." + methodName + " not found. Skipping."));
				}
				else
				{
					HarmonyMethod val = ((prefix == null) ? ((HarmonyMethod)null) : new HarmonyMethod(typeof(AuroraQuickConnect), prefix, (Type[])null));
					HarmonyMethod val2 = ((postfix == null) ? ((HarmonyMethod)null) : new HarmonyMethod(typeof(AuroraQuickConnect), postfix, (Type[])null));
					_harmony.Patch((MethodBase)methodInfo, val, val2, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
					Log.LogInfo((object)("Patched " + type.Name + "." + methodName));
				}
			}
			catch (Exception ex)
			{
				Log.LogWarning((object)("[Patch] Failed patching " + type.Name + "." + methodName + ": " + ex.GetType().Name + ": " + ex.Message));
			}
		}

		private void PatchSilent(Type type, string methodName, string? prefix = null, string? postfix = null)
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				MethodInfo methodInfo = AccessTools.Method(type, methodName, (Type[])null, (Type[])null);
				if (!(methodInfo == null))
				{
					HarmonyMethod val = ((prefix == null) ? ((HarmonyMethod)null) : new HarmonyMethod(typeof(AuroraQuickConnect), prefix, (Type[])null));
					HarmonyMethod val2 = ((postfix == null) ? ((HarmonyMethod)null) : new HarmonyMethod(typeof(AuroraQuickConnect), postfix, (Type[])null));
					_harmony.Patch((MethodBase)methodInfo, val, val2, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
					Log.LogDebug((object)("Patched optional: " + type.Name + "." + methodName));
				}
			}
			catch
			{
			}
		}

		private static void FejdStartup_Start_Postfix(FejdStartup __instance)
		{
			FejdStartup __instance2 = __instance;
			try
			{
				Ui.TryInjectPlayAuroraButtonAboveStart(__instance2, delegate
				{
					OnPlayAuroraClicked(__instance2);
				});
				if (_hideChangelog || _hideMerchStore || _hideModdedWarning)
				{
					((MonoBehaviour)__instance2).StartCoroutine(HideUiElementsDelayed(__instance2));
				}
			}
			catch (Exception arg)
			{
				ManualLogSource log = Log;
				if (log != null)
				{
					log.LogError((object)$"FejdStartup_Start_Postfix exception: {arg}");
				}
			}
		}

		[IteratorStateMachine(typeof(<HideUiElementsDelayed>d__36))]
		private static IEnumerator HideUiElementsDelayed(FejdStartup fs)
		{
			//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
			return new <HideUiElementsDelayed>d__36(0)
			{
				fs = fs
			};
		}

		private static bool FejdStartup_OnCharacterStart_Prefix(FejdStartup __instance)
		{
			if (!_pending)
			{
				return true;
			}
			_pending = false;
			Log.LogInfo((object)$"OnCharacterStart intercepted (Play Aurora) -> joining {_host}:{_port}");
			if (_connectRoutine != null)
			{
				try
				{
					((MonoBehaviour)__instance).StopCoroutine(_connectRoutine);
				}
				catch
				{
				}
				_connectRoutine = null;
			}
			_connectRoutine = ((MonoBehaviour)__instance).StartCoroutine(ConnectToServerRoutine(__instance));
			return false;
		}

		private static void FejdStartup_Back_Postfix()
		{
			_pending = false;
		}

		private static void OnPlayAuroraClicked(FejdStartup fs)
		{
			Log.LogInfo((object)"Play Aurora clicked.");
			_pending = true;
			if (!Ui.TryInvokeVoidBestEffort(fs, "OnStartGame") && !Ui.TryInvokeVoidBestEffort(fs, "OnStart") && !Ui.ClickButtonByLabel(fs, new string[2] { "start", "game" }, Array.Empty<string>()))
			{
				Log.LogWarning((object)"Couldn't open Character Select automatically. Click Valheim's Start Game once, then click Play Aurora again.");
				_pending = false;
			}
		}

		[IteratorStateMachine(typeof(<ConnectToServerRoutine>d__40))]
		private static IEnumerator ConnectToServerRoutine(FejdStartup fs)
		{
			//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
			return new <ConnectToServerRoutine>d__40(0)
			{
				fs = fs
			};
		}
	}
}

BepInEx/plugins/AuroraWardDecay.dll

Decompiled 2 weeks ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using HarmonyLib;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("AuroraWardDecay")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("AuroraWardDecay")]
[assembly: AssemblyCopyright("Copyright ©  2025")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("91245976-b7c2-4fcd-88a9-505fe801b8e8")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace AuroraWardDecay
{
	public class Class1
	{
	}
}
namespace AuroraWardDecayMod
{
	[BepInPlugin("aurora.warddecay", "AuroraWardDecay", "1.0.5")]
	public class AuroraWardDecayPlugin : BaseUnityPlugin
	{
		[CompilerGenerated]
		private sealed class <ServerSweepLoop>d__12 : IEnumerator<object>, IDisposable, IEnumerator
		{
			private int <>1__state;

			private object <>2__current;

			public AuroraWardDecayPlugin <>4__this;

			private PrivateArea[] <wards>5__1;

			private long <nowTicks>5__2;

			private long <maxAge>5__3;

			private PrivateArea[] <>s__4;

			private int <>s__5;

			private PrivateArea <pa>5__6;

			private ZNetView <nview>5__7;

			private ZDO <zdo>5__8;

			private long <lastTouched>5__9;

			private Exception <ex>5__10;

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

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

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

			[DebuggerHidden]
			void IDisposable.Dispose()
			{
				<wards>5__1 = null;
				<>s__4 = null;
				<pa>5__6 = null;
				<nview>5__7 = null;
				<zdo>5__8 = null;
				<ex>5__10 = null;
				<>1__state = -2;
			}

			private bool MoveNext()
			{
				//IL_0031: Unknown result type (might be due to invalid IL or missing references)
				//IL_003b: Expected O, but got Unknown
				switch (<>1__state)
				{
				default:
					return false;
				case 0:
					<>1__state = -1;
					break;
				case 1:
					<>1__state = -1;
					if ((Object)(object)ZNet.instance == (Object)null || !ZNet.instance.IsServer())
					{
						break;
					}
					try
					{
						<wards>5__1 = Object.FindObjectsOfType<PrivateArea>();
						if (<wards>5__1 == null || <wards>5__1.Length == 0)
						{
							break;
						}
						<nowTicks>5__2 = NowTicks();
						<maxAge>5__3 = DaysToTicks(DecayDays.Value);
						<>s__4 = <wards>5__1;
						for (<>s__5 = 0; <>s__5 < <>s__4.Length; <>s__5++)
						{
							<pa>5__6 = <>s__4[<>s__5];
							if (Object.op_Implicit((Object)(object)<pa>5__6))
							{
								<nview>5__7 = ((Component)<pa>5__6).GetComponent<ZNetView>();
								if (Object.op_Implicit((Object)(object)<nview>5__7) && <nview>5__7.IsValid())
								{
									<zdo>5__8 = <nview>5__7.GetZDO();
									if (<zdo>5__8 != null)
									{
										<lastTouched>5__9 = <zdo>5__8.GetLong("aurora_lastTouched_ticks", 0L);
										if (<lastTouched>5__9 <= 0)
										{
											<zdo>5__8.Set("aurora_lastTouched_ticks", <nowTicks>5__2);
										}
										else
										{
											if (<nowTicks>5__2 - <lastTouched>5__9 >= <maxAge>5__3)
											{
												Object.Destroy((Object)(object)((Component)<pa>5__6).gameObject);
											}
											<nview>5__7 = null;
											<zdo>5__8 = null;
											<pa>5__6 = null;
										}
									}
								}
							}
						}
						<>s__4 = null;
						<wards>5__1 = null;
					}
					catch (Exception ex)
					{
						<ex>5__10 = ex;
						((BaseUnityPlugin)<>4__this).Logger.LogError((object)$"Ward decay sweep failed: {<ex>5__10}");
					}
					break;
				}
				<>2__current = (object)new WaitForSeconds(CheckIntervalSeconds.Value);
				<>1__state = 1;
				return true;
			}

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

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

		public const string PluginGuid = "aurora.warddecay";

		public const string PluginName = "AuroraWardDecay";

		public const string PluginVersion = "1.0.5";

		internal const string ZdoKeyLastTouchedTicks = "aurora_lastTouched_ticks";

		internal static ConfigEntry<float> CheckIntervalSeconds;

		internal static ConfigEntry<double> DecayDays;

		internal static ConfigEntry<bool> RefreshOnInteractOnly;

		internal static ConfigEntry<bool> EnableHoverText;

		internal static ConfigEntry<string> HoverFormat;

		private Harmony _harmony;

		private void Awake()
		{
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c1: Expected O, but got Unknown
			CheckIntervalSeconds = ((BaseUnityPlugin)this).Config.Bind<float>("General", "CheckIntervalSeconds", 30f, "How often the server checks for expired wards.");
			DecayDays = ((BaseUnityPlugin)this).Config.Bind<double>("General", "DecayDays", 7.0, "Days without interaction before a ward expires.");
			RefreshOnInteractOnly = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "RefreshOnInteractOnly", true, "If true, only Interact() refreshes the timer (placement always seeds).");
			EnableHoverText = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "EnableHoverText", true, "Show remaining time on ward hover.");
			HoverFormat = ((BaseUnityPlugin)this).Config.Bind<string>("General", "HoverFormat", "<color=yellow><b>Upkeep:</b></color> {0}", "Format for remaining time; {0}=time left.");
			_harmony = new Harmony("aurora.warddecay");
			_harmony.PatchAll();
			((MonoBehaviour)this).StartCoroutine(ServerSweepLoop());
			((BaseUnityPlugin)this).Logger.LogInfo((object)"AuroraWardDecay 1.0.5 loaded");
		}

		private void OnDestroy()
		{
			try
			{
				Harmony harmony = _harmony;
				if (harmony != null)
				{
					harmony.UnpatchSelf();
				}
			}
			catch
			{
			}
		}

		[IteratorStateMachine(typeof(<ServerSweepLoop>d__12))]
		private IEnumerator ServerSweepLoop()
		{
			//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
			return new <ServerSweepLoop>d__12(0)
			{
				<>4__this = this
			};
		}

		internal static long NowTicks()
		{
			return (((Object)(object)ZNet.instance != (Object)null) ? ZNet.instance.GetTime() : DateTime.UtcNow).ToUniversalTime().Ticks;
		}

		internal static long DaysToTicks(double days)
		{
			return TimeSpan.FromDays(days).Ticks;
		}

		internal static string FormatRemaining(long nowTicks, long lastTouchedTicks, double days)
		{
			long num = DaysToTicks(days);
			long num2 = ((lastTouchedTicks > 0) ? Math.Max(0L, num - (nowTicks - lastTouchedTicks)) : num);
			if (num2 <= 0)
			{
				return "expired";
			}
			TimeSpan timeSpan = TimeSpan.FromTicks(num2);
			if (timeSpan.TotalDays >= 1.0)
			{
				return $"{(int)timeSpan.TotalDays}d {timeSpan.Hours}h";
			}
			if (timeSpan.TotalHours >= 1.0)
			{
				return $"{(int)timeSpan.TotalHours}h {timeSpan.Minutes}m";
			}
			return $"{timeSpan.Minutes}m {timeSpan.Seconds}s";
		}
	}
	internal static class SeedHelper
	{
		public static void Seed(PrivateArea pa)
		{
			if (!Object.op_Implicit((Object)(object)pa))
			{
				return;
			}
			ZNetView component = ((Component)pa).GetComponent<ZNetView>();
			if (Object.op_Implicit((Object)(object)component) && component.IsValid())
			{
				ZDO zDO = component.GetZDO();
				if (zDO != null && zDO.GetLong("aurora_lastTouched_ticks", 0L) == 0)
				{
					zDO.Set("aurora_lastTouched_ticks", AuroraWardDecayPlugin.NowTicks());
				}
			}
		}
	}
	[HarmonyPatch(typeof(PrivateArea), "Awake")]
	public static class Patch_PrivateArea_Awake_Seed
	{
		private static void Postfix(PrivateArea __instance)
		{
			SeedHelper.Seed(__instance);
		}
	}
	[HarmonyPatch(typeof(PrivateArea), "Interact")]
	public static class Patch_PrivateArea_Interact
	{
		private static void Postfix(PrivateArea __instance, bool __result, Humanoid human, bool hold, bool alt)
		{
			if (!__result || !AuroraWardDecayPlugin.RefreshOnInteractOnly.Value)
			{
				return;
			}
			ZNetView component = ((Component)__instance).GetComponent<ZNetView>();
			if (Object.op_Implicit((Object)(object)component) && component.IsValid())
			{
				ZDO zDO = component.GetZDO();
				if (zDO != null)
				{
					zDO.Set("aurora_lastTouched_ticks", AuroraWardDecayPlugin.NowTicks());
				}
			}
		}
	}
	[HarmonyPatch(typeof(PrivateArea), "GetHoverText")]
	public static class Patch_PrivateArea_GetHoverText
	{
		private static void Postfix(PrivateArea __instance, ref string __result)
		{
			if (!AuroraWardDecayPlugin.EnableHoverText.Value)
			{
				return;
			}
			ZNetView component = ((Component)__instance).GetComponent<ZNetView>();
			if (!Object.op_Implicit((Object)(object)component) || !component.IsValid())
			{
				return;
			}
			ZDO zDO = component.GetZDO();
			if (zDO != null)
			{
				long @long = zDO.GetLong("aurora_lastTouched_ticks", 0L);
				long nowTicks = AuroraWardDecayPlugin.NowTicks();
				string arg = AuroraWardDecayPlugin.FormatRemaining(nowTicks, @long, AuroraWardDecayPlugin.DecayDays.Value);
				StringBuilder stringBuilder = new StringBuilder(__result ?? string.Empty);
				if (!stringBuilder.ToString().EndsWith("\n"))
				{
					stringBuilder.Append('\n');
				}
				stringBuilder.AppendFormat(AuroraWardDecayPlugin.HoverFormat.Value, arg);
				__result = stringBuilder.ToString();
			}
		}
	}
}

BepInEx/plugins/Ethereal.dll

Decompiled 2 weeks ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyCompany("Aurora Server")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyDescription("Ethereal donor reward system - auras and colored names for supporters")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("Ethereal")]
[assembly: AssemblyTitle("Ethereal")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace Ethereal
{
	public static class AuraManager
	{
		private const string AuraObjectName = "EtherealAura";

		private static Dictionary<Player, GameObject> _activeAuras = new Dictionary<Player, GameObject>();

		private static Dictionary<Player, float> _rainbowHue = new Dictionary<Player, float>();

		public static void ApplyAura(Player player, string colorName)
		{
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Expected O, but got Unknown
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)player == (Object)null)
			{
				return;
			}
			RemoveAura(player);
			if (!(colorName == "None") && !string.IsNullOrEmpty(colorName))
			{
				Color auraColor = EtherealPlugin.GetAuraColor(colorName);
				GameObject val = new GameObject("EtherealAura");
				val.transform.SetParent(((Component)player).transform);
				val.transform.localPosition = new Vector3(0f, 1f, 0f);
				EtherealAuraEffect etherealAuraEffect = val.AddComponent<EtherealAuraEffect>();
				etherealAuraEffect.Initialize(colorName, auraColor, player);
				_activeAuras[player] = val;
				if (colorName == "Rainbow")
				{
					_rainbowHue[player] = 0f;
				}
				EtherealPlugin.Log.LogInfo((object)("Applied " + colorName + " aura to " + player.GetPlayerName()));
			}
		}

		public static void RemoveAura(Player player)
		{
			if ((Object)(object)player == (Object)null)
			{
				return;
			}
			if (_activeAuras.TryGetValue(player, out var value))
			{
				if ((Object)(object)value != (Object)null)
				{
					Object.Destroy((Object)(object)value);
				}
				_activeAuras.Remove(player);
			}
			_rainbowHue.Remove(player);
			Transform val = ((Component)player).transform.Find("AuraTrail");
			if ((Object)(object)val != (Object)null)
			{
				Object.Destroy((Object)(object)((Component)val).gameObject);
			}
			Transform val2 = ((Component)player).transform.Find("EtherealAura");
			if ((Object)(object)val2 != (Object)null)
			{
				Object.Destroy((Object)(object)((Component)val2).gameObject);
			}
		}

		public static void UpdateAllAuras()
		{
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			List<Player> list = new List<Player>(_rainbowHue.Keys);
			foreach (Player item in list)
			{
				if (!((Object)(object)item == (Object)null) && _activeAuras.TryGetValue(item, out var value) && (Object)(object)value != (Object)null)
				{
					EtherealAuraEffect component = value.GetComponent<EtherealAuraEffect>();
					if ((Object)(object)component != (Object)null)
					{
						float num = (_rainbowHue[item] + Time.deltaTime * 0.2f) % 1f;
						_rainbowHue[item] = num;
						Color newColor = Color.HSVToRGB(num, 0.8f, 1f);
						component.UpdateColor(newColor);
					}
				}
			}
		}

		public static void CleanupDeadAuras()
		{
			List<Player> list = new List<Player>();
			foreach (KeyValuePair<Player, GameObject> activeAura in _activeAuras)
			{
				if ((Object)(object)activeAura.Key == (Object)null || (Object)(object)activeAura.Value == (Object)null)
				{
					list.Add(activeAura.Key);
				}
			}
			foreach (Player item in list)
			{
				_activeAuras.Remove(item);
				_rainbowHue.Remove(item);
			}
		}

		public static void ApplyAurasToAllPlayers()
		{
			foreach (Player allPlayer in Player.GetAllPlayers())
			{
				if (!((Object)(object)allPlayer == (Object)null))
				{
					string playerName = allPlayer.GetPlayerName();
					EtherealPlayerData etherealData = EtherealPlugin.GetEtherealData(playerName);
					if (etherealData != null && etherealData.SelectedColor != "None" && (!_activeAuras.ContainsKey(allPlayer) || (Object)(object)_activeAuras[allPlayer] == (Object)null))
					{
						ApplyAura(allPlayer, etherealData.SelectedColor);
					}
				}
			}
		}

		public static bool HasAura(Player player)
		{
			return _activeAuras.ContainsKey(player) && (Object)(object)_activeAuras[player] != (Object)null;
		}
	}
	public class EtherealAuraEffect : MonoBehaviour
	{
		private string _colorName;

		private Color _baseColor;

		private Light _auraLight;

		private ParticleSystem _particleSystem;

		private ParticleSystem _sparkleSystem;

		private ParticleSystem _trailSystem;

		private float _pulseTime = 0f;

		private Player _player;

		private Vector3 _lastPosition;

		private float _trailEmissionTimer = 0f;

		public void Initialize(string colorName, Color color, Player player)
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			_colorName = colorName;
			_baseColor = color;
			_player = player;
			_lastPosition = (((Object)(object)player != (Object)null) ? ((Component)player).transform.position : Vector3.zero);
			CreatePointLight();
			CreateMainParticles();
			CreateSparkleParticles();
			CreateTrailParticles();
		}

		private void CreatePointLight()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Expected O, but got Unknown
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject("AuraLight");
			val.transform.SetParent(((Component)this).transform);
			val.transform.localPosition = Vector3.zero;
			_auraLight = val.AddComponent<Light>();
			_auraLight.type = (LightType)2;
			_auraLight.color = _baseColor;
			_auraLight.intensity = 1.5f;
			_auraLight.range = 4f;
			_auraLight.shadows = (LightShadows)0;
		}

		private void CreateMainParticles()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Expected O, but got Unknown
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_0117: Unknown result type (might be due to invalid IL or missing references)
			//IL_011c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0127: Unknown result type (might be due to invalid IL or missing references)
			//IL_012e: Expected O, but got Unknown
			//IL_0139: Unknown result type (might be due to invalid IL or missing references)
			//IL_0143: Unknown result type (might be due to invalid IL or missing references)
			//IL_0148: Unknown result type (might be due to invalid IL or missing references)
			//IL_0150: Unknown result type (might be due to invalid IL or missing references)
			//IL_015a: Unknown result type (might be due to invalid IL or missing references)
			//IL_015f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0176: Unknown result type (might be due to invalid IL or missing references)
			//IL_017b: Unknown result type (might be due to invalid IL or missing references)
			//IL_018c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0191: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_01dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f4: Expected O, but got Unknown
			//IL_0233: Unknown result type (might be due to invalid IL or missing references)
			//IL_0244: Unknown result type (might be due to invalid IL or missing references)
			//IL_0249: Unknown result type (might be due to invalid IL or missing references)
			//IL_025b: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject("AuraParticles");
			val.transform.SetParent(((Component)this).transform);
			val.transform.localPosition = Vector3.zero;
			_particleSystem = val.AddComponent<ParticleSystem>();
			MainModule main = _particleSystem.main;
			((MainModule)(ref main)).loop = true;
			((MainModule)(ref main)).startLifetime = MinMaxCurve.op_Implicit(2f);
			((MainModule)(ref main)).startSpeed = MinMaxCurve.op_Implicit(0.3f);
			((MainModule)(ref main)).startSize = MinMaxCurve.op_Implicit(0.15f);
			((MainModule)(ref main)).maxParticles = 50;
			((MainModule)(ref main)).simulationSpace = (ParticleSystemSimulationSpace)1;
			((MainModule)(ref main)).startColor = MinMaxGradient.op_Implicit(new Color(_baseColor.r, _baseColor.g, _baseColor.b, 0.6f));
			EmissionModule emission = _particleSystem.emission;
			((EmissionModule)(ref emission)).rateOverTime = MinMaxCurve.op_Implicit(20f);
			ShapeModule shape = _particleSystem.shape;
			((ShapeModule)(ref shape)).shapeType = (ParticleSystemShapeType)0;
			((ShapeModule)(ref shape)).radius = 0.5f;
			ColorOverLifetimeModule colorOverLifetime = _particleSystem.colorOverLifetime;
			((ColorOverLifetimeModule)(ref colorOverLifetime)).enabled = true;
			Gradient val2 = new Gradient();
			val2.SetKeys((GradientColorKey[])(object)new GradientColorKey[2]
			{
				new GradientColorKey(_baseColor, 0f),
				new GradientColorKey(_baseColor, 1f)
			}, (GradientAlphaKey[])(object)new GradientAlphaKey[4]
			{
				new GradientAlphaKey(0f, 0f),
				new GradientAlphaKey(0.6f, 0.3f),
				new GradientAlphaKey(0.6f, 0.7f),
				new GradientAlphaKey(0f, 1f)
			});
			((ColorOverLifetimeModule)(ref colorOverLifetime)).color = MinMaxGradient.op_Implicit(val2);
			SizeOverLifetimeModule sizeOverLifetime = _particleSystem.sizeOverLifetime;
			((SizeOverLifetimeModule)(ref sizeOverLifetime)).enabled = true;
			AnimationCurve val3 = new AnimationCurve();
			val3.AddKey(0f, 0.5f);
			val3.AddKey(0.5f, 1f);
			val3.AddKey(1f, 0f);
			((SizeOverLifetimeModule)(ref sizeOverLifetime)).size = new MinMaxCurve(1f, val3);
			VelocityOverLifetimeModule velocityOverLifetime = _particleSystem.velocityOverLifetime;
			((VelocityOverLifetimeModule)(ref velocityOverLifetime)).enabled = true;
			((VelocityOverLifetimeModule)(ref velocityOverLifetime)).y = MinMaxCurve.op_Implicit(0.5f);
			ParticleSystemRenderer component = val.GetComponent<ParticleSystemRenderer>();
			component.renderMode = (ParticleSystemRenderMode)0;
			((Renderer)component).material = CreateParticleMaterial();
		}

		private void CreateSparkleParticles()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Expected O, but got Unknown
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00af: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0105: Unknown result type (might be due to invalid IL or missing references)
			//IL_010a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0115: Unknown result type (might be due to invalid IL or missing references)
			//IL_011c: Expected O, but got Unknown
			//IL_0126: Unknown result type (might be due to invalid IL or missing references)
			//IL_0130: Unknown result type (might be due to invalid IL or missing references)
			//IL_0135: Unknown result type (might be due to invalid IL or missing references)
			//IL_013d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0147: Unknown result type (might be due to invalid IL or missing references)
			//IL_014c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0153: Unknown result type (might be due to invalid IL or missing references)
			//IL_015d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0162: Unknown result type (might be due to invalid IL or missing references)
			//IL_0179: Unknown result type (might be due to invalid IL or missing references)
			//IL_017e: Unknown result type (might be due to invalid IL or missing references)
			//IL_018f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0194: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_01da: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e1: Expected O, but got Unknown
			//IL_0244: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject("AuraSparkles");
			val.transform.SetParent(((Component)this).transform);
			val.transform.localPosition = Vector3.zero;
			_sparkleSystem = val.AddComponent<ParticleSystem>();
			MainModule main = _sparkleSystem.main;
			((MainModule)(ref main)).loop = true;
			((MainModule)(ref main)).startLifetime = MinMaxCurve.op_Implicit(1f);
			((MainModule)(ref main)).startSpeed = MinMaxCurve.op_Implicit(0f);
			((MainModule)(ref main)).startSize = MinMaxCurve.op_Implicit(0.08f);
			((MainModule)(ref main)).maxParticles = 30;
			((MainModule)(ref main)).simulationSpace = (ParticleSystemSimulationSpace)1;
			((MainModule)(ref main)).startColor = MinMaxGradient.op_Implicit(new Color(1f, 1f, 1f, 0.8f));
			EmissionModule emission = _sparkleSystem.emission;
			((EmissionModule)(ref emission)).rateOverTime = MinMaxCurve.op_Implicit(15f);
			ShapeModule shape = _sparkleSystem.shape;
			((ShapeModule)(ref shape)).shapeType = (ParticleSystemShapeType)0;
			((ShapeModule)(ref shape)).radius = 0.8f;
			ColorOverLifetimeModule colorOverLifetime = _sparkleSystem.colorOverLifetime;
			((ColorOverLifetimeModule)(ref colorOverLifetime)).enabled = true;
			Gradient val2 = new Gradient();
			val2.SetKeys((GradientColorKey[])(object)new GradientColorKey[3]
			{
				new GradientColorKey(Color.white, 0f),
				new GradientColorKey(_baseColor, 0.5f),
				new GradientColorKey(Color.white, 1f)
			}, (GradientAlphaKey[])(object)new GradientAlphaKey[3]
			{
				new GradientAlphaKey(0f, 0f),
				new GradientAlphaKey(1f, 0.5f),
				new GradientAlphaKey(0f, 1f)
			});
			((ColorOverLifetimeModule)(ref colorOverLifetime)).color = MinMaxGradient.op_Implicit(val2);
			SizeOverLifetimeModule sizeOverLifetime = _sparkleSystem.sizeOverLifetime;
			((SizeOverLifetimeModule)(ref sizeOverLifetime)).enabled = true;
			AnimationCurve val3 = new AnimationCurve();
			val3.AddKey(0f, 0f);
			val3.AddKey(0.2f, 1f);
			val3.AddKey(0.5f, 0.3f);
			val3.AddKey(0.8f, 1f);
			val3.AddKey(1f, 0f);
			((SizeOverLifetimeModule)(ref sizeOverLifetime)).size = new MinMaxCurve(1f, val3);
			ParticleSystemRenderer component = val.GetComponent<ParticleSystemRenderer>();
			component.renderMode = (ParticleSystemRenderMode)0;
			((Renderer)component).material = CreateParticleMaterial();
		}

		private void CreateTrailParticles()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Expected O, but got Unknown
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_00da: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_010f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0120: Unknown result type (might be due to invalid IL or missing references)
			//IL_0125: Unknown result type (might be due to invalid IL or missing references)
			//IL_0135: Unknown result type (might be due to invalid IL or missing references)
			//IL_013a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0145: Unknown result type (might be due to invalid IL or missing references)
			//IL_014c: Expected O, but got Unknown
			//IL_0157: Unknown result type (might be due to invalid IL or missing references)
			//IL_0161: Unknown result type (might be due to invalid IL or missing references)
			//IL_0166: Unknown result type (might be due to invalid IL or missing references)
			//IL_016e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0178: Unknown result type (might be due to invalid IL or missing references)
			//IL_017d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0185: Unknown result type (might be due to invalid IL or missing references)
			//IL_018f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0199: Unknown result type (might be due to invalid IL or missing references)
			//IL_019e: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0206: Unknown result type (might be due to invalid IL or missing references)
			//IL_020b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0216: Unknown result type (might be due to invalid IL or missing references)
			//IL_021d: Expected O, but got Unknown
			//IL_024a: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject("AuraTrail");
			val.transform.SetParent(((Component)this).transform.parent);
			val.transform.localPosition = new Vector3(0f, 0.1f, 0f);
			_trailSystem = val.AddComponent<ParticleSystem>();
			MainModule main = _trailSystem.main;
			((MainModule)(ref main)).loop = true;
			((MainModule)(ref main)).startLifetime = MinMaxCurve.op_Implicit(2f);
			((MainModule)(ref main)).startSpeed = MinMaxCurve.op_Implicit(0f);
			((MainModule)(ref main)).startSize = new MinMaxCurve(0.3f, 0.5f);
			((MainModule)(ref main)).maxParticles = 100;
			((MainModule)(ref main)).simulationSpace = (ParticleSystemSimulationSpace)1;
			((MainModule)(ref main)).startColor = MinMaxGradient.op_Implicit(new Color(_baseColor.r, _baseColor.g, _baseColor.b, 0.5f));
			EmissionModule emission = _trailSystem.emission;
			((EmissionModule)(ref emission)).rateOverTime = MinMaxCurve.op_Implicit(0f);
			((EmissionModule)(ref emission)).rateOverDistance = MinMaxCurve.op_Implicit(0f);
			ShapeModule shape = _trailSystem.shape;
			((ShapeModule)(ref shape)).enabled = false;
			ColorOverLifetimeModule colorOverLifetime = _trailSystem.colorOverLifetime;
			((ColorOverLifetimeModule)(ref colorOverLifetime)).enabled = true;
			Gradient val2 = new Gradient();
			val2.SetKeys((GradientColorKey[])(object)new GradientColorKey[3]
			{
				new GradientColorKey(_baseColor, 0f),
				new GradientColorKey(_baseColor, 0.5f),
				new GradientColorKey(_baseColor * 0.5f, 1f)
			}, (GradientAlphaKey[])(object)new GradientAlphaKey[3]
			{
				new GradientAlphaKey(0.6f, 0f),
				new GradientAlphaKey(0.4f, 0.5f),
				new GradientAlphaKey(0f, 1f)
			});
			((ColorOverLifetimeModule)(ref colorOverLifetime)).color = MinMaxGradient.op_Implicit(val2);
			SizeOverLifetimeModule sizeOverLifetime = _trailSystem.sizeOverLifetime;
			((SizeOverLifetimeModule)(ref sizeOverLifetime)).enabled = true;
			AnimationCurve val3 = new AnimationCurve();
			val3.AddKey(0f, 1f);
			val3.AddKey(1f, 0f);
			((SizeOverLifetimeModule)(ref sizeOverLifetime)).size = new MinMaxCurve(1f, val3);
			ParticleSystemRenderer component = val.GetComponent<ParticleSystemRenderer>();
			component.renderMode = (ParticleSystemRenderMode)0;
			((Renderer)component).material = CreateParticleMaterial();
		}

		private Material CreateParticleMaterial()
		{
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Expected O, but got Unknown
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Expected O, but got Unknown
			Material val = null;
			string[] array = new string[4] { "Particles/Standard Unlit", "Legacy Shaders/Particles/Additive", "Particles/Additive", "Sprites/Default" };
			string[] array2 = array;
			foreach (string text in array2)
			{
				Shader val2 = Shader.Find(text);
				if ((Object)(object)val2 != (Object)null)
				{
					val = new Material(val2);
					break;
				}
			}
			if ((Object)(object)val == (Object)null)
			{
				val = new Material(Shader.Find("Standard"));
			}
			Texture2D mainTexture = CreateCircleTexture(32);
			val.mainTexture = (Texture)(object)mainTexture;
			return val;
		}

		private Texture2D CreateCircleTexture(int size)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Expected O, but got Unknown
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			Texture2D val = new Texture2D(size, size, (TextureFormat)4, false);
			float num = (float)size / 2f;
			float num2 = (float)size / 2f;
			for (int i = 0; i < size; i++)
			{
				for (int j = 0; j < size; j++)
				{
					float num3 = Vector2.Distance(new Vector2((float)j, (float)i), new Vector2(num, num));
					float num4 = Mathf.Clamp01(1f - num3 / num2);
					num4 *= num4;
					val.SetPixel(j, i, new Color(1f, 1f, 1f, num4));
				}
			}
			val.Apply();
			return val;
		}

		public void UpdateColor(Color newColor)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			_baseColor = newColor;
			if ((Object)(object)_auraLight != (Object)null)
			{
				_auraLight.color = newColor;
			}
			if ((Object)(object)_particleSystem != (Object)null)
			{
				MainModule main = _particleSystem.main;
				((MainModule)(ref main)).startColor = MinMaxGradient.op_Implicit(new Color(newColor.r, newColor.g, newColor.b, 0.6f));
			}
			if ((Object)(object)_trailSystem != (Object)null)
			{
				MainModule main2 = _trailSystem.main;
				((MainModule)(ref main2)).startColor = MinMaxGradient.op_Implicit(new Color(newColor.r, newColor.g, newColor.b, 0.5f));
			}
		}

		private void Update()
		{
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_0112: Unknown result type (might be due to invalid IL or missing references)
			//IL_0117: Unknown result type (might be due to invalid IL or missing references)
			//IL_0124: Unknown result type (might be due to invalid IL or missing references)
			//IL_012e: Unknown result type (might be due to invalid IL or missing references)
			//IL_018f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0194: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a5: Unknown result type (might be due to invalid IL or missing references)
			_pulseTime += Time.deltaTime;
			float num = 1f + Mathf.Sin(_pulseTime * 2f) * 0.2f;
			if ((Object)(object)_auraLight != (Object)null)
			{
				_auraLight.intensity = 1.5f * num;
			}
			if (!((Object)(object)_player != (Object)null) || !((Object)(object)_trailSystem != (Object)null))
			{
				return;
			}
			Vector3 position = ((Component)_player).transform.position;
			float num2 = Vector3.Distance(position, _lastPosition);
			if (num2 > 0.05f)
			{
				_trailEmissionTimer += Time.deltaTime;
				if (_trailEmissionTimer >= 0.15f)
				{
					_trailEmissionTimer = 0f;
					EmitParams val = default(EmitParams);
					((EmitParams)(ref val)).position = position + new Vector3(Random.Range(-0.2f, 0.2f), 0.05f, Random.Range(-0.2f, 0.2f));
					((EmitParams)(ref val)).velocity = Vector3.up * 0.1f;
					((EmitParams)(ref val)).startSize = Random.Range(0.3f, 0.5f);
					((EmitParams)(ref val)).startLifetime = Random.Range(1.5f, 2.5f);
					((EmitParams)(ref val)).startColor = Color32.op_Implicit(new Color(_baseColor.r, _baseColor.g, _baseColor.b, 0.6f));
					_trailSystem.Emit(val, 1);
				}
			}
			_lastPosition = position;
		}

		private void OnDestroy()
		{
			CleanupParticleSystem(_particleSystem);
			CleanupParticleSystem(_sparkleSystem);
			if (!((Object)(object)_trailSystem != (Object)null) || !((Object)(object)((Component)_trailSystem).gameObject != (Object)null))
			{
				return;
			}
			ParticleSystemRenderer component = ((Component)_trailSystem).GetComponent<ParticleSystemRenderer>();
			if ((Object)(object)component != (Object)null && (Object)(object)((Renderer)component).material != (Object)null)
			{
				if ((Object)(object)((Renderer)component).material.mainTexture != (Object)null)
				{
					Object.Destroy((Object)(object)((Renderer)component).material.mainTexture);
				}
				Object.Destroy((Object)(object)((Renderer)component).material);
			}
			Object.Destroy((Object)(object)((Component)_trailSystem).gameObject);
		}

		private void CleanupParticleSystem(ParticleSystem ps)
		{
			if (!((Object)(object)ps != (Object)null))
			{
				return;
			}
			ParticleSystemRenderer component = ((Component)ps).GetComponent<ParticleSystemRenderer>();
			if ((Object)(object)component != (Object)null && (Object)(object)((Renderer)component).material != (Object)null)
			{
				if ((Object)(object)((Renderer)component).material.mainTexture != (Object)null)
				{
					Object.Destroy((Object)(object)((Renderer)component).material.mainTexture);
				}
				Object.Destroy((Object)(object)((Renderer)component).material);
			}
		}
	}
	public static class CommandHandler
	{
		[Serializable]
		[CompilerGenerated]
		private sealed class <>c
		{
			public static readonly <>c <>9 = new <>c();

			public static ConsoleEvent <>9__1_0;

			public static ConsoleEvent <>9__1_1;

			public static ConsoleEvent <>9__1_2;

			public static ConsoleEvent <>9__1_3;

			internal void <RegisterCommands>b__1_0(ConsoleEventArgs args)
			{
				if (!IsAdmin())
				{
					Terminal context = args.Context;
					if (context != null)
					{
						context.AddString("You must be an admin to use this command.");
					}
					return;
				}
				if (args.Length < 2)
				{
					Terminal context2 = args.Context;
					if (context2 != null)
					{
						context2.AddString("Usage: addethereal <playername>");
					}
					return;
				}
				string text = string.Join(" ", args.Args.Skip(1));
				if (EtherealPlugin.AddEtherealPlayer(text))
				{
					Terminal context3 = args.Context;
					if (context3 != null)
					{
						context3.AddString("Added " + text + " to Ethereal players!");
					}
					BroadcastEtherealChange(text, added: true);
					Player val = EtherealPlugin.FindPlayerByName(text);
					if ((Object)(object)val != (Object)null && (Object)(object)val == (Object)(object)Player.m_localPlayer)
					{
						MessageHud instance = MessageHud.instance;
						if (instance != null)
						{
							instance.ShowMessage((MessageType)2, "You have been granted Ethereal status!\nType /ethereal in chat to select your aura.", 0, (Sprite)null, false);
						}
					}
				}
				else
				{
					Terminal context4 = args.Context;
					if (context4 != null)
					{
						context4.AddString(text + " is already an Ethereal player.");
					}
				}
			}

			internal void <RegisterCommands>b__1_1(ConsoleEventArgs args)
			{
				if (!IsAdmin())
				{
					Terminal context = args.Context;
					if (context != null)
					{
						context.AddString("You must be an admin to use this command.");
					}
					return;
				}
				if (args.Length < 2)
				{
					Terminal context2 = args.Context;
					if (context2 != null)
					{
						context2.AddString("Usage: removeethereal <playername>");
					}
					return;
				}
				string text = string.Join(" ", args.Args.Skip(1));
				if (EtherealPlugin.RemoveEtherealPlayer(text))
				{
					Terminal context3 = args.Context;
					if (context3 != null)
					{
						context3.AddString("Removed " + text + " from Ethereal players.");
					}
					BroadcastEtherealChange(text, added: false);
					Player val = EtherealPlugin.FindPlayerByName(text);
					if ((Object)(object)val != (Object)null && (Object)(object)val == (Object)(object)Player.m_localPlayer)
					{
						MessageHud instance = MessageHud.instance;
						if (instance != null)
						{
							instance.ShowMessage((MessageType)2, "Your Ethereal status has been revoked.", 0, (Sprite)null, false);
						}
					}
				}
				else
				{
					Terminal context4 = args.Context;
					if (context4 != null)
					{
						context4.AddString(text + " is not an Ethereal player.");
					}
				}
			}

			internal void <RegisterCommands>b__1_2(ConsoleEventArgs args)
			{
				if (EtherealPlugin.EtherealPlayers.Count == 0)
				{
					Terminal context = args.Context;
					if (context != null)
					{
						context.AddString("No Ethereal players registered.");
					}
					return;
				}
				Terminal context2 = args.Context;
				if (context2 != null)
				{
					context2.AddString("===== Ethereal Players =====");
				}
				foreach (KeyValuePair<string, EtherealPlayerData> etherealPlayer in EtherealPlugin.EtherealPlayers)
				{
					string selectedColor = etherealPlayer.Value.SelectedColor;
					Terminal context3 = args.Context;
					if (context3 != null)
					{
						context3.AddString("  " + etherealPlayer.Key + " - Aura: " + selectedColor);
					}
				}
				Terminal context4 = args.Context;
				if (context4 != null)
				{
					context4.AddString("============================");
				}
			}

			internal void <RegisterCommands>b__1_3(ConsoleEventArgs args)
			{
				HandleEtherealCommand();
			}
		}

		private static bool _commandsRegistered;

		public static void RegisterCommands()
		{
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Expected O, but got Unknown
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Expected O, but got Unknown
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: Expected O, but got Unknown
			//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e2: Expected O, but got Unknown
			if (_commandsRegistered)
			{
				return;
			}
			try
			{
				object obj = <>c.<>9__1_0;
				if (obj == null)
				{
					ConsoleEvent val = delegate(ConsoleEventArgs args)
					{
						if (!IsAdmin())
						{
							Terminal context9 = args.Context;
							if (context9 != null)
							{
								context9.AddString("You must be an admin to use this command.");
							}
						}
						else if (args.Length < 2)
						{
							Terminal context10 = args.Context;
							if (context10 != null)
							{
								context10.AddString("Usage: addethereal <playername>");
							}
						}
						else
						{
							string text2 = string.Join(" ", args.Args.Skip(1));
							if (EtherealPlugin.AddEtherealPlayer(text2))
							{
								Terminal context11 = args.Context;
								if (context11 != null)
								{
									context11.AddString("Added " + text2 + " to Ethereal players!");
								}
								BroadcastEtherealChange(text2, added: true);
								Player val6 = EtherealPlugin.FindPlayerByName(text2);
								if ((Object)(object)val6 != (Object)null && (Object)(object)val6 == (Object)(object)Player.m_localPlayer)
								{
									MessageHud instance2 = MessageHud.instance;
									if (instance2 != null)
									{
										instance2.ShowMessage((MessageType)2, "You have been granted Ethereal status!\nType /ethereal in chat to select your aura.", 0, (Sprite)null, false);
									}
								}
							}
							else
							{
								Terminal context12 = args.Context;
								if (context12 != null)
								{
									context12.AddString(text2 + " is already an Ethereal player.");
								}
							}
						}
					};
					<>c.<>9__1_0 = val;
					obj = (object)val;
				}
				new ConsoleCommand("addethereal", "[name] - Add a player to Ethereal list", (ConsoleEvent)obj, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false);
				object obj2 = <>c.<>9__1_1;
				if (obj2 == null)
				{
					ConsoleEvent val2 = delegate(ConsoleEventArgs args)
					{
						if (!IsAdmin())
						{
							Terminal context5 = args.Context;
							if (context5 != null)
							{
								context5.AddString("You must be an admin to use this command.");
							}
						}
						else if (args.Length < 2)
						{
							Terminal context6 = args.Context;
							if (context6 != null)
							{
								context6.AddString("Usage: removeethereal <playername>");
							}
						}
						else
						{
							string text = string.Join(" ", args.Args.Skip(1));
							if (EtherealPlugin.RemoveEtherealPlayer(text))
							{
								Terminal context7 = args.Context;
								if (context7 != null)
								{
									context7.AddString("Removed " + text + " from Ethereal players.");
								}
								BroadcastEtherealChange(text, added: false);
								Player val5 = EtherealPlugin.FindPlayerByName(text);
								if ((Object)(object)val5 != (Object)null && (Object)(object)val5 == (Object)(object)Player.m_localPlayer)
								{
									MessageHud instance = MessageHud.instance;
									if (instance != null)
									{
										instance.ShowMessage((MessageType)2, "Your Ethereal status has been revoked.", 0, (Sprite)null, false);
									}
								}
							}
							else
							{
								Terminal context8 = args.Context;
								if (context8 != null)
								{
									context8.AddString(text + " is not an Ethereal player.");
								}
							}
						}
					};
					<>c.<>9__1_1 = val2;
					obj2 = (object)val2;
				}
				new ConsoleCommand("removeethereal", "[name] - Remove a player from Ethereal list", (ConsoleEvent)obj2, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false);
				object obj3 = <>c.<>9__1_2;
				if (obj3 == null)
				{
					ConsoleEvent val3 = delegate(ConsoleEventArgs args)
					{
						if (EtherealPlugin.EtherealPlayers.Count == 0)
						{
							Terminal context = args.Context;
							if (context != null)
							{
								context.AddString("No Ethereal players registered.");
							}
						}
						else
						{
							Terminal context2 = args.Context;
							if (context2 != null)
							{
								context2.AddString("===== Ethereal Players =====");
							}
							foreach (KeyValuePair<string, EtherealPlayerData> etherealPlayer in EtherealPlugin.EtherealPlayers)
							{
								string selectedColor = etherealPlayer.Value.SelectedColor;
								Terminal context3 = args.Context;
								if (context3 != null)
								{
									context3.AddString("  " + etherealPlayer.Key + " - Aura: " + selectedColor);
								}
							}
							Terminal context4 = args.Context;
							if (context4 != null)
							{
								context4.AddString("============================");
							}
						}
					};
					<>c.<>9__1_2 = val3;
					obj3 = (object)val3;
				}
				new ConsoleCommand("listethereals", "List all Ethereal players", (ConsoleEvent)obj3, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false);
				object obj4 = <>c.<>9__1_3;
				if (obj4 == null)
				{
					ConsoleEvent val4 = delegate
					{
						HandleEtherealCommand();
					};
					<>c.<>9__1_3 = val4;
					obj4 = (object)val4;
				}
				new ConsoleCommand("ethereal", "Open Ethereal aura selection menu", (ConsoleEvent)obj4, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false);
				_commandsRegistered = true;
				EtherealPlugin.Log.LogInfo((object)"Ethereal console commands registered!");
			}
			catch (Exception ex)
			{
				EtherealPlugin.Log.LogError((object)("Failed to register commands: " + ex.Message));
			}
		}

		private static bool IsAdmin()
		{
			if ((Object)(object)ZNet.instance == (Object)null)
			{
				return true;
			}
			if (ZNet.instance.IsServer())
			{
				return true;
			}
			return ZNet.instance.LocalPlayerIsAdminOrHost();
		}

		private static void BroadcastEtherealChange(string playerName, bool added)
		{
			EtherealPlugin.Log.LogInfo((object)$"BroadcastEtherealChange called: {playerName}, added={added}");
			if (ZRoutedRpc.instance == null)
			{
				EtherealPlugin.Log.LogWarning((object)"ZRoutedRpc.instance is null, cannot broadcast");
				return;
			}
			if ((Object)(object)ZNet.instance == (Object)null)
			{
				EtherealPlugin.Log.LogWarning((object)"ZNet.instance is null, cannot broadcast");
				return;
			}
			string text = (added ? "None" : "");
			if (added)
			{
				EtherealPlayerData etherealData = EtherealPlugin.GetEtherealData(playerName);
				if (etherealData != null)
				{
					text = etherealData.SelectedColor;
				}
			}
			EtherealPlugin.Log.LogInfo((object)$"Broadcasting ethereal change: {playerName} -> '{text}' (added={added})");
			ZRoutedRpc.instance.InvokeRoutedRPC(ZRoutedRpc.Everybody, "Ethereal_SyncColor", new object[2] { playerName, text });
			if (ZNet.instance.IsServer())
			{
				EtherealPlugin.Log.LogInfo((object)"Server: Also updating local ethereal data");
			}
		}

		public static void HandleEtherealCommand()
		{
			if ((Object)(object)Player.m_localPlayer == (Object)null)
			{
				EtherealPlugin.Log.LogWarning((object)"No local player for ethereal command");
				return;
			}
			string playerName = Player.m_localPlayer.GetPlayerName();
			EtherealPlugin.Log.LogInfo((object)("Ethereal command called by '" + playerName + "'"));
			EtherealPlugin.Log.LogInfo((object)$"Current ethereal players: {EtherealPlugin.EtherealPlayers.Count}");
			foreach (KeyValuePair<string, EtherealPlayerData> etherealPlayer in EtherealPlugin.EtherealPlayers)
			{
				EtherealPlugin.Log.LogInfo((object)("  - '" + etherealPlayer.Key + "' (color: " + etherealPlayer.Value.SelectedColor + ")"));
			}
			bool flag = EtherealPlugin.IsEthereal(playerName);
			EtherealPlugin.Log.LogInfo((object)$"Is '{playerName}' ethereal? {flag}");
			if (!flag)
			{
				((Character)Player.m_localPlayer).Message((MessageType)2, "You don't have Ethereal status.\nThis is a special feature for supporters!", 0, (Sprite)null);
				return;
			}
			EtherealPlugin.ShowColorMenu = true;
			EtherealPlugin.Log.LogInfo((object)"Opening Ethereal menu");
		}
	}
	[HarmonyPatch(typeof(Terminal), "InitTerminal")]
	public static class Terminal_InitTerminal_Patch
	{
		[HarmonyPostfix]
		public static void Postfix()
		{
			CommandHandler.RegisterCommands();
		}
	}
	public class ChatCommandMonitor : MonoBehaviour
	{
		private static ChatCommandMonitor _instance;

		public static void Initialize()
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Expected O, but got Unknown
			if (!((Object)(object)_instance != (Object)null))
			{
				GameObject val = new GameObject("EtherealChatMonitor");
				_instance = val.AddComponent<ChatCommandMonitor>();
				Object.DontDestroyOnLoad((Object)(object)val);
				EtherealPlugin.Log.LogInfo((object)"Chat command monitor initialized");
			}
		}

		private void Update()
		{
			if (Input.GetKeyDown((KeyCode)13) || Input.GetKeyDown((KeyCode)271))
			{
				CheckChatInput();
			}
		}

		private void CheckChatInput()
		{
			try
			{
				if ((Object)(object)Chat.instance == (Object)null)
				{
					return;
				}
				Type typeFromHandle = typeof(Chat);
				FieldInfo field = typeFromHandle.GetField("m_input", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				if (field == null)
				{
					return;
				}
				object value = field.GetValue(Chat.instance);
				if (value == null)
				{
					return;
				}
				PropertyInfo property = value.GetType().GetProperty("text");
				if (!(property == null))
				{
					string text = property.GetValue(value) as string;
					if (!string.IsNullOrEmpty(text) && text.Trim().Equals("/ethereal", StringComparison.OrdinalIgnoreCase))
					{
						EtherealPlugin.Log.LogInfo((object)"Detected /ethereal in chat!");
						property.SetValue(value, "");
						CommandHandler.HandleEtherealCommand();
					}
				}
			}
			catch
			{
			}
		}
	}
	[BepInPlugin("com.aurora.ethereal", "Ethereal", "1.0.0")]
	public class EtherealPlugin : BaseUnityPlugin
	{
		public const string PluginGUID = "com.aurora.ethereal";

		public const string PluginName = "Ethereal";

		public const string PluginVersion = "1.0.0";

		private Harmony _harmony;

		public static Dictionary<string, EtherealPlayerData> EtherealPlayers = new Dictionary<string, EtherealPlayerData>();

		public static bool ShowColorMenu = false;

		private Rect _menuRect;

		private Vector2 _scrollPosition;

		private bool _menuInitialized = false;

		public static readonly Dictionary<string, Color> AuraColors = new Dictionary<string, Color>
		{
			{
				"None",
				Color.clear
			},
			{
				"Crimson",
				new Color(0.86f, 0.08f, 0.24f)
			},
			{
				"Scarlet",
				new Color(1f, 0.14f, 0f)
			},
			{
				"Orange",
				new Color(1f, 0.5f, 0f)
			},
			{
				"Gold",
				new Color(1f, 0.84f, 0f)
			},
			{
				"Yellow",
				new Color(1f, 1f, 0.2f)
			},
			{
				"Lime",
				new Color(0.5f, 1f, 0f)
			},
			{
				"Emerald",
				new Color(0.31f, 0.78f, 0.47f)
			},
			{
				"Jade",
				new Color(0f, 0.66f, 0.42f)
			},
			{
				"Cyan",
				new Color(0f, 1f, 1f)
			},
			{
				"Azure",
				new Color(0f, 0.5f, 1f)
			},
			{
				"Sapphire",
				new Color(0.06f, 0.32f, 0.73f)
			},
			{
				"Violet",
				new Color(0.54f, 0.17f, 0.89f)
			},
			{
				"Purple",
				new Color(0.63f, 0.13f, 0.94f)
			},
			{
				"Magenta",
				new Color(1f, 0f, 1f)
			},
			{
				"Rose",
				new Color(1f, 0.08f, 0.58f)
			},
			{
				"Pink",
				new Color(1f, 0.41f, 0.71f)
			},
			{
				"White",
				new Color(1f, 1f, 1f)
			},
			{
				"Silver",
				new Color(0.75f, 0.75f, 0.75f)
			},
			{
				"Ethereal Blue",
				new Color(0.4f, 0.8f, 1f)
			},
			{
				"Ethereal Green",
				new Color(0.4f, 1f, 0.8f)
			},
			{
				"Ethereal Purple",
				new Color(0.8f, 0.4f, 1f)
			},
			{
				"Rainbow",
				Color.white
			}
		};

		public static EtherealPlugin Instance { get; private set; }

		public static ManualLogSource Log => ((BaseUnityPlugin)Instance).Logger;

		private static string DataFilePath => Path.Combine(Paths.ConfigPath, "Ethereal_Players.txt");

		private void Awake()
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Expected O, but got Unknown
			Instance = this;
			_harmony = new Harmony("com.aurora.ethereal");
			_harmony.PatchAll();
			LoadEtherealData();
			ChatCommandMonitor.Initialize();
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Ethereal v1.0.0 loaded!");
		}

		private void OnDestroy()
		{
			Harmony harmony = _harmony;
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
			SaveEtherealData();
		}

		private void Update()
		{
			if (ShowColorMenu && Input.GetKeyDown((KeyCode)27))
			{
				ShowColorMenu = false;
				Cursor.lockState = (CursorLockMode)1;
				Cursor.visible = false;
			}
		}

		private void OnGUI()
		{
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: Expected O, but got Unknown
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			if (ShowColorMenu && !((Object)(object)Player.m_localPlayer == (Object)null))
			{
				Cursor.lockState = (CursorLockMode)0;
				Cursor.visible = true;
				if (!_menuInitialized)
				{
					_menuRect = new Rect((float)(Screen.width / 2 - 200), (float)(Screen.height / 2 - 250), 400f, 500f);
					_menuInitialized = true;
				}
				GUI.backgroundColor = new Color(0.1f, 0.1f, 0.15f, 0.95f);
				_menuRect = GUI.Window(98765, _menuRect, new WindowFunction(DrawColorMenu), "Ethereal Aura Selection");
			}
		}

		private void DrawColorMenu(int windowID)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Expected O, but got Unknown
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cd: Expected O, but got Unknown
			//IL_00ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_012a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0142: Unknown result type (might be due to invalid IL or missing references)
			//IL_0147: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0280: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_02fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c1: Unknown result type (might be due to invalid IL or missing references)
			GUILayout.Space(10f);
			GUIStyle val = new GUIStyle(GUI.skin.label);
			val.alignment = (TextAnchor)4;
			val.fontSize = 14;
			val.fontStyle = (FontStyle)1;
			val.normal.textColor = new Color(0.8f, 0.9f, 1f);
			GUILayout.Label("Select your aura color:", val, Array.Empty<GUILayoutOption>());
			GUILayout.Space(10f);
			string playerName = Player.m_localPlayer.GetPlayerName();
			string text = "None";
			EtherealPlayerData etherealData = GetEtherealData(playerName);
			if (etherealData != null)
			{
				text = etherealData.SelectedColor;
			}
			Color color = Color.white;
			if (AuraColors.TryGetValue(text, out var value))
			{
				color = value;
			}
			GUIStyle val2 = new GUIStyle(GUI.skin.label);
			val2.richText = true;
			val2.alignment = (TextAnchor)4;
			GUILayout.Label("Current: <color=#" + ColorToHex(color) + ">" + text + "</color>", val2, Array.Empty<GUILayoutOption>());
			GUILayout.Space(10f);
			_scrollPosition = GUILayout.BeginScrollView(_scrollPosition, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Height(350f) });
			int num = 2;
			int num2 = 0;
			GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
			foreach (KeyValuePair<string, Color> auraColor in AuraColors)
			{
				if (num2 >= num)
				{
					GUILayout.EndHorizontal();
					GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
					num2 = 0;
				}
				Color backgroundColor = ((auraColor.Key == "None") ? Color.gray : auraColor.Value);
				GUI.backgroundColor = backgroundColor;
				string text2 = auraColor.Key;
				if (auraColor.Key == text)
				{
					text2 = "> " + auraColor.Key + " <";
				}
				if (GUILayout.Button(text2, (GUILayoutOption[])(object)new GUILayoutOption[2]
				{
					GUILayout.Width(180f),
					GUILayout.Height(35f)
				}))
				{
					SelectAuraColor(auraColor.Key);
				}
				num2++;
			}
			GUILayout.EndHorizontal();
			GUILayout.EndScrollView();
			GUI.backgroundColor = new Color(0.1f, 0.1f, 0.15f, 0.95f);
			GUILayout.Space(10f);
			GUI.backgroundColor = new Color(0.6f, 0.2f, 0.2f);
			if (GUILayout.Button("Close", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Height(30f) }))
			{
				ShowColorMenu = false;
				Cursor.lockState = (CursorLockMode)1;
				Cursor.visible = false;
			}
			GUI.DragWindow(new Rect(0f, 0f, 10000f, 20f));
		}

		private void SelectAuraColor(string colorName)
		{
			if ((Object)(object)Player.m_localPlayer == (Object)null)
			{
				return;
			}
			string playerName = Player.m_localPlayer.GetPlayerName();
			if (!IsEthereal(playerName))
			{
				Log.LogWarning((object)("Player '" + playerName + "' is not in Ethereal list!"));
				return;
			}
			string normalizedPlayerName = GetNormalizedPlayerName(playerName);
			EtherealPlayers[normalizedPlayerName].SelectedColor = colorName;
			SaveEtherealData();
			AuraManager.ApplyAura(Player.m_localPlayer, colorName);
			SyncEtherealData(normalizedPlayerName, colorName);
			string text = ((colorName == "None") ? "Your Ethereal aura has been removed." : ("Your Ethereal aura is now " + colorName + "!"));
			if ((Object)(object)MessageHud.instance != (Object)null)
			{
				MessageHud.instance.ShowMessage((MessageType)2, text, 0, (Sprite)null, false);
			}
			Log.LogInfo((object)("Player '" + normalizedPlayerName + "' selected aura color: " + colorName));
		}

		public static string ColorToHex(Color color)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			return ColorUtility.ToHtmlStringRGB(color);
		}

		public static Color GetAuraColor(string colorName)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			if (AuraColors.TryGetValue(colorName, out var value))
			{
				return value;
			}
			return Color.white;
		}

		public static void LoadEtherealData()
		{
			try
			{
				EtherealPlayers.Clear();
				if (!File.Exists(DataFilePath))
				{
					return;
				}
				string[] array = File.ReadAllLines(DataFilePath);
				string[] array2 = array;
				foreach (string text in array2)
				{
					if (!string.IsNullOrWhiteSpace(text))
					{
						string[] array3 = text.Split(new char[1] { '|' });
						if (array3.Length >= 2)
						{
							string text2 = array3[0].Trim();
							string selectedColor = array3[1].Trim();
							EtherealPlayers[text2] = new EtherealPlayerData
							{
								PlayerName = text2,
								SelectedColor = selectedColor
							};
						}
					}
				}
				Log.LogInfo((object)$"Loaded {EtherealPlayers.Count} Ethereal players from file.");
			}
			catch (Exception ex)
			{
				Log.LogError((object)("Failed to load Ethereal data: " + ex.Message));
			}
		}

		public static void SaveEtherealData()
		{
			try
			{
				List<string> list = new List<string>();
				foreach (KeyValuePair<string, EtherealPlayerData> etherealPlayer in EtherealPlayers)
				{
					list.Add(etherealPlayer.Value.PlayerName + "|" + etherealPlayer.Value.SelectedColor);
				}
				File.WriteAllLines(DataFilePath, list);
				Log.LogInfo((object)$"Saved {EtherealPlayers.Count} Ethereal players to file.");
			}
			catch (Exception ex)
			{
				Log.LogError((object)("Failed to save Ethereal data: " + ex.Message));
			}
		}

		public static bool AddEtherealPlayer(string playerName)
		{
			playerName = playerName?.Trim();
			if (string.IsNullOrEmpty(playerName))
			{
				return false;
			}
			if (IsEthereal(playerName))
			{
				return false;
			}
			EtherealPlayers[playerName] = new EtherealPlayerData
			{
				PlayerName = playerName,
				SelectedColor = "None"
			};
			SaveEtherealData();
			Log.LogInfo((object)("Added '" + playerName + "' to Ethereal players."));
			return true;
		}

		public static bool RemoveEtherealPlayer(string playerName)
		{
			playerName = playerName?.Trim();
			if (string.IsNullOrEmpty(playerName))
			{
				return false;
			}
			string text = null;
			foreach (string key in EtherealPlayers.Keys)
			{
				if (key.Equals(playerName, StringComparison.OrdinalIgnoreCase))
				{
					text = key;
					break;
				}
			}
			if (text == null)
			{
				return false;
			}
			EtherealPlayers.Remove(text);
			SaveEtherealData();
			Player val = FindPlayerByName(playerName);
			if ((Object)(object)val != (Object)null)
			{
				AuraManager.RemoveAura(val);
			}
			Log.LogInfo((object)("Removed '" + text + "' from Ethereal players."));
			return true;
		}

		public static Player FindPlayerByName(string name)
		{
			foreach (Player allPlayer in Player.GetAllPlayers())
			{
				if (allPlayer.GetPlayerName().Equals(name, StringComparison.OrdinalIgnoreCase))
				{
					return allPlayer;
				}
			}
			return null;
		}

		public static bool IsEthereal(string playerName)
		{
			foreach (string key in EtherealPlayers.Keys)
			{
				if (key.Equals(playerName, StringComparison.OrdinalIgnoreCase))
				{
					return true;
				}
			}
			return false;
		}

		public static EtherealPlayerData GetEtherealData(string playerName)
		{
			foreach (KeyValuePair<string, EtherealPlayerData> etherealPlayer in EtherealPlayers)
			{
				if (etherealPlayer.Key.Equals(playerName, StringComparison.OrdinalIgnoreCase))
				{
					return etherealPlayer.Value;
				}
			}
			return null;
		}

		public static string GetNormalizedPlayerName(string playerName)
		{
			foreach (string key in EtherealPlayers.Keys)
			{
				if (key.Equals(playerName, StringComparison.OrdinalIgnoreCase))
				{
					return key;
				}
			}
			return playerName;
		}

		private void SyncEtherealData(string playerName, string colorName)
		{
			if ((Object)(object)ZNet.instance == (Object)null)
			{
				Log.LogWarning((object)"SyncEtherealData: ZNet.instance is null");
				return;
			}
			if (ZRoutedRpc.instance == null)
			{
				Log.LogWarning((object)"SyncEtherealData: ZRoutedRpc.instance is null");
				return;
			}
			Log.LogInfo((object)("SyncEtherealData: Broadcasting " + playerName + " -> " + colorName));
			ZRoutedRpc.instance.InvokeRoutedRPC(ZRoutedRpc.Everybody, "Ethereal_SyncColor", new object[2] { playerName, colorName });
		}

		public static void RegisterRPCs()
		{
			if (ZRoutedRpc.instance == null)
			{
				Log.LogWarning((object)"RegisterRPCs: ZRoutedRpc.instance is null!");
				return;
			}
			ZRoutedRpc.instance.Register<string, string>("Ethereal_SyncColor", (Action<long, string, string>)RPC_SyncColor);
			ZRoutedRpc.instance.Register<string>("Ethereal_RequestData", (Action<long, string>)RPC_RequestData);
			ZRoutedRpc.instance.Register<string>("Ethereal_SendAllData", (Action<long, string>)RPC_ReceiveAllData);
			Log.LogInfo((object)"Ethereal RPCs registered.");
		}

		public static void RequestDataFromServer()
		{
			if (ZRoutedRpc.instance == null)
			{
				Log.LogWarning((object)"RequestDataFromServer: ZRoutedRpc.instance is null");
				return;
			}
			if ((Object)(object)ZNet.instance == (Object)null)
			{
				Log.LogWarning((object)"RequestDataFromServer: ZNet.instance is null");
				return;
			}
			if ((Object)(object)Player.m_localPlayer == (Object)null)
			{
				Log.LogWarning((object)"RequestDataFromServer: No local player");
				return;
			}
			string playerName = Player.m_localPlayer.GetPlayerName();
			Log.LogInfo((object)("Requesting ethereal data from server for " + playerName));
			ZNetPeer serverPeer = ZNet.instance.GetServerPeer();
			if (serverPeer != null)
			{
				long uid = serverPeer.m_uid;
				Log.LogInfo((object)$"Sending request to server peer {uid}");
				ZRoutedRpc.instance.InvokeRoutedRPC(uid, "Ethereal_RequestData", new object[1] { playerName });
			}
			else
			{
				Log.LogInfo((object)"No server peer found, we might be the server");
				ZRoutedRpc.instance.InvokeRoutedRPC(ZRoutedRpc.Everybody, "Ethereal_RequestData", new object[1] { playerName });
			}
		}

		private static void RPC_SyncColor(long sender, string playerName, string colorName)
		{
			Log.LogInfo((object)$"RPC_SyncColor received: {playerName} -> '{colorName}' from sender {sender}");
			if (string.IsNullOrEmpty(colorName))
			{
				string text = null;
				foreach (string key in EtherealPlayers.Keys)
				{
					if (key.Equals(playerName, StringComparison.OrdinalIgnoreCase))
					{
						text = key;
						break;
					}
				}
				if (text != null)
				{
					EtherealPlayers.Remove(text);
					if ((Object)(object)ZNet.instance != (Object)null && ZNet.instance.IsServer())
					{
						SaveEtherealData();
					}
					Log.LogInfo((object)("Removed " + text + " from Ethereal list via sync"));
					Player val = FindPlayerByName(playerName);
					if ((Object)(object)val != (Object)null)
					{
						AuraManager.RemoveAura(val);
					}
				}
				return;
			}
			string text2 = null;
			foreach (string key2 in EtherealPlayers.Keys)
			{
				if (key2.Equals(playerName, StringComparison.OrdinalIgnoreCase))
				{
					text2 = key2;
					break;
				}
			}
			if (text2 != null)
			{
				EtherealPlayers[text2].SelectedColor = colorName;
			}
			else
			{
				EtherealPlayers[playerName] = new EtherealPlayerData
				{
					PlayerName = playerName,
					SelectedColor = colorName
				};
			}
			if ((Object)(object)ZNet.instance != (Object)null && ZNet.instance.IsServer())
			{
				SaveEtherealData();
			}
			Log.LogInfo((object)$"Updated ethereal data: {playerName} -> {colorName}, total players: {EtherealPlayers.Count}");
			Player val2 = FindPlayerByName(playerName);
			if ((Object)(object)val2 != (Object)null)
			{
				AuraManager.ApplyAura(val2, colorName);
			}
		}

		private static void RPC_RequestData(long sender, string requesterName)
		{
			Log.LogInfo((object)$"RPC_RequestData received from {sender} for {requesterName}");
			if ((Object)(object)ZNet.instance == (Object)null || !ZNet.instance.IsServer())
			{
				Log.LogInfo((object)"Not server, ignoring request");
				return;
			}
			string text = SerializeAllData();
			Log.LogInfo((object)$"Sending all ethereal data to {sender}: {text}");
			ZRoutedRpc.instance.InvokeRoutedRPC(sender, "Ethereal_SendAllData", new object[1] { text });
		}

		private static void RPC_ReceiveAllData(long sender, string data)
		{
			Log.LogInfo((object)("RPC_ReceiveAllData received: " + data));
			DeserializeAllData(data);
			Log.LogInfo((object)$"After deserialize, ethereal players: {EtherealPlayers.Count}");
			foreach (KeyValuePair<string, EtherealPlayerData> etherealPlayer in EtherealPlayers)
			{
				Log.LogInfo((object)("  - " + etherealPlayer.Key + ": " + etherealPlayer.Value.SelectedColor));
			}
			foreach (Player allPlayer in Player.GetAllPlayers())
			{
				string playerName = allPlayer.GetPlayerName();
				EtherealPlayerData etherealData = GetEtherealData(playerName);
				if (etherealData != null)
				{
					AuraManager.ApplyAura(allPlayer, etherealData.SelectedColor);
				}
			}
		}

		private static string SerializeAllData()
		{
			List<string> list = new List<string>();
			foreach (KeyValuePair<string, EtherealPlayerData> etherealPlayer in EtherealPlayers)
			{
				list.Add(etherealPlayer.Key + ":" + etherealPlayer.Value.SelectedColor);
			}
			return string.Join(";", list);
		}

		private static void DeserializeAllData(string data)
		{
			try
			{
				if (string.IsNullOrEmpty(data))
				{
					return;
				}
				string[] array = data.Split(new char[1] { ';' });
				string[] array2 = array;
				foreach (string text in array2)
				{
					string[] array3 = text.Split(new char[1] { ':' });
					if (array3.Length >= 2)
					{
						EtherealPlayers[array3[0]] = new EtherealPlayerData
						{
							PlayerName = array3[0],
							SelectedColor = array3[1]
						};
					}
				}
			}
			catch (Exception ex)
			{
				Log.LogError((object)("Failed to deserialize Ethereal data: " + ex.Message));
			}
		}
	}
	[Serializable]
	public class EtherealPlayerData
	{
		public string PlayerName;

		public string SelectedColor = "None";
	}
	public static class NameColorPatches
	{
		public static readonly Color EtherealShoutColor = new Color(1f, 0.35f, 0f);

		public static string GetColoredName(string originalName)
		{
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			if (string.IsNullOrEmpty(originalName))
			{
				return originalName;
			}
			EtherealPlayerData etherealData = EtherealPlugin.GetEtherealData(originalName);
			if (etherealData == null || etherealData.SelectedColor == "None")
			{
				return originalName;
			}
			Color color = EtherealPlugin.GetAuraColor(etherealData.SelectedColor);
			if (etherealData.SelectedColor == "Rainbow")
			{
				float num = Time.time * 0.3f % 1f;
				color = Color.HSVToRGB(num, 0.8f, 1f);
			}
			string text = EtherealPlugin.ColorToHex(color);
			return "<color=#" + text + ">" + originalName + "</color>";
		}

		public static string StripColorTags(string text)
		{
			if (string.IsNullOrEmpty(text))
			{
				return text;
			}
			string pattern = "<color=[^>]+>|</color>";
			return Regex.Replace(text, pattern, "");
		}

		public static string GetEtherealShoutColorHex()
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			return EtherealPlugin.ColorToHex(EtherealShoutColor);
		}

		public static void ColorizeTextComponent(Text textComponent)
		{
			if ((Object)(object)textComponent == (Object)null)
			{
				return;
			}
			string text = textComponent.text;
			if (string.IsNullOrEmpty(text) || text.Contains("<color="))
			{
				return;
			}
			foreach (KeyValuePair<string, EtherealPlayerData> etherealPlayer in EtherealPlugin.EtherealPlayers)
			{
				if (etherealPlayer.Value.SelectedColor == "None" || !text.Contains(etherealPlayer.Key))
				{
					continue;
				}
				string coloredName = GetColoredName(etherealPlayer.Key);
				textComponent.text = text.Replace(etherealPlayer.Key, coloredName);
				textComponent.supportRichText = true;
				break;
			}
		}

		public static string ColorizeString(string text)
		{
			if (string.IsNullOrEmpty(text) || text.Contains("<color="))
			{
				return text;
			}
			foreach (KeyValuePair<string, EtherealPlayerData> etherealPlayer in EtherealPlugin.EtherealPlayers)
			{
				if (etherealPlayer.Value.SelectedColor == "None" || !text.Contains(etherealPlayer.Key))
				{
					continue;
				}
				return text.Replace(etherealPlayer.Key, GetColoredName(etherealPlayer.Key));
			}
			return text;
		}
	}
	[HarmonyPatch]
	public static class NetworkPatches
	{
		[CompilerGenerated]
		private sealed class <ApplyAllAurasDelayed>d__3 : IEnumerator<object>, IDisposable, IEnumerator
		{
			private int <>1__state;

			private object <>2__current;

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

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

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

			[DebuggerHidden]
			void IDisposable.Dispose()
			{
				<>1__state = -2;
			}

			private bool MoveNext()
			{
				//IL_0026: Unknown result type (might be due to invalid IL or missing references)
				//IL_0030: Expected O, but got Unknown
				switch (<>1__state)
				{
				default:
					return false;
				case 0:
					<>1__state = -1;
					<>2__current = (object)new WaitForSeconds(2f);
					<>1__state = 1;
					return true;
				case 1:
					<>1__state = -1;
					EtherealPlugin.Log.LogInfo((object)"Applying auras to all players after spawn");
					AuraManager.ApplyAurasToAllPlayers();
					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();
			}
		}

		[CompilerGenerated]
		private sealed class <ApplyAuraDelayed>d__2 : IEnumerator<object>, IDisposable, IEnumerator
		{
			private int <>1__state;

			private object <>2__current;

			public Player player;

			public string colorName;

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

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

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

			[DebuggerHidden]
			void IDisposable.Dispose()
			{
				<>1__state = -2;
			}

			private bool MoveNext()
			{
				//IL_0026: Unknown result type (might be due to invalid IL or missing references)
				//IL_0030: Expected O, but got Unknown
				switch (<>1__state)
				{
				default:
					return false;
				case 0:
					<>1__state = -1;
					<>2__current = (object)new WaitForSeconds(0.5f);
					<>1__state = 1;
					return true;
				case 1:
					<>1__state = -1;
					if ((Object)(object)player != (Object)null)
					{
						AuraManager.ApplyAura(player, colorName);
					}
					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();
			}
		}

		[HarmonyPatch(typeof(ZNet), "Start")]
		[HarmonyPostfix]
		public static void ZNet_Start_Postfix()
		{
			EtherealPlugin.RegisterRPCs();
		}

		[HarmonyPatch(typeof(Player), "OnSpawned")]
		[HarmonyPostfix]
		public static void Player_OnSpawned_Postfix(Player __instance)
		{
			try
			{
				string playerName = __instance.GetPlayerName();
				EtherealPlugin.Log.LogInfo((object)$"Player spawned: {playerName} (local: {(Object)(object)__instance == (Object)(object)Player.m_localPlayer})");
				if ((Object)(object)__instance == (Object)(object)Player.m_localPlayer)
				{
					EtherealPlugin.RequestDataFromServer();
				}
				EtherealPlayerData etherealData = EtherealPlugin.GetEtherealData(playerName);
				if (etherealData != null && etherealData.SelectedColor != "None")
				{
					EtherealPlugin.Log.LogInfo((object)("Applying aura to " + playerName + " on spawn"));
					((MonoBehaviour)__instance).StartCoroutine(ApplyAuraDelayed(__instance, etherealData.SelectedColor));
				}
				if ((Object)(object)__instance == (Object)(object)Player.m_localPlayer)
				{
					((MonoBehaviour)__instance).StartCoroutine(ApplyAllAurasDelayed());
				}
			}
			catch (Exception ex)
			{
				EtherealPlugin.Log.LogError((object)("Error in OnSpawned: " + ex.Message));
			}
		}

		[IteratorStateMachine(typeof(<ApplyAuraDelayed>d__2))]
		private static IEnumerator ApplyAuraDelayed(Player player, string colorName)
		{
			//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
			return new <ApplyAuraDelayed>d__2(0)
			{
				player = player,
				colorName = colorName
			};
		}

		[IteratorStateMachine(typeof(<ApplyAllAurasDelayed>d__3))]
		private static IEnumerator ApplyAllAurasDelayed()
		{
			//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
			return new <ApplyAllAurasDelayed>d__3(0);
		}

		[HarmonyPatch(typeof(Player), "OnDestroy")]
		[HarmonyPrefix]
		public static void Player_OnDestroy_Prefix(Player __instance)
		{
			AuraManager.RemoveAura(__instance);
		}
	}
	[HarmonyPatch(typeof(Player), "Update")]
	public static class PlayerUpdatePatch
	{
		private static float _lastUpdate;

		private static float _lastAuraCheck;

		[HarmonyPostfix]
		public static void Postfix(Player __instance)
		{
			if (!((Object)(object)__instance != (Object)(object)Player.m_localPlayer) && !(Time.time - _lastUpdate < 0.1f))
			{
				_lastUpdate = Time.time;
				AuraManager.UpdateAllAuras();
				AuraManager.CleanupDeadAuras();
				if (Time.time - _lastAuraCheck > 2f)
				{
					_lastAuraCheck = Time.time;
					AuraManager.ApplyAurasToAllPlayers();
				}
			}
		}
	}
	[HarmonyPatch(typeof(Player), "TakeInput")]
	public static class Player_TakeInput_Patch
	{
		[HarmonyPrefix]
		public static bool Prefix(Player __instance, ref bool __result)
		{
			if (EtherealPlugin.ShowColorMenu)
			{
				__result = false;
				return false;
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(GameCamera), "UpdateMouseCapture")]
	public static class GameCamera_UpdateMouseCapture_Patch
	{
		[HarmonyPostfix]
		public static void Postfix()
		{
			if (EtherealPlugin.ShowColorMenu)
			{
				Cursor.lockState = (CursorLockMode)0;
				Cursor.visible = true;
			}
		}
	}
	[HarmonyPatch(typeof(Menu), "IsVisible")]
	public static class Menu_IsVisible_Patch
	{
		[HarmonyPostfix]
		public static void Postfix(ref bool __result)
		{
			if (EtherealPlugin.ShowColorMenu)
			{
				__result = true;
			}
		}
	}
	[HarmonyPatch(typeof(Chat), "RPC_ChatMessage")]
	public static class Chat_RPC_ChatMessage_Patch
	{
		[HarmonyPrefix]
		public static void Prefix(ref string text, ref int type)
		{
			try
			{
				if (type == 2 && !((Object)(object)Player.m_localPlayer == (Object)null))
				{
					string playerName = Player.m_localPlayer.GetPlayerName();
					EtherealPlayerData etherealData = EtherealPlugin.GetEtherealData(playerName);
					if (etherealData != null && etherealData.SelectedColor != "None")
					{
						EtherealPlugin.Log.LogInfo((object)("Ethereal player " + playerName + " is shouting"));
					}
				}
			}
			catch (Exception ex)
			{
				EtherealPlugin.Log.LogWarning((object)("Error in RPC_ChatMessage patch: " + ex.Message));
			}
		}
	}
	[HarmonyPatch(typeof(Chat), "UpdateWorldTexts")]
	public static class Chat_UpdateWorldTexts_Patch
	{
		[HarmonyPostfix]
		public static void Postfix(Chat __instance)
		{
			//IL_0193: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				FieldInfo field = typeof(Chat).GetField("m_worldTexts", BindingFlags.Instance | BindingFlags.NonPublic);
				if (field == null || !(field.GetValue(__instance) is IList list))
				{
					return;
				}
				foreach (object item in list)
				{
					FieldInfo field2 = item.GetType().GetField("m_type");
					FieldInfo fieldInfo = item.GetType().GetField("m_textMeshField") ?? item.GetType().GetField("m_text");
					FieldInfo field3 = item.GetType().GetField("m_name");
					if (field2 == null || field3 == null)
					{
						continue;
					}
					object value = field2.GetValue(item);
					if (value == null || (int)value != 2)
					{
						continue;
					}
					string text = field3.GetValue(item) as string;
					if (string.IsNullOrEmpty(text))
					{
						continue;
					}
					EtherealPlayerData etherealData = EtherealPlugin.GetEtherealData(text);
					if (etherealData == null || etherealData.SelectedColor == "None" || !(fieldInfo != null))
					{
						continue;
					}
					object value2 = fieldInfo.GetValue(item);
					if (value2 != null)
					{
						PropertyInfo property = value2.GetType().GetProperty("color");
						if (property != null)
						{
							property.SetValue(value2, NameColorPatches.EtherealShoutColor);
						}
					}
				}
			}
			catch
			{
			}
		}
	}
}

BepInEx/plugins/VikingMessages.dll

Decompiled 2 weeks ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using Microsoft.CodeAnalysis;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.Networking;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyCompany("VikingMessages")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyCopyright("Copyright © 2024")]
[assembly: AssemblyDescription("Elden Ring-inspired message system for Valheim")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("Viking Messages")]
[assembly: AssemblyTitle("Viking Messages")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace VikingMessages
{
	[Serializable]
	public class VikingMessage
	{
		public string Id;

		public Vector3 Position;

		public Quaternion Rotation;

		public string Template;

		public string Words;

		public int EmoteIndex;

		public long AuthorId;

		public string AuthorName;

		public int Reputation;

		public List<long> VotedPlayers = new List<long>();

		public DateTime CreatedTime;

		public string[] EquippedItems = new string[0];

		public Vector3 LookDirection;
	}
	[Serializable]
	public class PlayerReputation
	{
		public long PlayerId;

		public string PlayerName;

		public int TotalReputation;

		public int MessageCount;

		public PlayerReputation()
		{
		}

		public PlayerReputation(long id, string name)
		{
			PlayerId = id;
			PlayerName = name;
			TotalReputation = 0;
			MessageCount = 0;
		}
	}
	[Serializable]
	public class LeaderboardData
	{
		public List<PlayerReputation> Players = new List<PlayerReputation>();
	}
	public class GhostPhantom : MonoBehaviour
	{
		[CompilerGenerated]
		private sealed class <PlayEmoteDelayed>d__21 : IEnumerator<object>, IDisposable, IEnumerator
		{
			private int <>1__state;

			private object <>2__current;

			public string emoteName;

			public GhostPhantom <>4__this;

			private string <triggerName>5__1;

			private Exception <ex>5__2;

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

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

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

			[DebuggerHidden]
			void IDisposable.Dispose()
			{
				<triggerName>5__1 = null;
				<ex>5__2 = null;
				<>1__state = -2;
			}

			private bool MoveNext()
			{
				//IL_0026: Unknown result type (might be due to invalid IL or missing references)
				//IL_0030: Expected O, but got Unknown
				switch (<>1__state)
				{
				default:
					return false;
				case 0:
					<>1__state = -1;
					<>2__current = (object)new WaitForSeconds(0.1f);
					<>1__state = 1;
					return true;
				case 1:
					<>1__state = -1;
					if ((Object)(object)<>4__this._animator != (Object)null)
					{
						try
						{
							((Behaviour)<>4__this._animator).enabled = true;
							<>4__this._animator.speed = 0.7f;
							<triggerName>5__1 = "emote_" + emoteName.ToLower();
							ManualLogSource log = VikingMessagesPlugin.Log;
							if (log != null)
							{
								log.LogInfo((object)("Attempting to play emote trigger: " + <triggerName>5__1));
							}
							<>4__this._animator.SetTrigger(<triggerName>5__1);
							<triggerName>5__1 = null;
						}
						catch (Exception ex)
						{
							<ex>5__2 = ex;
							ManualLogSource log2 = VikingMessagesPlugin.Log;
							if (log2 != null)
							{
								log2.LogWarning((object)("Failed to play emote " + emoteName + ": " + <ex>5__2.Message));
							}
						}
					}
					else
					{
						ManualLogSource log3 = VikingMessagesPlugin.Log;
						if (log3 != null)
						{
							log3.LogWarning((object)"No animator available for ghost emote");
						}
					}
					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();
			}
		}

		[CompilerGenerated]
		private sealed class <SetupGhostCoroutine>d__13 : IEnumerator<object>, IDisposable, IEnumerator
		{
			private int <>1__state;

			private object <>2__current;

			public GhostPhantom <>4__this;

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

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

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

			[DebuggerHidden]
			void IDisposable.Dispose()
			{
				<>1__state = -2;
			}

			private bool MoveNext()
			{
				switch (<>1__state)
				{
				default:
					return false;
				case 0:
					<>1__state = -1;
					<>2__current = null;
					<>1__state = 1;
					return true;
				case 1:
					<>1__state = -1;
					if ((Object)(object)Player.m_localPlayer == (Object)null)
					{
						ManualLogSource log = VikingMessagesPlugin.Log;
						if (log != null)
						{
							log.LogWarning((object)"No local player for ghost clone");
						}
						<>4__this.CreateFallbackGhost();
					}
					else
					{
						<>4__this.CreatePlayerClone();
					}
					<>4__this.CreateGlowLight();
					<>4__this.Show();
					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 float _displayDuration = 5f;

		private float _currentTimer;

		private float _fadeInTime = 0.5f;

		private bool _isVisible;

		private List<Renderer> _renderers = new List<Renderer>();

		private static readonly Color GhostColor = new Color(0.85f, 0.9f, 1f, 0.7f);

		private GameObject _visualClone;

		private Animator _animator;

		private Light _glowLight;

		private string _pendingEmote;

		private VikingMessage _message;

		public void Initialize(VikingMessage message, float duration = 5f)
		{
			_message = message;
			_displayDuration = duration;
			_pendingEmote = GetEmoteName(message.EmoteIndex);
			ManualLogSource log = VikingMessagesPlugin.Log;
			if (log != null)
			{
				log.LogInfo((object)$"GhostPhantom.Initialize: emote={_pendingEmote}, emoteIndex={message.EmoteIndex}");
			}
		}

		private void Start()
		{
			((MonoBehaviour)this).StartCoroutine(SetupGhostCoroutine());
		}

		[IteratorStateMachine(typeof(<SetupGhostCoroutine>d__13))]
		private IEnumerator SetupGhostCoroutine()
		{
			//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
			return new <SetupGhostCoroutine>d__13(0)
			{
				<>4__this = this
			};
		}

		private void CreatePlayerClone()
		{
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				Player localPlayer = Player.m_localPlayer;
				Transform val = ((Component)localPlayer).transform.Find("Visual");
				if ((Object)(object)val == (Object)null)
				{
					ManualLogSource log = VikingMessagesPlugin.Log;
					if (log != null)
					{
						log.LogWarning((object)"Could not find Visual transform on player");
					}
					CreateFallbackGhost();
					return;
				}
				_visualClone = Object.Instantiate<GameObject>(((Component)val).gameObject, ((Component)this).transform);
				((Object)_visualClone).name = "GhostVisual";
				_visualClone.transform.localPosition = Vector3.zero;
				_visualClone.transform.localRotation = Quaternion.identity;
				_visualClone.transform.localScale = Vector3.one;
				_animator = _visualClone.GetComponent<Animator>();
				if ((Object)(object)_animator == (Object)null)
				{
					_animator = _visualClone.GetComponentInChildren<Animator>();
				}
				DisableComponents(_visualClone);
				Renderer[] componentsInChildren = _visualClone.GetComponentsInChildren<Renderer>(true);
				foreach (Renderer val2 in componentsInChildren)
				{
					if ((Object)(object)val2 != (Object)null)
					{
						val2.enabled = true;
						SkinnedMeshRenderer val3 = (SkinnedMeshRenderer)(object)((val2 is SkinnedMeshRenderer) ? val2 : null);
						if (val3 != null)
						{
							val3.updateWhenOffscreen = true;
						}
					}
				}
				Transform[] componentsInChildren2 = _visualClone.GetComponentsInChildren<Transform>(true);
				foreach (Transform val4 in componentsInChildren2)
				{
					if ((Object)(object)val4 != (Object)null && (Object)(object)((Component)val4).gameObject != (Object)null)
					{
						((Component)val4).gameObject.SetActive(true);
					}
				}
				ApplyGhostMaterials(_visualClone);
				ManualLogSource log2 = VikingMessagesPlugin.Log;
				if (log2 != null)
				{
					log2.LogInfo((object)$"Ghost clone created successfully with {_renderers.Count} renderers");
				}
			}
			catch (Exception arg)
			{
				ManualLogSource log3 = VikingMessagesPlugin.Log;
				if (log3 != null)
				{
					log3.LogError((object)$"Failed to create player clone: {arg}");
				}
				CreateFallbackGhost();
			}
		}

		private void DisableComponents(GameObject obj)
		{
			MonoBehaviour[] componentsInChildren = obj.GetComponentsInChildren<MonoBehaviour>(true);
			foreach (MonoBehaviour val in componentsInChildren)
			{
				if ((Object)(object)val != (Object)null && (Object)(object)val != (Object)(object)this)
				{
					((Behaviour)val).enabled = false;
				}
			}
			ZNetView[] componentsInChildren2 = obj.GetComponentsInChildren<ZNetView>(true);
			foreach (ZNetView val2 in componentsInChildren2)
			{
				if ((Object)(object)val2 != (Object)null)
				{
					Object.Destroy((Object)(object)val2);
				}
			}
			ZSyncTransform[] componentsInChildren3 = obj.GetComponentsInChildren<ZSyncTransform>(true);
			foreach (ZSyncTransform val3 in componentsInChildren3)
			{
				if ((Object)(object)val3 != (Object)null)
				{
					Object.Destroy((Object)(object)val3);
				}
			}
			ZSyncAnimation[] componentsInChildren4 = obj.GetComponentsInChildren<ZSyncAnimation>(true);
			foreach (ZSyncAnimation val4 in componentsInChildren4)
			{
				if ((Object)(object)val4 != (Object)null)
				{
					Object.Destroy((Object)(object)val4);
				}
			}
			VisEquipment[] componentsInChildren5 = obj.GetComponentsInChildren<VisEquipment>(true);
			foreach (VisEquipment val5 in componentsInChildren5)
			{
				if ((Object)(object)val5 != (Object)null)
				{
					Object.Destroy((Object)(object)val5);
				}
			}
			Collider[] componentsInChildren6 = obj.GetComponentsInChildren<Collider>(true);
			foreach (Collider val6 in componentsInChildren6)
			{
				if ((Object)(object)val6 != (Object)null)
				{
					val6.enabled = false;
				}
			}
			ParticleSystem[] componentsInChildren7 = obj.GetComponentsInChildren<ParticleSystem>(true);
			foreach (ParticleSystem val7 in componentsInChildren7)
			{
				if ((Object)(object)val7 != (Object)null)
				{
					val7.Stop();
				}
			}
			AudioSource[] componentsInChildren8 = obj.GetComponentsInChildren<AudioSource>(true);
			foreach (AudioSource val8 in componentsInChildren8)
			{
				if ((Object)(object)val8 != (Object)null)
				{
					((Behaviour)val8).enabled = false;
				}
			}
		}

		private void ApplyGhostMaterials(GameObject obj)
		{
			_renderers.Clear();
			Renderer[] componentsInChildren = obj.GetComponentsInChildren<Renderer>(true);
			foreach (Renderer val in componentsInChildren)
			{
				if (!((Object)(object)val == (Object)null))
				{
					_renderers.Add(val);
					Material[] array = (Material[])(object)new Material[val.sharedMaterials.Length];
					for (int j = 0; j < val.sharedMaterials.Length; j++)
					{
						Material val2 = CreateGhostMaterial(val.sharedMaterials[j]);
						array[j] = val2;
					}
					val.materials = array;
				}
			}
		}

		private Material CreateGhostMaterial(Material sourceMat)
		{
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Expected O, but got Unknown
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
			Shader val = Shader.Find("Standard");
			if ((Object)(object)val == (Object)null)
			{
				val = Shader.Find("Sprites/Default");
			}
			Material val2 = new Material(val);
			if ((Object)(object)sourceMat != (Object)null && sourceMat.HasProperty("_MainTex"))
			{
				val2.mainTexture = sourceMat.mainTexture;
			}
			val2.color = GhostColor;
			val2.SetFloat("_Mode", 3f);
			val2.SetInt("_SrcBlend", 5);
			val2.SetInt("_DstBlend", 10);
			val2.SetInt("_ZWrite", 0);
			val2.DisableKeyword("_ALPHATEST_ON");
			val2.EnableKeyword("_ALPHABLEND_ON");
			val2.DisableKeyword("_ALPHAPREMULTIPLY_ON");
			val2.renderQueue = 3000;
			val2.EnableKeyword("_EMISSION");
			val2.SetColor("_EmissionColor", new Color(0.3f, 0.4f, 0.5f));
			return val2;
		}

		private void CreateFallbackGhost()
		{
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0106: Unknown result type (might be due to invalid IL or missing references)
			//IL_0172: Unknown result type (might be due to invalid IL or missing references)
			//IL_0193: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_0223: Unknown result type (might be due to invalid IL or missing references)
			//IL_0244: Unknown result type (might be due to invalid IL or missing references)
			//IL_0265: Unknown result type (might be due to invalid IL or missing references)
			ManualLogSource log = VikingMessagesPlugin.Log;
			if (log != null)
			{
				log.LogInfo((object)"Creating fallback ghost (primitive shapes)");
			}
			Material val = CreateGhostMaterial(null);
			GameObject val2 = GameObject.CreatePrimitive((PrimitiveType)1);
			((Object)val2).name = "GhostBody";
			val2.transform.SetParent(((Component)this).transform);
			val2.transform.localPosition = new Vector3(0f, 1f, 0f);
			val2.transform.localScale = new Vector3(0.5f, 0.7f, 0.35f);
			Object.Destroy((Object)(object)val2.GetComponent<Collider>());
			Renderer component = val2.GetComponent<Renderer>();
			component.material = val;
			_renderers.Add(component);
			GameObject val3 = GameObject.CreatePrimitive((PrimitiveType)0);
			((Object)val3).name = "GhostHead";
			val3.transform.SetParent(((Component)this).transform);
			val3.transform.localPosition = new Vector3(0f, 1.85f, 0f);
			val3.transform.localScale = new Vector3(0.35f, 0.35f, 0.35f);
			Object.Destroy((Object)(object)val3.GetComponent<Collider>());
			Renderer component2 = val3.GetComponent<Renderer>();
			component2.material = Object.Instantiate<Material>(val);
			_renderers.Add(component2);
			GameObject val4 = GameObject.CreatePrimitive((PrimitiveType)1);
			val4.transform.SetParent(((Component)this).transform);
			val4.transform.localPosition = new Vector3(-0.4f, 1.2f, 0f);
			val4.transform.localRotation = Quaternion.Euler(0f, 0f, 30f);
			val4.transform.localScale = new Vector3(0.12f, 0.35f, 0.12f);
			Object.Destroy((Object)(object)val4.GetComponent<Collider>());
			val4.GetComponent<Renderer>().material = Object.Instantiate<Material>(val);
			_renderers.Add(val4.GetComponent<Renderer>());
			GameObject val5 = GameObject.CreatePrimitive((PrimitiveType)1);
			val5.transform.SetParent(((Component)this).transform);
			val5.transform.localPosition = new Vector3(0.4f, 1.2f, 0f);
			val5.transform.localRotation = Quaternion.Euler(0f, 0f, -30f);
			val5.transform.localScale = new Vector3(0.12f, 0.35f, 0.12f);
			Object.Destroy((Object)(object)val5.GetComponent<Collider>());
			val5.GetComponent<Renderer>().material = Object.Instantiate<Material>(val);
			_renderers.Add(val5.GetComponent<Renderer>());
		}

		private void CreateGlowLight()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Expected O, but got Unknown
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject("GhostLight");
			val.transform.SetParent(((Component)this).transform);
			val.transform.localPosition = new Vector3(0f, 1.2f, 0f);
			_glowLight = val.AddComponent<Light>();
			_glowLight.type = (LightType)2;
			_glowLight.color = new Color(0.7f, 0.8f, 1f);
			_glowLight.intensity = 0.8f;
			_glowLight.range = 3f;
			_glowLight.shadows = (LightShadows)0;
		}

		public void Show()
		{
			((Component)this).gameObject.SetActive(true);
			_isVisible = true;
			_currentTimer = _displayDuration;
			if (!string.IsNullOrEmpty(_pendingEmote))
			{
				((MonoBehaviour)this).StartCoroutine(PlayEmoteDelayed(_pendingEmote));
			}
			UpdateAlpha(0f);
		}

		[IteratorStateMachine(typeof(<PlayEmoteDelayed>d__21))]
		private IEnumerator PlayEmoteDelayed(string emoteName)
		{
			//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
			return new <PlayEmoteDelayed>d__21(0)
			{
				<>4__this = this,
				emoteName = emoteName
			};
		}

		public void Hide()
		{
			_isVisible = false;
			((Component)this).gameObject.SetActive(false);
			foreach (Renderer renderer in _renderers)
			{
				if (!((Object)(object)renderer != (Object)null))
				{
					continue;
				}
				Material[] materials = renderer.materials;
				foreach (Material val in materials)
				{
					if ((Object)(object)val != (Object)null)
					{
						Object.Destroy((Object)(object)val);
					}
				}
			}
			Object.Destroy((Object)(object)((Component)this).gameObject, 0.1f);
		}

		private void Update()
		{
			if (_isVisible)
			{
				_currentTimer -= Time.deltaTime;
				EnsureRenderersEnabled();
				float num = _displayDuration - _currentTimer;
				float num2 = 2f;
				float alpha = ((num < _fadeInTime) ? (num / _fadeInTime * 0.7f) : ((!(_currentTimer < num2)) ? 0.7f : (_currentTimer / num2 * 0.7f)));
				UpdateAlpha(alpha);
				if ((Object)(object)_glowLight != (Object)null)
				{
					_glowLight.intensity = 0.6f + Mathf.Sin(Time.time * 3f) * 0.2f;
				}
				if (_currentTimer <= 0f)
				{
					Hide();
				}
			}
		}

		private void EnsureRenderersEnabled()
		{
			if ((Object)(object)_visualClone == (Object)null)
			{
				return;
			}
			Renderer[] componentsInChildren = _visualClone.GetComponentsInChildren<Renderer>(true);
			foreach (Renderer val in componentsInChildren)
			{
				if ((Object)(object)val != (Object)null && !val.enabled)
				{
					val.enabled = true;
				}
			}
			Transform[] componentsInChildren2 = _visualClone.GetComponentsInChildren<Transform>(true);
			foreach (Transform val2 in componentsInChildren2)
			{
				if ((Object)(object)val2 != (Object)null && (Object)(object)((Component)val2).gameObject != (Object)null && !((Component)val2).gameObject.activeSelf && ((Object)(object)((Component)val2).GetComponent<Renderer>() != (Object)null || (Object)(object)((Component)val2).GetComponent<SkinnedMeshRenderer>() != (Object)null))
				{
					((Component)val2).gameObject.SetActive(true);
				}
			}
		}

		private void UpdateAlpha(float alpha)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			Color ghostColor = GhostColor;
			ghostColor.a = alpha;
			foreach (Renderer renderer in _renderers)
			{
				if ((Object)(object)renderer == (Object)null)
				{
					continue;
				}
				Material[] materials = renderer.materials;
				foreach (Material val in materials)
				{
					if ((Object)(object)val != (Object)null)
					{
						val.color = ghostColor;
					}
				}
			}
		}

		private string GetEmoteName(int emoteIndex)
		{
			List<string> availableEmotes = MessageTemplates.AvailableEmotes;
			if (availableEmotes != null && emoteIndex >= 0 && emoteIndex < availableEmotes.Count)
			{
				return availableEmotes[emoteIndex];
			}
			return "wave";
		}

		private void OnDestroy()
		{
			foreach (Renderer renderer in _renderers)
			{
				if (!((Object)(object)renderer != (Object)null))
				{
					continue;
				}
				Material[] materials = renderer.materials;
				foreach (Material val in materials)
				{
					if ((Object)(object)val != (Object)null)
					{
						Object.Destroy((Object)(object)val);
					}
				}
			}
			_renderers.Clear();
		}
	}
	public static class GhostPhantomManager
	{
		private static GhostPhantom _currentGhost;

		public static void ShowGhost(Vector3 position, Quaternion rotation, VikingMessage message, float duration = 5f)
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Expected O, but got Unknown
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				if ((Object)(object)_currentGhost != (Object)null)
				{
					_currentGhost.Hide();
					_currentGhost = null;
				}
				GameObject val = new GameObject("VikingMessageGhost");
				val.transform.position = position;
				val.transform.rotation = rotation;
				_currentGhost = val.AddComponent<GhostPhantom>();
				_currentGhost.Initialize(message, duration);
				ManualLogSource log = VikingMessagesPlugin.Log;
				if (log != null)
				{
					log.LogInfo((object)$"Ghost spawned at {position} with rotation {((Quaternion)(ref rotation)).eulerAngles}");
				}
			}
			catch (Exception arg)
			{
				ManualLogSource log2 = VikingMessagesPlugin.Log;
				if (log2 != null)
				{
					log2.LogError((object)$"Failed to spawn ghost: {arg}");
				}
			}
		}

		public static void HideCurrentGhost()
		{
			if ((Object)(object)_currentGhost != (Object)null)
			{
				_currentGhost.Hide();
				_currentGhost = null;
			}
		}

		public static void Cleanup()
		{
			HideCurrentGhost();
		}
	}
	public static class LeaderboardManager
	{
		[CompilerGenerated]
		private static class <>O
		{
			public static UnityAction <0>__CloseLeaderboard;
		}

		private static GameObject _leaderboardUI;

		private static bool _isVisible;

		private static bool _hasStealthBuff;

		private static bool _hasCarryBuff;

		public const float CARRY_WEIGHT_BONUS = 500f;

		private static SE_Stats _reputationBuff;

		private const string BUFF_NAME = "SE_ReputationTop3";

		public static bool IsVisible => _isVisible;

		public static void ShowLeaderboard()
		{
			if ((Object)(object)_leaderboardUI != (Object)null)
			{
				CloseLeaderboard();
				return;
			}
			CreateLeaderboardUI();
			_isVisible = true;
			GUIManager.BlockInput(true);
		}

		public static void CloseLeaderboard()
		{
			if ((Object)(object)_leaderboardUI != (Object)null)
			{
				Object.Destroy((Object)(object)_leaderboardUI);
				_leaderboardUI = null;
			}
			_isVisible = false;
			GUIManager.BlockInput(false);
		}

		private static void CreateLeaderboardUI()
		{
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			if (GUIManager.Instance == null)
			{
				ManualLogSource log = VikingMessagesPlugin.Log;
				if (log != null)
				{
					log.LogWarning((object)"GUIManager not ready");
				}
				return;
			}
			try
			{
				_leaderboardUI = GUIManager.Instance.CreateWoodpanel(GUIManager.CustomGUIFront.transform, new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), new Vector2(0f, 0f), 500f, 550f, false);
			}
			catch (Exception ex)
			{
				ManualLogSource log2 = VikingMessagesPlugin.Log;
				if (log2 != null)
				{
					log2.LogWarning((object)("CreateWoodpanel failed: " + ex.Message));
				}
			}
			if ((Object)(object)_leaderboardUI == (Object)null)
			{
				_leaderboardUI = CreateFallbackPanel();
			}
			if ((Object)(object)_leaderboardUI == (Object)null)
			{
				ManualLogSource log3 = VikingMessagesPlugin.Log;
				if (log3 != null)
				{
					log3.LogError((object)"Failed to create leaderboard UI");
				}
			}
			else
			{
				PopulateLeaderboardContent();
			}
		}

		private static GameObject CreateFallbackPanel()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Expected O, but got Unknown
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Expected O, but got Unknown
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0101: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject("VikingMessages_LeaderboardCanvas");
			Canvas val2 = val.AddComponent<Canvas>();
			val2.renderMode = (RenderMode)0;
			val2.sortingOrder = 100;
			CanvasScaler val3 = val.AddComponent<CanvasScaler>();
			val3.uiScaleMode = (ScaleMode)1;
			val3.referenceResolution = new Vector2(1920f, 1080f);
			val.AddComponent<GraphicRaycaster>();
			GameObject val4 = new GameObject("Panel");
			val4.transform.SetParent(val.transform, false);
			RectTransform val5 = val4.AddComponent<RectTransform>();
			val5.sizeDelta = new Vector2(500f, 550f);
			val5.anchorMin = new Vector2(0.5f, 0.5f);
			val5.anchorMax = new Vector2(0.5f, 0.5f);
			val5.anchoredPosition = Vector2.zero;
			Image val6 = val4.AddComponent<Image>();
			((Graphic)val6).color = new Color(0.18f, 0.12f, 0.08f, 0.97f);
			CreateBorderFrame(val4.transform, new Vector2(500f, 550f));
			return val4;
		}

		private static void CreateBorderFrame(Transform parent, Vector2 size)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Expected O, but got Unknown
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Expected O, but got Unknown
			//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00de: Unknown result type (might be due to invalid IL or missing references)
			//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0108: Unknown result type (might be due to invalid IL or missing references)
			//IL_010f: Expected O, but got Unknown
			//IL_0138: Unknown result type (might be due to invalid IL or missing references)
			//IL_014e: Unknown result type (might be due to invalid IL or missing references)
			//IL_015f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0176: Unknown result type (might be due to invalid IL or missing references)
			//IL_018d: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bb: Expected O, but got Unknown
			//IL_01e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_020b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0222: Unknown result type (might be due to invalid IL or missing references)
			//IL_0239: Unknown result type (might be due to invalid IL or missing references)
			//IL_0250: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject("OuterBorder");
			val.transform.SetParent(parent, false);
			Image val2 = val.AddComponent<Image>();
			((Graphic)val2).color = new Color(0.6f, 0.45f, 0.2f);
			RectTransform component = val.GetComponent<RectTransform>();
			component.sizeDelta = new Vector2(size.x + 8f, size.y + 8f);
			component.anchoredPosition = Vector2.zero;
			val.transform.SetAsFirstSibling();
			GameObject val3 = new GameObject("InnerBorder");
			val3.transform.SetParent(parent, false);
			Image val4 = val3.AddComponent<Image>();
			((Graphic)val4).color = new Color(0.1f, 0.07f, 0.04f);
			RectTransform component2 = val3.GetComponent<RectTransform>();
			component2.sizeDelta = new Vector2(size.x + 4f, size.y + 4f);
			component2.anchoredPosition = Vector2.zero;
			val3.transform.SetSiblingIndex(1);
			GameObject val5 = new GameObject("TopBar");
			val5.transform.SetParent(parent, false);
			Image val6 = val5.AddComponent<Image>();
			((Graphic)val6).color = new Color(0.5f, 0.38f, 0.18f);
			RectTransform component3 = val5.GetComponent<RectTransform>();
			component3.sizeDelta = new Vector2(size.x - 40f, 4f);
			component3.anchorMin = new Vector2(0.5f, 1f);
			component3.anchorMax = new Vector2(0.5f, 1f);
			component3.anchoredPosition = new Vector2(0f, -25f);
			GameObject val7 = new GameObject("BottomBar");
			val7.transform.SetParent(parent, false);
			Image val8 = val7.AddComponent<Image>();
			((Graphic)val8).color = new Color(0.5f, 0.38f, 0.18f);
			RectTransform component4 = val7.GetComponent<RectTransform>();
			component4.sizeDelta = new Vector2(size.x - 40f, 4f);
			component4.anchorMin = new Vector2(0.5f, 0f);
			component4.anchorMax = new Vector2(0.5f, 0f);
			component4.anchoredPosition = new Vector2(0f, 25f);
		}

		private static void PopulateLeaderboardContent()
		{
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: 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_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0110: Unknown result type (might be due to invalid IL or missing references)
			//IL_0117: Unknown result type (might be due to invalid IL or missing references)
			//IL_0140: Unknown result type (might be due to invalid IL or missing references)
			//IL_0147: Unknown result type (might be due to invalid IL or missing references)
			//IL_0170: Unknown result type (might be due to invalid IL or missing references)
			//IL_0177: Unknown result type (might be due to invalid IL or missing references)
			//IL_019b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0202: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0207: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_03bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_0402: Unknown result type (might be due to invalid IL or missing references)
			//IL_024d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0254: Unknown result type (might be due to invalid IL or missing references)
			//IL_0223: Unknown result type (might be due to invalid IL or missing references)
			//IL_0228: Unknown result type (might be due to invalid IL or missing references)
			//IL_045c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0472: Unknown result type (might be due to invalid IL or missing references)
			//IL_0303: Unknown result type (might be due to invalid IL or missing references)
			//IL_030a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0338: Unknown result type (might be due to invalid IL or missing references)
			//IL_033f: Unknown result type (might be due to invalid IL or missing references)
			GUIManager instance = GUIManager.Instance;
			Font font = ((instance != null) ? instance.AveriaSerifBold : null);
			Font font2 = ((instance != null) ? instance.AveriaSerif : null);
			Color color = (Color)(((??)instance?.ValheimOrange) ?? new Color(1f, 0.64f, 0.1f));
			CreateStyledText(_leaderboardUI.transform, "Reputation Leaderboard", new Vector2(0f, -40f), 28, color, font, (TextAnchor)4, outline: true);
			CreateStyledText(_leaderboardUI.transform, "Top 3 players gain +100% Stamina Regen & +500 Carry Weight", new Vector2(0f, -75f), 14, new Color(0.85f, 0.8f, 0.65f), font2, (TextAnchor)4, outline: true);
			CreateStyledText(_leaderboardUI.transform, "[F7] Toggle", new Vector2(0f, -95f), 12, new Color(0.6f, 0.55f, 0.4f), font2, (TextAnchor)4, outline: false);
			CreateStyledText(_leaderboardUI.transform, "Rank", new Vector2(-180f, -130f), 16, color, font, (TextAnchor)4, outline: true, bottomAnchor: false, 60f);
			CreateStyledText(_leaderboardUI.transform, "Player", new Vector2(-50f, -130f), 16, color, font, (TextAnchor)3, outline: true, bottomAnchor: false, 150f);
			CreateStyledText(_leaderboardUI.transform, "Reputation", new Vector2(140f, -130f), 16, color, font, (TextAnchor)4, outline: true, bottomAnchor: false, 100f);
			CreateDividerLine(_leaderboardUI.transform, new Vector2(0f, -150f), 420f);
			List<PlayerReputation> leaderboard = MessageManagerAlt.GetLeaderboard();
			float num = -175f;
			int num2 = 1;
			foreach (PlayerReputation item in leaderboard.Take(12))
			{
				bool flag = num2 <= 3;
				Color val = (Color)(flag ? GetRankColor(num2) : new Color(0.9f, 0.85f, 0.7f));
				if (flag)
				{
					CreateRowHighlight(_leaderboardUI.transform, new Vector2(0f, num), val);
				}
				string rankDisplay = GetRankDisplay(num2);
				CreateStyledText(_leaderboardUI.transform, rankDisplay, new Vector2(-180f, num), 16, val, font, (TextAnchor)4, outline: true, bottomAnchor: false, 60f);
				string text = item.PlayerName ?? "Unknown";
				if (string.IsNullOrEmpty(text) || string.IsNullOrWhiteSpace(text))
				{
					text = "Anonymous";
				}
				if (text.Length > 18)
				{
					text = text.Substring(0, 15) + "...";
				}
				ManualLogSource log = VikingMessagesPlugin.Log;
				if (log != null)
				{
					log.LogInfo((object)$"Leaderboard display: rank={num2}, name='{text}', rep={item.TotalReputation}");
				}
				CreateStyledText(_leaderboardUI.transform, text, new Vector2(-50f, num), 15, val, font2, (TextAnchor)3, outline: true, bottomAnchor: false, 150f);
				CreateStyledText(_leaderboardUI.transform, item.TotalReputation.ToString(), new Vector2(140f, num), 16, val, font, (TextAnchor)4, outline: true, bottomAnchor: false, 100f);
				num -= 32f;
				num2++;
			}
			if (leaderboard.Count == 0)
			{
				CreateStyledText(_leaderboardUI.transform, "No reputation data yet!", new Vector2(0f, -220f), 18, new Color(0.75f, 0.7f, 0.55f), font, (TextAnchor)4, outline: true);
				CreateStyledText(_leaderboardUI.transform, "Place messages and earn votes to appear here.", new Vector2(0f, -255f), 14, new Color(0.6f, 0.55f, 0.45f), font2, (TextAnchor)4, outline: true);
			}
			if ((Object)(object)Player.m_localPlayer != (Object)null)
			{
				long playerID = Player.m_localPlayer.GetPlayerID();
				if (MessageManagerAlt.IsPlayerInTop3(playerID))
				{
					CreateStyledText(_leaderboardUI.transform, "★ You are in the Top 3! Buffs Active ★", new Vector2(0f, 80f), 16, new Color(0.4f, 1f, 0.4f), font, (TextAnchor)4, outline: true, bottomAnchor: true);
				}
			}
			CreateCloseButton(_leaderboardUI.transform);
		}

		private static void CreateStyledText(Transform parent, string text, Vector2 position, int fontSize, Color color, Font font, TextAnchor alignment, bool outline, bool bottomAnchor = false, float width = 400f)
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Expected O, but got Unknown
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0092: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00af: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0102: Unknown result type (might be due to invalid IL or missing references)
			//IL_011c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0133: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject("Text_" + text.Substring(0, Math.Min(10, text.Length)));
			val.transform.SetParent(parent, false);
			Text val2 = val.AddComponent<Text>();
			val2.text = text;
			val2.font = font ?? Resources.GetBuiltinResource<Font>("Arial.ttf");
			val2.fontSize = fontSize;
			((Graphic)val2).color = color;
			val2.alignment = alignment;
			val2.horizontalOverflow = (HorizontalWrapMode)1;
			val2.verticalOverflow = (VerticalWrapMode)1;
			RectTransform component = val.GetComponent<RectTransform>();
			component.sizeDelta = new Vector2(width, 30f);
			if (bottomAnchor)
			{
				component.anchorMin = new Vector2(0.5f, 0f);
				component.anchorMax = new Vector2(0.5f, 0f);
			}
			else
			{
				component.anchorMin = new Vector2(0.5f, 1f);
				component.anchorMax = new Vector2(0.5f, 1f);
			}
			component.anchoredPosition = position;
			if (outline)
			{
				Outline val3 = val.AddComponent<Outline>();
				((Shadow)val3).effectColor = Color.black;
				((Shadow)val3).effectDistance = new Vector2(1f, -1f);
			}
		}

		private static void CreateDividerLine(Transform parent, Vector2 position, float width)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Expected O, but got Unknown
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject("Divider");
			val.transform.SetParent(parent, false);
			Image val2 = val.AddComponent<Image>();
			((Graphic)val2).color = new Color(0.5f, 0.4f, 0.25f);
			RectTransform component = val.GetComponent<RectTransform>();
			component.sizeDelta = new Vector2(width, 2f);
			component.anchorMin = new Vector2(0.5f, 1f);
			component.anchorMax = new Vector2(0.5f, 1f);
			component.anchoredPosition = position;
		}

		private static void CreateRowHighlight(Transform parent, Vector2 position, Color baseColor)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Expected O, but got Unknown
			//IL_0022: 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)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject("RowHighlight");
			val.transform.SetParent(parent, false);
			Image val2 = val.AddComponent<Image>();
			((Graphic)val2).color = new Color(baseColor.r * 0.25f, baseColor.g * 0.25f, baseColor.b * 0.15f, 0.4f);
			RectTransform component = val.GetComponent<RectTransform>();
			component.sizeDelta = new Vector2(420f, 28f);
			component.anchorMin = new Vector2(0.5f, 1f);
			component.anchorMax = new Vector2(0.5f, 1f);
			component.anchoredPosition = position;
			val.transform.SetSiblingIndex(3);
		}

		private static void CreateCloseButton(Transform parent)
		{
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Expected O, but got Unknown
			//IL_00db: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_010e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0124: Unknown result type (might be due to invalid IL or missing references)
			//IL_013a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0158: Unknown result type (might be due to invalid IL or missing references)
			//IL_015d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0170: Unknown result type (might be due to invalid IL or missing references)
			//IL_018c: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f1: Expected O, but got Unknown
			//IL_021f: Unknown result type (might be due to invalid IL or missing references)
			//IL_023f: Unknown result type (might be due to invalid IL or missing references)
			//IL_024c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0269: Unknown result type (might be due to invalid IL or missing references)
			//IL_0270: Expected O, but got Unknown
			//IL_01d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01df: Expected O, but got Unknown
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0300: Unknown result type (might be due to invalid IL or missing references)
			//IL_030d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0323: Unknown result type (might be due to invalid IL or missing references)
			//IL_033a: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Expected O, but got Unknown
			GUIManager instance = GUIManager.Instance;
			if (instance != null)
			{
				try
				{
					GameObject val = instance.CreateButton("Close", parent, new Vector2(0.5f, 0f), new Vector2(0.5f, 0f), new Vector2(0f, 45f), 140f, 45f);
					if ((Object)(object)val != (Object)null)
					{
						Button component = val.GetComponent<Button>();
						if (component != null)
						{
							ButtonClickedEvent onClick = component.onClick;
							object obj = <>O.<0>__CloseLeaderboard;
							if (obj == null)
							{
								UnityAction val2 = CloseLeaderboard;
								<>O.<0>__CloseLeaderboard = val2;
								obj = (object)val2;
							}
							((UnityEvent)onClick).AddListener((UnityAction)obj);
						}
						return;
					}
				}
				catch
				{
				}
			}
			GameObject val3 = new GameObject("CloseButton");
			val3.transform.SetParent(parent, false);
			Image val4 = val3.AddComponent<Image>();
			((Graphic)val4).color = new Color(0.35f, 0.25f, 0.15f);
			RectTransform component2 = val3.GetComponent<RectTransform>();
			component2.sizeDelta = new Vector2(140f, 45f);
			component2.anchorMin = new Vector2(0.5f, 0f);
			component2.anchorMax = new Vector2(0.5f, 0f);
			component2.anchoredPosition = new Vector2(0f, 45f);
			Button val5 = val3.AddComponent<Button>();
			((Selectable)val5).targetGraphic = (Graphic)(object)val4;
			ColorBlock colors = ((Selectable)val5).colors;
			((ColorBlock)(ref colors)).normalColor = new Color(0.35f, 0.25f, 0.15f);
			((ColorBlock)(ref colors)).highlightedColor = new Color(0.45f, 0.35f, 0.2f);
			((ColorBlock)(ref colors)).pressedColor = new Color(0.25f, 0.18f, 0.1f);
			((Selectable)val5).colors = colors;
			ButtonClickedEvent onClick2 = val5.onClick;
			object obj3 = <>O.<0>__CloseLeaderboard;
			if (obj3 == null)
			{
				UnityAction val6 = CloseLeaderboard;
				<>O.<0>__CloseLeaderboard = val6;
				obj3 = (object)val6;
			}
			((UnityEvent)onClick2).AddListener((UnityAction)obj3);
			GameObject val7 = new GameObject("Border");
			val7.transform.SetParent(val3.transform, false);
			Image val8 = val7.AddComponent<Image>();
			((Graphic)val8).color = new Color(0.55f, 0.42f, 0.22f);
			RectTransform component3 = val7.GetComponent<RectTransform>();
			component3.sizeDelta = new Vector2(144f, 49f);
			component3.anchoredPosition = Vector2.zero;
			val7.transform.SetAsFirstSibling();
			GameObject val9 = new GameObject("Text");
			val9.transform.SetParent(val3.transform, false);
			Text val10 = val9.AddComponent<Text>();
			val10.text = "Close";
			val10.font = ((instance != null) ? instance.AveriaSerifBold : null) ?? Resources.GetBuiltinResource<Font>("Arial.ttf");
			val10.fontSize = 18;
			((Graphic)val10).color = new Color(1f, 0.9f, 0.7f);
			val10.alignment = (TextAnchor)4;
			RectTransform component4 = val9.GetComponent<RectTransform>();
			component4.sizeDelta = new Vector2(140f, 45f);
			component4.anchoredPosition = Vector2.zero;
			Outline val11 = val9.AddComponent<Outline>();
			((Shadow)val11).effectColor = Color.black;
			((Shadow)val11).effectDistance = new Vector2(1f, -1f);
		}

		private static string GetRankDisplay(int rank)
		{
			return rank switch
			{
				1 => "1st", 
				2 => "2nd", 
				3 => "3rd", 
				_ => rank.ToString(), 
			};
		}

		private static Color GetRankColor(int rank)
		{
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			return (Color)(rank switch
			{
				1 => new Color(1f, 0.84f, 0f), 
				2 => new Color(0.78f, 0.78f, 0.8f), 
				3 => new Color(0.85f, 0.55f, 0.25f), 
				_ => Color.white, 
			});
		}

		public static void CheckAndApplyBuffs()
		{
			if (!((Object)(object)Player.m_localPlayer == (Object)null))
			{
				long playerID = Player.m_localPlayer.GetPlayerID();
				bool flag = MessageManagerAlt.IsPlayerInTop3(playerID);
				ManualLogSource log = VikingMessagesPlugin.Log;
				if (log != null)
				{
					log.LogInfo((object)$"CheckAndApplyBuffs: localId={playerID}, shouldHave={flag}, hasCarry={_hasCarryBuff}");
				}
				if (flag && !_hasCarryBuff)
				{
					ApplyBuffs();
				}
				else if (!flag && _hasCarryBuff)
				{
					RemoveBuffs();
				}
			}
		}

		private static void ApplyBuffs()
		{
			if ((Object)(object)Player.m_localPlayer == (Object)null)
			{
				return;
			}
			_hasCarryBuff = true;
			_hasStealthBuff = true;
			try
			{
				SEMan sEMan = ((Character)Player.m_localPlayer).GetSEMan();
				if (sEMan != null)
				{
					int stableHashCode = StringExtensionMethods.GetStableHashCode("SE_ReputationTop3");
					StatusEffect statusEffect = sEMan.GetStatusEffect(stableHashCode);
					if ((Object)(object)statusEffect != (Object)null)
					{
						sEMan.RemoveStatusEffect(statusEffect, false);
					}
					SE_Stats val = ScriptableObject.CreateInstance<SE_Stats>();
					((Object)val).name = "SE_ReputationTop3";
					((StatusEffect)val).m_name = "Reputation Champion";
					((StatusEffect)val).m_tooltip = "Top 3 Reputation Bonus:\n• +500 Carry Weight\n• +100% Stamina Regeneration";
					try
					{
						string[] array = new string[5] { "Thunderstone", "DragonTear", "SurtlingCore", "Coins", "Ruby" };
						string[] array2 = array;
						foreach (string text in array2)
						{
							ObjectDB instance = ObjectDB.instance;
							GameObject val2 = ((instance != null) ? instance.GetItemPrefab(text) : null);
							if (!((Object)(object)val2 != (Object)null))
							{
								continue;
							}
							ItemDrop component = val2.GetComponent<ItemDrop>();
							if ((Object)(object)component != (Object)null && component.m_itemData?.m_shared?.m_icons != null && component.m_itemData.m_shared.m_icons.Length != 0)
							{
								((StatusEffect)val).m_icon = component.m_itemData.m_shared.m_icons[0];
								ManualLogSource log = VikingMessagesPlugin.Log;
								if (log != null)
								{
									log.LogInfo((object)("Using icon from " + text));
								}
								break;
							}
						}
						if ((Object)(object)((StatusEffect)val).m_icon == (Object)null)
						{
							ObjectDB instance2 = ObjectDB.instance;
							StatusEffect val3 = ((instance2 != null) ? instance2.GetStatusEffect(StringExtensionMethods.GetStableHashCode("Rested")) : null);
							if ((Object)(object)val3 != (Object)null && (Object)(object)val3.m_icon != (Object)null)
							{
								((StatusEffect)val).m_icon = val3.m_icon;
							}
						}
					}
					catch
					{
					}
					val.m_addMaxCarryWeight = 500f;
					val.m_staminaRegenMultiplier = 2f;
					((StatusEffect)val).m_ttl = 0f;
					sEMan.AddStatusEffect((StatusEffect)(object)val, false, 0, 0f);
					_reputationBuff = val;
					ManualLogSource log2 = VikingMessagesPlugin.Log;
					if (log2 != null)
					{
						log2.LogInfo((object)$"Top 3 buffs applied via StatusEffect (hash={stableHashCode}): +500 carry, +100% stamina regen");
					}
				}
			}
			catch (Exception ex)
			{
				ManualLogSource log3 = VikingMessagesPlugin.Log;
				if (log3 != null)
				{
					log3.LogWarning((object)("Failed to apply StatusEffect buff: " + ex.Message));
				}
			}
			Player localPlayer = Player.m_localPlayer;
			if (localPlayer != null)
			{
				((Character)localPlayer).Message((MessageType)2, "<color=yellow>Top 3 Reputation Bonus Active!</color>\n+500 Carry Weight & +100% Stamina Regen", 0, (Sprite)null);
			}
		}

		private static void RemoveBuffs()
		{
			if ((Object)(object)Player.m_localPlayer == (Object)null)
			{
				return;
			}
			try
			{
				SEMan sEMan = ((Character)Player.m_localPlayer).GetSEMan();
				if (sEMan != null)
				{
					int stableHashCode = StringExtensionMethods.GetStableHashCode("SE_ReputationTop3");
					StatusEffect statusEffect = sEMan.GetStatusEffect(stableHashCode);
					if ((Object)(object)statusEffect != (Object)null)
					{
						sEMan.RemoveStatusEffect(statusEffect, false);
					}
				}
			}
			catch (Exception ex)
			{
				ManualLogSource log = VikingMessagesPlugin.Log;
				if (log != null)
				{
					log.LogWarning((object)("Failed to remove buff: " + ex.Message));
				}
			}
			_hasCarryBuff = false;
			_hasStealthBuff = false;
			_reputationBuff = null;
			ManualLogSource log2 = VikingMessagesPlugin.Log;
			if (log2 != null)
			{
				log2.LogInfo((object)"Top 3 buffs removed");
			}
			Player localPlayer = Player.m_localPlayer;
			if (localPlayer != null)
			{
				((Character)localPlayer).Message((MessageType)2, "<color=#888888>Reputation Bonus Removed</color>", 0, (Sprite)null);
			}
		}

		public static bool HasStealthBuff()
		{
			return _hasStealthBuff;
		}

		public static float GetCarryWeightBonus()
		{
			return _hasCarryBuff ? 500f : 0f;
		}

		public static void Update()
		{
			if (_isVisible && Input.GetKeyDown((KeyCode)27))
			{
				CloseLeaderboard();
			}
			else if (Input.GetKeyDown((KeyCode)288))
			{
				if (_isVisible)
				{
					CloseLeaderboard();
				}
				else if ((Object)(object)Player.m_localPlayer != (Object)null && !InventoryGui.IsVisible() && !Menu.IsVisible() && !Console.IsVisible())
				{
					ShowLeaderboard();
				}
			}
		}
	}
	[HarmonyPatch]
	public static class LeaderboardPatches
	{
	}
	public class MessageGlyphItem : MonoBehaviour, Hoverable
	{
		private ItemDrop _itemDrop;

		private void Awake()
		{
			_itemDrop = ((Component)this).GetComponent<ItemDrop>();
		}

		public string GetHoverText()
		{
			return "Message Glyph\n[<color=yellow><b>E</b></color>] Place Message";
		}

		public string GetHoverName()
		{
			return "Message Glyph";
		}
	}
	public class MessagePlacementHandler : MonoBehaviour
	{
		private static MessagePlacementHandler _instance;

		private bool _isPlacing;

		private float _placementTimer;

		private const float PlacementDuration = 2f;

		private Vector3 _placementPosition;

		private Quaternion _placementRotation;

		public static MessagePlacementHandler Instance
		{
			get
			{
				//IL_0016: Unknown result type (might be due to invalid IL or missing references)
				//IL_001c: Expected O, but got Unknown
				if ((Object)(object)_instance == (Object)null)
				{
					GameObject val = new GameObject("MessagePlacementHandler");
					_instance = val.AddComponent<MessagePlacementHandler>();
					Object.DontDestroyOnLoad((Object)(object)val);
				}
				return _instance;
			}
		}

		public bool IsPlacing => _isPlacing;

		private void Update()
		{
			if (_isPlacing)
			{
				_placementTimer -= Time.deltaTime;
				if (_placementTimer <= 0f)
				{
					FinishPlacement();
				}
				if ((Object)(object)Player.m_localPlayer != (Object)null && !((Character)Player.m_localPlayer).IsEncumbered() && !((Character)Player.m_localPlayer).InAttack() && !(((Character)Player.m_localPlayer).GetHealth() < ((Character)Player.m_localPlayer).GetMaxHealth() * 0.9f))
				{
				}
			}
		}

		public void StartPlacement(Player player)
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			if (!_isPlacing)
			{
				_isPlacing = true;
				_placementTimer = 2f;
				_placementPosition = ((Component)player).transform.position + ((Component)player).transform.forward * 1.5f;
				_placementRotation = Quaternion.Euler(0f, ((Component)player).transform.eulerAngles.y, 0f);
				RaycastHit val = default(RaycastHit);
				if (Physics.Raycast(_placementPosition + Vector3.up * 5f, Vector3.down, ref val, 10f, LayerMask.GetMask(new string[3] { "Default", "static_solid", "terrain" })))
				{
					_placementPosition = ((RaycastHit)(ref val)).point;
				}
				player.StartEmote("kneel", true);
				((Character)player).Message((MessageType)2, "Placing message...", 0, (Sprite)null);
				VikingMessagesPlugin.Log.LogInfo((object)"Started message placement");
			}
		}

		private void FinishPlacement()
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			_isPlacing = false;
			MessageUIManager.UI.ShowCreateUI(_placementPosition, _placementRotation);
			VikingMessagesPlugin.Log.LogInfo((object)"Finished placement, opening UI");
		}

		public void CancelPlacement()
		{
			if (_isPlacing)
			{
				_isPlacing = false;
				if ((Object)(object)Player.m_localPlayer != (Object)null)
				{
					((Character)Player.m_localPlayer).Message((MessageType)1, "Placement cancelled", 0, (Sprite)null);
				}
			}
		}
	}
	[HarmonyPatch]
	public static class MessageGlyphPatches
	{
		[HarmonyPatch(typeof(Player), "ConsumeItem")]
		[HarmonyPrefix]
		public static bool ConsumeItem_Prefix(Player __instance, ItemData item, ref bool __result)
		{
			object obj;
			if (item == null)
			{
				obj = null;
			}
			else
			{
				GameObject dropPrefab = item.m_dropPrefab;
				obj = ((dropPrefab != null) ? ((Object)dropPrefab).name : null);
			}
			if ((string?)obj != "MessageGlyph")
			{
				return true;
			}
			if (!CanPlaceMessage(__instance))
			{
				((Character)__instance).Message((MessageType)2, "Cannot place message here!", 0, (Sprite)null);
				__result = false;
				return false;
			}
			MessagePlacementHandler.Instance.StartPlacement(__instance);
			((Humanoid)__instance).GetInventory().RemoveItem(item, 1);
			__result = true;
			return false;
		}

		[HarmonyPatch(typeof(Humanoid), "UseItem")]
		[HarmonyPrefix]
		public static bool UseItem_Prefix(Humanoid __instance, ItemData item)
		{
			object obj;
			if (item == null)
			{
				obj = null;
			}
			else
			{
				GameObject dropPrefab = item.m_dropPrefab;
				obj = ((dropPrefab != null) ? ((Object)dropPrefab).name : null);
			}
			if ((string?)obj != "MessageGlyph")
			{
				return true;
			}
			Player val = (Player)(object)((__instance is Player) ? __instance : null);
			if (val != null)
			{
				((Humanoid)val).ConsumeItem(((Humanoid)val).GetInventory(), item, false);
				return false;
			}
			return true;
		}

		private static bool CanPlaceMessage(Player player)
		{
			if (((Character)player).InInterior())
			{
				return false;
			}
			if (((Character)player).IsSwimming())
			{
				return false;
			}
			if (((Character)player).IsAttached())
			{
				return false;
			}
			if (((Character)player).IsDead())
			{
				return false;
			}
			return true;
		}

		[HarmonyPatch(typeof(Character), "Damage")]
		[HarmonyPostfix]
		public static void Character_Damage_Postfix(Character __instance, HitData hit)
		{
			if ((Object)(object)__instance == (Object)(object)Player.m_localPlayer && MessagePlacementHandler.Instance.IsPlacing)
			{
				MessagePlacementHandler.Instance.CancelPlacement();
			}
		}
	}
	public static class MessageManagerAlt
	{
		private static Dictionary<string, VikingMessage> _messages = new Dictionary<string, VikingMessage>();

		private static Dictionary<long, PlayerReputation> _playerReputations = new Dictionary<long, PlayerReputation>();

		private static string _saveFilePath;

		private static string _leaderboardFilePath;

		private static string _currentWorldName;

		public const string RPC_PlaceMessage = "VikingMessages_PlaceMessage";

		public const string RPC_VoteMessage = "VikingMessages_VoteMessage";

		public const string RPC_RequestSync = "VikingMessages_RequestSync";

		public const string RPC_SyncMessages = "VikingMessages_SyncMessages";

		public const string RPC_RemoveMessage = "VikingMessages_RemoveMessage";

		public const string RPC_SyncTemplates = "VikingMessages_SyncTemplates";

		public const string RPC_SyncLeaderboard = "VikingMessages_SyncLeaderboard";

		public const string RPC_NotifyAppraise = "VikingMessages_NotifyAppraise";

		private static bool _rpcsRegistered = false;

		public static void Initialize()
		{
			ManualLogSource log = VikingMessagesPlugin.Log;
			if (log != null)
			{
				log.LogInfo((object)"MessageManagerAlt initialized");
			}
		}

		public static void RegisterRPCs()
		{
			if (_rpcsRegistered || ZRoutedRpc.instance == null)
			{
				return;
			}
			try
			{
				ZRoutedRpc.instance.Register<ZPackage>("VikingMessages_PlaceMessage", (Action<long, ZPackage>)RPC_OnPlaceMessage);
				ZRoutedRpc.instance.Register<ZPackage>("VikingMessages_VoteMessage", (Action<long, ZPackage>)RPC_OnVoteMessage);
				ZRoutedRpc.instance.Register<ZPackage>("VikingMessages_RequestSync", (Action<long, ZPackage>)RPC_OnRequestSync);
				ZRoutedRpc.instance.Register<ZPackage>("VikingMessages_SyncMessages", (Action<long, ZPackage>)RPC_OnSyncMessages);
				ZRoutedRpc.instance.Register<ZPackage>("VikingMessages_RemoveMessage", (Action<long, ZPackage>)RPC_OnRemoveMessage);
				ZRoutedRpc.instance.Register<ZPackage>("VikingMessages_SyncTemplates", (Action<long, ZPackage>)RPC_OnSyncTemplates);
				ZRoutedRpc.instance.Register<ZPackage>("VikingMessages_SyncLeaderboard", (Action<long, ZPackage>)RPC_OnSyncLeaderboard);
				ZRoutedRpc.instance.Register<ZPackage>("VikingMessages_NotifyAppraise", (Action<long, ZPackage>)RPC_OnNotifyAppraise);
				_rpcsRegistered = true;
				ManualLogSource log = VikingMessagesPlugin.Log;
				if (log != null)
				{
					log.LogInfo((object)"RPCs registered successfully");
				}
			}
			catch (Exception arg)
			{
				ManualLogSource log2 = VikingMessagesPlugin.Log;
				if (log2 != null)
				{
					log2.LogError((object)$"Failed to register RPCs: {arg}");
				}
			}
		}

		private static void RPC_OnPlaceMessage(long sender, ZPackage pkg)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_0100: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				string text = pkg.ReadString();
				Vector3 position = pkg.ReadVector3();
				Quaternion rotation = pkg.ReadQuaternion();
				string template = pkg.ReadString();
				string words = pkg.ReadString();
				int num = pkg.ReadInt();
				string text2 = pkg.ReadString();
				Vector3 lookDirection = pkg.ReadVector3();
				int num2 = pkg.ReadInt();
				string[] array = new string[num2];
				for (int i = 0; i < num2; i++)
				{
					array[i] = pkg.ReadString();
				}
				ManualLogSource log = VikingMessagesPlugin.Log;
				if (log != null)
				{
					log.LogInfo((object)$"RPC_OnPlaceMessage: id={text}, author={text2}, emote={num}");
				}
				VikingMessage value = new VikingMessage
				{
					Id = text,
					Position = position,
					Rotation = rotation,
					Template = template,
					Words = words,
					EmoteIndex = num,
					AuthorId = sender,
					AuthorName = text2,
					Reputation = 0,
					CreatedTime = DateTime.UtcNow,
					VotedPlayers = new List<long>(),
					EquippedItems = array,
					LookDirection = lookDirection
				};
				_messages[text] = value;
				UpdatePlayerMessageCount(sender, text2);
				if ((Object)(object)ZNet.instance != (Object)null && ZNet.instance.IsServer())
				{
					SaveMessages();
					SaveLeaderboard();
				}
				BroadcastMessageSync();
				BroadcastLeaderboard();
			}
			catch (Exception arg)
			{
				ManualLogSource log2 = VikingMessagesPlugin.Log;
				if (log2 != null)
				{
					log2.LogError((object)$"Error processing PlaceMessage: {arg}");
				}
			}
		}

		private static void RPC_OnVoteMessage(long sender, ZPackage pkg)
		{
			try
			{
				string text = pkg.ReadString();
				bool flag = pkg.ReadBool();
				if (!_messages.TryGetValue(text, out var value) || value.VotedPlayers.Contains(sender) || value.AuthorId == sender)
				{
					return;
				}
				value.VotedPlayers.Add(sender);
				value.Reputation += (flag ? 1 : (-1));
				UpdatePlayerReputation(value.AuthorId, value.AuthorName, flag ? 1 : (-1));
				if (flag && (Object)(object)ZNet.instance != (Object)null && ZNet.instance.IsServer())
				{
					NotifyAuthorOfAppraise(value.AuthorId);
				}
				if (value.Reputation <= VikingMessagesPlugin.MinReputation.Value)
				{
					_messages.Remove(text);
					ManualLogSource log = VikingMessagesPlugin.Log;
					if (log != null)
					{
						log.LogInfo((object)("Message " + text + " removed due to low reputation"));
					}
				}
				if ((Object)(object)ZNet.instance != (Object)null && ZNet.instance.IsServer())
				{
					SaveMessages();
					SaveLeaderboard();
				}
				BroadcastMessageSync();
				BroadcastLeaderboard();
			}
			catch (Exception arg)
			{
				ManualLogSource log2 = VikingMessagesPlugin.Log;
				if (log2 != null)
				{
					log2.LogError((object)$"Error processing VoteMessage: {arg}");
				}
			}
		}

		private static void NotifyAuthorOfAppraise(long authorId)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Expected O, but got Unknown
			try
			{
				ZPackage val = new ZPackage();
				val.Write("appraise");
				List<ZNetPeer> peers = ZNet.instance.GetPeers();
				foreach (ZNetPeer item in peers)
				{
					if (((ZDOID)(ref item.m_characterID)).UserID == authorId)
					{
						ZRoutedRpc.instance.InvokeRoutedRPC(item.m_uid, "VikingMessages_NotifyAppraise", new object[1] { val });
						ManualLogSource log = VikingMessagesPlugin.Log;
						if (log != null)
						{
							log.LogInfo((object)$"Sent appraise notification to {authorId}");
						}
						break;
					}
				}
			}
			catch (Exception ex)
			{
				ManualLogSource log2 = VikingMessagesPlugin.Log;
				if (log2 != null)
				{
					log2.LogWarning((object)("Failed to notify author: " + ex.Message));
				}
			}
		}

		private static void RPC_OnNotifyAppraise(long sender, ZPackage pkg)
		{
			try
			{
				string text = pkg.ReadString();
				if (text == "appraise")
				{
					Player localPlayer = Player.m_localPlayer;
					if (localPlayer != null)
					{
						((Character)localPlayer).Message((MessageType)2, "<color=#FFD700>Your message was appraised!</color>", 0, (Sprite)null);
					}
				}
			}
			catch (Exception ex)
			{
				ManualLogSource log = VikingMessagesPlugin.Log;
				if (log != null)
				{
					log.LogWarning((object)("Error processing notification: " + ex.Message));
				}
			}
		}

		private static void RPC_OnRequestSync(long sender, ZPackage pkg)
		{
			if (!((Object)(object)ZNet.instance == (Object)null) && ZNet.instance.IsServer())
			{
				ManualLogSource log = VikingMessagesPlugin.Log;
				if (log != null)
				{
					log.LogInfo((object)$"Sync requested by {sender}");
				}
				SendMessagesToClient(sender);
				SendTemplatesToClient(sender);
				SendLeaderboardToClient(sender);
			}
		}

		private static void RPC_OnSyncMessages(long sender, ZPackage pkg)
		{
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)ZNet.instance != (Object)null && ZNet.instance.IsServer())
			{
				return;
			}
			try
			{
				int num = pkg.ReadInt();
				Dictionary<string, VikingMessage> dictionary = new Dictionary<string, VikingMessage>();
				for (int i = 0; i < num; i++)
				{
					VikingMessage vikingMessage = new VikingMessage
					{
						Id = pkg.ReadString(),
						Position = pkg.ReadVector3(),
						Rotation = pkg.ReadQuaternion(),
						Template = pkg.ReadString(),
						Words = pkg.ReadString(),
						EmoteIndex = pkg.ReadInt(),
						AuthorId = pkg.ReadLong(),
						AuthorName = pkg.ReadString(),
						Reputation = pkg.ReadInt(),
						LookDirection = pkg.ReadVector3()
					};
					int num2 = pkg.ReadInt();
					vikingMessage.EquippedItems = new string[num2];
					for (int j = 0; j < num2; j++)
					{
						vikingMessage.EquippedItems[j] = pkg.ReadString();
					}
					int num3 = pkg.ReadInt();
					vikingMessage.VotedPlayers = new List<long>();
					for (int k = 0; k < num3; k++)
					{
						vikingMessage.VotedPlayers.Add(pkg.ReadLong());
					}
					dictionary[vikingMessage.Id] = vikingMessage;
				}
				_messages = dictionary;
				ManualLogSource log = VikingMessagesPlugin.Log;
				if (log != null)
				{
					log.LogInfo((object)$"Synced {num} messages from server");
				}
				RefreshAllMessageStones();
			}
			catch (Exception arg)
			{
				ManualLogSource log2 = VikingMessagesPlugin.Log;
				if (log2 != null)
				{
					log2.LogError((object)$"Error processing SyncMessages: {arg}");
				}
			}
		}

		private static void RPC_OnRemoveMessage(long sender, ZPackage pkg)
		{
			try
			{
				string key = pkg.ReadString();
				if (_messages.ContainsKey(key))
				{
					_messages.Remove(key);
					if ((Object)(object)ZNet.instance != (Object)null && ZNet.instance.IsServer())
					{
						SaveMessages();
					}
					BroadcastMessageSync();
				}
			}
			catch (Exception arg)
			{
				ManualLogSource log = VikingMessagesPlugin.Log;
				if (log != null)
				{
					log.LogError((object)$"Error processing RemoveMessage: {arg}");
				}
			}
		}

		private static void RPC_OnSyncTemplates(long sender, ZPackage pkg)
		{
			if ((Object)(object)ZNet.instance != (Object)null && ZNet.instance.IsServer())
			{
				return;
			}
			try
			{
				string json = pkg.ReadString();
				MessageTemplates.LoadFromServerJson(json);
				ManualLogSource log = VikingMessagesPlugin.Log;
				if (log != null)
				{
					log.LogInfo((object)"Templates synced from server");
				}
			}
			catch (Exception arg)
			{
				ManualLogSource log2 = VikingMessagesPlugin.Log;
				if (log2 != null)
				{
					log2.LogError((object)$"Error processing SyncTemplates: {arg}");
				}
			}
		}

		private static void RPC_OnSyncLeaderboard(long sender, ZPackage pkg)
		{
			if ((Object)(object)ZNet.instance != (Object)null && ZNet.instance.IsServer())
			{
				return;
			}
			try
			{
				int num = pkg.ReadInt();
				_playerReputations.Clear();
				ManualLogSource log = VikingMessagesPlugin.Log;
				if (log != null)
				{
					log.LogInfo((object)$"RPC_OnSyncLeaderboard: Receiving {num} players");
				}
				for (int i = 0; i < num; i++)
				{
					PlayerReputation playerReputation = new PlayerReputation
					{
						PlayerId = pkg.ReadLong(),
						PlayerName = pkg.ReadString(),
						TotalReputation = pkg.ReadInt(),
						MessageCount = pkg.ReadInt()
					};
					_playerReputations[playerReputation.PlayerId] = playerReputation;
					ManualLogSource log2 = VikingMessagesPlugin.Log;
					if (log2 != null)
					{
						log2.LogInfo((object)$"  Player {i}: id={playerReputation.PlayerId}, name='{playerReputation.PlayerName}', rep={playerReputation.TotalReputation}");
					}
				}
				ManualLogSource log3 = VikingMessagesPlugin.Log;
				if (log3 != null)
				{
					log3.LogInfo((object)$"Synced leaderboard: {num} players");
				}
				LeaderboardManager.CheckAndApplyBuffs();
			}
			catch (Exception arg)
			{
				ManualLogSource log4 = VikingMessagesPlugin.Log;
				if (log4 != null)
				{
					log4.LogError((object)$"Error processing SyncLeaderboard: {arg}");
				}
			}
		}

		public static void PlaceMessage(Vector3 position, Quaternion rotation, string template, string words, int emoteIndex)
		{
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Expected O, but got Unknown
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)Player.m_localPlayer == (Object)null))
			{
				string text = Guid.NewGuid().ToString();
				string playerName = Player.m_localPlayer.GetPlayerName();
				Vector3 forward = ((Component)Player.m_localPlayer).transform.forward;
				string[] array = CapturePlayerEquipment();
				ManualLogSource log = VikingMessagesPlugin.Log;
				if (log != null)
				{
					log.LogInfo((object)$"PlaceMessage: id={text}, author='{playerName}', emote={emoteIndex}");
				}
				ZPackage val = new ZPackage();
				val.Write(text);
				val.Write(position);
				val.Write(rotation);
				val.Write(template);
				val.Write(words);
				val.Write(emoteIndex);
				val.Write(playerName ?? "Unknown");
				val.Write(forward);
				val.Write(array.Length);
				string[] array2 = array;
				foreach (string text2 in array2)
				{
					val.Write(text2 ?? "");
				}
				ZRoutedRpc.instance.InvokeRoutedRPC(ZRoutedRpc.Everybody, "VikingMessages_PlaceMessage", new object[1] { val });
			}
		}

		private static string[] CapturePlayerEquipment()
		{
			List<string> list = new List<string>();
			try
			{
				if ((Object)(object)Player.m_localPlayer == (Object)null)
				{
					return list.ToArray();
				}
				VisEquipment component = ((Component)Player.m_localPlayer).GetComponent<VisEquipment>();
				if ((Object)(object)component == (Object)null)
				{
					return list.ToArray();
				}
				Inventory inventory = ((Humanoid)Player.m_localPlayer).GetInventory();
				if (inventory == null)
				{
					return list.ToArray();
				}
				foreach (ItemData allItem in inventory.GetAllItems())
				{
					if (allItem.m_equipped && (Object)(object)allItem.m_dropPrefab != (Object)null)
					{
						list.Add(((Object)allItem.m_dropPrefab).name);
					}
				}
			}
			catch (Exception ex)
			{
				ManualLogSource log = VikingMessagesPlugin.Log;
				if (log != null)
				{
					log.LogWarning((object)("Failed to capture equipment: " + ex.Message));
				}
			}
			return list.ToArray();
		}

		public static bool VoteMessage(string messageId, bool isLike)
		{
			//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f7: Expected O, but got Unknown
			if (!_messages.TryGetValue(messageId, out var value))
			{
				Player localPlayer = Player.m_localPlayer;
				if (localPlayer != null)
				{
					((Character)localPlayer).Message((MessageType)2, "Message not found!", 0, (Sprite)null);
				}
				return false;
			}
			Player localPlayer2 = Player.m_localPlayer;
			long num = ((localPlayer2 != null) ? localPlayer2.GetPlayerID() : 0);
			Player localPlayer3 = Player.m_localPlayer;
			string value2 = ((localPlayer3 != null) ? localPlayer3.GetPlayerName() : null) ?? "";
			if (value.AuthorId == num || (!string.IsNullOrEmpty(value2) && !string.IsNullOrEmpty(value.AuthorName) && value.AuthorName.Equals(value2, StringComparison.OrdinalIgnoreCase)))
			{
				Player localPlayer4 = Player.m_localPlayer;
				if (localPlayer4 != null)
				{
					((Character)localPlayer4).Message((MessageType)2, "You cannot appraise your own message!", 0, (Sprite)null);
				}
				return false;
			}
			if (value.VotedPlayers.Contains(num))
			{
				Player localPlayer5 = Player.m_localPlayer;
				if (localPlayer5 != null)
				{
					((Character)localPlayer5).Message((MessageType)2, "You have already rated this message!", 0, (Sprite)null);
				}
				return false;
			}
			ZPackage val = new ZPackage();
			val.Write(messageId);
			val.Write(isLike);
			ZRoutedRpc.instance.InvokeRoutedRPC(ZRoutedRpc.Everybody, "VikingMessages_VoteMessage", new object[1] { val });
			return true;
		}

		public static void RequestMessages()
		{
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Expected O, but got Unknown
			if (ZRoutedRpc.instance != null)
			{
				ManualLogSource log = VikingMessagesPlugin.Log;
				if (log != null)
				{
					log.LogInfo((object)"Requesting sync from server");
				}
				ZPackage val = new ZPackage();
				ZRoutedRpc.instance.InvokeRoutedRPC(ZRoutedRpc.Everybody, "VikingMessages_RequestSync", new object[1] { val });
			}
		}

		public static VikingMessage GetMessage(string messageId)
		{
			VikingMessage value;
			return _messages.TryGetValue(messageId, out value) ? value : null;
		}

		public static IEnumerable<VikingMessage> GetAllMessages()
		{
			return _messages.Values;
		}

		public static int GetMessageCount()
		{
			return _messages.Count;
		}

		private static void UpdatePlayerMessageCount(long playerId, string playerName)
		{
			if (!_playerReputations.TryGetValue(playerId, out var value))
			{
				value = new PlayerReputation(playerId, playerName);
				_playerReputations[playerId] = value;
			}
			value.MessageCount++;
			value.PlayerName = playerName;
		}

		private static void UpdatePlayerReputation(long playerId, string playerName, int delta)
		{
			if (!_playerReputations.TryGetValue(playerId, out var value))
			{
				value = new PlayerReputation(playerId, playerName);
				_playerReputations[playerId] = value;
			}
			value.TotalReputation += delta;
			value.PlayerName = playerName;
		}

		public static List<PlayerReputation> GetLeaderboard()
		{
			Dictionary<string, PlayerReputation> dictionary = new Dictionary<string, PlayerReputation>();
			foreach (PlayerReputation value2 in _playerReputations.Values)
			{
				string key = (string.IsNullOrEmpty(value2.PlayerName) ? $"id_{value2.PlayerId}" : value2.PlayerName.ToLower());
				if (dictionary.TryGetValue(key, out var value))
				{
					value.TotalReputation += value2.TotalReputation;
					value.MessageCount += value2.MessageCount;
					if (string.IsNullOrEmpty(value.PlayerName) && !string.IsNullOrEmpty(value2.PlayerName))
					{
						value.PlayerName = value2.PlayerName;
					}
				}
				else
				{
					dictionary[key] = new PlayerReputation
					{
						PlayerId = value2.PlayerId,
						PlayerName = value2.PlayerName,
						TotalReputation = value2.TotalReputation,
						MessageCount = value2.MessageCount
					};
				}
			}
			return dictionary.Values.OrderByDescending((PlayerReputation p) => p.TotalReputation).ToList();
		}

		public static bool IsPlayerInTop3(long playerId)
		{
			Player localPlayer = Player.m_localPlayer;
			string localPlayerName = ((localPlayer != null) ? localPlayer.GetPlayerName() : null) ?? "";
			List<PlayerReputation> list = GetLeaderboard().Take(3).ToList();
			bool flag = list.Any((PlayerReputation p) => p.PlayerId == playerId || (!string.IsNullOrEmpty(localPlayerName) && !string.IsNullOrEmpty(p.PlayerName) && p.PlayerName.Equals(localPlayerName, StringComparison.OrdinalIgnoreCase)));
			ManualLogSource log = VikingMessagesPlugin.Log;
			if (log != null)
			{
				log.LogInfo((object)$"IsPlayerInTop3: playerId={playerId}, name={localPlayerName}, top3Count={list.Count}, result={flag}");
			}
			if (list.Count > 0)
			{
				foreach (PlayerReputation item in list)
				{
					ManualLogSource log2 = VikingMessagesPlugin.Log;
					if (log2 != null)
					{
						log2.LogInfo((object)$"  Top3 player: id={item.PlayerId}, name='{item.PlayerName}', rep={item.TotalReputation}");
					}
				}
			}
			return flag;
		}

		private static void SendMessagesToClient(long clientId)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Expected O, but got Unknown
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
			ZPackage val = new ZPackage();
			val.Write(_messages.Count);
			foreach (VikingMessage value in _messages.Values)
			{
				val.Write(value.Id);
				val.Write(value.Position);
				val.Write(value.Rotation);
				val.Write(value.Template ?? "");
				val.Write(value.Words ?? "");
				val.Write(value.EmoteIndex);
				val.Write(value.AuthorId);
				val.Write(value.AuthorName ?? "Unknown");
				val.Write(value.Reputation);
				val.Write(value.LookDirection);
				string[] array = value.EquippedItems ?? new string[0];
				val.Write(array.Length);
				string[] array2 = array;
				foreach (string text in array2)
				{
					val.Write(text ?? "");
				}
				val.Write(value.VotedPlayers?.Count ?? 0);
				if (value.VotedPlayers == null)
				{
					continue;
				}
				foreach (long votedPlayer in value.VotedPlayers)
				{
					val.Write(votedPlayer);
				}
			}
			ZRoutedRpc.instance.InvokeRoutedRPC(clientId, "VikingMessages_SyncMessages", new object[1] { val });
		}

		private static void BroadcastMessageSync()
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Expected O, but got Unknown
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
			ZPackage val = new ZPackage();
			val.Write(_messages.Count);
			foreach (VikingMessage value in _messages.Values)
			{
				val.Write(value.Id);
				val.Write(value.Position);
				val.Write(value.Rotation);
				val.Write(value.Template ?? "");
				val.Write(value.Words ?? "");
				val.Write(value.EmoteIndex);
				val.Write(value.AuthorId);
				val.Write(value.AuthorName ?? "Unknown");
				val.Write(value.Reputation);
				val.Write(value.LookDirection);
				string[] array = value.EquippedItems ?? new string[0];
				val.Write(array.Length);
				string[] array2 = array;
				foreach (string text in array2)
				{
					val.Write(text ?? "");
				}
				val.Write(value.VotedPlayers?.Count ?? 0);
				if (value.VotedPlayers == null)
				{
					continue;
				}
				foreach (long votedPlayer in value.VotedPlayers)
				{
					val.Write(votedPlayer);
				}
			}
			ZRoutedRpc.instance.InvokeRoutedRPC(ZRoutedRpc.Everybody, "VikingMessages_SyncMessages", new object[1] { val });
		}

		private static void SendTemplatesToClient(long clientId)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Expected O, but got Unknown
			string serverTemplatesJson = MessageTemplates.GetServerTemplatesJson();
			ZPackage val = new ZPackage();
			val.Write(serverTemplatesJson);
			ZRoutedRpc.instance.InvokeRoutedRPC(clientId, "VikingMessages_SyncTemplates", new object[1] { val });
			ManualLogSource log = VikingMessagesPlugin.Log;
			if (log != null)
			{
				log.LogInfo((object)$"Sent templates to client {clientId}");
			}
		}

		private static void SendLeaderboardToClient(long clientId)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Expected O, but got Unknown
			ZPackage val = new ZPackage();
			List<PlayerReputation> list = _playerReputations.Values.ToList();
			val.Write(list.Count);
			ManualLogSource log = VikingMessagesPlugin.Log;
			if (log != null)
			{
				log.LogInfo((object)$"SendLeaderboardToClient: Sending {list.Count} players to {clientId}");
			}
			foreach (PlayerReputation item in list)
			{
				val.Write(item.PlayerId);
				val.Write(item.PlayerName ?? "Unknown");
				val.Write(item.TotalReputation);
				val.Write(item.MessageCount);
				ManualLogSource log2 = VikingMessagesPlugin.Log;
				if (log2 != null)
				{
					log2.LogInfo((object)$"  Sending player: id={item.PlayerId}, name='{item.PlayerName}', rep={item.TotalReputation}");
				}
			}
			ZRoutedRpc.instance.InvokeRoutedRPC(clientId, "VikingMessages_SyncLeaderboard", new object[1] { val });
		}

		private static void BroadcastLeaderboard()
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Expected O, but got Unknown
			ZPackage val = new ZPackage();
			List<PlayerReputation> list = _playerReputations.Values.ToList();
			val.Write(list.Count);
			ManualLogSource log = VikingMessagesPlugin.Log;
			if (log != null)
			{
				log.LogInfo((object)$"BroadcastLeaderboard: Broadcasting {list.Count} players");
			}
			foreach (PlayerReputation item in list)
			{
				val.Write(item.PlayerId);
				val.Write(item.PlayerName ?? "Unknown");
				val.Write(item.TotalReputation);
				val.Write(item.MessageCount);
			}
			ZRoutedRpc.instance.InvokeRoutedRPC(ZRoutedRpc.Everybody, "VikingMessages_SyncLeaderboard", new object[1] { val });
		}

		public static void SpawnMessageStone(VikingMessage msg)
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)VikingMessagesPlugin.MessageStonePrefab == (Object)null))
			{
				GameObject val = Object.Instantiate<GameObject>(VikingMessagesPlugin.MessageStonePrefab, msg.Position, msg.Rotation);
				val.SetActive(true);
				MessageStone component = val.GetComponent<MessageStone>();
				if ((Object)(object)component != (Object)null)
				{
					component.Initialize(msg);
				}
			}
		}

		private static void RefreshAllMessageStones()
		{
			MessageStone[] array = Object.FindObjectsOfType<MessageStone>();
			MessageStone[] array2 = array;
			foreach (MessageStone messageStone in array2)
			{
				Object.Destroy((Object)(object)((Component)messageStone).gameObject);
			}
			foreach (VikingMessage value in _messages.Values)
			{
				SpawnMessageStone(value);
			}
			ManualLogSource log = VikingMessagesPlugin.Log;
			if (log != null)
			{
				log.LogInfo((object)$"Refreshed {_messages.Count} message stones");
			}
		}

		private static void SetupSavePath(string worldName)
		{
			if (string.IsNullOrEmpty(worldName))
			{
				worldName = "Unknown";
			}
			_currentWorldName = worldName;
			string text = Path.Combine(Paths.ConfigPath, "VikingMessages");
			if (!Directory.Exists(text))
			{
				Directory.CreateDirectory(text);
			}
			string text2 = string.Join("_", worldName.Split(Path.GetInvalidFileNameChars()));
			_saveFilePath = Path.Combine(text, "messages_" + text2 + ".json");
			_leaderboardFilePath = Path.Combine(text, "leaderboard_" + text2 + ".json");
		}

		public static void SaveMessages()
		{
			if ((Object)(object)ZNet.instance == (Object)null || !ZNet.instance.IsServer())
			{
				return;
			}
			if (string.IsNullOrEmpty(_saveFilePath))
			{
				SetupSavePath(ZNet.instance.GetWorldName());
			}
			try
			{
				StringBuilder stringBuilder = new StringBuilder();
				stringBuilder.AppendLine("{");
				stringBuilder.AppendLine("  \"Messages\": [");
				List<VikingMessage> list = _messages.Values.ToList();
				for (int i = 0; i < list.Count; i++)
				{
					VikingMessage vikingMessage = list[i];
					stringBuilder.AppendLine("    {");
					stringBuilder.AppendLine("      \"Id\": \"" + Escape(vikingMessage.Id) + "\",");
					stringBuilder.AppendLine("      \"PosX\": " + F(vikingMessage.Position.x) + ", \"PosY\": " + F(vikingMessage.Position.y) + ", \"PosZ\": " + F(vikingMessage.Position.z) + ",");
					stringBuilder.AppendLine("      \"RotX\": " + F(vikingMessage.Rotation.x) + ", \"RotY\": " + F(vikingMessage.Rotation.y) + ", \"RotZ\": " + F(vikingMessage.Rotation.z) + ", \"RotW\": " + F(vikingMessage.Rotation.w) + ",");
					stringBuilder.AppendLine("      \"Template\": \"" + Escape(vikingMessage.Template) + "\",");
					stringBuilder.AppendLine("      \"Words\": \"" + Escape(vikingMessage.Words) + "\",");
					stringBuilder.AppendLine($"      \"EmoteIndex\": {vikingMessage.EmoteIndex},");
					stringBuilder.AppendLine($"      \"AuthorId\": {vikingMessage.AuthorId},");
					stringBuilder.AppendLine("      \"AuthorName\": \"" + Escape(vikingMessage.AuthorName) + "\",");
					stringBuilder.AppendLine($"      \"Reputation\": {vikingMessage.Reputation},");
					stringBuilder.AppendLine("      \"LookDirX\": " + F(vikingMessage.LookDirection.x) + ", \"LookDirY\": " + F(vikingMessage.LookDirection.y) + ", \"LookDirZ\": " + F(vikingMessage.LookDirection.z) + ",");
					stringBuilder.Append("      \"Equipment\": [");
					if (vikingMessage.EquippedItems != null && vikingMessage.EquippedItems.Length != 0)
					{
						stringBuilder.Append(string.Join(", ", vikingMessage.EquippedItems.Select((string e) => "\"" + Escape(e) + "\"")));
					}
					stringBuilder.AppendLine("],");
					stringBuilder.Append("      \"VotedPlayers\": [");
					if (vikingMessage.VotedPlayers != null && vikingMessage.VotedPlayers.Count > 0)
					{
						stringBuilder.Append(string.Join(", ", vikingMessage.VotedPlayers));
					}
					stringBuilder.AppendLine("]");
					stringBuilder.AppendLine((i < list.Count - 1) ? "    }," : "    }");
				}
				stringBuilder.AppendLine("  ]");
				stringBuilder.AppendLine("}");
				File.WriteAllText(_saveFilePath, stringBuilder.ToString());
				ManualLogSource log = VikingMessagesPlugin.Log;
				if (log != null)
				{
					log.LogInfo((object)$"Saved {_messages.Count} messages");
				}
			}
			catch (Exception arg)
			{
				ManualLogSource log2 = VikingMessagesPlugin.Log;
				if (log2 != null)
				{
					log2.LogError((object)$"Failed to save messages: {arg}");
				}
			}
		}

		public static void SaveLeaderboard()
		{
			if ((Object)(object)ZNet.instance == (Object)null || !ZNet.instance.IsServer())
			{
				return;
			}
			if (string.IsNullOrEmpty(_leaderboardFilePath))
			{
				SetupSavePath(ZNet.instance.GetWorldName());
			}
			try
			{
				StringBuilder stringBuilder = new StringBuilder();
				stringBuilder.AppendLine("{");
				stringBuilder.AppendLine("  \"Players\": [");
				List<PlayerReputation> list = _playerReputations.Values.ToList();
				for (int i = 0; i < list.Count; i++)
				{
					PlayerReputation playerReputation = list[i];
					stringBuilder.AppendLine("    {");
					stringBuilder.AppendLine($"      \"PlayerId\": {playerReputation.PlayerId},");
					stringBuilder.AppendLine("      \"PlayerName\": \"" + Escape(playerReputation.PlayerName) + "\",");
					stringBuilder.AppendLine($"      \"TotalReputation\": {playerReputation.TotalReputation},");
					stringBuilder.AppendLine($"      \"MessageCount\": {playerReputation.MessageCount}");
					stringBuilder.AppendLine((i < list.Count - 1) ? "    }," : "    }");
				}
				stringBuilder.AppendLine("  ]");
				stringBuilder.AppendLine("}");
				File.WriteAllText(_leaderboardFilePath, stringBuilder.ToString());
			}
			catch (Exception arg)
			{
				ManualLogSource log = VikingMessagesPlugin.Log;
				if (log != null)
				{
					log.LogError((object)$"Failed to save leaderboard: {arg}");
				}
			}
		}

		public static void LoadMessages()
		{
			if ((Object)(object)ZNet.instance == (Object)null || !ZNet.instance.IsServer())
			{
				return;
			}
			SetupSavePath(ZNet.instance.GetWorldName());
			try
			{
				if (File.Exists(_saveFilePath))
				{
					string json = File.ReadAllText(_saveFilePath);
					ParseMessagesJson(json);
					ManualLogSource log = VikingMessagesPlugin.Log;
					if (log != null)
					{
						log.LogInfo((object)$"Loaded {_messages.Count} messages");
					}
				}
				if (File.Exists(_leaderboardFilePath))
				{
					string json2 = File.ReadAllText(_leaderboardFilePath);
					ParseLeaderboardJson(json2);
					ManualLogSource log2 = VikingMessagesPlugin.Log;
					if (log2 != null)
					{
						log2.LogInfo((object)$"Loaded {_playerReputations.Count} player reputations");
					}
				}
			}
			catch (Exception arg)
			{
				ManualLogSource log3 = VikingMessagesPlugin.Log;
				if (log3 != null)
				{
					log3.LogError((object)$"Failed to load data: {arg}");
				}
			}
		}

		private static void ParseMessagesJson(string json)
		{
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0092: Unknown result type (might be due to invalid IL or missing references)
			//IL_012b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0130: Unknown result type (might be due to invalid IL or missing references)
			_messages.Clear();
			int startIndex = 0;
			while ((startIndex = json.IndexOf("\"Id\":", startIndex)) >= 0)
			{
				try
				{
					VikingMessage vikingMessage = new VikingMessage();
					vikingMessage.Id = ExtractString(json, "Id", startIndex);
					vikingMessage.Position = new Vector3(ExtractFloat(json, "PosX", startIndex), ExtractFloat(json, "PosY", startIndex), ExtractFloat(json, "PosZ", startIndex));
					vikingMessage.Rotation = new Quaternion(ExtractFloat(json, "RotX", startIndex), ExtractFloat(json, "RotY", startIndex), ExtractFloat(json, "RotZ", startIndex), ExtractFloat(json, "RotW", startIndex));
					vikingMessage.Template = ExtractString(json, "Template", startIndex);
					vikingMessage.Words = ExtractString(json, "Words", startIndex);
					vikingMessage.EmoteIndex = (int)ExtractFloat(json, "EmoteIndex", startIndex);
					vikingMessage.AuthorId = (long)ExtractFloat(json, "AuthorId", startIndex);
					vikingMessage.AuthorName = ExtractString(json, "AuthorName", startIndex);
					vikingMessage.Reputation = (int)ExtractFloat(json, "Reputation", startIndex);
					vikingMessage.LookDirection = new Vector3(ExtractFloat(json, "LookDirX", startIndex), ExtractFloat(json, "LookDirY", startIndex), ExtractFloat(json, "LookDirZ", startIndex));
					vikingMessage.EquippedItems = ExtractStringArray(json, "Equipment", startIndex);
					vikingMessage.VotedPlayers = ExtractLongArray(json, "VotedPlayers", startIndex);
					if (!string.IsNullOrEmpty(vikingMessage.Id))
					{
						_messages[vikingMessage.Id] = vikingMessage;
					}
				}
				catch
				{
				}
				startIndex++;
			}
		}

		private static void ParseLeaderboardJson(string json)
		{
			_playerReputations.Clear();
			int startIndex = 0;
			while ((startIndex = json.IndexOf("\"PlayerId\":", startIndex)) >= 0)
			{
				try
				{
					PlayerReputation playerReputation = new PlayerReputation();
					playerReputation.PlayerId = (long)ExtractFloat(json, "PlayerId", startIndex);
					playerReputation.PlayerName = ExtractString(json, "PlayerName", startIndex);
					playerReputation.TotalReputation = (int)ExtractFloat(json, "TotalReputation", startIndex);
					playerReputation.MessageCount = (int)ExtractFloat(json, "MessageCount", startIndex);
					if (playerReputation.PlayerId != 0)
					{
						_playerReputations[playerReputation.PlayerId] = playerReputation;
					}
				}
				catch
				{
				}
				startIndex++;
			}
		}

		private static string F(float v)
		{
			return v.ToString(CultureInfo.InvariantCulture);
		}

		private static string Escape(string s)
		{
			return s?.Replace("\\", "\\\\").Replace("\"", "\\\"").Replace("\n", "\\n") ?? "";
		}

		private static string ExtractString(string json, string field, int startIdx)
		{
			string text = "\"" + field + "\": \"";
			int num = json.IndexOf(text, startIdx);
			if (num < 0 || num > startIdx + 2000)
			{
				return "";
			}
			num += text.Length;
			int num2 = json.IndexOf("\"", num);
			if (num2 < 0)
			{
				return "";
			}
			return json.Substring(num, num2 - num).Replace("\\n", "\n").Replace("\\\"", "\"");
		}

		private static float ExtractFloat(string json, string field, int startIdx)
		{
			string text = "\"" + field + "\": ";
			int num = json.IndexOf(text, startIdx);
			if (num < 0 || num > startIdx + 2000)
			{
				return 0f;
			}
			num += text.Length;
			int i;
			for (i = num; i < json.Length && (char.IsDigit(json[i]) || json[i] == '.' || json[i] == '-' || json[i] == 'E' || json[i] == 'e' || json[i] == '+'); i++)
			{
			}
			float.TryParse(json.Substring(num, i - num), NumberStyles.Float, CultureInfo.InvariantCulture, out var result);
			return result;
		}

		private static string[] ExtractStringArray(string json, string field, int startIdx)
		{
			List<string> list = new List<string>();
			string text = "\"" + field + "\": [";
			int num = json.IndexOf(text, startIdx);
			if (num < 0 || num > startIdx + 2000)
			{
				return list.ToArray();
			}
			num += text.Length;
			int num2 = json.IndexOf("]", num);
			if (num2 < 0)
			{
				return list.ToArray();
			}
			string text2 = json.Substring(num, num2 - num);
			int startIndex = 0;
			while ((startIndex = text2.IndexOf("\"", startIndex)) >= 0)
			{
				int num3 = startIndex + 1;
				int num4 = text2.IndexOf("\"", num3);
				if (num4 > num3)
				{
					list.Add(text2.Substring(num3, num4 - num3));
				}
				startIndex = num4 + 1;
			}
			return list.ToArray();
		}

		private static List<long> ExtractLongArray(string json, string field, int startIdx)
		{
			List<long> list = new List<long>();
			string text = "\"" + field + "\": [";
			int num = json.IndexOf(text, startIdx);
			if (num < 0 || num > startIdx + 2000)
			{
				return list;
			}
			num += text.Length;
			int num2 = json.IndexOf("]", num);
			if (num2 < 0)
			{
				return list;
			}
			string text2 = json.Substring(num, num2 - num);
			string[] array = text2.Split(new char[1] { ',' });
			foreach (string text3 in array)
			{
				if (long.TryParse(text3.Trim(), out var result))
				{
					list.Add(result);
				}
			}
			return list;
		}
	}
	[HarmonyPatch]
	public static class NetworkingPatches
	{
		[CompilerGenerated]
		private sealed class <DelayedLoad>d__2 : IEnumerator<object>, IDisposable, IEnumerator
		{
			private int <>1__state;

			private object <>2__current;

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

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

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

			[DebuggerHidden]
			void IDisposable.Dispose()
			{
				<>1__state = -2;
			}

			private bool MoveNext()
			{
				//IL_0026: Unknown result type (might be due to invalid IL or missing references)
				//IL_0030: Expected O, but got Unknown
				switch (<>1__state)
		

BepInEx/plugins/WardInfusion/WardInfusion.dll

Decompiled 2 weeks ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;
using WardInfusion.Patches;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyCompany("WardInfusion")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyDescription("Adds Ward Essence item to protect individual build pieces like chests, portals, and workstations")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("WardInfusion")]
[assembly: AssemblyTitle("WardInfusion")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace WardInfusion
{
	public class WardedPiece : MonoBehaviour
	{
		private ZNetView m_nview;

		private Piece m_piece;

		private GameObject m_wardEffect;

		private static GameObject s_wardEffectPrefab;

		private long m_cachedOwner;

		private bool m_cachedActive;

		private List<long> m_cachedPermitted = new List<long>();

		private float m_updateTimer;

		private const float UpdateInterval = 1f;

		private void Awake()
		{
			m_nview = ((Component)this).GetComponent<ZNetView>();
			m_piece = ((Component)this).GetComponent<Piece>();
			if (!((Object)(object)m_nview == (Object)null))
			{
				m_nview.Register<long>("WardInfusion_SetOwner", (Action<long, long>)RPC_SetOwner);
				m_nview.Register<bool>("WardInfusion_SetActive", (Action<long, bool>)RPC_SetActive);
				m_nview.Register<string>("WardInfusion_SetPermitted", (Action<long, string>)RPC_SetPermitted);
				m_nview.Register<long>("WardInfusion_AddPermitted", (Action<long, long>)RPC_AddPermitted);
				m_nview.Register<long>("WardInfusion_RemovePermitted", (Action<long, long>)RPC_RemovePermitted);
			}
		}

		private void Start()
		{
			UpdateCache();
			CreateWardEffect();
			UpdateVisuals();
		}

		private void Update()
		{
			if (!((Object)(object)m_nview == (Object)null) && m_nview.IsValid())
			{
				m_updateTimer += Time.deltaTime;
				if (m_updateTimer >= 1f)
				{
					m_updateTimer = 0f;
					UpdateCache();
					UpdateVisuals();
				}
			}
		}

		private void UpdateCache()
		{
			if ((Object)(object)m_nview == (Object)null || !m_nview.IsValid())
			{
				return;
			}
			ZDO zDO = m_nview.GetZDO();
			if (zDO == null)
			{
				return;
			}
			m_cachedOwner = zDO.GetLong(WardInfusionPlugin.WardOwnerHash, 0L);
			m_cachedActive = zDO.GetBool(WardInfusionPlugin.WardActiveHash, true);
			string @string = zDO.GetString(WardInfusionPlugin.WardPermittedHash, "");
			m_cachedPermitted.Clear();
			if (string.IsNullOrEmpty(@string))
			{
				return;
			}
			string[] array = @string.Split(new char[1] { ',' });
			foreach (string s in array)
			{
				if (long.TryParse(s, out var result))
				{
					m_cachedPermitted.Add(result);
				}
			}
		}

		private void CreateWardEffect()
		{
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)s_wardEffectPrefab == (Object)null && (Object)(object)ZNetScene.instance != (Object)null)
			{
				GameObject prefab = ZNetScene.instance.GetPrefab("guard_stone");
				if ((Object)(object)prefab != (Object)null)
				{
					PrivateArea component = prefab.GetComponent<PrivateArea>();
					if ((Object)(object)component != (Object)null && (Object)(object)component.m_enabledEffect != (Object)null)
					{
						s_wardEffectPrefab = component.m_enabledEffect;
					}
				}
			}
			if ((Object)(object)s_wardEffectPrefab != (Object)null)
			{
				m_wardEffect = Object.Instantiate<GameObject>(s_wardEffectPrefab, ((Component)this).transform);
				m_wardEffect.transform.localPosition = Vector3.up * 0.5f;
				m_wardEffect.transform.localScale = Vector3.one * 0.3f;
			}
		}

		private void UpdateVisuals()
		{
			if ((Object)(object)m_wardEffect != (Object)null)
			{
				bool active = IsWarded() && m_cachedActive;
				m_wardEffect.SetActive(active);
			}
		}

		public bool IsWarded()
		{
			return m_cachedOwner != 0;
		}

		public bool IsWardActive()
		{
			return m_cachedActive;
		}

		public long GetOwner()
		{
			return m_cachedOwner;
		}

		public bool IsOwner(long playerID)
		{
			return m_cachedOwner == playerID;
		}

		public bool IsPermitted(long playerID)
		{
			if (!IsWarded())
			{
				return true;
			}
			if (!m_cachedActive)
			{
				return true;
			}
			if (IsOwner(playerID))
			{
				return true;
			}
			return m_cachedPermitted.Contains(playerID);
		}

		public bool IsLocalPlayerPermitted()
		{
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer == (Object)null)
			{
				return false;
			}
			return IsPermitted(localPlayer.GetPlayerID());
		}

		public List<long> GetPermittedPlayers()
		{
			return new List<long>(m_cachedPermitted);
		}

		public void SetOwner(long playerID)
		{
			if (!((Object)(object)m_nview == (Object)null) && m_nview.IsValid())
			{
				m_nview.InvokeRPC("WardInfusion_SetOwner", new object[1] { playerID });
			}
		}

		public void InitializeWard(long ownerID, bool active = true)
		{
			if ((Object)(object)m_nview == (Object)null)
			{
				m_nview = ((Component)this).GetComponent<ZNetView>();
			}
			if ((Object)(object)m_nview == (Object)null || !m_nview.IsValid())
			{
				WardInfusionPlugin.Instance.Logger.LogWarning((object)"InitializeWard: No valid ZNetView");
				m_cachedOwner = ownerID;
				m_cachedActive = active;
				return;
			}
			ZDO zDO = m_nview.GetZDO();
			if (zDO != null)
			{
				zDO.Set(WardInfusionPlugin.WardOwnerHash, ownerID);
				zDO.Set(WardInfusionPlugin.WardActiveHash, active);
				WardInfusionPlugin.Instance.Logger.LogInfo((object)$"InitializeWard: Set owner to {ownerID}, active: {active}");
			}
			m_cachedOwner = ownerID;
			m_cachedActive = active;
			UpdateVisuals();
		}

		public void SetActive(bool active)
		{
			if (!((Object)(object)m_nview == (Object)null) && m_nview.IsValid())
			{
				m_nview.InvokeRPC("WardInfusion_SetActive", new object[1] { active });
			}
		}

		public void AddPermitted(long playerID)
		{
			if (!((Object)(object)m_nview == (Object)null) && m_nview.IsValid())
			{
				m_nview.InvokeRPC("WardInfusion_AddPermitted", new object[1] { playerID });
			}
		}

		public void RemovePermitted(long playerID)
		{
			if (!((Object)(object)m_nview == (Object)null) && m_nview.IsValid())
			{
				m_nview.InvokeRPC("WardInfusion_RemovePermitted", new object[1] { playerID });
			}
		}

		public void RemoveWard()
		{
			SetOwner(0L);
			SetActive(active: true);
			if ((Object)(object)m_nview != (Object)null && m_nview.IsValid())
			{
				m_nview.InvokeRPC("WardInfusion_SetPermitted", new object[1] { "" });
			}
			Player localPlayer = Player.m_localPlayer;
			if (!((Object)(object)localPlayer != (Object)null))
			{
				return;
			}
			GameObject wardEssencePrefab = WardInfusionPlugin.WardEssencePrefab;
			if ((Object)(object)wardEssencePrefab != (Object)null)
			{
				ItemDrop component = wardEssencePrefab.GetComponent<ItemDrop>();
				if ((Object)(object)component != (Object)null)
				{
					((Humanoid)localPlayer).GetInventory().AddItem(wardEssencePrefab, 1);
					((Character)localPlayer).Message((MessageType)1, "Ward Essence returned to inventory", 0, (Sprite)null);
					WardInfusionPlugin.Instance.Logger.LogInfo((object)"Returned Ward Essence to player inventory");
				}
			}
		}

		private void RPC_SetOwner(long sender, long ownerID)
		{
			if (!((Object)(object)m_nview == (Object)null) && m_nview.IsOwner())
			{
				ZDO zDO = m_nview.GetZDO();
				if (zDO != null)
				{
					zDO.Set(WardInfusionPlugin.WardOwnerHash, ownerID);
					m_cachedOwner = ownerID;
					UpdateVisuals();
				}
			}
		}

		private void RPC_SetActive(long sender, bool active)
		{
			if (!((Object)(object)m_nview == (Object)null) && m_nview.IsOwner())
			{
				ZDO zDO = m_nview.GetZDO();
				if (zDO != null)
				{
					zDO.Set(WardInfusionPlugin.WardActiveHash, active);
					m_cachedActive = active;
					UpdateVisuals();
				}
			}
		}

		private void RPC_SetPermitted(long sender, string permittedStr)
		{
			if ((Object)(object)m_nview == (Object)null || !m_nview.IsOwner())
			{
				return;
			}
			ZDO zDO = m_nview.GetZDO();
			if (zDO == null)
			{
				return;
			}
			zDO.Set(WardInfusionPlugin.WardPermittedHash, permittedStr);
			m_cachedPermitted.Clear();
			if (string.IsNullOrEmpty(permittedStr))
			{
				return;
			}
			string[] array = permittedStr.Split(new char[1] { ',' });
			foreach (string s in array)
			{
				if (long.TryParse(s, out var result))
				{
					m_cachedPermitted.Add(result);
				}
			}
		}

		private void RPC_AddPermitted(long sender, long playerID)
		{
			if (!((Object)(object)m_nview == (Object)null) && m_nview.IsOwner() && !m_cachedPermitted.Contains(playerID))
			{
				m_cachedPermitted.Add(playerID);
				SavePermitted();
			}
		}

		private void RPC_RemovePermitted(long sender, long playerID)
		{
			if (!((Object)(object)m_nview == (Object)null) && m_nview.IsOwner() && m_cachedPermitted.Remove(playerID))
			{
				SavePermitted();
			}
		}

		private void SavePermitted()
		{
			if ((Object)(object)m_nview == (Object)null || !m_nview.IsOwner())
			{
				return;
			}
			ZDO zDO = m_nview.GetZDO();
			if (zDO != null)
			{
				string text = string.Join(",", m_cachedPermitted.Select((long id) => id.ToString()));
				zDO.Set(WardInfusionPlugin.WardPermittedHash, text);
			}
		}

		public string GetOwnerName()
		{
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
			if (!IsWarded() || m_cachedOwner == 0)
			{
				return "None";
			}
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer != (Object)null)
			{
				long playerID = localPlayer.GetPlayerID();
				if (playerID == m_cachedOwner)
				{
					return localPlayer.GetPlayerName();
				}
			}
			if ((Object)(object)ZNet.instance != (Object)null)
			{
				List<PlayerInfo> playerList = ZNet.instance.GetPlayerList();
				if (playerList != null)
				{
					foreach (PlayerInfo item in playerList)
					{
						PlayerInfo current = item;
						ZDOID characterID = current.m_characterID;
						if (((ZDOID)(ref characterID)).UserID == m_cachedOwner)
						{
							return current.m_name;
						}
						if (((ZDOID)(ref current.m_characterID)).ID == m_cachedOwner)
						{
							return current.m_name;
						}
					}
				}
			}
			foreach (Player allPlayer in Player.GetAllPlayers())
			{
				if (allPlayer.GetPlayerID() == m_cachedOwner)
				{
					return allPlayer.GetPlayerName();
				}
			}
			if ((Object)(object)m_piece != (Object)null)
			{
				long creator = m_piece.GetCreator();
				if (creator == m_cachedOwner)
				{
					return "You";
				}
			}
			return "Unknown";
		}

		private void OnDestroy()
		{
			if ((Object)(object)m_wardEffect != (Object)null)
			{
				Object.Destroy((Object)(object)m_wardEffect);
			}
		}
	}
	public class WardHoverable : MonoBehaviour, Hoverable
	{
		private Piece m_piece;

		private Smelter m_smelter;

		private void Awake()
		{
			m_piece = ((Component)this).GetComponentInParent<Piece>();
			m_smelter = ((Component)this).GetComponentInParent<Smelter>();
		}

		public string GetHoverText()
		{
			string text = "";
			text = (((Object)(object)m_piece != (Object)null) ? Localization.instance.Localize(m_piece.m_name) : ((!((Object)(object)m_smelter != (Object)null)) ? ((Object)((Component)this).gameObject).name.Replace("(Clone)", "").Trim() : ((Object)m_smelter).name.Replace("(Clone)", "").Trim()));
			WardedPiece componentInParent = ((Component)this).GetComponentInParent<WardedPiece>();
			if ((Object)(object)componentInParent != (Object)null && componentInParent.IsWarded())
			{
				return WardInfusionManager.GetWardedHoverText(componentInParent, text);
			}
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer != (Object)null)
			{
				Inventory inventory = ((Humanoid)localPlayer).GetInventory();
				if (inventory != null)
				{
					bool flag = false;
					foreach (ItemData allItem in inventory.GetAllItems())
					{
						if (allItem.m_shared.m_name == "Ward Essence" || ((Object)(object)allItem.m_dropPrefab != (Object)null && ((Object)allItem.m_dropPrefab).name == "WardEssence"))
						{
							flag = true;
							break;
						}
					}
					if (flag)
					{
						return text + "\n[<color=yellow><b>Alt + E</b></color>] Infuse Ward";
					}
				}
			}
			return text;
		}

		public string GetHoverName()
		{
			if ((Object)(object)m_piece != (Object)null)
			{
				return Localization.instance.Localize(m_piece.m_name);
			}
			return ((Object)((Component)this).gameObject).name.Replace("(Clone)", "").Trim();
		}

		public static void AddToPiece(GameObject pieceObj)
		{
			if ((Object)(object)pieceObj == (Object)null)
			{
				return;
			}
			int num = 0;
			Collider component = pieceObj.GetComponent<Collider>();
			if ((Object)(object)component != (Object)null && (Object)(object)pieceObj.GetComponent<WardHoverable>() == (Object)null)
			{
				pieceObj.AddComponent<WardHoverable>();
				num++;
			}
			Collider[] componentsInChildren = pieceObj.GetComponentsInChildren<Collider>(true);
			Collider[] array = componentsInChildren;
			foreach (Collider val in array)
			{
				if (!((Object)(object)((Component)val).GetComponent<WardHoverable>() != (Object)null) && !val.isTrigger)
				{
					((Component)val).gameObject.AddComponent<WardHoverable>();
					num++;
				}
			}
			WardInfusionPlugin.Instance.Logger.LogInfo((object)$"WardHoverable: Added {num} components to {((Object)pieceObj).name}");
		}
	}
	public static class WardInfusionManager
	{
		private static bool s_itemRegistered = false;

		private static bool s_recipeRegistered = false;

		private static WardedPiece s_currentWardedPiece;

		public static readonly HashSet<string> WardablePieces = new HashSet<string>
		{
			"piece_chest_wood", "piece_chest", "piece_chest_private", "piece_chest_blackmetal", "portal_wood", "portal", "smelter", "blastfurnace", "charcoal_kiln", "piece_bathtub",
			"piece_workbench", "piece_workbench_ext1", "piece_workbench_ext2", "piece_workbench_ext3", "piece_workbench_ext4", "forge", "forge_ext1", "forge_ext2", "forge_ext3", "forge_ext4",
			"forge_ext5", "forge_ext6", "piece_stonecutter", "piece_artisanstation", "piece_cauldron", "fermenter", "piece_spinningwheel", "windmill", "eitrrefinery", "piece_magetable",
			"piece_cookingstation", "piece_cookingstation_iron", "piece_oven", "piece_beehive", "piece_groundtorch_wood", "piece_brazierceiling01", "blackforge", "blackforge_ext1", "blackforge_ext2"
		};

		public static bool CanBeWarded(GameObject piece)
		{
			if ((Object)(object)piece == (Object)null)
			{
				return false;
			}
			string prefabName = Utils.GetPrefabName(piece);
			string item = prefabName.ToLower();
			bool flag = WardablePieces.Contains(prefabName) || WardablePieces.Contains(item);
			if (!flag && ((Object)(object)piece.GetComponent<Container>() != (Object)null || (Object)(object)piece.GetComponent<TeleportWorld>() != (Object)null || (Object)(object)piece.GetComponent<CraftingStation>() != (Object)null || (Object)(object)piece.GetComponent<Fermenter>() != (Object)null || (Object)(object)piece.GetComponent<Beehive>() != (Object)null || (Object)(object)piece.GetComponent<CookingStation>() != (Object)null || (Object)(object)piece.GetComponent<Smelter>() != (Object)null))
			{
				flag = true;
			}
			return flag;
		}

		public static void RegisterWardEssenceItem(ObjectDB objectDB)
		{
			//IL_022a: Unknown result type (might be due to invalid IL or missing references)
			if (s_itemRegistered || (Object)(object)objectDB == (Object)null)
			{
				return;
			}
			if (objectDB.m_items == null || objectDB.m_items.Count == 0)
			{
				WardInfusionPlugin.Instance.Logger.LogWarning((object)"ObjectDB items not loaded yet, skipping registration");
				return;
			}
			try
			{
				GameObject itemPrefab = objectDB.GetItemPrefab("WardEssence");
				if ((Object)(object)itemPrefab != (Object)null)
				{
					WardInfusionPlugin.WardEssencePrefab = itemPrefab;
					s_itemRegistered = true;
					WardInfusionPlugin.Instance.Logger.LogInfo((object)"Ward Essence already registered");
					return;
				}
				GameObject itemPrefab2 = objectDB.GetItemPrefab("SurtlingCore");
				if ((Object)(object)itemPrefab2 == (Object)null)
				{
					WardInfusionPlugin.Instance.Logger.LogWarning((object)"Could not find SurtlingCore");
					return;
				}
				WardInfusionPlugin.Instance.Logger.LogInfo((object)"Creating Ward Essence item...");
				bool activeSelf = itemPrefab2.activeSelf;
				itemPrefab2.SetActive(false);
				GameObject val = Object.Instantiate<GameObject>(itemPrefab2);
				((Object)val).name = "WardEssence";
				itemPrefab2.SetActive(activeSelf);
				Object.DontDestroyOnLoad((Object)(object)val);
				ZSyncTransform[] componentsInChildren = val.GetComponentsInChildren<ZSyncTransform>(true);
				foreach (ZSyncTransform val2 in componentsInChildren)
				{
					Object.DestroyImmediate((Object)(object)val2);
				}
				WardInfusionPlugin.Instance.Logger.LogInfo((object)"Removed ZSyncTransform components");
				ZNetView component = val.GetComponent<ZNetView>();
				if ((Object)(object)component != (Object)null)
				{
					FieldInfo field = typeof(ZNetView).GetField("m_prefabName", BindingFlags.Instance | BindingFlags.NonPublic);
					if (field != null)
					{
						field.SetValue(component, "WardEssence");
						WardInfusionPlugin.Instance.Logger.LogInfo((object)"Set ZNetView.m_prefabName to WardEssence");
					}
				}
				ItemDrop component2 = val.GetComponent<ItemDrop>();
				if ((Object)(object)component2 == (Object)null)
				{
					WardInfusionPlugin.Instance.Logger.LogError((object)"ItemDrop component not found!");
					Object.Destroy((Object)(object)val);
					return;
				}
				ItemData itemData = component2.m_itemData;
				itemData.m_shared.m_name = "Ward Essence";
				itemData.m_shared.m_description = "A magical essence that can protect individual build pieces. Hold Alt+E on a chest, portal, workstation, or other interactable piece to ward it.";
				itemData.m_shared.m_itemType = (ItemType)1;
				itemData.m_shared.m_maxStackSize = 50;
				itemData.m_shared.m_weight = 0.5f;
				itemData.m_shared.m_teleportable = true;
				ZNetScene instance = ZNetScene.instance;
				GameObject val3 = ((instance != null) ? instance.GetPrefab("guard_stone") : null);
				if ((Object)(object)val3 != (Object)null)
				{
					Piece component3 = val3.GetComponent<Piece>();
					if ((Object)(object)component3 != (Object)null && (Object)(object)component3.m_icon != (Object)null)
					{
						itemData.m_shared.m_icons = (Sprite[])(object)new Sprite[1] { component3.m_icon };
						WardInfusionPlugin.Instance.Logger.LogInfo((object)"Copied icon from guard_stone");
					}
				}
				itemData.m_dropPrefab = val;
				WardInfusionPlugin.Instance.Logger.LogInfo((object)"Ward Essence item configured");
				objectDB.m_items.Add(val);
				int stableHashCode = StringExtensionMethods.GetStableHashCode(((Object)val).name);
				try
				{
					FieldInfo field2 = typeof(ObjectDB).GetField("m_itemByHash", BindingFlags.Instance | BindingFlags.NonPublic);
					if (field2 != null && field2.GetValue(objectDB) is Dictionary<int, GameObject> dictionary && !dictionary.ContainsKey(stableHashCode))
					{
						dictionary[stableHashCode] = val;
						WardInfusionPlugin.Instance.Logger.LogInfo((object)$"Added to ObjectDB.m_itemByHash with hash {stableHashCode}");
					}
				}
				catch (Exception ex)
				{
					WardInfusionPlugin.Instance.Logger.LogWarning((object)("Could not update ObjectDB hash: " + ex.Message));
				}
				if ((Object)(object)ZNetScene.instance != (Object)null)
				{
					try
					{
						FieldInfo field3 = typeof(ZNetScene).GetField("m_namedPrefabs", BindingFlags.Instance | BindingFlags.NonPublic);
						if (field3 != null && field3.GetValue(ZNetScene.instance) is Dictionary<int, GameObject> dictionary2 && !dictionary2.ContainsKey(stableHashCode))
						{
							dictionary2[stableHashCode] = val;
							WardInfusionPlugin.Instance.Logger.LogInfo((object)$"Added to ZNetScene.m_namedPrefabs with hash {stableHashCode}");
						}
					}
					catch (Exception ex2)
					{
						WardInfusionPlugin.Instance.Logger.LogWarning((object)("Could not register with ZNetScene: " + ex2.Message));
					}
				}
				WardInfusionPlugin.WardEssencePrefab = val;
				s_itemRegistered = true;
				WardInfusionPlugin.Instance.Logger.LogInfo((object)"Ward Essence item registered successfully!");
			}
			catch (Exception arg)
			{
				WardInfusionPlugin.Instance.Logger.LogError((object)$"Failed to register Ward Essence: {arg}");
			}
		}

		public static void RegisterWardEssenceRecipe(ObjectDB objectDB)
		{
			//IL_01fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0201: Unknown result type (might be due to invalid IL or missing references)
			//IL_0209: Unknown result type (might be due to invalid IL or missing references)
			//IL_0211: Unknown result type (might be due to invalid IL or missing references)
			//IL_021d: Expected O, but got Unknown
			if (s_recipeRegistered)
			{
				return;
			}
			if ((Object)(object)objectDB == (Object)null)
			{
				WardInfusionPlugin.Instance.Logger.LogWarning((object)"RegisterWardEssenceRecipe: objectDB is null");
				return;
			}
			if ((Object)(object)WardInfusionPlugin.WardEssencePrefab == (Object)null)
			{
				WardInfusionPlugin.Instance.Logger.LogWarning((object)"RegisterWardEssenceRecipe: WardEssencePrefab is null - item not registered yet");
				return;
			}
			if (objectDB.m_items == null || objectDB.m_items.Count == 0)
			{
				WardInfusionPlugin.Instance.Logger.LogWarning((object)"RegisterWardEssenceRecipe: objectDB.m_items is empty");
				return;
			}
			if (objectDB.m_recipes == null)
			{
				WardInfusionPlugin.Instance.Logger.LogWarning((object)"RegisterWardEssenceRecipe: objectDB.m_recipes is null");
				return;
			}
			try
			{
				if ((Object)(object)objectDB.m_recipes.Find((Recipe x) => (Object)(object)x != (Object)null && ((Object)x).name == "Recipe_WardEssence") != (Object)null)
				{
					s_recipeRegistered = true;
					WardInfusionPlugin.Instance.Logger.LogInfo((object)"Ward Essence recipe already exists");
					return;
				}
				WardInfusionPlugin.Instance.Logger.LogInfo((object)"Creating Ward Essence recipe...");
				List<Requirement> list = new List<Requirement>();
				string value = WardInfusionPlugin.WardEssenceRecipe.Value;
				WardInfusionPlugin.Instance.Logger.LogInfo((object)("Recipe string: " + value));
				string[] array = value.Split(new char[1] { ',' });
				foreach (string text in array)
				{
					string[] array2 = text.Trim().Split(new char[1] { ':' });
					if (array2.Length != 2)
					{
						continue;
					}
					string text2 = array2[0].Trim();
					int num = int.Parse(array2[1].Trim());
					GameObject itemPrefab = objectDB.GetItemPrefab(text2);
					if ((Object)(object)itemPrefab != (Object)null)
					{
						ItemDrop component = itemPrefab.GetComponent<ItemDrop>();
						if ((Object)(object)component != (Object)null)
						{
							list.Add(new Requirement
							{
								m_resItem = component,
								m_amount = num,
								m_recover = true
							});
							WardInfusionPlugin.Instance.Logger.LogInfo((object)$"Added ingredient: {text2} x{num}");
						}
					}
					else
					{
						WardInfusionPlugin.Instance.Logger.LogWarning((object)("Recipe item not found: " + text2));
					}
				}
				if (list.Count == 0)
				{
					WardInfusionPlugin.Instance.Logger.LogWarning((object)"No valid ingredients found for Ward Essence recipe!");
					return;
				}
				Recipe val = ScriptableObject.CreateInstance<Recipe>();
				((Object)val).name = "Recipe_WardEssence";
				val.m_item = WardInfusionPlugin.WardEssencePrefab.GetComponent<ItemDrop>();
				val.m_amount = WardInfusionPlugin.WardEssenceCraftAmount.Value;
				val.m_enabled = true;
				val.m_minStationLevel = 1;
				ZNetScene instance = ZNetScene.instance;
				GameObject val2 = ((instance != null) ? instance.GetPrefab("piece_workbench") : null);
				if ((Object)(object)val2 != (Object)null)
				{
					CraftingStation component2 = val2.GetComponent<CraftingStation>();
					val.m_craftingStation = component2;
					WardInfusionPlugin.Instance.Logger.LogInfo((object)"Recipe set to require workbench");
				}
				else
				{
					WardInfusionPlugin.Instance.Logger.LogWarning((object)"Could not find workbench prefab, recipe will be hand-craftable");
				}
				val.m_resources = list.ToArray();
				objectDB.m_recipes.Add(val);
				s_recipeRegistered = true;
				WardInfusionPlugin.Instance.Logger.LogInfo((object)$"Ward Essence recipe registered successfully! Total recipes: {objectDB.m_recipes.Count}");
			}
			catch (Exception arg)
			{
				WardInfusionPlugin.Instance.Logger.LogError((object)$"Failed to register Ward Essence recipe: {arg}");
			}
		}

		public static bool ApplyWardToPiece(Player player, GameObject pieceObj)
		{
			//IL_032d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0332: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)player == (Object)null || (Object)(object)pieceObj == (Object)null)
			{
				WardInfusionPlugin.Instance.Logger.LogWarning((object)"ApplyWardToPiece: player or pieceObj is null");
				return false;
			}
			WardInfusionPlugin.Instance.Logger.LogInfo((object)("ApplyWardToPiece: Trying to ward " + ((Object)pieceObj).name));
			GameObject val = pieceObj;
			TeleportWorld componentInParent = pieceObj.GetComponentInParent<TeleportWorld>();
			Container componentInParent2 = pieceObj.GetComponentInParent<Container>();
			CraftingStation componentInParent3 = pieceObj.GetComponentInParent<CraftingStation>();
			Fermenter componentInParent4 = pieceObj.GetComponentInParent<Fermenter>();
			Beehive componentInParent5 = pieceObj.GetComponentInParent<Beehive>();
			CookingStation componentInParent6 = pieceObj.GetComponentInParent<CookingStation>();
			Smelter componentInParent7 = pieceObj.GetComponentInParent<Smelter>();
			if ((Object)(object)componentInParent != (Object)null)
			{
				val = ((Component)componentInParent).gameObject;
			}
			else if ((Object)(object)componentInParent2 != (Object)null)
			{
				val = ((Component)componentInParent2).gameObject;
			}
			else if ((Object)(object)componentInParent3 != (Object)null)
			{
				val = ((Component)componentInParent3).gameObject;
			}
			else if ((Object)(object)componentInParent4 != (Object)null)
			{
				val = ((Component)componentInParent4).gameObject;
			}
			else if ((Object)(object)componentInParent5 != (Object)null)
			{
				val = ((Component)componentInParent5).gameObject;
			}
			else if ((Object)(object)componentInParent6 != (Object)null)
			{
				val = ((Component)componentInParent6).gameObject;
			}
			else if ((Object)(object)componentInParent7 != (Object)null)
			{
				val = ((Component)componentInParent7).gameObject;
			}
			WardInfusionPlugin.Instance.Logger.LogInfo((object)("ApplyWardToPiece: Target object is " + ((Object)val).name));
			if (!CanBeWarded(val))
			{
				((Character)player).Message((MessageType)2, "Cannot apply ward to this piece.", 0, (Sprite)null);
				return false;
			}
			WardedPiece wardedPiece = val.GetComponent<WardedPiece>();
			if ((Object)(object)wardedPiece != (Object)null && wardedPiece.IsWarded())
			{
				((Character)player).Message((MessageType)2, "This piece is already warded.", 0, (Sprite)null);
				return false;
			}
			Inventory inventory = ((Humanoid)player).GetInventory();
			ItemData val2 = null;
			foreach (ItemData allItem in inventory.GetAllItems())
			{
				if (allItem.m_shared.m_name == "Ward Essence" || ((Object)(object)allItem.m_dropPrefab != (Object)null && ((Object)allItem.m_dropPrefab).name == "WardEssence"))
				{
					val2 = allItem;
					break;
				}
			}
			if (val2 == null)
			{
				((Character)player).Message((MessageType)2, "You need Ward Essence to ward this piece.", 0, (Sprite)null);
				return false;
			}
			inventory.RemoveItem(val2, 1);
			WardInfusionPlugin.Instance.Logger.LogInfo((object)("ApplyWardToPiece: Removed Ward Essence, applying ward to " + ((Object)val).name));
			if ((Object)(object)wardedPiece == (Object)null)
			{
				wardedPiece = val.AddComponent<WardedPiece>();
			}
			long playerID = player.GetPlayerID();
			WardInfusionPlugin.Instance.Logger.LogInfo((object)$"ApplyWardToPiece: Setting owner to {playerID} ({player.GetPlayerName()})");
			wardedPiece.InitializeWard(playerID);
			((Character)player).Message((MessageType)2, "Ward applied!", 0, (Sprite)null);
			if ((Object)(object)ZNetScene.instance != (Object)null)
			{
				GameObject prefab = ZNetScene.instance.GetPrefab("vfx_Place_stone_wall_2x1");
				if ((Object)(object)prefab != (Object)null)
				{
					Object.Instantiate<GameObject>(prefab, pieceObj.transform.position, Quaternion.identity);
				}
			}
			return true;
		}

		public static void ShowWardUI(WardedPiece wardedPiece)
		{
			s_currentWardedPiece = wardedPiece;
			if ((Object)(object)wardedPiece == (Object)null)
			{
				return;
			}
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer == (Object)null)
			{
				return;
			}
			long playerID = localPlayer.GetPlayerID();
			bool flag = wardedPiece.IsOwner(playerID);
			bool flag2 = wardedPiece.IsWardActive();
			string ownerName = wardedPiece.GetOwnerName();
			string text = (flag2 ? "Active" : "Inactive");
			if (flag)
			{
				string text2 = "Owner: " + ownerName + "\nStatus: " + text + "\n\n[1] " + (flag2 ? "Deactivate Ward" : "Activate Ward") + "\n[2] Remove Ward";
				if ((Object)(object)MessageHud.instance != (Object)null)
				{
					MessageHud.instance.ShowMessage((MessageType)2, text2, 0, (Sprite)null, false);
				}
			}
			else if (!flag2)
			{
				bool flag3 = wardedPiece.IsPermitted(playerID);
				string text3 = "Owner: " + ownerName + "\nStatus: " + text + "\n\n[1] " + (flag3 ? "Remove Yourself" : "Add Yourself");
				if ((Object)(object)MessageHud.instance != (Object)null)
				{
					MessageHud.instance.ShowMessage((MessageType)2, text3, 0, (Sprite)null, false);
				}
			}
			else
			{
				string text4 = "Owner: " + ownerName + "\nStatus: " + text + "\n\nWard is active. Ask owner to deactivate.";
				if ((Object)(object)MessageHud.instance != (Object)null)
				{
					MessageHud.instance.ShowMessage((MessageType)2, text4, 0, (Sprite)null, false);
				}
			}
		}

		public static void HandleWardUIInput(int key)
		{
			if ((Object)(object)s_currentWardedPiece == (Object)null)
			{
				return;
			}
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer == (Object)null)
			{
				return;
			}
			long playerID = localPlayer.GetPlayerID();
			bool flag = s_currentWardedPiece.IsOwner(playerID);
			bool flag2 = s_currentWardedPiece.IsWardActive();
			if (flag)
			{
				switch (key)
				{
				case 1:
					s_currentWardedPiece.SetActive(!flag2);
					((Character)localPlayer).Message((MessageType)2, flag2 ? "Ward deactivated." : "Ward activated!", 0, (Sprite)null);
					break;
				case 2:
					s_currentWardedPiece.RemoveWard();
					((Character)localPlayer).Message((MessageType)2, "Ward removed.", 0, (Sprite)null);
					break;
				}
			}
			else if (!flag2 && key == 1)
			{
				if (s_currentWardedPiece.IsPermitted(playerID))
				{
					s_currentWardedPiece.RemovePermitted(playerID);
					((Character)localPlayer).Message((MessageType)2, "You have been removed from this ward.", 0, (Sprite)null);
				}
				else
				{
					s_currentWardedPiece.AddPermitted(playerID);
					((Character)localPlayer).Message((MessageType)2, "You have been added to this ward.", 0, (Sprite)null);
				}
			}
			s_currentWardedPiece = null;
		}

		public static string GetWardedHoverText(WardedPiece wardedPiece, string originalText)
		{
			if ((Object)(object)wardedPiece == (Object)null || !wardedPiece.IsWarded())
			{
				return originalText;
			}
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer == (Object)null)
			{
				return originalText;
			}
			string ownerName = wardedPiece.GetOwnerName();
			bool flag = wardedPiece.IsOwner(localPlayer.GetPlayerID());
			bool flag2 = wardedPiece.IsLocalPlayerPermitted();
			bool flag3 = wardedPiece.IsWardActive();
			string text = (flag3 ? "<color=green>Active</color>" : "<color=yellow>Inactive</color>");
			string text2 = "\n<color=#00FFFF>[Warded]</color> " + text;
			text2 = text2 + "\nOwner: " + ownerName;
			if (flag || !flag3)
			{
				text2 += "\n<color=yellow>[Alt+E]</color> Manage Ward";
			}
			if (!flag2 && flag3)
			{
				text2 += "\n<color=red>No Access</color>";
			}
			return originalText + text2;
		}
	}
	[BepInPlugin("com.wardinfusion.valheim", "WardInfusion", "1.0.42")]
	public class WardInfusionPlugin : BaseUnityPlugin
	{
		public const string PluginGUID = "com.wardinfusion.valheim";

		public const string PluginName = "WardInfusion";

		public const string PluginVersion = "1.0.42";

		private static WardInfusionPlugin _instance;

		private Harmony _harmony;

		public static ConfigEntry<string> WardEssenceRecipe;

		public static ConfigEntry<int> WardEssenceCraftAmount;

		public static GameObject WardEssencePrefab;

		public static ItemData WardEssenceItem;

		public static readonly int WardOwnerHash = StringExtensionMethods.GetStableHashCode("WardInfusion_Owner");

		public static readonly int WardActiveHash = StringExtensionMethods.GetStableHashCode("WardInfusion_Active");

		public static readonly int WardPermittedHash = StringExtensionMethods.GetStableHashCode("WardInfusion_Permitted");

		public static WardInfusionPlugin Instance => _instance;

		public ManualLogSource Logger => ((BaseUnityPlugin)this).Logger;

		private void Awake()
		{
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Expected O, but got Unknown
			_instance = this;
			WardEssenceRecipe = ((BaseUnityPlugin)this).Config.Bind<string>("General", "WardEssenceRecipe", "FineWood:5,SurtlingCore:1,GreydwarfEye:5", "Recipe for Ward Essence (format: item:amount,item:amount)");
			WardEssenceCraftAmount = ((BaseUnityPlugin)this).Config.Bind<int>("General", "WardEssenceCraftAmount", 1, "Amount of Ward Essence crafted per recipe");
			_harmony = new Harmony("com.wardinfusion.valheim");
			try
			{
				SafePatcher.ApplyPatches(_harmony);
			}
			catch (Exception arg)
			{
				Logger.LogError((object)$"Failed to apply patches: {arg}");
			}
			Logger.LogInfo((object)"WardInfusion v1.0.42 loaded!");
		}

		private void OnDestroy()
		{
			Harmony harmony = _harmony;
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
		}
	}
}
namespace WardInfusion.Patches
{
	public static class SafePatcher
	{
		private static bool s_lateRegistrationDone;

		private static float s_lastInteractTime;

		private static bool s_waitingForInput;

		private static WardedPiece s_targetWard;

		public static void ApplyPatches(Harmony harmony)
		{
			TryPatch(harmony, typeof(ObjectDB), "Awake", null, typeof(SafePatcher).GetMethod("ObjectDB_Awake_Postfix", BindingFlags.Static | BindingFlags.Public));
			TryPatch(harmony, typeof(Game), "Start", null, typeof(SafePatcher).GetMethod("Game_Start_Postfix", BindingFlags.Static | BindingFlags.Public));
			TryPatch(harmony, typeof(Player), "OnSpawned", null, typeof(SafePatcher).GetMethod("Player_OnSpawned_Postfix", BindingFlags.Static | BindingFlags.Public));
			TryPatch(harmony, typeof(Player), "Update", null, typeof(SafePatcher).GetMethod("Player_Update_Postfix", BindingFlags.Static | BindingFlags.Public));
			TryPatchInteract(harmony, typeof(Container), "Container_Interact_Prefix");
			TryPatchInteract(harmony, typeof(TeleportWorld), "TeleportWorld_Interact_Prefix");
			TryPatchInteract(harmony, typeof(Fermenter), "Fermenter_Interact_Prefix");
			TryPatchInteract(harmony, typeof(Beehive), "Beehive_Interact_Prefix");
			TryPatchInteract(harmony, typeof(CraftingStation), "CraftingStation_Interact_Prefix");
			TryPatchInteract(harmony, typeof(CookingStation), "CookingStation_Interact_Prefix");
			TryPatch(harmony, typeof(ItemDrop), "DropItem", typeof(SafePatcher).GetMethod("ItemDrop_DropItem_Prefix", BindingFlags.Static | BindingFlags.Public), null);
			TryPatchHoverText(harmony, typeof(Container), "Container_GetHoverText_Postfix");
			TryPatchHoverText(harmony, typeof(TeleportWorld), "TeleportWorld_GetHoverText_Postfix");
			TryPatchHoverText(harmony, typeof(Fermenter), "Fermenter_GetHoverText_Postfix");
			TryPatchHoverText(harmony, typeof(Beehive), "Beehive_GetHoverText_Postfix");
			TryPatchHoverText(harmony, typeof(CraftingStation), "CraftingStation_GetHoverText_Postfix");
			TryPatchHoverText(harmony, typeof(CookingStation), "CookingStation_GetHoverText_Postfix");
			TryPatch(harmony, typeof(Smelter), "Awake", null, typeof(SafePatcher).GetMethod("Smelter_Awake_Postfix", BindingFlags.Static | BindingFlags.Public));
			TryPatch(harmony, typeof(Container), "Awake", null, typeof(SafePatcher).GetMethod("Container_Awake_Postfix", BindingFlags.Static | BindingFlags.Public));
			TryPatch(harmony, typeof(TeleportWorld), "Awake", null, typeof(SafePatcher).GetMethod("TeleportWorld_Awake_Postfix", BindingFlags.Static | BindingFlags.Public));
			TryPatch(harmony, typeof(CraftingStation), "Awake", null, typeof(SafePatcher).GetMethod("CraftingStation_Awake_Postfix", BindingFlags.Static | BindingFlags.Public));
			TryPatch(harmony, typeof(Fermenter), "Awake", null, typeof(SafePatcher).GetMethod("Fermenter_Awake_Postfix", BindingFlags.Static | BindingFlags.Public));
			TryPatch(harmony, typeof(Beehive), "Awake", null, typeof(SafePatcher).GetMethod("Beehive_Awake_Postfix", BindingFlags.Static | BindingFlags.Public));
			TryPatch(harmony, typeof(CookingStation), "Awake", null, typeof(SafePatcher).GetMethod("CookingStation_Awake_Postfix", BindingFlags.Static | BindingFlags.Public));
		}

		private static void TryPatch(Harmony harmony, Type targetType, string methodName, MethodInfo prefix, MethodInfo postfix)
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				MethodInfo methodInfo = AccessTools.Method(targetType, methodName, (Type[])null, (Type[])null);
				if (methodInfo != null)
				{
					object obj = harmony;
					obj = methodInfo;
					obj = (object)((!(prefix != null)) ? ((HarmonyMethod)null) : new HarmonyMethod(prefix));
					obj = (object)((!(postfix != null)) ? ((HarmonyMethod)null) : new HarmonyMethod(postfix));
					((Harmony)obj).Patch((MethodBase)obj, (HarmonyMethod)obj, (HarmonyMethod)obj, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
					WardInfusionPlugin.Instance.Logger.LogInfo((object)("Patched " + targetType.Name + "." + methodName));
				}
				else
				{
					WardInfusionPlugin.Instance.Logger.LogWarning((object)("Method not found: " + targetType.Name + "." + methodName));
				}
			}
			catch (Exception ex)
			{
				WardInfusionPlugin.Instance.Logger.LogWarning((object)("Failed to patch " + targetType.Name + "." + methodName + ": " + ex.Message));
			}
		}

		private static void TryPatchInteract(Harmony harmony, Type targetType, string prefixMethodName)
		{
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Expected O, but got Unknown
			try
			{
				MethodInfo[] methods = targetType.GetMethods(BindingFlags.Instance | BindingFlags.Public);
				MethodInfo methodInfo = null;
				MethodInfo[] array = methods;
				foreach (MethodInfo methodInfo2 in array)
				{
					if (methodInfo2.Name == "Interact")
					{
						methodInfo = methodInfo2;
						break;
					}
				}
				if (methodInfo != null)
				{
					MethodInfo method = typeof(SafePatcher).GetMethod(prefixMethodName, BindingFlags.Static | BindingFlags.Public);
					if (method != null)
					{
						harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(method), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
						WardInfusionPlugin.Instance.Logger.LogInfo((object)("Patched " + targetType.Name + ".Interact"));
					}
				}
				else
				{
					WardInfusionPlugin.Instance.Logger.LogWarning((object)("Interact method not found on " + targetType.Name));
				}
			}
			catch (Exception ex)
			{
				WardInfusionPlugin.Instance.Logger.LogWarning((object)("Failed to patch " + targetType.Name + ".Interact: " + ex.Message));
			}
		}

		private static void TryPatchHoverText(Harmony harmony, Type targetType, string postfixMethodName)
		{
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Expected O, but got Unknown
			try
			{
				MethodInfo methodInfo = AccessTools.Method(targetType, "GetHoverText", (Type[])null, (Type[])null);
				if (methodInfo != null)
				{
					MethodInfo method = typeof(SafePatcher).GetMethod(postfixMethodName, BindingFlags.Static | BindingFlags.Public);
					if (method != null)
					{
						harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(method), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
					}
				}
			}
			catch (Exception ex)
			{
				WardInfusionPlugin.Instance.Logger.LogWarning((object)("Failed to patch " + targetType.Name + ".GetHoverText: " + ex.Message));
			}
		}

		public static void ObjectDB_Awake_Postfix(ObjectDB __instance)
		{
			WardInfusionPlugin.Instance.Logger.LogInfo((object)"ObjectDB.Awake called");
			TryRegisterItems(__instance, "ObjectDB.Awake");
		}

		public static void Game_Start_Postfix()
		{
			WardInfusionPlugin.Instance.Logger.LogInfo((object)"Game.Start called - attempting registration");
			if ((Object)(object)ObjectDB.instance != (Object)null)
			{
				TryRegisterItems(ObjectDB.instance, "Game.Start");
			}
			else
			{
				WardInfusionPlugin.Instance.Logger.LogWarning((object)"Game.Start: ObjectDB.instance is null");
			}
			if ((Object)(object)WardInfusionPlugin.WardEssencePrefab != (Object)null && (Object)(object)ZNetScene.instance != (Object)null)
			{
				EnsureZNetSceneRegistration();
			}
		}

		private static void EnsureZNetSceneRegistration()
		{
			try
			{
				GameObject wardEssencePrefab = WardInfusionPlugin.WardEssencePrefab;
				if ((Object)(object)wardEssencePrefab == (Object)null)
				{
					return;
				}
				int stableHashCode = StringExtensionMethods.GetStableHashCode(((Object)wardEssencePrefab).name);
				FieldInfo field = typeof(ObjectDB).GetField("m_itemByHash", BindingFlags.Instance | BindingFlags.NonPublic);
				if (field != null && (Object)(object)ObjectDB.instance != (Object)null && field.GetValue(ObjectDB.instance) is Dictionary<int, GameObject> dictionary && !dictionary.ContainsKey(stableHashCode))
				{
					dictionary[stableHashCode] = wardEssencePrefab;
					WardInfusionPlugin.Instance.Logger.LogInfo((object)$"Added Ward Essence to ObjectDB.m_itemByHash (hash: {stableHashCode})");
				}
				if ((Object)(object)ZNetScene.instance != (Object)null)
				{
					FieldInfo field2 = typeof(ZNetScene).GetField("m_namedPrefabs", BindingFlags.Instance | BindingFlags.NonPublic);
					if (field2 != null && field2.GetValue(ZNetScene.instance) is Dictionary<int, GameObject> dictionary2 && !dictionary2.ContainsKey(stableHashCode))
					{
						dictionary2[stableHashCode] = wardEssencePrefab;
						WardInfusionPlugin.Instance.Logger.LogInfo((object)$"Added Ward Essence to ZNetScene.m_namedPrefabs (hash: {stableHashCode})");
					}
				}
				ItemDrop component = wardEssencePrefab.GetComponent<ItemDrop>();
				if ((Object)(object)component != (Object)null)
				{
					component.m_itemData.m_dropPrefab = wardEssencePrefab;
					WardInfusionPlugin.Instance.Logger.LogInfo((object)"Set dropPrefab to WardEssence");
				}
			}
			catch (Exception arg)
			{
				WardInfusionPlugin.Instance.Logger.LogError((object)$"EnsureZNetSceneRegistration failed: {arg}");
			}
		}

		public static void Player_OnSpawned_Postfix()
		{
			if (!s_lateRegistrationDone)
			{
				WardInfusionPlugin.Instance.Logger.LogInfo((object)"Player.OnSpawned - final registration attempt");
				if ((Object)(object)ObjectDB.instance != (Object)null)
				{
					TryRegisterItems(ObjectDB.instance, "Player.OnSpawned");
					s_lateRegistrationDone = true;
				}
				else
				{
					WardInfusionPlugin.Instance.Logger.LogWarning((object)"Player.OnSpawned: ObjectDB.instance is null");
				}
			}
		}

		public static void ItemDrop_DropItem_Prefix(ItemData item, int amount, Vector3 position, Quaternion rotation)
		{
			if (item != null && (item.m_shared.m_name == "Ward Essence" || ((Object)(object)item.m_dropPrefab != (Object)null && ((Object)item.m_dropPrefab).name == "WardEssence")) && (Object)(object)item.m_dropPrefab == (Object)null)
			{
				GameObject wardEssencePrefab = WardInfusionPlugin.WardEssencePrefab;
				if ((Object)(object)wardEssencePrefab != (Object)null)
				{
					item.m_dropPrefab = wardEssencePrefab;
					WardInfusionPlugin.Instance.Logger.LogInfo((object)"Fixed Ward Essence dropPrefab");
				}
			}
		}

		public static void Smelter_Awake_Postfix(Smelter __instance)
		{
			if (!((Object)(object)__instance == (Object)null))
			{
				WardHoverable.AddToPiece(((Component)__instance).gameObject);
				WardInfusionPlugin.Instance.Logger.LogInfo((object)("Added WardHoverable to Smelter: " + ((Object)((Component)__instance).gameObject).name));
				TryRestoreWard(((Component)__instance).gameObject);
			}
		}

		public static void Container_Awake_Postfix(Container __instance)
		{
			if (!((Object)(object)__instance == (Object)null))
			{
				TryRestoreWard(((Component)__instance).gameObject);
			}
		}

		public static void TeleportWorld_Awake_Postfix(TeleportWorld __instance)
		{
			if (!((Object)(object)__instance == (Object)null))
			{
				TryRestoreWard(((Component)__instance).gameObject);
			}
		}

		public static void CraftingStation_Awake_Postfix(CraftingStation __instance)
		{
			if (!((Object)(object)__instance == (Object)null))
			{
				TryRestoreWard(((Component)__instance).gameObject);
			}
		}

		public static void Fermenter_Awake_Postfix(Fermenter __instance)
		{
			if (!((Object)(object)__instance == (Object)null))
			{
				TryRestoreWard(((Component)__instance).gameObject);
			}
		}

		public static void Beehive_Awake_Postfix(Beehive __instance)
		{
			if (!((Object)(object)__instance == (Object)null))
			{
				TryRestoreWard(((Component)__instance).gameObject);
			}
		}

		public static void CookingStation_Awake_Postfix(CookingStation __instance)
		{
			if (!((Object)(object)__instance == (Object)null))
			{
				TryRestoreWard(((Component)__instance).gameObject);
			}
		}

		private static void TryRestoreWard(GameObject pieceObj)
		{
			if ((Object)(object)pieceObj == (Object)null || (Object)(object)pieceObj.GetComponent<WardedPiece>() != (Object)null)
			{
				return;
			}
			ZNetView component = pieceObj.GetComponent<ZNetView>();
			if ((Object)(object)component == (Object)null || !component.IsValid())
			{
				return;
			}
			ZDO zDO = component.GetZDO();
			if (zDO != null)
			{
				long @long = zDO.GetLong(WardInfusionPlugin.WardOwnerHash, 0L);
				if (@long != 0)
				{
					WardedPiece wardedPiece = pieceObj.AddComponent<WardedPiece>();
					WardInfusionPlugin.Instance.Logger.LogInfo((object)$"Restored ward on {((Object)pieceObj).name} (Owner: {@long})");
				}
			}
		}

		private static void TryRegisterItems(ObjectDB objectDB, string source)
		{
			try
			{
				WardInfusionPlugin.Instance.Logger.LogInfo((object)("[" + source + "] Attempting item registration..."));
				WardInfusionPlugin.Instance.Logger.LogInfo((object)$"[{source}] ObjectDB.m_items count: {objectDB.m_items?.Count ?? (-1)}");
				WardInfusionManager.RegisterWardEssenceItem(objectDB);
				WardInfusionManager.RegisterWardEssenceRecipe(objectDB);
			}
			catch (Exception arg)
			{
				WardInfusionPlugin.Instance.Logger.LogError((object)$"[{source}] Registration failed: {arg}");
			}
		}

		public static void Player_Update_Postfix(Player __instance)
		{
			//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00de: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_0126: Unknown result type (might be due to invalid IL or missing references)
			//IL_012b: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)__instance != (Object)(object)Player.m_localPlayer)
			{
				return;
			}
			if (Input.GetKey((KeyCode)308) && Input.GetKeyDown((KeyCode)101))
			{
				GameObject hoverObject = ((Humanoid)__instance).GetHoverObject();
				GameObject val = null;
				if ((Object)(object)hoverObject != (Object)null)
				{
					Smelter componentInParent = hoverObject.GetComponentInParent<Smelter>();
					if ((Object)(object)componentInParent != (Object)null)
					{
						val = ((Component)componentInParent).gameObject;
					}
					else
					{
						Piece componentInParent2 = hoverObject.GetComponentInParent<Piece>();
						if ((Object)(object)componentInParent2 != (Object)null)
						{
							val = ((Component)componentInParent2).gameObject;
						}
					}
				}
				if ((Object)(object)val == (Object)null)
				{
					Camera main = Camera.main;
					if ((Object)(object)main != (Object)null)
					{
						Ray val2 = main.ScreenPointToRay(new Vector3((float)Screen.width / 2f, (float)Screen.height / 2f, 0f));
						RaycastHit[] array = Physics.RaycastAll(val2, 50f);
						Array.Sort(array, (RaycastHit a, RaycastHit b) => ((RaycastHit)(ref a)).distance.CompareTo(((RaycastHit)(ref b)).distance));
						RaycastHit[] array2 = array;
						for (int i = 0; i < array2.Length; i++)
						{
							RaycastHit val3 = array2[i];
							if (!((Object)(object)((Component)((RaycastHit)(ref val3)).collider).gameObject.GetComponent<Heightmap>() != (Object)null) && ((Component)((RaycastHit)(ref val3)).collider).gameObject.layer != 8)
							{
								Smelter componentInParent3 = ((Component)((RaycastHit)(ref val3)).collider).GetComponentInParent<Smelter>();
								if ((Object)(object)componentInParent3 != (Object)null)
								{
									val = ((Component)componentInParent3).gameObject;
									break;
								}
								Piece componentInParent4 = ((Component)((RaycastHit)(ref val3)).collider).GetComponentInParent<Piece>();
								if ((Object)(object)componentInParent4 != (Object)null && WardInfusionManager.CanBeWarded(((Component)componentInParent4).gameObject))
								{
									val = ((Component)componentInParent4).gameObject;
									break;
								}
							}
						}
					}
				}
				if ((Object)(object)val != (Object)null)
				{
					WardedPiece wardedPiece = val.GetComponent<WardedPiece>();
					if ((Object)(object)wardedPiece == (Object)null)
					{
						wardedPiece = val.GetComponentInParent<WardedPiece>();
					}
					if ((Object)(object)wardedPiece != (Object)null && wardedPiece.IsWarded())
					{
						s_targetWard = wardedPiece;
						s_waitingForInput = true;
						s_lastInteractTime = Time.time;
						WardInfusionManager.ShowWardUI(wardedPiece);
					}
					else
					{
						Inventory inventory = ((Humanoid)__instance).GetInventory();
						if (inventory != null)
						{
							bool flag = false;
							foreach (ItemData allItem in inventory.GetAllItems())
							{
								if (allItem.m_shared.m_name == "Ward Essence" || ((Object)(object)allItem.m_dropPrefab != (Object)null && ((Object)allItem.m_dropPrefab).name == "WardEssence"))
								{
									flag = true;
									break;
								}
							}
							if (flag)
							{
								WardInfusionManager.ApplyWardToPiece(__instance, val);
							}
						}
					}
				}
			}
			if (s_waitingForInput && (Object)(object)s_targetWard != (Object)null)
			{
				if (Time.time - s_lastInteractTime > 5f)
				{
					s_waitingForInput = false;
					s_targetWard = null;
				}
				else if (Input.GetKeyDown((KeyCode)49) || Input.GetKeyDown((KeyCode)257))
				{
					WardInfusionManager.HandleWardUIInput(1);
					s_waitingForInput = false;
					s_targetWard = null;
				}
				else if (Input.GetKeyDown((KeyCode)50) || Input.GetKeyDown((KeyCode)258))
				{
					WardInfusionManager.HandleWardUIInput(2);
					s_waitingForInput = false;
					s_targetWard = null;
				}
				else if (Input.GetKeyDown((KeyCode)27))
				{
					s_waitingForInput = false;
					s_targetWard = null;
				}
			}
		}

		public static bool Container_Interact_Prefix(Container __instance, ref bool __result)
		{
			if (TryApplyWardFromInteract(((Component)__instance).gameObject, ref __result))
			{
				return false;
			}
			return CheckWardPermission(((Component)__instance).gameObject, ref __result);
		}

		public static bool TeleportWorld_Interact_Prefix(TeleportWorld __instance, ref bool __result)
		{
			if (TryApplyWardFromInteract(((Component)__instance).gameObject, ref __result))
			{
				return false;
			}
			return CheckWardPermission(((Component)__instance).gameObject, ref __result);
		}

		public static bool Fermenter_Interact_Prefix(Fermenter __instance, ref bool __result)
		{
			if (TryApplyWardFromInteract(((Component)__instance).gameObject, ref __result))
			{
				return false;
			}
			return CheckWardPermission(((Component)__instance).gameObject, ref __result);
		}

		public static bool Beehive_Interact_Prefix(Beehive __instance, ref bool __result)
		{
			if (TryApplyWardFromInteract(((Component)__instance).gameObject, ref __result))
			{
				return false;
			}
			return CheckWardPermission(((Component)__instance).gameObject, ref __result);
		}

		public static bool CraftingStation_Interact_Prefix(CraftingStation __instance, ref bool __result)
		{
			if (TryApplyWardFromInteract(((Component)__instance).gameObject, ref __result))
			{
				return false;
			}
			return CheckWardPermission(((Component)__instance).gameObject, ref __result);
		}

		public static bool CookingStation_Interact_Prefix(CookingStation __instance, ref bool __result)
		{
			if (TryApplyWardFromInteract(((Component)__instance).gameObject, ref __result))
			{
				return false;
			}
			return CheckWardPermission(((Component)__instance).gameObject, ref __result);
		}

		private static bool TryApplyWardFromInteract(GameObject obj, ref bool result)
		{
			if (!Input.GetKey((KeyCode)308))
			{
				return false;
			}
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer == (Object)null)
			{
				return false;
			}
			Inventory inventory = ((Humanoid)localPlayer).GetInventory();
			if (inventory == null)
			{
				return false;
			}
			ItemData val = null;
			foreach (ItemData allItem in inventory.GetAllItems())
			{
				if (allItem.m_shared.m_name == "Ward Essence" || ((Object)(object)allItem.m_dropPrefab != (Object)null && ((Object)allItem.m_dropPrefab).name == "WardEssence"))
				{
					val = allItem;
					break;
				}
			}
			if (val != null)
			{
				bool flag = WardInfusionManager.ApplyWardToPiece(localPlayer, obj);
				result = flag;
				return true;
			}
			return false;
		}

		private static bool CheckWardPermission(GameObject obj, ref bool result)
		{
			WardedPiece wardedPiece = obj.GetComponent<WardedPiece>();
			if ((Object)(object)wardedPiece == (Object)null)
			{
				wardedPiece = obj.GetComponentInParent<WardedPiece>();
			}
			if ((Object)(object)wardedPiece != (Object)null && wardedPiece.IsWarded() && !wardedPiece.IsLocalPlayerPermitted())
			{
				if ((Object)(object)Player.m_localPlayer != (Object)null)
				{
					((Character)Player.m_localPlayer).Message((MessageType)2, "You are not permitted to use this.", 0, (Sprite)null);
				}
				result = false;
				return false;
			}
			return true;
		}

		public static void Container_GetHoverText_Postfix(Container __instance, ref string __result)
		{
			AddWardedHoverText(((Component)__instance).gameObject, ref __result);
		}

		public static void TeleportWorld_GetHoverText_Postfix(TeleportWorld __instance, ref string __result)
		{
			AddWardedHoverText(((Component)__instance).gameObject, ref __result);
		}

		public static void Fermenter_GetHoverText_Postfix(Fermenter __instance, ref string __result)
		{
			AddWardedHoverText(((Component)__instance).gameObject, ref __result);
		}

		public static void Beehive_GetHoverText_Postfix(Beehive __instance, ref string __result)
		{
			AddWardedHoverText(((Component)__instance).gameObject, ref __result);
		}

		public static void CraftingStation_GetHoverText_Postfix(CraftingStation __instance, ref string __result)
		{
			AddWardedHoverText(((Component)__instance).gameObject, ref __result);
		}

		public static void CookingStation_GetHoverText_Postfix(CookingStation __instance, ref string __result)
		{
			AddWardedHoverText(((Component)__instance).gameObject, ref __result);
		}

		private static void AddWardedHoverText(GameObject obj, ref string result)
		{
			WardedPiece wardedPiece = obj.GetComponent<WardedPiece>();
			if ((Object)(object)wardedPiece == (Object)null)
			{
				wardedPiece = obj.GetComponentInParent<WardedPiece>();
			}
			if ((Object)(object)wardedPiece != (Object)null && wardedPiece.IsWarded())
			{
				result = WardInfusionManager.GetWardedHoverText(wardedPiece, result);
				return;
			}
			Player localPlayer = Player.m_localPlayer;
			if (!((Object)(object)localPlayer != (Object)null) || !WardInfusionManager.CanBeWarded(obj))
			{
				return;
			}
			Inventory inventory = ((Humanoid)localPlayer).GetInventory();
			if (inventory == null)
			{
				return;
			}
			bool flag = false;
			foreach (ItemData allItem in inventory.GetAllItems())
			{
				if (allItem.m_shared.m_name == "Ward Essence" || ((Object)(object)allItem.m_dropPrefab != (Object)null && ((Object)allItem.m_dropPrefab).name == "WardEssence"))
				{
					flag = true;
					break;
				}
			}
			if (flag)
			{
				result += "\n[<color=yellow><b>Alt + E</b></color>] Infuse Ward";
			}
		}
	}
}