Decompiled source of HighBaller v2.7.12

mods/HighBaller-IL2CPP.dll

Decompiled 13 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using HarmonyLib;
using HighBaller;
using HighBaller.Automation;
using HighBaller.Core;
using HighBaller.Core.Models;
using HighBaller.Helpers;
using HighBaller.UI;
using Il2CppFishNet;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppScheduleOne;
using Il2CppScheduleOne.Core.Items.Framework;
using Il2CppScheduleOne.DevUtilities;
using Il2CppScheduleOne.Economy;
using Il2CppScheduleOne.GameTime;
using Il2CppScheduleOne.ItemFramework;
using Il2CppScheduleOne.Levelling;
using Il2CppScheduleOne.Messaging;
using Il2CppScheduleOne.NPCs;
using Il2CppScheduleOne.NPCs.Relation;
using Il2CppScheduleOne.Persistence;
using Il2CppScheduleOne.PlayerScripts;
using Il2CppScheduleOne.Product;
using Il2CppScheduleOne.Product.Packaging;
using Il2CppScheduleOne.Quests;
using Il2CppScheduleOne.UI;
using Il2CppScheduleOne.UI.Handover;
using Il2CppScheduleOne.UI.Phone;
using Il2CppScheduleOne.UI.Phone.ContactsApp;
using Il2CppScheduleOne.UI.Phone.Messages;
using Il2CppScheduleOne.UI.Phone.ProductManagerApp;
using Il2CppSystem;
using Il2CppSystem.Collections.Generic;
using MelonLoader;
using MelonLoader.Preferences;
using Microsoft.CodeAnalysis;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: MelonInfo(typeof(Main), "HighBaller", "2.7.12", "xyrilyn, zocke18r, SFox & Virtunerd", null)]
[assembly: MelonAdditionalCredits("Original Deal Optimizer by xyrilyn; 0.4.7f6 compat by k0Mods; 0.4.7f12 update")]
[assembly: MelonGame("TVGS", "Schedule I")]
[assembly: MelonPlatformDomain(/*Could not decode attribute arguments.*/)]
[assembly: MelonOptionalDependencies(new string[] { "Il2CppInterop.Runtime", "Il2Cppmscorlib", "Il2CppScheduleOne.Core", "Il2CppFishNet.Runtime", "System.Collections", "System.Linq" })]
[assembly: HarmonyDontPatchAll]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("xyrilyn, zocke18r, SFox, Virtunerd, k0Mods")]
[assembly: AssemblyConfiguration("IL2CPP")]
[assembly: AssemblyDescription("Deal optimizer, auto counter offer, auto deal completion")]
[assembly: AssemblyFileVersion("2.7.12.0")]
[assembly: AssemblyInformationalVersion("2.7.12+c40c9e5d28a59089ea21e8a8feb2c69982087237")]
[assembly: AssemblyProduct("HighBaller-IL2CPP")]
[assembly: AssemblyTitle("HighBaller-IL2CPP")]
[assembly: AssemblyVersion("2.7.12.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace HighBaller
{
	public static class Config
	{
		private static MelonPreferences_Category _dealOptimizerCategory;

		internal static MelonPreferences_Entry<float> MinSuccessProbability;

		internal static MelonPreferences_Entry<bool> PriceOptimizationEnabled;

		internal static MelonPreferences_Entry<bool> CounterOfferDarkModeEnabled;

		private static MelonPreferences_Category _dealOptimizerCategoryAutomation;

		internal static MelonPreferences_Entry<bool> AutoCounterOfferEnabled;

		internal static MelonPreferences_Entry<bool> AutoContractAcceptedEnabled;

		internal static MelonPreferences_Entry<DealWindow> AutoContractAcceptedWindow;

		internal static MelonPreferences_Entry<bool> IncreaseQuantityEnabled;

		internal static MelonPreferences_Entry<bool> RoundQuantityToNearest5;

		internal static MelonPreferences_Entry<bool> AutoHandoverEnabled;

		internal static MelonPreferences_Entry<bool> AlwaysAcceptCounterOffersEnabled;

		private static MelonPreferences_Category _dealOptimizerCategoryFeatures;

		internal static MelonPreferences_Entry<bool> DelayAutoResponseDuringSave;

		internal static MelonPreferences_Entry<bool> DebugModeEnabled;

		private static MelonPreferences_Entry<S1APINPCHandling> _customNpcHandling;

		private static bool _s1APIResolved;

		private static Type _s1APINpcType;

		private static FieldInfo _s1NpcField;

		private static FieldInfo _isCustomField;

		private static FieldInfo _allField;

		public static void Initialize()
		{
			_dealOptimizerCategory = MelonPreferences.CreateCategory("HighBaller_IL2CPP", "High Baller");
			MinSuccessProbability = _dealOptimizerCategory.CreateEntry<float>("MinSuccessProbability", 0.98f, "Minimum Success Probability", "The minimum probability of success required for a deal [0.00, 0.99]", false, false, (ValueValidator)(object)new ValueRange<float>(0f, 0.99f), (string)null);
			PriceOptimizationEnabled = _dealOptimizerCategory.CreateEntry<bool>("PriceOptimizationEnabled", false, "Price Optimization Enabled", "Whether to enable price optimization", false, false, (ValueValidator)null, (string)null);
			CounterOfferDarkModeEnabled = _dealOptimizerCategory.CreateEntry<bool>("CounterOfferDarkModeEnabled", true, "Counter Offer Dark Mode", "Whether to enable counter offer dark mode", false, false, (ValueValidator)null, (string)null);
			_dealOptimizerCategoryAutomation = MelonPreferences.CreateCategory("HighBaller_IL2CPP_Automation", "High Baller Automation");
			AutoCounterOfferEnabled = _dealOptimizerCategoryAutomation.CreateEntry<bool>("AutoCounterOfferEnabled", false, "Enable Auto Counter Offer", "Whether to enable auto counter offer", false, false, (ValueValidator)null, (string)null);
			AutoContractAcceptedEnabled = _dealOptimizerCategoryAutomation.CreateEntry<bool>("AutoContractAcceptedEnabled", false, "Enable Auto Deal Scheduling", "Whether to enable auto deal scheduling", false, false, (ValueValidator)null, (string)null);
			AutoContractAcceptedWindow = _dealOptimizerCategoryAutomation.CreateEntry<DealWindow>("AutoDealWindow", DealWindow.LateNight, "Auto Deal Time Window", "The window to auto accept deal. Current falls back to the next window once the current one is too close to its cutoff.", false, false, (ValueValidator)null, "AutoContractAcceptedWindow");
			AlwaysAcceptCounterOffersEnabled = _dealOptimizerCategoryAutomation.CreateEntry<bool>("AlwaysAcceptCounterOffersEnabled", false, "Always Accept Counter Offers", "Force every customer counter-offer evaluation to succeed (regardless of price/quantity).", false, false, (ValueValidator)null, (string)null);
			IncreaseQuantityEnabled = _dealOptimizerCategoryAutomation.CreateEntry<bool>("IncreaseQuantityEnabled", false, "Increase Quantity till max spend", "If enabled, the quantity will be increased until the max spend is reached", false, false, (ValueValidator)null, (string)null);
			RoundQuantityToNearest5 = _dealOptimizerCategoryAutomation.CreateEntry<bool>("RoundQuantityToNearest5", false, "Round quantity to nearest 5", "If enabled, suggested/auto counter-offer quantities are rounded to the nearest multiple of 5 (minimum 5) and re-priced", false, false, (ValueValidator)null, (string)null);
			AutoHandoverEnabled = _dealOptimizerCategoryAutomation.CreateEntry<bool>("AutoHandoverEnabled", false, "Enable automatic handovers", "Whether to enable automatic handover", false, false, (ValueValidator)null, (string)null);
			_dealOptimizerCategoryFeatures = MelonPreferences.CreateCategory("HighBaller_IL2CPP_Features");
			DelayAutoResponseDuringSave = _dealOptimizerCategoryFeatures.CreateEntry<bool>("DelayAutoResponseDuringSave", true, "Don't send auto responses during save", "Whether to delay auto response during save", false, false, (ValueValidator)null, (string)null);
			DebugModeEnabled = _dealOptimizerCategoryFeatures.CreateEntry<bool>("DebugModeEnabled", false, "Debug Mode Enabled", "Enables a lot of logging in the console if needed", false, false, (ValueValidator)null, (string)null);
			_customNpcHandling = _dealOptimizerCategoryFeatures.CreateEntry<S1APINPCHandling>("S1APINPCHandling", S1APINPCHandling.Include, "S1API Custom NPC Handling", "NoAutomation allows orders but skips auto counter-offer/scheduling/handover. Exclude skips all mod features for custom NPCs.", false, false, (ValueValidator)null, "CustomNPCHandling");
		}

		public static S1APINPCHandling GetCustomNpcMode(NPC npc)
		{
			if ((Object)(object)npc == (Object)null || _customNpcHandling.Value == S1APINPCHandling.Include)
			{
				return S1APINPCHandling.Include;
			}
			try
			{
				if (!TryResolveS1ApiMembers() || !(_allField.GetValue(null) is IEnumerable enumerable))
				{
					return S1APINPCHandling.Include;
				}
				foreach (object item in enumerable)
				{
					if (item != null)
					{
						object? value = _s1NpcField.GetValue(item);
						NPC val = (NPC)((value is NPC) ? value : null);
						if (val != null && !((Object)(object)val != (Object)(object)npc))
						{
							object value2 = _isCustomField.GetValue(item);
							return (value2 is bool && (bool)value2) ? _customNpcHandling.Value : S1APINPCHandling.Include;
						}
					}
				}
			}
			catch (Exception ex)
			{
				Main.Log("GetCustomNpcMode error: " + ex.Message, error: false, warning: true);
			}
			return S1APINPCHandling.Include;
		}

		private static bool TryResolveS1ApiMembers()
		{
			if (_s1APIResolved)
			{
				if (_s1APINpcType != null && _s1NpcField != null && _isCustomField != null)
				{
					return _allField != null;
				}
				return false;
			}
			_s1APIResolved = true;
			Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
			for (int i = 0; i < assemblies.Length; i++)
			{
				_s1APINpcType = assemblies[i].GetType("S1API.Entities.NPC");
				if (_s1APINpcType != null)
				{
					break;
				}
			}
			if (_s1APINpcType == null)
			{
				return false;
			}
			_s1NpcField = _s1APINpcType.GetField("S1NPC", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			_isCustomField = _s1APINpcType.GetField("IsCustomNPC", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			_allField = _s1APINpcType.GetField("All", BindingFlags.Static | BindingFlags.Public);
			Main.Log($"S1API detected: NPC type={_s1APINpcType.FullName}, S1NPC={_s1NpcField != null}, IsCustomNPC={_isCustomField != null}, All={_allField != null}", error: false, warning: false, bypassConfig: true);
			if (_s1NpcField != null && _isCustomField != null)
			{
				return _allField != null;
			}
			return false;
		}
	}
	public enum DealWindow
	{
		Morning = 1,
		Afternoon,
		Night,
		LateNight,
		Current
	}
	public enum S1APINPCHandling
	{
		Include,
		NoAutomation,
		Exclude
	}
	public class Main : MelonMod
	{
		internal const string MelonName = "HighBaller";

		internal static bool SuppressNextPriceEval;

		private string _lastCounterofferPriceText;

		private bool _listening;

		internal UIHandler UIHandler;

		public static void Log(string message, bool error = false, bool warning = false, bool bypassConfig = false)
		{
			if (Config.DebugModeEnabled.Value || bypassConfig)
			{
				if (error)
				{
					Melon<Main>.Logger.Error(message);
				}
				else if (warning)
				{
					Melon<Main>.Logger.Warning(message);
				}
				else
				{
					Melon<Main>.Logger.Msg(message);
				}
			}
		}

		public override void OnInitializeMelon()
		{
			UIHandler = new UIHandler();
			Config.Initialize();
			((MelonBase)this).HarmonyInstance.PatchAll(typeof(Main).Assembly);
			Log("Initialized HighBaller Fixed v" + ((MelonBase)this).Info.Version, error: false, warning: false, bypassConfig: true);
			Log("DebugMode is " + (Config.DebugModeEnabled.Value ? "enabled" : "disabled") + ", logs will show if it is enabled.", error: false, warning: false, bypassConfig: true);
		}

		public override void OnGUI()
		{
			UIHandler.OnGUI();
		}

		public override void OnSceneWasLoaded(int buildIndex, string sceneName)
		{
			if (sceneName != "Main")
			{
				return;
			}
			try
			{
				Il2CppArrayBase<ProductManager> val = Object.FindObjectsOfType<ProductManager>();
				if (val != null && val.Length > 0)
				{
					ProductManager value = val[0];
					Log($"ProductManager: {value}");
				}
				else
				{
					Log("No ProductManager found in scene.", error: false, warning: true);
				}
			}
			catch (Exception ex)
			{
				Log("Error finding ProductManager: " + ex.Message, error: false, warning: false, bypassConfig: true);
			}
		}

		public override void OnSceneWasUnloaded(int buildIndex, string sceneName)
		{
			if (_listening)
			{
				_listening = false;
			}
			_lastCounterofferPriceText = null;
		}

		public override void OnUpdate()
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			Scene activeScene = SceneManager.GetActiveScene();
			bool num = ((Scene)(ref activeScene)).name == "Main";
			MessagesApp instance = PlayerSingleton<MessagesApp>.Instance;
			if (num && !_listening && (Object)(object)instance != (Object)null)
			{
				Subscribe();
			}
			if (num && (Object)(object)instance != (Object)null && (Object)(object)instance.CounterofferInterface != (Object)null && (Object)(object)instance.CounterofferInterface.PriceSelector != (Object)null && instance.CounterofferInterface.IsOpen)
			{
				string text = instance.CounterofferInterface.PriceSelector.SelectedAmount.ToString(CultureInfo.InvariantCulture);
				if (!string.Equals(_lastCounterofferPriceText, text, StringComparison.Ordinal))
				{
					_lastCounterofferPriceText = text;
					OfferEvaluator.OfferPriceChangeCheckWithLog();
				}
			}
			else
			{
				_lastCounterofferPriceText = null;
			}
		}

		private void Subscribe()
		{
			MessagesApp instance = PlayerSingleton<MessagesApp>.Instance;
			if ((Object)(object)instance == (Object)null || (Object)(object)instance.CounterofferInterface == (Object)null || (Object)(object)instance.CounterofferInterface.PriceSelector == (Object)null)
			{
				Log("Listener attachment skipped because the counter-offer UI is not ready.", error: false, warning: true);
				return;
			}
			Log("Counter-offer polling initialized");
			_listening = true;
		}
	}
}
namespace HighBaller.UI
{
	internal static class CustomerInfoFormatter
	{
		private static string FormatCurrency(float amount)
		{
			return $"${amount:F2}";
		}

		private static List<EDay> GetSortedOrderDays(List<EDay> orderDays, EDay currentDay)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			return orderDays.OrderBy(delegate(EDay day)
			{
				//IL_0000: Unknown result type (might be due to invalid IL or missing references)
				//IL_0002: Unknown result type (might be due to invalid IL or missing references)
				//IL_0007: Unknown result type (might be due to invalid IL or missing references)
				//IL_0009: Expected I4, but got Unknown
				int num = day - currentDay;
				if (num < 0)
				{
					num += 7;
				}
				return num;
			}).ToList();
		}

		internal static string FormatCustomerInfo(Customer customer, CustomerData customerData, NPCRelationData relationData, EDay currentDay)
		{
			//IL_00a8: 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_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01db: Unknown result type (might be due to invalid IL or missing references)
			//IL_022e: Unknown result type (might be due to invalid IL or missing references)
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.Append("<section>Customer Details</section>\n<label>Name:</label> <value>").Append(customer.NPC.FullName).Append("</value>\n");
			if ((Object)(object)customer.AssignedDealer != (Object)null)
			{
				stringBuilder.Append("<label>Assigned Dealer:</label> <value>").Append(((NPC)customer.AssignedDealer).FirstName).Append(' ')
					.Append(((NPC)customer.AssignedDealer).LastName)
					.Append("</value>\n");
			}
			List<EDay> val = new List<EDay>();
			customerData.GetOrderDays(customer.CurrentAddiction, relationData.RelationDelta / 5f, val);
			List<EDay> list = new List<EDay>();
			Enumerator<EDay> enumerator = val.GetEnumerator();
			while (enumerator.MoveNext())
			{
				EDay current = enumerator.Current;
				list.Add(current);
			}
			float adjustedWeeklySpend = customerData.GetAdjustedWeeklySpend(relationData.RelationDelta / 5f);
			float amount = adjustedWeeklySpend * 3f / (float)list.Count;
			float value = adjustedWeeklySpend / customerData.GetAdjustedWeeklySpend(1f) * 100f;
			StringBuilder stringBuilder2 = stringBuilder.Append("<section>Financial Information</section>\n");
			StringBuilder.AppendInterpolatedStringHandler handler = new StringBuilder.AppendInterpolatedStringHandler(42, 1, stringBuilder2);
			handler.AppendLiteral("<label>Max Spend:</label> <value>");
			handler.AppendFormatted(FormatCurrency(customerData.MaxWeeklySpend));
			handler.AppendLiteral("</value>\n");
			StringBuilder stringBuilder3 = stringBuilder2.Append(ref handler);
			StringBuilder.AppendInterpolatedStringHandler handler2 = new StringBuilder.AppendInterpolatedStringHandler(42, 1, stringBuilder3);
			handler2.AppendLiteral("<label>Min Spend:</label> <value>");
			handler2.AppendFormatted(FormatCurrency(customerData.MinWeeklySpend));
			handler2.AppendLiteral("</value>\n");
			StringBuilder stringBuilder4 = stringBuilder3.Append(ref handler2);
			StringBuilder stringBuilder5 = stringBuilder4;
			StringBuilder.AppendInterpolatedStringHandler handler3 = new StringBuilder.AppendInterpolatedStringHandler(67, 2, stringBuilder4);
			handler3.AppendLiteral("<label>Daily Spend Limit:</label> <value>");
			handler3.AppendFormatted(FormatCurrency(amount));
			handler3.AppendLiteral(" (");
			handler3.AppendFormatted(value, "F2");
			handler3.AppendLiteral("% of Max Daily)</value>\n");
			stringBuilder5.Append(ref handler3);
			List<EDay> sortedOrderDays = GetSortedOrderDays(list, currentDay);
			stringBuilder.Append("<section>Schedule Information</section>\n<label>Next Order Days:</label>\n");
			for (int i = 0; i < sortedOrderDays.Count; i++)
			{
				stringBuilder4 = stringBuilder;
				StringBuilder stringBuilder6 = stringBuilder4;
				handler = new StringBuilder.AppendInterpolatedStringHandler(20, 2, stringBuilder4);
				handler.AppendLiteral("<value>  ");
				handler.AppendFormatted(i + 1);
				handler.AppendLiteral(". ");
				handler.AppendFormatted<EDay>(sortedOrderDays[i]);
				handler.AppendLiteral("</value>\n");
				stringBuilder6.Append(ref handler);
			}
			stringBuilder.Append("<section>Product Preferences</section>\n");
			List<CustomerHelper.ProductOrders> list2 = CustomerHelper.GetProductsFromCustomer(customer).ToList();
			if (list2.Count == 0)
			{
				stringBuilder.Append(((Object)(object)customer.AssignedDealer != (Object)null) ? "<value>Dealer has no appealing products for sale</value>\n" : "<value>Won't buy anything</value>\n");
			}
			foreach (CustomerHelper.ProductOrders item in list2)
			{
				PaymentQuantityResult paymentQuantity = item.PaymentQuantity;
				stringBuilder4 = stringBuilder;
				StringBuilder stringBuilder7 = stringBuilder4;
				handler = new StringBuilder.AppendInterpolatedStringHandler(34, 4, stringBuilder4);
				handler.AppendLiteral("<value>");
				handler.AppendFormatted(((BaseItemDefinition)item.Product).Name);
				handler.AppendLiteral(" - $");
				handler.AppendFormatted(paymentQuantity.Payment, "F2");
				handler.AppendLiteral(" × ");
				handler.AppendFormatted(paymentQuantity.Quantity);
				handler.AppendLiteral(" (Appeal: ");
				handler.AppendFormatted(paymentQuantity.Appeal, "F3");
				handler.AppendLiteral(")</value>\n");
				stringBuilder7.Append(ref handler);
			}
			return stringBuilder.ToString();
		}
	}
	internal class PanelRenderer
	{
		private const int MaxGuiScale = 10;

		private static GUIStyle _salesPanelStyle;

		private static GUIStyle _salesHeaderStyle;

		private static int _guiScale = 1;

		private Texture2D _cachedPanelBackground;

		private readonly PanelState _contactPanel;

		private GUIStyle _infoLabelStyle;

		private GUIStyle _infoValueHighlightStyle;

		private GUIStyle _infoValueStyle;

		private readonly PanelState _salesPanel;

		private GUIStyle _sectionHeaderStyle;

		internal PanelRenderer(PanelState salesPanel, PanelState contactPanel)
		{
			_salesPanel = salesPanel;
			_contactPanel = contactPanel;
			InitializeStyles();
		}

		private void InitializeStyles()
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Expected O, but got Unknown
			//IL_0047: Expected O, but got Unknown
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: 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_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Expected O, but got Unknown
			//IL_0091: Expected O, but got Unknown
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Expected O, but got Unknown
			//IL_00e4: Expected O, but got Unknown
			//IL_00ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0103: Unknown result type (might be due to invalid IL or missing references)
			//IL_0118: Unknown result type (might be due to invalid IL or missing references)
			//IL_0122: Unknown result type (might be due to invalid IL or missing references)
			//IL_0128: Unknown result type (might be due to invalid IL or missing references)
			//IL_0132: Expected O, but got Unknown
			//IL_0137: Expected O, but got Unknown
			//IL_0142: Unknown result type (might be due to invalid IL or missing references)
			//IL_0147: Unknown result type (might be due to invalid IL or missing references)
			//IL_014f: 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_016e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0174: Unknown result type (might be due to invalid IL or missing references)
			//IL_017e: Expected O, but got Unknown
			//IL_0183: Expected O, but got Unknown
			//IL_018e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0193: Unknown result type (might be due to invalid IL or missing references)
			//IL_019b: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d1: Expected O, but got Unknown
			//IL_01d6: Expected O, but got Unknown
			GUIStyle val = new GUIStyle(GUIStyle.op_Implicit("box"));
			val.normal.background = Texture2D.whiteTexture;
			val.normal.textColor = Color.white;
			val.padding = new RectOffset(10, 10, 10, 10);
			_salesPanelStyle = val;
			GUIStyle val2 = new GUIStyle(GUIStyle.op_Implicit("label"))
			{
				fontSize = 20,
				fontStyle = (FontStyle)1
			};
			val2.normal.textColor = Color.white;
			val2.alignment = (TextAnchor)3;
			val2.padding = new RectOffset(10, 0, 0, 0);
			_salesHeaderStyle = val2;
			GUIStyle val3 = new GUIStyle(GUIStyle.op_Implicit("label"))
			{
				fontSize = 16,
				fontStyle = (FontStyle)1
			};
			val3.normal.textColor = new Color(0.9f, 0.9f, 1f);
			val3.padding = new RectOffset(0, 0, 10, 5);
			_sectionHeaderStyle = val3;
			GUIStyle val4 = new GUIStyle(GUIStyle.op_Implicit("label"))
			{
				fontSize = 14,
				fontStyle = (FontStyle)1
			};
			val4.normal.textColor = new Color(0.8f, 0.8f, 0.8f);
			val4.padding = new RectOffset(10, 0, 2, 2);
			_infoLabelStyle = val4;
			GUIStyle val5 = new GUIStyle(GUIStyle.op_Implicit("label"))
			{
				fontSize = 14
			};
			val5.normal.textColor = new Color(1f, 0.95f, 0.8f);
			val5.padding = new RectOffset(10, 0, 2, 8);
			_infoValueStyle = val5;
			GUIStyle val6 = new GUIStyle(GUIStyle.op_Implicit("label"))
			{
				fontSize = 14,
				fontStyle = (FontStyle)1
			};
			val6.normal.textColor = new Color(0.3f, 1f, 0.4f);
			val6.padding = new RectOffset(10, 0, 2, 8);
			_infoValueHighlightStyle = val6;
		}

		private static void HandlePanelDragging(PanelState panel, Rect dragRect, Event currentEvent)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Invalid comparison between Unknown and I4
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Invalid comparison between Unknown and I4
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			EventType type = currentEvent.type;
			if ((int)type != 0)
			{
				if ((int)type == 1)
				{
					panel.IsDragging = false;
				}
			}
			else if (((Rect)(ref dragRect)).Contains(currentEvent.mousePosition))
			{
				panel.IsDragging = true;
				panel.DragOffset = currentEvent.mousePosition - panel.Position;
				currentEvent.Use();
			}
			if (panel.IsDragging && (int)currentEvent.type == 3)
			{
				panel.Position = currentEvent.mousePosition - panel.DragOffset;
				currentEvent.Use();
			}
		}

		internal void DrawPanel(PanelState panel, float width, float height)
		{
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			if (panel.IsVisible)
			{
				Rect dragRect = default(Rect);
				((Rect)(ref dragRect))..ctor(panel.Position.x, panel.Position.y, width - 90f, 40f);
				HandlePanelDragging(panel, dragRect, Event.current);
				panel.Position.x = Mathf.Clamp(panel.Position.x, 0f, (float)Screen.width - width);
				panel.Position.y = Mathf.Clamp(panel.Position.y, 0f, (float)Screen.height - height);
				GUI.backgroundColor = Color.black;
				DrawPanelBackground(panel, width, height);
				DrawPanelContent(panel, width, height);
				DrawPanelHeader(panel, width);
				DrawPanelButtons(panel, width);
			}
		}

		private void DrawPanelBackground(PanelState panel, float width, float height)
		{
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Expected O, but got Unknown
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)_cachedPanelBackground == (Object)null)
			{
				_cachedPanelBackground = new Texture2D(1, 1);
				_cachedPanelBackground.SetPixel(0, 0, new Color(0.15f, 0.15f, 0.2f, 0.95f));
				_cachedPanelBackground.Apply();
			}
			ImguiCompat.DrawTexture(new Rect(panel.Position.x, panel.Position.y, width, height), _cachedPanelBackground);
		}

		private void DrawPanelContent(PanelState panel, float width, float height)
		{
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			string[] array = panel.Content.Split(new char[1] { '\n' }, StringSplitOptions.None);
			float num = panel.Position.y + 40f;
			float num2 = width - 20f;
			panel.ScrollPosition = GUI.BeginScrollView(new Rect(panel.Position.x, num, width, height - 40f), panel.ScrollPosition, new Rect(0f, 0f, num2, (float)(array.Length * 25)));
			float lineY = 0f;
			string[] array2 = array;
			foreach (string line in array2)
			{
				lineY = DrawContentLine(line, num2, lineY);
			}
			GUI.EndScrollView();
		}

		private float DrawContentLine(string line, float contentWidth, float lineY)
		{
			//IL_0039: 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_017d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
			if (line.StartsWith("<section>"))
			{
				string text = line.Replace("<section>", "").Replace("</section>", "");
				GUI.Label(new Rect(10f, lineY, contentWidth, 25f), text, _sectionHeaderStyle);
				return lineY + 30f;
			}
			if (line.Contains("<label>"))
			{
				string text2 = ExtractTaggedText(line, "<label>", "</label>");
				bool flag = line.Contains("<value-good>");
				string text3 = ExtractTaggedText(line, flag ? "<value-good>" : "<value>", flag ? "</value-good>" : "</value>");
				if (string.IsNullOrEmpty(text2))
				{
					return lineY;
				}
				GUI.Label(new Rect(10f, lineY, 140f, 20f), text2, _infoLabelStyle);
				if (!string.IsNullOrEmpty(text3))
				{
					GUI.Label(new Rect(160f, lineY, contentWidth - 160f, 20f), text3, flag ? _infoValueHighlightStyle : _infoValueStyle);
				}
				return lineY + 25f;
			}
			if (line.StartsWith("<value>"))
			{
				string text4 = line.Replace("<value>", "").Replace("</value>", "");
				GUI.Label(new Rect(20f, lineY, contentWidth - 20f, 20f), text4, _infoValueStyle);
				return lineY + 25f;
			}
			if (string.IsNullOrWhiteSpace(line))
			{
				return lineY;
			}
			GUI.Label(new Rect(10f, lineY, contentWidth, 20f), line, _infoValueStyle);
			return lineY + 25f;
		}

		private static string ExtractTaggedText(string line, string openTag, string closeTag)
		{
			int num = line.IndexOf(openTag, StringComparison.Ordinal);
			if (num < 0)
			{
				return "";
			}
			int num2 = num + openTag.Length;
			int num3 = line.IndexOf(closeTag, StringComparison.Ordinal);
			if (num3 >= num2)
			{
				return line.Substring(num2, num3 - num2);
			}
			return "";
		}

		private static void DrawPanelHeader(PanelState panel, float width)
		{
			//IL_001c: 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)
			GUI.Box(new Rect(panel.Position.x, panel.Position.y, width, 40f), "", _salesPanelStyle);
			GUI.Label(new Rect(panel.Position.x, panel.Position.y, width, 40f), panel.Title + " (Drag to Move)", _salesHeaderStyle);
		}

		private void DrawPanelButtons(PanelState panel, float width)
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ef: Unknown result type (might be due to invalid IL or missing references)
			if (GUI.Button(new Rect(panel.Position.x + width - 30f, panel.Position.y + 5f, 25f, 25f), "X"))
			{
				panel.IsVisible = false;
				panel.Position = new Vector2(20f, 20f);
				if (panel == _salesPanel)
				{
					UIHandler.SelectedProduct = null;
				}
				else if (panel == _contactPanel)
				{
					UIHandler.SelectedCustomer = null;
				}
			}
			if (GUI.Button(new Rect(panel.Position.x + width - 60f, panel.Position.y + 5f, 25f, 25f), "+"))
			{
				ChangeGuiScale(1);
			}
			if (GUI.Button(new Rect(panel.Position.x + width - 90f, panel.Position.y + 5f, 25f, 25f), "-"))
			{
				ChangeGuiScale(-1);
			}
		}

		private void ChangeGuiScale(int delta)
		{
			_guiScale = Mathf.Clamp(_guiScale + delta, 1, 10);
			ApplyGuiScale();
		}

		private void ApplyGuiScale()
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Expected O, but got Unknown
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Expected O, but got Unknown
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Expected O, but got Unknown
			//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f0: Expected O, but got Unknown
			_sectionHeaderStyle.fontSize = 16 + _guiScale;
			_sectionHeaderStyle.padding = new RectOffset(0, 0, 10 + _guiScale * 4, 5 + _guiScale * 2);
			_infoLabelStyle.fontSize = 14 + _guiScale;
			_infoLabelStyle.padding = new RectOffset(10, 0, 2 + _guiScale * 4, 2 + _guiScale * 4);
			_infoValueStyle.fontSize = 14 + _guiScale;
			_infoValueStyle.padding = new RectOffset(10 + _guiScale * 8, 0, 2 + _guiScale * 2, 8 + _guiScale * 4);
			_infoValueHighlightStyle.fontSize = 14 + _guiScale;
			_infoValueHighlightStyle.padding = new RectOffset(10 + _guiScale * 8, 0, 2 + _guiScale * 2, 8 + _guiScale * 4);
		}
	}
	internal class PanelState
	{
		public string Content = "";

		public Vector2 DragOffset = Vector2.zero;

		public bool IsDragging;

		public bool IsVisible;

		public Vector2 Position = new Vector2(20f, 20f);

		public Vector2 ScrollPosition = Vector2.zero;

		public readonly string Title;

		public PanelState(string title)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			Title = title;
			base..ctor();
		}
	}
	internal static class PriceButtonFix
	{
		private static readonly HashSet<int> Wired = new HashSet<int>();

		internal static void Apply(ProductManagerApp app)
		{
			if ((Object)(object)app == (Object)null)
			{
				return;
			}
			ProductAppDetailPanel componentInChildren = ((Component)app).GetComponentInChildren<ProductAppDetailPanel>(true);
			if ((Object)(object)componentInChildren == (Object)null)
			{
				return;
			}
			foreach (Button componentsInChild in ((Component)componentInChildren).GetComponentsInChildren<Button>(true))
			{
				Transform parent = ((Component)componentsInChild).transform.parent;
				if ((Object)(object)parent == (Object)null || (Object)(object)parent.parent == (Object)null || ((Object)parent.parent).name != "AskingPrice")
				{
					continue;
				}
				float num;
				if (((Object)componentsInChild).name == "Add")
				{
					num = 1f;
				}
				else
				{
					if (!(((Object)componentsInChild).name == "Remove"))
					{
						continue;
					}
					num = -1f;
				}
				if (Wired.Add(((Object)componentsInChild).GetInstanceID()))
				{
					ProductAppDetailPanel target = componentInChildren;
					float delta = num;
					((UnityEvent)componentsInChild.onClick).AddListener(UnityAction.op_Implicit((Action)delegate
					{
						Click(target, delta);
					}));
					Main.Log($"Wired Products asking-price '{((Object)componentsInChild).name}' button ({delta:+0;-0})");
				}
			}
		}

		private static void Click(ProductAppDetailPanel panel, float change)
		{
			if (!((Object)(object)panel == (Object)null) && !((Object)(object)panel.ActiveProduct == (Object)null))
			{
				panel.AdjustPrice(change);
			}
		}
	}
	internal class SalesInfoFormatter
	{
		private readonly PanelState _salesPanel;

		private DelayedPriceCalculator _currentPriceCalculator;

		internal SalesInfoFormatter(PanelState salesPanel)
		{
			_salesPanel = salesPanel;
		}

		internal void CancelPendingCalculation()
		{
			if (_currentPriceCalculator != null)
			{
				_currentPriceCalculator.Cancel();
				_currentPriceCalculator = null;
			}
		}

		private static string FormatCurrency(float amount)
		{
			return $"${amount:F2}";
		}

		internal string FormatSalesInfo(ProductEntry entry, float? overridePrice = null)
		{
			if ((Object)(object)entry == (Object)null || (Object)(object)entry.Definition == (Object)null)
			{
				Main.Log("Sales info formatting skipped because entry or definition is null.", error: false, warning: true);
				return "";
			}
			StringBuilder stringBuilder = new StringBuilder();
			StringBuilder stringBuilder2 = stringBuilder.Append("<section>Product Details</section>\n");
			StringBuilder stringBuilder3 = stringBuilder2;
			StringBuilder.AppendInterpolatedStringHandler handler = new StringBuilder.AppendInterpolatedStringHandler(40, 1, stringBuilder2);
			handler.AppendLiteral("<label>Product:</label> <value>");
			handler.AppendFormatted(((BaseItemDefinition)entry.Definition).Name);
			handler.AppendLiteral("</value>\n");
			StringBuilder stringBuilder4 = stringBuilder3.Append(ref handler);
			StringBuilder stringBuilder5 = stringBuilder4;
			StringBuilder.AppendInterpolatedStringHandler handler2 = new StringBuilder.AppendInterpolatedStringHandler(43, 1, stringBuilder4);
			handler2.AppendLiteral("<label>Base Price:</label> <value>");
			handler2.AppendFormatted(FormatCurrency(entry.Definition.Price));
			handler2.AppendLiteral("</value>\n");
			StringBuilder stringBuilder6 = stringBuilder5.Append(ref handler2);
			StringBuilder stringBuilder7 = stringBuilder6;
			StringBuilder.AppendInterpolatedStringHandler handler3 = new StringBuilder.AppendInterpolatedStringHandler(45, 1, stringBuilder6);
			handler3.AppendLiteral("<label>Market Value:</label> <value>");
			handler3.AppendFormatted(FormatCurrency(entry.Definition.MarketValue));
			handler3.AppendLiteral("</value>\n");
			stringBuilder7.Append(ref handler3);
			if (overridePrice.HasValue && !Mathf.Approximately(overridePrice.Value, entry.Definition.Price))
			{
				stringBuilder6 = stringBuilder;
				StringBuilder stringBuilder8 = stringBuilder6;
				handler = new StringBuilder.AppendInterpolatedStringHandler(46, 1, stringBuilder6);
				handler.AppendLiteral("<label>Current Price:</label> <value>");
				handler.AppendFormatted(FormatCurrency(overridePrice.Value));
				handler.AppendLiteral("</value>\n");
				stringBuilder8.Append(ref handler);
			}
			List<CustomerAppeal> list = (from ca in (from knownCustomer in CustomerHelper.GetKnownCustomers()
					select new CustomerAppeal
					{
						Customer = knownCustomer,
						Appeal = CustomerHelper.GetProductAppeal(entry.Definition, knownCustomer, overridePrice),
						PaymentQuantity = CustomerHelper.CalculatePaymentQuantity(entry.Definition, knownCustomer, overridePrice)
					}).ToList()
				orderby ca.Appeal descending
				select ca).ToList();
			List<CustomerAppeal> list2 = list.FindAll((CustomerAppeal ca) => ca.Appeal > 0.05f);
			float value = PriceOptimizer.EvaluatePriceAcceptance(entry.Definition, list, overridePrice ?? entry.Definition.Price);
			double value2 = ((list2.Count > 0) ? list2.Average((CustomerAppeal ca) => ca.PaymentQuantity.Quantity) : 0.0);
			string value3 = ((list2.Count > 0) ? FormatCurrency(list2.Average((CustomerAppeal ca) => ca.PaymentQuantity.Payment)) : FormatCurrency(0f));
			string value4 = ((list2.Count > 0) ? FormatCurrency(list2.Average((CustomerAppeal ca) => ca.PaymentQuantity.Payment / (float)ca.PaymentQuantity.Quantity)) : FormatCurrency(0f));
			StringBuilder stringBuilder9 = stringBuilder.Append("<section>Market Analysis</section>\n");
			handler = new StringBuilder.AppendInterpolatedStringHandler(62, 1, stringBuilder9);
			handler.AppendLiteral("<label>Potential Customers:</label> <value-good>");
			handler.AppendFormatted(list2.Count);
			handler.AppendLiteral("</value-good>\n");
			StringBuilder stringBuilder10 = stringBuilder9.Append(ref handler);
			StringBuilder stringBuilder11 = stringBuilder10;
			handler2 = new StringBuilder.AppendInterpolatedStringHandler(51, 1, stringBuilder10);
			handler2.AppendLiteral("<label>Average Order Size:</label> <value>");
			handler2.AppendFormatted(value2, "F1");
			handler2.AppendLiteral("</value>\n");
			stringBuilder2 = stringBuilder11.Append(ref handler2);
			StringBuilder stringBuilder12 = stringBuilder2;
			handler3 = new StringBuilder.AppendInterpolatedStringHandler(48, 1, stringBuilder2);
			handler3.AppendLiteral("<label>Average Payment:</label> <value>");
			handler3.AppendFormatted(value3);
			handler3.AppendLiteral("</value>\n");
			stringBuilder4 = stringBuilder12.Append(ref handler3);
			StringBuilder stringBuilder13 = stringBuilder4;
			StringBuilder.AppendInterpolatedStringHandler handler4 = new StringBuilder.AppendInterpolatedStringHandler(47, 1, stringBuilder4);
			handler4.AppendLiteral("<label>Per-Unit Price:</label> <value>");
			handler4.AppendFormatted(value4);
			handler4.AppendLiteral("</value>\n");
			stringBuilder6 = stringBuilder13.Append(ref handler4);
			StringBuilder stringBuilder14 = stringBuilder6;
			StringBuilder.AppendInterpolatedStringHandler handler5 = new StringBuilder.AppendInterpolatedStringHandler(50, 1, stringBuilder6);
			handler5.AppendLiteral("<label>Max Spender Score:</label> <value>");
			handler5.AppendFormatted(value, "F2");
			handler5.AppendLiteral("</value>\n");
			stringBuilder14.Append(ref handler5);
			float value5 = ((list2.Count > 0) ? list2.Average((CustomerAppeal ca) => ca.Appeal) : 0f);
			float value6 = ((list2.Count > 0) ? list2.Min((CustomerAppeal ca) => ca.Appeal) : 0f);
			float value7 = ((list2.Count > 0) ? list2.Max((CustomerAppeal ca) => ca.Appeal) : 0f);
			float value8 = ((list.Count > 0) ? list.Average((CustomerAppeal ca) => ca.Appeal) : 0f);
			float value9 = ((list.Count > 0) ? list.Min((CustomerAppeal ca) => ca.Appeal) : 0f);
			stringBuilder10 = stringBuilder.Append("<section>Appeal Statistics</section>\n<label>Customer Appeal:</label>\n");
			StringBuilder stringBuilder15 = stringBuilder10;
			handler = new StringBuilder.AppendInterpolatedStringHandler(25, 1, stringBuilder10);
			handler.AppendLiteral("<value>Average: ");
			handler.AppendFormatted(value5, "F2");
			handler.AppendLiteral("</value>\n");
			stringBuilder2 = stringBuilder15.Append(ref handler);
			StringBuilder stringBuilder16 = stringBuilder2;
			handler2 = new StringBuilder.AppendInterpolatedStringHandler(21, 1, stringBuilder2);
			handler2.AppendLiteral("<value>Min: ");
			handler2.AppendFormatted(value6, "F2");
			handler2.AppendLiteral("</value>\n");
			stringBuilder4 = stringBuilder16.Append(ref handler2);
			StringBuilder stringBuilder17 = stringBuilder4;
			handler3 = new StringBuilder.AppendInterpolatedStringHandler(21, 1, stringBuilder4);
			handler3.AppendLiteral("<value>Max: ");
			handler3.AppendFormatted(value7, "F2");
			handler3.AppendLiteral("</value>\n");
			stringBuilder6 = stringBuilder17.Append(ref handler3);
			StringBuilder stringBuilder18 = stringBuilder6;
			handler4 = new StringBuilder.AppendInterpolatedStringHandler(77, 2, stringBuilder6);
			handler4.AppendLiteral("<label>Overall Appeal:</label>\n<value>Average: ");
			handler4.AppendFormatted(value8, "F2");
			handler4.AppendLiteral("</value>\n<value>Min: ");
			handler4.AppendFormatted(value9, "F2");
			handler4.AppendLiteral("</value>\n");
			stringBuilder18.Append(ref handler4);
			if (!Config.PriceOptimizationEnabled.Value)
			{
				return stringBuilder.ToString();
			}
			stringBuilder6 = stringBuilder.Append("<section>Price Optimization</section>\n");
			StringBuilder stringBuilder19 = stringBuilder6;
			handler = new StringBuilder.AppendInterpolatedStringHandler(47, 1, stringBuilder6);
			handler.AppendLiteral("<label>Original Price:</label> <value>");
			handler.AppendFormatted(FormatCurrency(entry.Definition.Price));
			handler.AppendLiteral("</value>\n");
			stringBuilder19.Append(ref handler).Append("<label>Optimal Price:</label> <value>Calculating...</value>\n").Append("<label>Expected Revenue:</label> <value>Calculating...</value>\n")
				.Append("<label>Units Needed:</label> <value>Calculating...</value>\n")
				.Append("<label>No-Loss Price:</label> <value>Calculating...</value>\n")
				.Append("<label>Max Markup:</label> <value>Calculating...</value>\n");
			float initialPrice = overridePrice ?? entry.Definition.Price;
			float maxPrice = Math.Max(((list.Count > 0) ? list.Max((CustomerAppeal ca) => DealCalculator.CalculateSpendingLimits(ca.Customer).maxSpend) : (entry.Definition.MarketValue * 3f)) - 1f, entry.Definition.MarketValue * 2f);
			_currentPriceCalculator = new DelayedPriceCalculator(entry.Definition, list, initialPrice, 1f, maxPrice, delegate((float optimalPrice, float noLossPrice, float expectedRevenue, int expectedUnits) result)
			{
				float item = result.optimalPrice;
				float item2 = result.noLossPrice;
				float amount = ((result.expectedUnits > 0) ? (result.expectedRevenue / (float)result.expectedUnits) : 0f);
				string[] array = _salesPanel.Content.Split(new char[1] { '\n' }, StringSplitOptions.None);
				for (int i = 0; i < array.Length; i++)
				{
					if (array[i].Contains("Optimal Price:"))
					{
						array[i] = "<label>Optimal Price:</label> <value>" + FormatCurrency(item) + "</value>\n";
					}
					else if (array[i].Contains("Expected Revenue:"))
					{
						array[i] = "<label>Expected Revenue:</label> <value>" + FormatCurrency(result.expectedRevenue) + " (" + FormatCurrency(amount) + "/unit)</value>\n";
					}
					else if (array[i].Contains("Units Needed:"))
					{
						array[i] = "<label>Units Needed:</label> <value>" + result.expectedUnits + "</value>\n";
					}
					else if (array[i].Contains("No-Loss Price:"))
					{
						array[i] = "<label>No-Loss Price:</label> <value>" + FormatCurrency(item2) + "</value>\n";
					}
					else if (array[i].Contains("Max Markup:"))
					{
						array[i] = $"<label>Max Markup:</label> <value>{(item - entry.Definition.Price) / entry.Definition.Price * 100f:F1}%</value>\n";
					}
				}
				_salesPanel.Content = string.Join("\n", array);
			});
			_currentPriceCalculator.Start();
			return stringBuilder.ToString();
		}
	}
	public class UIHandler
	{
		internal static ProductManagerApp ProductManagerApp;

		private static string _counterOfferDisplayText = "";

		private readonly PanelState _contactPanel;

		private GUIStyle _displayTextStyle;

		private readonly PanelRenderer _panelRenderer;

		private readonly SalesInfoFormatter _salesInfoFormatter;

		private readonly PanelState _salesPanel;

		private const float PriceRefreshDelay = 0.4f;

		private float _lastSeenPrice = -1f;

		private float _priceChangedAt = -1f;

		public static ProductEntry SelectedProduct { get; set; }

		public static Customer SelectedCustomer { get; set; }

		public UIHandler()
		{
			InitializeStyles();
			_salesPanel = new PanelState("Sales Information");
			_contactPanel = new PanelState("Contact Information");
			_salesInfoFormatter = new SalesInfoFormatter(_salesPanel);
			_panelRenderer = new PanelRenderer(_salesPanel, _contactPanel);
		}

		private void InitializeStyles()
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: 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_0034: Expected O, but got Unknown
			GUIStyle val = new GUIStyle(GUIStyle.op_Implicit("label"))
			{
				fontSize = 18
			};
			val.normal.background = Texture2D.whiteTexture;
			val.alignment = (TextAnchor)4;
			_displayTextStyle = val;
		}

		public static void UpdateCounterOfferDisplayText(string text, string reasonText)
		{
			_counterOfferDisplayText = text + "\n" + reasonText;
		}

		private void RefreshSalesPanelOnPriceChange()
		{
			ProductEntry selectedProduct = SelectedProduct;
			if (!((Object)(object)selectedProduct == (Object)null) && !((Object)(object)selectedProduct.Definition == (Object)null))
			{
				float price = selectedProduct.Definition.Price;
				if (!Mathf.Approximately(price, _lastSeenPrice))
				{
					_lastSeenPrice = price;
					_priceChangedAt = Time.unscaledTime;
				}
				else if (!(_priceChangedAt < 0f) && !(Time.unscaledTime - _priceChangedAt < 0.4f))
				{
					_priceChangedAt = -1f;
					Main.Log($"ProductManager: Price changed to {price} for {((BaseItemDefinition)selectedProduct.Definition).ID}", error: false, warning: false, bypassConfig: true);
					UpdateSalesInfoPanel(selectedProduct);
				}
			}
		}

		public void UpdateSalesInfoPanel(ProductEntry entry, float? overridePrice = null)
		{
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			_salesInfoFormatter.CancelPendingCalculation();
			SelectedProduct = entry;
			_lastSeenPrice = (((Object)(object)entry != (Object)null && (Object)(object)entry.Definition != (Object)null) ? entry.Definition.Price : (-1f));
			_priceChangedAt = -1f;
			_salesPanel.IsVisible = true;
			_salesPanel.ScrollPosition = Vector2.zero;
			_salesPanel.Content = _salesInfoFormatter.FormatSalesInfo(entry, overridePrice);
		}

		public void UpdateContactInfoPanel(Customer customer)
		{
			//IL_0083: 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_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)customer == (Object)null)
			{
				_contactPanel.IsVisible = false;
				return;
			}
			if ((Object)(object)customer.customerData == (Object)null || (Object)(object)customer.NPC == (Object)null || customer.NPC.RelationData == null)
			{
				Main.Log("Contact info panel skipped because customer data, NPC, or relation data is null.", error: false, warning: true);
				_contactPanel.IsVisible = false;
				return;
			}
			TimeManager instance = NetworkSingleton<TimeManager>.Instance;
			if ((Object)(object)instance == (Object)null)
			{
				Main.Log("Contact info panel skipped because TimeManager is unavailable.", error: false, warning: true);
				_contactPanel.IsVisible = false;
				return;
			}
			EDay currentDay = instance.CurrentDay;
			SelectedCustomer = customer;
			_contactPanel.IsVisible = true;
			_contactPanel.ScrollPosition = Vector2.zero;
			_contactPanel.Content = CustomerInfoFormatter.FormatCustomerInfo(customer, customer.customerData, customer.NPC.RelationData, currentDay);
		}

		private void DrawSalesInfoPanel()
		{
			_panelRenderer.DrawPanel(_salesPanel, 420f, 800f);
		}

		private void DrawContactInfoPanel()
		{
			_panelRenderer.DrawPanel(_contactPanel, 440f, 700f);
		}

		public void OnGUI()
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_012b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0131: Invalid comparison between Unknown and I4
			//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
			Scene activeScene = SceneManager.GetActiveScene();
			if (((Scene)(ref activeScene)).name != "Main")
			{
				return;
			}
			Phone instance = PlayerSingleton<Phone>.Instance;
			if ((Object)(object)instance == (Object)null || !instance.IsOpen)
			{
				return;
			}
			if (!PlayerSingleton<HomeScreen>.Instance.isOpen && (Object)(object)PlayerSingleton<MessagesApp>.Instance != (Object)null && PlayerSingleton<MessagesApp>.Instance.CounterofferInterface.IsOpen)
			{
				if (Config.CounterOfferDarkModeEnabled.Value)
				{
					GUI.backgroundColor = new Color(0.15f, 0.15f, 0.2f, 0.95f);
					_displayTextStyle.normal.textColor = Color.white;
				}
				else
				{
					_displayTextStyle.normal.textColor = Color.black;
				}
				GUI.Label(new Rect((float)(Screen.width / 2 - 190), (float)(Screen.height / 2 - 250), 380f, 70f), _counterOfferDisplayText, _displayTextStyle);
				GUI.backgroundColor = Color.white;
			}
			if ((Object)(object)ProductManagerApp != (Object)null && ((App<ProductManagerApp>)(object)ProductManagerApp).isOpen && _salesPanel.IsVisible)
			{
				if ((int)Event.current.type == 7)
				{
					RefreshSalesPanelOnPriceChange();
				}
				DrawSalesInfoPanel();
			}
			if (!((Object)(object)PlayerSingleton<ContactsApp>.Instance == (Object)null) && ((App<ContactsApp>)(object)PlayerSingleton<ContactsApp>.Instance).isOpen && _contactPanel.IsVisible)
			{
				DrawContactInfoPanel();
			}
		}
	}
}
namespace HighBaller.Patches.Sales
{
	[HarmonyPatch(typeof(ProductManagerApp), "SelectProduct")]
	public static class ProductManagerSelectProductPatch
	{
		public static void Prefix(ProductManagerApp __instance, ProductEntry entry)
		{
			UIHandler.ProductManagerApp = __instance;
			PriceButtonFix.Apply(__instance);
		}

