Decompiled source of DealerSelfSupplySystem v1.2.0

DealerSelfSupplySystem.dll

Decompiled 2 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using DealerSelfSupplySystem;
using DealerSelfSupplySystem.DealerExtension;
using DealerSelfSupplySystem.Persistence;
using DealerSelfSupplySystem.UI;
using DealerSelfSupplySystem.Utils;
using HarmonyLib;
using Il2CppScheduleOne.Economy;
using Il2CppScheduleOne.ItemFramework;
using Il2CppScheduleOne.NPCs;
using Il2CppScheduleOne.Persistence;
using Il2CppScheduleOne.Storage;
using Il2CppScheduleOne.UI;
using Il2CppSystem;
using Il2CppSystem.Collections.Generic;
using MelonLoader;
using MelonLoader.Preferences;
using Microsoft.CodeAnalysis;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: MelonInfo(typeof(Core), "DealerSelfSupplySystem", "1.2.0", "KaikiNoodles", null)]
[assembly: MelonGame("TVGS", "Schedule I")]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("DealerSelfSupplySystem")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+42c67e3802cf2f691e233bb0155ed6cbc6d3c1fe")]
[assembly: AssemblyProduct("DealerSelfSupplySystem")]
[assembly: AssemblyTitle("DealerSelfSupplySystem")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace DealerSelfSupplySystem
{
	public class Config
	{
		public static MelonPreferences_Category balanceCategory;

		public static MelonPreferences_Entry<bool> multipleDealersPerStorage;

		public static MelonPreferences_Entry<bool> dealerStorageUIClosedByDefault;

		public static MelonPreferences_Entry<float> dealerInventoryThreshold;

		public static MelonPreferences_Entry<KeyCode> uiToggleKey;

		public static MelonPreferences_Entry<bool> smallUIMode;

		public static MelonPreferences_Entry<Vector2> uiPosition;

		public static MelonPreferences_Entry<int> maxDealersPerStorage;

		public static MelonPreferences_Entry<float> dealerStorageCheckInterval;

		public static MelonPreferences_Entry<float> dealerCollectionShareRate;

		public Config()
		{
			//IL_0130: Unknown result type (might be due to invalid IL or missing references)
			balanceCategory = MelonPreferences.CreateCategory("DealerSelfSupplySystem");
			multipleDealersPerStorage = balanceCategory.CreateEntry<bool>("MultipleDealersPerStorage", true, (string)null, "Allow multiple dealers to be assigned to the same storage.", false, false, (ValueValidator)null, (string)null);
			maxDealersPerStorage = balanceCategory.CreateEntry<int>("MaxDealersPerStorage", 3, (string)null, "Maximum number of dealers that can be assigned to a single storage when multiple dealers are enabled.", false, false, (ValueValidator)null, (string)null);
			dealerCollectionShareRate = balanceCategory.CreateEntry<float>("DealerCollectionShareRate", 0.5f, (string)null, "Percentage of empty inventory slots a dealer will try to fill when multiple dealers share a storage (0.1-1.0).", false, false, (ValueValidator)null, (string)null);
			dealerStorageUIClosedByDefault = balanceCategory.CreateEntry<bool>("DealerStorageUIClosedByDefault", true, (string)null, "Set the dealer storage UI to be collapsed by default.", false, false, (ValueValidator)null, (string)null);
			dealerInventoryThreshold = balanceCategory.CreateEntry<float>("DealerInventoryThreshold", 0.3f, (string)null, "The inventory threshold for a dealer to be considered low on items (0.0 - 1.0).", false, false, (ValueValidator)null, (string)null);
			dealerStorageCheckInterval = balanceCategory.CreateEntry<float>("DealerStorageCheckInterval", 60f, (string)null, "How often (in seconds) dealers check if they need to collect items from storage.", false, false, (ValueValidator)null, (string)null);
			uiToggleKey = balanceCategory.CreateEntry<KeyCode>("UIToggleKey", (KeyCode)9, (string)null, "Key used to toggle the dealer assignment UI panel.", false, false, (ValueValidator)null, (string)null);
			smallUIMode = balanceCategory.CreateEntry<bool>("SmallUIMode", true, (string)null, "Use a more compact UI to avoid blocking storage slots.", false, false, (ValueValidator)null, (string)null);
			uiPosition = balanceCategory.CreateEntry<Vector2>("UIPosition", new Vector2(1f, 1f), (string)null, "Position of the UI panel (X,Y in screen space, values from 0-1).", false, false, (ValueValidator)null, (string)null);
			MelonPreferences.Save();
		}
	}
	public class Core : MelonMod
	{
		[CompilerGenerated]
		private sealed class <InitializeExtendedDealersWithRetry>d__22 : IEnumerator<object>, IEnumerator, IDisposable
		{
			private int <>1__state;

			private object <>2__current;

			public Core <>4__this;

			private int <attempts>5__1;

			private int <maxAttempts>5__2;

			private List<Dealer> <dealers>5__3;

			private List<Dealer>.Enumerator <>s__4;

			private Dealer <dealer>5__5;

			private DealerExtendedBrain <dealerExtendedBrain>5__6;

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

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

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

			[DebuggerHidden]
			void IDisposable.Dispose()
			{
				<dealers>5__3 = null;
				<>s__4 = default(List<Dealer>.Enumerator);
				<dealer>5__5 = null;
				<dealerExtendedBrain>5__6 = null;
				<>1__state = -2;
			}

			private bool MoveNext()
			{
				//IL_0034: Unknown result type (might be due to invalid IL or missing references)
				//IL_003e: Expected O, but got Unknown
				//IL_0228: Unknown result type (might be due to invalid IL or missing references)
				//IL_0232: Expected O, but got Unknown
				switch (<>1__state)
				{
				default:
					return false;
				case 0:
					<>1__state = -1;
					<>2__current = (object)new WaitForSeconds(1f);
					<>1__state = 1;
					return true;
				case 1:
					<>1__state = -1;
					<attempts>5__1 = 0;
					<maxAttempts>5__2 = 5;
					goto IL_024b;
				case 2:
					{
						<>1__state = -1;
						goto IL_0243;
					}
					IL_024b:
					if (dealersInitialized || <attempts>5__1 >= <maxAttempts>5__2)
					{
						break;
					}
					<attempts>5__1++;
					MelonLogger.Msg($"Attempting to initialize dealers (attempt {<attempts>5__1}/{<maxAttempts>5__2})...");
					<dealers>5__3 = GameUtils.GetAllDealers();
					if (<dealers>5__3.Count > 0)
					{
						<>s__4 = <dealers>5__3.GetEnumerator();
						try
						{
							while (<>s__4.MoveNext())
							{
								<dealer>5__5 = <>s__4.Current;
								if (!((Object)(object)<dealer>5__5 == (Object)null))
								{
									<dealerExtendedBrain>5__6 = new DealerExtendedBrain(<dealer>5__5);
									DealerStorageManager.AddDealerExtendedBrain(<dealerExtendedBrain>5__6);
									<dealerExtendedBrain>5__6 = null;
									<dealer>5__5 = null;
								}
							}
						}
						finally
						{
							((IDisposable)<>s__4).Dispose();
						}
						<>s__4 = default(List<Dealer>.Enumerator);
						dealersInitialized = true;
						MelonLogger.Msg($"Successfully initialized {<dealers>5__3.Count} dealers");
						goto IL_0243;
					}
					MelonLogger.Msg($"No dealers found on attempt {<attempts>5__1}, will retry in 3 seconds...");
					<>2__current = (object)new WaitForSeconds(3f);
					<>1__state = 2;
					return true;
					IL_0243:
					<dealers>5__3 = null;
					goto IL_024b;
				}
				if (!dealersInitialized)
				{
					MelonLogger.Error($"Failed to initialize dealers after {<maxAttempts>5__2} attempts");
				}
				return false;
			}

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

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

		private static bool dealersInitialized;

		public static Instance MelonLogger { get; private set; }

		public static DealerStorageManager DealerStorageManager { get; private set; }

		public static bool MainSceneLoaded { get; private set; }

		public static Config Config { get; private set; }

		public override void OnInitializeMelon()
		{
			MelonLogger = ((MelonBase)this).LoggerInstance;
			MelonLogger.Msg("DealerSelfSupplySystem initializing...");
			Config = new Config();
			DealerStorageManager = new DealerStorageManager();
			ApplyConfigToDealerStorageManager();
			MelonLogger.Msg("Initialization complete.");
		}

		private void ApplyConfigToDealerStorageManager()
		{
			if (DealerStorageManager != null && Config.dealerStorageCheckInterval != null)
			{
				float num = Mathf.Clamp(Config.dealerStorageCheckInterval.Value, 10f, 300f);
				DealerStorageManager.SetCheckInterval(num);
				MelonLogger.Msg($"Set dealer storage check interval to {num} seconds");
			}
		}

		public override void OnSceneWasLoaded(int buildIndex, string sceneName)
		{
			if (sceneName == "Main")
			{
				MainSceneLoaded = true;
				MelonLogger.Msg("Main scene loaded.");
				MelonCoroutines.Start(InitializeExtendedDealersWithRetry());
			}
		}

		public override void OnSceneWasUnloaded(int buildIndex, string sceneName)
		{
			if (sceneName == "Main")
			{
				MainSceneLoaded = false;
				dealersInitialized = false;
				MelonLogger.Msg("Main scene unloaded. Cleaning up dealer storage manager...");
				DealerStorageManager.CleanUp();
			}
		}

		public override void OnLateUpdate()
		{
			if (MainSceneLoaded && dealersInitialized)
			{
				DealerStorageManager.CheckDealerStorage();
			}
		}

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

		public override void OnUpdate()
		{
			if (Input.GetKeyDown((KeyCode)290))
			{
				SavePoint.SAVE_COOLDOWN = 0f;
			}
			if (!MainSceneLoaded || !dealersInitialized)
			{
				return;
			}
			foreach (KeyValuePair<StorageEntity, DealerExtensionUI> item in DealerStorageManager._dealerStorageUIDictionary)
			{
				if (item.Value != null && (Object)(object)item.Value.DealerUIObject != (Object)null && item.Value.DealerUIObject.activeSelf)
				{
					item.Value.Update();
				}
			}
		}

		public override void OnPreferencesSaved()
		{
			ApplyConfigToDealerStorageManager();
			MelonLogger.Msg("Configuration updated");
		}
	}
}
namespace DealerSelfSupplySystem.Utils
{
	internal class GameUtils
	{
		public static List<Dealer> GetAllDealers()
		{
			return ((IEnumerable<Dealer>)Object.FindObjectsOfType<Dealer>()).ToList();
		}

		public static List<Dealer> GetRecruitedDealers()
		{
			List<Dealer> source = ((IEnumerable<Dealer>)Object.FindObjectsOfType<Dealer>(true)).ToList();
			return source.Where((Dealer dealer) => dealer.IsRecruited).ToList();
		}
	}
	public static class Messages
	{
		public static List<string> DealerItemCollectionMessages = new List<string>
		{
			"Yo boss! Just hit the stash. This shit's fire, no cap.", "Grabbed that product from the spot. Five-O ain't see nothin'.", "Storage run complete. Got that good-good for the fiends.", "Snatched some merch from the back. We movin' weight tonight!", "Just re-upped from storage. Clientele been blowin' up my phone.", "Raided the stash spot. We 'bout to run the block with this batch.", "Yo, I just touched the package. This that top-shelf shit right here.", "Storage run was clean. Ain't nobody peepin' our moves.", "Got that work from the back. Time to flood the streets, ya dig?", "Just secured the bag from storage. We eatin' good tonight!",
			"Product secured, ready to slang. These streets gonna pay us, feel me?", "Took that heat from storage. Trap about to be jumpin'!", "Got that pack from the back. Fiends gonna be lined up 'round the block.", "Straight murked that storage inventory. We 'bout to make it rain!", "Finessed some product from storage. Time to tax these customers.", "Storage run complete. Got that gas that'll have 'em coming back.", "Just hit a lick on our own stash. That's smart business, ya heard?", "Got them thangs from storage. Custies better have my paper ready.", "Inventory grabbed. Bout to flip this shit and double up.", "Storage run was a success. We pushin' P tonight for real!"
		};

		public static List<string> DealerNoItemsFoundMessages = new List<string>
		{
			"Yo, storage is bone dry. Can't make money with empty hands, boss.", "Ain't shit in the stash! How we supposed to eat?", "Storage lookin' weak as hell. No product, no profit, feel me?", "Stash spot empty. These streets ain't gonna wait for us to re-up.", "Bruh, storage is a ghost town. Custies gonna start hittin' up the competition.", "Storage run was a bust. Can't hustle with air, ya dig?", "Nothin' in the back but dust and disappointment. We lookin' soft out here.", "Storage empty as my pockets before this job. We need to fix that ASAP.", "Can't find what I need in this bitch. How we supposed to trap with no pack?", "Yo, storage situation is FUBAR. Need that re-up yesterday.",
			"Stash spsot drier than the Sahara. We 'bout to lose our corner if we don't re-up.", "Storage run was dead. No product means no paper, and that's bad business.", "Came up empty-handed. The block gonna think we fell off if we don't re-up soon.", "Storage got nothin' I can push. Fiends blowin' up my phone for nothin'.", "Stash is straight garbage. Can't serve the customers with empty bags.", "Storage ain't hittin'. Need that work or we'll be the ones lookin' for work.", "This empty storage shit is bad for business. Streets talk, and they sayin' we slippin'.", "Went to grab product and came back with fuck all. We need to re-up, boss.", "Storage situation is trash. Can't be a player if we ain't got no game to sell.", "Stash run was a fail. Competition gonna eat our lunch if we don't stock up."
		};

		public static List<string> DealerAlreadyAssignedMessages = new List<string>
		{
			"Yo boss, I can't be in two places at once! Already got a stash spot to look after.", "What you think I am, Superman? Can't handle multiple spots, I'm a hustler not a superhero!", "Nah, that's too much heat. One stash is risky enough, two is just askin' to get caught slippin'.", "Boss, you trippin'! I already got a rack to run. Can't split myself like a damn cell.", "C'mon now, do I look like I got a twin brother? Already assigned to another stash!", "You want the feds all up in our business? One spot per dealer, that's operational security 101!", "Look, I ain't no octopus with eight arms. Got my hands full with the spot I already got.", "Yo, I may be good, but I ain't got that clone technology! Already working another stash.", "What, you think I can teleport? Already committed to another storage spot, feel me?", "Nah, that's bad business. Can't manage two spots without droppin' the ball on both.",
			"You payin' me enough for ONE job. Want me at two spots? Then we gotta renegotiate my cut!", "Boss, you know the rules: one dealer, one stash. That's how we stay under the radar.", "I look like I'm about that corporate ladder life? One hustle at a time is how I roll.", "My momma didn't raise no magician! Can't be in two places at once, already got a spot.", "Bruh, that's amateur hour. Spreadin' myself thin is how mistakes happen. One rack only!", "Listen, multi-tasking is for office workers. Street hustlers need focus. Got my spot already.", "You must be smokin' your own supply! I'm already assigned to another stash, can't do both.", "What's next, you want me to cook and clean too? Already got a storage assignment!", "Nah fam, that's a recipe for disaster. One dealer, one stash - that's how we maintain quality control.", "I ain't got a twin brother hidin' somewhere! Already committed to another rack, boss."
		};

		public static string GetRandomItemCollectionMessage(bool success)
		{
			if (success)
			{
				int index = Random.Range(0, DealerItemCollectionMessages.Count);
				return DealerItemCollectionMessages[index];
			}
			int index2 = Random.Range(0, DealerNoItemsFoundMessages.Count);
			return DealerNoItemsFoundMessages[index2];
		}

		public static string GetRandomDealerAlreadyAssignedMessage()
		{
			int index = Random.Range(0, DealerAlreadyAssignedMessages.Count);
			return DealerAlreadyAssignedMessages[index];
		}
	}
}
namespace DealerSelfSupplySystem.UI
{
	internal class FlexiblePopup
	{
		[CompilerGenerated]
		private sealed class <ShowPopupAndWaitForResult>d__19 : IEnumerator<object>, IEnumerator, IDisposable
		{
			private int <>1__state;

			private object <>2__current;

			public string title;

			public (string buttonText, string choiceResult)[] options;

			public Action<string> resultCallback;

			public Vector2 position;

			private Task<string> <choiceTask>5__1;

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

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

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

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

			private bool MoveNext()
			{
				//IL_003c: Unknown result type (might be due to invalid IL or missing references)
				//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
				//IL_00d4: Expected O, but got Unknown
				switch (<>1__state)
				{
				default:
					return false;
				case 0:
					<>1__state = -1;
					<choiceTask>5__1 = Show(title, options, position);
					goto IL_0095;
				case 1:
					<>1__state = -1;
					goto IL_0095;
				case 2:
					{
						<>1__state = -1;
						return false;
					}
					IL_0095:
					if (!<choiceTask>5__1.IsCompleted)
					{
						if (<choiceTask>5__1.IsFaulted || <choiceTask>5__1.IsCanceled)
						{
							resultCallback(null);
							return false;
						}
						<>2__current = null;
						<>1__state = 1;
						return true;
					}
					resultCallback(<choiceTask>5__1.Result);
					ClosePopup();
					<>2__current = (object)new WaitForSeconds(0.2f);
					<>1__state = 2;
					return true;
				}
			}

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

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

		private static readonly Vector2 DEFAULT_POSITION = new Vector2(0.5f, 0.5f);

		private static GameObject popupObject;

		private static TaskCompletionSource<string> choiceTaskCompletionSource;

		public static event Action OnPopupCancelled;

		public static void Initialize()
		{
		}

		public static Task<string> Show(string title, (string buttonText, string choiceResult)[] options)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			return Show(title, options, DEFAULT_POSITION);
		}

		public static async Task<string> Show(string title, (string buttonText, string choiceResult)[] options, Vector2 position)
		{
			//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)
			choiceTaskCompletionSource = new TaskCompletionSource<string>();
			if ((Object)(object)popupObject == (Object)null)
			{
				CreateDialog(title, options, position);
			}
			else
			{
				UpdateDialog(title, options);
			}
			if ((Object)(object)popupObject != (Object)null)
			{
				popupObject.SetActive(true);
			}
			else
			{
				MelonLogger.Error("Failed to create or find FlexiblePopup object.");
				choiceTaskCompletionSource.SetResult(null);
			}
			return await choiceTaskCompletionSource.Task;
		}

		private static void CreateDialog(string title, (string buttonText, string choiceResult)[] options)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			CreateDialog(title, options, DEFAULT_POSITION);
		}

		private static void CreateDialog(string title, (string buttonText, string choiceResult)[] options, Vector2 position)
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Expected O, but got Unknown
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Expected O, but got Unknown
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00af: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0115: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0208: Unknown result type (might be due to invalid IL or missing references)
			//IL_021f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0235: Unknown result type (might be due to invalid IL or missing references)
			//IL_025f: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = null;
			RectTransform val2 = null;
			try
			{
				popupObject = new GameObject("FlexiblePopup");
				Object.DontDestroyOnLoad((Object)(object)popupObject);
				Canvas val3 = popupObject.AddComponent<Canvas>();
				val3.renderMode = (RenderMode)0;
				val3.sortingOrder = 100;
				popupObject.AddComponent<GraphicRaycaster>();
				val = new GameObject("Panel");
				val.transform.SetParent(popupObject.transform, false);
				Image val4 = val.AddComponent<Image>();
				((Graphic)val4).color = new Color(0.1f, 0.1f, 0.1f, 0.9f);
				val2 = val.GetComponent<RectTransform>();
				val2.anchorMin = position;
				val2.anchorMax = position;
				val2.pivot = position;
				val2.sizeDelta = new Vector2(300f, (float)(200 + (options.Length - 2) * 50));
				val2.anchoredPosition = position;
				CreateText(val.transform, "Title", title, 18, new Vector2(0f, val2.sizeDelta.y / 2f - 30f));
				float num = 60f;
				float num2 = (float)(options.Length - 1) * num / 2f - 30f;
				for (int i = 0; i < options.Length; i++)
				{
					int index = i;
					CreateButton(val.transform, $"OptionButton_{i}", options[i].buttonText, new Vector2(0f, num2 - (float)i * num), delegate
					{
						OnOptionButtonClicked(options[index].choiceResult);
					});
				}
				CreateButton(val.transform, "CloseButton", "X", new Vector2(val2.sizeDelta.x / 2f - 15f, val2.sizeDelta.y / 2f - 15f), (Action)OnCloseButtonClicked, (Vector2?)new Vector2(30f, 30f), EButtonType.Primary);
				popupObject.SetActive(false);
			}
			catch (Exception ex)
			{
				MelonLogger.Error("Error creating FlexiblePopup: " + ex.Message + "\n" + ex.StackTrace);
				if ((Object)(object)popupObject != (Object)null)
				{
					Object.Destroy((Object)(object)popupObject);
				}
				popupObject = null;
				choiceTaskCompletionSource?.TrySetResult(null);
			}
		}

		private static void UpdateDialog(string title, (string buttonText, string choiceResult)[] options)
		{
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c2: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)popupObject == (Object)null)
			{
				CreateDialog(title, options);
				return;
			}
			Transform obj = popupObject.transform.Find("Panel/Title");
			Text val = ((obj != null) ? ((Component)obj).GetComponent<Text>() : null);
			if ((Object)(object)val != (Object)null)
			{
				val.text = title;
			}
			Transform obj2 = popupObject.transform.Find("Panel");
			RectTransform val2 = ((obj2 != null) ? ((Component)obj2).GetComponent<RectTransform>() : null);
			if (!((Object)(object)val2 != (Object)null))
			{
				return;
			}
			val2.sizeDelta = new Vector2(300f, (float)(200 + (options.Length - 2) * 50));
			for (int i = 0; i < 20; i++)
			{
				Transform val3 = ((Component)val2).transform.Find($"OptionButton_{i}");
				if ((Object)(object)val3 != (Object)null)
				{
					Object.Destroy((Object)(object)((Component)val3).gameObject);
				}
			}
			float num = 60f;
			float num2 = (float)(options.Length - 1) * num / 2f - 30f;
			for (int j = 0; j < options.Length; j++)
			{
				int index = j;
				CreateButton(((Component)val2).transform, $"OptionButton_{j}", options[j].buttonText, new Vector2(0f, num2 - (float)j * num), delegate
				{
					OnOptionButtonClicked(options[index].choiceResult);
				});
			}
		}

		public static GameObject CreateButton(Transform parent, string name, string buttonText, Vector2 position, Action onClickAction, Vector2? size = null, EButtonType buttonType = EButtonType.Primary)
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Expected O, but got Unknown
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0104: Unknown result type (might be due to invalid IL or missing references)
			//IL_0123: Unknown result type (might be due to invalid IL or missing references)
			//IL_013a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0151: 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_0167: 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)
			Vector2 sizeDelta = (Vector2)(((??)size) ?? new Vector2(200f, 40f));
			GameObject val = new GameObject(name);
			val.transform.SetParent(parent, false);
			Image val2 = val.AddComponent<Image>();
			((Graphic)val2).color = Styling.PRIMARY_COLOR;
			if (buttonType == EButtonType.Secondary)
			{
				((Graphic)val2).color = Styling.SECONDARY_COLOR;
			}
			if (buttonType == EButtonType.Destructive)
			{
				((Graphic)val2).color = Styling.DESTRUCTIVE_COLOR;
			}
			Button val3 = val.AddComponent<Button>();
			((Selectable)val3).targetGraphic = (Graphic)(object)val2;
			((UnityEventBase)val3.onClick).RemoveAllListeners();
			((UnityEvent)val3.onClick).AddListener(UnityAction.op_Implicit(onClickAction));
			GameObject val4 = CreateText(val.transform, "Text", buttonText, 14, Vector2.zero);
			RectTransform component = val4.GetComponent<RectTransform>();
			component.anchorMin = Vector2.zero;
			component.anchorMax = Vector2.one;
			component.sizeDelta = Vector2.zero;
			component.offsetMin = Vector2.zero;
			component.offsetMax = Vector2.zero;
			RectTransform component2 = val.GetComponent<RectTransform>();
			component2.anchorMin = new Vector2(0.5f, 0.5f);
			component2.anchorMax = new Vector2(0.5f, 0.5f);
			component2.pivot = new Vector2(0.5f, 0.5f);
			component2.anchoredPosition = position;
			component2.sizeDelta = sizeDelta;
			return val;
		}

		public static GameObject CreateText(Transform parent, string name, string textContent, int fontSize, Vector2 position)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Expected O, but got Unknown
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject(name);
			val.transform.SetParent(parent, false);
			Text val2 = val.AddComponent<Text>();
			val2.text = textContent;
			val2.fontSize = fontSize;
			val2.alignment = (TextAnchor)4;
			((Graphic)val2).color = Color.white;
			val2.font = Resources.GetBuiltinResource<Font>("Arial.ttf");
			if ((Object)(object)val2.font == (Object)null)
			{
				MelonLogger.Warning("Arial.ttf not found. UI Text may not render correctly.");
			}
			RectTransform component = val.GetComponent<RectTransform>();
			component.anchorMin = new Vector2(0.5f, 0.5f);
			component.anchorMax = new Vector2(0.5f, 0.5f);
			component.pivot = new Vector2(0.5f, 0.5f);
			component.anchoredPosition = position;
			component.sizeDelta = new Vector2(280f, 30f);
			return val;
		}

		private static void OnOptionButtonClicked(string choiceResult)
		{
			choiceTaskCompletionSource?.TrySetResult(choiceResult);
			if ((Object)(object)popupObject != (Object)null)
			{
				popupObject.SetActive(false);
			}
			MelonLogger.Msg("Option '" + choiceResult + "' selected");
		}

		private static void OnCloseButtonClicked()
		{
			choiceTaskCompletionSource?.TrySetResult(null);
			if ((Object)(object)popupObject != (Object)null)
			{
				popupObject.SetActive(false);
			}
			MelonLogger.Msg("Popup closed");
			FlexiblePopup.OnPopupCancelled?.Invoke();
		}

		public static void ClosePopup()
		{
			if ((Object)(object)popupObject != (Object)null)
			{
				popupObject.SetActive(false);
			}
			choiceTaskCompletionSource?.TrySetResult(null);
		}

		public static void Destroy()
		{
			if ((Object)(object)popupObject != (Object)null)
			{
				Object.Destroy((Object)(object)popupObject);
				popupObject = null;
			}
			choiceTaskCompletionSource?.TrySetResult(null);
			FlexiblePopup.OnPopupCancelled = null;
		}

		public static IEnumerator ShowPopupAndWaitForResult(string title, (string buttonText, string choiceResult)[] options, Action<string> resultCallback)
		{
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			return ShowPopupAndWaitForResult(title, options, resultCallback, DEFAULT_POSITION);
		}

		[IteratorStateMachine(typeof(<ShowPopupAndWaitForResult>d__19))]
		public static IEnumerator ShowPopupAndWaitForResult(string title, (string buttonText, string choiceResult)[] options, Action<string> resultCallback, Vector2 position)
		{
			//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)
			//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
			return new <ShowPopupAndWaitForResult>d__19(0)
			{
				title = title,
				options = options,
				resultCallback = resultCallback,
				position = position
			};
		}
	}
	public static class Styling
	{
		public static Color PRIMARY_COLOR = new Color(23f / 85f, 2f / 3f, 0.8980392f, 1f);

		public static Color SECONDARY_COLOR = new Color(0.9372549f, 0.9843137f, 1f, 1f);

		public static Color DESTRUCTIVE_COLOR = new Color(1f, 0.47058824f, 0.41960785f, 1f);
	}
	public enum EButtonType
	{
		Primary,
		Secondary,
		Destructive
	}
}
namespace DealerSelfSupplySystem.Persistence
{
	[Serializable]
	public class DealerStorageAssignment
	{
		public string StorageName { get; set; }

