Decompiled source of LethalCards v2.0.1

BepInEx/plugins/LethalCards/LethalCards.dll

Decompiled a month ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using LethalCards.Audio;
using LethalCards.Binders;
using LethalCards.Boosters;
using LethalCards.Cards;
using LethalCards.Debugging;
using LethalCards.Grading;
using LethalCards.Museum;
using LethalCards.NetcodePatcher;
using LethalCards.Networking;
using LethalCards.Save;
using LethalCards.ShipDisplay;
using LethalCards.TerminalCommands;
using LethalLib.Modules;
using Microsoft.CodeAnalysis;
using TMPro;
using Unity.Collections;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;
using UnityEngine.InputSystem.Utilities;
using UnityEngine.SceneManagement;
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("LethalCards")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("2.0.1.0")]
[assembly: AssemblyInformationalVersion("2.0.1+fd94cd07bc78a4b179baa669f6e866b24f6a96db")]
[assembly: AssemblyProduct("LethalCards")]
[assembly: AssemblyTitle("LethalCards")]
[assembly: AssemblyVersion("2.0.1.0")]
[module: RefSafetyRules(11)]
[module: NetcodePatchedAssembly]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[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 LethalCards
{
	internal static class BalanceConfig
	{
		internal const int DefaultGradingCost = 10;

		internal const int DefaultGradingTurnaroundDays = 3;

		internal const int DefaultLightBoosterSpawnWeight = 45;

		internal const int DefaultHeavyBoosterSpawnWeight = 25;

		internal const int DefaultStandardBoosterBoxSpawnWeight = 20;

		internal const int DefaultGoldenBoosterBoxSpawnWeight = 10;

		internal const int DefaultBinderSpawnWeight = 20;

		internal const int DefaultLightBoosterValue = 30;

		internal const int DefaultHeavyBoosterValue = 50;

		internal const int DefaultStandardBoosterBoxValue = 75;

		internal const int DefaultGoldenBoosterBoxValue = 150;

		private static readonly WeightedRarityTable DefaultLightSlot1 = new WeightedRarityTable(72.5f, 20f, 7.5f, 0f, 0f);

		private static readonly WeightedRarityTable DefaultLightSlot2 = new WeightedRarityTable(69f, 20f, 7.5f, 2.5f, 1f);

		private static readonly WeightedRarityTable DefaultLightSlot3 = new WeightedRarityTable(58f, 20f, 15f, 5f, 2f);

		private static readonly WeightedRarityTable DefaultHeavySlot1 = new WeightedRarityTable(30f, 55f, 10f, 5f, 0f);

		private static readonly WeightedRarityTable DefaultHeavySlot2 = new WeightedRarityTable(25f, 50f, 15f, 10f, 0f);

		private static readonly WeightedRarityTable DefaultHeavySlot3 = new WeightedRarityTable(20f, 40f, 20f, 15f, 5f);

		private static readonly WeightedVariantTable DefaultVariants = new WeightedVariantTable(69f, 25f, 5f, 1f);

		private static readonly WeightedGodPackTable DefaultGodPack = new WeightedGodPackTable(60f, 40f);

		private static readonly WeightedBoosterBoxTable DefaultStandardBoxPackMix = new WeightedBoosterBoxTable(90f, 10f);

		private static readonly WeightedGradeTable DefaultGrades = new WeightedGradeTable(2f, 4f, 6f, 8f, 10f, 12f, 13f, 23f, 17f, 5f);

		private static readonly float[] GradeMultipliers = new float[11]
		{
			0f, 0f, 0.2f, 0.35f, 0.5f, 0.65f, 0.8f, 1f, 1.5f, 2.5f,
			5f
		};

		private static readonly float[] VariantValueMultipliers = new float[5] { 1f, 1f, 1.5f, 2f, 3f };

		internal static WeightedRarityTable LightSlot1 { get; private set; } = DefaultLightSlot1;

		internal static WeightedRarityTable LightSlot2 { get; private set; } = DefaultLightSlot2;

		internal static WeightedRarityTable LightSlot3 { get; private set; } = DefaultLightSlot3;

		internal static WeightedRarityTable HeavySlot1 { get; private set; } = DefaultHeavySlot1;

		internal static WeightedRarityTable HeavySlot2 { get; private set; } = DefaultHeavySlot2;

		internal static WeightedRarityTable HeavySlot3 { get; private set; } = DefaultHeavySlot3;

		internal static WeightedVariantTable Variants { get; private set; } = DefaultVariants;

		internal static WeightedGodPackTable GodPackRarities { get; private set; } = DefaultGodPack;

		internal static WeightedBoosterBoxTable StandardBoxPackMix { get; private set; } = DefaultStandardBoxPackMix;

		internal static WeightedGradeTable GradeChances { get; private set; } = DefaultGrades;

		internal static float HeavyGodPackChancePercent { get; private set; } = 5f;

		internal static float HeavyGodPackChance => HeavyGodPackChancePercent / 100f;

		internal static int GradingCost { get; private set; } = 10;

		internal static int GradingTurnaroundDays { get; private set; } = 3;

		internal static int LightBoosterSpawnWeight { get; private set; } = 45;

		internal static int HeavyBoosterSpawnWeight { get; private set; } = 25;

		internal static int StandardBoosterBoxSpawnWeight { get; private set; } = 20;

		internal static int GoldenBoosterBoxSpawnWeight { get; private set; } = 10;

		internal static int BinderSpawnWeight { get; private set; } = 20;

		internal static int LightBoosterValue { get; private set; } = 30;

		internal static int HeavyBoosterValue { get; private set; } = 50;

		internal static int StandardBoosterBoxValue { get; private set; } = 75;

		internal static int GoldenBoosterBoxValue { get; private set; } = 150;

		internal static bool LegacyCardValueBehavior { get; private set; }

		internal static void Load(ConfigFile config)
		{
			//IL_02be: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c8: Expected O, but got Unknown
			LightSlot1 = BindRarity(config, "Rarity - Light Slot 1", DefaultLightSlot1);
			LightSlot2 = BindRarity(config, "Rarity - Light Slot 2", DefaultLightSlot2);
			LightSlot3 = BindRarity(config, "Rarity - Light Slot 3", DefaultLightSlot3);
			HeavySlot1 = BindRarity(config, "Rarity - Heavy Slot 1", DefaultHeavySlot1);
			HeavySlot2 = BindRarity(config, "Rarity - Heavy Slot 2", DefaultHeavySlot2);
			HeavySlot3 = BindRarity(config, "Rarity - Heavy Slot 3", DefaultHeavySlot3);
			HeavyGodPackChancePercent = ClampFloat(BindFloat(config, "God Pack", "HeavyGodPackChance", 5f, "Direct percent chance for Heavy packs to become God Packs. Clamped to 0-100. Light packs never become God Packs."), 0f, 100f, "God Pack.HeavyGodPackChance");
			GodPackRarities = BindGodPack(config, DefaultGodPack);
			Variants = BindVariants(config, DefaultVariants);
			BindVariantValues(config);
			StandardBoxPackMix = BindBoosterBoxMix(config, DefaultStandardBoxPackMix);
			GradingCost = ClampInt(BindInt(config, "Grading", "GradingCost", 10, "Credits charged by the grading pedestal per submitted card. Clamped to 0 or higher."), 0, int.MaxValue, "Grading.GradingCost");
			GradingTurnaroundDays = ClampInt(BindInt(config, "Grading", "GradingTurnaroundDays", 3, "Number of in-game days before submitted grading jobs become ready. Clamped to 0 or higher."), 0, int.MaxValue, "Grading.GradingTurnaroundDays");
			for (int i = 1; i <= 10; i++)
			{
				GradeMultipliers[i] = ClampFloat(BindFloat(config, "Grading", $"Grade{i}ValueMultiplier", GradeMultipliers[i], "Multiplier applied to a card's ungraded value after this grade is rolled. Negative values are clamped to 0."), 0f, float.MaxValue, $"Grading.Grade{i}ValueMultiplier");
			}
			GradeChances = BindGrades(config, DefaultGrades);
			LightBoosterSpawnWeight = BindNonNegativeInt(config, "Spawning", "LightBoosterSpawnWeight", 45, "Relative scrap spawn weight for Light Booster packs on all levels. 0 disables natural spawning while preserving item registration. Restart after changing.");
			HeavyBoosterSpawnWeight = BindNonNegativeInt(config, "Spawning", "HeavyBoosterSpawnWeight", 25, "Relative scrap spawn weight for Heavy Booster packs on all levels. 0 disables natural spawning while preserving item registration. Restart after changing.");
			StandardBoosterBoxSpawnWeight = BindNonNegativeInt(config, "Spawning", "StandardBoosterBoxSpawnWeight", 20, "Relative scrap spawn weight for Standard Booster Boxes on all levels. 0 disables natural spawning while preserving item registration. Restart after changing.");
			GoldenBoosterBoxSpawnWeight = BindNonNegativeInt(config, "Spawning", "GoldenBoosterBoxSpawnWeight", 10, "Relative scrap spawn weight for Golden Booster Boxes on all levels. 0 disables natural spawning while preserving item registration. Restart after changing.");
			BinderSpawnWeight = BindNonNegativeInt(config, "Spawning", "BinderSpawnWeight", 20, "Relative scrap spawn weight for Card Binders on all levels. Higher values make them more common. 0 disables natural spawning while preserving item registration. Restart after changing.");
			LightBoosterValue = BindNonNegativeInt(config, "Economy", "LightBoosterScrapValue", 30, "Fixed scrap value for Light Booster packs. Negative values are clamped to 0.");
			HeavyBoosterValue = BindNonNegativeInt(config, "Economy", "HeavyBoosterScrapValue", 50, "Fixed scrap value for Heavy Booster packs. Negative values are clamped to 0.");
			StandardBoosterBoxValue = BindNonNegativeInt(config, "Economy", "StandardBoosterBoxScrapValue", 75, "Fixed scrap value for Standard Booster Boxes. Negative values are clamped to 0.");
			GoldenBoosterBoxValue = BindNonNegativeInt(config, "Economy", "GoldenBoosterBoxScrapValue", 150, "Fixed scrap value for Golden Booster Boxes. Negative values are clamped to 0.");
			LegacyCardValueBehavior = config.Bind<bool>("Compatibility", "LegacyCardValueBehavior", false, new ConfigDescription("When enabled, Lethal Cards preserves its legacy card-value behavior and does not permanently adopt value changes made by external mods. When disabled (default), legitimate external scrap-value changes are synchronized to the card's current value for compatibility with mods such as Lethal Casino.", (AcceptableValueBase)null, Array.Empty<object>())).Value;
			config.Save();
			LogEffectiveValues();
		}

		internal static float GetGradeMultiplier(int grade)
		{
			if (grade < 1 || grade > 10)
			{
				return 1f;
			}
			return GradeMultipliers[grade];
		}

		internal static float GetVariantValueMultiplier(CardVariant variant)
		{
			return variant switch
			{
				CardVariant.Foil => VariantValueMultipliers[1], 
				CardVariant.AlternateArt => VariantValueMultipliers[2], 
				CardVariant.Misprint => VariantValueMultipliers[3], 
				_ => VariantValueMultipliers[0], 
			};
		}

		internal static WeightedRarityTable GetRarityTable(BoosterType type, int slotIndex)
		{
			if (type == BoosterType.Heavy)
			{
				return slotIndex switch
				{
					0 => HeavySlot1, 
					1 => HeavySlot2, 
					_ => HeavySlot3, 
				};
			}
			return slotIndex switch
			{
				0 => LightSlot1, 
				1 => LightSlot2, 
				_ => LightSlot3, 
			};
		}

		internal static int GetBoosterValue(BoosterType type)
		{
			if (type != BoosterType.Heavy)
			{
				return LightBoosterValue;
			}
			return HeavyBoosterValue;
		}

		internal static int GetBoosterBoxValue(BoosterBoxType type)
		{
			if (type != BoosterBoxType.Golden)
			{
				return StandardBoosterBoxValue;
			}
			return GoldenBoosterBoxValue;
		}

		private static WeightedRarityTable BindRarity(ConfigFile config, string section, WeightedRarityTable defaults)
		{
			WeightedRarityTable raw = new WeightedRarityTable(BindFloat(config, section, "CommonChance", defaults.Common, WeightDescription("Common cards")), BindFloat(config, section, "UncommonChance", defaults.Uncommon, WeightDescription("Uncommon cards")), BindFloat(config, section, "RareChance", defaults.Rare, WeightDescription("Rare cards")), BindFloat(config, section, "UltraRareChance", defaults.UltraRare, WeightDescription("Ultra Rare cards")), BindFloat(config, section, "SecretRareChance", defaults.SecretRare, WeightDescription("Secret Rare cards")));
			return NormalizeRarity(section, raw, defaults);
		}

		private static WeightedVariantTable BindVariants(ConfigFile config, WeightedVariantTable defaults)
		{
			return NormalizeVariants(new WeightedVariantTable(BindFloat(config, "Variants", "StandardChance", defaults.Standard, WeightDescription("Standard variant")), BindFloat(config, "Variants", "FoilChance", defaults.Foil, WeightDescription("Foil variant")), BindFloat(config, "Variants", "AlternateArtChance", defaults.AlternateArt, WeightDescription("Alternate Art variant")), BindFloat(config, "Variants", "MisprintChance", defaults.Misprint, WeightDescription("Misprint variant"))), defaults);
		}

		private static WeightedGodPackTable BindGodPack(ConfigFile config, WeightedGodPackTable defaults)
		{
			return NormalizeGodPack(new WeightedGodPackTable(BindFloat(config, "God Pack", "UltraRareChance", defaults.UltraRare, WeightDescription("Ultra Rare God Pack slots")), BindFloat(config, "God Pack", "SecretRareChance", defaults.SecretRare, WeightDescription("Secret Rare God Pack slots"))), defaults);
		}

		private static void BindVariantValues(ConfigFile config)
		{
			VariantValueMultipliers[0] = BindNonNegativeFiniteFloat(config, "Variant Values", "StandardValueMultiplier", 1f, "Literal value multiplier for Standard cards. This affects monetary value only and does not affect pull odds.");
			VariantValueMultipliers[1] = BindNonNegativeFiniteFloat(config, "Variant Values", "FoilValueMultiplier", 1.5f, "Literal value multiplier for Foil cards. This affects monetary value only and does not affect pull odds.");
			VariantValueMultipliers[2] = BindNonNegativeFiniteFloat(config, "Variant Values", "AlternateArtValueMultiplier", 2f, "Literal value multiplier for Alternate Art cards. This affects monetary value only and does not affect pull odds.");
			VariantValueMultipliers[3] = BindNonNegativeFiniteFloat(config, "Variant Values", "MisprintValueMultiplier", 3f, "Literal value multiplier for Misprint cards. This affects monetary value only and does not affect pull odds.");
		}

		private static WeightedBoosterBoxTable BindBoosterBoxMix(ConfigFile config, WeightedBoosterBoxTable defaults)
		{
			return NormalizeBoosterBox(new WeightedBoosterBoxTable(BindFloat(config, "Booster Boxes", "StandardBoxLightPackChance", defaults.Light, "Relative weight for Light packs in Standard Booster Boxes. Normalized automatically: 90/10 = 90%/10%, 3/1 = 75%/25%."), BindFloat(config, "Booster Boxes", "StandardBoxHeavyPackChance", defaults.Heavy, "Relative weight for Heavy packs in Standard Booster Boxes. Normalized automatically: 90/10 = 90%/10%, 3/1 = 75%/25%.")), defaults);
		}

		private static WeightedGradeTable BindGrades(ConfigFile config, WeightedGradeTable defaults)
		{
			float[] array = new float[10];
			for (int i = 0; i < array.Length; i++)
			{
				array[i] = BindFloat(config, "Grading", $"Grade{i + 1}Chance", defaults.GetWeight(i + 1), "Non-negative grade roll weight. Grade chance weights are normalized automatically and do not need to sum to 100.");
			}
			return NormalizeGrades(new WeightedGradeTable(array), defaults);
		}

		private static WeightedRarityTable NormalizeRarity(string name, WeightedRarityTable raw, WeightedRarityTable fallback)
		{
			float[] weights = ClampWeights(name, raw.ToArray());
			if (Sum(weights) <= 0f)
			{
				Plugin.Log.LogWarning("BALANCE CONFIG FALLBACK | " + name + " weights were all zero or invalid; using production defaults.");
				return fallback.Normalized();
			}
			return new WeightedRarityTable(weights).Normalized();
		}

		private static WeightedVariantTable NormalizeVariants(WeightedVariantTable raw, WeightedVariantTable fallback)
		{
			float[] weights = ClampWeights("Variants", raw.ToArray());
			if (Sum(weights) <= 0f)
			{
				Plugin.Log.LogWarning("BALANCE CONFIG FALLBACK | Variant weights were all zero or invalid; using production defaults.");
				return fallback.Normalized();
			}
			return new WeightedVariantTable(weights).Normalized();
		}

		private static WeightedGodPackTable NormalizeGodPack(WeightedGodPackTable raw, WeightedGodPackTable fallback)
		{
			float[] weights = ClampWeights("God Pack", raw.ToArray());
			if (Sum(weights) <= 0f)
			{
				Plugin.Log.LogWarning("BALANCE CONFIG FALLBACK | God Pack Ultra/Secret weights were all zero or invalid; using production defaults.");
				return fallback.Normalized();
			}
			return new WeightedGodPackTable(weights).Normalized();
		}

		private static WeightedGradeTable NormalizeGrades(WeightedGradeTable raw, WeightedGradeTable fallback)
		{
			float[] weights = ClampWeights("Grading grade chances", raw.ToArray());
			if (Sum(weights) <= 0f)
			{
				Plugin.Log.LogWarning("BALANCE CONFIG FALLBACK | Grade chance weights were all zero or invalid; using production defaults.");
				return fallback.Normalized();
			}
			return new WeightedGradeTable(weights).Normalized();
		}

		private static WeightedBoosterBoxTable NormalizeBoosterBox(WeightedBoosterBoxTable raw, WeightedBoosterBoxTable fallback)
		{
			float[] weights = ClampWeights("Booster Boxes", raw.ToArray());
			if (Sum(weights) <= 0f)
			{
				Plugin.Log.LogWarning("BALANCE CONFIG FALLBACK | Standard Booster Box Light/Heavy weights were all zero or invalid; using production defaults.");
				return fallback.Normalized();
			}
			return new WeightedBoosterBoxTable(weights).Normalized();
		}

		private static float[] ClampWeights(string name, float[] weights)
		{
			bool flag = false;
			for (int i = 0; i < weights.Length; i++)
			{
				if (!(weights[i] >= 0f))
				{
					weights[i] = 0f;
					flag = true;
				}
			}
			if (flag)
			{
				Plugin.Log.LogWarning("BALANCE CONFIG CLAMPED | " + name + " had negative weights; negatives were treated as 0.");
			}
			return weights;
		}

		private static float BindFloat(ConfigFile config, string section, string key, float defaultValue, string description)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Expected O, but got Unknown
			return config.Bind<float>(section, key, defaultValue, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty<object>())).Value;
		}

		private static int BindInt(ConfigFile config, string section, string key, int defaultValue, string description)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Expected O, but got Unknown
			return config.Bind<int>(section, key, defaultValue, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty<object>())).Value;
		}

		private static int BindNonNegativeInt(ConfigFile config, string section, string key, int defaultValue, string description)
		{
			return ClampInt(BindInt(config, section, key, defaultValue, description), 0, int.MaxValue, section + "." + key);
		}

		private static float BindNonNegativeFiniteFloat(ConfigFile config, string section, string key, float defaultValue, string description)
		{
			float num = BindFloat(config, section, key, defaultValue, description);
			if (float.IsNaN(num) || float.IsInfinity(num))
			{
				Plugin.Log.LogWarning($"BALANCE CONFIG FALLBACK | {section}.{key}={num} was invalid; using default {defaultValue}.");
				return defaultValue;
			}
			return ClampFloat(num, 0f, float.MaxValue, section + "." + key);
		}

		private static int ClampInt(int value, int min, int max, string name)
		{
			int num = Math.Max(min, Math.Min(max, value));
			if (num != value)
			{
				Plugin.Log.LogWarning($"BALANCE CONFIG CLAMPED | {name}={value} was clamped to {num}.");
			}
			return num;
		}

		private static float ClampFloat(float value, float min, float max, string name)
		{
			float num = Math.Max(min, Math.Min(max, value));
			if (Math.Abs(num - value) > 0.0001f)
			{
				Plugin.Log.LogWarning($"BALANCE CONFIG CLAMPED | {name}={value} was clamped to {num}.");
			}
			return num;
		}

		private static string WeightDescription(string label)
		{
			return "Non-negative weight/chance for " + label + ". Tables are normalized automatically and do not need to sum to 100.";
		}

		private static float Sum(float[] weights)
		{
			float num = 0f;
			foreach (float num2 in weights)
			{
				num += num2;
			}
			return num;
		}

		private static void LogEffectiveValues()
		{
			LogRarity("Light Slot 1", LightSlot1);
			LogRarity("Light Slot 2", LightSlot2);
			LogRarity("Light Slot 3", LightSlot3);
			LogRarity("Heavy Slot 1", HeavySlot1);
			LogRarity("Heavy Slot 2", HeavySlot2);
			LogRarity("Heavy Slot 3", HeavySlot3);
			Plugin.Log.LogInfo($"VARIANT CONFIG EFFECTIVE | Standard={Variants.Standard:F2}% | Foil={Variants.Foil:F2}% | AlternateArt={Variants.AlternateArt:F2}% | Misprint={Variants.Misprint:F2}%");
			Plugin.Log.LogInfo($"VARIANT VALUE CONFIG EFFECTIVE | Standard={VariantValueMultipliers[0]:F2}x | Foil={VariantValueMultipliers[1]:F2}x | AlternateArt={VariantValueMultipliers[2]:F2}x | Misprint={VariantValueMultipliers[3]:F2}x");
			Plugin.Log.LogInfo($"GOD PACK CONFIG EFFECTIVE | TriggerChance={HeavyGodPackChancePercent:F2}% | UltraRare={GodPackRarities.UltraRare:F2}% | SecretRare={GodPackRarities.SecretRare:F2}%");
			Plugin.Log.LogInfo($"BOOSTER BOX CONFIG EFFECTIVE | StandardBoxLight={StandardBoxPackMix.Light:F2}% | StandardBoxHeavy={StandardBoxPackMix.Heavy:F2}% | GoldenBoxHeavy=100.00%");
			Plugin.Log.LogInfo($"BALANCE CONFIG EFFECTIVE | GradingCost={GradingCost} | GradingTurnaroundDays={GradingTurnaroundDays} | LightSpawnWeight={LightBoosterSpawnWeight} | HeavySpawnWeight={HeavyBoosterSpawnWeight} | StandardBoxSpawnWeight={StandardBoosterBoxSpawnWeight} | GoldenBoxSpawnWeight={GoldenBoosterBoxSpawnWeight} | BinderSpawnWeight={BinderSpawnWeight}");
			Plugin.Log.LogInfo($"ECONOMY CONFIG EFFECTIVE | LightBoosterValue={LightBoosterValue} | HeavyBoosterValue={HeavyBoosterValue} | StandardBoxValue={StandardBoosterBoxValue} | GoldenBoxValue={GoldenBoosterBoxValue}");
			Plugin.Log.LogInfo($"GRADING CHANCE CONFIG EFFECTIVE | Grade1={GradeChances.GetWeight(1):F2}% | Grade2={GradeChances.GetWeight(2):F2}% | Grade3={GradeChances.GetWeight(3):F2}% | Grade4={GradeChances.GetWeight(4):F2}% | Grade5={GradeChances.GetWeight(5):F2}% | Grade6={GradeChances.GetWeight(6):F2}% | Grade7={GradeChances.GetWeight(7):F2}% | Grade8={GradeChances.GetWeight(8):F2}% | Grade9={GradeChances.GetWeight(9):F2}% | Grade10={GradeChances.GetWeight(10):F2}%");
			Plugin.Log.LogInfo($"GRADING MULTIPLIER CONFIG EFFECTIVE | Grade1={GradeMultipliers[1]:F2} | Grade2={GradeMultipliers[2]:F2} | Grade3={GradeMultipliers[3]:F2} | Grade4={GradeMultipliers[4]:F2} | Grade5={GradeMultipliers[5]:F2} | Grade6={GradeMultipliers[6]:F2} | Grade7={GradeMultipliers[7]:F2} | Grade8={GradeMultipliers[8]:F2} | Grade9={GradeMultipliers[9]:F2} | Grade10={GradeMultipliers[10]:F2}");
		}

		private static void LogRarity(string label, WeightedRarityTable table)
		{
			Plugin.Log.LogInfo($"RARITY CONFIG EFFECTIVE | {label} | Common={table.Common:F2}% | Uncommon={table.Uncommon:F2}% | Rare={table.Rare:F2}% | UltraRare={table.UltraRare:F2}% | SecretRare={table.SecretRare:F2}%");
		}
	}
	internal readonly struct WeightedRarityTable
	{
		internal readonly float Common;

		internal readonly float Uncommon;

		internal readonly float Rare;

		internal readonly float UltraRare;

		internal readonly float SecretRare;

		internal WeightedRarityTable(float common, float uncommon, float rare, float ultraRare, float secretRare)
		{
			Common = common;
			Uncommon = uncommon;
			Rare = rare;
			UltraRare = ultraRare;
			SecretRare = secretRare;
		}

		internal WeightedRarityTable(float[] weights)
			: this(weights[0], weights[1], weights[2], weights[3], weights[4])
		{
		}

		internal CardRarity Roll(Random random)
		{
			float num = (float)(random.NextDouble() * 100.0);
			if (num < Common)
			{
				return CardRarity.Common;
			}
			if (num < Common + Uncommon)
			{
				return CardRarity.Uncommon;
			}
			if (num < Common + Uncommon + Rare)
			{
				return CardRarity.Rare;
			}
			if (num < Common + Uncommon + Rare + UltraRare)
			{
				return CardRarity.UltraRare;
			}
			return CardRarity.SecretRare;
		}

		internal float[] ToArray()
		{
			return new float[5] { Common, Uncommon, Rare, UltraRare, SecretRare };
		}

		internal WeightedRarityTable Normalized()
		{
			float num = Common + Uncommon + Rare + UltraRare + SecretRare;
			return new WeightedRarityTable(Common * 100f / num, Uncommon * 100f / num, Rare * 100f / num, UltraRare * 100f / num, SecretRare * 100f / num);
		}
	}
	internal readonly struct WeightedVariantTable
	{
		internal readonly float Standard;

		internal readonly float Foil;

		internal readonly float AlternateArt;

		internal readonly float Misprint;

		internal WeightedVariantTable(float standard, float foil, float alternateArt, float misprint)
		{
			Standard = standard;
			Foil = foil;
			AlternateArt = alternateArt;
			Misprint = misprint;
		}

		internal WeightedVariantTable(float[] weights)
			: this(weights[0], weights[1], weights[2], weights[3])
		{
		}

		internal CardVariant Roll(Random random)
		{
			float num = (float)(random.NextDouble() * 100.0);
			if (num < Standard)
			{
				return CardVariant.Standard;
			}
			if (num < Standard + Foil)
			{
				return CardVariant.Foil;
			}
			if (num < Standard + Foil + AlternateArt)
			{
				return CardVariant.AlternateArt;
			}
			return CardVariant.Misprint;
		}

		internal float[] ToArray()
		{
			return new float[4] { Standard, Foil, AlternateArt, Misprint };
		}

		internal WeightedVariantTable Normalized()
		{
			float num = Standard + Foil + AlternateArt + Misprint;
			return new WeightedVariantTable(Standard * 100f / num, Foil * 100f / num, AlternateArt * 100f / num, Misprint * 100f / num);
		}
	}
	internal readonly struct WeightedGodPackTable
	{
		internal readonly float UltraRare;

		internal readonly float SecretRare;

		internal WeightedGodPackTable(float ultraRare, float secretRare)
		{
			UltraRare = ultraRare;
			SecretRare = secretRare;
		}

		internal WeightedGodPackTable(float[] weights)
			: this(weights[0], weights[1])
		{
		}

		internal CardRarity Roll(Random random)
		{
			if (!((float)(random.NextDouble() * 100.0) < UltraRare))
			{
				return CardRarity.SecretRare;
			}
			return CardRarity.UltraRare;
		}

		internal float[] ToArray()
		{
			return new float[2] { UltraRare, SecretRare };
		}

		internal WeightedGodPackTable Normalized()
		{
			float num = UltraRare + SecretRare;
			return new WeightedGodPackTable(UltraRare * 100f / num, SecretRare * 100f / num);
		}
	}
	internal readonly struct WeightedBoosterBoxTable
	{
		internal readonly float Light;

		internal readonly float Heavy;

		internal WeightedBoosterBoxTable(float light, float heavy)
		{
			Light = light;
			Heavy = heavy;
		}

		internal WeightedBoosterBoxTable(float[] weights)
			: this(weights[0], weights[1])
		{
		}

		internal BoosterType Roll(float roll)
		{
			if (!(roll * 100f < Heavy))
			{
				return BoosterType.Light;
			}
			return BoosterType.Heavy;
		}

		internal float[] ToArray()
		{
			return new float[2] { Light, Heavy };
		}

		internal WeightedBoosterBoxTable Normalized()
		{
			float num = Light + Heavy;
			return new WeightedBoosterBoxTable(Light * 100f / num, Heavy * 100f / num);
		}
	}
	internal readonly struct WeightedGradeTable
	{
		private readonly float[] weights;

		internal WeightedGradeTable(params float[] weights)
		{
			this.weights = weights;
		}

		internal int Roll(Random random)
		{
			float num = (float)(random.NextDouble() * 100.0);
			float num2 = 0f;
			for (int i = 0; i < weights.Length; i++)
			{
				num2 += weights[i];
				if (num < num2)
				{
					return i + 1;
				}
			}
			return 10;
		}

		internal float GetWeight(int grade)
		{
			if (grade < 1 || grade > weights.Length)
			{
				return 0f;
			}
			return weights[grade - 1];
		}

		internal float[] ToArray()
		{
			return (float[])weights.Clone();
		}

		internal WeightedGradeTable Normalized()
		{
			float num = 0f;
			float[] array = weights;
			foreach (float num2 in array)
			{
				num += num2;
			}
			float[] array2 = new float[weights.Length];
			for (int j = 0; j < weights.Length; j++)
			{
				array2[j] = weights[j] * 100f / num;
			}
			return new WeightedGradeTable(array2);
		}
	}
	internal sealed class ModLog
	{
		private readonly ManualLogSource source;

		internal ModLog(ManualLogSource source)
		{
			this.source = source;
		}

		internal void LogInfo(object data)
		{
			if (Plugin.EnableDebugLogging)
			{
				source.LogInfo(data);
			}
		}

		internal void LogDebug(object data)
		{
			if (Plugin.EnableDebugLogging)
			{
				source.LogInfo(data);
			}
		}

		internal void LogAlways(object data)
		{
			source.LogInfo(data);
		}

		internal void LogWarning(object data)
		{
			source.LogWarning(data);
		}

		internal void LogError(object data)
		{
			source.LogError(data);
		}
	}
	[BepInPlugin("Hdaddy.LethalCards", "Lethal Cards", "2.0.1")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class Plugin : BaseUnityPlugin
	{
		public const string PluginGuid = "Hdaddy.LethalCards";

		public const string PluginName = "Lethal Cards";

		public const string PluginVersion = "2.0.1";

		private static readonly Vector3 CardHeldPositionCorrection = new Vector3(0.1f, 0.1f, -0.08f);

		private static readonly Vector3 BoosterPackHeldPositionCorrection = new Vector3(0.1f, 0.1f, -0.08f);

		private static readonly Vector3 BoosterBoxHeldPositionCorrection = new Vector3(0.08f, 0.175f, -0.12f);

		private static readonly Vector3 BinderHeldPositionCorrection = new Vector3(0.1f, 0.1f, -0.1f);

		private static readonly Vector3 BinderHeldRotationCorrection = new Vector3(-90f, 0f, 0f);

		private static readonly HashSet<Item> HeldPositionAdjustedItems = new HashSet<Item>();

		private static readonly HashSet<Item> HeldRotationAdjustedItems = new HashSet<Item>();

		private const float CardFloorVerticalOffset = 0.03f;

		private const float BoosterPackFloorVerticalOffset = 0.06f;

		private const float BoosterBoxFloorVerticalOffset = 0.15f;

		internal static ModLog Log = null;

		internal static Item? LightBoosterItem;

		internal static Item? HeavyBoosterItem;

		internal static Item? BoosterBoxItem;

		internal static Item? GoldenBoosterBoxItem;

		internal static Item? CardBinderItem;

		private Harmony? harmony;

		internal static bool EnableDebugLogging { get; private set; }

		private void Awake()
		{
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Expected O, but got Unknown
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Expected O, but got Unknown
			//IL_0094: Expected O, but got Unknown
			//IL_02ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0309: Expected O, but got Unknown
			Log = new ModLog(((BaseUnityPlugin)this).Logger);
			string text = Path.Combine(Paths.ConfigPath, "LethalCards.cfg");
			string[] files = Directory.GetFiles(Paths.ConfigPath, "*.LethalCards.cfg");
			if (!File.Exists(text) && files.Length == 1)
			{
				File.Copy(files[0], text);
				Log.LogInfo("Copied existing Lethal Cards settings to LethalCards.cfg; the legacy file is no longer used.");
			}
			ConfigFile val = new ConfigFile(text, true);
			EnableDebugLogging = val.Bind<bool>("General", "EnableDebugLogging", false, "Enable verbose Lethal Cards diagnostics and developer-only test helpers.").Value;
			val.Save();
			BalanceConfig.Load(val);
			ShipCardDisplayConfig.Load(val);
			CompanyMuseumDisplayConfig.Load(val);
			Type[] types = Assembly.GetExecutingAssembly().GetTypes();
			for (int i = 0; i < types.Length; i++)
			{
				MethodInfo[] methods = types[i].GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
				foreach (MethodInfo methodInfo in methods)
				{
					if (methodInfo.IsDefined(typeof(RuntimeInitializeOnLoadMethodAttribute), inherit: false))
					{
						methodInfo.Invoke(null, null);
					}
				}
			}
			if (EnableDebugLogging)
			{
				Log.LogAlways("LETHAL CARDS DEBUG LOGGING ENABLED | Developer diagnostics and test spawns are active");
			}
			string text2 = Path.Combine(Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location), "lethalcards");
			Log.LogInfo("Loading asset bundle from: " + text2);
			AssetBundle val2 = AssetBundle.LoadFromFile(text2);
			if ((Object)(object)val2 == (Object)null)
			{
				Log.LogError("FAILED TO LOAD lethalcards ASSET BUNDLE");
				return;
			}
			Log.LogInfo("Asset bundle loaded successfully.");
			BoosterRevealAssets.Load(val2);
			GradingPedestalSpawner.LoadAssets(val2);
			GradedCardSlabPresentation.LoadAssets(val2);
			CompanyMuseumDisplaySpawner.LoadAssets(val2);
			ShipCardDisplaySpawner.LoadAssets(val2);
			foreach (CardDefinition item in CardDatabase.Cards.Take(7))
			{
				if (item.AssetName != null)
				{
					RegisterCard(val2, item);
				}
			}
			RegisterBooster(val2, "LightBoosterPackItem", BoosterType.Light, BalanceConfig.LightBoosterSpawnWeight);
			RegisterBooster(val2, "HeavyBoosterPackItem", BoosterType.Heavy, BalanceConfig.HeavyBoosterSpawnWeight);
			BoosterBoxItem = RegisterBoosterBox(val2, "BoosterBoxItem", BoosterBoxType.Standard, BalanceConfig.StandardBoosterBoxSpawnWeight);
			GoldenBoosterBoxItem = RegisterBoosterBox(val2, "GoldenBoosterBoxItem", BoosterBoxType.Golden, BalanceConfig.GoldenBoosterBoxSpawnWeight);
			foreach (CardDefinition item2 in CardDatabase.Cards.Skip(7))
			{
				if (item2.AssetName != null)
				{
					RegisterCard(val2, item2);
				}
			}
			CardBinderItem = RegisterCardBinder(val2);
			Log.LogInfo($"CARD REGISTRY | Definitions={CardDatabase.Cards.Count} | " + $"Implemented={CardDatabase.GetImplementedCards().Count()} | " + string.Join(" | ", ((CardRarity[])Enum.GetValues(typeof(CardRarity))).Select((CardRarity rarity) => $"{rarity}={CardDatabase.GetImplementedCards().Count((CardDefinition card) => card.Rarity == rarity)}")));
			harmony = new Harmony("Hdaddy.LethalCards");
			harmony.PatchAll();
			Log.LogAlways("LETHAL CARDS INITIALIZED | Version=2.0.1 | " + $"Cards={CardDatabase.GetImplementedCards().Count()}/{CardDatabase.Cards.Count} | " + "Systems=Boosters,Collection,Grading,Binder,ShipDisplay,Museum");
			Log.LogInfo($"SILENT ITEM AUDIO FALLBACKS | AssignedFields={SilentItemAudio.AssignmentCount}");
		}

		private bool PrepareCardPrefab(GameObject prefab, Item item, string cardId)
		{
			if ((Object)(object)prefab == (Object)null)
			{
				Log.LogError("CARD PREFAB PREP FAILED | Prefab was null.");
				return false;
			}
			if ((Object)(object)prefab.GetComponent<NetworkObject>() == (Object)null)
			{
				Log.LogError("CARD PREFAB PREP FAILED | Prefab=" + ((Object)prefab).name + " | Reason=NetworkObject missing");
				return false;
			}
			CardInstanceData component = prefab.GetComponent<CardInstanceData>();
			if ((Object)(object)prefab.GetComponent<GradingReturnData>() == (Object)null)
			{
				prefab.AddComponent<GradingReturnData>();
			}
			if ((Object)(object)prefab.GetComponent<NetworkItemConsumption>() == (Object)null)
			{
				prefab.AddComponent<NetworkItemConsumption>();
			}
			if ((Object)(object)prefab.GetComponent<CardVariantVisuals>() == (Object)null)
			{
				prefab.AddComponent<CardVariantVisuals>();
			}
			if ((Object)(object)component == (Object)null)
			{
				prefab.AddComponent<CardInstanceData>();
			}
			return CardPhysicalState.PreparePrefab(item, prefab, cardId);
		}

		private void RegisterCard(AssetBundle bundle, CardDefinition card)
		{
			//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
			Item val = bundle.LoadAsset<Item>(card.AssetName);
			if ((Object)(object)val == (Object)null || (Object)(object)val.spawnPrefab == (Object)null || (Object)(object)val.spawnPrefab.GetComponent<NetworkObject>() == (Object)null || (Object)(object)val.spawnPrefab.GetComponent<PhysicsProp>() == (Object)null)
			{
				Log.LogError("CARD DISABLED | Id=" + card.CardId + " | Asset=" + card.AssetName + " | Missing item, prefab, NetworkObject, or PhysicsProp.");
			}
			else if (!PrepareCardPrefab(val.spawnPrefab, val, card.CardId))
			{
				Log.LogError("CARD DISABLED | Id=" + card.CardId + " | Asset=" + card.AssetName + " | Physical card scale or collider initialization failed.");
			}
			else
			{
				SilentItemAudio.EnsureFallbacks(val);
				val.verticalOffset = 0.03f;
				ApplyHeldPositionCorrection(val, CardHeldPositionCorrection, "Card");
				val.saveItemVariable = true;
				val.canBeInspected = true;
				NetworkPrefabs.RegisterNetworkPrefab(val.spawnPrefab);
				Items.RegisterItem(val);
				card.AttachImplementedItem(val);
			}
		}

		internal static bool EnsureActionTooltip(Item? item, string action)
		{
			action = BoosterActionTooltips.Format(action);
			if ((Object)(object)item == (Object)null)
			{
				Log.LogWarning("ACTION TOOLTIP NOT CONFIGURED | Action=\"" + action + "\" | Item reference is null.");
				return false;
			}
			if (item.toolTips != null && item.toolTips.Length != 0 && item.toolTips[0] == action)
			{
				return false;
			}
			string[] array = ((item.toolTips == null || item.toolTips.Length == 0) ? new string[1] : ((string[])item.toolTips.Clone()));
			array[0] = action;
			item.toolTips = array;
			return true;
		}

		private Item? RegisterBoosterBox(AssetBundle bundle, string assetName, BoosterBoxType type, int spawnWeight)
		{
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0179: Unknown result type (might be due to invalid IL or missing references)
			Item val = bundle.LoadAsset<Item>(assetName);
			if ((Object)(object)val == (Object)null || (Object)(object)val.spawnPrefab == (Object)null || (Object)(object)val.spawnPrefab.GetComponent<NetworkObject>() == (Object)null)
			{
				Log.LogError("BOOSTER BOX REGISTRATION FAILED | Asset=" + assetName + " | Missing Item, spawn prefab, or NetworkObject.");
				return null;
			}
			SetFixedScrapValue(val, BalanceConfig.GetBoosterBoxValue(type));
			SilentItemAudio.EnsureFallbacks(val);
			val.verticalOffset = 0.15f;
			string type2 = ((type == BoosterBoxType.Golden) ? "GoldenBox" : "StandardBox");
			ApplyHeldPositionCorrection(val, BoosterBoxHeldPositionCorrection, type2);
			PhysicsProp component = val.spawnPrefab.GetComponent<PhysicsProp>();
			if ((Object)(object)component == (Object)null)
			{
				Log.LogError("BOOSTER BOX REGISTRATION FAILED | Asset=" + assetName + " | Missing PhysicsProp.");
				return null;
			}
			BoosterBoxBehaviour boosterBoxBehaviour = val.spawnPrefab.AddComponent<BoosterBoxBehaviour>();
			((GrabbableObject)boosterBoxBehaviour).itemProperties = ((GrabbableObject)component).itemProperties;
			if ((Object)(object)((GrabbableObject)boosterBoxBehaviour).itemProperties != (Object)(object)val)
			{
				ModLog log = Log;
				object arg = type;
				string name = ((Object)val).name;
				Item itemProperties = ((GrabbableObject)component).itemProperties;
				log.LogWarning($"BOOSTER BOX ITEM REFERENCE MISMATCH | Type={arg} | Loaded={name} | Original={((itemProperties != null) ? ((Object)itemProperties).name : null)}");
			}
			((GrabbableObject)boosterBoxBehaviour).grabbable = ((GrabbableObject)component).grabbable;
			((GrabbableObject)boosterBoxBehaviour).isInFactory = ((GrabbableObject)component).isInFactory;
			((GrabbableObject)boosterBoxBehaviour).mainObjectRenderer = ((GrabbableObject)component).mainObjectRenderer;
			boosterBoxBehaviour.BoxType = type;
			if ((Object)(object)((GrabbableObject)boosterBoxBehaviour).itemProperties != (Object)null && (Object)(object)((GrabbableObject)boosterBoxBehaviour).itemProperties != (Object)(object)val)
			{
				SilentItemAudio.EnsureFallbacks(((GrabbableObject)boosterBoxBehaviour).itemProperties);
				((GrabbableObject)boosterBoxBehaviour).itemProperties.verticalOffset = 0.15f;
				ApplyHeldPositionCorrection(((GrabbableObject)boosterBoxBehaviour).itemProperties, BoosterBoxHeldPositionCorrection, type2);
			}
			bool flag = EnsureActionTooltip(val, "Open Box");
			if ((Object)(object)((GrabbableObject)boosterBoxBehaviour).itemProperties != (Object)(object)val)
			{
				flag |= EnsureActionTooltip(((GrabbableObject)boosterBoxBehaviour).itemProperties, "Open Box");
			}
			val.saveItemVariable = true;
			Object.DestroyImmediate((Object)(object)component);
			if ((Object)(object)val.spawnPrefab.GetComponent<NetworkItemConsumption>() == (Object)null)
			{
				val.spawnPrefab.AddComponent<NetworkItemConsumption>();
			}
			NetworkPrefabs.RegisterNetworkPrefab(val.spawnPrefab);
			if (spawnWeight > 0)
			{
				Items.RegisterScrap(val, spawnWeight, (LevelTypes)(-1));
			}
			else
			{
				Items.RegisterItem(val);
			}
			Log.LogInfo($"BOOSTER BOX REGISTERED | Type={type} | SpawnWeight={spawnWeight}");
			return val;
		}

		private void RegisterBooster(AssetBundle bundle, string assetName, BoosterType packType, int spawnWeight)
		{
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0130: Unknown result type (might be due to invalid IL or missing references)
			Item val = bundle.LoadAsset<Item>(assetName);
			if ((Object)(object)val == (Object)null)
			{
				Log.LogError("Failed to load booster item: " + assetName);
				return;
			}
			if ((Object)(object)val.spawnPrefab == (Object)null)
			{
				Log.LogError(assetName + " has no spawn prefab.");
				return;
			}
			SetFixedScrapValue(val, BalanceConfig.GetBoosterValue(packType));
			SilentItemAudio.EnsureFallbacks(val);
			val.verticalOffset = 0.06f;
			string type = ((packType == BoosterType.Heavy) ? "HeavyPack" : "LightPack");
			ApplyHeldPositionCorrection(val, BoosterPackHeldPositionCorrection, type);
			PhysicsProp component = val.spawnPrefab.GetComponent<PhysicsProp>();
			if ((Object)(object)component == (Object)null)
			{
				Log.LogError(assetName + " has no PhysicsProp.");
				return;
			}
			BoosterPackBehaviour boosterPackBehaviour = val.spawnPrefab.AddComponent<BoosterPackBehaviour>();
			((GrabbableObject)boosterPackBehaviour).itemProperties = ((GrabbableObject)component).itemProperties;
			((GrabbableObject)boosterPackBehaviour).grabbable = ((GrabbableObject)component).grabbable;
			((GrabbableObject)boosterPackBehaviour).isInFactory = ((GrabbableObject)component).isInFactory;
			((GrabbableObject)boosterPackBehaviour).mainObjectRenderer = ((GrabbableObject)component).mainObjectRenderer;
			boosterPackBehaviour.PackType = packType;
			if ((Object)(object)((GrabbableObject)boosterPackBehaviour).itemProperties != (Object)null && (Object)(object)((GrabbableObject)boosterPackBehaviour).itemProperties != (Object)(object)val)
			{
				SilentItemAudio.EnsureFallbacks(((GrabbableObject)boosterPackBehaviour).itemProperties);
				((GrabbableObject)boosterPackBehaviour).itemProperties.verticalOffset = 0.06f;
				ApplyHeldPositionCorrection(((GrabbableObject)boosterPackBehaviour).itemProperties, BoosterPackHeldPositionCorrection, type);
			}
			bool flag = EnsureActionTooltip(val, "Rip Pack");
			if ((Object)(object)((GrabbableObject)boosterPackBehaviour).itemProperties != (Object)(object)val)
			{
				flag |= EnsureActionTooltip(((GrabbableObject)boosterPackBehaviour).itemProperties, "Rip Pack");
			}
			Object.DestroyImmediate((Object)(object)component);
			if ((Object)(object)val.spawnPrefab.GetComponent<NetworkItemConsumption>() == (Object)null)
			{
				val.spawnPrefab.AddComponent<NetworkItemConsumption>();
			}
			Log.LogInfo("Replaced PhysicsProp with " + $"BoosterPackBehaviour for {packType} pack.");
			NetworkPrefabs.RegisterNetworkPrefab(val.spawnPrefab);
			if (spawnWeight > 0)
			{
				Items.RegisterScrap(val, spawnWeight, (LevelTypes)(-1));
			}
			else
			{
				Items.RegisterItem(val);
			}
			switch (packType)
			{
			case BoosterType.Light:
				LightBoosterItem = val;
				break;
			case BoosterType.Heavy:
				HeavyBoosterItem = val;
				break;
			}
			Log.LogInfo($"Registered {packType} booster | " + $"Configured Spawn Weight: {spawnWeight}");
		}

		private static void SetFixedScrapValue(Item item, int value)
		{
			item.maxValue = (item.minValue = Math.Max(0, value));
		}

		private Item? RegisterCardBinder(AssetBundle bundle)
		{
			//IL_017b: Unknown result type (might be due to invalid IL or missing references)
			//IL_018b: Unknown result type (might be due to invalid IL or missing references)
			Item val = bundle.LoadAsset<Item>("CardBinderItem");
			if ((Object)(object)val == (Object)null || (Object)(object)val.spawnPrefab == (Object)null)
			{
				Log.LogError("CARD BINDER REGISTRATION FAILED | Asset=CardBinderItem | Missing Item or spawn prefab.");
				return null;
			}
			if (((Object)val.spawnPrefab).name != "CardBinder")
			{
				Log.LogError("CARD BINDER REGISTRATION FAILED | Asset=CardBinderItem | ExpectedPrefab=CardBinder | ActualPrefab=" + ((Object)val.spawnPrefab).name);
				return null;
			}
			NetworkObject component = val.spawnPrefab.GetComponent<NetworkObject>();
			PhysicsProp component2 = val.spawnPrefab.GetComponent<PhysicsProp>();
			if ((Object)(object)component == (Object)null || (Object)(object)component2 == (Object)null)
			{
				Log.LogError("CARD BINDER REGISTRATION FAILED | Asset=CardBinderItem | Prefab=" + ((Object)val.spawnPrefab).name + " | " + $"NetworkObject={(Object)(object)component != (Object)null} | PhysicsProp={(Object)(object)component2 != (Object)null}");
				return null;
			}
			if (val.spawnPrefab.GetComponents<GrabbableObject>().Length != 1)
			{
				Log.LogError("CARD BINDER REGISTRATION FAILED | Prefab=" + ((Object)val.spawnPrefab).name + " | Expected exactly one GrabbableObject component.");
				return null;
			}
			if (!val.spawnPrefab.GetComponentsInChildren<Collider>(true).Any((Collider collider) => (Object)(object)collider != (Object)null && ((Component)collider).CompareTag("PhysicsProp")))
			{
				Log.LogError("CARD BINDER REGISTRATION FAILED | Prefab=" + ((Object)val.spawnPrefab).name + " | No collider tagged PhysicsProp was found for vanilla pickup targeting.");
				return null;
			}
			SetFixedScrapValue(val, 10);
			SilentItemAudio.EnsureFallbacks(val);
			ApplyHeldPositionCorrection(val, BinderHeldPositionCorrection, "Binder");
			ApplyHeldRotationCorrection(val, BinderHeldRotationCorrection, "Binder");
			val.saveItemVariable = true;
			if ((Object)(object)val.spawnPrefab.GetComponent<CardBinderBehaviour>() == (Object)null)
			{
				val.spawnPrefab.AddComponent<CardBinderBehaviour>();
			}
			NetworkPrefabs.RegisterNetworkPrefab(val.spawnPrefab);
			int binderSpawnWeight = BalanceConfig.BinderSpawnWeight;
			if (binderSpawnWeight > 0)
			{
				Items.RegisterScrap(val, binderSpawnWeight, (LevelTypes)(-1));
			}
			else
			{
				Items.RegisterItem(val);
			}
			Log.LogInfo("CARD BINDER REGISTERED | Asset=CardBinderItem | Prefab=" + ((Object)val.spawnPrefab).name + " | " + $"InitialValue={10} | SpawnWeight={binderSpawnWeight}");
			return val;
		}

		private static void ApplyHeldPositionCorrection(Item item, Vector3 correction, string type)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: 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)
			if (HeldPositionAdjustedItems.Add(item))
			{
				_ = item.positionOffset;
				item.positionOffset += correction;
			}
		}

		private static void ApplyHeldRotationCorrection(Item item, Vector3 correction, string type)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: 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)
			if (HeldRotationAdjustedItems.Add(item))
			{
				_ = item.rotationOffset;
				item.rotationOffset += correction;
			}
		}
	}
	public static class MyPluginInfo
	{
		public const string PLUGIN_GUID = "LethalCards";

		public const string PLUGIN_NAME = "LethalCards";

		public const string PLUGIN_VERSION = "2.0.1";
	}
}
namespace LethalCards.TerminalCommands
{
	[HarmonyPatch(typeof(Terminal))]
	public static class CollectionTerminalPatch
	{
		private sealed class CollectionPageState
		{
			public int PageIndex;