		private static void Postfix(ProductEntry entry)
		{
			Melon<Main>.Instance.UIHandler.UpdateSalesInfoPanel(entry);
		}
	}
}
namespace HighBaller.Patches.Leveling
{
	[HarmonyPatch(typeof(LevelManager), "AddXP")]
	public static class LevelManagerLoggingPatch
	{
		public static void Postfix(int xp)
		{
			Main.Log($"LevelManager: AddXP: {xp}");
		}
	}
}
namespace HighBaller.Patches.Handover
{
	public static class HandoverPackageSelector
	{
		public static List<ProductPackage<T>> FindOptimalPackages<T>(List<ProductPackage<T>> availablePackages, int targetQuantity)
		{
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			if (targetQuantity <= 0 || ((IEnumerable<ProductPackage<T>>)availablePackages).Sum((Func<ProductPackage<T>, int>)TotalUnitsSelector) < targetQuantity)
			{
				return new List<ProductPackage<T>>();
			}
			List<ProductPackage<T>> selectedPackages = new List<ProductPackage<T>>();
			int num = targetQuantity;
			List<ProductPackage<T>> list = availablePackages.OrderByDescending(PackageSizeSelector).ToList();
			foreach (ProductPackage<T> item in list)
			{
				if (num <= 0)
				{
					break;
				}
				int num2 = Math.Min(item.AvailableQuantity, num / item.PackageSize);
				if (num2 > 0)
				{
					selectedPackages.Add(new ProductPackage<T>(item.PackageSize, item.Slot, num2, item.Quality));
					num -= num2 * item.PackageSize;
				}
			}
			if (num <= 0)
			{
				return selectedPackages;
			}
			List<ProductPackage<T>> list2 = FindExactMatch(list.Where((ProductPackage<T> p) => !selectedPackages.Any((ProductPackage<T> sp) => sp.Slot.Equals(p.Slot))).ToList(), num);
			if (list2 == null)
			{
				return new List<ProductPackage<T>>();
			}
			selectedPackages.AddRange(list2);
			return selectedPackages;
			static int PackageSizeSelector(ProductPackage<T> p)
			{
				return p.PackageSize;
			}
			static int TotalUnitsSelector(ProductPackage<T> p)
			{
				return p.TotalUnits;
			}
		}