		public float PosX { get; set; }

		public float PosY { get; set; }

		public float PosZ { get; set; }

		public string DealerName { get; set; }

		public string DealerFullName { get; set; }

		[JsonIgnore]
		public Vector3 StorageEntityPosition
		{
			get
			{
				//IL_0013: Unknown result type (might be due to invalid IL or missing references)
				//IL_0018: Unknown result type (might be due to invalid IL or missing references)
				//IL_001b: Unknown result type (might be due to invalid IL or missing references)
				return new Vector3(PosX, PosY, PosZ);
			}
			set
			{
				//IL_0002: Unknown result type (might be due to invalid IL or missing references)
				//IL_000f: Unknown result type (might be due to invalid IL or missing references)
				//IL_001c: Unknown result type (might be due to invalid IL or missing references)
				PosX = value.x;
				PosY = value.y;
				PosZ = value.z;
			}
		}
	}
	public class DealerSaveDataManager
	{
		[CompilerGenerated]
		private sealed class <>c__DisplayClass5_0
		{
			public Dealer matchedDealer;

			internal bool <RestoreDealerAssignments>b__0(DealerExtendedBrain d)
			{
				return (Object)(object)d.Dealer == (Object)(object)matchedDealer;
			}
		}

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

			private object <>2__current;

			public List<DealerStorageAssignment> assignments;