			public bool Browsing;
		}

		private const string CollectionCommand = "collection";

		private const string CardsCommand = "cards";

		private const string HelpSubcommand = "help";

		private const int CollectionPageSize = 3;

		private static ConditionalWeakTable<Terminal, CollectionPageState> CollectionPages = new ConditionalWeakTable<Terminal, CollectionPageState>();

		internal static void ResetContext()
		{
			CollectionPages = new ConditionalWeakTable<Terminal, CollectionPageState>();
		}

		private static void SetCollectionContext(Terminal terminal, bool browsing)
		{
			GradingNetworkSync.CancelStatusRequest();
			CollectionPageState value = CollectionPages.GetValue(terminal, (Terminal _) => new CollectionPageState());
			if (value.Browsing != browsing)
			{
				value.Browsing = browsing;
			}
		}

		[HarmonyPatch("QuitTerminal")]
		[HarmonyPrefix]
		private static void QuitPrefix(Terminal __instance)
		{
			SetCollectionContext(__instance, browsing: false);
		}

		[HarmonyPatch("BeginUsingTerminal")]
		[HarmonyPrefix]
		private static void BeginPrefix(Terminal __instance)
		{
			SetCollectionContext(__instance, browsing: false);
		}

		[HarmonyPatch("OnDisable")]
		[HarmonyPrefix]
		private static void DisablePrefix(Terminal __instance)
		{
			SetCollectionContext(__instance, browsing: false);
		}