		private static List<ProductPackage<T>> FindExactMatch<T>(List<ProductPackage<T>> packages, int target)
		{
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			if (target == 0)
			{
				return new List<ProductPackage<T>>();
			}
			if (packages.Count == 0 || target < 0)
			{
				return null;
			}
			ProductPackage<T> productPackage = packages[0];
			List<ProductPackage<T>> packages2 = packages.Skip(1).ToList();
			int num = Math.Min(productPackage.AvailableQuantity, target / productPackage.PackageSize);
			for (int i = 0; i <= num; i++)
			{
				int target2 = target - i * productPackage.PackageSize;
				List<ProductPackage<T>> list = FindExactMatch(packages2, target2);
				if (list != null)
				{
					if (i > 0)
					{
						list.Add(new ProductPackage<T>(productPackage.PackageSize, productPackage.Slot, i, productPackage.Quality));
					}
					return list;
				}
			}
			return null;
		}
	}
	[HarmonyPatch(typeof(HandoverScreenContractMode), "Open")]
	public static class HandoverScreenOpenPatch
	{
		public static bool Prefix(Contract contract)
		{
			Customer val = (((Object)(object)contract != (Object)null && (Object)(object)contract.Customer != (Object)null) ? ((Component)contract.Customer).GetComponent<Customer>() : null);
			if ((Object)(object)val != (Object)null && (Object)(object)val.CustomerData != (Object)null)
			{
				return true;
			}
			Main.Log("HandoverScreen.Open blocked: customer or customerData is null (likely S1API custom NPC).", error: false, warning: true);
			return false;
		}
	}
	[HarmonyPatch(typeof(Customer), "CompleteContractDialogueChosen")]
	public static class HandoverService
	{
		public static bool Prefix(Customer __instance)
		{
			if (!Config.AutoHandoverEnabled.Value)
			{
				return true;
			}
			if (Config.GetCustomNpcMode(((Object)(object)__instance != (Object)null) ? __instance.NPC : null) < S1APINPCHandling.NoAutomation)
			{
				return DoDeal(__instance);
			}
			Main.Log("Auto handover skipped for custom NPC: " + (((Object)(object)__instance.customerData != (Object)null) ? ((Object)__instance.customerData).name : "unknown"));
			return true;
		}

		private static bool DoDeal(Customer customer)
		{
			//IL_00fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_0103: Unknown result type (might be due to invalid IL or missing references)
			//IL_0108: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_036c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0371: Unknown result type (might be due to invalid IL or missing references)
			//IL_0390: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_0225: Unknown result type (might be due to invalid IL or missing references)
			//IL_022b: Unknown result type (might be due to invalid IL or missing references)
			//IL_030a: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)customer == (Object)null || (Object)(object)customer.NPC == (Object)null)
			{
				Main.Log("Auto handover skipped because the customer is invalid.", error: false, warning: true);
				return true;
			}
			if ((Object)(object)customer.CurrentContract == (Object)null || customer.CurrentContract.ProductList == null || customer.CurrentContract.ProductList.entries == null || customer.CurrentContract.ProductList.entries.Count == 0)
			{
				Main.Log("Auto handover skipped because the current contract has no products.", error: false, warning: true);
				return true;
			}
			Main.Log("Customer: " + (((Object)(object)customer.NPC != (Object)null) ? customer.NPC.FullName : "unknown"));
			Entry obj = customer.CurrentContract.ProductList.entries[0];
			string productID = obj.ProductID;
			int quantity = obj.Quantity;
			if (quantity <= 0)
			{
				return true;
			}
			if ((Object)(object)customer.CustomerData == (Object)null)
			{
				Main.Log("Auto handover skipped because customer data is null.", error: false, warning: true);
				return true;
			}
			EQuality minQuality = StandardsMethod.GetCorrespondingQuality(customer.CustomerData.Standards);
			List<ProductPackage<ItemSlot>> list = new List<ProductPackage<ItemSlot>>();
			PlayerInventory instance = PlayerSingleton<PlayerInventory>.Instance;
			if ((Object)(object)Player.Local == (Object)null || (Object)(object)instance == (Object)null)
			{
				Main.Log("Auto handover skipped because Player.Local or Inventory is null.", error: false, warning: true);
				return true;
			}
			Enumerator<ItemSlot> enumerator = instance.GetAllInventorySlots().GetEnumerator();
			while (enumerator.MoveNext())
			{
				ItemSlot current = enumerator.Current;
				ItemInstance itemInstance = current.ItemInstance;
				if (itemInstance != null && !(((BaseItemDefinition)itemInstance.Definition).ID != productID) && ((BaseItemInstance)itemInstance).Quantity > 0)
				{
					Main.Log($"Item: {((BaseItemDefinition)itemInstance.Definition).ID} - {((BaseItemInstance)itemInstance).Quantity} - {((BaseItemDefinition)itemInstance.Definition).Category}");
					ProductItemInstance val = ((Il2CppObjectBase)itemInstance).TryCast<ProductItemInstance>();
					if (val != null && !((Object)(object)val.packaging == (Object)null) && ((QualityItemInstance)val).Quality >= minQuality)
					{
						PackagingDefinition packaging = val.packaging;
						Main.Log($"ProductItem: {((BaseItemDefinition)itemInstance.Definition).ID} - {((BaseItemInstance)itemInstance).Quantity} - {((BaseItemDefinition)packaging).Name}");
						Main.Log($"Packaging: {packaging.Quantity} {((BaseItemDefinition)packaging).ID}");
						list.Add(new ProductPackage<ItemSlot>(packaging.Quantity, current, ((BaseItemInstance)itemInstance).Quantity, ((QualityItemInstance)val).Quality));
					}
				}
			}
			List<ProductPackage<ItemSlot>> list2 = new List<ProductPackage<ItemSlot>>();
			IEnumerable<EQuality> source = Enum.GetValues(typeof(EQuality)).Cast<EQuality>();
			Func<EQuality, bool> predicate = (EQuality q) => q >= minQuality;
			foreach (EQuality qualityLevel in source.Where(predicate))
			{
				Main.Log($"Finding optimal packages for quality: {qualityLevel}");
				list2 = HandoverPackageSelector.FindOptimalPackages(list.Where((ProductPackage<ItemSlot> p) => p.Quality == qualityLevel).ToList(), quantity);
				if (list2.Count > 0)
				{
					Main.Log($"Found optimal packages for quality: {qualityLevel}");
					break;
				}
			}
			if (list2.Count == 0)
			{
				Main.Log("No suitable combination of packages found to meet target quantity");
				return true;
			}
			List<ItemInstance> val2 = new List<ItemInstance>();
			foreach (ProductPackage<ItemSlot> item in list2)
			{
				Main.Log($"Selected package: {item?.PackageSize} units, {item?.AvailableQuantity} packages");
				if (item == null)
				{
					Main.Log("Selected package is null", error: false, warning: true);
					continue;
				}
				ItemInstance copy = item.Slot.ItemInstance.GetCopy(-1);
				if (item.Slot.Quantity.Equals(item.AvailableQuantity))
				{
					((BaseItemInstance)item.Slot.ItemInstance).RequestClearSlot();
				}
				else
				{
					item.Slot.ChangeQuantity(-item.AvailableQuantity, false);
				}
				((BaseItemInstance)copy).Quantity = item.AvailableQuantity;
				val2.Add(copy);
			}
			customer.ProcessHandover(customer.CurrentContract, val2, true, true);
			return false;
		}
	}
}
namespace HighBaller.Patches.CounterOffer
{
	[HarmonyPatch(typeof(CounterofferInterface), "SetProduct")]
	public static class CounterofferInterfaceChangeProductPatch
	{
		private static void Postfix(ProductDefinition newProduct)
		{
			MessagesApp instance = PlayerSingleton<MessagesApp>.Instance;
			if ((Object)(object)instance == (Object)null || (Object)(object)newProduct == (Object)null)
			{
				Main.Log("Counteroffer product change skipped because the UI or product is unavailable.", error: false, warning: true);
				return;
			}
			Main.Log("CounterofferInterfaceChangeProductPatch: " + ((BaseItemDefinition)newProduct).Name);
			OfferData offerData = OfferEvaluator.GetOfferData();
			if (offerData != null)
			{
				Customer customer = offerData.Customer;
				int quantity = offerData.Quantity;
				float price = offerData.Price;
				var (num, num2) = DealCalculator.FindOptimalQuantity(customer, newProduct, quantity, price * 0.25f);
				if (!Mathf.Approximately((float)num2, price))
				{
					instance.CounterofferInterface.PriceSelector.ChangeAmount((float)(num2 - (int)price));
					instance.CounterofferInterface.ChangeQuantity((float)(num - quantity));
				}
			}
		}
	}
	[HarmonyPatch(typeof(AmountSelector), "ChangeAmount")]
	public static class CounterofferInterfacePostChangePricePatch
	{
		private static void Postfix(AmountSelector __instance, float change)
		{
			MessagesApp instance = PlayerSingleton<MessagesApp>.Instance;
			if (!((Object)(object)instance == (Object)null) && !((Object)(object)instance.CounterofferInterface == (Object)null) && !((Object)(object)instance.CounterofferInterface.PriceSelector != (Object)(object)__instance))
			{
				if (Main.SuppressNextPriceEval)
				{
					Main.SuppressNextPriceEval = false;
				}
				else
				{
					OfferEvaluator.OfferPriceChangeCheckNoLog();
				}
			}
		}
	}
	[HarmonyPatch(typeof(CounterofferInterface), "ChangeQuantity", new Type[] { typeof(float) })]
	public static class CounterofferInterfacePostChangeQuantityPatch
	{
		private static void Postfix(float change)
		{
			MessagesApp instance = PlayerSingleton<MessagesApp>.Instance;
			if ((Object)(object)instance == (Object)null || !instance.CounterofferInterface.IsOpen)
			{
				return;
			}
			OfferData offerData = OfferEvaluator.GetOfferData();
			if (offerData == null)
			{
				return;
			}
			Customer customer = offerData.Customer;
			float item = DealCalculator.CalculateSpendingLimits(customer).maxSpend;
			CounterofferInterface counterofferInterface = instance.CounterofferInterface;
			ProductDefinition product = counterofferInterface.selectedProduct ?? offerData.Product;
			int quantity = offerData.Quantity;
			float price = offerData.Price;
			int num = DealCalculator.FindOptimalPrice(customer, product, quantity, 1f, item, -1f, null, log: true);
			if (num <= 1)
			{
				ContractInfo offeredContractInfo = customer.OfferedContractInfo;
				ProductList val = ((offeredContractInfo != null) ? offeredContractInfo.Products : null);
				if (val != null)
				{
					List<Entry> entries = val.entries;
					if (entries != null && entries.Count > 0)
					{
						int quantity2 = offeredContractInfo.Products.entries[0].Quantity;
						if (quantity2 > 0)
						{
							num = Math.Min((int)(offeredContractInfo.Payment / (float)quantity2 * (float)quantity), (int)item - 1);
							Main.Log($"FindOptimalPrice fallback: proportional price {num} for {quantity} units");
						}
					}
				}
			}
			if (!Mathf.Approximately((float)num, price))
			{
				Main.SuppressNextPriceEval = true;
				counterofferInterface.PriceSelector.ChangeAmount((float)(num - (int)price));
			}
			OfferEvaluator.OfferPriceChangeCheckNoLog();
		}
	}
	[HarmonyPatch(typeof(CounterofferInterface), "Open")]
	public static class CounterofferInterfacePostOpenPatch
	{
		private static void Postfix(ProductDefinition product, int quantity, float price, MSGConversation _conversation, Action<ProductDefinition, int, float> _orderConfirmedCallback)
		{
			MessagesApp instance = PlayerSingleton<MessagesApp>.Instance;
			Customer customerFromConversation = CustomerHelper.GetCustomerFromConversation(_conversation);
			if ((Object)(object)instance == (Object)null || (Object)(object)product == (Object)null || (Object)(object)customerFromConversation == (Object)null)
			{
				Main.Log("Counteroffer open automation skipped because the UI, product, or customer is unavailable.", error: false, warning: true);
			}
			else if (Config.GetCustomNpcMode(customerFromConversation.NPC) < S1APINPCHandling.Exclude)
			{
				var (num, num2) = DealCalculator.FindOptimalQuantity(customerFromConversation, product, quantity, price);
				if (!((float)num2 <= price))
				{
					instance.CounterofferInterface.PriceSelector.ChangeAmount((float)(num2 - (int)price));
					instance.CounterofferInterface.ChangeQuantity((float)(num - quantity));
				}
			}
		}
	}
}
namespace HighBaller.Patches.Contracts
{
	[HarmonyPatch(typeof(Customer), "AcceptContractClicked")]
	public static class AcceptContractClickedPatch
	{
		public static void Postfix(Customer __instance)
		{
			DealAutoScheduler.TryAutoScheduleDeal(__instance);
		}
	}
	[HarmonyPatch(typeof(Customer), "EvaluateCounteroffer")]
	public static class EvaluateCounterOfferPatch
	{
		public static bool Prefix(Customer __instance, ref bool __result)
		{
			if (!Config.AlwaysAcceptCounterOffersEnabled.Value)
			{
				return true;
			}
			if ((Object)(object)__instance != (Object)null && Config.GetCustomNpcMode(__instance.NPC) >= S1APINPCHandling.NoAutomation)
			{
				return true;
			}
			__result = true;
			Main.Log("AlwaysAcceptCounterOffers: forcing accept for " + (((Object)(object)__instance != (Object)null && (Object)(object)__instance.customerData != (Object)null) ? ((Object)__instance.customerData).name : "unknown"));
			return false;
		}

		public static void Postfix(Customer __instance, bool __result)
		{
			if (!__result)
			{
				Main.Log("Counter failed", error: false, warning: true);
			}
			else
			{
				DealAutoScheduler.TryAutoScheduleDeal(__instance);
			}
		}
	}
	[HarmonyPatch(typeof(Customer), "OfferContract")]
	public static class OfferContractPatch
	{
		public static void Postfix(ContractInfo info, Customer __instance, MethodBase __originalMethod)
		{
			Entry entry;
			if (!((Object)(object)__instance == (Object)null))
			{
				object obj;
				if (info == null)
				{
					obj = null;
				}
				else
				{
					ProductList products = info.Products;
					obj = ((products != null) ? products.entries : null);
				}
				if (obj != null && info.Products.entries.Count != 0)
				{
					if (Config.GetCustomNpcMode(__instance.NPC) >= S1APINPCHandling.NoAutomation)
					{
						Main.Log("OfferContractPatch: skipping automation for custom NPC: " + (((Object)(object)__instance.customerData != (Object)null) ? ((Object)__instance.customerData).name : "unknown"));
					}
					else if ((Object)(object)__instance.customerData == (Object)null || (Object)(object)__instance.NPC == (Object)null)
					{
						Main.Log("OfferContractPatch skipped because customerData or NPC is null.", error: false, warning: true);
					}
					else if (Config.AutoCounterOfferEnabled.Value)
					{
						Main.Log("Customer: " + (((Object)(object)__instance.customerData != (Object)null) ? ((Object)__instance.customerData).name : "unknown") + ", Contract: " + info.Products.entries[0].ProductID);
						entry = info.Products.entries[0];
						ProductDefinition val = null;
						Enumerator<ProductDefinition> enumerator = ProductManager.ListedProducts.GetEnumerator();
						while (enumerator.MoveNext())
						{
							ProductDefinition current = enumerator.Current;
							if (MatchesEntry(current))
							{
								val = current;
								break;
							}
						}
						if ((Object)(object)val == (Object)null)
						{
							val = Registry.GetItem<ProductDefinition>(entry.ProductID);
						}
						if ((Object)(object)val == (Object)null)
						{
							Main.Log("Auto counter-offer skipped because the offered product could not be resolved.", error: false, warning: true);
							return;
						}
						float item = DealCalculator.CalculateSpendingLimits(__instance).maxSpend;
						if ((double)info.Payment >= Math.Floor(item))
						{
							Main.Log("Skipping counter offer for " + ((Object)__instance.customerData).name + " because they are over their max spend");
							new DelayedCounterOffer(__instance, val, entry.Quantity, info.Payment, skipCounterOffer: true).Start();
							return;
						}
						InitialOfferData initialOfferData = new InitialOfferData
						{
							ProductId = entry.ProductID,
							Quantity = entry.Quantity,
							Payment = info.Payment
						};
						var (quantity, num) = DealCalculator.FindOptimalQuantity(__instance, val, entry.Quantity, info.Payment, initialOfferData);
						new DelayedCounterOffer(__instance, val, quantity, num).Start();
					}
					else if (Config.AutoContractAcceptedEnabled.Value)
					{
						Main.Log("Auto-scheduling (without counter-offer) for " + (((Object)(object)__instance.customerData != (Object)null) ? ((Object)__instance.customerData).name : "unknown"));
						new DelayedCounterOffer(__instance, null, 0, 0f, skipCounterOffer: true).Start();
					}
					return;
				}
			}
			Main.Log("OfferContractPatch skipped because the contract info is incomplete.", error: false, warning: true);
			bool MatchesEntry(ProductDefinition product)
			{
				return ((BaseItemDefinition)product).ID.Equals(entry.ProductID);
			}
		}
	}
}
namespace HighBaller.Patches.Contacts
{
	[HarmonyPatch(typeof(ContactsDetailPanel), "Open")]
	public static class ContactsDetailPanelOpenPatch
	{
		[HarmonyPostfix]
		public static void Postfix(NPC npc, ContactsDetailPanel __instance)
		{
			if (!((Object)(object)npc == (Object)null))
			{
				Main.Log($"RelationCircle: {npc.ID}, Name: {npc.FullName}, RelationDelta: {npc.RelationData.RelationDelta}, Unlocked: {npc.RelationData.Unlocked}");
				Customer customerFromNpc = CustomerHelper.GetCustomerFromNpc(npc);
				if ((Object)(object)customerFromNpc == (Object)null)
				{
					Main.Log("Not a customer");
					Melon<Main>.Instance.UIHandler.UpdateSalesInfoPanel(null);
				}
				else
				{
					Melon<Main>.Instance.UIHandler.UpdateContactInfoPanel(customerFromNpc);
				}
			}
		}
	}
}
namespace HighBaller.Helpers
{
	public static class CustomerHelper
	{
		public class ProductOrders
		{
			public ProductDefinition Product { get; set; }