			private int <maxAttempts>5__1;

			private int <attempts>5__2;

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

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

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

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

			private bool MoveNext()
			{
				//IL_0043: Unknown result type (might be due to invalid IL or missing references)
				//IL_004d: Expected O, but got Unknown
				//IL_0075: Unknown result type (might be due to invalid IL or missing references)
				//IL_007f: Expected O, but got Unknown
				//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
				//IL_00cc: Expected O, but got Unknown
				switch (<>1__state)
				{
				default:
					return false;
				case 0:
					<>1__state = -1;
					<>2__current = (object)new WaitForSeconds(1f);
					<>1__state = 1;
					return true;
				case 1:
					<>1__state = -1;
					<maxAttempts>5__1 = 10;
					<attempts>5__2 = 0;
					goto IL_00a0;
				case 2:
					<>1__state = -1;
					<attempts>5__2++;
					goto IL_00a0;
				case 3:
					<>1__state = -1;
					<>2__current = RestoreDealerAssignments(assignments);
					<>1__state = 4;
					return true;
				case 4:
					{
						<>1__state = -1;
						return false;
					}
					IL_00a0:
					if (!Core.MainSceneLoaded && <attempts>5__2 < <maxAttempts>5__1)
					{
						<>2__current = (object)new WaitForSeconds(3f);
						<>1__state = 2;
						return true;
					}
					<>2__current = (object)new WaitForSeconds(1f);
					<>1__state = 3;
					return true;
				}
			}

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

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

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

			private object <>2__current;

			public List<DealerStorageAssignment> assignments;

			private int <restoredCount>5__1;

			private List<Dealer> <allDealers>5__2;

			private List<StorageEntity> <allStorages>5__3;

			private int <retryRound>5__4;

			private List<DealerStorageAssignment>.Enumerator <>s__5;

			private DealerStorageAssignment <assignment>5__6;

			private <>c__DisplayClass5_0 <>8__7;

			private StorageEntity <matchedStorage>5__8;

			private DealerExtendedBrain <dealerBrain>5__9;

			private bool <success>5__10;

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

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

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

			[DebuggerHidden]
			void IDisposable.Dispose()
			{
				<allDealers>5__2 = null;
				<allStorages>5__3 = null;
				<>s__5 = default(List<DealerStorageAssignment>.Enumerator);
				<assignment>5__6 = null;
				<>8__7 = null;
				<matchedStorage>5__8 = null;
				<dealerBrain>5__9 = null;
				<>1__state = -2;
			}

			private bool MoveNext()
			{
				//IL_0059: Unknown result type (might be due to invalid IL or missing references)
				//IL_0063: Expected O, but got Unknown
				//IL_036c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0376: Expected O, but got Unknown
				//IL_0211: Unknown result type (might be due to invalid IL or missing references)
				switch (<>1__state)
				{
				default:
					return false;
				case 0:
					<>1__state = -1;
					<restoredCount>5__1 = 0;
					<allDealers>5__2 = GameUtils.GetRecruitedDealers();
					if (<allDealers>5__2.Count == 0)
					{
						<>2__current = (object)new WaitForSeconds(5f);
						<>1__state = 1;
						return true;
					}
					goto IL_0094;
				case 1:
					<>1__state = -1;
					<allDealers>5__2 = GameUtils.GetRecruitedDealers();
					if (<allDealers>5__2.Count == 0)
					{
						return false;
					}
					goto IL_0094;
				case 2:
					{
						<>1__state = -1;
						<retryRound>5__4++;
						break;
					}
					IL_0094:
					<allStorages>5__3 = FindAllStorageEntities();
					Core.MelonLogger.Msg($"Found {<allStorages>5__3.Count} storage entities");
					<retryRound>5__4 = 0;
					break;
				}
				if (<retryRound>5__4 < 3)
				{
					<>s__5 = assignments.GetEnumerator();
					try
					{
						while (<>s__5.MoveNext())
						{
							<assignment>5__6 = <>s__5.Current;
							<>8__7 = new <>c__DisplayClass5_0();
							if (IsAssignmentAlreadyRestored(<assignment>5__6, <allDealers>5__2, <allStorages>5__3))
							{
								continue;
							}
							<>8__7.matchedDealer = FindMatchingDealer(<allDealers>5__2, <assignment>5__6);
							if ((Object)(object)<>8__7.matchedDealer == (Object)null)
							{
								Core.MelonLogger.Warning("Could not find dealer with name: " + <assignment>5__6.DealerFullName);
								continue;
							}
							<matchedStorage>5__8 = FindMatchingStorage(<allStorages>5__3, <assignment>5__6);
							if ((Object)(object)<matchedStorage>5__8 == (Object)null)
							{
								Core.MelonLogger.Warning($"Could not find matching storage for {<assignment>5__6.StorageName} near position {<assignment>5__6.StorageEntityPosition}");
								continue;
							}
							<dealerBrain>5__9 = Core.DealerStorageManager.GetAllDealersExtendedBrain().FirstOrDefault((DealerExtendedBrain d) => (Object)(object)d.Dealer == (Object)(object)<>8__7.matchedDealer);
							if (<dealerBrain>5__9 == null)
							{
								<dealerBrain>5__9 = new DealerExtendedBrain(<>8__7.matchedDealer);
								Core.DealerStorageManager.AddDealerExtendedBrain(<dealerBrain>5__9);
							}
							<success>5__10 = Core.DealerStorageManager.SetDealerToStorage(<matchedStorage>5__8, <dealerBrain>5__9);
							if (<success>5__10)
							{
								<restoredCount>5__1++;
								Core.MelonLogger.Msg("Successfully restored assignment: " + ((NPC)<>8__7.matchedDealer).fullName + " -> " + ((Object)<matchedStorage>5__8).name);
							}
							<>8__7 = null;
							<matchedStorage>5__8 = null;
							<dealerBrain>5__9 = null;
							<assignment>5__6 = null;
						}
					}
					finally
					{
						((IDisposable)<>s__5).Dispose();
					}
					<>s__5 = default(List<DealerStorageAssignment>.Enumerator);
					if (<restoredCount>5__1 != assignments.Count)
					{
						<>2__current = (object)new WaitForSeconds(5f);
						<>1__state = 2;
						return true;
					}
				}
				Core.MelonLogger.Msg($"Successfully restored {<restoredCount>5__1}/{assignments.Count} dealer-storage assignments");
				return false;
			}

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

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