		[HarmonyPatch("ParsePlayerSentence")]
		[HarmonyPrefix]
		[HarmonyPriority(800)]
		private static bool ParsePlayerSentencePrefix(Terminal __instance, ref TerminalNode __result)
		{
			if ((Object)(object)__instance == (Object)null)
			{
				return true;
			}
			GradingNetworkSync.CancelStatusRequest();
			string text = __instance.screenText.text.Substring(__instance.screenText.text.Length - __instance.textAdded).Trim().ToLowerInvariant();
			if (CollectionPages.GetValue(__instance, (Terminal _) => new CollectionPageState()).Browsing)
			{
				switch (text)
				{
				case "next":
				case "prev":
				case "previous":
					text = "collection " + ((text == "next") ? "next" : "previous");
					break;
				}
			}
			int num;
			switch (text)
			{
			case "grading":
			case "grades":
			{
				NetworkManager singleton = NetworkManager.Singleton;
				Plugin.Log.LogInfo($"GRADING COMMAND | Command={text} | IsHost={singleton != null && singleton.IsHost} | " + $"IsServer={singleton != null && singleton.IsServer} | IsClient={singleton != null && singleton.IsClient} | " + "LocalClientId=" + (((Object)(object)singleton != (Object)null) ? singleton.LocalClientId.ToString() : "<none>") + " | " + $"RuntimeJobCount={GradingManager.Jobs.Count}");
				SetCollectionContext(__instance, browsing: false);
				TerminalNode val = ScriptableObject.CreateInstance<TerminalNode>();
				val.clearPreviousText = true;
				if ((Object)(object)singleton != (Object)null && !singleton.IsServer)
				{
					val.displayText = "\nLETHAL CARDS GRADING STATUS\n\nRetrieving grading status...\n\n";
					if (!GradingNetworkSync.RequestStatus(delegate(int jobCount, string display)
					{
						if ((Object)(object)__instance == (Object)null)
						{
							Plugin.Log.LogWarning("GRADING RESPONSE BLOCKED | Reason=TerminalDestroyedBeforeDisplay");
						}
						else if (!__instance.terminalInUse)
						{
							Plugin.Log.LogWarning("GRADING RESPONSE BLOCKED | Reason=TerminalNoLongerInUse");
						}
						else
						{
							TerminalNode val3 = ScriptableObject.CreateInstance<TerminalNode>();
							val3.clearPreviousText = true;
							val3.displayText = display;
							Plugin.Log.LogInfo($"GRADING CLIENT DISPLAY | JobCount={jobCount} | OutputLength={display?.Length ?? 0}");
							__instance.LoadNewNode(val3);
						}
					}))
					{
						val.displayText = "\nLETHAL CARDS GRADING STATUS\n\nUnable to contact the server. Try grades again.\n\n";
					}
				}
				else
				{
					val.displayText = BuildGradingText(text);
				}
				__result = val;
				return false;
			}
			default:
				num = ((text.StartsWith("cards", StringComparison.Ordinal) && text.Length > "cards".Length && char.IsWhiteSpace(text["cards".Length])) ? 1 : 0);
				break;
			case "cards":
				num = 1;
				break;
			}
			bool flag = (byte)num != 0;
			bool flag2 = flag && text.Substring("cards".Length).Trim() == "help";
			if (!flag && text != "collection" && (!text.StartsWith("collection", StringComparison.Ordinal) || text.Length <= "collection".Length || !char.IsWhiteSpace(text["collection".Length])))
			{
				SetCollectionContext(__instance, browsing: false);
				return true;
			}
			SetCollectionContext(__instance, !flag);
			string query = (flag ? "" : text.Substring("collection".Length).Trim());
			Plugin.Log.LogInfo("TERMINAL: LETHAL CARDS command received | Command=" + (flag ? "cards" : "collection"));
			TerminalNode val2 = ScriptableObject.CreateInstance<TerminalNode>();
			val2.clearPreviousText = true;
			val2.displayText = ((!flag) ? BuildCollectionResponse(__instance, query) : (flag2 ? BuildHelpText() : "\nUnknown Lethal Cards command.\nType \"cards help\" for available commands.\n\n"));
			__result = val2;
			return false;
		}