			public PaymentQuantityResult PaymentQuantity { get; set; }
		}

		public static Customer GetCustomerFromConversation(MSGConversation conversation)
		{
			if (conversation == null)
			{
				Main.Log("Could not resolve customer because the conversation is null.", error: false, warning: true);
				return null;
			}
			string contactName = conversation.ContactName;
			foreach (Customer item in from knownCustomer in GetKnownCustomers()
				where (Object)(object)knownCustomer != (Object)null && (Object)(object)knownCustomer.NPC != (Object)null
				select knownCustomer)
			{
				if (item.NPC.MSGConversation == conversation || (!string.IsNullOrWhiteSpace(contactName) && (string.Equals(item.NPC.FullName, contactName, StringComparison.OrdinalIgnoreCase) || ((Object)(object)item.customerData != (Object)null && string.Equals(((Object)item.customerData).name, contactName, StringComparison.OrdinalIgnoreCase)))))
				{
					return item;
				}
			}
			Main.Log("Could not resolve customer from conversation: " + contactName, error: false, warning: true);
			return null;
		}

		public static Customer GetCustomerFromMessagesApp(MessagesApp messagesApp)
		{
			if ((Object)(object)messagesApp != (Object)null)
			{
				return GetCustomerFromConversation(messagesApp.currentConversation);
			}
			Main.Log("Could not resolve customer because MessagesApp is null.", error: false, warning: true);
			return null;
		}

		public static float GetProductAppeal(ProductDefinition product, Customer customer, float? overridePrice = null)
		{
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)product == (Object)null || (Object)(object)customer == (Object)null || (Object)(object)customer.customerData == (Object)null || product.MarketValue <= 0f)
			{
				Main.Log("Product appeal calculation skipped because the product or customer data is invalid.", error: false, warning: true);
				return 0f;
			}
			float productEnjoyment = customer.GetProductEnjoyment(product, StandardsMethod.GetCorrespondingQuality(customer.customerData.Standards));
			float num = (overridePrice ?? product.Price) / product.MarketValue;
			float num2 = Mathf.Lerp(1f, -1f, num / 2f);
			return productEnjoyment + num2;
		}

		public static PaymentQuantityResult CalculatePaymentQuantity(ProductDefinition product, Customer customer, float? overridePrice = null)
		{
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: 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_01c4: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)product == (Object)null || (Object)(object)customer == (Object)null || (Object)(object)customer.customerData == (Object)null)
			{
				Main.Log("Payment quantity calculation skipped because the product or customer is invalid.", error: false, warning: true);
				return null;
			}
			CustomerData customerData = customer.customerData;
			EQuality correspondingQuality = StandardsMethod.GetCorrespondingQuality(customerData.Standards);
			float num = overridePrice ?? product.Price;
			if (num <= 0f)
			{
				Main.Log("Payment quantity calculation skipped because the price is not greater than zero.", error: false, warning: true);
				return new PaymentQuantityResult
				{
					Payment = 0f,
					Quantity = 0,
					Quality = correspondingQuality,
					Appeal = 0f
				};
			}
			float productAppeal = GetProductAppeal(product, customer, overridePrice);
			if (productAppeal < 0.05f)
			{
				return new PaymentQuantityResult
				{
					Payment = 0f,
					Quantity = 0,
					Quality = correspondingQuality,
					Appeal = productAppeal
				};
			}
			float productEnjoyment = customer.GetProductEnjoyment(product, correspondingQuality);
			int num2 = 7;
			if ((Object)(object)customer.AssignedDealer == (Object)null)
			{
				List<EDay> val = new List<EDay>();
				customerData.GetOrderDays(customer.CurrentAddiction, customer.NPC.RelationData.RelationDelta / 5f, val);
				num2 = Math.Max(val.Count, 1);
			}
			float num3 = customerData.GetAdjustedWeeklySpend(customer.NPC.RelationData.RelationDelta / 5f) / (float)num2 * Mathf.Lerp(0.66f, 1.5f, productEnjoyment);
			float num4 = num * Mathf.Lerp(0.66f, 1.5f, productEnjoyment);
			int num5 = Mathf.Clamp(Mathf.RoundToInt(num3 / num), 1, 1000);
			if (num5 >= 14)
			{
				num5 = Mathf.RoundToInt((float)(num5 / 5)) * 5;
			}
			float payment = Mathf.RoundToInt(num4 * (float)num5 / 5f) * 5;
			return new PaymentQuantityResult
			{
				Payment = payment,
				Quantity = num5,
				Quality = correspondingQuality,
				Appeal = productAppeal
			};
		}

		public static Customer GetCustomerFromNpc(NPC npc)
		{
			if ((Object)(object)npc == (Object)null)
			{
				Main.Log("Could not resolve customer because the NPC is null.", error: false, warning: true);
				return null;
			}
			using (IEnumerator<Customer> enumerator = (from knownCustomer in GetKnownCustomers()
				where (Object)(object)knownCustomer != (Object)null && (Object)(object)knownCustomer.NPC != (Object)null && (((Object)knownCustomer.NPC).Equals((Object)(object)npc) || string.Equals(knownCustomer.NPC.FullName, npc.FullName, StringComparison.OrdinalIgnoreCase))
				select knownCustomer).GetEnumerator())
			{
				if (enumerator.MoveNext())
				{
					return enumerator.Current;
				}
			}
			Main.Log("Could not resolve customer from NPC: " + npc.FullName, error: false, warning: true);
			return null;
		}

		public static IEnumerable<ProductOrders> GetProductsFromCustomer(Customer customer)
		{
			if ((Object)(object)customer == (Object)null)
			{
				Main.Log("Could not get products because the customer is null.", error: false, warning: true);
				return Array.Empty<ProductOrders>();
			}
			List<ProductOrders> list = new List<ProductOrders>();
			Enumerator<ProductDefinition> enumerator = customer.GetOrderableProducts((Dealer)null).GetEnumerator();
			while (enumerator.MoveNext())
			{
				ProductDefinition current = enumerator.Current;
				PaymentQuantityResult paymentQuantityResult = CalculatePaymentQuantity(current, customer);
				if (paymentQuantityResult != null && paymentQuantityResult.Appeal >= 0.05f)
				{
					list.Add(new ProductOrders
					{
						Product = current,
						PaymentQuantity = paymentQuantityResult
					});
				}
			}
			list.Sort((ProductOrders a, ProductOrders b) => b.PaymentQuantity.Appeal.CompareTo(a.PaymentQuantity.Appeal));
			return list.Take(4);
		}

		public static List<Customer> GetKnownCustomers()
		{
			List<Customer> list = new List<Customer>();
			try
			{
				List<Customer> unlockedCustomers = Customer.UnlockedCustomers;
				if (unlockedCustomers != null)
				{
					Enumerator<Customer> enumerator = unlockedCustomers.GetEnumerator();
					while (enumerator.MoveNext())
					{
						Customer current = enumerator.Current;
						AddCustomer(list, current);
					}
				}
			}
			catch (Exception ex)
			{
				Main.Log("Error enumerating UnlockedCustomers: " + ex.Message, error: false, warning: true);
			}
			try
			{
				Il2CppArrayBase<Customer> val = Resources.FindObjectsOfTypeAll<Customer>();
				if (val != null)
				{
					foreach (Customer item in val)
					{
						AddCustomer(list, item);
					}
				}
			}
			catch (Exception ex2)
			{
				Main.Log("Error enumerating all Customer objects: " + ex2.Message, error: false, warning: true);
			}
			Main.Log("GetKnownCustomers found " + list.Count + " customers (incl. S1API custom NPCs)");
			return list;
		}

		private static void AddCustomer(List<Customer> customers, Customer customer)
		{
			if ((Object)(object)customer == (Object)null)
			{
				return;
			}
			try
			{
				if ((Object)(object)customer.NPC == (Object)null)
				{
					return;
				}
				if ((Object)(object)customer.customerData == (Object)null)
				{
					if (Config.GetCustomNpcMode(customer.NPC) >= S1APINPCHandling.Exclude)
					{
						Main.Log("Skipping custom NPC with missing customerData (Mode 2).");
						return;
					}
					Main.Log("Adding custom NPC with missing customerData: " + (customer.NPC.FullName ?? "unknown"));
				}
				if (!customers.Any((Customer existing) => (Object)(object)existing == (Object)(object)customer || ((Object)(object)existing != (Object)null && (Object)(object)existing.NPC != (Object)null && (Object)(object)customer.NPC != (Object)null && (Object)(object)existing.NPC == (Object)(object)customer.NPC)))
				{
					customers.Add(customer);
				}
			}
			catch (Exception ex)
			{
				Main.Log("Error adding customer: " + ex.Message, error: false, warning: true);
			}
		}
	}
	internal static class DisplayHelper
	{
		public static void UpdateCounterOfferDisplayText(string text, string reasonText)
		{
			UIHandler.UpdateCounterOfferDisplayText(text, reasonText);
		}
	}
	internal static class ImguiCompat
	{
		private static GUIStyle _style;

		internal static void DrawTexture(Rect position, Texture2D image)
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Invalid comparison between Unknown and I4
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Expected O, but got Unknown
			if (!((Object)(object)image == (Object)null) && Event.current != null && (int)Event.current.type == 7)
			{
				if (_style == null)
				{
					_style = new GUIStyle();
				}
				_style.normal.background = image;
				Color backgroundColor = GUI.backgroundColor;
				GUI.backgroundColor = Color.white;
				_style.Draw(position, false, false, false, false);
				GUI.backgroundColor = backgroundColor;
			}
		}
	}
}
namespace HighBaller.Core
{
	public static class DealAutoScheduler
	{
		private static DealWindow ResolveCurrentWindowOption()
		{
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0138: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				TimeManager instance = NetworkSingleton<TimeManager>.Instance;
				if ((Object)(object)instance == (Object)null)
				{
					Main.Log("Window 5: TimeManager unavailable, defaulting to Late Night.", error: false, warning: true);
					return DealWindow.LateNight;
				}
				int currentTime = instance.CurrentTime;
				int minSumFrom24HourTime = TimeManager.GetMinSumFrom24HourTime(currentTime);
				int num = DealWindowSelector.WINDOW_CUTOFF_MINS;
				if (num <= 0)
				{
					num = 60;
				}
				for (int i = 0; i < 4; i++)
				{
					EDealWindow val = (EDealWindow)i;
					DealWindowInfo windowInfo = DealWindowInfo.GetWindowInfo(val);
					int minSumFrom24HourTime2 = TimeManager.GetMinSumFrom24HourTime(windowInfo.StartTime);
					int num2 = TimeManager.GetMinSumFrom24HourTime(windowInfo.EndTime);
					if (num2 <= minSumFrom24HourTime2)
					{
						num2 += 1440;
					}
					int num3 = minSumFrom24HourTime;
					if (num3 < minSumFrom24HourTime2)
					{
						num3 += 1440;
					}
					if (num3 >= minSumFrom24HourTime2 && num3 < num2)
					{
						if (num2 - num3 > num)
						{
							Main.Log($"Window 5: current time {currentTime} -> window {val} (option {i + 1}).");
							return (DealWindow)(i + 1);
						}
						int num4 = (i + 1) % 4;
						Main.Log($"Window 5: current window {val} too close to cutoff (remaining {num2 - num3} mins), falling back to {num4} (option {num4 + 1}).");
						return (DealWindow)(num4 + 1);
					}
				}
				Main.Log($"Window 5: current time {currentTime} did not match any window, defaulting to Morning.", error: false, warning: true);
				return DealWindow.Morning;
			}
			catch (Exception ex)
			{
				Main.Log("Window 5 resolution error: " + ex.Message + " - defaulting to Late Night.", error: false, warning: true);
				return DealWindow.LateNight;
			}
		}

