Decompiled source of SharedUpgrades Mod Compatibility and QoL Focused v1.0.1

BepInEx/plugins/SharedUpgradesModCompatibilityQoL/SharedUpgradesModCompatibilityQoL.dll

Decompiled 32 minutes 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.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using ExitGames.Client.Photon;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Photon.Pun;
using Photon.Realtime;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("ByteSizeMetal")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.1.0")]
[assembly: AssemblyInformationalVersion("1.0.1")]
[assembly: AssemblyProduct("SharedUpgrades - Mod Compatibility and QoL Focused")]
[assembly: AssemblyTitle("SharedUpgradesModCompatibilityQoL")]
[assembly: AssemblyMetadata("Author", "ByteSizeMetal")]
[assembly: AssemblyVersion("1.0.1.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[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 SharedUpgradesFix
{
	internal enum UpgradeKind
	{
		Vanilla,
		RepoLib,
		StatKey
	}
	internal sealed class UpgradeInfo
	{
		public string Key;

		public string Id;

		public string Source;

		public string ItemName;

		public UpgradeKind Kind;

		public Assembly Owner;

		internal object Registered;

		public object Target;

		public bool DetectedPooled;

		public string PooledReason;

		public string TeamEffect;

		public PropertyInfo MaxLevelProp;

		public string DisplayName => Catalog.Pretty(Id);

		public bool Pooled => UpgradeOptions.Pooled(this);

		public int MaxLevel()
		{
			if (HostRules.Remote)
			{
				if (!HostRules.TryRule(Key, out var rule))
				{
					return 0;
				}
				return rule.Cap;
			}
			if (MaxLevelProp == null || Target == null)
			{
				return 0;
			}
			try
			{
				object? value = MaxLevelProp.GetValue(Target);
				ConfigEntryBase val = (ConfigEntryBase)((value is ConfigEntryBase) ? value : null);
				if (val != null)
				{
					object boxedValue = val.BoxedValue;
					if (boxedValue is int)
					{
						return (int)boxedValue;
					}
				}
			}
			catch
			{
			}
			return 0;
		}
	}
	internal static class Catalog
	{
		public const string KeyPrefix = "playerUpgrade";

		internal const int MaxKeys = 512;

		private static FieldInfo _repoDict;

		private static FieldInfo _idField;

		private static FieldInfo _itemField;

		private static PropertyInfo _repoProp;

		private static FieldInfo[] _callbackFields;

		private static Type _repoPlayerUpgrade;

		private static MethodInfo _repoGetLevel;

		private static readonly Dictionary<string, UpgradeInfo> ByKey = new Dictionary<string, UpgradeInfo>();

		private static readonly HashSet<Assembly> Scanned = new HashSet<Assembly>();

		private static int _lastRepoCount = -1;

		public static bool RepoLibReady { get; private set; }

		public static IEnumerable<UpgradeInfo> All => ByKey.Values;

		internal static void RefreshForDisplay()
		{
			RefreshRepoLib(force: false);
		}

		public static void InitRepoLib(Assembly repoLib)
		{
			if (repoLib == null)
			{
				Plugin.Log.LogWarning((object)"REPOLib not found - REPOLib upgrades can't be identified; share-once and team-pool detection are off.");
				return;
			}
			Type type = repoLib.GetType("REPOLib.Modules.Upgrades");
			_repoPlayerUpgrade = repoLib.GetType("REPOLib.Modules.PlayerUpgrade");
			if (type == null || _repoPlayerUpgrade == null)
			{
				Plugin.Log.LogWarning((object)"REPOLib: 'REPOLib.Modules.Upgrades' or 'REPOLib.Modules.PlayerUpgrade' not found - REPOLib-specific fixes are off.");
				return;
			}
			_repoDict = type.GetField("_playerUpgrades", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			_repoProp = type.GetProperty("PlayerUpgrades", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			_idField = _repoPlayerUpgrade.GetField("UpgradeId", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			_itemField = _repoPlayerUpgrade.GetField("Item", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			_repoGetLevel = _repoPlayerUpgrade.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).FirstOrDefault((MethodInfo m) => m.Name == "GetLevel");
			_callbackFields = new FieldInfo[2]
			{
				_repoPlayerUpgrade.GetField("_upgradeAction", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic),
				_repoPlayerUpgrade.GetField("StartAction", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
			}.Where((FieldInfo f) => f != null && typeof(Delegate).IsAssignableFrom(f.FieldType)).ToArray();
			if ((_repoDict == null && _repoProp == null) || _idField == null)
			{
				Plugin.Log.LogWarning((object)"REPOLib: upgrade list ('Upgrades._playerUpgrades'/'PlayerUpgrades') or 'PlayerUpgrade.UpgradeId' not found - REPOLib-specific fixes are off.");
			}
			else
			{
				RepoLibReady = true;
			}
		}

		public static bool TryGet(string key, out UpgradeInfo info)
		{
			info = null;
			if (key == null || !key.StartsWith("playerUpgrade", StringComparison.Ordinal))
			{
				return false;
			}
			if (ByKey.TryGetValue(key, out info))
			{
				return true;
			}
			RefreshRepoLib(force: false);
			return ByKey.TryGetValue(key, out info);
		}

		public static bool IsRepoLib(string key)
		{
			if (TryGet(key, out var info))
			{
				return info.Kind == UpgradeKind.RepoLib;
			}
			return false;
		}

		public static UpgradeInfo ForItem(Item item)
		{
			if ((Object)(object)item == (Object)null)
			{
				return null;
			}
			RefreshRepoLib(force: false);
			UpgradeInfo upgradeInfo = ByKey.Values.FirstOrDefault((UpgradeInfo u) => u.ItemName == ((Object)item).name);
			if (upgradeInfo != null)
			{
				return upgradeInfo;
			}
			string name = SyncPolicy.Normalize(((Object)item).name);
			return ByKey.Values.FirstOrDefault((UpgradeInfo u) => u.ItemName == null && name.EndsWith(SyncPolicy.Normalize(u.Id), StringComparison.Ordinal));
		}

		internal static void RegisterNative(string key)
		{
			if (!ByKey.ContainsKey(key))
			{
				ByKey.Add(key, new UpgradeInfo
				{
					Key = key,
					Id = Strip(key),
					Source = "R.E.P.O. (vanilla)",
					Kind = UpgradeKind.Vanilla
				});
			}
		}

		private static void RefreshRepoLib(bool force)
		{
			if (!RepoLibReady)
			{
				return;
			}
			List<object> list;
			try
			{
				if (_repoDict?.GetValue(null) is IDictionary dictionary)
				{
					if (!force && dictionary.Count == _lastRepoCount)
					{
						return;
					}
					_lastRepoCount = dictionary.Count;
					list = dictionary.Values.Cast<object>().ToList();
				}
				else
				{
					list = (_repoProp.GetValue(null) as IEnumerable)?.Cast<object>().ToList() ?? new List<object>();
					if (!force && list.Count == _lastRepoCount)
					{
						return;
					}
					_lastRepoCount = list.Count;
				}
			}
			catch (Exception ex)
			{
				Plugin.Debug("reading REPOLib upgrades failed: " + ex.Message);
				return;
			}
			bool flag = false;
			foreach (object pu in list)
			{
				string text = ((pu == null) ? null : (_idField.GetValue(pu) as string));
				if (string.IsNullOrEmpty(text))
				{
					continue;
				}
				string key = "playerUpgrade" + text;
				if (!ByKey.TryGetValue(key, out var value) || value.Kind != UpgradeKind.RepoLib)
				{
					Delegate? obj = _callbackFields.Select((FieldInfo f) => f.GetValue(pu) as Delegate).FirstOrDefault((Delegate x) => (object)x != null);
					Assembly assembly = obj?.Method?.DeclaringType?.Assembly;
					if (assembly == null)
					{
						assembly = MoreInterop.NativeOwner(pu);
					}
					object obj2 = obj?.Target;
					UpgradeInfo obj3 = new UpgradeInfo
					{
						Key = key,
						Id = text,
						Kind = UpgradeKind.RepoLib,
						Owner = assembly,
						Target = obj2,
						Registered = pu
					};
					object? obj4 = _itemField?.GetValue(pu);
					object? obj5 = ((obj4 is Item) ? obj4 : null);
					obj3.ItemName = ((obj5 != null) ? ((Object)obj5).name : null);
					obj3.Source = PluginName(assembly) ?? "unknown REPOLib mod";
					UpgradeInfo upgradeInfo = obj3;
					PropertyInfo propertyInfo = obj2?.GetType().GetProperty("MaxLevel", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
					if (propertyInfo != null && typeof(ConfigEntryBase).IsAssignableFrom(propertyInfo.PropertyType))
					{
						upgradeInfo.MaxLevelProp = propertyInfo;
					}
					upgradeInfo.TeamEffect = TeamEffectCompat.Description(upgradeInfo);
					if (upgradeInfo.TeamEffect != null)
					{
						Mark(upgradeInfo, upgradeInfo.TeamEffect);
					}
					ByKey[key] = upgradeInfo;
					flag = true;
				}
			}
			if (flag && !force)
			{
				ScanNewOwners();
				UpgradeOptions.Register(ByKey.Values);
			}
		}

		private static string PluginName(Assembly a)
		{
			if (a == null)
			{
				return null;
			}
			foreach (PluginInfo value in Chainloader.PluginInfos.Values)
			{
				if ((Object)(object)value.Instance != (Object)null && ((object)value.Instance).GetType().Assembly == a)
				{
					return $"{value.Metadata.Name} {value.Metadata.Version}";
				}
			}
			return a.GetName().Name;
		}

		private static void ScanNewOwners()
		{
			foreach (Assembly item in (from u in ByKey.Values
				where u.Kind == UpgradeKind.RepoLib && u.Owner != null
				select u.Owner).Distinct().ToList())
			{
				if (Scanned.Add(item))
				{
					try
					{
						ScanAssembly(item);
					}
					catch (Exception ex)
					{
						Plugin.Log.LogWarning((object)("Team-pool scan of " + item.GetName().Name + " failed: " + ex.Message));
					}
				}
			}
		}

		private static void ScanAssembly(Assembly asm)
		{
			List<UpgradeInfo> source = ByKey.Values.Where((UpgradeInfo u) => u.Owner == asm).ToList();
			Dictionary<string, UpgradeInfo> dictionary = source.GroupBy<UpgradeInfo, string>((UpgradeInfo u) => u.Id, StringComparer.OrdinalIgnoreCase).ToDictionary<IGrouping<string, UpgradeInfo>, string, UpgradeInfo>((IGrouping<string, UpgradeInfo> g) => g.Key, (IGrouping<string, UpgradeInfo> g) => g.First(), StringComparer.OrdinalIgnoreCase);
			Dictionary<Type, List<UpgradeInfo>> dictionary2 = (from u in source
				where u.Target != null
				group u by u.Target.GetType()).ToDictionary((IGrouping<Type, UpgradeInfo> g) => g.Key, (IGrouping<Type, UpgradeInfo> g) => g.ToList());
			int num = 0;
			foreach (Type item in SafeTypes(asm))
			{
				MethodInfo[] methods;
				try
				{
					methods = item.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
				}
				catch
				{
					continue;
				}
				if (dictionary2.TryGetValue(item, out var value) && methods.Any(IsTeamTotalName))
				{
					foreach (UpgradeInfo item2 in value)
					{
						Mark(item2, item.Name + " declares " + methods.First(IsTeamTotalName).Name + "()");
					}
				}
				MethodInfo[] array = methods;
				foreach (MethodInfo methodInfo in array)
				{
					List<KeyValuePair<OpCode, object>> list;
					try
					{
						if (methodInfo.IsAbstract || methodInfo.GetMethodBody() == null)
						{
							continue;
						}
						list = PatchProcessor.ReadMethodBody((MethodBase)methodInfo).ToList();
						num++;
						goto IL_0245;
					}
					catch
					{
					}
					continue;
					IL_0245:
					bool flag = list.Any((KeyValuePair<OpCode, object> i) => IsPlayerCollection(i.Value));
					UpgradeInfo upgradeInfo = null;
					Type type = null;
					for (int num3 = 0; num3 < list.Count; num3++)
					{
						OpCode key = list[num3].Key;
						object value2 = list[num3].Value;
						if (key == OpCodes.Ldstr && value2 is string text)
						{
							string key2 = (text.StartsWith("playerUpgrade", StringComparison.Ordinal) ? text.Substring("playerUpgrade".Length) : text);
							if (dictionary.TryGetValue(key2, out var value3))
							{
								upgradeInfo = value3;
							}
						}
						else if (value2 is FieldInfo fieldInfo && dictionary2.ContainsKey(fieldInfo.FieldType))
						{
							type = fieldInfo.FieldType;
						}
						else
						{
							if (!(value2 is MethodInfo methodInfo2))
							{
								continue;
							}
							if (IsTeamTotalName(methodInfo2))
							{
								Type type2 = (dictionary2.ContainsKey(methodInfo2.DeclaringType) ? methodInfo2.DeclaringType : type);
								if (!(type2 != null))
								{
									continue;
								}
								foreach (UpgradeInfo item3 in dictionary2[type2])
								{
									Mark(item3, item.Name + "." + methodInfo.Name + " calls " + methodInfo2.Name + "()");
								}
							}
							else if (dictionary2.ContainsKey(methodInfo2.ReturnType))
							{
								type = methodInfo2.ReturnType;
							}
							else
							{
								if (!flag || !(_repoGetLevel != null) || !(methodInfo2.DeclaringType == _repoPlayerUpgrade) || !(methodInfo2.Name == "GetLevel") || upgradeInfo == null)
								{
									continue;
								}
								int num4 = num3 + 1;
								int num5 = 0;
								for (; num4 < list.Count; num4++)
								{
									if (num5 >= 3)
									{
										break;
									}
									if (!(list[num4].Key == OpCodes.Nop))
									{
										num5++;
										if (list[num4].Key == OpCodes.Add)
										{
											Mark(upgradeInfo, item.Name + "." + methodInfo.Name + " adds up players' levels");
											break;
										}
									}
								}
							}
						}
					}
				}
			}
			Plugin.Debug($"team-pool scan of {asm.GetName().Name}: {num} methods");
		}

		internal static bool AutomaticPooled(UpgradeInfo info)
		{
			if (info.Owner?.GetName().Name == "MoreUpgrades")
			{
				if (info.Id == "Item Value")
				{
					return TeamEffectCompat.MoreValueActive;
				}
				if (info.Id == "Item Resist")
				{
					return false;
				}
			}
			return info.DetectedPooled;
		}

		private static void Mark(UpgradeInfo u, string why)
		{
			if (!u.DetectedPooled)
			{
				u.DetectedPooled = true;
				u.PooledReason = why;
			}
		}

		private static bool IsTeamTotalName(MethodInfo m)
		{
			if (m.Name.StartsWith("GetTotal", StringComparison.Ordinal))
			{
				return m.Name.EndsWith("Levels", StringComparison.Ordinal);
			}
			return false;
		}

		private static bool IsPlayerCollection(object operand)
		{
			if (operand is MethodInfo methodInfo)
			{
				if (!(methodInfo.Name == "PlayerGetAll"))
				{
					return methodInfo.Name == "get_PlayerList";
				}
				return true;
			}
			if (operand is FieldInfo fieldInfo)
			{
				if (!(fieldInfo.Name == "PlayerList"))
				{
					return fieldInfo.Name == "playerGrabbing";
				}
				return true;
			}
			return false;
		}

		private static IEnumerable<Type> SafeTypes(Assembly a)
		{
			try
			{
				return a.GetTypes();
			}
			catch (ReflectionTypeLoadException ex)
			{
				return ex.Types.Where((Type t) => t != null);
			}
		}

		public static string Strip(string key)
		{
			if (!key.StartsWith("playerUpgrade", StringComparison.Ordinal))
			{
				return key;
			}
			return key.Substring("playerUpgrade".Length);
		}

		public static string Pretty(string id)
		{
			if (string.IsNullOrEmpty(id) || id.Contains(' '))
			{
				return id;
			}
			StringBuilder stringBuilder = new StringBuilder();
			for (int i = 0; i < id.Length; i++)
			{
				if (i > 0 && char.IsUpper(id[i]) && !char.IsUpper(id[i - 1]))
				{
					stringBuilder.Append(' ');
				}
				stringBuilder.Append(id[i]);
			}
			return stringBuilder.ToString();
		}

		public static bool MatchesAny(string list, UpgradeInfo u)
		{
			if (string.IsNullOrWhiteSpace(list))
			{
				return false;
			}
			string[] array = list.Split(new char[2] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries);
			for (int i = 0; i < array.Length; i++)
			{
				if (MatchesName(array[i], u))
				{
					return true;
				}
			}
			return false;
		}

		public static bool MatchesName(string entry, UpgradeInfo u)
		{
			if (u != null)
			{
				return ShopUpgradePolicy.NameMatches(entry, u.Id, u.Key);
			}
			return false;
		}

		public static void LogCatalog()
		{
			if (ByKey.Count == 0)
			{
				return;
			}
			Plugin.Log.LogInfo((object)$"Recognized upgrade effects ({ByKey.Count}):");
			foreach (IGrouping<string, UpgradeInfo> item in from u in ByKey.Values
				group u by u.Source into g
				orderby (!(g.Key == "R.E.P.O. (vanilla)")) ? g.Key : ""
				select g)
			{
				IEnumerable<string> values = item.OrderBy((UpgradeInfo u) => u.Id).Select(delegate(UpgradeInfo u)
				{
					List<string> list = new List<string>();
					if (UpgradeOptions.Effective(u) == UpgradeHandling.Consumable)
					{
						list.Add("consumable: no highest-level refill");
					}
					if (!UpgradeOptions.SharingAllowed(u))
					{
						list.Add("sharing disabled in patch options");
					}
					if (u.Pooled)
					{
						list.Add("Team: one contribution per purchase");
					}
					int num = u.MaxLevel();
					if (num > 0 && HostRules.Bool("CapAtModMaxLevel", Plugin.CapAtModMaxLevel.Value))
					{
						list.Add($"max {num}");
					}
					int num2 = EffectCeiling.For(u);
					if (num2 > 0)
					{
						list.Add($"full effect at {num2}");
					}
					return (list.Count != 0) ? (u.DisplayName + " (" + string.Join(", ", list) + ")") : u.DisplayName;
				});
				Plugin.Log.LogInfo((object)("  [" + item.Key + "] " + string.Join(", ", values)));
			}
			foreach (UpgradeInfo item2 in ByKey.Values.Where((UpgradeInfo u) => u.Pooled && u.PooledReason != null))
			{
				Plugin.Debug(item2.Id + ": team-pooled because " + item2.PooledReason);
			}
		}
	}
	internal sealed class ChargeLedger : MonoBehaviour
	{
		private sealed class Receipt
		{
		}

		private sealed class Change
		{
			internal string Key;

			internal string Owner;

			internal int Before;

			internal bool Setter;
		}

		internal const string SaveKey = "sharedUpgradesCompatibilityChargeLedgerV1";

		private static readonly FieldInfo Dictionaries = AccessTools.Field(typeof(StatsManager), "dictionaryOfDictionaries");

		private static readonly FieldInfo Names = AccessTools.Field(typeof(StatsManager), "playerNames");

		private static readonly FieldInfo SaveReady = AccessTools.Field(typeof(StatsManager), "saveFileReady");

		private static readonly FieldInfo TogglePlayer = AccessTools.Field(typeof(ItemToggle), "playerTogglePhotonID");

		private static MethodInfo _apply;

		private static FieldInfo _registry;

		private static FieldInfo _levels;

		private static PropertyInfo _itemId;

		private static Type _itemType;

		private static ChargeLedgerModel _model;

		private static ChargeLedgerModel _remote;

		private static StatsManager _stats;

		private static object _room;

		private static int _host;

		private static bool _sessionKnown;

		private static bool _failed;

		private static bool _installed;

		private static bool _purchasePending;

		private static int _reportedEpoch;

		private static float _next;

		private static float _heartbeat;

		private static readonly Dictionary<string, int> Reported = new Dictionary<string, int>();

		private static readonly Dictionary<string, int> EarlySpend = new Dictionary<string, int>();

		private static readonly Dictionary<string, int> PendingLower = new Dictionary<string, int>();

		private static ConditionalWeakTable<Component, Receipt> Receipts = new ConditionalWeakTable<Component, Receipt>();

		internal static bool Applying { get; private set; }

		private static SortedDictionary<string, Dictionary<string, int>> Data
		{
			get
			{
				if (!((Object)(object)StatsManager.instance == (Object)null))
				{
					return Dictionaries?.GetValue(StatsManager.instance) as SortedDictionary<string, Dictionary<string, int>>;
				}
				return null;
			}
		}

		private static bool Host => SemiFunc.IsMasterClientOrSingleplayer();

		private static bool Supported
		{
			get
			{
				if (_apply != null && _registry != null && _levels != null)
				{
					return _itemId != null;
				}
				return false;
			}
		}

		private static string Pair(string key, string owner)
		{
			return key + "\n" + owner;
		}

		private static string LocalId()
		{
			PlayerAvatar val = SemiFunc.PlayerAvatarLocal();
			if (!((Object)(object)val == (Object)null))
			{
				return SemiFunc.PlayerGetSteamID(val);
			}
			return null;
		}

		private static object Upgrade(string key)
		{
			if (!(_registry?.GetValue(null) is IDictionary dictionary) || !dictionary.Contains(Catalog.Strip(key)))
			{
				return null;
			}
			return dictionary[Catalog.Strip(key)];
		}

		private static Dictionary<string, int> Levels(string key)
		{
			object obj = Upgrade(key);
			if (obj != null)
			{
				return _levels?.GetValue(obj) as Dictionary<string, int>;
			}
			return null;
		}

		private static int Current(string key, string owner)
		{
			Dictionary<string, int> dictionary = Levels(key);
			if (dictionary == null || !dictionary.TryGetValue(owner, out var value))
			{
				return 0;
			}
			return Math.Max(0, value);
		}

		internal static void Apply(Harmony harmony, Assembly repo, Assembly more = null)
		{
			//IL_02d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d8: Expected O, but got Unknown
			//IL_0317: Unknown result type (might be due to invalid IL or missing references)
			//IL_032c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0339: Expected O, but got Unknown
			//IL_0339: Expected O, but got Unknown
			//IL_0350: Unknown result type (might be due to invalid IL or missing references)
			//IL_0365: Unknown result type (might be due to invalid IL or missing references)
			//IL_0372: Expected O, but got Unknown
			//IL_0372: Expected O, but got Unknown
			//IL_0386: Unknown result type (might be due to invalid IL or missing references)
			//IL_0394: Expected O, but got Unknown
			//IL_03bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ca: Expected O, but got Unknown
			//IL_03f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0400: Expected O, but got Unknown
			//IL_0429: Unknown result type (might be due to invalid IL or missing references)
			//IL_0436: Expected O, but got Unknown
			//IL_045e: Unknown result type (might be due to invalid IL or missing references)
			//IL_046c: Expected O, but got Unknown
			//IL_02b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_02be: Expected O, but got Unknown
			if (Dictionaries?.FieldType != typeof(SortedDictionary<string, Dictionary<string, int>>) || Names?.FieldType != typeof(Dictionary<string, string>) || SaveReady?.FieldType != typeof(bool))
			{
				throw new MissingFieldException("Native ledger save contracts changed");
			}
			Type type = repo?.GetType("REPOLib.Modules.PlayerUpgrade");
			Type type2 = repo?.GetType("REPOLib.Modules.Upgrades");
			_registry = ((type2 == null) ? null : AccessTools.Field(type2, "_playerUpgrades"));
			_levels = ((type == null) ? null : AccessTools.Field(type, "PlayerDictionary"));
			_apply = ((type == null) ? null : AccessTools.Method(type, "ApplyUpgrade", new Type[2]
			{
				typeof(string),
				typeof(int)
			}, (Type[])null));
			_itemType = repo?.GetType("REPOLib.Modules.REPOLibItemUpgrade");
			_itemId = _itemType?.GetProperty("UpgradeId", BindingFlags.Instance | BindingFlags.Public);
			if (!Supported)
			{
				Plugin.Log.LogWarning((object)"Consumable ledger unavailable: verified REPOLib APIs missing; original purchase behavior retained.");
				return;
			}
			MethodInfo methodInfo = AccessTools.DeclaredMethod(_itemType, "Upgrade", Type.EmptyTypes, (Type[])null);
			MethodInfo methodInfo2 = AccessTools.DeclaredMethod(type, "SetLevel", new Type[2]
			{
				typeof(string),
				typeof(int)
			}, (Type[])null);
			MethodInfo methodInfo3 = AccessTools.DeclaredMethod(type2, "HandleUpgradeEvent", (Type[])null, (Type[])null);
			if (methodInfo == null || methodInfo2 == null || methodInfo3 == null || TogglePlayer == null || SaveReady == null)
			{
				throw new MissingMethodException("Consumable ledger origin/spending/save contract changed");
			}
			if (more != null)
			{
				MethodInfo methodInfo4 = more.GetType("MoreUpgrades.REPOLibPatches.REPOLibItemUpgradePatch")?.GetMethod("Upgrade", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
				if (methodInfo4?.ReturnType != typeof(void) || methodInfo4.GetParameters().Length != 3 || methodInfo4.GetParameters()[0].ParameterType != type || methodInfo4.GetParameters()[1].ParameterType != typeof(PlayerAvatar) || methodInfo4.GetParameters()[2].ParameterType != typeof(int))
				{
					throw new MissingMethodException("MoreUpgrades purchase adapter contract changed");
				}
				harmony.Patch((MethodBase)methodInfo4, new HarmonyMethod(typeof(ChargeLedger), "MorePurchase", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			HarmonyMethod val = new HarmonyMethod(typeof(ChargeLedger), "ItemUse", (Type[])null);
			val.priority = 800;
			val.before = new string[1] { "bulletbot.moreupgrades" };
			harmony.Patch((MethodBase)methodInfo, val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)methodInfo2, new HarmonyMethod(typeof(ChargeLedger), "BeforeChange", (Type[])null), new HarmonyMethod(typeof(ChargeLedger), "AfterChange", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)_apply, new HarmonyMethod(typeof(ChargeLedger), "BeforeChange", (Type[])null), new HarmonyMethod(typeof(ChargeLedger), "AfterChange", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)methodInfo3, new HarmonyMethod(typeof(ChargeLedger), "UpgradeEvent", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(StatsManager), "Awake", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(ChargeLedger), "RegisterSave", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(StatsManager), "LoadGame", (Type[])null, (Type[])null), new HarmonyMethod(typeof(ChargeLedger), "BeforeLoad", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(StatsManager), "ResetAllStats", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(ChargeLedger), "ResetSave", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(StatsManager), "SaveGame", (Type[])null, (Type[])null), new HarmonyMethod(typeof(ChargeLedger), "BeforeSave", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			RegisterSave();
			_installed = true;
			Plugin.Log.LogInfo((object)"Host consumable ledger ready: verified pickups grant once; each player's spent charges remain separate and save with the run.");
		}

		private static void RegisterSave()
		{
			if (Data != null && !Data.ContainsKey("sharedUpgradesCompatibilityChargeLedgerV1"))
			{
				Data.Add("sharedUpgradesCompatibilityChargeLedgerV1", new Dictionary<string, int>());
			}
		}

		private static void BeforeSave()
		{
			if (!Host || _model == null)
			{
				return;
			}
			try
			{
				KeyValuePair<string, int>[] array = PendingLower.ToArray();
				for (int i = 0; i < array.Length; i++)
				{
					KeyValuePair<string, int> keyValuePair = array[i];
					int num = keyValuePair.Key.IndexOf('\n');
					if (num >= 0)
					{
						string key = keyValuePair.Key.Substring(0, num);
						string owner = keyValuePair.Key.Substring(num + 1);
						ChargeLedgerModel.Wallet wallet = _model.Get(key, owner);
						if (wallet != null)
						{
							_model.Spend(key, owner, Math.Min(keyValuePair.Value, wallet.Issued));
						}
					}
				}
				Store();
			}
			catch (Exception exception)
			{
				Fail(exception);
			}
		}

		private static void BeforeLoad()
		{
			Clear();
			if (Data != null)
			{
				Data["sharedUpgradesCompatibilityChargeLedgerV1"] = new Dictionary<string, int>();
			}
		}

		private static void ResetSave()
		{
			Clear();
			if (Data != null)
			{
				Data["sharedUpgradesCompatibilityChargeLedgerV1"] = new Dictionary<string, int>();
			}
		}

		private static void Clear()
		{
			_model = (_remote = null);
			_reportedEpoch = 0;
			Reported.Clear();
			EarlySpend.Clear();
			PendingLower.Clear();
			Receipts = new ConditionalWeakTable<Component, Receipt>();
			_failed = (_purchasePending = false);
			_next = (_heartbeat = 0f);
		}

		private static void Session()
		{
			object obj = (PhotonNetwork.InRoom ? PhotonNetwork.CurrentRoom : null);
			int num;
			if (!PhotonNetwork.InRoom)
			{
				num = 0;
			}
			else
			{
				Player masterClient = PhotonNetwork.MasterClient;
				num = ((masterClient != null) ? masterClient.ActorNumber : 0);
			}
			int num2 = num;
			bool flag = _stats == StatsManager.instance && _room == obj;
			if (_sessionKnown && flag && _host == num2)
			{
				return;
			}
			ChargeLedgerModel chargeLedgerModel = (flag ? _remote : null);
			if (!flag)
			{
				Clear();
			}
			_stats = StatsManager.instance;
			_room = obj;
			_host = num2;
			_sessionKnown = true;
			if (Host && chargeLedgerModel != null)
			{
				Dictionary<string, int> value;
				ChargeLedgerModel ledger;
				ChargeLedgerModel chargeLedgerModel2 = ((Data != null && Data.TryGetValue("sharedUpgradesCompatibilityChargeLedgerV1", out value) && ChargeLedgerModel.Load(value, out ledger)) ? ledger : null);
				if (chargeLedgerModel2 == null || (chargeLedgerModel2.Epoch == chargeLedgerModel.Epoch && chargeLedgerModel2.Revision < chargeLedgerModel.Revision))
				{
					_model = chargeLedgerModel;
					Store();
				}
			}
			_remote = null;
			_next = (_heartbeat = 0f);
		}

		private static ChargeLedgerModel Ensure()
		{
			Session();
			if (Host && !_failed && _installed && Supported && Data != null)
			{
				object value = SaveReady.GetValue(StatsManager.instance);
				if (!(value is bool) || (bool)value)
				{
					RegisterSave();
					Dictionary<string, int> dictionary = Data["sharedUpgradesCompatibilityChargeLedgerV1"];
					if (_model != null && dictionary.TryGetValue("$epoch", out var value2) && value2 == _model.Epoch)
					{
						return _model;
					}
					if (ChargeLedgerModel.Load(dictionary, out var ledger))
					{
						_model = ledger;
						return ledger;
					}
					if (dictionary.Keys.Any((string k) => k.StartsWith("$", StringComparison.Ordinal) || k.StartsWith("g|", StringComparison.Ordinal) || k.StartsWith("i|", StringComparison.Ordinal) || k.StartsWith("u|", StringComparison.Ordinal) || k.StartsWith("s|", StringComparison.Ordinal)))
					{
						Fail(new InvalidOperationException("Stored charge ledger is invalid; preserved without rebasing spent charges"));
						return null;
					}
					_model = new ChargeLedgerModel(new Random().Next(1, int.MaxValue));
					Store();
					return _model;
				}
			}
			return null;
		}

		private static void Store()
		{
			if (_model != null && Data != null)
			{
				Data["sharedUpgradesCompatibilityChargeLedgerV1"] = _model.Save();
			}
		}

		internal static bool OwnsCandidate(string key)
		{
			try
			{
				return Candidate(key);
			}
			catch (Exception exception)
			{
				Fail(exception);
				return false;
			}
		}

		private static bool Candidate(string key)
		{
			if (!Host || _failed || !_installed || !Supported || !Plugin.TrackConsumableCharges.Value || !Catalog.TryGet(key, out var info) || info.Kind != UpgradeKind.RepoLib || UpgradeOptions.Effective(info) != UpgradeHandling.Consumable || !UpgradeOptions.Enabled(info))
			{
				return false;
			}
			return Ensure() != null;
		}

		internal static bool Owns(string key)
		{
			if (!_installed || _failed || !Supported || !ChargeLedgerModel.ValidKey(key) || !HostRules.Ready)
			{
				return false;
			}
			if (!HostRules.Remote)
			{
				return OwnsCandidate(key);
			}
			if (HostRules.TryRule(key, out var rule))
			{
				return rule.Charges;
			}
			return false;
		}

		private static int Cap(string key)
		{
			if (!Catalog.TryGet(key, out var info))
			{
				return 0;
			}
			return UpgradeOptions.ShareCap(info);
		}

		private static string[] Players(string key)
		{
			return ConnectedTeam.UpgradeIds(Levels(key));
		}

		private static void Seed(ChargeLedgerModel model, string key)
		{
			IEnumerable<string> first = ((Names?.GetValue(StatsManager.instance) is Dictionary<string, string> dictionary) ? dictionary.Keys.AsEnumerable() : Enumerable.Empty<string>());
			model.Seed(key, Levels(key), first.Concat(Players(key)));
		}

		private static bool Proof(Component component, out string key, out PlayerAvatar buyer, out PhotonView view)
		{
			key = null;
			buyer = null;
			view = null;
			if ((Object)(object)component == (Object)null || _itemId == null)
			{
				return false;
			}
			key = "playerUpgrade" + (_itemId.GetValue(component) as string);
			ItemToggle component2 = component.GetComponent<ItemToggle>();
			ItemUpgrade component3 = component.GetComponent<ItemUpgrade>();
			if ((Object)(object)component2 == (Object)null || (Object)(object)component3 == (Object)null || !component3.isPlayerUpgrade || !component2.toggleState)
			{
				return false;
			}
			buyer = SemiFunc.PlayerAvatarGetFromPhotonID((int)TogglePlayer.GetValue(component2));
			view = component.GetComponentInParent<PhotonView>();
			if ((Object)(object)buyer != (Object)null && ChargeLedgerModel.ValidOwner(SemiFunc.PlayerGetSteamID(buyer)))
			{
				if (PhotonNetwork.InRoom)
				{
					if ((Object)(object)view != (Object)null)
					{
						return view.ViewID > 0;
					}
					return false;
				}
				return true;
			}
			return false;
		}

		private static bool MorePurchase(object __0)
		{
			return !Owns(MoreInterop.UpgradeKey(__0));
		}

		private static bool ItemUse(Component __instance)
		{
			try
			{
				if (!Proof(__instance, out var key, out var buyer, out var view) || !Owns(key))
				{
					return true;
				}
				if (Host)
				{
					return !Purchase(__instance, key, buyer);
				}
				if ((Object)(object)buyer == (Object)(object)SemiFunc.PlayerAvatarLocal())
				{
					Net.SendConfig("chargebuy", new object[3]
					{
						view.ViewID,
						key,
						SemiFunc.PlayerGetSteamID(buyer)
					}, new int[1] { PhotonNetwork.MasterClient.ActorNumber });
				}
				return false;
			}
			catch (Exception exception)
			{
				Fail(exception);
				return true;
			}
		}

		private static bool Purchase(Component item, string key, PlayerAvatar buyer)
		{
			if (Receipts.TryGetValue(item, out var _))
			{
				return true;
			}
			ChargeLedgerModel chargeLedgerModel = Ensure();
			if (chargeLedgerModel == null || !OwnsCandidate(key))
			{
				return false;
			}
			Seed(chargeLedgerModel, key);
			string[] array = Players(key);
			string value2 = SemiFunc.PlayerGetSteamID(buyer);
			if (!array.Contains(value2))
			{
				return false;
			}
			chargeLedgerModel.Purchase(key, array, (string id) => Current(key, id), Cap(key), Plugin.GrantConsumablesToLateJoiners.Value);
			Receipts.Add(item, new Receipt());
			Store();
			ApplyBalances(key);
			_purchasePending = true;
			UpgradePanelRefresh.Request();
			return true;
		}

		internal static void ReceivePurchase(int sender, object raw)
		{
			if (!Host || !PhotonNetwork.InRoom || !(raw is object[] array) || array.Length != 3 || !(array[0] is int num) || num <= 0 || !(array[1] is string text) || !(array[2] is string text2))
			{
				return;
			}
			PhotonView val = PhotonView.Find(num);
			Component val2 = (((Object)(object)val == (Object)null) ? null : ((Component)val).GetComponentInChildren(_itemType));
			if (!Proof(val2, out var key, out var buyer, out var _) || key != text || SemiFunc.PlayerGetSteamID(buyer) != text2 || (Object)(object)buyer.photonView == (Object)null || buyer.photonView.OwnerActorNr != sender || !OwnsCandidate(key))
			{
				return;
			}
			try
			{
				Purchase(val2, key, buyer);
			}
			catch (Exception exception)
			{
				Fail(exception);
			}
		}

		private static bool UpgradeEvent(EventData __0)
		{
			object customData = __0.CustomData;
			Hashtable val = (Hashtable)((customData is Hashtable) ? customData : null);
			if (val != null && ((Dictionary<object, object>)(object)val).TryGetValue((object)"UpgradeId", out object value) && value is string text && ((Dictionary<object, object>)(object)val).TryGetValue((object)"SteamId", out object value2))
			{
				string owner = value2 as string;
				if (owner != null && ((Dictionary<object, object>)(object)val).TryGetValue((object)"Level", out object value3) && value3 is int num)
				{
					string key = "playerUpgrade" + text;
					if (!Owns(key))
					{
						return true;
					}
					if (!ChargeLedgerModel.ValidOwner(owner) || num < 0 || num > Current(key, owner))
					{
						return false;
					}
					if (PhotonNetwork.InRoom)
					{
						int sender = __0.Sender;
						Player masterClient = PhotonNetwork.MasterClient;
						if (sender != ((masterClient != null) ? new int?(masterClient.ActorNumber) : ((int?)null)))
						{
							return SemiFunc.PlayerGetAll().Any((PlayerAvatar p) => (Object)(object)p != (Object)null && (Object)(object)p.photonView != (Object)null && p.photonView.OwnerActorNr == __0.Sender && SemiFunc.PlayerGetSteamID(p) == owner);
						}
					}
					return true;
				}
			}
			return true;
		}

		private static void BeforeChange(object __instance, string __0, MethodBase __originalMethod, ref object __state)
		{
			__state = null;
			if (!Applying && Supported && !string.IsNullOrEmpty(__0))
			{
				string text = MoreInterop.UpgradeKey(__instance);
				if (text != null && Owns(text))
				{
					__state = new Change
					{
						Key = text,
						Owner = __0,
						Before = Current(text, __0),
						Setter = (__originalMethod.Name == "SetLevel")
					};
				}
			}
		}

		private static void AfterChange(object __state)
		{
			if (!(__state is Change change) || Applying)
			{
				return;
			}
			int num = Current(change.Key, change.Owner);
			if (num >= change.Before)
			{
				return;
			}
			string key = Pair(change.Key, change.Owner);
			UpgradePanelRefresh.Request();
			int valueOrDefault = ((Host ? _model : _remote)?.Get(change.Key, change.Owner)?.Used).GetValueOrDefault();
			PendingLower[key] = (int)Math.Min(2147483647L, (long)Math.Max(valueOrDefault, PendingLower.TryGetValue(key, out var value) ? value : 0) + (long)change.Before - num);
			if (!change.Setter || change.Owner != LocalId())
			{
				return;
			}
			try
			{
				ChargeLedgerModel.Wallet wallet = (Host ? Ensure() : _remote)?.Get(change.Key, change.Owner);
				if (wallet == null)
				{
					EarlySpend[change.Key] = (EarlySpend.TryGetValue(change.Key, out var value2) ? value2 : 0) + change.Before - num;
					return;
				}
				int num2 = (Reported.TryGetValue(change.Key, out var value3) ? value3 : wallet.Used);
				num2 = (int)Math.Min(2147483647L, (long)num2 + (long)change.Before - num);
				Reported[change.Key] = num2;
				if (Host)
				{
					AcceptSpend(change.Key, change.Owner, num2);
				}
				else
				{
					Report(change.Key, change.Owner, num2);
				}
			}
			catch (Exception exception)
			{
				Fail(exception);
			}
		}

		private static void Report(string key, string owner, int used)
		{
			if (_remote != null && PhotonNetwork.InRoom && PhotonNetwork.MasterClient != null)
			{
				Net.SendConfig("chargespent", new object[4] { _remote.Epoch, key, owner, used }, new int[1] { PhotonNetwork.MasterClient.ActorNumber });
			}
		}

		private static bool AcceptSpend(string key, string owner, int cumulative)
		{
			ChargeLedgerModel chargeLedgerModel = Ensure();
			ChargeLedgerModel.Wallet wallet = chargeLedgerModel?.Get(key, owner);
			if (wallet == null)
			{
				return false;
			}
			if (cumulative <= 0 || cumulative < wallet.Used)
			{
				return false;
			}
			PendingLower.Remove(Pair(key, owner));
			if (!chargeLedgerModel.Spend(key, owner, Math.Min(cumulative, wallet.Issued)))
			{
				return false;
			}
			Store();
			_next = 0f;
			_heartbeat = Math.Min(_heartbeat, Time.unscaledTime + 0.1f);
			UpgradePanelRefresh.Request();
			return true;
		}

		internal static void ReceiveSpend(int sender, object raw)
		{
			if (!Host || !PhotonNetwork.InRoom || !(raw is object[] array) || array.Length != 4 || !(array[0] is int num) || !(array[1] is string key))
			{
				return;
			}
			object obj = array[2];
			string owner = obj as string;
			if (owner != null && array[3] is int num2 && num2 >= 0 && OwnsCandidate(key))
			{
				ChargeLedgerModel chargeLedgerModel = Ensure();
				if (chargeLedgerModel != null && chargeLedgerModel.Epoch == num && SemiFunc.PlayerGetAll().Any((PlayerAvatar p) => (Object)(object)p != (Object)null && (Object)(object)p.photonView != (Object)null && p.photonView.OwnerActorNr == sender && SemiFunc.PlayerGetSteamID(p) == owner) && PhotonNetwork.PlayerList.Any((Player p) => p.ActorNumber == sender))
				{
					AcceptSpend(key, owner, num2);
				}
			}
		}

		private static void ApplyBalances(string changedKey = null)
		{
			ChargeLedgerModel chargeLedgerModel = (Host ? _model : _remote);
			if (chargeLedgerModel == null || !HostRules.Ready)
			{
				return;
			}
			foreach (KeyValuePair<string, ChargeLedgerModel.Upgrade> upgrade in chargeLedgerModel.Upgrades)
			{
				if ((changedKey != null && upgrade.Key != changedKey) || !Owns(upgrade.Key))
				{
					continue;
				}
				HashSet<string> hashSet = new HashSet<string>(Players(upgrade.Key), StringComparer.Ordinal);
				foreach (KeyValuePair<string, ChargeLedgerModel.Wallet> player in upgrade.Value.Players)
				{
					if (!hashSet.Contains(player.Key))
					{
						continue;
					}
					int num = player.Value.Used;
					if (player.Key == LocalId() && Reported.TryGetValue(upgrade.Key, out var value))
					{
						num = Math.Max(num, value);
					}
					string key = Pair(upgrade.Key, player.Key);
					if (PendingLower.TryGetValue(key, out var value2))
					{
						if (num >= value2)
						{
							PendingLower.Remove(key);
						}
						else
						{
							num = value2;
						}
					}
					int num2 = Math.Max(0, player.Value.Issued - num);
					int num3 = Current(upgrade.Key, player.Key);
					if (num2 == num3)
					{
						continue;
					}
					try
					{
						Applying = true;
						_apply.Invoke(Upgrade(upgrade.Key), new object[2] { player.Key, num2 });
						UpgradePanelRefresh.Request();
					}
					catch (Exception ex)
					{
						Plugin.Debug("Charge effect callback failed: " + ex.GetBaseException().Message);
					}
					finally
					{
						Applying = false;
					}
				}
			}
		}

		internal static Dictionary<string, int> Display(string owner, Dictionary<string, int> source)
		{
			ChargeLedgerModel chargeLedgerModel = (Host ? _model : _remote);
			Dictionary<string, int> dictionary = new Dictionary<string, int>(source);
			if (chargeLedgerModel != null)
			{
				foreach (KeyValuePair<string, ChargeLedgerModel.Upgrade> upgrade in chargeLedgerModel.Upgrades)
				{
					ChargeLedgerModel.Wallet wallet = chargeLedgerModel.Get(upgrade.Key, owner);
					if (wallet != null && Owns(upgrade.Key))
					{
						int num = wallet.Used;
						if (owner == LocalId() && Reported.TryGetValue(upgrade.Key, out var value))
						{
							num = Math.Max(num, value);
						}
						if (PendingLower.TryGetValue(Pair(upgrade.Key, owner), out var value2))
						{
							num = Math.Max(num, value2);
						}
						int num2 = Math.Max(0, wallet.Issued - num);
						if (num2 == 0)
						{
							dictionary.Remove(upgrade.Key);
						}
						else
						{
							dictionary[upgrade.Key] = num2;
						}
					}
				}
			}
			string[] array = (from kv in dictionary
				where kv.Value <= 0 && SyncPolicy.Consumable(kv.Key)
				select kv.Key).ToArray();
			foreach (string key in array)
			{
				dictionary.Remove(key);
			}
			return dictionary;
		}

		internal static void ReceiveState(int sender, object raw)
		{
			Session();
			if (Host || !HostRules.Ready || !PhotonNetwork.InRoom)
			{
				return;
			}
			Player masterClient = PhotonNetwork.MasterClient;
			if (masterClient == null || masterClient.ActorNumber != sender || !ChargeLedgerModel.Decode(raw, out var ledger) || (_remote != null && ledger.Epoch == _remote.Epoch && ledger.Revision < _remote.Revision))
			{
				return;
			}
			if (_reportedEpoch != ledger.Epoch)
			{
				Reported.Clear();
				if (_reportedEpoch != 0)
				{
					PendingLower.Clear();
					EarlySpend.Clear();
				}
				_reportedEpoch = ledger.Epoch;
			}
			_remote = ledger;
			string text = LocalId();
			if (!string.IsNullOrEmpty(text))
			{
				foreach (string key in ledger.Upgrades.Keys)
				{
					ChargeLedgerModel.Wallet wallet = ledger.Get(key, text);
					if (wallet != null)
					{
						if (!Reported.ContainsKey(key))
						{
							Reported[key] = wallet.Used;
						}
						if (EarlySpend.TryGetValue(key, out var value))
						{
							Reported[key] = (int)Math.Min(2147483647L, (long)Reported[key] + (long)value);
							EarlySpend.Remove(key);
							Report(key, text, Reported[key]);
						}
					}
				}
			}
			ApplyBalances();
			UpgradePanelRefresh.Request();
		}

		internal static void Send(int[] actors = null)
		{
			if (Host && _model != null && PhotonNetwork.InRoom)
			{
				Net.SendConfig("charges", _model.Packet(), actors);
			}
		}

		private void LateUpdate()
		{
			if (_purchasePending)
			{
				Session();
				if (_purchasePending && Host)
				{
					_purchasePending = false;
					Send();
					_heartbeat = Time.unscaledTime + 2f;
				}
			}
		}

		private void Update()
		{
			Session();
			if (Time.unscaledTime < _next)
			{
				return;
			}
			_next = Time.unscaledTime + 0.25f;
			try
			{
				if (Host)
				{
					ChargeLedgerModel chargeLedgerModel = Ensure();
					if (chargeLedgerModel == null)
					{
						return;
					}
					int revision = chargeLedgerModel.Revision;
					UpgradeInfo[] array = Catalog.All.ToArray();
					foreach (UpgradeInfo upgradeInfo in array)
					{
						if (OwnsCandidate(upgradeInfo.Key))
						{
							Seed(chargeLedgerModel, upgradeInfo.Key);
							string[] array2 = Players(upgradeInfo.Key);
							foreach (string owner in array2)
							{
								chargeLedgerModel.Join(upgradeInfo.Key, owner, Current(upgradeInfo.Key, owner), Cap(upgradeInfo.Key), Plugin.GrantConsumablesToLateJoiners.Value);
							}
						}
					}
					string owner2 = LocalId();
					foreach (KeyValuePair<string, int> item in Reported)
					{
						ChargeLedgerModel.Wallet wallet = chargeLedgerModel.Get(item.Key, owner2);
						if (wallet != null)
						{
							chargeLedgerModel.Spend(item.Key, owner2, Math.Min(item.Value, wallet.Issued));
						}
					}
					if (chargeLedgerModel.Revision != revision)
					{
						Store();
						UpgradePanelRefresh.Request();
					}
					ApplyBalances();
					if (!_purchasePending && (chargeLedgerModel.Revision != revision || Time.unscaledTime >= _heartbeat))
					{
						Send();
						_heartbeat = Time.unscaledTime + 2f;
					}
				}
				else
				{
					if (_remote == null)
					{
						return;
					}
					ApplyBalances();
					string owner3 = LocalId();
					if (!(Time.unscaledTime >= _heartbeat))
					{
						return;
					}
					_heartbeat = Time.unscaledTime + 2f;
					{
						foreach (KeyValuePair<string, int> item2 in Reported)
						{
							ChargeLedgerModel.Wallet wallet2 = _remote.Get(item2.Key, owner3);
							if (wallet2 != null && item2.Value > wallet2.Used)
							{
								Report(item2.Key, owner3, item2.Value);
							}
						}
						return;
					}
				}
			}
			catch (Exception exception)
			{
				Fail(exception);
			}
		}

		private static void Fail(Exception exception)
		{
			if (!_failed)
			{
				_failed = true;
				Plugin.Log.LogWarning((object)("Consumable ledger paused; original purchase handling retained and saved ledger preserved: " + exception.GetBaseException().Message));
			}
		}
	}
	internal sealed class ChargeLedgerModel
	{
		internal sealed class Wallet
		{
			internal int Issued;

			internal int Used;

			internal int Seen;

			internal int Remaining => Math.Max(0, Issued - Used);
		}

		internal sealed class Upgrade
		{
			internal int Grants;

			internal readonly Dictionary<string, Wallet> Players = new Dictionary<string, Wallet>(StringComparer.Ordinal);
		}

		internal const int MaxOwners = 64;

		internal const int MaxUpgrades = 16;

		internal readonly Dictionary<string, Upgrade> Upgrades = new Dictionary<string, Upgrade>(StringComparer.Ordinal);

		internal int Epoch;

		internal int Revision;

		internal ChargeLedgerModel(int epoch)
		{
			Epoch = epoch;
		}

		internal bool Seed(string key, IDictionary<string, int> observed, IEnumerable<string> known)
		{
			if (Upgrades.ContainsKey(key))
			{
				return false;
			}
			if (Upgrades.Count >= 16)
			{
				throw new InvalidOperationException("Charge ledger upgrade capacity reached");
			}
			Upgrade upgrade = new Upgrade();
			if (observed != null)
			{
				foreach (int value2 in observed.Values)
				{
					upgrade.Grants = Math.Max(upgrade.Grants, Math.Max(0, value2));
				}
			}
			HashSet<string> hashSet = new HashSet<string>(known ?? Enumerable.Empty<string>(), StringComparer.Ordinal);
			if (observed != null)
			{
				hashSet.UnionWith(observed.Keys);
			}
			if (hashSet.Where(ValidOwner).Concat(Upgrades.Values.SelectMany((Upgrade u) => u.Players.Keys)).Distinct<string>(StringComparer.Ordinal)
				.Count() > 64)
			{
				throw new InvalidOperationException("Charge ledger player capacity reached");
			}
			foreach (string item in hashSet.Where(ValidOwner))
			{
				if (upgrade.Players.Count >= 64)
				{
					throw new InvalidOperationException("Charge ledger player capacity reached");
				}
				int value;
				int issued = ((observed != null && observed.TryGetValue(item, out value)) ? Math.Max(0, value) : 0);
				upgrade.Players.Add(item, new Wallet
				{
					Issued = issued,
					Seen = upgrade.Grants
				});
			}
			Upgrades.Add(key, upgrade);
			Touch();
			return true;
		}

		internal Wallet Join(string key, string owner, int observed, int cap, bool historical = true)
		{
			if (!ValidOwner(owner) || !Upgrades.TryGetValue(key, out var value))
			{
				return null;
			}
			if (!value.Players.TryGetValue(owner, out var value2))
			{
				if (value.Players.Count >= 64 || Upgrades.Values.SelectMany((Upgrade u) => u.Players.Keys).Append(owner).Distinct<string>(StringComparer.Ordinal)
					.Count() > 64)
				{
					throw new InvalidOperationException("Charge ledger player capacity reached");
				}
				int val = (historical ? ((cap > 0) ? Math.Min(value.Grants, cap) : value.Grants) : 0);
				value2 = new Wallet
				{
					Issued = Math.Max(Math.Max(0, observed), val),
					Seen = value.Grants
				};
				value.Players.Add(owner, value2);
				Touch();
				return value2;
			}
			int num = Math.Max(0, value.Grants - value2.Seen);
			if (num > 0)
			{
				int val2 = (historical ? ((cap > 0) ? Math.Max(0, cap - value2.Remaining) : (int.MaxValue - value2.Issued)) : 0);
				checked
				{
					value2.Issued += Math.Min(num, Math.Min(val2, int.MaxValue - value2.Issued));
					value2.Seen = value.Grants;
					Touch();
				}
			}
			return value2;
		}

		internal void Purchase(string key, IEnumerable<string> connected, Func<string, int> observed, int cap, bool historical = true)
		{
			Upgrade upgrade = Upgrades[key];
			string[] array = connected.Where(ValidOwner).Distinct<string>(StringComparer.Ordinal).ToArray();
			string[] array2 = array;
			foreach (string text in array2)
			{
				Join(key, text, observed(text), cap, historical);
			}
			if (upgrade.Grants == int.MaxValue)
			{
				throw new InvalidOperationException("Charge grant counter overflow");
			}
			upgrade.Grants++;
			array2 = array;
			foreach (string text2 in array2)
			{
				Join(key, text2, observed(text2), cap);
			}
			Touch();
		}

		internal bool Spend(string key, string owner, int cumulative)
		{
			if (!Upgrades.TryGetValue(key, out var value) || !value.Players.TryGetValue(owner, out var value2) || cumulative <= value2.Used || cumulative > value2.Issued)
			{
				return false;
			}
			value2.Used = cumulative;
			Touch();
			return true;
		}

		internal Wallet Get(string key, string owner)
		{
			if (!Upgrades.TryGetValue(key, out var value) || !value.Players.TryGetValue(owner, out var value2))
			{
				return null;
			}
			return value2;
		}

		private void Touch()
		{
			if (Revision == int.MaxValue)
			{
				throw new InvalidOperationException("Charge revision overflow");
			}
			Revision++;
		}

		internal static bool ValidOwner(string owner)
		{
			if (!string.IsNullOrWhiteSpace(owner))
			{
				return owner.Length <= 96;
			}
			return false;
		}

		internal static bool ValidKey(string key)
		{
			if (key != null && key.StartsWith("playerUpgrade", StringComparison.Ordinal) && key.Length > 13)
			{
				return key.Length <= 128;
			}
			return false;
		}

		private static string Enc(string value)
		{
			return Convert.ToBase64String(Encoding.UTF8.GetBytes(value));
		}

		internal Dictionary<string, int> Save()
		{
			Dictionary<string, int> dictionary = new Dictionary<string, int>(StringComparer.Ordinal)
			{
				["$schema"] = 1,
				["$epoch"] = Epoch,
				["$revision"] = Revision
			};
			foreach (KeyValuePair<string, Upgrade> upgrade in Upgrades)
			{
				string text = Enc(upgrade.Key);
				dictionary["g|" + text] = upgrade.Value.Grants;
				foreach (KeyValuePair<string, Wallet> player in upgrade.Value.Players)
				{
					string text2 = text + "|" + Enc(player.Key);
					dictionary["i|" + text2] = player.Value.Issued;
					dictionary["u|" + text2] = player.Value.Used;
					dictionary["s|" + text2] = player.Value.Seen;
				}
			}
			return dictionary;
		}

		internal static bool Load(IDictionary<string, int> data, out ChargeLedgerModel ledger)
		{
			ledger = null;
			if (data == null || data.Count > 3091 || !data.TryGetValue("$schema", out var value) || value != 1 || !data.TryGetValue("$epoch", out var value2) || value2 <= 0 || !data.TryGetValue("$revision", out var value3) || value3 < 0)
			{
				return false;
			}
			try
			{
				ChargeLedgerModel chargeLedgerModel = new ChargeLedgerModel(value2)
				{
					Revision = value3
				};
				foreach (KeyValuePair<string, int> item in data.Where((KeyValuePair<string, int> kv) => kv.Key.StartsWith("g|", StringComparison.Ordinal)))
				{
					string key = Encoding.UTF8.GetString(Convert.FromBase64String(item.Key.Substring(2)));
					if (!ValidKey(key) || item.Value < 0 || chargeLedgerModel.Upgrades.Count >= 16 || chargeLedgerModel.Upgrades.ContainsKey(key))
					{
						return false;
					}
					chargeLedgerModel.Upgrades.Add(key, new Upgrade
					{
						Grants = item.Value
					});
				}
				foreach (KeyValuePair<string, int> item2 in data.Where((KeyValuePair<string, int> kv) => kv.Key.StartsWith("i|", StringComparison.Ordinal)))
				{
					string[] array = item2.Key.Split('|');
					if (array.Length != 3)
					{
						return false;
					}
					string key2 = Encoding.UTF8.GetString(Convert.FromBase64String(array[1]));
					string text = Encoding.UTF8.GetString(Convert.FromBase64String(array[2]));
					string text2 = item2.Key.Substring(2);
					if (!ValidOwner(text) || !chargeLedgerModel.Upgrades.TryGetValue(key2, out var value4) || value4.Players.Count >= 64 || !data.TryGetValue("u|" + text2, out var value5) || !data.TryGetValue("s|" + text2, out var value6) || item2.Value < 0 || value5 < 0 || value5 > item2.Value || value6 < 0 || value6 > value4.Grants)
					{
						return false;
					}
					value4.Players.Add(text, new Wallet
					{
						Issued = item2.Value,
						Used = value5,
						Seen = value6
					});
				}
				foreach (string item3 in data.Keys.Where((string k) => k.StartsWith("u|", StringComparison.Ordinal) || k.StartsWith("s|", StringComparison.Ordinal)))
				{
					if (!data.ContainsKey("i|" + item3.Substring(2)))
					{
						return false;
					}
				}
				if (chargeLedgerModel.Upgrades.Values.SelectMany((Upgrade u) => u.Players.Keys).Distinct<string>(StringComparer.Ordinal).Count() > 64)
				{
					return false;
				}
				ledger = chargeLedgerModel;
				return true;
			}
			catch (Exception ex) when (ex is FormatException || ex is ArgumentException)
			{
				return false;
			}
		}

		internal object[] Packet()
		{
			string[] array = Upgrades.Keys.OrderBy<string, string>((string k) => k, StringComparer.Ordinal).ToArray();
			string[] array2 = Upgrades.Values.SelectMany((Upgrade u) => u.Players.Keys).Distinct<string>(StringComparer.Ordinal).OrderBy<string, string>((string o) => o, StringComparer.Ordinal)
				.ToArray();
			List<int> list = new List<int>();
			List<int> list2 = new List<int>();
			List<int> list3 = new List<int>();
			List<int> list4 = new List<int>();
			List<int> list5 = new List<int>();
			for (int num = 0; num < array.Length; num++)
			{
				foreach (KeyValuePair<string, Wallet> player in Upgrades[array[num]].Players)
				{
					list.Add(num);
					list2.Add(Array.IndexOf(array2, player.Key));
					list3.Add(player.Value.Issued);
					list4.Add(player.Value.Used);
					list5.Add(player.Value.Seen);
				}
			}
			return new object[11]
			{
				1,
				Epoch,
				Revision,
				array,
				array.Select((string key) => Upgrades[key].Grants).ToArray(),
				array2,
				list.ToArray(),
				list2.ToArray(),
				list3.ToArray(),
				list4.ToArray(),
				list5.ToArray()
			};
		}

		internal static bool Decode(object raw, out ChargeLedgerModel ledger)
		{
			ledger = null;
			if (!(raw is object[] array) || array.Length != 11 || !(array[0] is int num) || num != 1 || !(array[1] is int num2) || num2 <= 0 || !(array[2] is int num3) || num3 < 0 || !(array[3] is string[] array2) || !(array[4] is int[] array3) || !(array[5] is string[] array4) || !(array[6] is int[] array5) || !(array[7] is int[] array6) || !(array[8] is int[] array7) || !(array[9] is int[] array8) || !(array[10] is int[] array9) || array2.Length > 16 || array4.Length > 64 || array3.Length != array2.Length || array5.Length > 1024 || array6.Length != array5.Length || array7.Length != array5.Length || array8.Length != array5.Length || array9.Length != array5.Length || array2.Any((string key2) => !ValidKey(key2)) || array4.Any((string owner) => !ValidOwner(owner)) || array2.Distinct<string>(StringComparer.Ordinal).Count() != array2.Length || array4.Distinct<string>(StringComparer.Ordinal).Count() != array4.Length || array3.Any((int g) => g < 0))
			{
				return false;
			}
			ChargeLedgerModel chargeLedgerModel = new ChargeLedgerModel(num2)
			{
				Revision = num3
			};
			for (int num4 = 0; num4 < array2.Length; num4++)
			{
				chargeLedgerModel.Upgrades.Add(array2[num4], new Upgrade
				{
					Grants = array3[num4]
				});
			}
			for (int num5 = 0; num5 < array5.Length; num5++)
			{
				if (array5[num5] < 0 || array5[num5] >= array2.Length || array6[num5] < 0 || array6[num5] >= array4.Length || array7[num5] < 0 || array8[num5] < 0 || array8[num5] > array7[num5] || array9[num5] < 0 || array9[num5] > array3[array5[num5]])
				{
					return false;
				}
				Upgrade upgrade = chargeLedgerModel.Upgrades[array2[array5[num5]]];
				string key = array4[array6[num5]];
				if (upgrade.Players.ContainsKey(key))
				{
					return false;
				}
				upgrade.Players.Add(key, new Wallet
				{
					Issued = array7[num5],
					Used = array8[num5],
					Seen = array9[num5]
				});
			}
			ledger = chargeLedgerModel;
			return true;
		}
	}
	internal static class ConnectedTeam
	{
		private static object _room;

		private static readonly Dictionary<int, string> Ids = new Dictionary<int, string>();

		internal static string[] UpgradeIds(Dictionary<string, int> levels)
		{
			if (!SemiFunc.IsMultiplayer())
			{
				PlayerAvatar val = SemiFunc.PlayerAvatarLocal();
				string text = (((Object)(object)val == (Object)null) ? null : SemiFunc.PlayerGetSteamID(val));
				if (!string.IsNullOrEmpty(text))
				{
					return new string[1] { text };
				}
				return Array.Empty<string>();
			}
			if (_room != PhotonNetwork.CurrentRoom)
			{
				_room = PhotonNetwork.CurrentRoom;
				Ids.Clear();
			}
			Player[] playerList = PhotonNetwork.PlayerList;
			HashSet<int> actors = new HashSet<int>(playerList.Select((Player p) => p.ActorNumber));
			int[] array = Ids.Keys.Where((int a) => !actors.Contains(a)).ToArray();
			foreach (int key in array)
			{
				Ids.Remove(key);
			}
			foreach (PlayerAvatar item in SemiFunc.PlayerGetAll())
			{
				if (!((Object)(object)item == (Object)null) && !((Object)(object)item.photonView == (Object)null) && actors.Contains(item.photonView.OwnerActorNr))
				{
					string value = SemiFunc.PlayerGetSteamID(item);
					if (!string.IsNullOrEmpty(value))
					{
						Ids[item.photonView.OwnerActorNr] = value;
					}
				}
			}
			HashSet<string> hashSet = new HashSet<string>(StringComparer.Ordinal);
			Player[] array2 = playerList;
			foreach (Player val2 in array2)
			{
				if (Ids.TryGetValue(val2.ActorNumber, out var value2))
				{
					hashSet.Add(value2);
				}
				else if (!string.IsNullOrEmpty(val2.UserId) && levels != null && levels.ContainsKey(val2.UserId))
				{
					hashSet.Add(val2.UserId);
				}
			}
			return hashSet.ToArray();
		}
	}
	internal static class EffectCeiling
	{
		private static readonly Dictionary<Type, PropertyInfo> Amounts = new Dictionary<Type, PropertyInfo>();

		private static readonly HashSet<string> Allowed = new HashSet<string>(StringComparer.Ordinal)
		{
			"nop", "ldarg.0", "ldarg.3", "dup", "pop", "br", "br.s", "brtrue", "brtrue.s", "ldc.r4",
			"conv.r4", "mul", "call", "callvirt", "ret"
		};

		internal static int For(UpgradeInfo info)
		{
			object obj = info?.Target;
			if (obj == null)
			{
				return 0;
			}
			PropertyInfo propertyInfo = AmountOf(obj.GetType());
			if (propertyInfo == null)
			{
				return 0;
			}
			try
			{
				return (propertyInfo.GetValue(obj, null) is ConfigEntry<float> val) ? ShopUpgradePolicy.FullChanceAt(val.Value) : 0;
			}
			catch
			{
				return 0;
			}
		}

		private static PropertyInfo AmountOf(Type type)
		{
			if (Amounts.TryGetValue(type, out var value))
			{
				return value;
			}
			PropertyInfo propertyInfo = null;
			try
			{
				propertyInfo = Read(type);
			}
			catch (Exception ex)
			{
				Plugin.Debug("Effect ceiling: could not read " + type.Name + ".Calculate: " + ex.GetBaseException().Message);
			}
			Amounts[type] = propertyInfo;
			return propertyInfo;
		}

		private static PropertyInfo Read(Type type)
		{
			MethodInfo methodInfo = AccessTools.DeclaredMethod(type, "Calculate", (Type[])null, (Type[])null);
			if (methodInfo == null || methodInfo.IsAbstract || methodInfo.ReturnType != typeof(float))
			{
				return null;
			}
			ParameterInfo[] parameters = methodInfo.GetParameters();
			if (parameters.Length != 3 || parameters[0].ParameterType != typeof(float) || parameters[2].ParameterType != typeof(int))
			{
				return null;
			}
			PropertyInfo propertyInfo = AccessTools.Property(type, "UpgradeAmount");
			if (propertyInfo == null || propertyInfo.PropertyType != typeof(ConfigEntry<float>) || propertyInfo.GetGetMethod(nonPublic: true) == null)
			{
				return null;
			}
			if (!(AccessTools.FirstMethod(typeof(PatchProcessor), (Func<MethodInfo, bool>)((MethodInfo m) => m.Name == "GetOriginalInstructions" && m.GetParameters().Length == 2 && !m.GetParameters()[1].ParameterType.IsByRef))?.Invoke(null, new object[2] { methodInfo, null }) is List<CodeInstruction> list))
			{
				return null;
			}
			int num = -1;
			int num2 = -1;
			int num3 = -1;
			int num4 = -1;
			int num5 = -1;
			int num6 = 0;
			int num7 = 0;
			int num8 = 0;
			int num9 = -1;
			for (int num10 = 0; num10 < list.Count; num10++)
			{
				string name = list[num10].opcode.Name;
				if (!Allowed.Contains(name))
				{
					return null;
				}
				if (name == "nop")
				{
					continue;
				}
				num9 = num10;
				if (name == "ldc.r4" && (!(list[num10].operand is float num11) || num11 != 0f))
				{
					return null;
				}
				if (name == "ldarg.3")
				{
					num7++;
					num3 = num10;
				}
				if (name == "mul")
				{
					num8++;
					num4 = num10;
				}
				if (name != "call" && name != "callvirt")
				{
					continue;
				}
				num6++;
				MethodInfo methodInfo2 = list[num10].operand as MethodInfo;
				if (methodInfo2 == null)
				{
					return null;
				}
				if (methodInfo2.Name == "get_UpgradeAmount" && methodInfo2.DeclaringType != null && methodInfo2.DeclaringType.IsAssignableFrom(type))
				{
					num = num10;
					continue;
				}
				if (methodInfo2.Name == "get_Value" && methodInfo2.DeclaringType == typeof(ConfigEntry<float>))
				{
					num2 = num10;
					continue;
				}
				if (methodInfo2.Name == "Clamp01" && methodInfo2.DeclaringType?.FullName == "UnityEngine.Mathf")
				{
					num5 = num10;
					continue;
				}
				return null;
			}
			bool flag = num6 == 3 && num7 == 1 && num8 == 1 && num >= 0 && num < num2 && num2 < num3 && num3 < num4 && num4 < num5 && num9 >= 0 && list[num9].opcode.Name == "ret" && num5 == PreviousReal(list, num9);
			if (flag)
			{
				Plugin.Debug("Effect ceiling: " + type.Name + " is a chance of " + propertyInfo.Name + " × level, so the shop also stops where it reaches 100%.");
			}
			if (!flag)
			{
				return null;
			}
			return propertyInfo;
		}

		private static int PreviousReal(List<CodeInstruction> code, int index)
		{
			for (int num = index - 1; num >= 0; num--)
			{
				if (code[num].opcode.Name != "nop")
				{
					return num;
				}
			}
			return -1;
		}
	}
	internal static class GroupedDisplayPolicy
	{
		internal sealed class Text
		{
			internal string Names;

			internal string Numbers;

			internal int Rows;
		}

		internal sealed class Layout
		{
			internal string Text;

			internal int Rows;

			internal float Width;
		}

		private sealed class Section
		{
			internal string Title;

			internal readonly List<KeyValuePair<string, string>> Entries = new List<KeyValuePair<string, string>>();
		}

		private const string Indent = "<space=0.7em>";

		private const float EntryIndent = 0.4f;

		private const float CountGap = 0.45f;

		private const float ColumnGap = 1f;

		internal static Layout Arrange(string names, string numbers, int columns, string countColor, Func<string, float> em)
		{
			List<Section> list = Parse(names, numbers);
			float num = 0f;
			float num2 = 0f;
			float[] array = new float[columns];
			int num3 = 0;
			foreach (Section item in list)
			{
				if (item.Title != null)
				{
					num2 = Math.Max(num2, em(item.Title));
				}
				int num4 = (item.Entries.Count + columns - 1) / columns;
				for (int i = 0; i < item.Entries.Count; i++)
				{
					num = Math.Max(num, em(item.Entries[i].Value));
					array[i / num4] = Math.Max(array[i / num4], em(item.Entries[i].Key));
				}
			}
			float num5 = (list.Any((Section s) => s.Title != null) ? 0.4f : 0f);
			float num6 = num5 + num + 0.45f;
			float[] array2 = new float[columns];
			float num7 = 0f;
			for (int num8 = 0; num8 < columns; num8++)
			{
				array2[num8] = ((num8 == 0) ? 0f : (num7 + 1f));
				num7 = array2[num8] + ((array[num8] > 0f) ? (num6 + array[num8]) : 0f);
				if (num8 == 0)
				{
					num7 = Math.Max(num7, num2);
				}
			}
			StringBuilder stringBuilder = new StringBuilder();
			foreach (Section item2 in list)
			{
				if (item2.Title != null)
				{
					stringBuilder.Append(item2.Title).Append('\n');
					num3++;
				}
				int num9 = (item2.Entries.Count + columns - 1) / columns;
				int num10 = 0;
				while (num10 < num9)
				{
					for (int num11 = 0; num11 < columns; num11++)
					{
						int num12 = num10 + num11 * num9;
						if (num12 < item2.Entries.Count)
						{
							KeyValuePair<string, string> keyValuePair = item2.Entries[num12];
							stringBuilder.Append("<pos=").Append(Em(array2[num11] + num5)).Append("><color=#")
								.Append(countColor)
								.Append('>')
								.Append(keyValuePair.Value)
								.Append("</color><pos=")
								.Append(Em(array2[num11] + num6))
								.Append('>')
								.Append(keyValuePair.Key);
						}
					}
					stringBuilder.Append('\n');
					num10++;
					num3++;
				}
			}
			return new Layout
			{
				Text = stringBuilder.ToString(),
				Rows = num3,
				Width = num7
			};
		}

		internal static float HiddenX(float nativeX, float screenLeft, float textLeft, float width, float margin)
		{
			float num = screenLeft - margin - textLeft - width;
			if (!float.IsNaN(num) && !float.IsInfinity(num))
			{
				return Math.Min(nativeX, num);
			}
			return nativeX;
		}

		internal static float ShownX(float nativeX, float screenLeft, float textLeft, float margin)
		{
			float num = screenLeft + margin - textLeft;
			if (!float.IsNaN(num) && !float.IsInfinity(num))
			{
				return Math.Min(nativeX, num);
			}
			return nativeX;
		}

		internal static string[] SharedNames(IDictionary<string, int> levels, Func<string, string> displayName)
		{
			return (from g in levels.Where((KeyValuePair<string, int> kv) => kv.Value > 0).GroupBy<KeyValuePair<string, int>, string>((KeyValuePair<string, int> kv) => Label(displayName(kv.Key) ?? kv.Key), StringComparer.OrdinalIgnoreCase)
				where g.Count() > 1
				select g.Key + ": " + string.Join(", ", from kv in g.OrderBy<KeyValuePair<string, int>, string>((KeyValuePair<string, int> kv) => kv.Key, StringComparer.Ordinal)
					select "\"" + kv.Key + "\"=" + kv.Value)).ToArray();
		}

		private static string Label(string name)
		{
			if (!name.EndsWith(" (Team)", StringComparison.Ordinal))
			{
				return name;
			}
			return name.Substring(0, name.Length - 7);
		}

		private static string Em(float value)
		{
			return value.ToString("0.##", CultureInfo.InvariantCulture) + "em";
		}

		private static List<Section> Parse(string names, string numbers)
		{
			List<Section> list = new List<Section>();
			string[] array = (names ?? "").Split('\n');
			string[] array2 = (numbers ?? "").Split('\n');
			for (int i = 0; i < array.Length; i++)
			{
				string text = array[i];
				string text2 = ((i < array2.Length) ? array2[i] : "");
				if (text.Length == 0)
				{
					continue;
				}
				if (text2.Length == 0)
				{
					list.Add(new Section
					{
						Title = text
					});
					continue;
				}
				if (list.Count == 0)
				{
					list.Add(new Section());
				}
				if (text.StartsWith("<space=0.7em>", StringComparison.Ordinal))
				{
					text = text.Substring("<space=0.7em>".Length);
				}
				list[list.Count - 1].Entries.Add(new KeyValuePair<string, string>(text, text2));
			}
			return list;
		}

		internal static Text Build(IDictionary<string, int> levels, Func<string, string> displayName, Func<string, bool> external, Func<string, bool> oneTime = null)
		{
			StringBuilder stringBuilder = new StringBuilder();
			StringBuilder stringBuilder2 = new StringBuilder();
			int num = 0;
			var source = levels.Where((KeyValuePair<string, int> kv) => kv.Value > 0).Take(256).Select(delegate(KeyValuePair<string, int> kv)
			{
				string key = kv.Key;
				int value = kv.Value;
				string name = displayName(kv.Key) ?? kv.Key;
				Func<string, bool> func = oneTime;
				return new
				{
					Key = key,
					Count = value,
					Name = name,
					Section = ((func == null || !func(kv.Key)) ? (external(kv.Key) ? 1 : 2) : 0)
				};
			})
				.ToArray();
			int[] array = new int[3] { 0, 1, 2 };
			foreach (int section in array)
			{
				var array2 = source.Where(e => e.Section == section).OrderBy(e => e.Name, StringComparer.OrdinalIgnoreCase).ThenBy(e => e.Key, StringComparer.Ordinal)
					.ToArray();
				if (array2.Length == 0)
				{
					continue;
				}
				stringBuilder.Append("<b>").Append((section == 0) ? "One-Time Use" : ((section == 1) ? "External Map" : "Personal")).Append("</b>\n");
				stringBuilder2.Append('\n');
				num++;
				var array3 = array2;
				foreach (var anon in array3)
				{
					string text = anon.Name;
					if (section == 1 && text.EndsWith(" (Team)", StringComparison.Ordinal))
					{
						text = text.Substring(0, text.Length - 7);
					}
					stringBuilder.Append("<space=0.7em>").Append(text).Append("\n");
					stringBuilder2.Append("<b>").Append(anon.Count).Append("</b>\n");
					num++;
				}
			}
			return new Text
			{
				Names = stringBuilder.ToString(),
				Numbers = stringBuilder2.ToString(),
				Rows = num
			};
		}
	}
	internal static class GroupedUpgradePanel
	{
		private sealed class Defaults
		{
			internal float NameSize;

			internal float NumberSize;

			internal float NameSpacing;

			internal float NumberSpacing;

			internal bool NameAuto;

			internal bool NumberAuto;

			internal bool Touched;

			internal TextWrappingModes NameWrap;

			internal TextWrappingModes NumberWrap;

			internal VerticalAlignmentOptions NameVertical;

			internal Color NumberColor;

			internal float AreaWidth = float.PositiveInfinity;

			internal float AreaHeight = float.PositiveInfinity;

			internal float LayoutSize;

			internal float LayoutWidth;

			internal float ScreenLeft = float.NaN;

			internal float LeftEdge;

			internal float TextLeft;

			internal float Scale;

			internal float NativeHideX;

			internal float NativeShowX;

			internal float NativeHeaderX;

			internal float NativeShowY;

			internal float RaisedShowY;

			internal int Columns;

			internal string SingleNames;

			internal string SingleNumbers;

			internal string LayoutKey;

			internal string LayoutText;

			internal string RenderedNames;
		}

		private const string FitterGuid = "DarkSpider90.TextUpgradesUIScale";

		private const float BottomMargin = 36f;

		private const float RightLimit = 0.65f;

		private const float HideMargin = 24f;

		private const float LeftMargin = 5.25f;

		private static FieldRef<StatsUI, TextMeshProUGUI> _names;

		private static FieldRef<StatsUI, TextMeshProUGUI> _numbers;

		private static FieldRef<StatsUI, TextMeshProUGUI> _header;

		private static FieldRef<SemiUI, Vector2> _hideCurrent;

		private static readonly HashSet<string> ReportedNames = new HashSet<string>();

		private static Func<string, string> _name;

		private static Action<StatsUI> _fetch;

		private static PropertyInfo _otherEnabled;

		private static readonly ConditionalWeakTable<StatsUI, Defaults> Original = new ConditionalWeakTable<StatsUI, Defaults>();

		private static bool _ready;

		private static bool _warned;

		internal static void Apply(Harmony harmony)
		{
			//IL_00fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_010a: Expected O, but got Unknown
			//IL_0133: Unknown result type (might be due to invalid IL or missing references)
			//IL_0140: Expected O, but got Unknown
			//IL_0153: Unknown result type (might be due to invalid IL or missing references)
			//IL_0168: Unknown result type (might be due to invalid IL or missing references)
			//IL_016e: Expected O, but got Unknown
			//IL_0196: Expected O, but got Unknown
			//IL_01aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b0: Expected O, but got Unknown
			try
			{
				_names = AccessTools.FieldRefAccess<StatsUI, TextMeshProUGUI>("Text");
				_numbers = AccessTools.FieldRefAccess<StatsUI, TextMeshProUGUI>("textNumbers");
				_header = AccessTools.FieldRefAccess<StatsUI, TextMeshProUGUI>("upgradesHeader");
				_hideCurrent = AccessTools.FieldRefAccess<SemiUI, Vector2>("hidePositionCurrent");
				MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(StatsUI), "Fetch", Type.EmptyTypes, (Type[])null);
				_fetch = AccessTools.MethodDelegate<Action<StatsUI>>(methodInfo, (object)null, true);
				_name = AccessTools.MethodDelegate<Func<string, string>>(AccessTools.DeclaredMethod(typeof(StatsUI), "GetUpgradeDisplayName", new Type[1] { typeof(string) }, (Type[])null), (object)null, true);
				if (Chainloader.PluginInfos.TryGetValue("DarkSpider90.TextUpgradesUIScale", out var value) && (Object)(object)value.Instance != (Object)null)
				{
					_otherEnabled = ((object)value.Instance).GetType().GetProperty("ModEnabled", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
				}
				harmony.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(StatsUI), "Start", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(GroupedUpgradePanel), "Capture", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				harmony.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(EnergyUI), "Start", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(GroupedUpgradePanel), "CaptureStamina", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				HarmonyMethod val = new HarmonyMethod(typeof(GroupedUpgradePanel), "Prepare", (Type[])null);
				HarmonyMethod val2 = new HarmonyMethod(typeof(GroupedUpgradePanel), "Render", (Type[])null);
				val2.priority = 800;
				val2.before = new string[1] { "DarkSpider90.TextUpgradesUIScale" };
				harmony.Patch((MethodBase)methodInfo, val, val2, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				val2 = new HarmonyMethod(typeof(GroupedUpgradePanel), "Fit", (Type[])null);
				val2.priority = 0;
				val2.after = new string[1] { "DarkSpider90.TextUpgradesUIScale" };
				harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, val2, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				_ready = true;
				Plugin.Log.LogInfo((object)"Grouped upgrade panel ready: keep the original font size; use two columns when one would not fit. TextUpgradesUIScale may remain enabled.");
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Grouped upgrade panel unavailable; native panel retained: " + ex.GetBaseException().Message));
			}
		}

		private static Defaults Get(StatsUI panel)
		{
			//IL_008e: 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)
			//IL_009a: 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_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: 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_0125: Unknown result type (might be due to invalid IL or missing references)
			if (Original.TryGetValue(panel, out var value))
			{
				return value;
			}
			TextMeshProUGUI val = _names.Invoke(panel);
			TextMeshProUGUI val2 = _numbers.Invoke(panel);
			if ((Object)(object)val == (Object)null || (Object)(object)val2 == (Object)null)
			{
				return null;
			}
			value = new Defaults
			{
				NameSize = ((TMP_Text)val).fontSize,
				NumberSize = ((TMP_Text)val2).fontSize,
				NameSpacing = ((TMP_Text)val).lineSpacing,
				NumberSpacing = ((TMP_Text)val2).lineSpacing,
				NameAuto = ((TMP_Text)val).enableAutoSizing,
				NumberAuto = ((TMP_Text)val2).enableAutoSizing,
				NameWrap = ((TMP_Text)val).textWrappingMode,
				NumberWrap = ((TMP_Text)val2).textWrappingMode,
				NameVertical = ((TMP_Text)val).verticalAlignment,
				NumberColor = ((Graphic)val2).color,
				NativeHideX = ((SemiUI)panel).hidePosition.x,
				NativeShowX = ((SemiUI)panel).showPosition.x,
				NativeShowY = ((SemiUI)panel).showPosition.y,
				RaisedShowY = ((SemiUI)panel).showPosition.y
			};
			TextMeshProUGUI obj = _header.Invoke(panel);
			RectTransform val3 = ((obj != null) ? ((TMP_Text)obj).rectTransform : null);
			if ((Object)(object)val3 != (Object)null)
			{
				value.NativeHeaderX = val3.anchoredPosition.x;
			}
			MeasureArea(panel, value, ((TMP_Text)val).rectTransform);
			Original.Add(panel, value);
			return value;
		}

		private static void MeasureArea(StatsUI panel, Defaults saved, RectTransform rect)
		{
			//IL_000d: 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_0030: 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_0037: 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_00b2: 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_011f: 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_012f: 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_0160: Unknown result type (might be due to invalid IL or missing references)
			//IL_0165: 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)
			Transform parent = ((Transform)rect).parent;
			RectTransform val = (RectTransform)(object)((parent is RectTransform) ? parent : null);
			float x = ((Transform)rect).localScale.x;
			if ((Object)(object)val == (Object)null || x <= 0f)
			{
				return;
			}
			Rect rect2 = val.rect;
			Rect rect3 = rect.rect;
			Vector2 val2 = default(Vector2);
			((Vector2)(ref val2))..ctor(saved.NativeShowX, saved.NativeShowY);
			saved.ScreenLeft = ScreenLeft(val, ((Rect)(ref rect2)).xMin);
			saved.TextLeft = ((Rect)(ref rect3)).xMin * x;
			saved.Scale = x;
			TextMeshProUGUI obj = _header.Invoke(panel);
			RectTransform val3 = ((obj != null) ? ((TMP_Text)obj).rectTransform : null);
			Rect rect4;
			float leftEdge;
			if (!((Object)(object)val3 == (Object)null))
			{
				float textLeft = saved.TextLeft;
				float x2 = ((Transform)val3).localPosition.x;
				rect4 = val3.rect;
				leftEdge = Math.Min(textLeft, (x2 + ((Rect)(ref rect4)).xMin) * x);
			}
			else
			{
				leftEdge = saved.TextLeft;
			}
			saved.LeftEdge = leftEdge;
			EnergyUI instance = EnergyUI.instance;
			RectTransform val4 = (RectTransform)(((Object)(object)instance != (Object)null) ? /*isinst with value type is only supported in some contexts*/: null);
			if ((Object)(object)val4 != (Object)null && (Object)(object)((Transform)val4).parent == (Object)(object)val)
			{
				float y = ((SemiUI)instance).showPosition.y;
				rect4 = val4.rect;
				float num = y + ((Rect)(ref rect4)).yMin * ((Transform)val4).localScale.y;
				float num2 = ((Rect)(ref rect3)).yMax * x;
				if ((Object)(object)val3 != (Object)null)
				{
					float val5 = num2;
					float y2 = ((Transform)val3).localPosition.y;
					rect4 = val3.rect;
					num2 = Math.Max(val5, (y2 + ((Rect)(ref rect4)).yMax * ((Transform)val3).localScale.y) * x);
				}
				float num3 = num - 6f - num2;
				if (Finite(num3) && num3 < ((Rect)(ref rect2)).yMax && num3 > ((Rect)(ref rect2)).yMin)
				{
					saved.RaisedShowY = Math.Max(saved.NativeShowY, num3);
				}
			}
			float num4 = (((Rect)(ref rect2)).xMin + ((Rect)(ref rect2)).width * 0.65f - (val2.x + ((Rect)(ref rect3)).xMin * x)) / x;
			float num5 = (saved.RaisedShowY + ((Rect)(ref rect3)).yMax * x - ((Rect)(ref rect2)).yMin - 36f) / x;
			if (Finite(num4) && Finite(num5) && num4 > 0f && num5 > 0f)
			{
				saved.AreaWidth = num4;
				saved.AreaHeight = num5;
			}
		}

		private static float ScreenLeft(RectTransform hud, float fallback)
		{
			//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)
			Transform parent = ((Transform)hud).parent;
			RectTransform val = (RectTransform)(object)((parent is RectTransform) ? parent : null);
			if (val == null)
			{
				return fallback;
			}
			Vector3[] array = (Vector3[])(object)new Vector3[4];
			val.GetWorldCorners(array);
			float x = ((Transform)hud).InverseTransformPoint(array[0]).x;
			if (!Finite(x))
			{
				return fallback;
			}
			return Math.Min(x, fallback);
		}

		private static void Capture(StatsUI __instance)
		{
			if (_names != null)
			{
				Get(__instance);
			}
		}

		private static void CaptureStamina()
		{
			StatsUI instance = StatsUI.instance;
			if (_names != null && !((Object)(object)instance == (Object)null) && Original.TryGetValue(instance, out var value))
			{
				MeasureArea(instance, value, ((TMP_Text)_names.Invoke(instance)).rectTransform);
				value.LayoutKey = null;
			}
		}

		private static void Prepare(StatsUI __instance)
		{
			//IL_006c: 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)
			if (!_ready)
			{
				return;
			}
			try
			{
				Defaults defaults = Get(__instance);
				if (defaults != null)
				{
					TextMeshProUGUI val = _names.Invoke(__instance);
					TextMeshProUGUI val2 = _numbers.Invoke(__instance);
					if (defaults.Touched)
					{
						((TMP_Text)val).fontSize = defaults.NameSize;
						((TMP_Text)val2).fontSize = defaults.NumberSize;
						((TMP_Text)val).enableAutoSizing = defaults.NameAuto;
						((TMP_Text)val2).enableAutoSizing = defaults.NumberAuto;
						((TMP_Text)val).textWrappingMode = defaults.NameWrap;
						((TMP_Text)val2).textWrappingMode = defaults.NumberWrap;
						((TMP_Text)val).lineSpacing = defaults.NameSpacing;
						((TMP_Text)val2).lineSpacing = defaults.NumberSpacing;
					}
				}
			}
			catch (Exception e)
			{
				Warn(e);
			}
		}

		private static void Render(StatsUI __instance)
		{
			if (!_ready)
			{
				return;
			}
			try
			{
				Defaults defaults = Get(__instance);
				if (defaults == null)
				{
					return;
				}
				TextMeshProUGUI val = _names.Invoke(__instance);
				TextMeshProUGUI val2 = _numbers.Invoke(__instance);
				defaults.SingleNames = ((TMP_Text)val).text;
				defaults.SingleNumbers = ((TMP_Text)val2).text;
				if (!HostRules.Ready || !HostRules.Bool("ShowTeamPooledLevels", Plugin.ShowTeamPooledLevels.Value) || (Object)(object)StatsManager.instance == (Object)null)
				{
					return;
				}
				PlayerAvatar val3 = SemiFunc.PlayerAvatarLocal();
				if (!((Object)(object)val3 == (Object)null))
				{
					Dictionary<string, int> levels = TeamUpgradeDisplay.FetchForDisplay(StatsManager.instance, SemiFunc.PlayerGetSteamID(val3));
					UpgradeInfo info;
					GroupedDisplayPolicy.Text text = GroupedDisplayPolicy.Build(levels, _name, (string key) => Catalog.TryGet(key, out info) && info.Pooled, (string key) => SyncPolicy.Normalize(Catalog.Strip(key)) == "extralife");
					((TMP_Text)val).text = text.Names;
					((TMP_Text)val2).text = text.Numbers;
					if (text.Names != defaults.RenderedNames)
					{
						defaults.RenderedNames = text.Names;
						ReportSharedNames(levels);
					}
					defaults.SingleNames = ((TMP_Text)val).text;
					defaults.SingleNumbers = ((TMP_Text)val2).text;
					((Behaviour)_header.Invoke(__instance)).enabled = text.Rows > 0;
					if ((Object)(object)__instance.scanlineObject != (Object)null)
					{
						__instance.scanlineObject.SetActive(text.Rows > 0);
					}
				}
			}
			catch (Exception e)
			{
				Warn(e);
			}
		}

		private static void ReportSharedNames(IDictionary<string, int> levels)
		{
			string[] array = GroupedDisplayPolicy.SharedNames(levels, _name);
			foreach (string text in array)
			{
				if (ReportedNames.Add(text))
				{
					Plugin.Log.LogWarning((object)("Two upgrade rows share a name, so they are separate saved upgrades. " + text));
				}
			}
		}

		private static bool OtherFitterEnabled()
		{
			object? obj = _otherEnabled?.GetValue(null);
			ConfigEntryBase val = (ConfigEntryBase)((obj is ConfigEntryBase) ? obj : null);
			bool flag = default(bool);
			int num;
			if (val != null)
			{
				object boxedValue = val.BoxedValue;
				if (boxedValue is bool)
				{
					flag = (bool)boxedValue;
					num = 1;
				}
				else
				{
					num = 0;
				}
			}
			else
			{
				num = 0;
			}
			return (byte)((uint)num & (flag ? 1u : 0u)) != 0;
		}

		private static void Fit(StatsUI __instance)
		{
			//IL_0095: 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_00d0: Unknown result type (might be due to invalid IL or missing references)
			if (!_ready)
			{
				return;
			}
			try
			{
				Defaults defaults = Get(__instance);
				if (defaults == null)
				{
					return;
				}
				TextMeshProUGUI val = _names.Invoke(__instance);
				TextMeshProUGUI val2 = _numbers.Invoke(__instance);
				bool flag = OtherFitterEnabled();
				if (!HostRules.Ready || !HostRules.Bool("FitUpgradePanel", Plugin.FitUpgradePanel.Value))
				{
					if (defaults.Touched && !flag)
					{
						((TMP_Text)val).fontSize = defaults.NameSize;
						((TMP_Text)val2).fontSize = defaults.NumberSize;
						((TMP_Text)val).enableAutoSizing = defaults.NameAuto;
						((TMP_Text)val2).enableAutoSizing = defaults.NumberAuto;
						((TMP_Text)val).textWrappingMode = defaults.NameWrap;
						((TMP_Text)val2).textWrappingMode = defaults.NumberWrap;
						((TMP_Text)val).lineSpacing = defaults.NameSpacing;
						((TMP_Text)val2).lineSpacing = defaults.NumberSpacing;
					}
					if (defaults.Touched)
					{
						if (!flag)
						{
							((TMP_Text)val).verticalAlignment = defaults.NameVertical;
						}
						Land(__instance, defaults.NativeShowX, defaults.NativeShowY);
						Align(__instance, defaults, withRows: false);
						Park(__instance, defaults.NativeHideX);
						defaults.LayoutKey = null;
					}
					defaults.Touched = false;
					return;
				}
				((TMP_Text)val).enableAutoSizing = false;
				((TMP_Text)val).textWrappingMode = (TextWrappingModes)0;
				((TMP_Text)val).verticalAlignment = (VerticalAlignmentOptions)256;
				((TMP_Text)val).lineSpacing = defaults.NameSpacing;
				string text = defaults.SingleNames + "\0" + defaults.SingleNumbers;
				if (text != defaults.LayoutKey)
				{
					Arrange(defaults, val);
					defaults.LayoutKey = text;
					Land(__instance, (defaults.Columns > 1) ? GroupedDisplayPolicy.ShownX(defaults.NativeShowX, defaults.ScreenLeft, defaults.TextLeft, 5.25f) : defaults.NativeShowX, defaults.RaisedShowY);
					Align(__instance, defaults, ((SemiUI)__instance).showPosition.x < defaults.NativeShowX);
					Park(__instance, GroupedDisplayPolicy.HiddenX(defaults.NativeHideX, defaults.ScreenLeft, defaults.TextLeft, defaults.LayoutWidth * defaults.Scale, 24f));
					if (defaults.Columns > 1)
					{
						Plugin.Log.LogInfo((object)$"Two-column upgrade list: lands at {((SemiUI)__instance).showPosition.x:0.#} (native {defaults.NativeShowX:0.#}), screen left {defaults.ScreenLeft:0.#}, width {defaults.LayoutWidth * defaults.Scale:0.#}, font {defaults.LayoutSize:0.#}.");
					}
				}
				((TMP_Text)val).text = defaults.LayoutText;
				((TMP_Text)val2).text = "";
				((TMP_Text)val).fontSize = defaults.LayoutSize;
				defaults.Touched = true;
			}
			catch (Exception e)
			{
				Warn(e);
			}
		}

		private static void Arrange(Defaults saved, TextMeshProUGUI names)
		{
			//IL_0081: 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_00e2: Unknown result type (might be due to invalid IL or missing references)
			float font = Math.Min(saved.NameSize, saved.NumberSize);
			if (!Finite(font) || font < 1f)
			{
				font = 16f;
			}
			((TMP_Text)names).fontSize = font;
			float row = (((TMP_Text)names).GetPreferredValues("X\nX", float.PositiveInfinity, float.PositiveInfinity).y - ((TMP_Text)names).GetPreferredValues("X", float.PositiveInfinity, float.PositiveInfinity).y) / font;
			if (!Finite(row) || row <= 0f)
			{
				row = 1f;
			}
			string countColor = ColorUtility.ToHtmlStringRGB(saved.NumberColor);
			GroupedDisplayPolicy.Layout layout = GroupedDisplayPolicy.Arrange(saved.SingleNames, saved.SingleNumbers, 1, countColor, Em);
			float num = Size(layout);
			int columns = 1;
			if (num < font)
			{
				GroupedDisplayPolicy.Layout layout2 = GroupedDisplayPolicy.Arrange(saved.SingleNames, saved.SingleNumbers, 2, countColor, Em);
				float num2 = Size(layout2);
				if (num2 > num)
				{
					layout = layout2;
					num = num2;
					columns = 2;
				}
			}
			saved.LayoutText = layout.Text;
			saved.LayoutSize = num;
			saved.LayoutWidth = layout.Width * num;
			saved.Columns = columns;
			float Em(string value)
			{
				//IL_0011: Unknown result type (might be due to invalid IL or missing references)
				return ((TMP_Text)names).GetPreferredValues(value, float.PositiveInfinity, float.PositiveInfinity).x / font;
			}
			float Size(GroupedDisplayPolicy.Layout layout3)
			{
				return Math.Max(1f, Math.Min(font, Math.Min(saved.AreaWidth / Math.Max(0.01f, layout3.Width), saved.AreaHeight / Math.Max(0.01f, (float)layout3.Rows * row))));
			}
		}

		private static void Land(StatsUI panel, float x, float y)
		{
			//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_0007: 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)
			//IL_002a: 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_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: 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)
			//IL_003f: 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)
			//IL_005c: 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_006f: Unknown result type (might be due to invalid IL or missing references)
			Vector2 showPosition = ((SemiUI)panel).showPosition;
			if (showPosition.x != x || showPosition.y != y)
			{
				Vector2 val = _hideCurrent.Invoke((SemiUI)(object)panel);
				bool num = val.x == showPosition.x && val.y == showPosition.y;
				showPosition.x = x;
				showPosition.y = y;
				((SemiUI)panel).showPosition = showPosition;
				if (num)
				{
					_hideCurrent.Invoke((SemiUI)(object)panel) = showPosition;
				}
			}
		}

		private static void Align(StatsUI panel, Defaults saved, bool withRows)
		{
			//IL_0031: 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_0064: Unknown result type (might be due to invalid IL or missing references)
			TextMeshProUGUI obj = _header.Invoke(panel);
			RectTransform val = ((obj != null) ? ((TMP_Text)obj).rectTransform : null);
			if (!((Object)(object)val == (Object)null) && !(saved.Scale <= 0f))
			{
				Vector2 anchoredPosition = val.anchoredPosition;
				anchoredPosition.x = saved.NativeHeaderX + (withRows ? ((saved.TextLeft - saved.LeftEdge) / saved.Scale) : 0f);
				val.anchoredPosition = anchoredPosition;
			}
		}

		private static void Park(StatsUI panel, float x)
		{
			//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_0007: 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_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_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: 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_004a: 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_005d: 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)
			Vector2 hidePosition = ((SemiUI)panel).hidePosition;
			if (hidePosition.x != x)
			{
				Vector2 val = _hideCurrent.Invoke((SemiUI)(object)panel);
				bool num = val.x == hidePosition.x && val.y == hidePosition.y;
				hidePosition.x = x;
				((SemiUI)panel).hidePosition = hidePosition;
				if (num)
				{
					_hideCurrent.Invoke((SemiUI)(object)panel) = hidePosition;
				}
			}
		}

		private static bool Finite(float value)
		{
			if (!float.IsNaN(value))
			{
				return !float.IsInfinity(value);
			}
			return false;
		}

		internal static void Refresh()
		{
			if (_ready && (Object)(object)StatsUI.instance != (Object)null)
			{
				_fetch(StatsUI.instance);
			}
		}

		private static void Warn(Exception e)
		{
			if (!_warned)
			{
				_warned = true;
				Plugin.Log.LogWarning((object)("Upgrade panel layout retained its last valid state: " + e.GetBaseException().Message));
			}
		}
	}
	internal sealed class UpgradePanelRefresh : MonoBehaviour
	{
		private static bool _pending;

		internal static void Request()
		{
			_pending = true;
		}

		private void LateUpdate()
		{
			if (!_pending)
			{
				return;
			}
			_pending = false;
			try
			{
				GroupedUpgradePanel.Refresh();
			}
			catch (Exception ex)
			{
				Plugin.Debug("Upgrade panel refresh deferred: " + ex.GetBaseException().Message);
			}
		}
	}
	internal sealed class HighestSync : MonoBehaviour
	{
		private sealed class PeerReport
		{
			internal string Owner;

			internal readonly Dictionary<string, int> Levels = new Dictionary<string, int>(StringComparer.Ordinal);
		}

		private const float HeartbeatSeconds = 5f;

		private const int MaxPlayers = 32;

		private static readonly FieldInfo StatsDictionaries = AccessTools.Field(typeof(StatsManager), "dictionaryOfDictionaries");

		private static readonly Dictionary<int, PeerReport> Reports = new Dictionary<int, PeerReport>();

		private static readonly Dictionary<string, int> Targets = new Dictionary<string, int>(StringComparer.Ordinal);

		private static readonly HashSet<string> Dirty = new HashSet<string>(StringComparer.Ordinal);

		private static readonly HashSet<string> Warned = new HashSet<string>(StringComparer.Ordinal);

		private static string[] _owners = Array.Empty<string>();

		private static Dictionary<string, int> _remoteTargets;

		private static Dictionary<string, Dictionary<string, int>> _remotePersonal;

		private static string[] _remoteOwners = Array.Empty<string>();

		private static float _nextCheck;

		private static float _nextHeartbeat;

		private static bool _purchased;

		internal static bool Applying { get; private set; }

		private static SortedDictionary<string, Dictionary<string, int>> Stats
		{
			get
			{
				if (!((Object)(object)StatsManager.instance == (Object)null))
				{
					return StatsDictionaries?.GetValue(StatsManager.instance) as SortedDictionary<string, Dictionary<string, int>>;
				}
				return null;
			}
		}

		internal static bool HostOwns(string key)
		{
			if (HostRules.Ready && Catalog.TryGet(key, out var info))
			{
				return Eligible(info);
			}
			return false;
		}

		private static bool Eligible(UpgradeInfo info)
		{
			if (HostRules.Bool("ReconcileHighest", Plugin.ReconcileHighest.Value) && UpgradeAuthority.CanApply(info) && UpgradeOptions.Enabled(info))
			{
				return UpgradeOptions.Effective(info) == UpgradeHandling.SharedPermanent;
			}
			return false;
		}

		internal static void Observe(string key)
		{
			if (!Applying && HostOwns(key) && Dirty.Count < 512)
			{
				Dirty.Add(key);
			}
		}

		internal static void Request()
		{
			_nextCheck = 0f;
		}

		internal static void RequestSnapshot()
		{
			_nextCheck = (_nextHeartbeat = 0f);
		}

		internal static void ResetHostState()
		{
			Reports.Clear();
			Targets.Clear();
			Dirty.Clear();
			_owners = (_remoteOwners = Array.Empty<string>());
			_remoteTargets = null;
			_remotePersonal = null;
			_purchased = false;
			_nextCheck = (_nextHeartbeat = 0f);
		}

		internal static bool RecordPurchase(string key, string owner)
		{
			if (PhotonNetwork.InRoom && PhotonNetwork.IsMasterClient && !Applying && ChargeLedgerModel.ValidOwner(owner) && Catalog.TryGet(key, out var info) && Eligible(info))
			{
				SortedDictionary<string, Dictionary<string, int>> stats = Stats;
				if (stats != null && stats.TryGetValue(key, out var value) && !((Object)(object)PunManager.instance == (Object)null))
				{
					int num = Current(value, owner);
					int num2 = info.MaxLevel();
					if (num2 > 0 && num >= num2)
					{
						return true;
					}
					Targets.TryGetValue(key, out var value2);
					foreach (KeyValuePair<string, PlayerAvatar> item in Players())
					{
						value2 = Math.Max(value2, Observed(key, value, item.Key, item.Value));
					}
					int num3 = SyncPolicy.Increment(value2, UpgradeOptio