		private static string BuildHelpText()
		{
			return "\n=== LETHAL CARDS COMMANDS ===\n\ncollection\nView your discovered cards and variants.\n\ncollection next / previous\nMove between collection pages.\n\ncollection page <number>\nView a specific collection page.\n\ncollection <card name>\nView detailed collection information for one card.\n\nnext / prev / previous\nNavigate while browsing collection.\n\ngrading / grades\nView grading status and ready results.\n\ncards help\nDisplay this help screen.\n\n";
		}

		private static string NormalizeCardName(string value)
		{
			return CardDatabase.NormalizeName(value);
		}

		private static string BuildCardDetailText(string query)
		{
			string text = NormalizeCardName(query);
			CardDefinition cardDefinition = null;
			foreach (CardDefinition card in CardDatabase.Cards)
			{
				if (text.Length != 0 && !(NormalizeCardName(card.DisplayName) != text))
				{
					if (cardDefinition != null)
					{
						return "\nMore than one card matches that name.\nUse \"collection\" to view all cards.\n\n";
					}
					cardDefinition = card;
				}
			}
			if (cardDefinition == null)
			{
				return "\nCard not found.\n\nUse \"collection\" to view all cards.\nExample: collection ghost girl\n\n";
			}
			string text2 = cardDefinition.SetNumber.ToString("D3");
			bool flag = CollectionManager.HasCard(cardDefinition.CardId);
			CardVariant[] array = (CardVariant[])Enum.GetValues(typeof(CardVariant));
			int num = 0;
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.AppendLine();
			stringBuilder.AppendLine("=== " + cardDefinition.DisplayName.ToUpperInvariant() + " ===");
			stringBuilder.AppendLine();
			stringBuilder.AppendLine("Set: " + cardDefinition.SetId);
			stringBuilder.AppendLine("Set #: " + text2);
			if (!cardDefinition.IsImplemented)
			{
				stringBuilder.AppendLine("Not yet available in packs.");
			}
			stringBuilder.AppendLine("Discovered: " + (flag ? "Yes" : "No"));
			stringBuilder.AppendLine();
			stringBuilder.AppendLine("Variants:");
			CardVariant[] array2 = array;
			for (int i = 0; i < array2.Length; i++)
			{
				CardVariant variant = array2[i];
				bool flag2 = CollectionManager.HasVariant(cardDefinition.CardId, variant);
				if (flag2)
				{
					num++;
				}
				string text3 = Regex.Replace(variant.ToString(), "([a-z])([A-Z])", "$1 $2");
				stringBuilder.AppendLine("[" + (flag2 ? "X" : " ") + "] " + text3);
			}
			stringBuilder.AppendLine();
			stringBuilder.AppendLine($"Variants Found: {num} / {array.Length}");
			stringBuilder.AppendLine();
			return stringBuilder.ToString();
		}