		public static void TryAutoScheduleDeal(Customer customer)
		{
			//IL_0129: Unknown result type (might be due to invalid IL or missing references)
			//IL_0133: Unknown result type (might be due to invalid IL or missing references)
			//IL_013d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0147: Unknown result type (might be due to invalid IL or missing references)
			//IL_0174: Unknown result type (might be due to invalid IL or missing references)
			//IL_0180: Expected O, but got Unknown
			//IL_0192: 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)
			if (!Config.AutoContractAcceptedEnabled.Value)
			{
				return;
			}
			if ((Object)(object)customer != (Object)null && Config.GetCustomNpcMode(customer.NPC) >= S1APINPCHandling.NoAutomation)
			{
				object obj;
				if (!((Object)(object)customer.customerData != (Object)null))
				{
					NPC nPC = customer.NPC;
					obj = (((Object)(object)nPC != (Object)null) ? nPC.FullName : null) ?? "unknown";
				}
				else
				{
					obj = ((Object)customer.customerData).name;
				}
				Main.Log("Auto scheduling skipped for custom NPC: " + (string)obj);
				return;
			}
			if ((Object)(object)customer == (Object)null || customer.OfferedContractInfo == null)
			{
				Main.Log("Auto scheduling skipped because the customer or offered contract is null.", error: false, warning: true);
				return;
			}
			Main.Log("Auto scheduling for " + (((Object)(object)customer.customerData != (Object)null) ? ((Object)customer.customerData).name : "unknown"));
			DealWindow dealWindow = Config.AutoContractAcceptedWindow.Value;
			if ((Object)(object)customer.NPC == (Object)null || customer.NPC.MSGConversation == null)
			{
				Main.Log("Auto scheduling skipped because NPC or conversation is null.", error: false, warning: true);
				return;
			}
			if (dealWindow == DealWindow.Current)
			{
				dealWindow = ResolveCurrentWindowOption();
			}
			EDealWindow window;
			string text;
			switch (dealWindow)
			{
			case DealWindow.Morning:
				window = (EDealWindow)0;
				text = "Morning";
				break;
			case DealWindow.Afternoon:
				window = (EDealWindow)1;
				text = "Afternoon";
				break;
			case DealWindow.Night:
				window = (EDealWindow)2;
				text = "Night";
				break;
			case DealWindow.LateNight:
				window = (EDealWindow)3;
				text = "Late Night";
				break;
			default:
				window = (EDealWindow)3;
				text = "Late Night";
				Main.Log("AutoContractAcceptedWindow is not correctly set!\nDefaulting to Late Night \nCorrect Values: DealWindow.Morning, DealWindow.Afternoon, DealWindow.Night, DealWindow.LateNight, DealWindow.Current", error: false, warning: true);
				break;
			}
			customer.NPC.MSGConversation.SendMessage(new Message(text, (ESenderType)0, true, -1), true, true);
			customer.NPC.MSGConversation.ClearResponses(true);
			new DelayedScheduler(customer, window).Start();
		}
	}
	public static class DealCalculator
	{
		public static float CalculateSuccessProbability(Customer customer, ProductDefinition product, int quantity, float price, InitialOfferData initialOfferData)
		{
			if ((Object)(object)customer == (Object)null || (Object)(object)product == (Object)null || initialOfferData == null || quantity <= 0 || initialOfferData.Quantity <= 0)
			{
				Main.Log("Success probability calculation skipped because the input data is invalid.", error: false, warning: true);
				return 0f;
			}
			if ((Object)(object)customer.CustomerData == (Object)null)
			{
				Main.Log("Success probability calculation skipped because customerData is null.", error: false, warning: true);
				return 0f;
			}
			ProductDefinition item = Registry.GetItem<ProductDefinition>(initialOfferData.ProductId);
			if ((Object)(object)item == (Object)null)
			{
				Main.Log("Success probability calculation skipped because the initial product could not be resolved.", error: false, warning: true);
				return 0f;
			}
			float valueProposition = Customer.GetValueProposition(item, initialOfferData.Payment / (float)initialOfferData.Quantity);
			float productEnjoyment = customer.GetProductEnjoyment(product);
			float num = Mathf.InverseLerp(-1f, 1f, productEnjoyment);
			float valueProposition2 = Customer.GetValueProposition(product, price / (float)quantity);
			float num2 = Mathf.Lerp(1f, 0f, Mathf.Abs(Mathf.Lerp(0f, 2f, Mathf.Pow((float)quantity / (float)initialOfferData.Quantity, 0.6f) * 0.5f) - 1f));
			if (valueProposition2 * num2 > valueProposition)
			{
				return 1f;
			}
			if (valueProposition2 < 0.12f)
			{
				return 0f;
			}
			float num3 = productEnjoyment * valueProposition;
			float num4 = num * num2 * valueProposition2;
			if (!(num4 > num3))
			{
				return Mathf.Clamp01((0.9f - (Mathf.Lerp(0f, 1f, (num3 - num4) / 0.2f) - Mathf.Lerp(0f, 0.2f, Mathf.Max(customer.CurrentAddiction, customer.NPC.RelationData.NormalizedRelationDelta)))) / 0.9f);
			}
			return 1f;
		}

		public static (float maxSpend, float avgDailySpend) CalculateSpendingLimits(Customer customer)
		{
			if ((Object)(object)customer == (Object)null)
			{
				Main.Log("Spending limit calculation skipped because the customer is null.", error: false, warning: true);
				return (maxSpend: 0f, avgDailySpend: 0f);
			}
			CustomerData customerData = customer.CustomerData;
			if ((Object)(object)customerData == (Object)null)
			{
				Main.Log("Spending limit calculation skipped because customerData is null.", error: false, warning: true);
				return (maxSpend: 0f, avgDailySpend: 0f);
			}
			List<EDay> val = new List<EDay>();
			customerData.GetOrderDays(customer.CurrentAddiction, customer.NPC.RelationData.RelationDelta / 5f, val);
			int num = Math.Max(val.Count, 1);
			float num2 = customerData.GetAdjustedWeeklySpend(customer.NPC.RelationData.RelationDelta / 5f) / (float)num;
			return (maxSpend: num2 * 3f, avgDailySpend: num2);
		}

		public static int FindOptimalPrice(Customer customer, ProductDefinition product, int quantity, float currentPrice, float maxSpend, float minSuccessProbability = -1f, InitialOfferData initialOfferData = null, bool log = false)
		{
			if ((Object)(object)customer == (Object)null || (Object)(object)product == (Object)null || quantity <= 0)
			{
				Main.Log("Optimal price calculation skipped because customer/product/quantity input is invalid.", error: false, warning: true);
				return Math.Max(1, (int)currentPrice);
			}
			if (maxSpend <= 0f)
			{
				Main.Log("Optimal price calculation skipped because maxSpend is invalid.", error: false, warning: true);
				return Math.Max(1, (int)currentPrice);
			}
			if ((double)minSuccessProbability < 0.0)
			{
				minSuccessProbability = Config.MinSuccessProbability.Value;
			}
			int num = (int)Math.Floor(maxSpend - 0.01f);
			int num2 = Math.Min((int)currentPrice, num);
			int num3 = (int)currentPrice;
			if (initialOfferData == null)
			{
				ContractInfo offeredContractInfo = customer.OfferedContractInfo;
				if (offeredContractInfo != null)
				{
					ProductList products = offeredContractInfo.Products;
					if (products != null)
					{
						List<Entry> entries = products.entries;
						if (entries != null && entries.Count > 0 && offeredContractInfo.Products.entries[0].Quantity > 0)
						{
							initialOfferData = new InitialOfferData
							{
								ProductId = offeredContractInfo.Products.entries[0].ProductID,
								Quantity = offeredContractInfo.Products.entries[0].Quantity,
								Payment = offeredContractInfo.Payment
							};
							goto IL_015c;
						}
					}
				}
				initialOfferData = new InitialOfferData
				{
					ProductId = ((BaseItemDefinition)product).ID,
					Quantity = Math.Max(quantity, 1),
					Payment = Math.Max(currentPrice, 1f)
				};
				Main.Log("Optimal price calculation is using fallback initial offer data because offered contract data is unavailable.", error: false, warning: true);
			}
			goto IL_015c;
			IL_015c:
			if (log)
			{
				Main.Log($"Initial Offer Data: ProductId: {initialOfferData.ProductId}, Quantity: {initialOfferData.Quantity}, Payment: {initialOfferData.Payment}");
				Main.Log($"Binary Search Start - Product: {((BaseItemDefinition)product).ID}, Price: {currentPrice}, MaxSpend: {maxSpend}, Quantity: {quantity}, MinProbability: {minSuccessProbability}, Low: {num2}, High: {num}");
			}
			for (int i = 0; i < 20; i++)
			{
				if (num2 >= num)
				{
					break;
				}
				int num4 = (num2 + num) / 2;
				if (CalculateSuccessProbability(customer, product, quantity, num4, initialOfferData) >= minSuccessProbability)
				{
					num2 = num4 + 1;
					if (num2 == num)
					{
						num3 = ((CalculateSuccessProbability(customer, product, quantity, num4 + 1, initialOfferData) > minSuccessProbability) ? (num4 + 1) : num4);
						break;
					}
					num3 = num4;
				}
				else
				{
					num = num4;
				}
			}
			if (!log)
			{
				return num3;
			}
			Main.Log("Binary Search Complete:");
			Main.Log($"  Final bestFailingPrice: {num3}");
			Main.Log($"  Final Probability: {CalculateSuccessProbability(customer, product, quantity, num3, initialOfferData)}");
			return num3;
		}

		public static (int quantity, int price) FindOptimalQuantity(Customer customer, ProductDefinition product, int initialQuantity, float initialPrice, InitialOfferData initialOfferData = null)
		{
			if ((Object)(object)customer == (Object)null || (Object)(object)product == (Object)null || initialQuantity <= 0)
			{
				Main.Log("Optimal quantity calculation skipped because customer/product/quantity input is invalid.", error: false, warning: true);
				return (quantity: Math.Max(initialQuantity, 1), price: Math.Max((int)initialPrice, 1));
			}
			float item = CalculateSpendingLimits(customer).maxSpend;
			(int, int) result;
			if (!Config.IncreaseQuantityEnabled.Value)
			{
				int item2 = FindOptimalPrice(customer, product, initialQuantity, initialPrice, item, -1f, initialOfferData);
				result = (initialQuantity, item2);
			}
			else
			{
				int num = FindOptimalPrice(customer, product, initialQuantity, initialPrice, item, -1f, initialOfferData);
				int item3 = initialQuantity;
				int num2 = num;
				if (!((double)num2 >= Math.Floor(item * 0.99f)))
				{
					int num3 = initialQuantity;
					for (int i = 0; i < 20; i++)
					{
						num3++;
						int num4 = FindOptimalPrice(customer, product, num3, initialPrice, item, -1f, initialOfferData);
						if (num4 <= num2)
						{
							break;
						}
						item3 = num3;
						num2 = num4;
						if ((double)num2 >= Math.Floor(item * 0.99f))
						{
							break;
						}
					}
				}
				result = (item3, num2);
			}
			if (Config.RoundQuantityToNearest5.Value)
			{
				result = RoundQuantityToFive(customer, product, result, item, initialOfferData);
			}
			return result;
		}

		private static (int quantity, int price) RoundQuantityToFive(Customer customer, ProductDefinition product, (int quantity, int price) result, float maxSpend, InitialOfferData initialOfferData)
		{
			int num = Math.Max(5, (int)Math.Round((double)result.quantity / 5.0, MidpointRounding.AwayFromZero) * 5);
			if (num == result.quantity)
			{
				return result;
			}
			if (initialOfferData == null)
			{
				ContractInfo offeredContractInfo = customer.OfferedContractInfo;
				if (offeredContractInfo != null)
				{
					ProductList products = offeredContractInfo.Products;
					if (products != null)
					{
						List<Entry> entries = products.entries;
						if (entries != null && entries.Count > 0 && offeredContractInfo.Products.entries[0].Quantity > 0)
						{
							initialOfferData = new InitialOfferData
							{
								ProductId = offeredContractInfo.Products.entries[0].ProductID,
								Quantity = offeredContractInfo.Products.entries[0].Quantity,
								Payment = offeredContractInfo.Payment
							};
						}
					}
				}
			}
			if (initialOfferData == null)
			{
				Main.Log("Quantity rounding skipped because the original offer is unavailable.", error: false, warning: true);
				return result;
			}
			int num2 = FindOptimalPrice(customer, product, num, 1f, maxSpend, -1f, initialOfferData);
			float num3 = CalculateSuccessProbability(customer, product, num, num2, initialOfferData);
			if (num2 <= 1 || num3 < Config.MinSuccessProbability.Value)
			{
				Main.Log($"Quantity rou

mods/HighBaller-Mono.dll

Decompiled 13 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using FishNet;
using HarmonyLib;
using HighBaller;
using HighBaller.Automation;
using HighBaller.Core;
using HighBaller.Core.Models;
using HighBaller.Helpers;
using HighBaller.UI;
using MelonLoader;
using MelonLoader.Preferences;
using Microsoft.CodeAnalysis;
using ScheduleOne;
using ScheduleOne.Core.Items.Framework;
using ScheduleOne.DevUtilities;
using ScheduleOne.Economy;
using ScheduleOne.GameTime;
using ScheduleOne.ItemFramework;
using ScheduleOne.Levelling;
using ScheduleOne.Messaging;
using ScheduleOne.NPCs;
using ScheduleOne.NPCs.Relation;
using ScheduleOne.Persistence;
using ScheduleOne.PlayerScripts;
using ScheduleOne.Product;
using ScheduleOne.Product.Packaging;
using ScheduleOne.Quests;
using ScheduleOne.UI;
using ScheduleOne.UI.Handover;
using ScheduleOne.UI.Phone;
using ScheduleOne.UI.Phone.ContactsApp;
using ScheduleOne.UI.Phone.Messages;
using ScheduleOne.UI.Phone.ProductManagerApp;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: MelonInfo(typeof(Main), "HighBaller (Mono)", "2.7.12", "xyrilyn, zocke18r, SFox & Virtunerd", null)]
[assembly: MelonAdditionalCredits("Original Deal Optimizer by xyrilyn; 0.4.7f6 compat by k0Mods; 0.4.7f12 update")]
[assembly: MelonGame("TVGS", "Schedule I")]
[assembly: MelonPlatformDomain(/*Could not decode attribute arguments.*/)]
[assembly: MelonOptionalDependencies(new string[] { "ScheduleOne.Core", "FishNet.Runtime" })]
[assembly: HarmonyDontPatchAll]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: IgnoresAccessChecksTo("Assembly-CSharp")]
[assembly: IgnoresAccessChecksTo("ScheduleOne.Core")]
[assembly: AssemblyCompany("xyrilyn, zocke18r, SFox, Virtunerd, k0Mods")]
[assembly: AssemblyConfiguration("Mono")]
[assembly: AssemblyDescription("Deal optimizer, auto counter offer, auto deal completion")]
[assembly: AssemblyFileVersion("2.7.12.0")]
[assembly: AssemblyInformationalVersion("2.7.12+c40c9e5d28a59089ea21e8a8feb2c69982087237")]
[assembly: AssemblyProduct("HighBaller-Mono")]
[assembly: AssemblyTitle("HighBaller-Mono")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("2.7.12.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace HighBaller
{
	public static class Config
	{
		private static MelonPreferences_Category _dealOptimizerCategory;

		internal static MelonPreferences_Entry<float> MinSuccessProbability;

		internal static MelonPreferences_Entry<bool> PriceOptimizationEnabled;

		internal static MelonPreferences_Entry<bool> CounterOfferDarkModeEnabled;

		private static MelonPreferences_Category _dealOptimizerCategoryAutomation;

		internal static MelonPreferences_Entry<bool> AutoCounterOfferEnabled;

		internal static MelonPreferences_Entry<bool> AutoContractAcceptedEnabled;

		internal static MelonPreferences_Entry<DealWindow> AutoContractAcceptedWindow;

		internal static MelonPreferences_Entry<bool> IncreaseQuantityEnabled;

		internal static MelonPreferences_Entry<bool> RoundQuantityToNearest5;

		internal static MelonPreferences_Entry<bool> AutoHandoverEnabled;

		internal static MelonPreferences_Entry<bool> AlwaysAcceptCounterOffersEnabled;

		private static MelonPreferences_Category _dealOptimizerCategoryFeatures;

		internal static MelonPreferences_Entry<bool> DelayAutoResponseDuringSave;

		internal static MelonPreferences_Entry<bool> DebugModeEnabled;

		private static MelonPreferences_Entry<S1APINPCHandling> _customNpcHandling;

		private static bool _s1APIResolved;

		private static Type _s1APINpcType;

		private static FieldInfo _s1NpcField;

		private static FieldInfo _isCustomField;

		private static FieldInfo _allField;

		public static void Initialize()
		{
			_dealOptimizerCategory = MelonPreferences.CreateCategory("HighBaller_IL2CPP", "High Baller");
			MinSuccessProbability = _dealOptimizerCategory.CreateEntry<float>("MinSuccessProbability", 0.98f, "Minimum Success Probability", "The minimum probability of success required for a deal [0.00, 0.99]", false, false, (ValueValidator)(object)new ValueRange<float>(0f, 0.99f), (string)null);
			PriceOptimizationEnabled = _dealOptimizerCategory.CreateEntry<bool>("PriceOptimizationEnabled", false, "Price Optimization Enabled", "Whether to enable price optimization", false, false, (ValueValidator)null, (string)null);
			CounterOfferDarkModeEnabled = _dealOptimizerCategory.CreateEntry<bool>("CounterOfferDarkModeEnabled", true, "Counter Offer Dark Mode", "Whether to enable counter offer dark mode", false, false, (ValueValidator)null, (string)null);
			_dealOptimizerCategoryAutomation = MelonPreferences.CreateCategory("HighBaller_IL2CPP_Automation", "High Baller Automation");
			AutoCounterOfferEnabled = _dealOptimizerCategoryAutomation.CreateEntry<bool>("AutoCounterOfferEnabled", false, "Enable Auto Counter Offer", "Whether to enable auto counter offer", false, false, (ValueValidator)null, (string)null);
			AutoContractAcceptedEnabled = _dealOptimizerCategoryAutomation.CreateEntry<bool>("AutoContractAcceptedEnabled", false, "Enable Auto Deal Scheduling", "Whether to enable auto deal scheduling", false, false, (ValueValidator)null, (string)null);
			AutoContractAcceptedWindow = _dealOptimizerCategoryAutomation.CreateEntry<DealWindow>("AutoDealWindow", DealWindow.LateNight, "Auto Deal Time Window", "The window to auto accept deal. Current falls back to the next window once the current one is too close to its cutoff.", false, false, (ValueValidator)null, "AutoContractAcceptedWindow");
			AlwaysAcceptCounterOffersEnabled = _dealOptimizerCategoryAutomation.CreateEntry<bool>("AlwaysAcceptCounterOffersEnabled", false, "Always Accept Counter Offers", "Force every customer counter-offer evaluation to succeed (regardless of price/quantity).", false, false, (ValueValidator)null, (string)null);
			IncreaseQuantityEnabled = _dealOptimizerCategoryAutomation.CreateEntry<bool>("IncreaseQuantityEnabled", false, "Increase Quantity till max spend", "If enabled, the quantity will be increased until the max spend is reached", false, false, (ValueValidator)null, (string)null);
			RoundQuantityToNearest5 = _dealOptimizerCategoryAutomation.CreateEntry<bool>("RoundQuantityToNearest5", false, "Round quantity to nearest 5", "If enabled, suggested/auto counter-offer quantities are rounded to the nearest multiple of 5 (minimum 5) and re-priced", false, false, (ValueValidator)null, (string)null);
			AutoHandoverEnabled = _dealOptimizerCategoryAutomation.CreateEntry<bool>("AutoHandoverEnabled", false, "Enable automatic handovers", "Whether to enable automatic handover", false, false, (ValueValidator)null, (string)null);
			_dealOptimizerCategoryFeatures = MelonPreferences.CreateCategory("HighBaller_IL2CPP_Features");
			DelayAutoResponseDuringSave = _dealOptimizerCategoryFeatures.CreateEntry<bool>("DelayAutoResponseDuringSave", true, "Don't send auto responses during save", "Whether to delay auto response during save", false, false, (ValueValidator)null, (string)null);
			DebugModeEnabled = _dealOptimizerCategoryFeatures.CreateEntry<bool>("DebugModeEnabled", false, "Debug Mode Enabled", "Enables a lot of logging in the console if needed", false, false, (ValueValidator)null, (string)null);
			_customNpcHandling = _dealOptimizerCategoryFeatures.CreateEntry<S1APINPCHandling>("S1APINPCHandling", S1APINPCHandling.Include, "S1API Custom NPC Handling", "NoAutomation allows orders but skips auto counter-offer/scheduling/handover. Exclude skips all mod features for custom NPCs.", false, false, (ValueValidator)null, "CustomNPCHandling");
		}

		public static S1APINPCHandling GetCustomNpcMode(NPC npc)
		{
			if ((Object)(object)npc == (Object)null || _customNpcHandling.Value == S1APINPCHandling.Include)
			{
				return S1APINPCHandling.Include;
			}
			try
			{
				if (!TryResolveS1ApiMembers() || !(_allField.GetValue(null) is IEnumerable enumerable))
				{
					return S1APINPCHandling.Include;
				}
				foreach (object item in enumerable)
				{
					if (item != null)
					{
						object? value = _s1NpcField.GetValue(item);
						NPC val = (NPC)((value is NPC) ? value : null);
						if (val != null && !((Object)(object)val != (Object)(object)npc))
						{
							object value2 = _isCustomField.GetValue(item);
							return (value2 is bool && (bool)value2) ? _customNpcHandling.Value : S1APINPCHandling.Include;
						}
					}
				}
			}
			catch (Exception ex)
			{
				Main.Log("GetCustomNpcMode error: " + ex.Message, error: false, warning: true);
			}
			return S1APINPCHandling.Include;
		}

		private static bool TryResolveS1ApiMembers()
		{
			if (_s1APIResolved)
			{
				if (_s1APINpcType != null && _s1NpcField != null && _isCustomField != null)
				{
					return _allField != null;
				}
				return false;
			}
			_s1APIResolved = true;
			Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
			for (int i = 0; i < assemblies.Length; i++)
			{
				_s1APINpcType = assemblies[i].GetType("S1API.Entities.NPC");
				if (_s1APINpcType != null)
				{
					break;
				}
			}
			if (_s1APINpcType == null)
			{
				return false;
			}
			_s1NpcField = _s1APINpcType.GetField("S1NPC", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			_isCustomField = _s1APINpcType.GetField("IsCustomNPC", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			_allField = _s1APINpcType.GetField("All", BindingFlags.Static | BindingFlags.Public);
			Main.Log($"S1API detected: NPC type={_s1APINpcType.FullName}, S1NPC={_s1NpcField != null}, IsCustomNPC={_isCustomField != null}, All={_allField != null}", error: false, warning: false, bypassConfig: true);
			if (_s1NpcField != null && _isCustomField != null)
			{
				return _allField != null;
			}
			return false;
		}
	}
	public enum DealWindow
	{
		Morning = 1,
		Afternoon,
		Night,
		LateNight,
		Current
	}
	public enum S1APINPCHandling
	{
		Include,
		NoAutomation,
		Exclude
	}
	public class Main : MelonMod
	{
		internal const string MelonName = "HighBaller (Mono)";

		internal static bool SuppressNextPriceEval;

		private string _lastCounterofferPriceText;

		private bool _listening;

		internal UIHandler UIHandler;

		public static void Log(string message, bool error = false, bool warning = false, bool bypassConfig = false)
		{
			if (Config.DebugModeEnabled.Value || bypassConfig)
			{
				if (error)
				{
					Melon<Main>.Logger.Error(message);
				}
				else if (warning)
				{
					Melon<Main>.Logger.Warning(message);
				}
				else
				{
					Melon<Main>.Logger.Msg(message);
				}
			}
		}

		public override void OnInitializeMelon()
		{
			UIHandler = new UIHandler();
			Config.Initialize();
			((MelonBase)this).HarmonyInstance.PatchAll(typeof(Main).Assembly);
			Log("Initialized HighBaller Fixed v" + ((MelonBase)this).Info.Version, error: false, warning: false, bypassConfig: true);
			Log("DebugMode is " + (Config.DebugModeEnabled.Value ? "enabled" : "disabled") + ", logs will show if it is enabled.", error: false, warning: false, bypassConfig: true);
		}

		public override void OnGUI()
		{
			UIHandler.OnGUI();
		}

		public override void OnSceneWasLoaded(int buildIndex, string sceneName)
		{
			if (sceneName != "Main")
			{
				return;
			}
			try
			{
				ProductManager[] array = Object.FindObjectsOfType<ProductManager>();
				if (array != null && array.Length > 0)
				{
					ProductManager arg = array[0];
					Log($"ProductManager: {arg}");
				}
				else
				{
					Log("No ProductManager found in scene.", error: false, warning: true);
				}
			}
			catch (Exception ex)
			{
				Log("Error finding ProductManager: " + ex.Message, error: false, warning: false, bypassConfig: true);
			}
		}

		public override void OnSceneWasUnloaded(int buildIndex, string sceneName)
		{
			if (_listening)
			{
				_listening = false;
			}
			_lastCounterofferPriceText = null;
		}

		public override void OnUpdate()
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			Scene activeScene = SceneManager.GetActiveScene();
			bool num = ((Scene)(ref activeScene)).name == "Main";
			MessagesApp instance = PlayerSingleton<MessagesApp>.Instance;
			if (num && !_listening && (Object)(object)instance != (Object)null)
			{
				Subscribe();
			}
			if (num && (Object)(object)instance != (Object)null && (Object)(object)instance.CounterofferInterface != (Object)null && (Object)(object)instance.CounterofferInterface.PriceSelector != (Object)null && instance.CounterofferInterface.IsOpen)
			{
				string text = instance.CounterofferInterface.PriceSelector.SelectedAmount.ToString(CultureInfo.InvariantCulture);
				if (!string.Equals(_lastCounterofferPriceText, text, StringComparison.Ordinal))
				{
					_lastCounterofferPriceText = text;
					OfferEvaluator.OfferPriceChangeCheckWithLog();
				}
			}
			else
			{
				_lastCounterofferPriceText = null;
			}
		}

		private void Subscribe()
		{
			MessagesApp instance = PlayerSingleton<MessagesApp>.Instance;
			if ((Object)(object)instance == (Object)null || (Object)(object)instance.CounterofferInterface == (Object)null || (Object)(object)instance.CounterofferInterface.PriceSelector == (Object)null)
			{
				Log("Listener attachment skipped because the counter-offer UI is not ready.", error: false, warning: true);
				return;
			}
			Log("Counter-offer polling initialized");
			_listening = true;
		}
	}
}
namespace HighBaller.UI
{
	internal static class CustomerInfoFormatter
	{
		private static string FormatCurrency(float amount)
		{
			return $"${amount:F2}";
		}

		private static List<EDay> GetSortedOrderDays(List<EDay> orderDays, EDay currentDay)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			return orderDays.OrderBy(delegate(EDay day)
			{
				//IL_0000: Unknown result type (might be due to invalid IL or missing references)
				//IL_0002: Unknown result type (might be due to invalid IL or missing references)
				//IL_0007: Unknown result type (might be due to invalid IL or missing references)
				//IL_0009: Expected I4, but got Unknown
				int num = day - currentDay;
				if (num < 0)
				{
					num += 7;
				}
				return num;
			}).ToList();
		}

		internal static string FormatCustomerInfo(Customer customer, CustomerData customerData, NPCRelationData relationData, EDay currentDay)
		{
			//IL_00a8: 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_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_016d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0199: Unknown result type (might be due to invalid IL or missing references)
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.Append("<section>Customer Details</section>\n<label>Name:</label> <value>").Append(customer.NPC.FullName).Append("</value>\n");
			if ((Object)(object)customer.AssignedDealer != (Object)null)
			{
				stringBuilder.Append("<label>Assigned Dealer:</label> <value>").Append(((NPC)customer.AssignedDealer).FirstName).Append(' ')
					.Append(((NPC)customer.AssignedDealer).LastName)
					.Append("</value>\n");
			}
			List<EDay> list = new List<EDay>();
			customerData.GetOrderDays(customer.CurrentAddiction, relationData.RelationDelta / 5f, list);
			List<EDay> list2 = new List<EDay>();
			foreach (EDay item in list)
			{
				list2.Add(item);
			}
			float adjustedWeeklySpend = customerData.GetAdjustedWeeklySpend(relationData.RelationDelta / 5f);
			float amount = adjustedWeeklySpend * 3f / (float)list2.Count;
			float num = adjustedWeeklySpend / customerData.GetAdjustedWeeklySpend(1f) * 100f;
			stringBuilder.Append("<section>Financial Information</section>\n").Append("<label>Max Spend:</label> <value>" + FormatCurrency(customerData.MaxWeeklySpend) + "</value>\n").Append("<label>Min Spend:</label> <value>" + FormatCurrency(customerData.MinWeeklySpend) + "</value>\n")
				.Append($"<label>Daily Spend Limit:</label> <value>{FormatCurrency(amount)} ({num:F2}% of Max Daily)</value>\n");
			List<EDay> sortedOrderDays = GetSortedOrderDays(list2, currentDay);
			stringBuilder.Append("<section>Schedule Information</section>\n<label>Next Order Days:</label>\n");
			for (int i = 0; i < sortedOrderDays.Count; i++)
			{
				stringBuilder.Append($"<value>  {i + 1}. {sortedOrderDays[i]}</value>\n");
			}
			stringBuilder.Append("<section>Product Preferences</section>\n");
			List<CustomerHelper.ProductOrders> list3 = CustomerHelper.GetProductsFromCustomer(customer).ToList();
			if (list3.Count == 0)
			{
				stringBuilder.Append(((Object)(object)customer.AssignedDealer != (Object)null) ? "<value>Dealer has no appealing products for sale</value>\n" : "<value>Won't buy anything</value>\n");
			}
			foreach (CustomerHelper.ProductOrders item2 in list3)
			{
				PaymentQuantityResult paymentQuantity = item2.PaymentQuantity;
				stringBuilder.Append($"<value>{((BaseItemDefinition)item2.Product).Name} - ${paymentQuantity.Payment:F2} × {paymentQuantity.Quantity} (Appeal: {paymentQuantity.Appeal:F3})</value>\n");
			}
			return stringBuilder.ToString();
		}
	}
	internal class PanelRenderer
	{
		private const int MaxGuiScale = 10;

		private static GUIStyle _salesPanelStyle;

		private static GUIStyle _salesHeaderStyle;

		private static int _guiScale = 1;

		private Texture2D _cachedPanelBackground;

		private readonly PanelState _contactPanel;

		private GUIStyle _infoLabelStyle;

		private GUIStyle _infoValueHighlightStyle;

		private GUIStyle _infoValueStyle;

		private readonly PanelState _salesPanel;

		private GUIStyle _sectionHeaderStyle;

		internal PanelRenderer(PanelState salesPanel, PanelState contactPanel)
		{
			_salesPanel = salesPanel;
			_contactPanel = contactPanel;
			InitializeStyles();
		}

		private void InitializeStyles()
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Expected O, but got Unknown
			//IL_0047: Expected O, but got Unknown
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: 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_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Expected O, but got Unknown
			//IL_0091: Expected O, but got Unknown
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Expected O, but got Unknown
			//IL_00e4: Expected O, but got Unknown
			//IL_00ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0103: Unknown result type (might be due to invalid IL or missing references)
			//IL_0118: Unknown result type (might be due to invalid IL or missing references)
			//IL_0122: Unknown result type (might be due to invalid IL or missing references)
			//IL_0128: Unknown result type (might be due to invalid IL or missing references)
			//IL_0132: Expected O, but got Unknown
			//IL_0137: Expected O, but got Unknown
			//IL_0142: Unknown result type (might be due to invalid IL or missing references)
			//IL_0147: Unknown result type (might be due to invalid IL or missing references)
			//IL_014f: 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_016e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0174: Unknown result type (might be due to invalid IL or missing references)
			//IL_017e: Expected O, but got Unknown
			//IL_0183: Expected O, but got Unknown
			//IL_018e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0193: Unknown result type (might be due to invalid IL or missing references)
			//IL_019b: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d1: Expected O, but got Unknown
			//IL_01d6: Expected O, but got Unknown
			GUIStyle val = new GUIStyle(GUIStyle.op_Implicit("box"));
			val.normal.background = Texture2D.whiteTexture;
			val.normal.textColor = Color.white;
			val.padding = new RectOffset(10, 10, 10, 10);
			_salesPanelStyle = val;
			GUIStyle val2 = new GUIStyle(GUIStyle.op_Implicit("label"))
			{
				fontSize = 20,
				fontStyle = (FontStyle)1
			};
			val2.normal.textColor = Color.white;
			val2.alignment = (TextAnchor)3;
			val2.padding = new RectOffset(10, 0, 0, 0);
			_salesHeaderStyle = val2;
			GUIStyle val3 = new GUIStyle(GUIStyle.op_Implicit("label"))
			{
				fontSize = 16,
				fontStyle = (FontStyle)1
			};
			val3.normal.textColor = new Color(0.9f, 0.9f, 1f);
			val3.padding = new RectOffset(0, 0, 10, 5);
			_sectionHeaderStyle = val3;
			GUIStyle val4 = new GUIStyle(GUIStyle.op_Implicit("label"))
			{
				fontSize = 14,
				fontStyle = (FontStyle)1
			};
			val4.normal.textColor = new Color(0.8f, 0.8f, 0.8f);
			val4.padding = new RectOffset(10, 0, 2, 2);
			_infoLabelStyle = val4;
			GUIStyle val5 = new GUIStyle(GUIStyle.op_Implicit("label"))
			{
				fontSize = 14
			};
			val5.normal.textColor = new Color(1f, 0.95f, 0.8f);
			val5.padding = new RectOffset(10, 0, 2, 8);
			_infoValueStyle = val5;
			GUIStyle val6 = new GUIStyle(GUIStyle.op_Implicit("label"))
			{
				fontSize = 14,
				fontStyle = (FontStyle)1
			};
			val6.normal.textColor = new Color(0.3f, 1f, 0.4f);
			val6.padding = new RectOffset(10, 0, 2, 8);
			_infoValueHighlightStyle = val6;
		}

		private static void HandlePanelDragging(PanelState panel, Rect dragRect, Event currentEvent)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Invalid comparison between Unknown and I4
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Invalid comparison between Unknown and I4
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			EventType type = currentEvent.type;
			if ((int)type != 0)
			{
				if ((int)type == 1)
				{
					panel.IsDragging = false;
				}
			}
			else if (((Rect)(ref dragRect)).Contains(currentEvent.mousePosition))
			{
				panel.IsDragging = true;
				panel.DragOffset = currentEvent.mousePosition - panel.Position;
				currentEvent.Use();
			}
			if (panel.IsDragging && (int)currentEvent.type == 3)
			{
				panel.Position = currentEvent.mousePosition - panel.DragOffset;
				currentEvent.Use();
			}
		}

		internal void DrawPanel(PanelState panel, float width, float height)
		{
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			if (panel.IsVisible)
			{
				Rect dragRect = default(Rect);
				((Rect)(ref dragRect))..ctor(panel.Position.x, panel.Position.y, width - 90f, 40f);
				HandlePanelDragging(panel, dragRect, Event.current);
				panel.Position.x = Mathf.Clamp(panel.Position.x, 0f, (float)Screen.width - width);
				panel.Position.y = Mathf.Clamp(panel.Position.y, 0f, (float)Screen.height - height);
				GUI.backgroundColor = Color.black;
				DrawPanelBackground(panel, width, height);
				DrawPanelContent(panel, width, height);
				DrawPanelHeader(panel, width);
				DrawPanelButtons(panel, width);
			}
		}

		private void DrawPanelBackground(PanelState panel, float width, float height)
		{
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Expected O, but got Unknown
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)_cachedPanelBackground == (Object)null)
			{
				_cachedPanelBackground = new Texture2D(1, 1);
				_cachedPanelBackground.SetPixel(0, 0, new Color(0.15f, 0.15f, 0.2f, 0.95f));
				_cachedPanelBackground.Apply();
			}
			ImguiCompat.DrawTexture(new Rect(panel.Position.x, panel.Position.y, width, height), _cachedPanelBackground);
		}

		private void DrawPanelContent(PanelState panel, float width, float height)
		{
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			string[] array = panel.Content.Split(new char[1] { '\n' }, StringSplitOptions.None);
			float num = panel.Position.y + 40f;
			float num2 = width - 20f;
			panel.ScrollPosition = GUI.BeginScrollView(new Rect(panel.Position.x, num, width, height - 40f), panel.ScrollPosition, new Rect(0f, 0f, num2, (float)(array.Length * 25)));
			float lineY = 0f;
			string[] array2 = array;
			foreach (string line in array2)
			{
				lineY = DrawContentLine(line, num2, lineY);
			}
			GUI.EndScrollView();
		}

		private float DrawContentLine(string line, float contentWidth, float lineY)
		{
			//IL_0039: 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_017d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
			if (line.StartsWith("<section>"))
			{
				string text = line.Replace("<section>", "").Replace("</section>", "");
				GUI.Label(new Rect(10f, lineY, contentWidth, 25f), text, _sectionHeaderStyle);
				return lineY + 30f;
			}
			if (line.Contains("<label>"))
			{
				string text2 = ExtractTaggedText(line, "<label>", "</label>");
				bool flag = line.Contains("<value-good>");
				string text3 = ExtractTaggedText(line, flag ? "<value-good>" : "<value>", flag ? "</value-good>" : "</value>");
				if (string.IsNullOrEmpty(text2))
				{
					return lineY;
				}
				GUI.Label(new Rect(10f, lineY, 140f, 20f), text2, _infoLabelStyle);
				if (!string.IsNullOrEmpty(text3))
				{
					GUI.Label(new Rect(160f, lineY, contentWidth - 160f, 20f), text3, flag ? _infoValueHighlightStyle : _infoValueStyle);
				}
				return lineY + 25f;
			}
			if (line.StartsWith("<value>"))
			{
				string text4 = line.Replace("<value>", "").Replace("</value>", "");
				GUI.Label(new Rect(20f, lineY, contentWidth - 20f, 20f), text4, _infoValueStyle);
				return lineY + 25f;
			}
			if (string.IsNullOrWhiteSpace(line))
			{
				return lineY;
			}
			GUI.Label(new Rect(10f, lineY, contentWidth, 20f), line, _infoValueStyle);
			return lineY + 25f;
		}

		private static string ExtractTaggedText(string line, string openTag, string closeTag)
		{
			int num = line.IndexOf(openTag, StringComparison.Ordinal);
			if (num < 0)
			{
				return "";
			}
			int num2 = num + openTag.Length;
			int num3 = line.IndexOf(closeTag, StringComparison.Ordinal);
			if (num3 >= num2)
			{
				return line.Substring(num2, num3 - num2);
			}
			return "";
		}

		private static void DrawPanelHeader(PanelState panel, float width)
		{
			//IL_001c: 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)
			GUI.Box(new Rect(panel.Position.x, panel.Position.y, width, 40f), "", _salesPanelStyle);
			GUI.Label(new Rect(panel.Position.x, panel.Position.y, width, 40f), panel.Title + " (Drag to Move)", _salesHeaderStyle);
		}

		private void DrawPanelButtons(PanelState panel, float width)
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ef: Unknown result type (might be due to invalid IL or missing references)
			if (GUI.Button(new Rect(panel.Position.x + width - 30f, panel.Position.y + 5f, 25f, 25f), "X"))
			{
				panel.IsVisible = false;
				panel.Position = new Vector2(20f, 20f);
				if (panel == _salesPanel)
				{
					UIHandler.SelectedProduct = null;
				}
				else if (panel == _contactPanel)
				{
					UIHandler.SelectedCustomer = null;
				}
			}
			if (GUI.Button(new Rect(panel.Position.x + width - 60f, panel.Position.y + 5f, 25f, 25f), "+"))
			{
				ChangeGuiScale(1);
			}
			if (GUI.Button(new Rect(panel.Position.x + width - 90f, panel.Position.y + 5f, 25f, 25f), "-"))
			{
				ChangeGuiScale(-1);
			}
		}

		private void ChangeGuiScale(int delta)
		{
			_guiScale = Mathf.Clamp(_guiScale + delta, 1, 10);
			ApplyGuiScale();
		}

		private void ApplyGuiScale()
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Expected O, but got Unknown
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Expected O, but got Unknown
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Expected O, but got Unknown
			//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f0: Expected O, but got Unknown
			_sectionHeaderStyle.fontSize = 16 + _guiScale;
			_sectionHeaderStyle.padding = new RectOffset(0, 0, 10 + _guiScale * 4, 5 + _guiScale * 2);
			_infoLabelStyle.fontSize = 14 + _guiScale;
			_infoLabelStyle.padding = new RectOffset(10, 0, 2 + _guiScale * 4, 2 + _guiScale * 4);
			_infoValueStyle.fontSize = 14 + _guiScale;
			_infoValueStyle.padding = new RectOffset(10 + _guiScale * 8, 0, 2 + _guiScale * 2, 8 + _guiScale * 4);
			_infoValueHighlightStyle.fontSize = 14 + _guiScale;
			_infoValueHighlightStyle.padding = new RectOffset(10 + _guiScale * 8, 0, 2 + _guiScale * 2, 8 + _guiScale * 4);
		}
	}
	internal class PanelState
	{
		public string Content = "";

		public Vector2 DragOffset = Vector2.zero;

		public bool IsDragging;

		public bool IsVisible;

		public Vector2 Position = new Vector2(20f, 20f);

		public Vector2 ScrollPosition = Vector2.zero;

		public readonly string Title;

		public PanelState(string title)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			Title = title;
			base..ctor();
		}
	}
	internal static class PriceButtonFix
	{
		private static readonly HashSet<int> Wired = new HashSet<int>();

		internal static void Apply(ProductManagerApp app)
		{
			//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ec: Expected O, but got Unknown
			if ((Object)(object)app == (Object)null)
			{
				return;
			}
			ProductAppDetailPanel componentInChildren = ((Component)app).GetComponentInChildren<ProductAppDetailPanel>(true);
			if ((Object)(object)componentInChildren == (Object)null)
			{
				return;
			}
			Button[] componentsInChildren = ((Component)componentInChildren).GetComponentsInChildren<Button>(true);
			foreach (Button val in componentsInChildren)
			{
				Transform parent = ((Component)val).transform.parent;
				if ((Object)(object)parent == (Object)null || (Object)(object)parent.parent == (Object)null || ((Object)parent.parent).name != "AskingPrice")
				{
					continue;
				}
				float num;
				if (((Object)val).name == "Add")
				{
					num = 1f;
				}
				else
				{
					if (!(((Object)val).name == "Remove"))
					{
						continue;
					}
					num = -1f;
				}
				if (Wired.Add(((Object)val).GetInstanceID()))
				{
					ProductAppDetailPanel target = componentInChildren;
					float delta = num;
					((UnityEvent)val.onClick).AddListener((UnityAction)delegate
					{
						Click(target, delta);
					});
					Main.Log($"Wired Products asking-price '{((Object)val).name}' button ({delta:+0;-0})");
				}
			}
		}

		private static void Click(ProductAppDetailPanel panel, float change)
		{
			if (!((Object)(object)panel == (Object)null) && !((Object)(object)panel.ActiveProduct == (Object)null))
			{
				panel.AdjustPrice(change);
			}
		}
	}
	internal class SalesInfoFormatter
	{
		private readonly PanelState _salesPanel;

		private DelayedPriceCalculator _currentPriceCalculator;

		internal SalesInfoFormatter(PanelState salesPanel)
		{
			_salesPanel = salesPanel;
		}

		internal void CancelPendingCalculation()
		{
			if (_currentPriceCalculator != null)
			{
				_currentPriceCalculator.Cancel();
				_currentPriceCalculator = null;
			}
		}

		private static string FormatCurrency(float amount)
		{
			return $"${amount:F2}";
		}

		internal string FormatSalesInfo(ProductEntry entry, float? overridePrice = null)
		{
			if ((Object)(object)entry == (Object)null || (Object)(object)entry.Definition == (Object)null)
			{
				Main.Log("Sales info formatting skipped because entry or definition is null.", error: false, warning: true);
				return "";
			}
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.Append("<section>Product Details</section>\n").Append("<label>Product:</label> <value>" + ((BaseItemDefinition)entry.Definition).Name + "</value>\n").Append("<label>Base Price:</label> <value>" + FormatCurrency(entry.Definition.Price) + "</value>\n")
				.Append("<label>Market Value:</label> <value>" + FormatCurrency(entry.Definition.MarketValue) + "</value>\n");
			if (overridePrice.HasValue && !Mathf.Approximately(overridePrice.Value, entry.Definition.Price))
			{
				stringBuilder.Append("<label>Current Price:</label> <value>" + FormatCurrency(overridePrice.Value) + "</value>\n");
			}
			List<CustomerAppeal> list = (from ca in (from knownCustomer in CustomerHelper.GetKnownCustomers()
					select new CustomerAppeal
					{
						Customer = knownCustomer,
						Appeal = CustomerHelper.GetProductAppeal(entry.Definition, knownCustomer, overridePrice),
						PaymentQuantity = CustomerHelper.CalculatePaymentQuantity(entry.Definition, knownCustomer, overridePrice)
					}).ToList()
				orderby ca.Appeal descending
				select ca).ToList();
			List<CustomerAppeal> list2 = list.FindAll((CustomerAppeal ca) => ca.Appeal > 0.05f);
			float num = PriceOptimizer.EvaluatePriceAcceptance(entry.Definition, list, overridePrice ?? entry.Definition.Price);
			double num2 = ((list2.Count > 0) ? list2.Average((CustomerAppeal ca) => ca.PaymentQuantity.Quantity) : 0.0);
			string text = ((list2.Count > 0) ? FormatCurrency(list2.Average((CustomerAppeal ca) => ca.PaymentQuantity.Payment)) : FormatCurrency(0f));
			string text2 = ((list2.Count > 0) ? FormatCurrency(list2.Average((CustomerAppeal ca) => ca.PaymentQuantity.Payment / (float)ca.PaymentQuantity.Quantity)) : FormatCurrency(0f));
			stringBuilder.Append("<section>Market Analysis</section>\n").Append($"<label>Potential Customers:</label> <value-good>{list2.Count}</value-good>\n").Append($"<label>Average Order Size:</label> <value>{num2:F1}</value>\n")
				.Append("<label>Average Payment:</label> <value>" + text + "</value>\n")
				.Append("<label>Per-Unit Price:</label> <value>" + text2 + "</value>\n")
				.Append($"<label>Max Spender Score:</label> <value>{num:F2}</value>\n");
			float num3 = ((list2.Count > 0) ? list2.Average((CustomerAppeal ca) => ca.Appeal) : 0f);
			float num4 = ((list2.Count > 0) ? list2.Min((CustomerAppeal ca) => ca.Appeal) : 0f);
			float num5 = ((list2.Count > 0) ? list2.Max((CustomerAppeal ca) => ca.Appeal) : 0f);
			float num6 = ((list.Count > 0) ? list.Average((CustomerAppeal ca) => ca.Appeal) : 0f);
			float num7 = ((list.Count > 0) ? list.Min((CustomerAppeal ca) => ca.Appeal) : 0f);
			stringBuilder.Append("<section>Appeal Statistics</section>\n<label>Customer Appeal:</label>\n").Append($"<value>Average: {num3:F2}</value>\n").Append($"<value>Min: {num4:F2}</value>\n")
				.Append($"<value>Max: {num5:F2}</value>\n")
				.Append($"<label>Overall Appeal:</label>\n<value>Average: {num6:F2}</value>\n<value>Min: {num7:F2}</value>\n");
			if (!Config.PriceOptimizationEnabled.Value)
			{
				return stringBuilder.ToString();
			}
			stringBuilder.Append("<section>Price Optimization</section>\n").Append("<label>Original Price:</label> <value>" + FormatCurrency(entry.Definition.Price) + "</value>\n").Append("<label>Optimal Price:</label> <value>Calculating...</value>\n")
				.Append("<label>Expected Revenue:</label> <value>Calculating...</value>\n")
				.Append("<label>Units Needed:</label> <value>Calculating...</value>\n")
				.Append("<label>No-Loss Price:</label> <value>Calculating...</value>\n")
				.Append("<label>Max Markup:</label> <value>Calculating...</value>\n");
			float initialPrice = overridePrice ?? entry.Definition.Price;
			float maxPrice = Math.Max(((list.Count > 0) ? list.Max((CustomerAppeal ca) => DealCalculator.CalculateSpendingLimits(ca.Customer).maxSpend) : (entry.Definition.MarketValue * 3f)) - 1f, entry.Definition.MarketValue * 2f);
			_currentPriceCalculator = new DelayedPriceCalculator(entry.Definition, list, initialPrice, 1f, maxPrice, delegate((float optimalPrice, float noLossPrice, float expectedRevenue, int expectedUnits) result)
			{
				float item = result.optimalPrice;
				float item2 = result.noLossPrice;
				float amount = ((result.expectedUnits > 0) ? (result.expectedRevenue / (float)result.expectedUnits) : 0f);
				string[] array = _salesPanel.Content.Split(new char[1] { '\n' }, StringSplitOptions.None);
				for (int i = 0; i < array.Length; i++)
				{
					if (array[i].Contains("Optimal Price:"))
					{
						array[i] = "<label>Optimal Price:</label> <value>" + FormatCurrency(item) + "</value>\n";
					}
					else if (array[i].Contains("Expected Revenue:"))
					{
						array[i] = "<label>Expected Revenue:</label> <value>" + FormatCurrency(result.expectedRevenue) + " (" + FormatCurrency(amount) + "/unit)</value>\n";
					}
					else if (array[i].Contains("Units Needed:"))
					{
						array[i] = "<label>Units Needed:</label> <value>" + result.expectedUnits + "</value>\n";
					}
					else if (array[i].Contains("No-Loss Price:"))
					{
						array[i] = "<label>No-Loss Price:</label> <value>" + FormatCurrency(item2) + "</value>\n";
					}
					else if (array[i].Contains("Max Markup:"))
					{
						array[i] = $"<label>Max Markup:</label> <value>{(item - entry.Definition.Price) / entry.Definition.Price * 100f:F1}%</value>\n";
					}
				}
				_salesPanel.Content = string.Join("\n", array);
			});
			_currentPriceCalculator.Start();
			return stringBuilder.ToString();
		}
	}
	public class UIHandler
	{
		internal static ProductManagerApp ProductManagerApp;

		private static string _counterOfferDisplayText = "";

		private readonly PanelState _contactPanel;

		private GUIStyle _displayTextStyle;

		private readonly PanelRenderer _panelRenderer;

		private readonly SalesInfoFormatter _salesInfoFormatter;

		private readonly PanelState _salesPanel;

		private const float PriceRefreshDelay = 0.4f;

		private float _lastSeenPrice = -1f;

		private float _priceChangedAt = -1f;

		public static ProductEntry SelectedProduct { get; set; }

		public static Customer SelectedCustomer { get; set; }

		public UIHandler()
		{
			InitializeStyles();
			_salesPanel = new PanelState("Sales Information");
			_contactPanel = new PanelState("Contact Information");
			_salesInfoFormatter = new SalesInfoFormatter(_salesPanel);
			_panelRenderer = new PanelRenderer(_salesPanel, _contactPanel);
		}

		private void InitializeStyles()
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: 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_0034: Expected O, but got Unknown
			GUIStyle val = new GUIStyle(GUIStyle.op_Implicit("label"))
			{
				fontSize = 18
			};
			val.normal.background = Texture2D.whiteTexture;
			val.alignment = (TextAnchor)4;
			_displayTextStyle = val;
		}

		public static void UpdateCounterOfferDisplayText(string text, string reasonText)
		{
			_counterOfferDisplayText = text + "\n" + reasonText;
		}

		private void RefreshSalesPanelOnPriceChange()
		{
			ProductEntry selectedProduct = SelectedProduct;
			if (!((Object)(object)selectedProduct == (Object)null) && !((Object)(object)selectedProduct.Definition == (Object)null))
			{
				float price = selectedProduct.Definition.Price;
				if (!Mathf.Approximately(price, _lastSeenPrice))
				{
					_lastSeenPrice = price;
					_priceChangedAt = Time.unscaledTime;
				}
				else if (!(_priceChangedAt < 0f) && !(Time.unscaledTime - _priceChangedAt < 0.4f))
				{
					_priceChangedAt = -1f;
					Main.Log($"ProductManager: Price changed to {price} for {((BaseItemDefinition)selectedProduct.Definition).ID}", error: false, warning: false, bypassConfig: true);
					UpdateSalesInfoPanel(selectedProduct);
				}
			}
		}

		public void UpdateSalesInfoPanel(ProductEntry entry, float? overridePrice = null)
		{
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			_salesInfoFormatter.CancelPendingCalculation();
			SelectedProduct = entry;
			_lastSeenPrice = (((Object)(object)entry != (Object)null && (Object)(object)entry.Definition != (Object)null) ? entry.Definition.Price : (-1f));
			_priceChangedAt = -1f;
			_salesPanel.IsVisible = true;
			_salesPanel.ScrollPosition = Vector2.zero;
			_salesPanel.Content = _salesInfoFormatter.FormatSalesInfo(entry, overridePrice);
		}

		public void UpdateContactInfoPanel(Customer customer)
		{
			//IL_0083: 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_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)customer == (Object)null)
			{
				_contactPanel.IsVisible = false;
				return;
			}
			if ((Object)(object)customer.customerData == (Object)null || (Object)(object)customer.NPC == (Object)null || customer.NPC.RelationData == null)
			{
				Main.Log("Contact info panel skipped because customer data, NPC, or relation data is null.", error: false, warning: true);
				_contactPanel.IsVisible = false;
				return;
			}
			TimeManager instance = NetworkSingleton<TimeManager>.Instance;
			if ((Object)(object)instance == (Object)null)
			{
				Main.Log("Contact info panel skipped because TimeManager is unavailable.", error: false, warning: true);
				_contactPanel.IsVisible = false;
				return;
			}
			EDay currentDay = instance.CurrentDay;
			SelectedCustomer = customer;
			_contactPanel.IsVisible = true;
			_contactPanel.ScrollPosition = Vector2.zero;
			_contactPanel.Content = CustomerInfoFormatter.FormatCustomerInfo(customer, customer.customerData, customer.NPC.RelationData, currentDay);
		}

		private void DrawSalesInfoPanel()
		{
			_panelRenderer.DrawPanel(_salesPanel, 420f, 800f);
		}

		private void DrawContactInfoPanel()
		{
			_panelRenderer.DrawPanel(_contactPanel, 440f, 700f);
		}

		public void OnGUI()
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_012b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0131: Invalid comparison between Unknown and I4
			//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
			Scene activeScene = SceneManager.GetActiveScene();
			if (((Scene)(ref activeScene)).name != "Main")
			{
				return;
			}
			Phone instance = PlayerSingleton<Phone>.Instance;
			if ((Object)(object)instance == (Object)null || !instance.IsOpen)
			{
				return;
			}
			if (!PlayerSingleton<HomeScreen>.Instance.isOpen && (Object)(object)PlayerSingleton<MessagesApp>.Instance != (Object)null && PlayerSingleton<MessagesApp>.Instance.CounterofferInterface.IsOpen)
			{
				if (Config.CounterOfferDarkModeEnabled.Value)
				{
					GUI.backgroundColor = new Color(0.15f, 0.15f, 0.2f, 0.95f);
					_displayTextStyle.normal.textColor = Color.white;
				}
				else
				{
					_displayTextStyle.normal.textColor = Color.black;
				}
				GUI.Label(new Rect((float)(Screen.width / 2 - 190), (float)(Screen.height / 2 - 250), 380f, 70f), _counterOfferDisplayText, _displayTextStyle);
				GUI.backgroundColor = Color.white;
			}
			if ((Object)(object)ProductManagerApp != (Object)null && ((App<ProductManagerApp>)(object)ProductManagerApp).isOpen && _salesPanel.IsVisible)
			{
				if ((int)Event.current.type == 7)
				{
					RefreshSalesPanelOnPriceChange();
				}
				DrawSalesInfoPanel();
			}
			if (!((Object)(object)PlayerSingleton<ContactsApp>.Instance == (Object)null) && ((App<ContactsApp>)(object)PlayerSingleton<ContactsApp>.Instance).isOpen && _contactPanel.IsVisible)
			{
				DrawContactInfoPanel();
			}
		}
	}
}
namespace HighBaller.Patches.Sales
{
	[HarmonyPatch(typeof(ProductManagerApp), "SelectProduct")]
	public static class ProductManagerSelectProductPatch
	{
		public static void Prefix(ProductManagerApp __instance, ProductEntry entry)
		{
			UIHandler.ProductManagerApp = __instance;
			PriceButtonFix.Apply(__instance);
		}