		private const string MOD_FOLDER_NAME = "DealerSelfSupplySystem";

		private const float POSITION_MATCH_THRESHOLD = 10f;

		public static void SaveData(string gameSaveFolderPath)
		{
			//IL_00b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_014d: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				Core.MelonLogger.Msg("Saving dealer storage assignments for save at: " + gameSaveFolderPath);
				List<DealerStorageAssignment> list = new List<DealerStorageAssignment>();
				Dictionary<StorageEntity, List<DealerExtendedBrain>> allAssignments = Core.DealerStorageManager.GetAllAssignments();
				foreach (KeyValuePair<StorageEntity, List<DealerExtendedBrain>> item2 in allAssignments)
				{
					if (!((Object)(object)item2.Key != (Object)null))
					{
						continue;
					}
					StorageEntity key = item2.Key;
					foreach (DealerExtendedBrain item3 in item2.Value)
					{
						if ((Object)(object)item3?.Dealer != (Object)null)
						{
							DealerStorageAssignment item = new DealerStorageAssignment
							{
								StorageName = ((Object)key).name,
								StorageEntityPosition = ((Component)key).transform.position,
								DealerName = ((Object)item3.Dealer).name,
								DealerFullName = ((NPC)item3.Dealer).fullName
							};
							Core.MelonLogger.Msg($"Saving assignment: {((NPC)item3.Dealer).fullName} -> Storage '{((Object)key).name}' at {((Component)key).transform.position}");
							list.Add(item);
						}
					}
				}
				string path = CreateModSaveFolder(gameSaveFolderPath);
				string fileName = Path.GetFileName(gameSaveFolderPath);
				string text = Path.Combine(path, fileName + "_dealer_storage_data.json");
				string contents = JsonSerializer.Serialize(list, new JsonSerializerOptions
				{
					WriteIndented = true
				});
				File.WriteAllText(text, contents);
				Core.MelonLogger.Msg($"Successfully saved {list.Count} dealer assignments to {text}");
			}
			catch (Exception ex)
			{
				Core.MelonLogger.Error("Failed to save dealer storage assignments: " + ex.Message + "\n" + ex.StackTrace);
			}
		}

		public static void LoadData(string gameSaveFolderPath)
		{
			try
			{
				Core.MelonLogger.Msg("Loading dealer storage assignments for save at: " + gameSaveFolderPath);
				string modSaveFolder = GetModSaveFolder(gameSaveFolderPath);
				string fileName = Path.GetFileName(gameSaveFolderPath);
				string text = Path.Combine(modSaveFolder, fileName + "_dealer_storage_data.json");
				if (!File.Exists(text))
				{
					Core.MelonLogger.Msg("No dealer storage assignments file found at " + text);
					return;
				}
				string text2 = File.ReadAllText(text);
				if (string.IsNullOrEmpty(text2))
				{
					Core.MelonLogger.Msg("Save file is empty");
					return;
				}
				List<DealerStorageAssignment> list = null;
				try
				{
					list = JsonSerializer.Deserialize<List<DealerStorageAssignment>>(text2);
				}
				catch (Exception ex)
				{
					Core.MelonLogger.Error("Failed to deserialize JSON: " + ex.Message);
					return;
				}
				if (list == null || list.Count == 0)
				{
					Core.MelonLogger.Warning("Dealer storage data was invalid or empty");
					return;
				}
				Core.MelonLogger.Msg($"Loading {list.Count} dealer storage assignments");
				MelonCoroutines.Start(DelayedRestoreDealerAssignments(list));
			}
			catch (Exception ex2)
			{
				Core.MelonLogger.Error("Failed to load dealer storage assignments: " + ex2.Message + "\n" + ex2.StackTrace);
			}
		}

		[IteratorStateMachine(typeof(<DelayedRestoreDealerAssignments>d__4))]
		private static IEnumerator DelayedRestoreDealerAssignments(List<DealerStorageAssignment> assignments)
		{
			//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
			return new <DelayedRestoreDealerAssignments>d__4(0)
			{
				assignments = assignments
			};
		}

		[IteratorStateMachine(typeof(<RestoreDealerAssignments>d__5))]
		private static IEnumerator RestoreDealerAssignments(List<DealerStorageAssignment> assignments)
		{
			//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
			return new <RestoreDealerAssignments>d__5(0)
			{
				assignments = assignments
			};
		}

		private static bool IsAssignmentAlreadyRestored(DealerStorageAssignment assignment, List<Dealer> dealers, List<StorageEntity> storages)
		{
			Dealer dealer = FindMatchingDealer(dealers, assignment);
			StorageEntity val = FindMatchingStorage(storages, assignment);
			if ((Object)(object)dealer == (Object)null || (Object)(object)val == (Object)null)
			{
				return false;
			}
			DealerExtendedBrain dealerExtendedBrain = Core.DealerStorageManager.GetAllDealersExtendedBrain().FirstOrDefault((DealerExtendedBrain d) => (Object)(object)d.Dealer == (Object)(object)dealer);
			if (dealerExtendedBrain == null)
			{
				return false;
			}
			List<DealerExtendedBrain> dealersFromStorage = Core.DealerStorageManager.GetDealersFromStorage(val);
			return dealersFromStorage.Contains(dealerExtendedBrain);
		}

		private static Dealer FindMatchingDealer(List<Dealer> dealers, DealerStorageAssignment assignment)
		{
			Dealer val = ((IEnumerable<Dealer>)dealers).FirstOrDefault((Func<Dealer, bool>)((Dealer d) => string.Equals(((NPC)d).fullName, assignment.DealerFullName, StringComparison.OrdinalIgnoreCase)));
			if ((Object)(object)val != (Object)null)
			{
				return val;
			}
			Dealer val2 = ((IEnumerable<Dealer>)dealers).FirstOrDefault((Func<Dealer, bool>)((Dealer d) => string.Equals(((Object)d).name, assignment.DealerName, StringComparison.OrdinalIgnoreCase)));
			if ((Object)(object)val2 != (Object)null)
			{
				return val2;
			}
			return ((IEnumerable<Dealer>)dealers).FirstOrDefault((Func<Dealer, bool>)((Dealer d) => !string.IsNullOrEmpty(((NPC)d).fullName) && !string.IsNullOrEmpty(assignment.DealerFullName) && (((NPC)d).fullName.Contains(assignment.DealerFullName) || assignment.DealerFullName.Contains(((NPC)d).fullName))));
		}

		private static StorageEntity FindMatchingStorage(List<StorageEntity> storages, DealerStorageAssignment assignment)
		{
			//IL_0014: 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_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			Vector3 storageEntityPosition = assignment.StorageEntityPosition;
			List<StorageEntity> list = storages.Where((StorageEntity s) => ((Object)s).name == assignment.StorageName).ToList();
			if (list.Count == 1)
			{
				return list[0];
			}
			if (list.Count > 1)
			{
				return FindClosestStorage(list, storageEntityPosition);
			}
			return FindClosestStorage(storages, storageEntityPosition, 10f);
		}

		private static StorageEntity FindClosestStorage(List<StorageEntity> storages, Vector3 position, float maxDistance = float.MaxValue)
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			StorageEntity result = null;
			float num = maxDistance;
			foreach (StorageEntity storage in storages)
			{
				float num2 = Vector3.Distance(((Component)storage).transform.position, position);
				if (num2 < num)
				{
					num = num2;
					result = storage;
				}
			}
			return result;
		}

		private static List<StorageEntity> FindAllStorageEntities()
		{
			try
			{
				return ((IEnumerable<StorageEntity>)Object.FindObjectsOfType<StorageEntity>()).ToList();
			}
			catch (Exception ex)
			{
				Core.MelonLogger.Error("Error finding storage entities: " + ex.Message);
				return new List<StorageEntity>();
			}
		}

		private static string CreateModSaveFolder(string gameSaveFolderPath)
		{
			try
			{
				string directoryName = Path.GetDirectoryName(gameSaveFolderPath);
				string text = Path.Combine(directoryName, "DealerSelfSupplySystem");
				if (!Directory.Exists(text))
				{
					Directory.CreateDirectory(text);
					Core.MelonLogger.Msg("Created mod save folder at " + text);
				}
				return text;
			}
			catch (Exception ex)
			{
				Core.MelonLogger.Error("Failed to create mod save folder: " + ex.Message);
				string text2 = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "DealerSelfSupplySystem");
				if (!Directory.Exists(text2))
				{
					Directory.CreateDirectory(text2);
				}
				Core.MelonLogger.Msg("Using fallback save folder at " + text2);
				return text2;
			}
		}

		private static string GetModSaveFolder(string gameSaveFolderPath)
		{
			string directoryName = Path.GetDirectoryName(gameSaveFolderPath);
			return Path.Combine(directoryName, "DealerSelfSupplySystem");
		}
	}
}
namespace DealerSelfSupplySystem.Patches
{
	[HarmonyPatch(typeof(NPC), "Update")]
	public static class NPCUpdatePatch
	{
		public static void Postfix(NPC __instance)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			Vector3 position = ((Component)__instance).transform.position;
		}
	}
	[HarmonyPatch(typeof(SaveManager), "Save", new Type[] { typeof(string) })]
	public static class SavePatch
	{
		public static void Postfix(SaveManager __instance, string saveFolderPath)
		{
			DealerSaveDataManager.SaveData(saveFolderPath);
			Core.MelonLogger.Msg("Saved dealer storage data for save at " + saveFolderPath);
		}
	}
	[HarmonyPatch(typeof(LoadManager), "StartGame")]
	public static class LoadStartPatch
	{
		public static void Postfix(LoadManager __instance, SaveInfo info, bool allowLoadStacking)
		{
			DealerSaveDataManager.LoadData(info.SavePath);
			Core.MelonLogger.Msg("Loaded dealer storage data from " + info.SavePath);
		}
	}
	[HarmonyPatch(typeof(StorageMenu), "Open", new Type[] { typeof(StorageEntity) })]
	public static class StorageEntityOpenedPatch
	{
		public static void Postfix(StorageMenu __instance, StorageEntity entity)
		{
			DealerExtendedBrain dealerFromStorage = Core.DealerStorageManager.GetDealerFromStorage(entity);
			DealerExtensionUI dealerExtensionUI = Core.DealerStorageManager.GetDealerExtensionUI(entity);
			if (dealerExtensionUI == null)
			{
				dealerExtensionUI = new DealerExtensionUI(__instance, entity);
				Core.DealerStorageManager.SetDealerExtensionUI(entity, dealerExtensionUI);
			}
			dealerExtensionUI.ToggleUI(open: true);
		}
	}
	[HarmonyPatch(typeof(StorageMenu), "CloseMenu")]
	public static class StorageEntityClosedPatch
	{
		public static void Postfix(StorageMenu __instance)
		{
			StorageEntity storageMenu = Core.DealerStorageManager.GetStorageMenu(__instance);
			if (!((Object)(object)storageMenu == (Object)null))
			{
				Core.DealerStorageManager.GetDealerExtensionUI(storageMenu)?.ToggleUI(open: false);
			}
		}
	}
	[HarmonyPatch(typeof(StorageEntity), "OnClosed")]
	public static class StorageEntityClosedPatch2
	{
		public static void Postfix(StorageEntity __instance)
		{
			Core.DealerStorageManager.GetDealerExtensionUI(__instance)?.ToggleUI(open: false);
		}
	}
}
namespace DealerSelfSupplySystem.DealerExtension
{
	public class DealerExtendedBrain
	{
		[CompilerGenerated]
		private sealed class <SimulateItemCollection>d__33 : IEnumerator<object>, IEnumerator, IDisposable
		{
			private int <>1__state;