		private static string BuildCollectionResponse(Terminal terminal, string query)
		{
			CollectionPageState value = CollectionPages.GetValue(terminal, (Terminal _) => new CollectionPageState());
			if (query.Length == 0)
			{
				value.PageIndex = 0;
			}
			else
			{
				switch (query)
				{
				case "next":
					value.PageIndex++;
					break;
				case "previous":
				case "prev":
					value.PageIndex--;
					break;
				default:
					if (!query.StartsWith("page", StringComparison.Ordinal) || query.Length <= 4 || !char.IsWhiteSpace(query[4]))
					{
						return BuildCardDetailText(query);
					}
					goto case "page";
				case "page":
				{
					if (!int.TryParse(query.Substring(4).Trim(), out var result) || result < 1)
					{
						return "\nUse \"collection page <number>\" with a positive page number.\n\n";
					}
					value.PageIndex = result - 1;
					break;
				}
				}
			}
			int num = Math.Max(1, (CardDatabase.Cards.Count + 3 - 1) / 3);
			value.PageIndex = Math.Max(0, Math.Min(value.PageIndex, num - 1));
			return BuildCollectionText(value.PageIndex);
		}

		private static string BuildCollectionText(int pageIndex)
		{
			StringBuilder stringBuilder = new StringBuilder();
			CardVariant[] array = (CardVariant[])Enum.GetValues(typeof(CardVariant));
			int num = 0;
			int num2 = 0;
			CardDefinition[] array2 = CardDatabase.Cards.OrderBy<CardDefinition, string>((CardDefinition cardDefinition2) => cardDefinition2.SetId, StringComparer.Ordinal).ThenBy((CardDefinition cardDefinition2) => cardDefinition2.SetNumber).ToArray();
			int num3 = Math.Max(1, (array2.Length + 3 - 1) / 3);
			pageIndex = Math.Max(0, Math.Min(pageIndex, num3 - 1));
			int num4 = pageIndex * 3;
			int num5 = Math.Min(num4 + 3, array2.Length);
			CardDefinition[] array3 = array2;
			foreach (CardDefinition card in array3)
			{
				if (CollectionManager.HasCard(card.CardId))
				{
					num++;
				}
				num2 += array.Count((CardVariant variant2) => CollectionManager.HasVariant(card.CardId, variant2));
			}
			stringBuilder.AppendLine();
			stringBuilder.AppendLine("=== LETHAL CARDS COLLECTION ===");
			stringBuilder.AppendLine($"Page {pageIndex + 1} / {num3}");
			stringBuilder.AppendLine();
			for (int num7 = num4; num7 < num5; num7++)
			{
				CardDefinition cardDefinition = array2[num7];
				stringBuilder.AppendLine($"{cardDefinition.SetId}-{cardDefinition.SetNumber:D3} - {cardDefinition.DisplayName}");
				if (!cardDefinition.IsImplemented)
				{
					stringBuilder.AppendLine("  Not yet available in packs.");
				}
				CardVariant[] array4 = array;
				for (int num6 = 0; num6 < array4.Length; num6++)
				{
					CardVariant variant = array4[num6];
					bool flag = CollectionManager.HasVariant(cardDefinition.CardId, variant);
					string text = Regex.Replace(variant.ToString(), "([a-z])([A-Z])", "$1 $2");
					stringBuilder.AppendLine("  [" + (flag ? "X" : " ") + "] " + text);
				}
				stringBuilder.AppendLine();
			}
			stringBuilder.AppendLine($"Cards Discovered: {num} / {CardDatabase.Cards.Count}");
			stringBuilder.AppendLine($"Variants Discovered: {num2} / {CardDatabase.Cards.Count * array.Length}");
			if (pageIndex > 0)
			{
				stringBuilder.AppendLine("Previous: collection previous");
			}
			if (pageIndex + 1 < num3)
			{
				stringBuilder.AppendLine("Next: collection next");
			}
			stringBuilder.AppendLine();
			stringBuilder.AppendLine("Type \"collection <card name>\" for details.");
			stringBuilder.AppendLine("While browsing: next / prev / previous.");
			stringBuilder.AppendLine("Type \"cards help\" for Lethal Cards commands.");
			stringBuilder.AppendLine();
			return stringBuilder.ToString();
		}