		private static void Postfix(ProductEntry entry)
		{
			Melon<Main>.Instance.UIHandler.UpdateSalesInfoPanel(entry);
		}
	}
}
namespace HighBaller.Patches.Leveling
{
	[HarmonyPatch(typeof(LevelManager), "AddXP")]
	public static class LevelManagerLoggingPatch
	{
		public static void Postfix(int xp)
		{
			Main.Log($"LevelManager: AddXP: {xp}");
		}
	}
}
namespace HighBaller.Patches.Handover
{
	public static class HandoverPackageSelector
	{
		public static List<ProductPackage<T>> FindOptimalPackages<T>(List<ProductPackage<T>> availablePackages, int targetQuantity)
		{
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			if (targetQuantity <= 0 || ((IEnumerable<ProductPackage<T>>)availablePackages).Sum((Func<ProductPackage<T>, int>)TotalUnitsSelector) < targetQuantity)
			{
				return new List<ProductPackage<T>>();
			}
			List<ProductPackage<T>> selectedPackages = new List<ProductPackage<T>>();
			int num = targetQuantity;
			List<ProductPackage<T>> list = availablePackages.OrderByDescending(PackageSizeSelector).ToList();
			foreach (ProductPackage<T> item in list)
			{
				if (num <= 0)
				{
					break;
				}
				int num2 = Math.Min(item.AvailableQuantity, num / item.PackageSize);
				if (num2 > 0)
				{
					selectedPackages.Add(new ProductPackage<T>(item.PackageSize, item.Slot, num2, item.Quality));
					num -= num2 * item.PackageSize;
				}
			}
			if (num <= 0)
			{
				return selectedPackages;
			}
			List<ProductPackage<T>> list2 = FindExactMatch(list.Where((ProductPackage<T> p) => !selectedPackages.Any((ProductPackage<T> sp) => sp.Slot.Equals(p.Slot))).ToList(), num);
			if (list2 == null)
			{
				return new List<ProductPackage<T>>();
			}
			selectedPackages.AddRange(list2);
			return selectedPackages;
			static int PackageSizeSelector(ProductPackage<T> p)
			{
				return p.PackageSize;
			}
			static int TotalUnitsSelector(ProductPackage<T> p)
			{
				return p.TotalUnits;
			}
		}