			private object <>2__current;

			public StorageEntity storageEntity;

			public DealerExtendedBrain <>4__this;

			private float <travelTime>5__1;

			private int <itemsCollected>5__2;

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

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

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

			[DebuggerHidden]
			void IDisposable.Dispose()
			{
				int num = <>1__state;
				if (num == -3 || (uint)(num - 1) <= 1u)
				{
					try
					{
					}
					finally
					{
						<>m__Finally1();
					}
				}
				<>1__state = -2;
			}

			private bool MoveNext()
			{
				//IL_0101: Unknown result type (might be due to invalid IL or missing references)
				//IL_010b: Expected O, but got Unknown
				//IL_02f1: Unknown result type (might be due to invalid IL or missing references)
				//IL_02fb: Expected O, but got Unknown
				bool result;
				try
				{
					switch (<>1__state)
					{
					default:
						result = false;
						break;
					case 0:
						<>1__state = -1;
						<>4__this.LastProcessedStorageName = ((Object)storageEntity).name;
						<travelTime>5__1 = <>4__this.CalculateTravelTime(storageEntity);
						Core.MelonLogger.Msg($"Dealer {((NPC)<>4__this.Dealer).fullName} is traveling to storage {((Object)storageEntity).name}, ETA: {<travelTime>5__1:F1} seconds");
						<>1__state = -3;
						<>2__current = (object)new WaitForSeconds(<travelTime>5__1);
						<>1__state = 1;
						result = true;
						break;
					case 1:
						<>1__state = -3;
						if ((Object)(object)<>4__this.Dealer.currentContract != (Object)null && <>4__this._canBeInturrupted)
						{
							Core.MelonLogger.Msg("Dealer " + ((NPC)<>4__this.Dealer).fullName + " received a contract during travel, aborting item collection");
							<>4__this.IsProcessingItems = false;
							result = false;
							<>m__Finally1();
							break;
						}
						Core.MelonLogger.Msg($"Dealer {((NPC)<>4__this.Dealer).fullName} has reached storage {((Object)storageEntity).name} and is collecting items");
						<itemsCollected>5__2 = <>4__this.AddItemsFromStorage(storageEntity);
						if (<itemsCollected>5__2 > 0)
						{
							Core.MelonLogger.Msg("Dealer " + ((NPC)<>4__this.Dealer).fullName + " successfully collected items from storage " + ((Object)storageEntity).name);
							<>4__this.TotalItemsCollected += <itemsCollected>5__2;
							<>4__this.LastCollectionTime = DateTime.Now;
							((NPC)<>4__this.Dealer).SendTextMessage(Messages.GetRandomItemCollectionMessage(success: true));
						}
						else
						{
							Core.MelonLogger.Msg("Dealer " + ((NPC)<>4__this.Dealer).fullName + " found no suitable items in storage " + ((Object)storageEntity).name);
							((NPC)<>4__this.Dealer).SendTextMessage(Messages.GetRandomItemCollectionMessage(success: false));
						}
						<>2__current = (object)new WaitForSeconds(<travelTime>5__1);
						<>1__state = 2;
						result = true;
						break;
					case 2:
						<>1__state = -3;
						Core.MelonLogger.Msg("Dealer " + ((NPC)<>4__this.Dealer).fullName + " has returned from storage " + ((Object)storageEntity).name);
						<>m__Finally1();
						result = false;
						break;
					}
				}
				catch
				{
					//try-fault
					((IDisposable)this).Dispose();
					throw;
				}
				return result;
			}

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

			private void <>m__Finally1()
			{
				<>1__state = -1;
				<>4__this.IsProcessingItems = false;
			}

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

		private float lastInventoryCheckTime = 0f;

		private const float INVENTORY_CHECK_INTERVAL = 30f;

		private float INVENTORY_THRESHOLD;

		private bool _canBeInturrupted = false;

		public Dealer Dealer { get; private set; }

		public bool NeedsItems { get; private set; } = false;


		public bool IsProcessingItems { get; private set; } = false;


		public int TotalItemsCollected { get; private set; } = 0;


		public DateTime LastCollectionTime { get; private set; }

		public string LastProcessedStorageName { get; private set; } = "None";


		public DealerExtendedBrain(Dealer dealer)
		{
			Dealer = dealer;
			INVENTORY_THRESHOLD = Config.dealerInventoryThreshold.Value;
		}

		public bool CalculateNeedsItems()
		{
			if (Time.time - lastInventoryCheckTime < 30f)
			{
				return NeedsItems;
			}
			lastInventoryCheckTime = Time.time;
			try
			{
				List<ItemSlot> allSlots = Dealer.GetAllSlots();
				if (allSlots == null)
				{
					Core.MelonLogger.Msg("Dealer " + ((NPC)Dealer).fullName + " has no inventory slots array");
					NeedsItems = false;
					return false;
				}
				List<ItemSlot> list = new List<ItemSlot>();
				Enumerator<ItemSlot> enumerator = allSlots.GetEnumerator();
				while (enumerator.MoveNext())
				{
					ItemSlot current = enumerator.Current;
					if (current != null)
					{
						list.Add(current);
					}
				}
				if (list.Count == 0)
				{
					Core.MelonLogger.Msg("Dealer " + ((NPC)Dealer).fullName + " has no inventory slots");
					NeedsItems = false;
					return false;
				}
				int count = list.Count;
				int num = 0;
				foreach (ItemSlot item in list)
				{
					if (item.Quantity > 0)
					{
						num++;
					}
				}
				float num2 = (float)num / (float)count;
				bool flag = num2 < INVENTORY_THRESHOLD;
				Core.MelonLogger.Msg($"Dealer {((NPC)Dealer).fullName} inventory status: {num}/{count} slots filled ({num2:P1})");
				if (flag != NeedsItems)
				{
					if (flag)
					{
						Core.MelonLogger.Msg($"Dealer {((NPC)Dealer).fullName} inventory low ({num2:P1}), needs restocking");
					}
					else
					{
						Core.MelonLogger.Msg($"Dealer {((NPC)Dealer).fullName} inventory sufficient ({num2:P1})");
					}
				}
				NeedsItems = flag;
				return flag;
			}
			catch (Exception ex)
			{
				Core.MelonLogger.Error("Error checking dealer inventory: " + ex.Message);
				NeedsItems = false;
				return false;
			}
		}

		public bool TryCollectItemsFromStorage(StorageEntity storageEntity)
		{
			try
			{
				if ((Object)(object)storageEntity == (Object)null)
				{
					Core.MelonLogger.Error("Cannot collect items: storage entity is null");
					return false;
				}
				if ((Object)(object)Dealer.currentContract != (Object)null)
				{
					Core.MelonLogger.Msg("Dealer " + ((NPC)Dealer).fullName + " is busy with a contract, cannot collect items");
					return false;
				}
				if (!CalculateNeedsItems())
				{
					return false;
				}
				if (IsProcessingItems)
				{
					Core.MelonLogger.Msg("Dealer " + ((NPC)Dealer).fullName + " is already processing items, cannot collect again");
					return false;
				}
				if (!HasValidItemsForDealer(storageEntity))
				{
					Core.MelonLogger.Msg("Storage " + ((Object)storageEntity).name + " has no valid items for " + ((NPC)Dealer).fullName);
					return false;
				}
				IsProcessingItems = true;
				MelonCoroutines.Start(SimulateItemCollection(storageEntity));
				return true;
			}
			catch (Exception ex)
			{
				Core.MelonLogger.Error("Error in TryCollectItemsFromStorage: " + ex.Message);
				IsProcessingItems = false;
				return false;
			}
		}

		private bool HasValidItemsForDealer(StorageEntity storageEntity)
		{
			//IL_0116: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				List<ItemInstance> allItems = storageEntity.GetAllItems();
				if (allItems == null)
				{
					Core.MelonLogger.Msg("Storage " + ((Object)storageEntity).name + " has no items array");
					return false;
				}
				List<ItemInstance> list = new List<ItemInstance>();
				Enumerator<ItemInstance> enumerator = allItems.GetEnumerator();
				while (enumerator.MoveNext())
				{
					ItemInstance current = enumerator.Current;
					if (current != null)
					{
						list.Add(current);
					}
				}
				Core.MelonLogger.Msg($"Dealer {((NPC)Dealer).fullName} checking storage {((Object)storageEntity).name}: {list.Count} total items");
				int num = 0;
				int num2 = 0;
				foreach (ItemInstance item in list)
				{
					if (item != null && (int)item.Category == 0 && !item.Name.Contains("Unpackaged"))
					{
						num++;
						num2 += item.Quantity;
						Core.MelonLogger.Msg($"  - Valid item: {item.Name} (Quantity: {item.Quantity})");
					}
				}
				if (num > 0)
				{
					Core.MelonLogger.Msg($"Found {num} valid item types with total quantity of {num2} in storage {((Object)storageEntity).name}");
					return true;
				}
				Core.MelonLogger.Msg("No valid items found in storage " + ((Object)storageEntity).name);
				return false;
			}
			catch (Exception ex)
			{
				Core.MelonLogger.Error("Error checking valid items: " + ex.Message);
				return false;
			}
		}