		internal static string BuildGradingText(string command)
		{
			StringBuilder stringBuilder = new StringBuilder("\nLETHAL CARDS GRADING STATUS\n\n");
			int currentDay = GradingDayManager.CurrentDay;
			if (GradingManager.Jobs.Count == 0)
			{
				stringBuilder.AppendLine("No cards are currently in grading.");
			}
			foreach (GradingJob job in GradingManager.Jobs)
			{
				long num = (long)currentDay - (long)job.SubmittedDay;
				string text = ((num <= 0) ? "Processing Order..." : (num switch
				{
					2L => "Shipping Order...", 
					1L => "Assessing Grade...", 
					_ => "Ready for pickup!", 
				}));
				bool flag = num >= 3;
				string displayName = CardNameFormatter.GetDisplayName(CardDatabase.GetById(job.CardId)?.DisplayName ?? job.CardId, job.Variant);
				stringBuilder.AppendLine(displayName);
				stringBuilder.AppendLine("Status: " + text);
				if (flag)
				{
					stringBuilder.AppendLine($"Grade: {job.Grade}");
					stringBuilder.AppendLine(job.FinalValue.HasValue ? $"Value: ${job.FinalValue.Value}" : "Value: unavailable");
				}
				stringBuilder.AppendLine();
				Plugin.Log.LogDebug($"GRADING STATUS | CardId={job.CardId} | Variant={job.Variant} | DisplayName=\"{displayName}\" | SubmittedDay={job.SubmittedDay} | " + $"CurrentDay={currentDay} | DaysElapsed={num} | Status=\"{text}\" | GradeVisible={flag}" + $" | ValueVisible={flag}" + (flag ? $" | Grade={job.Grade} | FinalValue={job.FinalValue}" : ""));
			}
			return stringBuilder.ToString();
		}
	}
}
namespace LethalCards.ShipDisplay
{
	internal static class ShipCardDisplayConfig
	{
		private const string Section = "Ship Card Display";

		private static readonly Vector3 DefaultLocalPosition = new Vector3(-0.76f, 2.44f, -4.58f);

		private static readonly Vector3 DefaultLocalEulerAngles = new Vector3(0f, 180f, 0f);

		private static readonly Vector3[] PreviousDefaultLocalPositions = (Vector3[])(object)new Vector3[2]
		{
			new Vector3(-0.87f, 1.1f, -5.11f),
			new Vector3(-0.87f, 1.45f, -5.11f)
		};

		internal static Vector3 LocalPosition { get; private set; } = Vector3.zero;

		internal static Vector3 LocalEulerAngles { get; private set; } = Vector3.zero;

		internal static void Load(ConfigFile config)
		{
			//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00da: Unknown result type (might be due to invalid IL or missing references)
			//IL_0157: Unknown result type (might be due to invalid IL or missing references)
			//IL_015e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0175: Unknown result type (might be due to invalid IL or missing references)
			//IL_0189: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0117: Unknown result type (might be due to invalid IL or missing references)
			//IL_011c: Unknown result type (might be due to invalid IL or missing references)
			//IL_012d: Unknown result type (might be due to invalid IL or missing references)
			//IL_013e: Unknown result type (might be due to invalid IL or missing references)
			ConfigEntry<float> val = BindEntry(config, "PositionX", DefaultLocalPosition.x, "Initial ship-relative X position used only when this save has no authoritative furniture placement. Press P in the ship to log ship-relative coordinates and camera surface hits.");
			ConfigEntry<float> val2 = BindEntry(config, "PositionY", DefaultLocalPosition.y, "Initial ship-relative Y position used only when this save has no authoritative furniture placement. Existing furniture saves are never overridden.");
			ConfigEntry<float> val3 = BindEntry(config, "PositionZ", DefaultLocalPosition.z, "Initial ship-relative Z position used only when this save has no authoritative furniture placement. Press P in the ship to log ship-relative coordinates and camera surface hits.");
			ConfigEntry<float> val4 = BindEntry(config, "RotationX", DefaultLocalEulerAngles.x, "Initial ship-relative X rotation in degrees, used only before the cabinet has a saved furniture placement.");
			ConfigEntry<float> val5 = BindEntry(config, "RotationY", DefaultLocalEulerAngles.y, "Initial ship-relative Y rotation in degrees, used only before the cabinet has a saved furniture placement.");
			ConfigEntry<float> val6 = BindEntry(config, "RotationZ", DefaultLocalEulerAngles.z, "Initial ship-relative Z rotation in degrees, used only before the cabinet has a saved furniture placement.");
			Vector3 defaultLocalPosition = default(Vector3);
			((Vector3)(ref defaultLocalPosition))..ctor(val.Value, val2.Value, val3.Value);
			Vector3 val7 = default(Vector3);
			((Vector3)(ref val7))..ctor(val4.Value, val5.Value, val6.Value);
			if (IsRecognizedPreviousDefault(defaultLocalPosition, val7))
			{
				Vector3 val8 = defaultLocalPosition;
				val.Value = DefaultLocalPosition.x;
				val2.Value = DefaultLocalPosition.y;
				val3.Value = DefaultLocalPosition.z;
				defaultLocalPosition = DefaultLocalPosition;
				Plugin.Log.LogInfo("SHIP CARD DISPLAY CONFIG MIGRATED | " + $"PreviousLocalPosition={val8} | " + $"NewLocalPosition={DefaultLocalPosition}");
			}
			LocalPosition = defaultLocalPosition;
			LocalEulerAngles = val7;
			config.Save();
			Plugin.Log.LogInfo($"SHIP CARD DISPLAY CONFIG | LocalPosition={LocalPosition} | " + $"LocalRotation={LocalEulerAngles}");
		}