		private static List<ProductPackage<T>> FindExactMatch<T>(List<ProductPackage<T>> packages, int target)
		{
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			if (target == 0)
			{
				return new List<ProductPackage<T>>();
			}
			if (packages.Count == 0 || target < 0)
			{
				return null;
			}
			ProductPackage<T> productPackage = packages[0];
			List<ProductPackage<T>> packages2 = packages.Skip(1).ToList();
			int num = Math.Min(productPackage.AvailableQuantity, target / productPackage.PackageSize);
			for (int i = 0; i <= num; i++)
			{
				int target2 = target - i * productPackage.PackageSize;
				List<ProductPackage<T>> list = FindExactMatch(packages2, target2);
				if (list != null)
				{
					if (i > 0)
					{
						list.Add(new ProductPackage<T>(productPackage.PackageSize, productPackage.Slot, i, productPackage.Quality));
					}
					return list;
				}
			}
			return null;
		}
	}
	[HarmonyPatch(typeof(HandoverScreenContractMode), "Open")]
	public static class HandoverScreenOpenPatch
	{
		public static bool Prefix(Contract contract)
		{
			Customer val = (((Object)(object)contract != (Object)null && (Object)(object)contract.Customer != (Object)null) ? ((Component)contract.Customer).GetComponent<Customer>() : null);
			if ((Object)(object)val != (Object)null && (Object)(object)val.CustomerData != (Object)null)
			{
				return true;
			}
			Main.Log("HandoverScreen.Open blocked: customer or customerData is null (likely S1API custom NPC).", error: false, warning: true);
			return false;
		}
	}
	[HarmonyPatch(typeof(Customer), "CompleteContractDialogueChosen")]
	public static class HandoverService
	{
		public static bool Prefix(Customer __instance)
		{
			if (!Config.AutoHandoverEnabled.Value)
			{
				return true;
			}
			if (Config.GetCustomNpcMode(((Object)(object)__instance != (Object)null) ? __instance.NPC : null) < S1APINPCHandling.NoAutomation)
			{
				return DoDeal(__instance);
			}
			Main.Log("Auto handover skipped for custom NPC: " + (((Object)(object)__instance.customerData != (Object)null) ? ((Object)__instance.customerData).name : "unknown"));
			return true;
		}

		private static bool DoDeal(Customer customer)
		{
			//IL_00fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_0103: Unknown result type (might be due to invalid IL or missing references)
			//IL_0108: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0339: Unknown result type (might be due to invalid IL or missing references)
			//IL_0271: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)customer == (Object)null || (Object)(object)customer.NPC == (Object)null)
			{
				Main.Log("Auto handover skipped because the customer is invalid.", error: false, warning: true);
				return true;
			}
			if ((Object)(object)customer.CurrentContract == (Object)null || customer.CurrentContract.ProductList == null || customer.CurrentContract.ProductList.entries == null || customer.CurrentContract.ProductList.entries.Count == 0)
			{
				Main.Log("Auto handover skipped because the current contract has no products.", error: false, warning: true);
				return true;
			}
			Main.Log("Customer: " + (((Object)(object)customer.NPC != (Object)null) ? customer.NPC.FullName : "unknown"));
			Entry obj = customer.CurrentContract.ProductList.entries[0];
			string productID = obj.ProductID;
			int quantity = obj.Quantity;
			if (quantity <= 0)
			{
				return true;
			}
			if ((Object)(object)customer.CustomerData == (Object)null)
			{
				Main.Log("Auto handover skipped because customer data is null.", error: false, warning: true);
				return true;
			}
			EQuality minQuality = StandardsMethod.GetCorrespondingQuality(customer.CustomerData.Standards);
			List<ProductPackage<ItemSlot>> list = new List<ProductPackage<ItemSlot>>();
			PlayerInventory instance = PlayerSingleton<PlayerInventory>.Instance;
			if ((Object)(object)Player.Local == (Object)null || (Object)(object)instance == (Object)null)
			{
				Main.Log("Auto handover skipped because Player.Local or Inventory is null.", error: false, warning: true);
				return true;
			}
			foreach (ItemSlot allInventorySlot in instance.GetAllInventorySlots())
			{
				ItemInstance itemInstance = allInventorySlot.ItemInstance;
				if (itemInstance != null && !(((BaseItemDefinition)itemInstance.Definition).ID != productID) && ((BaseItemInstance)itemInstance).Quantity > 0)
				{
					Main.Log($"Item: {((BaseItemDefinition)itemInstance.Definition).ID} - {((BaseItemInstance)itemInstance).Quantity} - {((BaseItemDefinition)itemInstance.Definition).Category}");
					ProductItemInstance val = (ProductItemInstance)(object)((itemInstance is ProductItemInstance) ? itemInstance : null);
					if (val != null && !((Object)(object)val.packaging == (Object)null) && ((QualityItemInstance)val).Quality >= minQuality)
					{
						PackagingDefinition packaging = val.packaging;
						Main.Log($"ProductItem: {((BaseItemDefinition)itemInstance.Definition).ID} - {((BaseItemInstance)itemInstance).Quantity} - {((BaseItemDefinition)packaging).Name}");
						Main.Log($"Packaging: {packaging.Quantity} {((BaseItemDefinition)packaging).ID}");
						list.Add(new ProductPackage<ItemSlot>(packaging.Quantity, allInventorySlot, ((BaseItemInstance)itemInstance).Quantity, ((QualityItemInstance)val).Quality));
					}
				}
			}
			List<ProductPackage<ItemSlot>> list2 = new List<ProductPackage<ItemSlot>>();
			IEnumerable<EQuality> source = Enum.GetValues(typeof(EQuality)).Cast<EQuality>();
			Func<EQuality, bool> predicate = (EQuality q) => q >= minQuality;
			foreach (EQuality qualityLevel in source.Where(predicate))
			{
				Main.Log($"Finding optimal packages for quality: {qualityLevel}");
				list2 = HandoverPackageSelector.FindOptimalPackages(list.Where((ProductPackage<ItemSlot> p) => p.Quality == qualityLevel).ToList(), quantity);
				if (list2.Count > 0)
				{
					Main.Log($"Found optimal packages for quality: {qualityLevel}");
					break;
				}
			}
			if (list2.Count == 0)
			{
				Main.Log("No suitable combination of packages found to meet target quantity");
				return true;
			}
			List<ItemInstance> list3 = new List<ItemInstance>();
			foreach (ProductPackage<ItemSlot> item in list2)
			{
				Main.Log($"Selected package: {item?.PackageSize} units, {item?.AvailableQuantity} packages");
				if (item == null)
				{
					Main.Log("Selected package is null", error: false, warning: true);
					continue;
				}
				ItemInstance copy = item.Slot.ItemInstance.GetCopy(-1);
				if (item.Slot.Quantity.Equals(item.AvailableQuantity))
				{
					((BaseItemInstance)item.Slot.ItemInstance).RequestClearSlot();
				}
				else
				{
					item.Slot.ChangeQuantity(-item.AvailableQuantity, false);
				}
				((BaseItemInstance)copy).Quantity = item.AvailableQuantity;
				list3.Add(copy);
			}
			customer.ProcessHandover(customer.CurrentContract, list3, true, true);
			return false;
		}
	}
}
namespace HighBaller.Patches.CounterOffer
{
	[HarmonyPatch(typeof(CounterofferInterface), "SetProduct")]
	public static class CounterofferInterfaceChangeProductPatch
	{
		private static void Postfix(ProductDefinition newProduct)
		{
			MessagesApp instance = PlayerSingleton<MessagesApp>.Instance;
			if ((Object)(object)instance == (Object)null || (Object)(object)newProduct == (Object)null)
			{
				Main.Log("Counteroffer product change skipped because the UI or product is unavailable.", error: false, warning: true);
				return;
			}
			Main.Log("CounterofferInterfaceChangeProductPatch: " + ((BaseItemDefinition)newProduct).Name);
			OfferData offerData = OfferEvaluator.GetOfferData();
			if (offerData != null)
			{
				Customer customer = offerData.Customer;
				int quantity = offerData.Quantity;
				float price = offerData.Price;
				var (num, num2) = DealCalculator.FindOptimalQuantity(customer, newProduct, quantity, price * 0.25f);
				if (!Mathf.Approximately((float)num2, price))
				{
					instance.CounterofferInterface.PriceSelector.ChangeAmount((float)(num2 - (int)price));
					instance.CounterofferInterface.ChangeQuantity((float)(num - quantity));
				}
			}
		}
	}
	[HarmonyPatch(typeof(AmountSelector), "ChangeAmount")]
	public static class CounterofferInterfacePostChangePricePatch
	{
		private static void Postfix(AmountSelector __instance, float change)
		{
			MessagesApp instance = PlayerSingleton<MessagesApp>.Instance;
			if (!((Object)(object)instance == (Object)null) && !((Object)(object)instance.CounterofferInterface == (Object)null) && !((Object)(object)instance.CounterofferInterface.PriceSelector != (Object)(object)__instance))
			{
				if (Main.SuppressNextPriceEval)
				{
					Main.SuppressNextPriceEval = false;
				}
				else
				{
					OfferEvaluator.OfferPriceChangeCheckNoLog();
				}
			}
		}
	}
	[HarmonyPatch(typeof(CounterofferInterface), "ChangeQuantity", new Type[] { typeof(float) })]
	public static class CounterofferInterfacePostChangeQuantityPatch
	{
		private static void Postfix(float change)
		{
			MessagesApp instance = PlayerSingleton<MessagesApp>.Instance;
			if ((Object)(object)instance == (Object)null || !instance.CounterofferInterface.IsOpen)
			{
				return;
			}
			OfferData offerData = OfferEvaluator.GetOfferData();
			if (offerData == null)
			{
				return;
			}
			Customer customer = offerData.Customer;
			float item = DealCalculator.CalculateSpendingLimits(customer).maxSpend;
			CounterofferInterface counterofferInterface = instance.CounterofferInterface;
			ProductDefinition product = counterofferInterface.selectedProduct ?? offerData.Product;
			int quantity = offerData.Quantity;
			float price = offerData.Price;
			int num = DealCalculator.FindOptimalPrice(customer, product, quantity, 1f, item, -1f, null, log: true);
			if (num <= 1)
			{
				ContractInfo offeredContractInfo = customer.OfferedContractInfo;
				ProductList val = offeredContractInfo?.Products;
				if (val != null)
				{
					List<Entry> entries = val.entries;
					if (entries != null && entries.Count > 0)
					{
						int quantity2 = offeredContractInfo.Products.entries[0].Quantity;
						if (quantity2 > 0)
						{
							num = Math.Min((int)(offeredContractInfo.Payment / (float)quantity2 * (float)quantity), (int)item - 1);
							Main.Log($"FindOptimalPrice fallback: proportional price {num} for {quantity} units");
						}
					}
				}
			}
			if (!Mathf.Approximately((float)num, price))
			{
				Main.SuppressNextPriceEval = true;
				counterofferInterface.PriceSelector.ChangeAmount((float)(num - (int)price));
			}
			OfferEvaluator.OfferPriceChangeCheckNoLog();
		}
	}
	[HarmonyPatch(typeof(CounterofferInterface), "Open")]
	public static class CounterofferInterfacePostOpenPatch
	{
		private static void Postfix(ProductDefinition product, int quantity, float price, MSGConversation _conversation, Action<ProductDefinition, int, float> _orderConfirmedCallback)
		{
			MessagesApp instance = PlayerSingleton<MessagesApp>.Instance;
			Customer customerFromConversation = CustomerHelper.GetCustomerFromConversation(_conversation);
			if ((Object)(object)instance == (Object)null || (Object)(object)product == (Object)null || (Object)(object)customerFromConversation == (Object)null)
			{
				Main.Log("Counteroffer open automation skipped because the UI, product, or customer is unavailable.", error: false, warning: true);
			}
			else if (Config.GetCustomNpcMode(customerFromConversation.NPC) < S1APINPCHandling.Exclude)
			{
				var (num, num2) = DealCalculator.FindOptimalQuantity(customerFromConversation, product, quantity, price);
				if (!((float)num2 <= price))
				{
					instance.CounterofferInterface.PriceSelector.ChangeAmount((float)(num2 - (int)price));
					instance.CounterofferInterface.ChangeQuantity((float)(num - quantity));
				}
			}
		}
	}
}
namespace HighBaller.Patches.Contracts
{
	[HarmonyPatch(typeof(Customer), "AcceptContractClicked")]
	public static class AcceptContractClickedPatch
	{
		public static void Postfix(Customer __instance)
		{
			DealAutoScheduler.TryAutoScheduleDeal(__instance);
		}
	}
	[HarmonyPatch(typeof(Customer), "EvaluateCounteroffer")]
	public static class EvaluateCounterOfferPatch
	{
		public static bool Prefix(Customer __instance, ref bool __result)
		{
			if (!Config.AlwaysAcceptCounterOffersEnabled.Value)
			{
				return true;
			}
			if ((Object)(object)__instance != (Object)null && Config.GetCustomNpcMode(__instance.NPC) >= S1APINPCHandling.NoAutomation)
			{
				return true;
			}
			__result = true;
			Main.Log("AlwaysAcceptCounterOffers: forcing accept for " + (((Object)(object)__instance != (Object)null && (Object)(object)__instance.customerData != (Object)null) ? ((Object)__instance.customerData).name : "unknown"));
			return false;
		}

		public static void Postfix(Customer __instance, bool __result)
		{
			if (!__result)
			{
				Main.Log("Counter failed", error: false, warning: true);
			}
			else
			{
				DealAutoScheduler.TryAutoScheduleDeal(__instance);
			}
		}
	}
	[HarmonyPatch(typeof(Customer), "OfferContract")]
	public static class OfferContractPatch
	{
		public static void Postfix(ContractInfo info, Customer __instance, MethodBase __originalMethod)
		{
			Entry entry;
			if ((Object)(object)__instance == (Object)null || info?.Products?.entries == null || info.Products.entries.Count == 0)
			{
				Main.Log("OfferContractPatch skipped because the contract info is incomplete.", error: false, warning: true);
			}
			else if (Config.GetCustomNpcMode(__instance.NPC) >= S1APINPCHandling.NoAutomation)
			{
				Main.Log("OfferContractPatch: skipping automation for custom NPC: " + (((Object)(object)__instance.customerData != (Object)null) ? ((Object)__instance.customerData).name : "unknown"));
			}
			else if ((Object)(object)__instance.customerData == (Object)null || (Object)(object)__instance.NPC == (Object)null)
			{
				Main.Log("OfferContractPatch skipped because customerData or NPC is null.", error: false, warning: true);
			}
			else if (Config.AutoCounterOfferEnabled.Value)
			{
				Main.Log("Customer: " + (((Object)(object)__instance.customerData != (Object)null) ? ((Object)__instance.customerData).name : "unknown") + ", Contract: " + info.Products.entries[0].ProductID);
				entry = info.Products.entries[0];
				ProductDefinition val = null;
				foreach (ProductDefinition listedProduct in ProductManager.ListedProducts)
				{
					if (MatchesEntry(listedProduct))
					{
						val = listedProduct;
						break;
					}
				}
				if ((Object)(object)val == (Object)null)
				{
					val = Registry.GetItem<ProductDefinition>(entry.ProductID);
				}
				if ((Object)(object)val == (Object)null)
				{
					Main.Log("Auto counter-offer skipped because the offered product could not be resolved.", error: false, warning: true);
					return;
				}
				float item = DealCalculator.CalculateSpendingLimits(__instance).maxSpend;
				if ((double)info.Payment >= Math.Floor(item))
				{
					Main.Log("Skipping counter offer for " + ((Object)__instance.customerData).name + " because they are over their max spend");
					new DelayedCounterOffer(__instance, val, entry.Quantity, info.Payment, skipCounterOffer: true).Start();
					return;
				}
				InitialOfferData initialOfferData = new InitialOfferData
				{
					ProductId = entry.ProductID,
					Quantity = entry.Quantity,
					Payment = info.Payment
				};
				var (quantity, num) = DealCalculator.FindOptimalQuantity(__instance, val, entry.Quantity, info.Payment, initialOfferData);
				new DelayedCounterOffer(__instance, val, quantity, num).Start();
			}
			else if (Config.AutoContractAcceptedEnabled.Value)
			{
				Main.Log("Auto-scheduling (without counter-offer) for " + (((Object)(object)__instance.customerData != (Object)null) ? ((Object)__instance.customerData).name : "unknown"));
				new DelayedCounterOffer(__instance, null, 0, 0f, skipCounterOffer: true).Start();
			}
			bool MatchesEntry(ProductDefinition product)
			{
				return ((BaseItemDefinition)product).ID.Equals(entry.ProductID);
			}
		}
	}
}
namespace HighBaller.Patches.Contacts
{
	[HarmonyPatch(typeof(ContactsDetailPanel), "Open")]
	public static class ContactsDetailPanelOpenPatch
	{
		[HarmonyPostfix]
		public static void Postfix(NPC npc, ContactsDetailPanel __instance)
		{
			if (!((Object)(object)npc == (Object)null))
			{
				Main.Log($"RelationCircle: {npc.ID}, Name: {npc.FullName}, RelationDelta: {npc.RelationData.RelationDelta}, Unlocked: {npc.RelationData.Unlocked}");
				Customer customerFromNpc = CustomerHelper.GetCustomerFromNpc(npc);
				if ((Object)(object)customerFromNpc == (Object)null)
				{
					Main.Log("Not a customer");
					Melon<Main>.Instance.UIHandler.UpdateSalesInfoPanel(null);
				}
				else
				{
					Melon<Main>.Instance.UIHandler.UpdateContactInfoPanel(customerFromNpc);
				}
			}
		}
	}
}
namespace HighBaller.Helpers
{
	public static class CustomerHelper
	{
		public class ProductOrders
		{
			public ProductDefinition Product { get; set; }

			public PaymentQuantityResult PaymentQuantity { get; set; }
		}

		public static Customer GetCustomerFromConversation(MSGConversation conversation)
		{
			if (conversation == null)
			{
				Main.Log("Could not resolve customer because the conversation is null.", error: false, warning: true);
				return null;
			}
			string contactName = conversation.ContactName;
			foreach (Customer item in from knownCustomer in GetKnownCustomers()
				where (Object)(object)knownCustomer != (Object)null && (Object)(object)knownCustomer.NPC != (Object)null
				select knownCustomer)
			{
				if (item.NPC.MSGConversation == conversation || (!string.IsNullOrWhiteSpace(contactName) && (string.Equals(item.NPC.FullName, contactName, StringComparison.OrdinalIgnoreCase) || ((Object)(object)item.customerData != (Object)null && string.Equals(((Object)item.customerData).name, contactName, StringComparison.OrdinalIgnoreCase)))))
				{
					return item;
				}
			}
			Main.Log("Could not resolve customer from conversation: " + contactName, error: false, warning: true);
			return null;
		}

		public static Customer GetCustomerFromMessagesApp(MessagesApp messagesApp)
		{
			if ((Object)(object)messagesApp != (Object)null)
			{
				return GetCustomerFromConversation(messagesApp.currentConversation);
			}
			Main.Log("Could not resolve customer because MessagesApp is null.", error: false, warning: true);
			return null;
		}

		public static float GetProductAppeal(ProductDefinition product, Customer customer, float? overridePrice = null)
		{
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)product == (Object)null || (Object)(object)customer == (Object)null || (Object)(object)customer.customerData == (Object)null || product.MarketValue <= 0f)
			{
				Main.Log("Product appeal calculation skipped because the product or customer data is invalid.", error: false, warning: true);
				return 0f;
			}
			float productEnjoyment = customer.GetProductEnjoyment(product, StandardsMethod.GetCorrespondingQuality(customer.customerData.Standards));
			float num = (overridePrice ?? product.Price) / product.MarketValue;
			float num2 = Mathf.Lerp(1f, -1f, num / 2f);
			return productEnjoyment + num2;
		}

		public static PaymentQuantityResult CalculatePaymentQuantity(ProductDefinition product, Customer customer, float? overridePrice = null)
		{
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: 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_01c4: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)product == (Object)null || (Object)(object)customer == (Object)null || (Object)(object)customer.customerData == (Object)null)
			{
				Main.Log("Payment quantity calculation skipped because the product or customer is invalid.", error: false, warning: true);
				return null;
			}
			CustomerData customerData = customer.customerData;
			EQuality correspondingQuality = StandardsMethod.GetCorrespondingQuality(customerData.Standards);
			float num = overridePrice ?? product.Price;
			if (num <= 0f)
			{
				Main.Log("Payment quantity calculation skipped because the price is not greater than zero.", error: false, warning: true);
				return new PaymentQuantityResult
				{
					Payment = 0f,
					Quantity = 0,
					Quality = correspondingQuality,
					Appeal = 0f
				};
			}
			float productAppeal = GetProductAppeal(product, customer, overridePrice);
			if (productAppeal < 0.05f)
			{
				return new PaymentQuantityResult
				{
					Payment = 0f,
					Quantity = 0,
					Quality = correspondingQuality,
					Appeal = productAppeal
				};
			}
			float productEnjoyment = customer.GetProductEnjoyment(product, correspondingQuality);
			int num2 = 7;
			if ((Object)(object)customer.AssignedDealer == (Object)null)
			{
				List<EDay> list = new List<EDay>();
				customerData.GetOrderDays(customer.CurrentAddiction, customer.NPC.RelationData.RelationDelta / 5f, list);
				num2 = Math.Max(list.Count, 1);
			}
			float num3 = customerData.GetAdjustedWeeklySpend(customer.NPC.RelationData.RelationDelta / 5f) / (float)num2 * Mathf.Lerp(0.66f, 1.5f, productEnjoyment);
			float num4 = num * Mathf.Lerp(0.66f, 1.5f, productEnjoyment);
			int num5 = Mathf.Clamp(Mathf.RoundToInt(num3 / num), 1, 1000);
			if (num5 >= 14)
			{
				num5 = Mathf.RoundToInt((float)(num5 / 5)) * 5;
			}
			float payment = Mathf.RoundToInt(num4 * (float)num5 / 5f) * 5;
			return new PaymentQuantityResult
			{
				Payment = payment,
				Quantity = num5,
				Quality = correspondingQuality,
				Appeal = productAppeal
			};
		}

		public static Customer GetCustomerFromNpc(NPC npc)
		{
			if ((Object)(object)npc == (Object)null)
			{
				Main.Log("Could not resolve customer because the NPC is null.", error: false, warning: true);
				return null;
			}
			using (IEnumerator<Customer> enumerator = (from knownCustomer in GetKnownCustomers()
				where (Object)(object)knownCustomer != (Object)null && (Object)(object)knownCustomer.NPC != (Object)null && (((object)knownCustomer.NPC).Equals((object?)npc) || string.Equals(knownCustomer.NPC.FullName, npc.FullName, StringComparison.OrdinalIgnoreCase))
				select knownCustomer).GetEnumerator())
			{
				if (enumerator.MoveNext())
				{
					return enumerator.Current;
				}
			}
			Main.Log("Could not resolve customer from NPC: " + npc.FullName, error: false, warning: true);
			return null;
		}

		public static IEnumerable<ProductOrders> GetProductsFromCustomer(Customer customer)
		{
			if ((Object)(object)customer == (Object)null)
			{
				Main.Log("Could not get products because the customer is null.", error: false, warning: true);
				return Array.Empty<ProductOrders>();
			}
			List<ProductOrders> list = new List<ProductOrders>();
			foreach (ProductDefinition orderableProduct in customer.GetOrderableProducts((Dealer)null))
			{
				PaymentQuantityResult paymentQuantityResult = CalculatePaymentQuantity(orderableProduct, customer);
				if (paymentQuantityResult != null && paymentQuantityResult.Appeal >= 0.05f)
				{
					list.Add(new ProductOrders
					{
						Product = orderableProduct,
						PaymentQuantity = paymentQuantityResult
					});
				}
			}
			list.Sort((ProductOrders a, ProductOrders b) => b.PaymentQuantity.Appeal.CompareTo(a.PaymentQuantity.Appeal));
			return list.Take(4);
		}

		public static List<Customer> GetKnownCustomers()
		{
			List<Customer> list = new List<Customer>();
			try
			{
				List<Customer> unlockedCustomers = Customer.UnlockedCustomers;
				if (unlockedCustomers != null)
				{
					foreach (Customer item in unlockedCustomers)
					{
						AddCustomer(list, item);
					}
				}
			}
			catch (Exception ex)
			{
				Main.Log("Error enumerating UnlockedCustomers: " + ex.Message, error: false, warning: true);
			}
			try
			{
				Customer[] array = Resources.FindObjectsOfTypeAll<Customer>();
				if (array != null)
				{
					Customer[] array2 = array;
					foreach (Customer customer in array2)
					{
						AddCustomer(list, customer);
					}
				}
			}
			catch (Exception ex2)
			{
				Main.Log("Error enumerating all Customer objects: " + ex2.Message, error: false, warning: true);
			}
			Main.Log("GetKnownCustomers found " + list.Count + " customers (incl. S1API custom NPCs)");
			return list;
		}

		private static void AddCustomer(List<Customer> customers, Customer customer)
		{
			if ((Object)(object)customer == (Object)null)
			{
				return;
			}
			try
			{
				if ((Object)(object)customer.NPC == (Object)null)
				{
					return;
				}
				if ((Object)(object)customer.customerData == (Object)null)
				{
					if (Config.GetCustomNpcMode(customer.NPC) >= S1APINPCHandling.Exclude)
					{
						Main.Log("Skipping custom NPC with missing customerData (Mode 2).");
						return;
					}
					Main.Log("Adding custom NPC with missing customerData: " + (customer.NPC.FullName ?? "unknown"));
				}
				if (!customers.Any((Customer existing) => (Object)(object)existing == (Object)(object)customer || ((Object)(object)existing != (Object)null && (Object)(object)existing.NPC != (Object)null && (Object)(object)customer.NPC != (Object)null && (Object)(object)existing.NPC == (Object)(object)customer.NPC)))
				{
					customers.Add(customer);
				}
			}
			catch (Exception ex)
			{
				Main.Log("Error adding customer: " + ex.Message, error: false, warning: true);
			}
		}
	}
	internal static class DisplayHelper
	{
		public static void UpdateCounterOfferDisplayText(string text, string reasonText)
		{
			UIHandler.UpdateCounterOfferDisplayText(text, reasonText);
		}
	}
	internal static class ImguiCompat
	{
		private static GUIStyle _style;

		internal static void DrawTexture(Rect position, Texture2D image)
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Invalid comparison between Unknown and I4
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Expected O, but got Unknown
			if (!((Object)(object)image == (Object)null) && Event.current != null && (int)Event.current.type == 7)
			{
				if (_style == null)
				{
					_style = new GUIStyle();
				}
				_style.normal.background = image;
				Color backgroundColor = GUI.backgroundColor;
				GUI.backgroundColor = Color.white;
				_style.Draw(position, false, false, false, false);
				GUI.backgroundColor = backgroundColor;
			}
		}
	}
}
namespace HighBaller.Core
{
	public static class DealAutoScheduler
	{
		private static DealWindow ResolveCurrentWindowOption()
		{
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				TimeManager instance = NetworkSingleton<TimeManager>.Instance;
				if ((Object)(object)instance == (Object)null)
				{
					Main.Log("Window 5: TimeManager unavailable, defaulting to Late Night.", error: false, warning: true);
					return DealWindow.LateNight;
				}
				int currentTime = instance.CurrentTime;
				int minSumFrom24HourTime = TimeManager.GetMinSumFrom24HourTime(currentTime);
				int num = 120;
				if (num <= 0)
				{
					num = 60;
				}
				for (int i = 0; i < 4; i++)
				{
					EDealWindow val = (EDealWindow)i;
					DealWindowInfo windowInfo = DealWindowInfo.GetWindowInfo(val);
					int minSumFrom24HourTime2 = TimeManager.GetMinSumFrom24HourTime(windowInfo.StartTime);
					int num2 = TimeManager.GetMinSumFrom24HourTime(windowInfo.EndTime);
					if (num2 <= minSumFrom24HourTime2)
					{
						num2 += 1440;
					}
					int num3 = minSumFrom24HourTime;
					if (num3 < minSumFrom24HourTime2)
					{
						num3 += 1440;
					}
					if (num3 >= minSumFrom24HourTime2 && num3 < num2)
					{
						if (num2 - num3 > num)
						{
							Main.Log($"Window 5: current time {currentTime} -> window {val} (option {i + 1}).");
							return (DealWindow)(i + 1);
						}
						int num4 = (i + 1) % 4;
						Main.Log($"Window 5: current window {val} too close to cutoff (remaining {num2 - num3} mins), falling back to {(object)(EDealWindow)num4} (option {num4 + 1}).");
						return (DealWindow)(num4 + 1);
					}
				}
				Main.Log($"Window 5: current time {currentTime} did not match any window, defaulting to Morning.", error: false, warning: true);
				return DealWindow.Morning;
			}
			catch (Exception ex)
			{
				Main.Log("Window 5 resolution error: " + ex.Message + " - defaulting to Late Night.", error: false, warning: true);
				return DealWindow.LateNight;
			}
		}