		private float CalculateTravelTime(StorageEntity storageEntity)
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				if ((Object)(object)((Component)Dealer).transform != (Object)null && (Object)(object)((Component)storageEntity).transform != (Object)null)
				{
					float num = Vector3.Distance(((Component)Dealer).transform.position, ((Component)storageEntity).transform.position);
					float num2 = Mathf.Max(5f, num * 0.5f);
					return num2 * Random.Range(0.8f, 1.2f);
				}
			}
			catch (Exception ex)
			{
				Core.MelonLogger.Warning("Error calculating travel distance: " + ex.Message + ". Using default time.");
			}
			return Random.Range(10f, 20f);
		}

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

		public int AddItemsFromStorage(StorageEntity storageEntity)
		{
			//IL_0137: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				if ((Object)(object)storageEntity == (Object)null)
				{
					Core.MelonLogger.Error("Cannot add items: storage entity is null");
					return 0;
				}
				List<ItemInstance> allItems = storageEntity.GetAllItems();
				if (allItems == null)
				{
					Core.MelonLogger.Error("Storage returned null items array");
					return 0;
				}
				List<ItemInstance> list = new List<ItemInstance>();
				Enumerator<ItemInstance> enumerator = allItems.GetEnumerator();
				while (enumerator.MoveNext())
				{
					ItemInstance current = enumerator.Current;
					if (current != null)
					{
						list.Add(current);
					}
				}
				int num = 0;
				int num2 = 0;
				int num3 = CalculateMaxItemsToTake();
				Core.MelonLogger.Msg($"Dealer {((NPC)Dealer).fullName} attempting to collect up to {num3} items from {list.Count} items in storage");
				List<ItemInstance> list2 = new List<ItemInstance>();
				foreach (ItemInstance item in list)
				{
					if (item != null && (int)item.Category == 0 && !item.Name.Contains("Unpackaged"))
					{
						list2.Add(item);
						Core.MelonLogger.Msg($"Found valid item: {item.Name} (Quantity: {item.Quantity})");
					}
				}
				Core.MelonLogger.Msg($"Found {list2.Count} valid item types in storage {((Object)storageEntity).name}");
				foreach (ItemInstance item2 in list2)
				{
					if (num2 >= num3)
					{
						break;
					}
					int num4 = Mathf.Min(item2.Quantity, num3 - num2);
					if (num4 > 0)
					{
						ItemInstance copy = item2.GetCopy(num4);
						if (copy == null)
						{
							Core.MelonLogger.Warning("Failed to create copy of item " + item2.Name);
							continue;
						}
						Dealer.AddItemToInventory(copy);
						item2.ChangeQuantity(-num4);
						num++;
						num2 += num4;
						Core.MelonLogger.Msg($"Transferred {num4} of {item2.Name} to dealer {((NPC)Dealer).fullName}");
					}
				}
				Core.MelonLogger.Msg($"Dealer {((NPC)Dealer).fullName} collected {num2} items (from {num} stacks) from storage {((Object)storageEntity).name}");
				return num2;
			}
			catch (Exception ex)
			{
				Core.MelonLogger.Error("Error adding items from storage: " + ex.Message + "\n" + ex.StackTrace);
				return 0;
			}
		}

		private int CalculateMaxItemsToTake()
		{
			try
			{
				List<ItemSlot> allSlots = Dealer.GetAllSlots();
				if (allSlots == null)
				{
					return 1;
				}
				List<ItemSlot> list = new List<ItemSlot>();
				Enumerator<ItemSlot> enumerator = allSlots.GetEnumerator();
				while (enumerator.MoveNext())
				{
					ItemSlot current = enumerator.Current;
					if (current != null)
					{
						list.Add(current);
					}
				}
				int num = 0;
				int num2 = 0;
				foreach (ItemSlot item in list)
				{
					if (item.ItemInstance != null)
					{
						num += item.ItemInstance.StackLimit;
						num2 += item.ItemInstance.Quantity;
					}
					else
					{
						num += 20;
					}
				}
				int num3 = num - num2;
				float num4 = 0.75f;
				if (Config.multipleDealersPerStorage.Value)
				{
					num4 = Config.dealerCollectionShareRate.Value;
					num4 = Mathf.Clamp(num4, 0.1f, 1f);
				}
				int num5 = Mathf.Max(1, Mathf.FloorToInt((float)num3 * num4));
				Core.MelonLogger.Msg($"Dealer {((NPC)Dealer).fullName} capacity: {num2}/{num}, Available capacity: {num3}, Share rate: {num4:P1}, Will take up to: {num5} items");
				return num5;
			}
			catch (Exception ex)
			{
				Core.MelonLogger.Error("Error calculating max items to take: " + ex.Message);
				return 1;
			}
		}
	}
	public class DealerExtensionUI
	{
		[CompilerGenerated]
		private sealed class <>c__DisplayClass56_0
		{
			public List<string> assignedDealerIds;

			public string dealerChoice;

			internal bool <HandleDealerSelection>b__2(Dealer d)
			{
				return !assignedDealerIds.Contains(((Object)d).name);
			}

			internal void <HandleDealerSelection>b__4(string result)
			{
				dealerChoice = result;
			}

			internal bool <HandleDealerSelection>b__5(DealerExtendedBrain d)
			{
				return ((Object)d.Dealer).name == dealerChoice;
			}
		}

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

			private object <>2__current;

			public DealerExtensionUI <>4__this;

			private <>c__DisplayClass56_0 <>8__1;

			private bool <allowMultipleDealers>5__2;

			private int <maxDealersPerStorage>5__3;

			private Vector2 <popupPosition>5__4;

			private List<(string, string)> <dealerOptions>5__5;

			private DealerExtendedBrain <selectedDealer>5__6;

			private bool <success>5__7;

			private List<StorageEntity> <existingStorages>5__8;

			private string <message>5__9;

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

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

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

			[DebuggerHidden]
			void IDisposable.Dispose()
			{
				<>8__1 = null;
				<dealerOptions>5__5 = null;
				<selectedDealer>5__6 = null;
				<existingStorages>5__8 = null;
				<message>5__9 = null;
				<>1__state = -2;
			}

			private bool MoveNext()
			{
				//IL_0067: Unknown result type (might be due to invalid IL or missing references)
				//IL_006c: Unknown result type (might be due to invalid IL or missing references)
				//IL_00de: Unknown result type (might be due to invalid IL or missing references)
				//IL_01e4: Unknown result type (might be due to invalid IL or missing references)
				switch (<>1__state)
				{
				default:
					return false;
				case 0:
					<>1__state = -1;
					<>8__1 = new <>c__DisplayClass56_0();
					<allowMultipleDealers>5__2 = Config.multipleDealersPerStorage.Value;
					<maxDealersPerStorage>5__3 = Config.maxDealersPerStorage.Value;
					<popupPosition>5__4 = new Vector2(0.66f, 0.94f);
					if (<allowMultipleDealers>5__2 && <>4__this.AssignedDealers.Count >= <maxDealersPerStorage>5__3)
					{
						<>2__current = FlexiblePopup.ShowPopupAndWaitForResult("Storage Full", new(string, string)[1] { ("This storage already has the maximum number of dealers. You can increase the limit in the mod config.", "OK") }, delegate
						{
						}, <popupPosition>5__4);
						<>1__state = 1;
						return true;
					}
					<>8__1.assignedDealerIds = <>4__this.AssignedDealers.Select((DealerExtendedBrain d) => ((Object)d.Dealer).name).ToList();
					<dealerOptions>5__5 = (from d in GameUtils.GetRecruitedDealers()
						where !<>8__1.assignedDealerIds.Contains(((Object)d).name)
						select (((NPC)d).fullName, ((Object)d).name)).ToList();
					if (<dealerOptions>5__5.Count == 0)
					{
						<dealerOptions>5__5.Add(("No more dealers available", "None"));
					}
					<>8__1.dealerChoice = null;
					<>2__current = FlexiblePopup.ShowPopupAndWaitForResult("Choose Dealer", <dealerOptions>5__5.ToArray(), delegate(string result)
					{
						<>8__1.dealerChoice = result;
					}, <popupPosition>5__4);
					<>1__state = 2;
					return true;
				case 1:
					<>1__state = -1;
					return false;
				case 2:
					<>1__state = -1;
					if (!string.IsNullOrEmpty(<>8__1.dealerChoice) && <>8__1.dealerChoice != "None")
					{
						<selectedDealer>5__6 = Core.DealerStorageManager.GetAllDealersExtendedBrain().FirstOrDefault((DealerExtendedBrain d) => ((Object)d.Dealer).name == <>8__1.dealerChoice);
						if (<selectedDealer>5__6 != null)
						{
							<success>5__7 = false;
							if (!<allowMultipleDealers>5__2)
							{
								<existingStorages>5__8 = Core.DealerStorageManager.GetAssignedStoragesForDealer(<selectedDealer>5__6);
								if (<existingStorages>5__8.Count > 0 && !<existingStorages>5__8.Contains(<>4__this.StorageEntity))
								{
									<message>5__9 = Messages.GetRandomDealerAlreadyAssignedMessage();
									((NPC)<selectedDealer>5__6.Dealer).SendTextMessage(<message>5__9);
									<message>5__9 = null;
								}
								else
								{
									<success>5__7 = Core.DealerStorageManager.SetDealerToStorage(<>4__this.StorageEntity, <selectedDealer>5__6);
								}
								<existingStorages>5__8 = null;
							}
							else
							{
								<success>5__7 = Core.DealerStorageManager.SetDealerToStorage(<>4__this.StorageEntity, <selectedDealer>5__6);
							}
							if (<success>5__7)
							{
								<>4__this.UpdateDealersList();
							}
						}
						<selectedDealer>5__6 = null;
					}
					return false;
				}
			}

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

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

		private bool isExpanded = false;

		private bool popupOpen = false;

		private bool closeUIDefault;

		private static KeyCode toggleKey;

		private GameObject noAssignmentText;

		private float dealerItemHeight = 40f;

		private Dictionary<DealerExtendedBrain, GameObject> dealerListItems = new Dictionary<DealerExtendedBrain, GameObject>();

		public Guid UIGUID { get; private set; }

		public StorageMenu StorageMenu { get; private set; }

		public StorageEntity StorageEntity { get; private set; }

		public List<DealerExtendedBrain> AssignedDealers { get; private set; }

		public GameObject DealerUIObject { get; private set; }

		public GameObject ScrollView { get; private set; }

		public GameObject Content { get; private set; }

		public GameObject AddButton { get; private set; }

		public GameObject MainPanel { get; private set; }

		public DealerExtensionUI(StorageMenu storageMenu, StorageEntity storageEntity)
		{
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: 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)
			toggleKey = Config.uiToggleKey.Value;
			closeUIDefault = Config.dealerStorageUIClosedByDefault.Value;
			UIGUID = default(Guid);
			StorageMenu = storageMenu;
			StorageEntity = storageEntity;
			AssignedDealers = new List<DealerExtendedBrain>();
			if ((Object)(object)storageEntity != (Object)null)
			{
				AssignedDealers = Core.DealerStorageManager.GetDealersFromStorage(storageEntity);
				CreateDealerStorageUI(storageMenu);
			}
			else
			{
				Core.MelonLogger.Error("StorageEntity is null in DealerExtensionUI constructor");
			}
		}

		public void CreateDealerStorageUI(StorageMenu menu)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Expected O, but got Unknown
			DealerUIObject = new GameObject("DealerUI");
			Object.DontDestroyOnLoad((Object)(object)DealerUIObject);
			Canvas val = DealerUIObject.AddComponent<Canvas>();
			val.renderMode = (RenderMode)0;
			val.sortingOrder = 100;
			DealerUIObject.AddComponent<GraphicRaycaster>();
			CreateToggleButton();
			CreateMainPanel();
			SetExpanded(expanded: false);
		}

		private void CreateToggleButton()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Expected O, but got Unknown
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: 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_00b1: Expected O, but got Unknown
			//IL_010b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0121: Unknown result type (might be due to invalid IL or missing references)
			//IL_012e: Unknown result type (might be due to invalid IL or missing references)
			//IL_013b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0148: Unknown result type (might be due to invalid IL or missing references)
			//IL_0167: Unknown result type (might be due to invalid IL or missing references)
			//IL_017e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0195: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c3: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject("ToggleButton");
			val.transform.SetParent(DealerUIObject.transform, false);
			Image val2 = val.AddComponent<Image>();
			((Graphic)val2).color = Styling.PRIMARY_COLOR;
			Button val3 = val.AddComponent<Button>();
			((Selectable)val3).targetGraphic = (Graphic)(object)val2;
			ColorBlock colors = ((Selectable)val3).colors;
			((ColorBlock)(ref colors)).normalColor = Styling.PRIMARY_COLOR;
			((ColorBlock)(ref colors)).highlightedColor = Styling.SECONDARY_COLOR;
			((ColorBlock)(ref colors)).pressedColor = Styling.SECONDARY_COLOR;
			((Selectable)val3).colors = colors;
			((UnityEventBase)val3.onClick).RemoveAllListeners();
			((UnityEvent)val3.onClick).AddListener(UnityAction.op_Implicit((Action)TogglePanel));
			GameObject val4 = new GameObject("Text");
			val4.transform.SetParent(val.transform, false);
			Text val5 = val4.AddComponent<Text>();
			val5.text = "$";
			val5.font = Resources.GetBuiltinResource<Font>("Arial.ttf");
			val5.fontSize = 18;
			val5.fontStyle = (FontStyle)1;
			val5.alignment = (TextAnchor)4;
			((Graphic)val5).color = Color.white;
			RectTransform component = val4.GetComponent<RectTransform>();
			component.anchorMin = Vector2.zero;
			component.anchorMax = Vector2.one;
			component.offsetMin = Vector2.zero;
			component.offsetMax = Vector2.zero;
			RectTransform component2 = val.GetComponent<RectTransform>();
			component2.anchorMin = new Vector2(0.5f, 1f);
			component2.anchorMax = new Vector2(0.5f, 1f);
			component2.pivot = new Vector2(0.5f, 1f);
			component2.anchoredPosition = new Vector2(0f, -10f);
			component2.sizeDelta = new Vector2(32f, 32f);
		}

		private void CreateMainPanel()
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Expected O, but got Unknown
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ca: 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_00e0: Expected O, but got Unknown
			//IL_012e: Unknown result type (might be due to invalid IL or missing references)
			//IL_014d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0164: Unknown result type (might be due to invalid IL or missing references)
			//IL_017b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0192: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c4: Expected O, but got Unknown
			//IL_0222: Unknown result type (might be due to invalid IL or missing references)
			//IL_0246: Unknown result type (might be due to invalid IL or missing references)
			//IL_025d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0274: Unknown result type (might be due to invalid IL or missing references)
			//IL_028b: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c4: Expected O, but got Unknown
			//IL_02f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0336: Unknown result type (might be due to invalid IL or missing references)
			//IL_033d: Expected O, but got Unknown
			//IL_0393: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_03b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_03c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_03e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_03fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_0415: Unknown result type (might be due to invalid IL or missing references)
			//IL_042c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0443: Unknown result type (might be due to invalid IL or missing references)
			MainPanel = new GameObject("Panel");
			MainPanel.transform.SetParent(DealerUIObject.transform, false);
			Image val = MainPanel.AddComponent<Image>();
			((Graphic)val).color = new Color(0.1f, 0.1f, 0.1f, 0.9f);
			RectTransform component = MainPanel.GetComponent<RectTransform>();
			component.anchorMin = new Vector2(0.5f, 1f);
			component.anchorMax = new Vector2(0.5f, 1f);
			component.pivot = new Vector2(0.5f, 1f);
			component.sizeDelta = new Vector2(220f, 300f);
			component.anchoredPosition = new Vector2(-10f, -50f);
			GameObject val2 = new GameObject("Title");
			val2.transform.SetParent(MainPanel.transform, false);
			Text val3 = val2.AddComponent<Text>();
			val3.text = "Dealer Assignments";
			val3.font = Resources.GetBuiltinResource<Font>("Arial.ttf");
			val3.fontSize = 16;
			val3.alignment = (TextAnchor)4;
			((Graphic)val3).color = Color.white;
			RectTransform component2 = val2.GetComponent<RectTransform>();
			component2.anchorMin = new Vector2(0f, 1f);
			component2.anchorMax = new Vector2(1f, 1f);
			component2.pivot = new Vector2(0.5f, 1f);
			component2.sizeDelta = new Vector2(0f, 30f);
			component2.anchoredPosition = new Vector2(0f, 0f);
			noAssignmentText = new GameObject("NoAssignmentText");
			noAssignmentText.transform.SetParent(MainPanel.transform, false);
			Text val4 = noAssignmentText.AddComponent<Text>();
			val4.text = "No dealers assigned";
			val4.font = Resources.GetBuiltinResource<Font>("Arial.ttf");
			val4.fontSize = 14;
			val4.alignment = (TextAnchor)4;
			((Graphic)val4).color = Color.white;
			RectTransform component3 = noAssignmentText.GetComponent<RectTransform>();
			component3.anchorMin = new Vector2(0f, 0.5f);
			component3.anchorMax = new Vector2(1f, 0.5f);
			component3.pivot = new Vector2(0.5f, 0.5f);
			component3.sizeDelta = new Vector2(0f, 30f);
			component3.anchoredPosition = new Vector2(0f, 0f);
			CreateScrollView();
			AddButton = new GameObject("AddDealerButton");
			AddButton.transform.SetParent(MainPanel.transform, false);
			Image val5 = AddButton.AddComponent<Image>();
			((Graphic)val5).color = Styling.PRIMARY_COLOR;
			Button val6 = AddButton.AddComponent<Button>();
			((Selectable)val6).targetGraphic = (Graphic)(object)val5;
			((UnityEvent)val6.onClick).AddListener(UnityAction.op_Implicit((Action)OnAddDealerButtonClicked));
			GameObject val7 = new GameObject("Text");
			val7.transform.SetParent(AddButton.transform, false);
			Text val8 = val7.AddComponent<Text>();
			val8.text = "Add Dealer";
			val8.font = Resources.GetBuiltinResource<Font>("Arial.ttf");
			val8.fontSize = 14;
			val8.alignment = (TextAnchor)4;
			((Graphic)val8).color = Color.white;
			RectTransform component4 = val7.GetComponent<RectTransform>();
			component4.anchorMin = Vector2.zero;
			component4.anchorMax = Vector2.one;
			component4.sizeDelta = Vector2.zero;
			RectTransform component5 = AddButton.GetComponent<RectTransform>();
			component5.anchorMin = new Vector2(0f, 0f);
			component5.anchorMax = new Vector2(1f, 0f);
			component5.pivot = new Vector2(0.5f, 0f);
			component5.sizeDelta = new Vector2(-40f, 40f);
			component5.anchoredPosition = new Vector2(0f, 5f);
			UpdateDealersList();
		}

		private void CreateScrollView()
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Expected O, but got Unknown
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: 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_00f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fb: Expected O, but got Unknown
			//IL_0127: Unknown result type (might be due to invalid IL or missing references)
			//IL_0134: Unknown result type (might be due to invalid IL or missing references)
			//IL_0141: Unknown result type (might be due to invalid IL or missing references)
			//IL_0158: Unknown result type (might be due to invalid IL or missing references)
			//IL_0181: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ad: Expected O, but got Unknown
			//IL_01ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_0205: Unknown result type (might be due to invalid IL or missing references)
			//IL_021c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0233: Unknown result type (might be due to invalid IL or missing references)
			//IL_0240: Unknown result type (might be due to invalid IL or missing references)
			//IL_026d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0277: Expected O, but got Unknown
			ScrollView = new GameObject("ScrollView");
			ScrollView.transform.SetParent(MainPanel.transform, false);
			RectTransform val = ScrollView.GetComponent<RectTransform>() ?? ScrollView.AddComponent<RectTransform>();
			val.anchorMin = new Vector2(0f, 0f);
			val.anchorMax = new Vector2(1f, 1f);
			val.pivot = new Vector2(0.5f, 0.5f);
			val.sizeDelta = new Vector2(-20f, -110f);
			val.anchoredPosition = new Vector2(0f, -10f);
			Image val2 = ScrollView.AddComponent<Image>();
			((Graphic)val2).color = new Color(0.05f, 0.05f, 0.05f, 0.3f);
			ScrollRect val3 = ScrollView.AddComponent<ScrollRect>();
			GameObject val4 = new GameObject("Viewport");
			val4.transform.SetParent(ScrollView.transform, false);
			RectTransform val5 = val4.GetComponent<RectTransform>() ?? val4.AddComponent<RectTransform>();
			val5.anchorMin = Vector2.zero;
			val5.anchorMax = Vector2.one;
			val5.sizeDelta = Vector2.zero;
			val5.pivot = new Vector2(0.5f, 0.5f);
			Image val6 = val4.AddComponent<Image>();
			((Graphic)val6).color = new Color(0.1f, 0.1f, 0.1f, 0.01f);
			Mask val7 = val4.AddComponent<Mask>();
			val7.showMaskGraphic = false;
			Content = new GameObject("Content");
			Content.transform.SetParent(val4.transform, false);
			RectTransform val8 = Content.GetComponent<RectTransform>() ?? Content.AddComponent<RectTransform>();
			val8.anchorMin = new Vector2(0f, 1f);
			val8.anchorMax = new Vector2(1f, 1f);
			val8.pivot = new Vector2(0.5f, 1f);
			val8.sizeDelta = new Vector2(0f, 10f);
			val8.anchoredPosition = Vector2.zero;
			VerticalLayoutGroup val9 = Content.AddComponent<VerticalLayoutGroup>();
			((HorizontalOrVerticalLayoutGroup)val9).spacing = 8f;
			((LayoutGroup)val9).padding = new RectOffset(10, 10, 5, 5);
			((LayoutGroup)val9).childAlignment = (TextAnchor)1;
			((HorizontalOrVerticalLayoutGroup)val9).childControlHeight = false;
			((HorizontalOrVerticalLayoutGroup)val9).childForceExpandHeight = false;
			((HorizontalOrVerticalLayoutGroup)val9).childControlWidth = true;
			((HorizontalOrVerticalLayoutGroup)val9).childForceExpandWidth = true;
			ContentSizeFitter val10 = Content.AddComponent<ContentSizeFitter>();
			val10.verticalFit = (FitMode)2;
			val3.content = val8;
			val3.viewport = val5;
			val3.horizontal = false;
			val3.vertical = true;
			val3.scrollSensitivity = 20f;
			val3.movementType = (MovementType)1;
			val3.elasticity = 0.1f;
		}

		private GameObject CreateDealerListItem(DealerExtendedBrain dealer)
		{
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Expected O, but got Unknown
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cd: Expected O, but got Unknown
			//IL_0129: Unknown result type (might be due to invalid IL or missing references)
			//IL_0149: Unknown result type (might be due to invalid IL or missing references)
			//IL_0160: Unknown result type (might be due to invalid IL or missing references)
			//IL_0177: Unknown result type (might be due to invalid IL or missing references)
			//IL_018e: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bc: Expected O, but got Unknown
			//IL_01db: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0200: Unknown result type (might be due to invalid IL or missing references)
			//IL_0204: Unknown result type (might be due to invalid IL or missing references)
			//IL_0225: Unknown result type (might be due to invalid IL or missing references)
			//IL_0232: Unknown result type (might be due to invalid IL or missing references)
			//IL_025d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0264: Expected O, but got Unknown
			//IL_02b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_02cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0306: Unknown result type (might be due to invalid IL or missing references)
			//IL_031d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0334: Unknown result type (might be due to invalid IL or missing references)
			//IL_034b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0362: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject("DealerItem_" + ((Object)dealer.Dealer).name);
			val.transform.SetParent(Content.transform, false);
			Image val2 = val.AddComponent<Image>();
			((Graphic)val2).color = new Color(0.2f, 0.2f, 0.2f, 0.9f);
			LayoutElement val3 = val.AddComponent<LayoutElement>();
			val3.minHeight = dealerItemHeight;
			val3.preferredHeight = dealerItemHeight;
			val3.flexibleWidth = 1f;
			RectTransform component = val.GetComponent<RectTransform>();
			component.sizeDelta = new Vector2(0f, dealerItemHeight);
			GameObject val4 = new GameObject("DealerName");
			val4.transform.SetParent(val.transform, false);
			Text val5 = val4.AddComponent<Text>();
			val5.text = ((NPC)dealer.Dealer).fullName;
			val5.font = Resources.GetBuiltinResource<Font>("Arial.ttf");
			val5.fontSize = 14;
			val5.alignment = (TextAnchor)3;
			((Graphic)val5).color = Color.white;
			RectTransform component2 = val4.GetComponent<RectTransform>();
			component2.anchorMin = new Vector2(0f, 0f);
			component2.anchorMax = new Vector2(1f, 1f);
			component2.pivot = new Vector2(0f, 0.5f);
			component2.offsetMin = new Vector2(10f, 0f);
			component2.offsetMax = new Vector2(-30f, 0f);
			GameObject val6 = new GameObject("RemoveButton");
			val6.transform.SetParent(val.transform, false);
			Image val7 = val6.AddComponent<Image>();
			((Graphic)val7).color = Styling.DESTRUCTIVE_COLOR;
			Button val8 = val6.AddComponent<Button>();
			((Selectable)val8).targetGraphic = (Graphic)(object)val7;
			ColorBlock colors = ((Selectable)val8).colors;
			((ColorBlock)(ref colors)).normalColor = Styling.DESTRUCTIVE_COLOR;
			((ColorBlock)(ref colors)).highlightedColor = new Color(1f, 0.3f, 0.3f, 1f);
			((Selectable)val8).colors = colors;
			((UnityEvent)val8.onClick).AddListener(UnityAction.op_Implicit((Action)delegate
			{
				RemoveDealerFromStorage(dealer);
			}));
			GameObject val9 = new GameObject("X");
			val9.transform.SetParent(val6.transform, false);
			Text val10 = val9.AddComponent<Text>();
			val10.text = "X";
			val10.font = Resources.GetBuiltinResource<Font>("Arial.ttf");
			val10.fontSize = 14;
			val10.alignment = (TextAnchor)4;
			((Graphic)val10).color = Color.white;
			RectTransform component3 = val9.GetComponent<RectTransform>();
			component3.anchorMin = Vector2.zero;
			component3.anchorMax = Vector2.one;
			component3.sizeDelta = Vector2.zero;
			RectTransform component4 = val6.GetComponent<RectTransform>();
			component4.anchorMin = new Vector2(1f, 0.5f);
			component4.anchorMax = new Vector2(1f, 0.5f);
			component4.pivot = new Vector2(1f, 0.5f);
			component4.anchoredPosition = new Vector2(-5f, 0f);
			component4.sizeDelta = new Vector2(24f, 24f);
			return val;
		}

		private void RemoveDealerFromStorage(DealerExtendedBrain dealer)
		{
			Core.DealerStorageManager.RemoveDealerFromStorage(StorageEntity, dealer);
			UpdateDealersList();
		}

		private void UpdateDealersList()
		{
			//IL_014d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0159: Unknown result type (might be due to invalid IL or missing references)
			foreach (GameObject value2 in dealerListItems.Values)
			{
				Object.Destroy((Object)(object)value2);
			}
			dealerListItems.Clear();
			AssignedDealers = Core.DealerStorageManager.GetDealersFromStorage(StorageEntity);
			if ((Object)(object)noAssignmentText != (Object)null)
			{
				noAssignmentText.SetActive(AssignedDealers.Count == 0);
			}
			foreach (DealerExtendedBrain assignedDealer in AssignedDealers)
			{
				if ((Object)(object)assignedDealer?.Dealer != (Object)null)
				{
					GameObject value = CreateDealerListItem(assignedDealer);
					dealerListItems.Add(assignedDealer, value);
				}
			}
			if ((Object)(object)Content != (Object)null)
			{
				RectTransform component = Content.GetComponent<RectTransform>();
				if ((Object)(object)component != (Object)null)
				{
					float num = (dealerItemHeight + 5f) * (float)AssignedDealers.Count + 20f;
					component.sizeDelta = new Vector2(component.sizeDelta.x, num);
				}
				Canvas.ForceUpdateCanvases();
				LayoutRebuilder.ForceRebuildLayoutImmediate(Content.GetComponent<RectTransform>());
			}
		}

		private void TogglePanel()
		{
			SetExpanded(!isExpanded);
			if (popupOpen)
			{
				FlexiblePopup.ClosePopup();
			}
		}

		private void SetExpanded(bool expanded)
		{
			isExpanded = expanded;
			if ((Object)(object)MainPanel != (Object)null)
			{
				MainPanel.SetActive(expanded);
			}
		}

		public void ToggleUI(bool open)
		{
			if (open)
			{
				UpdateDealersList();
			}
			if ((Object)(object)DealerUIObject != (Object)null)
			{
				DealerUIObject.SetActive(open);
				if (open && closeUIDefault)
				{
					SetExpanded(expanded: false);
				}
			}
			if (!open)
			{
				FlexiblePopup.ClosePopup();
			}
		}

		public void Update()
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)DealerUIObject != (Object)null && DealerUIObject.activeSelf && Input.GetKeyDown(toggleKey))
			{
				TogglePanel();
			}
			if ((Object)(object)DealerUIObject != (Object)null && DealerUIObject.activeSelf && Input.GetKeyDown((KeyCode)27))
			{
				ToggleUI(open: false);
			}
		}

		public void OnAddDealerButtonClicked()
		{
			MelonCoroutines.Start(HandleDealerSelection());
		}

		[IteratorStateMachine(typeof(<HandleDealerSelection>d__56))]
		private IEnumerator HandleDealerSelection()
		{
			//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
			return new <HandleDealerSelection>d__56(0)
			{
				<>4__this = this
			};
		}
	}
	[Serializable]
	public class DealerStorageAssignment
	{
		public float PosX { get; set; }

		public float PosY { get; set; }

		public float PosZ { get; set; }

		public string DealerName { get; set; }

		[JsonIgnore]
		public Vector3 StorageEntityPosition
		{
			get
			{
				//IL_0013: Unknown result type (might be due to invalid IL or missing references)
				//IL_0018: Unknown result type (might be due to invalid IL or missing references)
				//IL_001b: Unknown result type (might be due to invalid IL or missing references)
				return new Vector3(PosX, PosY, PosZ);
			}
			set
			{
				//IL_0002: Unknown result type (might be due to invalid IL or missing references)
				//IL_000f: Unknown result type (might be due to invalid IL or missing references)
				//IL_001c: Unknown result type (might be due to invalid IL or missing references)
				PosX = value.x;
				PosY = value.y;
				PosZ = value.z;
			}
		}
	}
	public class DealerStorageManager
	{
		[CompilerGenerated]
		private sealed class <>c__DisplayClass27_0
		{
			public DealerStorageAssignment assignment;

			internal bool <RestoreDealerAssignments>b__0(Dealer d)
			{
				return ((NPC)d).fullName == assignment.DealerName;
			}
		}

		[CompilerGenerated]
		private sealed class <>c__DisplayClass27_1
		{
			public Dealer matchedDealer;

			internal bool <RestoreDealerAssignments>b__1(DealerExtendedBrain d)
			{
				return (Object)(object)d.Dealer == (Object)(object)matchedDealer;
			}
		}

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

			private object <>2__current;

			public List<DealerStorageAssignment> assignments;

			public DealerStorageManager <>4__this;

			private int <restoredCount>5__1;

			private List<Dealer> <allDealers>5__2;

			private List<StorageEntity> <allStorages>5__3;

			private List<StorageEntity>.Enumerator <>s__4;

			private StorageEntity <storage>5__5;

			private List<DealerStorageAssignment>.Enumerator <>s__6;

			private <>c__DisplayClass27_0 <>8__7;

			private <>c__DisplayClass27_1 <>8__8;

			private StorageEntity <matchedStorage>5__9;

			private float <closestDistance>5__10;

			private DealerExtendedBrain <dealerBrain>5__11;

			private bool <success>5__12;

			private List<StorageEntity>.Enumerator <>s__13;

			private StorageEntity <storage>5__14;

			private float <distance>5__15;

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

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

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

			[DebuggerHidden]
			void IDisposable.Dispose()
			{
				<allDealers>5__2 = null;
				<allStorages>5__3 = null;
				<>s__4 = default(List<StorageEntity>.Enumerator);
				<storage>5__5 = null;
				<>s__6 = default(List<DealerStorageAssignment>.Enumerator);
				<>8__7 = null;
				<>8__8 = null;
				<matchedStorage>5__9 = null;
				<dealerBrain>5__11 = null;
				<>s__13 = default(List<StorageEntity>.Enumerator);
				<storage>5__14 = null;
				<>1__state = -2;
			}

			private bool MoveNext()
			{
				//IL_0026: Unknown result type (might be due to invalid IL or missing references)
				//IL_0030: Expected O, but got Unknown
				//IL_013a: Unknown result type (might be due to invalid IL or missing references)
				//IL_01f7: Unknown result type (might be due to invalid IL or missing references)
				//IL_02df: Unknown result type (might be due to invalid IL or missing references)
				//IL_02ef: Unknown result type (might be due to invalid IL or missing references)
				//IL_03e0: Unknown result type (might be due to invalid IL or missing references)
				//IL_039b: Unknown result type (might be due to invalid IL or missing references)
				switch (<>1__state)
				{
				default:
					return false;
				case 0:
					<>1__state = -1;
					<>2__current = (object)new WaitForSeconds(2f);
					<>1__state = 1;
					return true;
				case 1:
					<>1__state = -1;
					<restoredCount>5__1 = 0;
					<allDealers>5__2 = GameUtils.GetRecruitedDealers();
					<allStorages>5__3 = <>4__this.FindAllStorageEntities();
					Core.MelonLogger.Msg($"Found {<allDealers>5__2.Count} dealers and {<allStorages>5__3.Count} storage entities");
					<>s__4 = <allStorages>5__3.GetEnumerator();
					try
					{
						while (<>s__4.MoveNext())
						{
							<storage>5__5 = <>s__4.Current;
							Core.MelonLogger.Msg($"Storage: {((Object)<storage>5__5).name}, Position: {((Component)<storage>5__5).transform.position}");
							<storage>5__5 = null;
						}