		private static bool IsRecognizedPreviousDefault(Vector3 position, Vector3 rotation)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: 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)
			if (!Approximately(rotation, DefaultLocalEulerAngles))
			{
				return false;
			}
			Vector3[] previousDefaultLocalPositions = PreviousDefaultLocalPositions;
			foreach (Vector3 right in previousDefaultLocalPositions)
			{
				if (Approximately(position, right))
				{
					return true;
				}
			}
			return false;
		}

		private static bool Approximately(Vector3 left, Vector3 right)
		{
			//IL_0000: 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_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			if (Mathf.Approximately(left.x, right.x) && Mathf.Approximately(left.y, right.y))
			{
				return Mathf.Approximately(left.z, right.z);
			}
			return false;
		}

		private static ConfigEntry<float> BindEntry(ConfigFile config, string key, float defaultValue, string description)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Expected O, but got Unknown
			return config.Bind<float>("Ship Card Display", key, defaultValue, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty<object>()));
		}
	}
	public sealed class ShipCardDisplayController : NetworkBehaviour
	{
		private enum InteractionResult
		{
			Success,
			AlreadyEmpty,
			InventoryFull,
			Busy,
			Synchronizing,
			AttachmentFailed,
			ActionChanged,
			Occluded,
			Failed
		}

		private sealed class PendingAttachment
		{
			internal ulong TransactionId { get; }

			internal ulong ClientId { get; }

			internal int InventorySlot { get; }

			internal ulong NetworkObjectId { get; }

			internal string Action { get; }

			internal int Attempts { get; set; }

			internal float ResponseDeadline { get; set; }

			internal PendingAttachment(ulong transactionId, ulong clientId, int inventorySlot, ulong networkObjectId, string action)
			{
				TransactionId = transactionId;
				ClientId = clientId;
				InventorySlot = inventorySlot;
				NetworkObjectId = networkObjectId;
				Action = action;
			}
		}

		private const float InteractionDistancePadding = 1f;

		private const float AttachRetryTimeout = 2f;

		private const float AttachmentResponseTimeout = 2.5f;

		private const int MaximumAttachmentAttempts = 2;

		private const float HeldStateSettleTimeout = 0.6f;

		private const float LocalRequestTimeout = 7f;

		private const float InteractionDebounce = 0.12f;

		private const float DiagnosticRateLimit = 2f;

		private const float MaximumSnapshotOriginOffset = 1.25f;

		private const int InteractionCollisionMask = -1;

		private static readonly MethodInfo? SwitchToItemSlotMethod = AccessTools.Method(typeof(PlayerControllerB), "SwitchToItemSlot", new Type[2]
		{
			typeof(int),
			typeof(GrabbableObject)
		}, (Type[])null);

		private readonly NetworkList<ShipCardDisplaySlotState> networkSlots = new NetworkList<ShipCardDisplaySlotState>();

		private readonly Transform?[] slotAnchors = (Transform?[])(object)new Transform[33];

		private readonly GameObject?[] slotVisuals = (GameObject?[])(object)new GameObject[33];

		private readonly Dictionary<ulong, PendingAttachment> pendingAttachments = new Dictionary<ulong, PendingAttachment>();

		private readonly HashSet<ulong> activeAttachmentCoroutines = new HashSet<ulong>();

		private readonly HashSet<ulong> terminalTransactions = new HashSet<ulong>();

		private bool transactionInProgress;

		private ulong activeTransactionId;

		private ulong activeTransactionClientId;

		private bool localInteractionPending;

		private float localInteractionPendingUntil;

		private float nextLocalInteractionTime;

		private ScanNodeProperties? aggregateScanNode;

		private ulong nextTransactionId = 1uL;

		private static bool crewWipeHandledThisRound;

		private static readonly HashSet<ShipCardDisplayController> SpawnedControllers = new HashSet<ShipCardDisplayController>();

		private static readonly Dictionary<string, float> LastDiagnosticTimes = new Dictionary<string, float>();

		public static event Action<int, string, CardVariant, int, int, int, bool>? AuthoritativeSlotChanged;

		public override void OnNetworkSpawn()
		{
			((NetworkBehaviour)this).OnNetworkSpawn();
			SpawnedControllers.Add(this);
			CacheSlotAnchors();
			networkSlots.OnListChanged += OnSlotListChanged;
			if (((NetworkBehaviour)this).IsServer)
			{
				ShipCardDisplayStoredCard[] array = ShipCardDisplaySaveManager.LoadForCurrentSave();
				networkSlots.Clear();
				for (int i = 0; i < 33; i++)
				{
					networkSlots.Add(ShipCardDisplaySlotState.FromStored(array[i]));
				}
			}
			RefreshAllVisuals();
			RefreshAggregateScanNode();
		}

		public override void OnNetworkDespawn()
		{
			SpawnedControllers.Remove(this);
			networkSlots.OnListChanged -= OnSlotListChanged;
			if (activeTransactionId != 0L)
			{
				SendTerminalResult(activeTransactionClientId, activeTransactionId, InteractionResult.Failed, "Canceled", "Reason=ControllerDespawned", sendToClient: false);
			}
			foreach (PendingAttachment value in pendingAttachments.Values)
			{
				SendTerminalResult(value.ClientId, value.TransactionId, InteractionResult.AttachmentFailed, "Canceled", "Reason=ControllerDespawnedDuringAttachment", sendToClient: false);
			}
			pendingAttachments.Clear();
			activeAttachmentCoroutines.Clear();
			localInteractionPending = false;
			ClearVisuals();
			((NetworkBehaviour)this).OnNetworkDespawn();
		}

		private void OnEnable()
		{
			if (((NetworkBehaviour)this).IsSpawned)
			{
				CacheSlotAnchors();
				RefreshAllVisuals();
				RefreshAggregateScanNode();
			}
		}

		internal bool TryGetSlotState(int slotIndex, out ShipCardDisplaySlotState state)
		{
			if (slotIndex >= 0 && slotIndex < networkSlots.Count)
			{
				state = networkSlots[slotIndex];
				return true;
			}
			state = ShipCardDisplaySlotState.Empty;
			return false;
		}

		internal void RequestDeposit(PlayerControllerB player, Ray interactionRay)
		{
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			GrabbableObject selectedCard = ShipCardDisplayInteractionPatch.GetSelectedCard(player);
			NetworkObject val = default(NetworkObject);
			if (((NetworkBehaviour)this).IsSpawned && !((Object)(object)player == (Object)null) && !((Object)(object)selectedCard == (Object)null) && ((Component)selectedCard).TryGetComponent<NetworkObject>(ref val) && TryBeginLocalInteraction())
			{
				NetworkObjectReference requestedCard = new NetworkObjectReference(val);
				Vector3 localRayOrigin = ((Component)this).transform.InverseTransformPoint(((Ray)(ref interactionRay)).origin);
				Vector3 val2 = ((Component)this).transform.InverseTransformDirection(((Ray)(ref interactionRay)).direction);
				InteractServerRpc(isDeposit: true, -1, requestedCard, localRayOrigin, ((Vector3)(ref val2)).normalized);
			}
		}

		internal void RequestWithdrawal(PlayerControllerB player, int slotIndex, Ray interactionRay)
		{
			//IL_001f: 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_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: 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_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			if (((NetworkBehaviour)this).IsSpawned && !((Object)(object)player == (Object)null) && TryBeginLocalInteraction())
			{
				Vector3 localRayOrigin = ((Component)this).transform.InverseTransformPoint(((Ray)(ref interactionRay)).origin);
				Vector3 val = ((Component)this).transform.InverseTransformDirection(((Ray)(ref interactionRay)).direction);
				InteractServerRpc(isDeposit: false, slotIndex, default(NetworkObjectReference), localRayOrigin, ((Vector3)(ref val)).normalized);
			}
		}

		[ServerRpc(RequireOwnership = false)]
		private void InteractServerRpc(bool isDeposit, int requestedSlot, NetworkObjectReference requestedCard, Vector3 localRayOrigin, Vector3 localRayDirection, ServerRpcParams rpcParams = default(ServerRpcParams))
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f3: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_011e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0123: Unknown result type (might be due to invalid IL or missing references)
			//IL_0125: Unknown result type (might be due to invalid IL or missing references)
			//IL_0186: Unknown result type (might be due to invalid IL or missing references)
			//IL_018d: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f5: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
			{
				FastBufferWriter val = ((NetworkBehaviour)this).__beginSendServerRpc(3387963691u, rpcParams, (RpcDelivery)0);
				((FastBufferWriter)(ref val)).WriteValueSafe<bool>(ref isDeposit, default(ForPrimitives));
				BytePacker.WriteValueBitPacked(val, requestedSlot);
				((FastBufferWriter)(ref val)).WriteValueSafe<NetworkObjectReference>(ref requestedCard, default(ForNetworkSerializable));
				((FastBufferWriter)(ref val)).WriteValueSafe(ref localRayOrigin);
				((FastBufferWriter)(ref val)).WriteValueSafe(ref localRayDirection);
				((NetworkBehaviour)this).__endSendServerRpc(ref val, 3387963691u, rpcParams, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
			{
				base.__rpc_exec_stage = (__RpcExecStage)0;
				ulong senderClientId = rpcParams.Receive.SenderClientId;
				ulong transactionId = nextTransactionId++;
				LogTransaction(transactionId, senderClientId, isDeposit ? "Deposit" : "Withdraw", "Received", $"RequestedDisplaySlot={requestedSlot + 1} | " + $"RequestedObject={((NetworkObjectReference)(ref requestedCard)).NetworkObjectId} | " + $"LocalRayOrigin={localRayOrigin} | LocalRayDirection={localRayDirection}");
				if (transactionInProgress || !((NetworkBehaviour)this).IsSpawned)
				{
					SendTerminalResult(senderClientId, transactionId, InteractionResult.Busy, "Rejected", transactionInProgress ? "Reason=Busy" : "Reason=ControllerNotSpawned");
					return;
				}
				transactionInProgress = true;
				activeTransactionId = transactionId;
				activeTransactionClientId = senderClientId;
				((MonoBehaviour)this).StartCoroutine(ProcessInteraction(senderClientId, transactionId, isDeposit, requestedSlot, requestedCard, localRayOrigin, localRayDirection));
			}
		}

		private IEnumerator ProcessInteraction(ulong senderClientId, ulong transactionId, bool isDeposit, int requestedSlot, NetworkObjectReference requestedCard, Vector3 localRayOrigin, Vector3 localRayDirection)
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				if (!TryResolvePlayer(senderClientId, out PlayerControllerB player))
				{
					Reject(senderClientId, transactionId, "PlayerNotFound");
					yield break;
				}
				LogTransaction(transactionId, senderClientId, isDeposit ? "Deposit" : "Withdraw", "PlayerResolved", $"SelectedInventorySlot={player.currentItemSlot} | " + "ServerHeld=" + (((Object)(object)player.currentlyHeldObjectServer == (Object)null) ? "none" : ((NetworkBehaviour)player.currentlyHeldObjectServer).NetworkObjectId.ToString()));
				if (!ValidatePlayerState(player, out string failure))
				{
					Reject(senderClientId, transactionId, failure);
					yield break;
				}
				if (!TryValidateInteractionSnapshot(player, localRayOrigin, localRayDirection, transactionId, out int selectedSlot, out string failure2, out string details))
				{
					Reject(senderClientId, transactionId, failure2, details);
					yield break;
				}
				if (!isDeposit && selectedSlot != requestedSlot)
				{
					Reject(senderClientId, transactionId, "InvalidSlotTarget", $"RequestedSlot={requestedSlot + 1} | SnapshotSlot={selectedSlot + 1}");
					yield break;
				}
				float deadline;
				if (isDeposit)
				{
					deadline = Time.realtimeSinceStartup + 0.6f;
					while (!IsHeldCardAuthoritativelyReady(player, requestedCard) && Time.realtimeSinceStartup < deadline)
					{
						yield return null;
					}
					string failure3;
					string details2;
					if (!IsHeldCardAuthoritativelyReady(player, requestedCard))
					{
						if (HasRequestedCardSelectionChanged(player, requestedCard))
						{
							CancelChangedInteraction(senderClientId, transactionId, "RequestedHeldCardNoLongerSelected");
						}
						else
						{
							RejectRetryable(senderClientId, transactionId, "HeldCardSynchronizationTimeout");
						}
					}
					else if (!ValidateCurrentPlayerAccess(player, transactionId, out failure3, out details2))
					{
						Reject(senderClientId, transactionId, failure3, details2);
					}
					else
					{
						TryDeposit(player, requestedCard, senderClientId, transactionId);
					}
					yield break;
				}
				deadline = Time.realtimeSinceStartup + 0.6f;
				while (!IsEmptySelectedSlotAuthoritativelyReady(player) && Time.realtimeSinceStartup < deadline)
				{
					yield return null;
				}
				string failure4;
				string details3;
				if (!IsEmptySelectedSlotAuthoritativelyReady(player))
				{
					if (HasSettledNonEmptySelection(player))
					{
						CancelChangedInteraction(senderClientId, transactionId, "SelectedInventorySlotNoLongerEmpty");
					}
					else
					{
						RejectRetryable(senderClientId, transactionId, "InventorySynchronizationTimeout");
					}
				}
				else if (!ValidateCurrentPlayerAccess(player, transactionId, out failure4, out details3))
				{
					Reject(senderClientId, transactionId, failure4, details3);
				}
				else
				{
					TryWithdraw(player, requestedSlot, senderClientId, transactionId);
				}
			}
			finally
			{
				ShipCardDisplayController shipCardDisplayController = this;
				shipCardDisplayController.transactionInProgress = false;
				if (shipCardDisplayController.activeTransactionId == transactionId)
				{
					shipCardDisplayController.activeTransactionId = 0uL;
					shipCardDisplayController.activeTransactionClientId = 0uL;
				}
				if (!shipCardDisplayController.terminalTransactions.Contains(transactionId) && !shipCardDisplayController.pendingAttachments.ContainsKey(transactionId))
				{
					Plugin.Log.LogError("SHIP CARD DISPLAY TRANSACTION ENDED WITHOUT RESULT | " + $"Transaction={transactionId} | Client={senderClientId}");
					shipCardDisplayController.SendTerminalResult(senderClientId, transactionId, InteractionResult.Failed, "Failed", "Reason=UnexpectedCoroutineTermination");
				}
			}
		}

		private void TryDeposit(PlayerControllerB player, NetworkObjectReference requestedCard, ulong senderClientId, ulong transactionId)
		{
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f7: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager singleton = NetworkManager.Singleton;
			NetworkObject val = default(NetworkObject);
			if ((Object)(object)singleton == (Object)null || !((NetworkObjectReference)(ref requestedCard)).TryGet(ref val, singleton))
			{
				Reject(senderClientId, transactionId, "InvalidCardReference");
				return;
			}
			GrabbableObject component = ((Component)val).GetComponent<GrabbableObject>();
			CardInstanceData component2 = ((Component)val).GetComponent<CardInstanceData>();
			NetworkItemConsumption component3 = ((Component)val).GetComponent<NetworkItemConsumption>();
			CardDefinition cardDefinition = (((Object)(object)component2 == (Object)null) ? null : CardDatabase.GetById(component2.CardId));
			if ((Object)(object)component == (Object)null || (Object)(object)component2 == (Object)null || (Object)(object)component3 == (Object)null || cardDefinition == null || cardDefinition.SetNumber < 1 || cardDefinition.SetNumber > 33 || !NetworkItemConsumption.IsValidHolder(player, component))
			{
				Reject(senderClientId, transactionId, "InvalidHeldCard", Plugin.EnableDebugLogging ? BuildHeldCardDiagnostic(player, requestedCard, val, component, component2, component3, cardDefinition) : string.Empty);
				return;
			}
			int num = FindInventorySlot(player, component);
			if (num < 0 || num != player.currentItemSlot)
			{
				Reject(senderClientId, transactionId, "HeldCardSlotMismatch", Plugin.EnableDebugLogging ? BuildHeldCardDiagnostic(player, requestedCard, val, component, component2, component3, cardDefinition) : string.Empty);
				return;
			}
			int num2 = cardDefinition.SetNumber - 1;
			ShipCardDisplayStoredCard shipCardDisplayStoredCard = ((num2 < networkSlots.Count) ? networkSlots[num2].ToStored() : null);
			if (shipCardDisplayStoredCard != null && !CanReconstruct(shipCardDisplayStoredCard))
			{
				Reject(senderClientId, transactionId, "StoredCardPrefabUnavailable");
				return;
			}
			ShipCardDisplayStoredCard shipCardDisplayStoredCard2 = new ShipCardDisplayStoredCard(cardDefinition.CardId, component2.Variant, component2.Grade, Math.Max(0, component2.UngradedValue), Math.Max(0, component2.FinalValue));
			if (!component3.TryConsumeServer())
			{
				Reject(senderClientId, transactionId, "CardConsumptionFailed");
				return;
			}
			if (!ShipCardDisplaySaveManager.TryCommitSlot(num2, shipCardDisplayStoredCard2))
			{
				RestoreIncomingAfterFailure(player, num, shipCardDisplayStoredCard2);
				Reject(senderClientId, transactionId, "PersistenceFailed");
				return;
			}
			bool awaitingOwnerAttachment = false;
			NetworkObject spawnedNetworkObject = null;
			if (shipCardDisplayStoredCard != null && !TrySpawnIntoInventory(player, num, shipCardDisplayStoredCard, transactionId, "Swap", trackOwnerAttachment: true, out spawnedNetworkObject, out awaitingOwnerAttachment))
			{
				bool flag = ShipCardDisplaySaveManager.TryCommitSlot(num2, shipCardDisplayStoredCard);
				RestoreIncomingAfterFailure(player, num, shipCardDisplayStoredCard2);
				Plugin.Log.LogError($"SHIP CARD DISPLAY SWAP ROLLED BACK | Slot={num2 + 1} | " + $"PersistenceRollback={flag}");
				Reject(senderClientId, transactionId, "CardReconstructionFailed");
				return;
			}
			ApplyNetworkSlot(num2, shipCardDisplayStoredCard2);
			LogTransaction(transactionId, senderClientId, (shipCardDisplayStoredCard == null) ? "Deposit" : "Swap", "Committed", $"DisplaySlot={num2 + 1} | IncomingObject={val.NetworkObjectId} | " + "OutgoingObject=" + (((Object)(object)spawnedNetworkObject == (Object)null) ? "none" : spawnedNetworkObject.NetworkObjectId.ToString()) + " | " + $"AwaitingOwnerAttachment={awaitingOwnerAttachment}");
			Plugin.Log.LogInfo("SHIP CARD DISPLAY " + ((shipCardDisplayStoredCard == null) ? "DEPOSIT" : "SWAP") + " | " + $"Player={player.playerUsername} | Slot={num2 + 1} | " + $"Incoming={shipCardDisplayStoredCard2.CardId}/{shipCardDisplayStoredCard2.Variant}/Grade{shipCardDisplayStoredCard2.Grade}/Value{shipCardDisplayStoredCard2.FinalValue}" + ((shipCardDisplayStoredCard == null) ? string.Empty : $" | Outgoing={shipCardDisplayStoredCard.CardId}/{shipCardDisplayStoredCard.Variant}/Grade{shipCardDisplayStoredCard.Grade}/Value{shipCardDisplayStoredCard.FinalValue}"));
			if (!awaitingOwnerAttachment)
			{
				CompleteTransaction(senderClientId, transactionId);
			}
		}

		private void TryWithdraw(PlayerControllerB player, int requestedSlot, ulong senderClientId, ulong transactionId)
		{
			if (requestedSlot < 0 || requestedSlot >= 33 || requestedSlot >= networkSlots.Count)
			{
				Reject(senderClientId, transactionId, "InvalidSlotTarget");
				return;
			}
			ShipCardDisplayStoredCard shipCardDisplayStoredCard = networkSlots[requestedSlot].ToStored();
			if (shipCardDisplayStoredCard == null)
			{
				SendTerminalResult(senderClientId, transactionId, InteractionResult.AlreadyEmpty, "Rejected", "Reason=AlreadyEmpty");
				return;
			}
			if ((Object)(object)player.currentlyHeldObjectServer != (Object)null || player.currentItemSlot < 0 || player.currentItemSlot >= player.ItemSlots.Length || (Object)(object)player.ItemSlots[player.currentItemSlot] != (Object)null)
			{
				SendTerminalResult(senderClientId, transactionId, InteractionResult.InventoryFull, "Rejected", "Reason=InventoryFull");
				return;
			}
			if (!CanReconstruct(shipCardDisplayStoredCard))
			{
				Reject(senderClientId, transactionId, "StoredCardPrefabUnavailable");
				return;
			}
			int currentItemSlot = player.currentItemSlot;
			if (!ShipCardDisplaySaveManager.TryCommitSlot(requestedSlot, null))
			{
				Reject(senderClientId, transactionId, "PersistenceFailed");
				return;
			}
			if (!TrySpawnIntoInventory(player, currentItemSlot, shipCardDisplayStoredCard, transactionId, "Withdraw", trackOwnerAttachment: true, out NetworkObject spawnedNetworkObject, out bool awaitingOwnerAttachment))
			{
				bool flag = ShipCardDisplaySaveManager.TryCommitSlot(requestedSlot, shipCardDisplayStoredCard);
				Plugin.Log.LogError($"SHIP CARD DISPLAY WITHDRAW ROLLED BACK | Slot={requestedSlot + 1} | " + $"PersistenceRollback={flag}");
				Reject(senderClientId, transactionId, "CardReconstructionFailed");
				return;
			}
			ApplyNetworkSlot(requestedSlot, null);
			LogTransaction(transactionId, senderClientId, "Withdraw", "Committed", $"DisplaySlot={requestedSlot + 1} | " + "OutgoingObject=" + (((spawnedNetworkObject != null) ? spawnedNetworkObject.NetworkObjectId.ToString() : null) ?? "none") + " | " + $"AwaitingOwnerAttachment={awaitingOwnerAttachment}");
			Plugin.Log.LogInfo("SHIP CARD DISPLAY WITHDRAW | Player=" + player.playerUsername + " | " + $"Slot={requestedSlot + 1} | Card={shipCardDisplayStoredCard.CardId}/{shipCardDisplayStoredCard.Variant}/" + $"Grade{shipCardDisplayStoredCard.Grade}/Value{shipCardDisplayStoredCard.FinalValue}");
			if (!awaitingOwnerAttachment)
			{
				CompleteTransaction(senderClientId, transactionId);
			}
		}

		private bool TrySpawnIntoInventory(PlayerControllerB player, int inventorySlot, ShipCardDisplayStoredCard storedCard, ulong transactionId, string action, bool trackOwnerAttachment, out NetworkObject? spawnedNetworkObject, out bool awaitingOwnerAttachment)
		{
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_015d: Unknown result type (might be due to invalid IL or missing references)
			spawnedNetworkObject = null;
			awaitingOwnerAttachment = false;
			CardDefinition byId = CardDatabase.GetById(storedCard.CardId);
			GameObject val = byId?.ItemAsset?.spawnPrefab;
			if (byId == null || (Object)(object)val == (Object)null || (Object)(object)StartOfRound.Instance == (Object)null)
			{
				return false;
			}
			GameObject val2 = Object.Instantiate<GameObject>(val, ((Component)player).transform.position, Quaternion.identity, StartOfRound.Instance.propsContainer);
			NetworkObject component = val2.GetComponent<NetworkObject>();
			GrabbableObject component2 = val2.GetComponent<GrabbableObject>();
			CardInstanceData component3 = val2.GetComponent<CardInstanceData>();
			if ((Object)(object)component == (Object)null || (Object)(object)component2 == (Object)null || (Object)(object)component3 == (Object)null)
			{
				Object.Destroy((Object)(object)val2);
				return false;
			}
			component3.InitializeLoaded(byId, storedCard.Variant, storedCard.Grade, storedCard.FinalValue, storedCard.UngradedValue);
			try
			{
				component.SpawnWithOwnership(player.actualClientId, false);
				if (!ApplyCardToInventory(player, inventorySlot, component2))
				{
					component.Despawn(true);
					return false;
				}
				spawnedNetworkObject = component;
				bool flag = (Object)(object)NetworkManager.Singleton != (Object)null && player.actualClientId != 0;
				if (trackOwnerAttachment && flag)
				{
					PendingAttachment pendingAttachment = new PendingAttachment(transactionId, player.actualClientId, inventorySlot, component.NetworkObjectId, action);
					pendingAttachments[transactionId] = pendingAttachment;
					awaitingOwnerAttachment = true;
					SendAttachmentAttempt(pendingAttachment);
				}
				else
				{
					AttachCardClientRpc(transactionId, player.actualClientId, inventorySlot, new NetworkObjectReference(component));
				}
				return true;
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError($"SHIP CARD DISPLAY CARD SPAWN FAILED | CardId={storedCard.CardId} | {arg}");
				if (component.IsSpawned)
				{
					component.Despawn(true);
				}
				else
				{
					Object.Destroy((Object)(object)val2);
				}
				return false;
			}
		}

		[ClientRpc]
		private void AttachCardClientRpc(ulong transactionId, ulong playerClientId, int inventorySlot, NetworkObjectReference cardReference)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d8: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Unknown result type (might be due to invalid IL or missing references)
			//IL_0103: Unknown result type (might be due to invalid IL or missing references)
			//IL_0128: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsServer || networkManager.IsHost))
			{
				ClientRpcParams val2 = default(ClientRpcParams);
				FastBufferWriter val = ((NetworkBehaviour)this).__beginSendClientRpc(472588625u, val2, (RpcDelivery)0);
				BytePacker.WriteValueBitPacked(val, transactionId);
				BytePacker.WriteValueBitPacked(val, playerClientId);
				BytePacker.WriteValueBitPacked(val, inventorySlot);
				((FastBufferWriter)(ref val)).WriteValueSafe<NetworkObjectReference>(ref cardReference, default(ForNetworkSerializable));
				((NetworkBehaviour)this).__endSendClientRpc(ref val, 472588625u, val2, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsClient || networkManager.IsHost))
			{
				base.__rpc_exec_stage = (__RpcExecStage)0;
				if (!((NetworkBehaviour)this).IsServer && (transactionId == 0L || activeAttachmentCoroutines.Add(transactionId)))
				{
					((MonoBehaviour)this).StartCoroutine(AttachCardWhenReady(transactionId, playerClientId, inventorySlot, cardReference));
				}
			}
		}

		private IEnumerator AttachCardWhenReady(ulong transactionId, ulong playerClientId, int inventorySlot, NetworkObjectReference cardReference)
		{
			//IL_0023: 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)
			float deadline = Time.realtimeSinceStartup + 2f;
			string terminalReason = "PrerequisitesNotReady";
			NetworkObject val = default(NetworkObject);
			while (Time.realtimeSinceStartup < deadline)
			{
				if (TryResolvePlayer(playerClientId, out PlayerControllerB player) && inventorySlot >= 0 && inventorySlot < player.ItemSlots.Length && ((NetworkObjectReference)(ref cardReference)).TryGet(ref val, (NetworkManager)null) && (Object)(object)val != (Object)null)
				{
					GrabbableObject val2 = player.ItemSlots[inventorySlot];
					GrabbableObject component = ((Component)val).GetComponent<GrabbableObject>();
					bool flag = !((NetworkBehaviour)player).IsOwner || val.IsOwner;
					if ((Object)(object)component != (Object)null && flag && ((Object)(object)val2 == (Object)null || (Object)(object)val2 == (Object)(object)component))
					{
						bool flag2 = ApplyCardToInventory(player, inventorySlot, component);
						if (flag2 && ValidateInventoryPostconditions(player, inventorySlot, component, out terminalReason))
						{
							if (transactionId != 0L)
							{
								activeAttachmentCoroutines.Remove(transactionId);
							}
							LogTransaction(transactionId, playerClientId, "Reconstruction", "OwnerAttached", $"NetworkObject={val.NetworkObjectId} | Slot={inventorySlot} | " + $"Equipped={player.currentItemSlot == inventorySlot}");
							if (((NetworkBehaviour)player).IsOwner && transactionId != 0L)
							{
								ConfirmAttachmentServerRpc(transactionId, val.NetworkObjectId, succeeded: true);
							}
							yield break;
						}
						if (!flag2)
						{
							terminalReason = "ApplyCardToInventoryReturnedFalse";
						}
					}
					else if (!flag)
					{
						terminalReason = "OwnershipNotReady";
					}
					else if ((Object)(object)val2 != (Object)null && (Object)(object)val2 != (Object)(object)component)
					{
						terminalReason = "IntendedSlotOccupied";
					}
				}
				yield return null;
			}
			if (transactionId != 0L)
			{
				activeAttachmentCoroutines.Remove(transactionId);
			}
			PlayerControllerB player2;
			bool flag3 = TryResolvePlayer(playerClientId, out player2) && ((NetworkBehaviour)player2).IsOwner;
			string data = "SHIP CARD DISPLAY INVENTORY ATTACH TIMED OUT | " + $"Transaction={transactionId} | PlayerClientId={playerClientId} | " + $"Slot={inventorySlot} | OwnerClient={flag3} | Reason={terminalReason}" + BuildAttachmentDiagnostic(playerClientId, inventorySlot, cardReference);
			if (flag3)
			{
				Plugin.Log.LogWarning(data);
			}
			else
			{
				Plugin.Log.LogInfo(data);
			}
			if (transactionId != 0 && flag3)
			{
				ConfirmAttachmentServerRpc(transactionId, ((NetworkObjectReference)(ref cardReference)).NetworkObjectId, succeeded: false);
			}
		}

		private static bool ApplyCardToInventory(PlayerControllerB player, int inventorySlot, GrabbableObject card)
		{
			if ((Object)(object)player == (Object)null || (Object)(object)card == (Object)null || inventorySlot < 0 || inventorySlot >= player.ItemSlots.Length)
			{
				return false;
			}
			GrabbableObject val = player.ItemSlots[inventorySlot];
			if ((Object)(object)val != (Object)null && (Object)(object)val != (Object)(object)card)
			{
				return false;
			}
			int num = FindInventorySlot(player, card);
			bool flag = num >= 0;
			if (SwitchToItemSlotMethod == null)
			{
				Plugin.Log.LogError("SHIP CARD DISPLAY INVENTORY ATTACH FAILED | PlayerControllerB.SwitchToItemSlot was not found");
				return false;
			}
			bool flag2 = player.currentItemSlot == inventorySlot;
			try
			{
				if (num >= 0 && num != inventorySlot)
				{
					player.ItemSlots[num] = null;
					if (((NetworkBehaviour)player).IsOwner && (Object)(object)HUDManager.Instance != (Object)null && num < HUDManager.Instance.itemSlotIcons.Length)
					{
						((Behaviour)HUDManager.Instance.itemSlotIcons[num]).enabled = false;
					}
				}
				if (flag2)
				{
					SwitchToItemSlotMethod.Invoke