		public static void TryAutoScheduleDeal(Customer customer)
		{
			//IL_0129: Unknown result type (might be due to invalid IL or missing references)
			//IL_0133: Unknown result type (might be due to invalid IL or missing references)
			//IL_013d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0147: Unknown result type (might be due to invalid IL or missing references)
			//IL_0174: Unknown result type (might be due to invalid IL or missing references)
			//IL_0180: Expected O, but got Unknown
			//IL_0192: 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)
			if (!Config.AutoContractAcceptedEnabled.Value)
			{
				return;
			}
			if ((Object)(object)customer != (Object)null && Config.GetCustomNpcMode(customer.NPC) >= S1APINPCHandling.NoAutomation)
			{
				object obj;
				if (!((Object)(object)customer.customerData != (Object)null))
				{
					NPC nPC = customer.NPC;
					obj = (((Object)(object)nPC != (Object)null) ? nPC.FullName : null) ?? "unknown";
				}
				else
				{
					obj = ((Object)customer.customerData).name;
				}
				Main.Log("Auto scheduling skipped for custom NPC: " + (string)obj);
				return;
			}
			if ((Object)(object)customer == (Object)null || customer.OfferedContractInfo == null)
			{
				Main.Log("Auto scheduling skipped because the customer or offered contract is null.", error: false, warning: true);
				return;
			}
			Main.Log("Auto scheduling for " + (((Object)(object)customer.customerData != (Object)null) ? ((Object)customer.customerData).name : "unknown"));
			DealWindow dealWindow = Config.AutoContractAcceptedWindow.Value;
			if ((Object)(object)customer.NPC == (Object)null || customer.NPC.MSGConversation == null)
			{
				Main.Log("Auto scheduling skipped because NPC or conversation is null.", error: false, warning: true);
				return;
			}
			if (dealWindow == DealWindow.Current)
			{
				dealWindow = ResolveCurrentWindowOption();
			}
			EDealWindow window;
			string text;
			switch (dealWindow)
			{
			case DealWindow.Morning:
				window = (EDealWindow)0;
				text = "Morning";
				break;
			case DealWindow.Afternoon:
				window = (EDealWindow)1;
				text = "Afternoon";
				break;
			case DealWindow.Night:
				window = (EDealWindow)2;
				text = "Night";
				break;
			case DealWindow.LateNight:
				window = (EDealWindow)3;
				text = "Late Night";
				break;
			default:
				window = (EDealWindow)3;
				text = "Late Night";
				Main.Log("AutoContractAcceptedWindow is not correctly set!\nDefaulting to Late Night \nCorrect Values: DealWindow.Morning, DealWindow.Afternoon, DealWindow.Night, DealWindow.LateNight, DealWindow.Current", error: false, warning: true);
				break;
			}
			customer.NPC.MSGConversation.SendMessage(new Message(text, (ESenderType)0, true, -1), true, true);
			customer.NPC.MSGConversation.ClearResponses(true);
			new DelayedScheduler(customer, window).Start();
		}
	}
	public static class DealCalculator
	{
		public static float CalculateSuccessProbability(Customer customer, ProductDefinition product, int quantity, float price, InitialOfferData initialOfferData)
		{
			if ((Object)(object)customer == (Object)null || (Object)(object)product == (Object)null || initialOfferData == null || quantity <= 0 || initialOfferData.Quantity <= 0)
			{
				Main.Log("Success probability calculation skipped because the input data is invalid.", error: false, warning: true);
				return 0f;
			}
			if ((Object)(object)customer.CustomerData == (Object)null)
			{
				Main.Log("Success probability calculation skipped because customerData is null.", error: false, warning: true);
				return 0f;
			}
			ProductDefinition item = Registry.GetItem<ProductDefinition>(initialOfferData.ProductId);
			if ((Object)(object)item == (Object)null)
			{
				Main.Log("Success probability calculation skipped because the initial product could not be resolved.", error: false, warning: true);
				return 0f;
			}
			float valueProposition = Customer.GetValueProposition(item, initialOfferData.Payment / (float)initialOfferData.Quantity);
			float productEnjoyment = customer.GetProductEnjoyment(product);
			float num = Mathf.InverseLerp(-1f, 1f, productEnjoyment);
			float valueProposition2 = Customer.GetValueProposition(product, price / (float)quantity);
			float num2 = Mathf.Lerp(1f, 0f, Mathf.Abs(Mathf.Lerp(0f, 2f, Mathf.Pow((float)quantity / (float)initialOfferData.Quantity, 0.6f) * 0.5f) - 1f));
			if (valueProposition2 * num2 > valueProposition)
			{
				return 1f;
			}
			if (valueProposition2 < 0.12f)
			{
				return 0f;
			}
			float num3 = productEnjoyment * valueProposition;
			float num4 = num * num2 * valueProposition2;
			if (!(num4 > num3))
			{
				return Mathf.Clamp01((0.9f - (Mathf.Lerp(0f, 1f, (num3 - num4) / 0.2f) - Mathf.Lerp(0f, 0.2f, Mathf.Max(customer.CurrentAddiction, customer.NPC.RelationData.NormalizedRelationDelta)))) / 0.9f);
			}
			return 1f;
		}

		public static (float maxSpend, float avgDailySpend) CalculateSpendingLimits(Customer customer)
		{
			if ((Object)(object)customer == (Object)null)
			{
				Main.Log("Spending limit calculation skipped because the customer is null.", error: false, warning: true);
				return (maxSpend: 0f, avgDailySpend: 0f);
			}
			CustomerData customerData = customer.CustomerData;
			if ((Object)(object)customerData == (Object)null)
			{
				Main.Log("Spending limit calculation skipped because customerData is null.", error: false, warning: true);
				return (maxSpend: 0f, avgDailySpend: 0f);
			}
			List<EDay> list = new List<EDay>();
			customerData.GetOrderDays(customer.CurrentAddiction, customer.NPC.RelationData.RelationDelta / 5f, list);
			int num = Math.Max(list.Count, 1);
			float num2 = customerData.GetAdjustedWeeklySpend(customer.NPC.RelationData.RelationDelta / 5f) / (float)num;
			return (maxSpend: num2 * 3f, avgDailySpend: num2);
		}

		public static int FindOptimalPrice(Customer customer, ProductDefinition product, int quantity, float currentPrice, float maxSpend, float minSuccessProbability = -1f, InitialOfferData initialOfferData = null, bool log = false)
		{
			if ((Object)(object)customer == (Object)null || (Object)(object)product == (Object)null || quantity <= 0)
			{
				Main.Log("Optimal price calculation skipped because customer/product/quantity input is invalid.", error: false, warning: true);
				return Math.Max(1, (int)currentPrice);
			}
			if (maxSpend <= 0f)
			{
				Main.Log("Optimal price calculation skipped because maxSpend is invalid.", error: false, warning: true);
				return Math.Max(1, (int)currentPrice);
			}
			if ((double)minSuccessProbability < 0.0)
			{
				minSuccessProbability = Config.MinSuccessProbability.Value;
			}
			int num = (int)Math.Floor(maxSpend - 0.01f);
			int num2 = Math.Min((int)currentPrice, num);
			int num3 = (int)currentPrice;
			if (initialOfferData == null)
			{
				ContractInfo offeredContractInfo = customer.OfferedContractInfo;
				if (offeredContractInfo != null)
				{
					ProductList products = offeredContractInfo.Products;
					if (products != null)
					{
						List<Entry> entries = products.entries;
						if (entries != null && entries.Count > 0 && offeredContractInfo.Products.entries[0].Quantity > 0)
						{
							initialOfferData = new InitialOfferData
							{
								ProductId = offeredContractInfo.Products.entries[0].ProductID,
								Quantity = offeredContractInfo.Products.entries[0].Quantity,
								Payment = offeredContractInfo.Payment
							};
							goto IL_015c;
						}
					}
				}
				initialOfferData = new InitialOfferData
				{
					ProductId = ((BaseItemDefinition)product).ID,
					Quantity = Math.Max(quantity, 1),
					Payment = Math.Max(currentPrice, 1f)
				};
				Main.Log("Optimal price calculation is using fallback initial offer data because offered contract data is unavailable.", error: false, warning: true);
			}
			goto IL_015c;
			IL_015c:
			if (log)
			{
				Main.Log($"Initial Offer Data: ProductId: {initialOfferData.ProductId}, Quantity: {initialOfferData.Quantity}, Payment: {initialOfferData.Payment}");
				Main.Log($"Binary Search Start - Product: {((BaseItemDefinition)product).ID}, Price: {currentPrice}, MaxSpend: {maxSpend}, Quantity: {quantity}, MinProbability: {minSuccessProbability}, Low: {num2}, High: {num}");
			}
			for (int i = 0; i < 20; i++)
			{
				if (num2 >= num)
				{
					break;
				}
				int num4 = (num2 + num) / 2;
				if (CalculateSuccessProbability(customer, product, quantity, num4, initialOfferData) >= minSuccessProbability)
				{
					num2 = num4 + 1;
					if (num2 == num)
					{
						num3 = ((CalculateSuccessProbability(customer, product, quantity, num4 + 1, initialOfferData) > minSuccessProbability) ? (num4 + 1) : num4);
						break;
					}
					num3 = num4;
				}
				else
				{
					num = num4;
				}
			}
			if (!log)
			{
				return num3;
			}
			Main.Log("Binary Search Complete:");
			Main.Log($"  Final bestFailingPrice: {num3}");
			Main.Log($"  Final Probability: {CalculateSuccessProbability(customer, product, quantity, num3, initialOfferData)}");
			return num3;
		}

		public static (int quantity, int price) FindOptimalQuantity(Customer customer, ProductDefinition product, int initialQuantity, float initialPrice, InitialOfferData initialOfferData = null)
		{
			if ((Object)(object)customer == (Object)null || (Object)(object)product == (Object)null || initialQuantity <= 0)
			{
				Main.Log("Optimal quantity calculation skipped because customer/product/quantity input is invalid.", error: false, warning: true);
				return (quantity: Math.Max(initialQuantity, 1), price: Math.Max((int)initialPrice, 1));
			}
			float item = CalculateSpendingLimits(customer).maxSpend;
			(int, int) result;
			if (!Config.IncreaseQuantityEnabled.Value)
			{
				int item2 = FindOptimalPrice(customer, product, initialQuantity, initialPrice, item, -1f, initialOfferData);
				result = (initialQuantity, item2);
			}
			else
			{
				int num = FindOptimalPrice(customer, product, initialQuantity, initialPrice, item, -1f, initialOfferData);
				int item3 = initialQuantity;
				int num2 = num;
				if (!((double)num2 >= Math.Floor(item * 0.99f)))
				{
					int num3 = initialQuantity;
					for (int i = 0; i < 20; i++)
					{
						num3++;
						int num4 = FindOptimalPrice(customer, product, num3, initialPrice, item, -1f, initialOfferData);
						if (num4 <= num2)
						{
							break;
						}
						item3 = num3;
						num2 = num4;
						if ((double)num2 >= Math.Floor(item * 0.99f))
						{
							break;
						}
					}
				}
				result = (item3, num2);
			}
			if (Config.RoundQuantityToNearest5.Value)
			{
				result = RoundQuantityToFive(customer, product, result, item, initialOfferData);
			}
			return result;
		}

		private static (int quantity, int price) RoundQuantityToFive(Customer customer, ProductDefinition product, (int quantity, int price) result, float maxSpend, InitialOfferData initialOfferData)
		{
			int num = Math.Max(5, (int)Math.Round((double)result.quantity / 5.0, MidpointRounding.AwayFromZero) * 5);
			if (num == result.quantity)
			{
				return result;
			}
			if (initialOfferData == null)
			{
				ContractInfo offeredContractInfo = customer.OfferedContractInfo;
				if (offeredContractInfo != null)
				{
					ProductList products = offeredContractInfo.Products;
					if (products != null)
					{
						List<Entry> entries = products.entries;
						if (entries != null && entries.Count > 0 && offeredContractInfo.Products.entries[0].Quantity > 0)
						{
							initialOfferData = new InitialOfferData
							{
								ProductId = offeredContractInfo.Products.entries[0].ProductID,
								Quantity = offeredContractInfo.Products.entries[0].Quantity,
								Payment = offeredContractInfo.Payment
							};
						}
					}
				}
			}
			if (initialOfferData == null)
			{
				Main.Log("Quantity rounding skipped because the original offer is unavailable.", error: false, warning: true);
				return result;
			}
			int num2 = FindOptimalPrice(customer, product, num, 1f, maxSpend, -1f, initialOfferData);
			float num3 = CalculateSuccessProbability(customer, product, num, num2, initialOfferData);
			if (num2 <= 1 || num3 < Config.MinSuccessProbability.Value)
			{
				Main.Log($"Quantity rounding {result.quantity} -> {num} rejected (price {num2}, probability {num3:F3}); keeping {result.quantity}");
				return result;
			}
			Main.Log($"Quantity rounded {result.quantity} -> {num}, price {result.price} -> {num2} (probability {num3:F3})");
			return (quantity: num, price: num2);
		}
	}
	public static class OfferEvaluator
	{
		public static OfferData GetOfferData()
		{
			MessagesApp instance = PlayerSingleton<MessagesApp>.Instance;
			if ((Object)(object)instance == (Object)null || instance.currentConversation == null || (Object)(object)instance.CounterofferInterface == (Object)null || (Object)(object)instance.CounterofferInterface.ProductLabel == (Object)null || (Object)(object)instance.CounterofferInterface.PriceSelector == (Object)null)
			{
				Main.Log("Counter-offer data could not be read because the UI state is incomplete.", error: false, warning: true);
				return null;
			}
			Customer customerFromMessagesApp = CustomerHelper.GetCustomerFromMessagesApp(instance);
			if ((Object)(object)customerFromMessagesApp == (Object)null || customerFromMessagesApp.OfferedContractInfo?.Products?.entries == null || customerFromMessagesApp.OfferedContractInfo.Products.entries.Count == 0)
			{
				Main.Log("Counter-offer data could not be read because the customer contract state is incomplete.", error: false, warning: true);
				return null;
			}
			Entry val = customerFromMessagesApp.OfferedContractInfo.Products.entries[0];
			ProductDefinition item = Registry.GetItem<ProductDefinition>(val.ProductID);
			if ((Object)(object)item == (Object)null)
			{
				Main.Log("Counter-offer data could not be read because the offered product could not be resolved.", error: false, warning: true);
				return null;
			}
			string[] array = (instance.CounterofferInterface.ProductLabel.text ?? string.Empty).Split(new char[1] { 'x' }, StringSplitOptions.RemoveEmptyEntries);
			if (array.Length == 0 || !int.TryParse(array[0].Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out var result) || result <= 0)
			{
				result = val.Quantity;
			}
			if (result <= 0)
			{
				Main.Log("Counter-offer data could not be read because the quantity is invalid.", error: false, warning: true);
				return null;
			}
			string text = instance.CounterofferInterface.PriceSelector.SelectedAmount.ToString(CultureInfo.InvariantCulture);
			float result2 = 0f;
			if (string.IsNullOrWhiteSpace(text) || float.TryParse(text, NumberStyles.Float, CultureInfo.CurrentCulture, out result2) || float.TryParse(text, NumberStyles.Float, CultureInfo.InvariantCulture, out result2))
			{
				return new OfferData(customerFromMessagesApp, item, result, result2);
			}
			Main.Log("Counter-offer data could not be read because the entered price is invalid.", error: false, warning: true);
			return null;
		}

		public static void OfferPriceChangeCheckNoLog()
		{
			OfferData offerData = GetOfferData();
			if (offerData != null)
			{
				EvaluateCounterOffer(offerData);
			}
		}

		public static void OfferPriceChangeCheckWithLog()
		{
			OfferData offerData = GetOfferData();
			if (offerData != null)
			{
				string message = $"\nCustomer Name: {((Object)offerData.Customer).name}\nProduct: {((BaseItemDefinition)offerData.Product).ID}\nQuantity: {offerData.Quantity}\nPrice: {offerData.Price}\n";
				EvaluateCounterOffer(offerData, log: true);
				Main.Log(message);
			}
		}

		private static void EvaluateCounterOffer(OfferData offerData, bool log = false)
		{
			if (offerData == null || (Object)(object)offerData.Customer == (Object)null || (Object)(object)offerData.Product == (Object)null || offerData.Quantity <= 0)
			{
				Main.Log(log ? "Detailed counter-offer evaluation skipped because the offer data is incomplete." : "Counter-offer evaluation skipped because the offer data is incomplete.", error: false, warning: true);
				return;
			}
			(float maxSpend, float avgDailySpend) tuple = DealCalculator.CalculateSpendingLimits(offerData.Customer);
			float item = tuple.maxSpend;
			float item2 = tuple.avgDailySpend;
			decimal num = Math.Round((decimal)item, 2);
			string text = "";
			if (log)
			{
				float adjustedWeeklySpend = offerData.Customer.CustomerData.GetAdjustedWeeklySpend(offerData.Customer.NPC.RelationData.RelationDelta / 5f);
				List<EDay> list = new List<EDay>();
				offerData.Customer.CustomerData.GetOrderDays(offerData.Customer.CurrentAddiction, offerData.Customer.NPC.RelationData.RelationDelta / 5f, list);
				text = $"\nAdjusted Weekly Spend: {adjustedWeeklySpend}\n" + $"Order Days: {list.Count}\n" + $"Average Daily Spend: {item2}\n" + $"Daily Spend Threshold (3x Avg): {num}\n" + $"Min Weekly Spend: {offerData.Customer.CustomerData.MinWeeklySpend}\n" + $"Max Weekly Spend: {offerData.Customer.CustomerData.MaxWeeklySpend}\n";
				bool flag = (Object)(object)offerData.Customer.AssignedDealer == (Object)null;
				string text2 = "";
				foreach (ProductDefinition orderableProduct in offerData.Customer.GetOrderableProducts(flag ? null : offerData.Customer.AssignedDealer))
				{
					text2 += $"[Name: {((BaseItemDefinition)orderableProduct).Name}, Price: {orderableProduct.Price}, Market: {orderableProduct.MarketValue}],\n";
				}
				text = text + "Orderable Products: " + text2 + "\n";
			}
			if (offerData.Price >= item)
			{
				DisplayHelper.UpdateCounterOfferDisplayText("Guaranteed Failure", $"Exceeded Max Spend ({num})");
				return;
			}
			ProductDefinition product = offerData.Product;
			if (!log)
			{
				MessagesApp instance = PlayerSingleton<MessagesApp>.Instance;
				if ((Object)(object)instance != (Object)null && (Object)(object)instance.CounterofferInterface != (Object)null && (Object)(object)instance.CounterofferInterface.selectedProduct != (Object)null)
				{
					product = instance.CounterofferInterface.selectedProduct;
				}
			}
			InitialOfferData initialOfferData = new InitialOfferData
			{
				ProductId = offerData.Customer.OfferedContractInfo.Products.entries[0].ProductID,
				Quantity = offerData.Customer.OfferedContractInfo.Products.entries[0].Quantity,
				Payment = offerData.Customer.OfferedContractInfo.Payment
			};
			decimal num2 = Math.Round((decimal)(DealCalculator.CalculateSuccessProbability(offerData.Customer, product, offerData.Quantity, offerData.Price, initialOfferData) * 100f), 3);
			if (log)
			{
				text += $"\nProbability of success: {num2}\n";
				DisplayHelper.UpdateCounterOfferDisplayText($"Probability of success: {num2}", "");
				Main.Log(text);
			}
			else
			{
				DisplayHelper.UpdateCounterOfferDisplayText($"Probability of success: {num2}%", $"Price per unit: {offerData.Price / (float)offerData.Quantit