Decompiled source of TraderOverhaul v0.0.9

TraderOverhaul.dll

Decompiled 2 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Text;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Newtonsoft.Json;
using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.Rendering;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("Trader Overhaul")]
[assembly: AssemblyDescription("Unified trader overhaul for Haldor, Hildir, and Bog Witch")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("TraderOverhaul")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("b7e4f347-ccbb-4fa9-9a20-b39679b6d0f7")]
[assembly: AssemblyFileVersion("0.0.9.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyVersion("0.0.9.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace TraderOverhaul
{
	public static class ConfigLoader
	{
		private static readonly string BuyFile = Path.Combine(Paths.ConfigPath, "TraderOverhaul.buy.json");

		private static readonly string SellFile = Path.Combine(Paths.ConfigPath, "TraderOverhaul.sell.json");

		private static readonly List<TradeEntry> EmptyEntries = new List<TradeEntry>();

		private static List<TradeEntry> BuyEntries = new List<TradeEntry>();

		private static List<TradeEntry> SellEntries = new List<TradeEntry>();

		public static void Initialize()
		{
			EnsureConfigFilesExist();
			LoadAllConfigs();
			ValidateAndLogStats();
		}

		internal static IReadOnlyList<TradeEntry> GetBuyEntries()
		{
			return BuyEntries ?? EmptyEntries;
		}

		internal static IReadOnlyList<TradeEntry> GetSellEntries()
		{
			return SellEntries ?? EmptyEntries;
		}

		private static void EnsureConfigFilesExist()
		{
			EnsureBuyConfigFile();
			EnsureSellConfigFile();
		}

		private static void EnsureBuyConfigFile()
		{
			if (!File.Exists(BuyFile))
			{
				File.WriteAllText(BuyFile, DefaultBuyJson());
				TraderOverhaulPlugin.Log.LogInfo((object)"[ConfigLoader] Created default buy config.");
			}
		}

		private static void EnsureSellConfigFile()
		{
			if (!File.Exists(SellFile))
			{
				File.WriteAllText(SellFile, DefaultSellJson());
				TraderOverhaulPlugin.Log.LogInfo((object)"[ConfigLoader] Created default sell config.");
			}
		}

		private static void LoadAllConfigs()
		{
			BuyEntries = LoadEntries(BuyFile, "BUY");
			SellEntries = LoadEntries(SellFile, "SELL");
		}

		private static List<TradeEntry> LoadEntries(string path, string label)
		{
			try
			{
				List<TradeEntry> list = JsonConvert.DeserializeObject<List<TradeEntry>>(File.ReadAllText(path)) ?? new List<TradeEntry>();
				TraderOverhaulPlugin.Log.LogInfo((object)$"[ConfigLoader] Loaded {list.Count} {label} entries.");
				return list;
			}
			catch (Exception arg)
			{
				TraderOverhaulPlugin.Log.LogError((object)$"[ConfigLoader] Error loading {label} config: {arg}");
				return new List<TradeEntry>();
			}
		}

		private static void ValidateAndLogStats()
		{
			BuyEntries = ValidateEntries(BuyEntries, "BUY");
			SellEntries = ValidateEntries(SellEntries, "SELL");
		}

		private static List<TradeEntry> ValidateEntries(List<TradeEntry> entries, string type)
		{
			int num = 0;
			int num2 = 0;
			entries = entries ?? new List<TradeEntry>();
			foreach (TradeEntry item in entries.ToList())
			{
				if (!ValidateEntry(item, type))
				{
					entries.Remove(item);
					num2++;
				}
				else
				{
					num++;
				}
			}
			if (num2 > 0)
			{
				TraderOverhaulPlugin.Log.LogWarning((object)$"[ConfigLoader] Removed {num2} invalid {type} entries.");
			}
			TraderOverhaulPlugin.Log.LogInfo((object)$"[ConfigLoader] {type}: {num} valid entries.");
			return entries;
		}

		private static bool ValidateEntry(TradeEntry entry, string type)
		{
			if (entry == null)
			{
				TraderOverhaulPlugin.Log.LogWarning((object)("[ConfigLoader] " + type + " entry is null, skipping."));
				return false;
			}
			if (string.IsNullOrWhiteSpace(entry.prefab))
			{
				TraderOverhaulPlugin.Log.LogWarning((object)("[ConfigLoader] " + type + " entry has empty prefab name, skipping."));
				return false;
			}
			if (entry.price <= 0)
			{
				TraderOverhaulPlugin.Log.LogWarning((object)$"[ConfigLoader] {type} entry '{entry.prefab}' has invalid price ({entry.price}), setting to 1.");
				entry.price = 1;
			}
			if (entry.stack <= 0)
			{
				TraderOverhaulPlugin.Log.LogWarning((object)$"[ConfigLoader] {type} entry '{entry.prefab}' has invalid stack ({entry.stack}), setting to 1.");
				entry.stack = 1;
			}
			return true;
		}

		private static string DefaultBuyJson()
		{
			return JsonConvert.SerializeObject((object)new List<TradeEntry>
			{
				new TradeEntry
				{
					prefab = "Wood",
					stack = 50,
					price = 25,
					requiredGlobalKey = "defeated_eikthyr"
				}
			}, (Formatting)1);
		}

		private static string DefaultSellJson()
		{
			return JsonConvert.SerializeObject((object)new List<TradeEntry>
			{
				new TradeEntry
				{
					prefab = "Wood",
					stack = 1,
					price = 1
				}
			}, (Formatting)1);
		}
	}
	public class TradeEntry
	{
		[JsonProperty("item_prefab")]
		public string prefab = "";

		[JsonProperty("item_quantity")]
		public int stack = 1;

		[JsonProperty("item_price")]
		public int price = 1;

		[JsonProperty("must_defeated_boss")]
		public string requiredGlobalKey = "";

		[JsonProperty("rarity")]
		public string rarity = "";
	}
	internal static class BankBalanceStore
	{
		private const string SharedKey = "TraderSharedBank_Balance";

		private const string LegacyHaldorKey = "HaldorBank_Balance";

		private const string LegacyHildirKey = "HildirBank_Balance";

		private const string LegacyBogWitchKey = "BogWitchBank_Balance";

		internal static int Read(Player player)
		{
			if ((Object)(object)player == (Object)null)
			{
				return 0;
			}
			if (TryRead(player, "TraderSharedBank_Balance", out var value))
			{
				return value;
			}
			int value2;
			bool num = TryRead(player, "HaldorBank_Balance", out value2);
			int value3;
			bool flag = TryRead(player, "HildirBank_Balance", out value3);
			int value4;
			bool flag2 = TryRead(player, "BogWitchBank_Balance", out value4);
			int num2 = 0;
			if (num)
			{
				num2 = Mathf.Max(num2, value2);
			}
			if (flag)
			{
				num2 = Mathf.Max(num2, value3);
			}
			if (flag2)
			{
				num2 = Mathf.Max(num2, value4);
			}
			Write(player, num2);
			return num2;
		}

		internal static void Write(Player player, int value)
		{
			if (!((Object)(object)player == (Object)null))
			{
				value = Mathf.Max(0, value);
				string value2 = value.ToString();
				player.m_customData["TraderSharedBank_Balance"] = value2;
				player.m_customData["HaldorBank_Balance"] = value2;
				player.m_customData["HildirBank_Balance"] = value2;
				player.m_customData["BogWitchBank_Balance"] = value2;
			}
		}

		private static bool TryRead(Player player, string key, out int value)
		{
			value = 0;
			if (player.m_customData.TryGetValue(key, out var value2))
			{
				return int.TryParse(value2, out value);
			}
			return false;
		}
	}
	internal static class EpicLootIntegration
	{
		private static bool _initialized;

		private static bool _available;

		private static Type _itemRarityEnum;

		private static MethodInfo _rollMagicItem;

		private static MethodInfo _canBeMagicItem;

		private static MethodInfo _saveMagicItem;

		internal static bool IsAvailable
		{
			get
			{
				if (!_initialized)
				{
					Initialize();
				}
				return _available;
			}
		}

		private static void Initialize()
		{
			_initialized = true;
			_available = false;
			try
			{
				Assembly assembly = null;
				Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
				foreach (Assembly assembly2 in assemblies)
				{
					if (assembly2.GetName().Name == "EpicLoot")
					{
						assembly = assembly2;
						break;
					}
				}
				if (assembly == null)
				{
					TraderOverhaulPlugin.Log.LogInfo((object)"[EpicLootIntegration] Epic Loot not found — rarity enchantments disabled.");
					return;
				}
				_itemRarityEnum = assembly.GetType("EpicLoot.ItemRarity");
				if (_itemRarityEnum == null)
				{
					TraderOverhaulPlugin.Log.LogWarning((object)"[EpicLootIntegration] Could not find ItemRarity enum.");
					return;
				}
				Type type = assembly.GetType("EpicLoot.MagicItem");
				if (type == null)
				{
					TraderOverhaulPlugin.Log.LogWarning((object)"[EpicLootIntegration] Could not find MagicItem type.");
					return;
				}
				Type type2 = assembly.GetType("EpicLoot.LootRoller");
				if (type2 == null)
				{
					TraderOverhaulPlugin.Log.LogWarning((object)"[EpicLootIntegration] Could not find LootRoller type.");
					return;
				}
				_rollMagicItem = type2.GetMethod("RollMagicItem", BindingFlags.Static | BindingFlags.Public, null, new Type[4]
				{
					_itemRarityEnum,
					typeof(ItemData),
					typeof(float),
					typeof(float)
				}, null);
				if (_rollMagicItem == null)
				{
					TraderOverhaulPlugin.Log.LogWarning((object)"[EpicLootIntegration] Could not find RollMagicItem method.");
					return;
				}
				Type type3 = assembly.GetType("EpicLoot.ItemDataExtensions");
				if (type3 == null)
				{
					TraderOverhaulPlugin.Log.LogWarning((object)"[EpicLootIntegration] Could not find ItemDataExtensions type.");
					return;
				}
				_saveMagicItem = type3.GetMethod("SaveMagicItem", BindingFlags.Static | BindingFlags.Public, null, new Type[2]
				{
					typeof(ItemData),
					type
				}, null);
				if (_saveMagicItem == null)
				{
					TraderOverhaulPlugin.Log.LogWarning((object)"[EpicLootIntegration] Could not find SaveMagicItem method.");
					return;
				}
				Type type4 = assembly.GetType("EpicLoot.EpicLoot");
				if (type4 != null)
				{
					_canBeMagicItem = type4.GetMethod("CanBeMagicItem", BindingFlags.Static | BindingFlags.Public, null, new Type[1] { typeof(ItemData) }, null);
				}
				_available = true;
				TraderOverhaulPlugin.Log.LogInfo((object)"[EpicLootIntegration] Epic Loot detected — rarity enchantments enabled.");
			}
			catch (Exception ex)
			{
				TraderOverhaulPlugin.Log.LogWarning((object)("[EpicLootIntegration] Failed to initialize: " + ex.Message));
			}
		}

		internal static bool ApplyRarity(ItemData item, string rarity)
		{
			if (item == null || string.IsNullOrEmpty(rarity))
			{
				return false;
			}
			if (!IsAvailable)
			{
				return false;
			}
			try
			{
				object obj;
				try
				{
					obj = Enum.Parse(_itemRarityEnum, rarity, ignoreCase: true);
				}
				catch
				{
					TraderOverhaulPlugin.Log.LogWarning((object)("[EpicLootIntegration] Unknown rarity: " + rarity));
					return false;
				}
				if (_canBeMagicItem != null && !(bool)_canBeMagicItem.Invoke(null, new object[1] { item }))
				{
					TraderOverhaulPlugin.Log.LogInfo((object)("[EpicLootIntegration] " + item.m_shared?.m_name + " cannot be made magic."));
					return false;
				}
				object obj3 = _rollMagicItem.Invoke(null, new object[4] { obj, item, 0f, 1f });
				if (obj3 == null)
				{
					TraderOverhaulPlugin.Log.LogWarning((object)("[EpicLootIntegration] RollMagicItem returned null for " + item.m_shared?.m_name));
					return false;
				}
				_saveMagicItem.Invoke(null, new object[2] { item, obj3 });
				TraderOverhaulPlugin.Log.LogInfo((object)("[EpicLootIntegration] Applied " + rarity + " to " + item.m_shared?.m_name));
				return true;
			}
			catch (TargetInvocationException ex)
			{
				TraderOverhaulPlugin.Log.LogWarning((object)("[EpicLootIntegration] Epic Loot API threw: " + (ex.InnerException?.Message ?? ex.Message)));
				return false;
			}
			catch (Exception ex2)
			{
				TraderOverhaulPlugin.Log.LogWarning((object)("[EpicLootIntegration] Failed to apply rarity: " + ex2.Message));
				return false;
			}
		}
	}
	[HarmonyPatch]
	public static class ModLocalization
	{
		private static readonly FieldInfo TranslationsField = AccessTools.Field(typeof(Localization), "m_translations");

		private static Dictionary<string, string> _englishDefaults;

		private static string _translationsDir;

		private static bool _initialized;

		private static readonly Regex EntryRegex = new Regex("\"key\"\\s*:\\s*\"((?:[^\"\\\\]|\\\\.)*)\"[^\"]*\"value\"\\s*:\\s*\"((?:[^\"\\\\]|\\\\.)*)\"", RegexOptions.Compiled);

		private static readonly Regex UnicodeEscapeRegex = new Regex("\\\\u([0-9a-fA-F]{4})", RegexOptions.Compiled);

		private static readonly FieldInfo InstanceField = AccessTools.Field(typeof(Localization), "m_instance");

		public static string Loc(string key)
		{
			if (Localization.instance == null)
			{
				return key;
			}
			return Localization.instance.Localize("$" + key);
		}

		public static string LocFmt(string key, params object[] args)
		{
			string text = Loc(key);
			try
			{
				return string.Format(text, args);
			}
			catch
			{
				return text;
			}
		}

		public static void Init()
		{
			_translationsDir = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Translations");
			BuildEnglishDefaults();
			_initialized = true;
			object? obj = InstanceField?.GetValue(null);
			Localization val = (Localization)((obj is Localization) ? obj : null);
			if (val != null)
			{
				TraderOverhaulPlugin.Log.LogInfo((object)"[Localization] Localization already initialized — injecting retroactively");
				InjectTranslations(val);
			}
		}

		public static void EnsureDefaultFile()
		{
			if (_englishDefaults == null)
			{
				return;
			}
			try
			{
				if (!Directory.Exists(_translationsDir))
				{
					Directory.CreateDirectory(_translationsDir);
				}
				string text = Path.Combine(_translationsDir, "English.json");
				if (File.Exists(text))
				{
					Dictionary<string, string> dictionary = ParseTranslationJson(File.ReadAllText(text));
					if (dictionary != null && dictionary.Count >= _englishDefaults.Count)
					{
						return;
					}
				}
				List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>(_englishDefaults);
				list.Sort((KeyValuePair<string, string> a, KeyValuePair<string, string> b) => string.Compare(a.Key, b.Key, StringComparison.Ordinal));
				StringBuilder stringBuilder = new StringBuilder();
				stringBuilder.AppendLine("{");
				stringBuilder.AppendLine("    \"entries\": [");
				for (int i = 0; i < list.Count; i++)
				{
					string text2 = ((i < list.Count - 1) ? "," : "");
					stringBuilder.AppendLine("        { \"key\": \"" + EscapeJson(list[i].Key) + "\", \"value\": \"" + EscapeJson(list[i].Value) + "\" }" + text2);
				}
				stringBuilder.AppendLine("    ]");
				stringBuilder.AppendLine("}");
				File.WriteAllText(text, stringBuilder.ToString(), Encoding.UTF8);
				TraderOverhaulPlugin.Log.LogInfo((object)("[Localization] Created default " + text));
			}
			catch (Exception ex)
			{
				TraderOverhaulPlugin.Log.LogWarning((object)("[Localization] Failed to write English.json: " + ex.Message));
			}
		}

		[HarmonyPatch(typeof(Localization), "SetupLanguage")]
		[HarmonyPostfix]
		private static void SetupLanguage_Postfix(Localization __instance)
		{
			if (_initialized)
			{
				InjectTranslations(__instance);
			}
		}

		private static void InjectTranslations(Localization loc)
		{
			if (loc == null)
			{
				return;
			}
			string selectedLanguage = loc.GetSelectedLanguage();
			if (!(TranslationsField?.GetValue(loc) is Dictionary<string, string> dictionary))
			{
				return;
			}
			if (_englishDefaults != null)
			{
				foreach (KeyValuePair<string, string> englishDefault in _englishDefaults)
				{
					dictionary[englishDefault.Key] = englishDefault.Value;
				}
			}
			Dictionary<string, string> dictionary2 = LoadTranslationFile((selectedLanguage != "English") ? selectedLanguage : null);
			if (dictionary2 == null && selectedLanguage != "English")
			{
				dictionary2 = LoadTranslationFile("English");
			}
			int num = 0;
			if (dictionary2 != null)
			{
				foreach (KeyValuePair<string, string> item in dictionary2)
				{
					dictionary[item.Key] = item.Value;
					num++;
				}
			}
			TraderOverhaulPlugin.Log.LogInfo((object)$"[Localization] Injected {_englishDefaults?.Count ?? 0} defaults + {num} \"{selectedLanguage}\" overrides");
		}

		private static Dictionary<string, string> LoadTranslationFile(string language)
		{
			if (string.IsNullOrEmpty(language) || string.IsNullOrEmpty(_translationsDir))
			{
				return null;
			}
			string text = Path.Combine(_translationsDir, language + ".json");
			if (!File.Exists(text))
			{
				return null;
			}
			try
			{
				Dictionary<string, string> dictionary = ParseTranslationJson(File.ReadAllText(text));
				if (dictionary == null || dictionary.Count == 0)
				{
					return null;
				}
				return dictionary;
			}
			catch (Exception ex)
			{
				TraderOverhaulPlugin.Log.LogWarning((object)("[Localization] Failed to load " + text + ": " + ex.Message));
				return null;
			}
		}

		private static Dictionary<string, string> ParseTranslationJson(string json)
		{
			if (string.IsNullOrEmpty(json))
			{
				return null;
			}
			try
			{
				Dictionary<string, string> dictionary = new Dictionary<string, string>();
				foreach (Match item in EntryRegex.Matches(json))
				{
					string text = UnescapeJson(item.Groups[1].Value);
					string text2 = UnescapeJson(item.Groups[2].Value);
					if (!string.IsNullOrEmpty(text) && text2 != null)
					{
						dictionary[text] = text2;
					}
				}
				return (dictionary.Count > 0) ? dictionary : null;
			}
			catch
			{
				return null;
			}
		}

		private static string UnescapeJson(string s)
		{
			if (string.IsNullOrEmpty(s))
			{
				return "";
			}
			s = UnicodeEscapeRegex.Replace(s, (Match m) => ((char)Convert.ToInt32(m.Groups[1].Value, 16)).ToString());
			return s.Replace("\\n", "\n").Replace("\\r", "\r").Replace("\\t", "\t")
				.Replace("\\\"", "\"")
				.Replace("\\\\", "\\");
		}

		private static string EscapeJson(string s)
		{
			if (string.IsNullOrEmpty(s))
			{
				return "";
			}
			return s.Replace("\\", "\\\\").Replace("\"", "\\\"").Replace("\n", "\\n")
				.Replace("\r", "\\r")
				.Replace("\t", "\\t");
		}

		private static void BuildEnglishDefaults()
		{
			_englishDefaults = new Dictionary<string, string>
			{
				{ "to_tab_buy", "Buy" },
				{ "to_tab_sell", "Sell" },
				{ "to_tab_bank", "Bank" },
				{ "to_search_placeholder", "Search..." },
				{ "to_cat_weapons", "Weapons" },
				{ "to_cat_armor", "Armor" },
				{ "to_cat_shields", "Shields" },
				{ "to_cat_ammo", "Ammo" },
				{ "to_cat_consumables", "Consumables" },
				{ "to_cat_materials", "Materials" },
				{ "to_cat_utility", "Utility" },
				{ "to_cat_trophies", "Trophies" },
				{ "to_cat_misc", "Misc" },
				{ "to_rarity_base", "Base" },
				{ "to_rarity_magic", "Magic" },
				{ "to_rarity_rare", "Rare" },
				{ "to_rarity_epic", "Epic" },
				{ "to_rarity_legendary", "Legendary" },
				{ "to_rarity_mythic", "Mythic" },
				{ "to_btn_select_item", "Select an item" },
				{ "to_btn_buy", "Buy x{0} ({1})" },
				{ "to_btn_buy_need", "Need {0} coins" },
				{ "to_btn_sell", "Sell x{0} ({1})" },
				{ "to_qty_label", "Qty: {0}" },
				{ "to_coins_display", "Bank: {0}" },
				{ "to_msg_not_enough", "Not enough coins in bank!" },
				{ "to_msg_inventory_full", "Inventory full!" },
				{ "to_msg_bought", "Bought {0} for {1} coins" },
				{ "to_msg_sold", "Sold {0} for {1} coins" },
				{ "to_bank_title", "{0}'s Bank" },
				{ "to_bank_balance", "Bank Balance: {0}" },
				{ "to_bank_inventory", "Inventory Coins: {0}" },
				{ "to_bank_total", "Total Wealth: {0}" },
				{ "to_bank_deposit", "Deposit All" },
				{ "to_bank_withdraw", "Withdraw All" },
				{ "to_bank_no_coins", "No coins to deposit!" },
				{ "to_bank_deposited", "Deposited {0} coins" },
				{ "to_bank_empty", "Bank is empty!" },
				{ "to_bank_withdrew", "Withdrew {0} coins" },
				{ "to_cmd_balance_set", "Bank balance set to {0}" },
				{ "to_cmd_balance_was", "Bank balance set to {0} (was {1})" },
				{ "to_cmd_usage", "Usage: setbankbalance <amount>" },
				{ "to_cmd_no_player", "No player found." }
			};
		}
	}
	[BepInPlugin("com.profmags.traderoverhaul", "Trader Overhaul", "0.0.9")]
	public class TraderOverhaulPlugin : BaseUnityPlugin
	{
		public const string PluginGUID = "com.profmags.traderoverhaul";

		public const string PluginName = "Trader Overhaul";

		public const string PluginVersion = "0.0.9";

		private static Harmony _harmony;

		internal static ManualLogSource Log;

		private static ConfigEntry<bool> _enableHaldor;

		private static ConfigEntry<bool> _enableHildir;

		private static ConfigEntry<bool> _enableBogWitch;

		internal static bool IsCustomUIEnabled(TraderKind kind)
		{
			return kind switch
			{
				TraderKind.Haldor => _enableHaldor.Value, 
				TraderKind.Hildir => _enableHildir.Value, 
				TraderKind.BogWitch => _enableBogWitch.Value, 
				_ => false, 
			};
		}

		private void Awake()
		{
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Expected O, but got Unknown
			Log = ((BaseUnityPlugin)this).Logger;
			Log.LogInfo((object)"Trader Overhaul v0.0.9 loading...");
			_enableHaldor = ((BaseUnityPlugin)this).Config.Bind<bool>("Custom UI", "EnableHaldor", true, "Use the custom trader UI for Haldor.");
			_enableHildir = ((BaseUnityPlugin)this).Config.Bind<bool>("Custom UI", "EnableHildir", true, "Use the custom trader UI for Hildir.");
			_enableBogWitch = ((BaseUnityPlugin)this).Config.Bind<bool>("Custom UI", "EnableBogWitch", true, "Use the custom trader UI for the Bog Witch.");
			ConfigLoader.Initialize();
			TraderPatches.SetTraderUI(((Component)this).gameObject.AddComponent<TraderUI>());
			_harmony = new Harmony("com.profmags.traderoverhaul");
			_harmony.PatchAll(typeof(TraderPatches));
			_harmony.PatchAll(typeof(ModLocalization));
			ModLocalization.Init();
			ModLocalization.EnsureDefaultFile();
			Log.LogInfo((object)"Trader Overhaul loaded successfully!");
		}

		private void OnDestroy()
		{
			Harmony harmony = _harmony;
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
			Log.LogInfo((object)"Trader Overhaul unloaded.");
		}
	}
	internal struct TraderPreviewProfile
	{
		internal Vector3 SpawnOffset;

		internal Vector3 CenterOffset;

		internal Vector3 CameraOffset;

		internal Quaternion Rotation;

		internal float AnimatorUpdateDelta;

		internal float CameraFov;
	}
	internal enum TraderKind
	{
		Unknown,
		Haldor,
		Hildir,
		BogWitch
	}
	internal static class TraderIdentity
	{
		internal static TraderKind Resolve(Trader trader)
		{
			if ((Object)(object)trader == (Object)null)
			{
				return TraderKind.Unknown;
			}
			return ResolvePrefabName(Utils.GetPrefabName(((Component)trader).gameObject));
		}

		internal static TraderKind ResolvePrefabName(string prefabName)
		{
			if (string.IsNullOrEmpty(prefabName))
			{
				return TraderKind.Unknown;
			}
			string a = prefabName.Replace("_", "").Replace(" ", "");
			if (string.Equals(a, "Haldor", StringComparison.OrdinalIgnoreCase))
			{
				return TraderKind.Haldor;
			}
			if (string.Equals(a, "Hildir", StringComparison.OrdinalIgnoreCase))
			{
				return TraderKind.Hildir;
			}
			if (string.Equals(a, "BogWitch", StringComparison.OrdinalIgnoreCase))
			{
				return TraderKind.BogWitch;
			}
			return TraderKind.Unknown;
		}

		internal static string DisplayName(TraderKind kind)
		{
			return kind switch
			{
				TraderKind.Haldor => "Haldor", 
				TraderKind.Hildir => "Hildir", 
				TraderKind.BogWitch => "Bog Witch", 
				_ => "Trader", 
			};
		}

		internal static bool KeepsVanillaBuyStock(TraderKind kind)
		{
			if (kind != TraderKind.Hildir)
			{
				return kind == TraderKind.BogWitch;
			}
			return true;
		}

		internal static TraderPreviewProfile GetPreviewProfile(TraderKind kind)
		{
			//IL_013f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0144: Unknown result type (might be due to invalid IL or missing references)
			//IL_015a: Unknown result type (might be due to invalid IL or missing references)
			//IL_015f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0175: Unknown result type (might be due to invalid IL or missing references)
			//IL_017a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0190: Unknown result type (might be due to invalid IL or missing references)
			//IL_0195: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_00c0: 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_00db: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0111: Unknown result type (might be due to invalid IL or missing references)
			//IL_0116: Unknown result type (might be due to invalid IL or missing references)
			switch (kind)
			{
			case TraderKind.Hildir:
			{
				TraderPreviewProfile result = default(TraderPreviewProfile);
				result.SpawnOffset = new Vector3(0f, 0.2625f, 0f);
				result.CenterOffset = new Vector3(0f, 1.05f, 0f);
				result.CameraOffset = new Vector3(0f, 0.35f, 4.2f);
				result.Rotation = Quaternion.Euler(0f, 0f, 0f);
				result.AnimatorUpdateDelta = 0.01f;
				result.CameraFov = 30f;
				return result;
			}
			case TraderKind.BogWitch:
			{
				TraderPreviewProfile result = default(TraderPreviewProfile);
				result.SpawnOffset = new Vector3(0f, -0.287f, 0f);
				result.CenterOffset = new Vector3(0f, 1.3649999f, 0f);
				result.CameraOffset = new Vector3(0f, 0.35f, 4.2f);
				result.Rotation = Quaternion.Euler(0f, 0f, 0f);
				result.AnimatorUpdateDelta = 0.01f;
				result.CameraFov = 61f;
				return result;
			}
			default:
			{
				TraderPreviewProfile result = default(TraderPreviewProfile);
				result.SpawnOffset = Vector3.zero;
				result.CenterOffset = new Vector3(0f, 0.9f, 0f);
				result.CameraOffset = new Vector3(0f, 0.2f, 4.5f);
				result.Rotation = Quaternion.Euler(0f, 180f, 0f);
				result.AnimatorUpdateDelta = 0.001f;
				result.CameraFov = 30f;
				return result;
			}
			}
		}
	}
	public static class TraderPatches
	{
		[Serializable]
		[CompilerGenerated]
		private sealed class <>c
		{
			public static readonly <>c <>9 = new <>c();

			public static ConsoleEvent <>9__13_0;

			internal void <Terminal_InitTerminal_Postfix>b__13_0(ConsoleEventArgs args)
			{
				string s = null;
				if (args.Length >= 3 && args[1] == "=")
				{
					s = args[2];
				}
				else if (args.Length >= 2 && args[1] != "=")
				{
					s = args[1];
				}
				if (!int.TryParse(s, out var result) || result < 0)
				{
					args.Context.AddString(ModLocalization.Loc("to_cmd_usage"));
					return;
				}
				Player localPlayer = Player.m_localPlayer;
				if ((Object)(object)localPlayer == (Object)null)
				{
					args.Context.AddString(ModLocalization.Loc("to_cmd_no_player"));
					return;
				}
				int num = BankBalanceStore.Read(localPlayer);
				BankBalanceStore.Write(localPlayer, result);
				GetTraderUI()?.ReloadBankBalance();
				((Character)localPlayer).Message((MessageType)2, ModLocalization.LocFmt("to_cmd_balance_set", result.ToString("N0")), 0, (Sprite)null);
				args.Context.AddString(ModLocalization.LocFmt("to_cmd_balance_was", result.ToString("N0"), num.ToString("N0")));
			}
		}

		private static TraderUI _traderUI;

		private static bool _customUIActive;

		internal static void SetTraderUI(TraderUI ui)
		{
			_traderUI = ui;
		}

		internal static TraderUI GetTraderUI()
		{
			return _traderUI;
		}

		internal static TraderKind GetTraderKind(Trader trader)
		{
			return TraderIdentity.Resolve(trader);
		}

		[HarmonyPatch(typeof(StoreGui), "Show")]
		[HarmonyPrefix]
		[HarmonyPriority(800)]
		private static bool StoreGui_Show_Prefix(StoreGui __instance, Trader trader)
		{
			if ((Object)(object)_traderUI == (Object)null)
			{
				return true;
			}
			TraderKind traderKind = GetTraderKind(trader);
			if (traderKind == TraderKind.Unknown)
			{
				return true;
			}
			if (!TraderOverhaulPlugin.IsCustomUIEnabled(traderKind))
			{
				return true;
			}
			((Component)__instance).gameObject.SetActive(false);
			_customUIActive = true;
			_traderUI.Show(trader, __instance);
			return false;
		}

		[HarmonyPatch(typeof(StoreGui), "Show")]
		[HarmonyPostfix]
		[HarmonyPriority(0)]
		private static void StoreGui_Show_Postfix(StoreGui __instance)
		{
			if (_customUIActive)
			{
				((Component)__instance).gameObject.SetActive(false);
			}
		}

		[HarmonyPatch(typeof(StoreGui), "Hide")]
		[HarmonyPostfix]
		private static void StoreGui_Hide_Postfix(StoreGui __instance)
		{
			if ((Object)(object)_traderUI != (Object)null && _traderUI.IsVisible)
			{
				_traderUI.Hide();
			}
			if (_customUIActive)
			{
				((Component)__instance).gameObject.SetActive(true);
				_customUIActive = false;
			}
		}

		[HarmonyPatch(typeof(StoreGui), "Update")]
		[HarmonyPrefix]
		[HarmonyPriority(800)]
		private static bool StoreGui_Update_Prefix()
		{
			return !_customUIActive;
		}

		[HarmonyPatch(typeof(StoreGui), "IsVisible")]
		[HarmonyPostfix]
		private static void StoreGui_IsVisible_Postfix(ref bool __result)
		{
			if ((Object)(object)_traderUI != (Object)null && _traderUI.IsVisible)
			{
				__result = true;
			}
		}

		[HarmonyPatch(typeof(Chat), "SetNpcText")]
		[HarmonyPrefix]
		private static bool Chat_SetNpcText_Prefix()
		{
			if ((Object)(object)_traderUI != (Object)null && _traderUI.IsVisible)
			{
				return false;
			}
			return true;
		}

		[HarmonyPatch(typeof(Chat), "HasFocus")]
		[HarmonyPostfix]
		private static void Chat_HasFocus_Postfix(ref bool __result)
		{
			if (!__result && (Object)(object)_traderUI != (Object)null && _traderUI.IsSearchFocused)
			{
				__result = true;
			}
		}

		[HarmonyPatch(typeof(Player), "TakeInput")]
		[HarmonyPrefix]
		private static bool Player_TakeInput_Prefix(ref bool __result)
		{
			if ((Object)(object)_traderUI != (Object)null && _traderUI.IsVisible)
			{
				__result = false;
				return false;
			}
			return true;
		}

		[HarmonyPatch(typeof(Terminal), "InitTerminal")]
		[HarmonyPostfix]
		private static void Terminal_InitTerminal_Postfix()
		{
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Expected O, but got Unknown
			object obj = <>c.<>9__13_0;
			if (obj == null)
			{
				ConsoleEvent val = delegate(ConsoleEventArgs args)
				{
					string s = null;
					if (args.Length >= 3 && args[1] == "=")
					{
						s = args[2];
					}
					else if (args.Length >= 2 && args[1] != "=")
					{
						s = args[1];
					}
					if (!int.TryParse(s, out var result) || result < 0)
					{
						args.Context.AddString(ModLocalization.Loc("to_cmd_usage"));
					}
					else
					{
						Player localPlayer = Player.m_localPlayer;
						if ((Object)(object)localPlayer == (Object)null)
						{
							args.Context.AddString(ModLocalization.Loc("to_cmd_no_player"));
						}
						else
						{
							int num = BankBalanceStore.Read(localPlayer);
							BankBalanceStore.Write(localPlayer, result);
							GetTraderUI()?.ReloadBankBalance();
							((Character)localPlayer).Message((MessageType)2, ModLocalization.LocFmt("to_cmd_balance_set", result.ToString("N0")), 0, (Sprite)null);
							args.Context.AddString(ModLocalization.LocFmt("to_cmd_balance_was", result.ToString("N0"), num.ToString("N0")));
						}
					}
				};
				<>c.<>9__13_0 = val;
				obj = (object)val;
			}
			new ConsoleCommand("setbankbalance", "Set shared trader bank balance. Usage: setbankbalance <amount>  or  setbankbalance = <amount>", (ConsoleEvent)obj, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false);
		}
	}
	public static class TextureLoader
	{
		private static readonly Dictionary<string, Texture2D> Cache = new Dictionary<string, Texture2D>();

		private static readonly Assembly ModAssembly = Assembly.GetExecutingAssembly();

		private static readonly MethodInfo LoadImageMethod = ResolveLoadImage();

		private static MethodInfo ResolveLoadImage()
		{
			return Type.GetType("UnityEngine.ImageConversion, UnityEngine.ImageConversionModule")?.GetMethod("LoadImage", new Type[2]
			{
				typeof(Texture2D),
				typeof(byte[])
			});
		}

		public static Texture2D LoadUITexture(string name)
		{
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Expected O, but got Unknown
			if (string.IsNullOrEmpty(name))
			{
				return null;
			}
			string key = "UI_" + name;
			if (Cache.TryGetValue(key, out var value))
			{
				return value;
			}
			if (LoadImageMethod == null)
			{
				TraderOverhaulPlugin.Log.LogWarning((object)"TextureLoader: ImageConversion.LoadImage not found via reflection.");
				return null;
			}
			string text = "TraderOverhaul.Resources.Textures.UI." + name + ".png";
			using Stream stream = ModAssembly.GetManifestResourceStream(text);
			if (stream == null)
			{
				TraderOverhaulPlugin.Log.LogWarning((object)("TextureLoader: UI resource '" + text + "' not found."));
				return null;
			}
			byte[] array = new byte[stream.Length];
			stream.Read(array, 0, array.Length);
			Texture2D val = new Texture2D(2, 2, (TextureFormat)4, false);
			if ((bool)LoadImageMethod.Invoke(null, new object[2] { val, array }))
			{
				((Object)val).name = name;
				Cache[key] = val;
				return val;
			}
			Object.Destroy((Object)(object)val);
			return null;
		}
	}
	public class TraderUI : MonoBehaviour
	{
		private class BuyEntry
		{
			public string PrefabName;

			public string Name;

			public string Description;

			public int Price;

			public int Stack;

			public string Category;

			public Sprite Icon;

			public string Rarity = "";
		}

		private class SellEntry
		{
			public ItemData Item;

			public string PrefabName;

			public string Name;

			public int Price;

			public int ConfigStack;

			public string Category;

			public Sprite Icon;

			public string Rarity = "";
		}

		private bool _isVisible;

		private Trader _currentTrader;

		private StoreGui _currentStoreGui;

		private TraderKind _currentTraderKind;

		private string _currentTraderName = "Trader";

		private int _activeTab;

		private static readonly string[] TabNames = new string[3] { "Buy", "Sell", "Bank" };

		private int _selectedBuyIndex = -1;

		private int _selectedSellIndex = -1;

		private readonly Dictionary<string, bool> _buyCategoryCollapsed = new Dictionary<string, bool>();

		private readonly Dictionary<string, bool> _sellCategoryCollapsed = new Dictionary<string, bool>();

		private readonly Dictionary<string, bool> _buyRarityCollapsed = new Dictionary<string, bool>();

		private readonly Dictionary<string, bool> _sellRarityCollapsed = new Dictionary<string, bool>();

		private static readonly string[] CategoryBuckets = new string[9] { "Weapons", "Armor", "Shields", "Ammo", "Consumables", "Materials", "Utility", "Trophies", "Misc" };

		private static readonly string[] RarityOrder = new string[6] { "", "Magic", "Rare", "Epic", "Legendary", "Mythic" };

		private static readonly Dictionary<string, string> RarityLocKeys = new Dictionary<string, string>
		{
			{ "", "to_rarity_base" },
			{ "Magic", "to_rarity_magic" },
			{ "Rare", "to_rarity_rare" },
			{ "Epic", "to_rarity_epic" },
			{ "Legendary", "to_rarity_legendary" },
			{ "Mythic", "to_rarity_mythic" }
		};

		private static readonly Dictionary<string, string> CategoryLocKeys = new Dictionary<string, string>
		{
			{ "Weapons", "to_cat_weapons" },
			{ "Armor", "to_cat_armor" },
			{ "Shields", "to_cat_shields" },
			{ "Ammo", "to_cat_ammo" },
			{ "Consumables", "to_cat_consumables" },
			{ "Materials", "to_cat_materials" },
			{ "Utility", "to_cat_utility" },
			{ "Trophies", "to_cat_trophies" },
			{ "Misc", "to_cat_misc" }
		};

		private readonly Dictionary<string, string> _rarityTooltipCache = new Dictionary<string, string>();

		private string _searchFilter = "";

		private TMP_InputField _searchInput;

		private string _activeCategoryFilter;

		private readonly List<Button> _categoryFilterButtons = new List<Button>();

		private readonly List<string> _categoryFilterKeys = new List<string>();

		private int _joyCategoryFocusIndex = -1;

		private int _lastJoyCategoryFocusIndex = -1;

		private GameObject _canvasGO;

		private bool _uiBuilt;

		private Sprite _bgSprite;

		private Sprite _textFieldSprite;

		private Sprite _catBtnSprite;

		private Sprite _sliderBgSprite;

		private GameObject _recipeElementPrefab;

		private GameObject _buttonTemplate;

		private float _scrollSensitivity = 40f;

		private TMP_FontAsset _valheimFont;

		private GameObject _mainPanel;

		private RectTransform _leftColumn;

		private RectTransform _middleColumn;

		private RectTransform _rightColumn;

		private GameObject _tabBuy;

		private GameObject _tabSell;

		private GameObject _tabBank;

		private int _bankBalance;

		private int _bankFocusedButton;

		private GameObject _bankContentPanel;

		private TMP_Text _bankTitleText;

		private TMP_Text _bankBalanceText;

		private TMP_Text _bankInvCoinsText;

		private TMP_Text _bankTotalText;

		private TMP_Text _bankStatusText;

		private Button _bankDepositButton;

		private Button _bankWithdrawButton;

		private GameObject _bankDepositSelected;

		private GameObject _bankWithdrawSelected;

		private RectTransform _listRoot;

		private ScrollRect _listScrollRect;

		private GameObject _listScrollbarGO;

		private TMP_Text _itemNameText;

		private TMP_Text _itemDescText;

		private ScrollRect _descScrollRect;

		private GameObject _descScrollbarGO;

		private int _descScrollResetFrames;

		private Button _actionButton;

		private TMP_Text _actionButtonLabel;

		private TMP_Text _coinDisplayText;

		private Slider _quantitySlider;

		private TMP_Text _quantityLabel;

		private int _selectedQuantity = 1;

		private RenderTexture _playerPreviewRT;

		private GameObject _playerCamGO;

		private Camera _playerCam;

		private GameObject _playerClone;

		private GameObject _playerLightRig;

		private RawImage _playerPreviewImg;

		private static readonly Vector3 PlayerSpawnPos = new Vector3(10000f, 5000f, 10000f);

		private RenderTexture _haldorPreviewRT;

		private GameObject _haldorCamGO;

		private Camera _haldorCam;

		private GameObject _haldorClone;

		private GameObject _haldorLightRig;

		private RawImage _haldorPreviewImg;

		private static readonly Vector3 TraderSpawnPos = new Vector3(10000f, 5000f, 10020f);

		private Color _savedAmbientColor;

		private float _savedAmbientIntensity;

		private AmbientMode _savedAmbientMode;

		private float _previewRotation;

		private const float AutoRotateSpeed = 12f;

		private bool _isDraggingPlayerPreview;

		private float _lastMouseX;

		private const float MouseDragSensitivity = 0.5f;

		private const float ColGap = 8f;

		private const float TabTopGap = 6f;

		private const float ExtraMiddleWidth = 80f;

		private const float OuterPad = 6f;

		private const float SearchBoxHeight = 32f;

		private const float FilterRowHeight = 38f;

		private static readonly Color ColOverlay = new Color(0f, 0f, 0f, 0f);

		private static readonly Color GoldColor = new Color(0.83f, 0.64f, 0.31f, 1f);

		private static readonly Color GoldTextColor = new Color(0.83f, 0.52f, 0.18f, 1f);

		private static readonly Color CategoryHeaderBg = new Color(0.3f, 0.25f, 0.15f, 0.85f);

		private static readonly Color CategoryHeaderText = new Color(1f, 0.9f, 0.5f, 1f);

		private float _panelWidth;

		private float _panelHeight;

		private float _leftColWidth;

		private float _midColWidth;

		private float _rightColWidth;

		private float _leftPad;

		private float _bottomPad;

		private float _colTopInset;

		private float _tabBtnHeight;

		private float _craftBtnHeight;

		private readonly List<BuyEntry> _allBuyEntries = new List<BuyEntry>();

		private readonly List<SellEntry> _allSellEntries = new List<SellEntry>();

		private readonly List<(GameObject go, int dataIndex)> _listElements = new List<(GameObject, int)>();

		private readonly List<GameObject> _categoryHeaders = new List<GameObject>();

		private int _lastInventoryHash;

		private int _lastCoinDisplayCount = -1;

		private int _lastBankBalanceDisplay = -1;

		private int _lastBankInvCoinsDisplay = -1;

		private Dictionary<string, string> _savedEquipSlots;

		private static readonly Color RaritySubHeaderBg = new Color(0.25f, 0.22f, 0.15f, 0.7f);

		private const string EpicLootDataKey = "randyknapp.mods.epicloot#EpicLoot.MagicItemComponent,EpicLoot";

		private static readonly string[] EpicLootRarityNames = new string[5] { "Magic", "Rare", "Epic", "Legendary", "Mythic" };

		public bool IsVisible => _isVisible;

		public bool IsSearchFocused
		{
			get
			{
				if ((Object)(object)_searchInput != (Object)null)
				{
					return _searchInput.isFocused;
				}
				return false;
			}
		}

		private static string LocCategory(string cat)
		{
			if (!CategoryLocKeys.TryGetValue(cat, out var value))
			{
				return cat;
			}
			return ModLocalization.Loc(value);
		}

		private static string LocRarity(string rarity)
		{
			if (!RarityLocKeys.TryGetValue(rarity, out var value))
			{
				return rarity;
			}
			return ModLocalization.Loc(value);
		}

		public void Show(Trader trader, StoreGui storeGui)
		{
			_currentTrader = trader;
			_currentStoreGui = storeGui;
			_currentTraderKind = TraderPatches.GetTraderKind(trader);
			_currentTraderName = TraderIdentity.DisplayName(_currentTraderKind);
			if (_uiBuilt && (Object)(object)_canvasGO == (Object)null)
			{
				CleanupForRebuild();
				TraderOverhaulPlugin.Log.LogWarning((object)"[TraderUI] Canvas destroyed — rebuilding UI");
			}
			if (!_uiBuilt)
			{
				BuildUI();
			}
			if (_uiBuilt)
			{
				_canvasGO.SetActive(true);
				_isVisible = true;
				_activeTab = 0;
				_selectedBuyIndex = -1;
				_selectedSellIndex = -1;
				_searchFilter = "";
				if ((Object)(object)_searchInput != (Object)null)
				{
					_searchInput.text = "";
				}
				_activeCategoryFilter = null;
				_joyCategoryFocusIndex = -1;
				_lastJoyCategoryFocusIndex = -1;
				_lastInventoryHash = 0;
				_lastCoinDisplayCount = -1;
				_lastBankBalanceDisplay = -1;
				_lastBankInvCoinsDisplay = -1;
				_buyRarityCollapsed.Clear();
				_sellRarityCollapsed.Clear();
				_rarityTooltipCache.Clear();
				SetupPlayerPreview();
				SetupTraderPreview();
				_previewRotation = 0f;
				EnablePreviewCameras();
				LoadBankBalance();
				UpdateBankTitle();
				BuildBuyEntries();
				BuildSellEntries();
				RefreshTabHighlights();
				RefreshTabPanels();
				UpdateCoinDisplay();
			}
		}

		public void Hide()
		{
			if (_isVisible)
			{
				_isVisible = false;
				DisablePreviewCameras();
				ClearPlayerPreview();
				ClearTraderPreview();
				if ((Object)(object)_canvasGO != (Object)null)
				{
					_canvasGO.SetActive(false);
				}
				StoreGui currentStoreGui = _currentStoreGui;
				_currentTrader = null;
				_currentStoreGui = null;
				_currentTraderKind = TraderKind.Unknown;
				_currentTraderName = "Trader";
				if ((Object)(object)currentStoreGui != (Object)null)
				{
					currentStoreGui.Hide();
				}
			}
		}

		private void Update()
		{
			//IL_00a0: 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)
			if (!_isVisible)
			{
				return;
			}
			bool flag = (Object)(object)_leftColumn != (Object)null && ((Component)_leftColumn).gameObject.activeSelf;
			if ((Object)(object)_listScrollbarGO != (Object)null && _listScrollbarGO.activeSelf != flag)
			{
				_listScrollbarGO.SetActive(flag);
			}
			if ((Object)(object)_descScrollbarGO != (Object)null && _descScrollbarGO.activeSelf != flag)
			{
				_descScrollbarGO.SetActive(flag);
			}
			if ((Object)(object)_currentTrader != (Object)null && (Object)(object)Player.m_localPlayer != (Object)null && Vector3.Distance(((Component)Player.m_localPlayer).transform.position, ((Component)_currentTrader).transform.position) > 15f)
			{
				Hide();
				return;
			}
			if (!ZInput.IsGamepadActive())
			{
				Cursor.lockState = (CursorLockMode)0;
				Cursor.visible = true;
			}
			else
			{
				Cursor.visible = false;
			}
			if (Input.GetKeyDown((KeyCode)27))
			{
				Hide();
				return;
			}
			if (!IsSearchFocused)
			{
				if (Input.GetKeyDown((KeyCode)113))
				{
					SwitchTab(Mathf.Max(0, _activeTab - 1));
				}
				if (Input.GetKeyDown((KeyCode)101))
				{
					SwitchTab(Mathf.Min(2, _activeTab + 1));
				}
			}
			UpdatePlayerPreviewRotation();
			UpdatePlayerCamera();
			RefreshSellListIfChanged();
			UpdateCoinDisplay();
			if (_activeTab == 2)
			{
				RefreshBankDisplay();
			}
			UpdateGamepadInput();
		}

		private void LateUpdate()
		{
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			if (!_isVisible)
			{
				return;
			}
			Hud instance = Hud.instance;
			if ((Object)(object)instance != (Object)null)
			{
				if ((Object)(object)instance.m_crosshair != (Object)null)
				{
					((Graphic)instance.m_crosshair).color = Color.clear;
				}
				if ((Object)(object)instance.m_hoverName != (Object)null)
				{
					((TMP_Text)instance.m_hoverName).text = "";
				}
			}
			if (_descScrollResetFrames > 0 && (Object)(object)_descScrollRect != (Object)null)
			{
				_descScrollRect.verticalNormalizedPosition = 1f;
				_descScrollRect.velocity = Vector2.zero;
				_descScrollResetFrames--;
			}
			if ((Object)(object)EventSystem.current != (Object)null && (Object)(object)EventSystem.current.currentSelectedGameObject != (Object)null && ((Object)(object)_searchInput == (Object)null || (Object)(object)EventSystem.current.currentSelectedGameObject != (Object)(object)((Component)_searchInput).gameObject))
			{
				EventSystem.current.SetSelectedGameObject((GameObject)null);
			}
			SaveAmbient();
			try
			{
				SetPreviewAmbient();
				if (_activeTab == 0 && (Object)(object)_playerCam != (Object)null)
				{
					_playerCam.Render();
				}
				else if (_activeTab == 1 && (Object)(object)_haldorCam != (Object)null)
				{
					_haldorCam.Render();
				}
			}
			finally
			{
				RestoreAmbient();
			}
		}

		private void CleanupForRebuild()
		{
			_uiBuilt = false;
			ClearPlayerPreview();
			ClearTraderPreview();
			if ((Object)(object)_playerCamGO != (Object)null)
			{
				Object.Destroy((Object)(object)_playerCamGO);
				_playerCamGO = null;
			}
			if ((Object)(object)_haldorCamGO != (Object)null)
			{
				Object.Destroy((Object)(object)_haldorCamGO);
				_haldorCamGO = null;
			}
			if ((Object)(object)_playerPreviewRT != (Object)null)
			{
				_playerPreviewRT.Release();
				Object.Destroy((Object)(object)_playerPreviewRT);
				_playerPreviewRT = null;
			}
			if ((Object)(object)_haldorPreviewRT != (Object)null)
			{
				_haldorPreviewRT.Release();
				Object.Destroy((Object)(object)_haldorPreviewRT);
				_haldorPreviewRT = null;
			}
			if ((Object)(object)_buttonTemplate != (Object)null)
			{
				Object.Destroy((Object)(object)_buttonTemplate);
				_buttonTemplate = null;
			}
			if ((Object)(object)_recipeElementPrefab != (Object)null)
			{
				Object.Destroy((Object)(object)_recipeElementPrefab);
				_recipeElementPrefab = null;
			}
			if ((Object)(object)_bgSprite != (Object)null)
			{
				Object.Destroy((Object)(object)_bgSprite);
				_bgSprite = null;
			}
			if ((Object)(object)_textFieldSprite != (Object)null)
			{
				Object.Destroy((Object)(object)_textFieldSprite);
				_textFieldSprite = null;
			}
			if ((Object)(object)_catBtnSprite != (Object)null)
			{
				Object.Destroy((Object)(object)_catBtnSprite);
				_catBtnSprite = null;
			}
			if ((Object)(object)_sliderBgSprite != (Object)null)
			{
				Object.Destroy((Object)(object)_sliderBgSprite);
				_sliderBgSprite = null;
			}
			_canvasGO = null;
			_mainPanel = null;
			_leftColumn = null;
			_middleColumn = null;
			_rightColumn = null;
			_listRoot = null;
			_listScrollRect = null;
			_listScrollbarGO = null;
			_descScrollbarGO = null;
			_descScrollRect = null;
			_searchInput = null;
			_tabBuy = null;
			_tabSell = null;
			_tabBank = null;
			_actionButton = null;
			_actionButtonLabel = null;
			_itemDescText = null;
			_coinDisplayText = null;
			_playerPreviewImg = null;
			_haldorPreviewImg = null;
			_bankContentPanel = null;
			_bankTitleText = null;
			_bankBalanceText = null;
			_bankInvCoinsText = null;
			_bankTotalText = null;
			_bankDepositButton = null;
			_bankWithdrawButton = null;
			_bankDepositSelected = null;
			_bankWithdrawSelected = null;
			_valheimFont = null;
			_categoryFilterButtons.Clear();
			_categoryFilterKeys.Clear();
			_listElements.Clear();
			_categoryHeaders.Clear();
		}

		private void OnDestroy()
		{
			ClearPlayerPreview();
			ClearTraderPreview();
			if ((Object)(object)_playerCamGO != (Object)null)
			{
				Object.Destroy((Object)(object)_playerCamGO);
			}
			if ((Object)(object)_haldorCamGO != (Object)null)
			{
				Object.Destroy((Object)(object)_haldorCamGO);
			}
			if ((Object)(object)_playerPreviewRT != (Object)null)
			{
				_playerPreviewRT.Release();
				Object.Destroy((Object)(object)_playerPreviewRT);
			}
			if ((Object)(object)_haldorPreviewRT != (Object)null)
			{
				_haldorPreviewRT.Release();
				Object.Destroy((Object)(object)_haldorPreviewRT);
			}
			if ((Object)(object)_buttonTemplate != (Object)null)
			{
				Object.Destroy((Object)(object)_buttonTemplate);
			}
			if ((Object)(object)_recipeElementPrefab != (Object)null)
			{
				Object.Destroy((Object)(object)_recipeElementPrefab);
			}
			if ((Object)(object)_bgSprite != (Object)null)
			{
				Object.Destroy((Object)(object)_bgSprite);
			}
			if ((Object)(object)_textFieldSprite != (Object)null)
			{
				Object.Destroy((Object)(object)_textFieldSprite);
			}
			if ((Object)(object)_catBtnSprite != (Object)null)
			{
				Object.Destroy((Object)(object)_catBtnSprite);
			}
			if ((Object)(object)_sliderBgSprite != (Object)null)
			{
				Object.Destroy((Object)(object)_sliderBgSprite);
			}
			if ((Object)(object)_canvasGO != (Object)null)
			{
				Object.Destroy((Object)(object)_canvasGO);
			}
		}

		private void UpdateGamepadInput()
		{
			if (ZInput.GetButtonDown("JoyTabLeft"))
			{
				SwitchTab(Mathf.Max(0, _activeTab - 1));
			}
			if (ZInput.GetButtonDown("JoyTabRight"))
			{
				SwitchTab(Mathf.Min(2, _activeTab + 1));
			}
			if (ZInput.GetButtonDown("JoyButtonB"))
			{
				Hide();
				return;
			}
			if (ZInput.GetButtonDown("JoyLStickDown") || ZInput.GetButtonDown("JoyDPadDown"))
			{
				if (_joyCategoryFocusIndex >= 0)
				{
					_lastJoyCategoryFocusIndex = _joyCategoryFocusIndex;
				}
				_joyCategoryFocusIndex = -1;
				UpdateCategoryFilterVisuals();
				MoveSelection(1);
				if ((Object)(object)EventSystem.current != (Object)null)
				{
					EventSystem.current.SetSelectedGameObject((GameObject)null);
				}
			}
			if (ZInput.GetButtonDown("JoyLStickUp") || ZInput.GetButtonDown("JoyDPadUp"))
			{
				if (((_activeTab == 0 && _selectedBuyIndex <= 0) || (_activeTab == 1 && _selectedSellIndex <= 0)) && _joyCategoryFocusIndex < 0 && _categoryFilterButtons.Count > 0)
				{
					_joyCategoryFocusIndex = ((_lastJoyCategoryFocusIndex >= 0) ? Mathf.Min(_lastJoyCategoryFocusIndex, _categoryFilterButtons.Count - 1) : 0);
					UpdateCategoryFilterVisuals();
				}
				else
				{
					if (_joyCategoryFocusIndex >= 0)
					{
						_lastJoyCategoryFocusIndex = _joyCategoryFocusIndex;
					}
					_joyCategoryFocusIndex = -1;
					UpdateCategoryFilterVisuals();
					MoveSelection(-1);
				}
				if ((Object)(object)EventSystem.current != (Object)null)
				{
					EventSystem.current.SetSelectedGameObject((GameObject)null);
				}
			}
			if (ZInput.GetButtonDown("JoyLStickLeft") || ZInput.GetButtonDown("JoyDPadLeft"))
			{
				if (_activeTab == 2)
				{
					_bankFocusedButton = 0;
					UpdateBankHighlight();
				}
				else
				{
					NavigateCategoryButtons(-1);
				}
			}
			if (ZInput.GetButtonDown("JoyLStickRight") || ZInput.GetButtonDown("JoyDPadRight"))
			{
				if (_activeTab == 2)
				{
					_bankFocusedButton = 1;
					UpdateBankHighlight();
				}
				else
				{
					NavigateCategoryButtons(1);
				}
			}
			if (ZInput.GetButtonDown("JoyButtonA"))
			{
				if (_joyCategoryFocusIndex >= 0 && _joyCategoryFocusIndex < _categoryFilterKeys.Count)
				{
					OnCategoryFilterClicked(_categoryFilterKeys[_joyCategoryFocusIndex]);
					_lastJoyCategoryFocusIndex = _joyCategoryFocusIndex;
					_joyCategoryFocusIndex = -1;
					UpdateCategoryFilterVisuals();
				}
				else if (_activeTab == 2)
				{
					if (_bankFocusedButton == 0)
					{
						OnBankDeposit();
					}
					else
					{
						OnBankWithdraw();
					}
				}
				else if ((Object)(object)_actionButton != (Object)null && ((Selectable)_actionButton).interactable)
				{
					OnActionButtonClicked();
				}
			}
			if (ZInput.GetButtonDown("JoyButtonX"))
			{
				ToggleFocusedCategory();
			}
			if ((Object)(object)_descScrollRect != (Object)null)
			{
				float num = 2f;
				if (ZInput.GetButton("JoyRStickDown"))
				{
					ScrollRect descScrollRect = _descScrollRect;
					descScrollRect.verticalNormalizedPosition -= num * Time.deltaTime;
					_descScrollRect.verticalNormalizedPosition = Mathf.Clamp01(_descScrollRect.verticalNormalizedPosition);
				}
				if (ZInput.GetButton("JoyRStickUp"))
				{
					ScrollRect descScrollRect2 = _descScrollRect;
					descScrollRect2.verticalNormalizedPosition += num * Time.deltaTime;
					_descScrollRect.verticalNormalizedPosition = Mathf.Clamp01(_descScrollRect.verticalNormalizedPosition);
				}
			}
		}

		private void NavigateCategoryButtons(int dir)
		{
			if (_categoryFilterButtons.Count == 0)
			{
				return;
			}
			if (_joyCategoryFocusIndex < 0)
			{
				if (_lastJoyCategoryFocusIndex >= 0)
				{
					_joyCategoryFocusIndex = Mathf.Clamp(_lastJoyCategoryFocusIndex, 0, _categoryFilterButtons.Count - 1);
				}
				else
				{
					_joyCategoryFocusIndex = ((dir <= 0) ? (_categoryFilterButtons.Count - 1) : 0);
				}
			}
			else
			{
				_joyCategoryFocusIndex = Mathf.Clamp(_joyCategoryFocusIndex + dir, 0, _categoryFilterButtons.Count - 1);
			}
			UpdateCategoryFilterVisuals();
		}

		private void MoveSelection(int direction)
		{
			if (_activeTab == 0)
			{
				if (_listElements.Count != 0)
				{
					int index = Mathf.Clamp(_listElements.FindIndex(((GameObject go, int dataIndex) e) => e.dataIndex == _selectedBuyIndex) + direction, 0, _listElements.Count - 1);
					int item = _listElements[index].dataIndex;
					SelectBuyItem(item);
					EnsureItemVisible(item);
				}
			}
			else if (_activeTab == 1)
			{
				if (_listElements.Count != 0)
				{
					int index2 = Mathf.Clamp(_listElements.FindIndex(((GameObject go, int dataIndex) e) => e.dataIndex == _selectedSellIndex) + direction, 0, _listElements.Count - 1);
					int item2 = _listElements[index2].dataIndex;
					SelectSellItem(item2);
					EnsureItemVisible(item2);
				}
			}
			else if (_activeTab == 2)
			{
				_bankFocusedButton = ((direction > 0) ? 1 : 0);
				UpdateBankHighlight();
			}
		}

		private void ToggleFocusedCategory()
		{
			if (_activeTab == 0 && _selectedBuyIndex >= 0)
			{
				List<BuyEntry> filteredBuyEntries = GetFilteredBuyEntries();
				if (_selectedBuyIndex < filteredBuyEntries.Count)
				{
					BuyEntry buyEntry = filteredBuyEntries[_selectedBuyIndex];
					if (!string.IsNullOrEmpty(buyEntry.Rarity))
					{
						string key = buyEntry.Category + "|" + buyEntry.Rarity;
						_buyRarityCollapsed[key] = !(_buyRarityCollapsed.TryGetValue(key, out var value) && value);
					}
					else
					{
						_buyCategoryCollapsed[buyEntry.Category] = !(_buyCategoryCollapsed.TryGetValue(buyEntry.Category, out var value2) && value2);
					}
					PopulateCurrentList();
				}
			}
			else
			{
				if (_activeTab != 1 || _selectedSellIndex < 0)
				{
					return;
				}
				List<SellEntry> filteredSellEntries = GetFilteredSellEntries();
				if (_selectedSellIndex < filteredSellEntries.Count)
				{
					SellEntry sellEntry = filteredSellEntries[_selectedSellIndex];
					if (!string.IsNullOrEmpty(sellEntry.Rarity))
					{
						string key2 = sellEntry.Category + "|" + sellEntry.Rarity;
						_sellRarityCollapsed[key2] = !(_sellRarityCollapsed.TryGetValue(key2, out var value3) && value3);
					}
					else
					{
						_sellCategoryCollapsed[sellEntry.Category] = !(_sellCategoryCollapsed.TryGetValue(sellEntry.Category, out var value4) && value4);
					}
					PopulateCurrentList();
				}
			}
		}

		private void BuildUI()
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Expected O, but got Unknown
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00da: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e5: 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)
			//IL_00fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_012e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0138: Expected O, but got Unknown
			//IL_016a: Unknown result type (might be due to invalid IL or missing references)
			//IL_017f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0194: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0215: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f4: Unknown result type (might be due to invalid IL or missing references)
			if (!ExtractAssets())
			{
				TraderOverhaulPlugin.Log.LogError((object)"[TraderUI] Failed to extract Valheim assets.");
				return;
			}
			_canvasGO = new GameObject("TraderOverhaul_Canvas");
			_canvasGO.transform.SetParent(((Component)this).transform);
			Canvas obj = _canvasGO.AddComponent<Canvas>();
			obj.renderMode = (RenderMode)0;
			obj.sortingOrder = 100;
			CanvasScaler obj2 = _canvasGO.AddComponent<CanvasScaler>();
			obj2.uiScaleMode = (ScaleMode)1;
			obj2.referenceResolution = new Vector2(1920f, 1080f);
			obj2.matchWidthOrHeight = 0.5f;
			_canvasGO.AddComponent<GraphicRaycaster>();
			GameObject val = new GameObject("Overlay", new Type[1] { typeof(RectTransform) });
			val.transform.SetParent(_canvasGO.transform, false);
			RectTransform component = val.GetComponent<RectTransform>();
			component.anchorMin = Vector2.zero;
			component.anchorMax = Vector2.one;
			component.offsetMin = Vector2.zero;
			component.offsetMax = Vector2.zero;
			((Graphic)val.AddComponent<Image>()).color = ColOverlay;
			_mainPanel = new GameObject("MainPanel", new Type[2]
			{
				typeof(RectTransform),
				typeof(Image)
			});
			_mainPanel.transform.SetParent(_canvasGO.transform, false);
			RectTransform component2 = _mainPanel.GetComponent<RectTransform>();
			component2.anchorMin = new Vector2(0.5f, 0.5f);
			component2.anchorMax = new Vector2(0.5f, 0.5f);
			component2.pivot = new Vector2(0.5f, 0.5f);
			component2.sizeDelta = new Vector2(_panelWidth, _panelHeight);
			component2.anchoredPosition = Vector2.zero;
			Image component3 = _mainPanel.GetComponent<Image>();
			if ((Object)(object)_bgSprite != (Object)null)
			{
				component3.sprite = _bgSprite;
				component3.type = (Type)0;
				component3.preserveAspect = false;
				((Graphic)component3).color = Color.white;
			}
			else
			{
				((Graphic)component3).color = new Color(0.18f, 0.14f, 0.09f, 0.92f);
			}
			float num = _leftPad + _leftColWidth + 8f;
			float num2 = num + _midColWidth + 8f;
			_leftColumn = CreateColumn("LeftColumn", _leftPad, _leftPad + _leftColWidth);
			_middleColumn = CreateColumn("MiddleColumn", num, num + _midColWidth);
			_rightColumn = CreateColumn("RightColumn", num2, num2 + _rightColWidth);
			BuildItemListArea();
			BuildDescriptionColumn();
			BuildPreviewColumn();
			_tabBuy = CreateTabButton(ModLocalization.Loc("to_tab_buy"), 0, _leftPad + _leftColWidth / 2f, _leftColWidth, 6f);
			_tabSell = CreateTabButton(ModLocalization.Loc("to_tab_sell"), 1, num + _midColWidth / 2f, _midColWidth, 6f);
			_tabBank = CreateTabButton(ModLocalization.Loc("to_tab_bank"), 2, num2 + _rightColWidth / 2f, _rightColWidth, 6f);
			BuildBankPanel();
			_canvasGO.SetActive(false);
			_uiBuilt = true;
		}

		private bool ExtractAssets()
		{
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0128: Unknown result type (might be due to invalid IL or missing references)
			//IL_0137: Unknown result type (might be due to invalid IL or missing references)
			//IL_021d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0222: Unknown result type (might be due to invalid IL or missing references)
			//IL_022d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0232: Unknown result type (might be due to invalid IL or missing references)
			//IL_0179: Unknown result type (might be due to invalid IL or missing references)
			//IL_017e: Unknown result type (might be due to invalid IL or missing references)
			//IL_029a: Unknown result type (might be due to invalid IL or missing references)
			//IL_029f: Unknown result type (might be due to invalid IL or missing references)
			InventoryGui instance = InventoryGui.instance;
			if ((Object)(object)instance == (Object)null || (Object)(object)instance.m_crafting == (Object)null)
			{
				return false;
			}
			Texture2D val = TextureLoader.LoadUITexture("PanelBackground");
			if ((Object)(object)val != (Object)null)
			{
				_bgSprite = Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), new Vector2(0.5f, 0.5f));
			}
			if ((Object)(object)instance.m_recipeElementPrefab == (Object)null)
			{
				return false;
			}
			_recipeElementPrefab = Object.Instantiate<GameObject>(instance.m_recipeElementPrefab);
			_recipeElementPrefab.SetActive(false);
			Object.DontDestroyOnLoad((Object)(object)_recipeElementPrefab);
			StripVanillaComponents(_recipeElementPrefab);
			Texture2D val2 = TextureLoader.LoadUITexture("SearchBarBackground");
			if ((Object)(object)val2 != (Object)null)
			{
				_textFieldSprite = Sprite.Create(val2, new Rect(0f, 0f, (float)((Texture)val2).width, (float)((Texture)val2).height), new Vector2(0.5f, 0.5f));
			}
			Texture2D val3 = TextureLoader.LoadUITexture("CategoryBackground");
			if ((Object)(object)val3 != (Object)null)
			{
				_catBtnSprite = Sprite.Create(val3, new Rect(0f, 0f, (float)((Texture)val3).width, (float)((Texture)val3).height), new Vector2(0.5f, 0.5f));
			}
			_craftBtnHeight = 30f;
			Rect rect;
			if ((Object)(object)instance.m_craftButton != (Object)null)
			{
				RectTransform component = ((Component)instance.m_craftButton).GetComponent<RectTransform>();
				if ((Object)(object)component != (Object)null)
				{
					rect = component.rect;
					_craftBtnHeight = Mathf.Max(((Rect)(ref rect)).height, 30f);
				}
				_buttonTemplate = Object.Instantiate<GameObject>(((Component)instance.m_craftButton).gameObject);
				((Object)_buttonTemplate).name = "ButtonTemplate";
				_buttonTemplate.SetActive(false);
				Object.DontDestroyOnLoad((Object)(object)_buttonTemplate);
			}
			if ((Object)(object)instance.m_recipeListRoot != (Object)null)
			{
				ScrollRect componentInParent = ((Component)instance.m_recipeListRoot).GetComponentInParent<ScrollRect>();
				if ((Object)(object)componentInParent != (Object)null)
				{
					_scrollSensitivity = componentInParent.scrollSensitivity;
				}
			}
			_valheimFont = FindValheimFont();
			RectTransform component2 = ((Component)instance.m_crafting).GetComponent<RectTransform>();
			rect = component2.rect;
			float width = ((Rect)(ref rect)).width;
			rect = component2.rect;
			float num = ((Rect)(ref rect)).height;
			if (width <= 10f)
			{
				width = 567f;
			}
			if (num <= 10f)
			{
				num = 480f;
			}
			float num2 = 260f;
			Transform val4 = ((Component)instance.m_crafting).transform.Find("Decription");
			if ((Object)(object)val4 != (Object)null)
			{
				RectTransform val5 = (RectTransform)(object)((val4 is RectTransform) ? val4 : null);
				if ((Object)(object)val5 != (Object)null)
				{
					rect = val5.rect;
					float width2 = ((Rect)(ref rect)).width;
					if (width2 > 10f)
					{
						num2 = width2;
					}
				}
			}
			_leftColWidth = num2;
			_midColWidth = num2 + 80f;
			_rightColWidth = num2;
			_leftPad = 6f;
			float num3 = _leftColWidth + 8f + _midColWidth + 8f + _rightColWidth;
			_panelWidth = num3 + 12f;
			_panelHeight = num * 0.9f;
			_bottomPad = 6f;
			_tabBtnHeight = Mathf.Max(_craftBtnHeight, 30f);
			_colTopInset = 6f + _tabBtnHeight + 6f;
			return true;
		}

		private RectTransform CreateColumn(string name, float xLeft, float xRight)
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Expected O, but got Unknown
			//IL_004f: 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_0079: 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_009e: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject(name, new Type[2]
			{
				typeof(RectTransform),
				typeof(Image)
			});
			val.transform.SetParent(_mainPanel.transform, false);
			RectTransform component = val.GetComponent<RectTransform>();
			component.anchorMin = new Vector2(0f, 0f);
			component.anchorMax = new Vector2(0f, 1f);
			component.pivot = new Vector2(0f, 0.5f);
			component.offsetMin = new Vector2(xLeft, _bottomPad);
			component.offsetMax = new Vector2(xRight, 0f - _colTopInset);
			ApplyPanelStyle(val.GetComponent<Image>());
			return component;
		}

		private void BuildItemListArea()
		{
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Expected O, but got Unknown
			//IL_005e: 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_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00eb: Expected O, but got Unknown
			//IL_0119: 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_014d: Unknown result type (might be due to invalid IL or missing references)
			//IL_015d: Unknown result type (might be due to invalid IL or missing references)
			//IL_016d: Unknown result type (might be due to invalid IL or missing references)
			BuildSearchBox();
			BuildCategoryFilterRow();
			GameObject val = new GameObject("ItemListScroll", new Type[3]
			{
				typeof(RectTransform),
				typeof(Image),
				typeof(Mask)
			});
			val.transform.SetParent((Transform)(object)_leftColumn, false);
			RectTransform component = val.GetComponent<RectTransform>();
			component.anchorMin = Vector2.zero;
			component.anchorMax = Vector2.one;
			component.offsetMin = new Vector2(2f, 2f);
			component.offsetMax = new Vector2(-2f, -80f);
			((Graphic)val.GetComponent<Image>()).color = new Color(0f, 0f, 0f, 0.01f);
			val.GetComponent<Mask>().showMaskGraphic = false;
			GameObject val2 = new GameObject("Content", new Type[1] { typeof(RectTransform) });
			val2.transform.SetParent(val.transform, false);
			_listRoot = val2.GetComponent<RectTransform>();
			_listRoot.anchorMin = new Vector2(0f, 1f);
			_listRoot.anchorMax = new Vector2(1f, 1f);
			_listRoot.pivot = new Vector2(0.5f, 1f);
			_listRoot.anchoredPosition = Vector2.zero;
			_listRoot.sizeDelta = Vector2.zero;
			Scrollbar val3 = CreateScrollbar(_leftPad + _leftColWidth);
			_listScrollbarGO = ((Component)val3).gameObject;
			_listScrollRect = val.AddComponent<ScrollRect>();
			_listScrollRect.content = _listRoot;
			_listScrollRect.viewport = component;
			_listScrollRect.vertical = true;
			_listScrollRect.horizontal = false;
			_listScrollRect.movementType = (MovementType)2;
			_listScrollRect.scrollSensitivity = _scrollSensitivity * 6f;
			_listScrollRect.verticalScrollbar = val3;
			_listScrollRect.verticalScrollbarVisibility = (ScrollbarVisibility)0;
		}

		private void BuildSearchBox()
		{
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Expected O, but got Unknown
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_0124: Unknown result type (might be due to invalid IL or missing references)
			//IL_012a: Expected O, but got Unknown
			//IL_0144: 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_0179: 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_01a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_020f: 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_022c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0237: Unknown result type (might be due to invalid IL or missing references)
			//IL_0242: Unknown result type (might be due to invalid IL or missing references)
			//IL_024c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0274: Unknown result type (might be due to invalid IL or missing references)
			//IL_0279: Unknown result type (might be due to invalid IL or missing references)
			//IL_0280: Unknown result type (might be due to invalid IL or missing references)
			//IL_0292: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_02eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0300: Unknown result type (might be due to invalid IL or missing references)
			//IL_03c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_03bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_03c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_03cb: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject("SearchField", new Type[2]
			{
				typeof(RectTransform),
				typeof(Image)
			});
			val.transform.SetParent((Transform)(object)_leftColumn, false);
			RectTransform component = val.GetComponent<RectTransform>();
			component.anchorMin = new Vector2(0f, 1f);
			component.anchorMax = new Vector2(1f, 1f);
			component.pivot = new Vector2(0.5f, 1f);
			component.sizeDelta = new Vector2(0f, 32f);
			component.anchoredPosition = new Vector2(0f, -2f);
			Image component2 = val.GetComponent<Image>();
			if ((Object)(object)_textFieldSprite != (Object)null)
			{
				component2.sprite = _textFieldSprite;
				component2.type = (Type)1;
				((Graphic)component2).color = Color.white;
			}
			else
			{
				((Graphic)component2).color = new Color(0.12f, 0.08f, 0.04f, 0.9f);
			}
			GameObject val2 = new GameObject("TextArea", new Type[2]
			{
				typeof(RectTransform),
				typeof(RectMask2D)
			});
			val2.transform.SetParent(val.transform, false);
			RectTransform component3 = val2.GetComponent<RectTransform>();
			component3.anchorMin = Vector2.zero;
			component3.anchorMax = Vector2.one;
			component3.offsetMin = new Vector2(8f, 2f);
			component3.offsetMax = new Vector2(-8f, -2f);
			GameObject val3 = new GameObject("Placeholder", new Type[1] { typeof(RectTransform) });
			val3.SetActive(false);
			val3.transform.SetParent(val2.transform, false);
			TextMeshProUGUI val4 = val3.AddComponent<TextMeshProUGUI>();
			if ((Object)(object)_valheimFont != (Object)null)
			{
				((TMP_Text)val4).font = _valheimFont;
			}
			((TMP_Text)val4).text = ModLocalization.Loc("to_search_placeholder");
			((TMP_Text)val4).fontSize = 16f;
			((Graphic)val4).color = new Color(0.6f, 0.55f, 0.45f, 0.7f);
			((TMP_Text)val4).alignment = (TextAlignmentOptions)4097;
			RectTransform component4 = val3.GetComponent<RectTransform>();
			component4.anchorMin = Vector2.zero;
			component4.anchorMax = Vector2.one;
			component4.offsetMin = Vector2.zero;
			component4.offsetMax = Vector2.zero;
			val3.SetActive(true);
			GameObject val5 = new GameObject("Text", new Type[1] { typeof(RectTransform) });
			val5.SetActive(false);
			val5.transform.SetParent(val2.transform, false);
			TextMeshProUGUI val6 = val5.AddComponent<TextMeshProUGUI>();
			if ((Object)(object)_valheimFont != (Object)null)
			{
				((TMP_Text)val6).font = _valheimFont;
			}
			((TMP_Text)val6).fontSize = 16f;
			((Graphic)val6).color = Color.white;
			((TMP_Text)val6).alignment = (TextAlignmentOptions)4097;
			RectTransform component5 = val5.GetComponent<RectTransform>();
			component5.anchorMin = Vector2.zero;
			component5.anchorMax = Vector2.one;
			component5.offsetMin = Vector2.zero;
			component5.offsetMax = Vector2.zero;
			val5.SetActive(true);
			_searchInput = val.AddComponent<TMP_InputField>();
			_searchInput.textViewport = component3;
			_searchInput.textComponent = (TMP_Text)(object)val6;
			_searchInput.placeholder = (Graphic)(object)val4;
			if ((Object)(object)_valheimFont != (Object)null)
			{
				_searchInput.fontAsset = _valheimFont;
			}
			_searchInput.pointSize = 16f;
			_searchInput.characterLimit = 50;
			((UnityEvent<string>)(object)_searchInput.onValueChanged).AddListener((UnityAction<string>)OnSearchChanged);
			Color baseColor = (Color)(((Object)(object)_textFieldSprite != (Object)null) ? Color.white : new Color(0.12f, 0.08f, 0.04f, 0.9f));
			AddHoverEffect(val, baseColor, 0.1f);
		}

		private void BuildCategoryFilterRow()
		{
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Expected O, but got Unknown
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: 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_00e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ef: Expected O, but got Unknown
			GameObject val = new GameObject("CategoryFilterRow", new Type[2]
			{
				typeof(RectTransform),
				typeof(Image)
			});
			val.transform.SetParent((Transform)(object)_leftColumn, false);
			RectTransform component = val.GetComponent<RectTransform>();
			component.anchorMin = new Vector2(0f, 1f);
			component.anchorMax = new Vector2(1f, 1f);
			component.pivot = new Vector2(0.5f, 1f);
			component.sizeDelta = new Vector2(-4f, 38f);
			component.anchoredPosition = new Vector2(0f, -38f);
			((Graphic)val.GetComponent<Image>()).color = new Color(0f, 0f, 0f, 0f);
			HorizontalLayoutGroup obj = val.AddComponent<HorizontalLayoutGroup>();
			((HorizontalOrVerticalLayoutGroup)obj).spacing = 2f;
			((LayoutGroup)obj).padding = new RectOffset(2, 2, 2, 2);
			((LayoutGroup)obj).childAlignment = (TextAnchor)4;
			((HorizontalOrVerticalLayoutGroup)obj).childForceExpandWidth = true;
			((HorizontalOrVerticalLayoutGroup)obj).childForceExpandHeight = true;
			((HorizontalOrVerticalLayoutGroup)obj).childControlWidth = true;
			((HorizontalOrVerticalLayoutGroup)obj).childControlHeight = true;
			_categoryFilterButtons.Clear();
			_categoryFilterKeys.Clear();
			Dictionary<string, string> dictionary = new Dictionary<string, string>
			{
				{ "Weapons", "AxeBronze" },
				{ "Armor", "HelmetTrollLeather" },
				{ "Shields", "ShieldWood" },
				{ "Ammo", "ArrowObsidian" },
				{ "Consumables", "MeadStaminaMinor" },
				{ "Materials", "Bronze" },
				{ "Utility", "BeltStrength" },
				{ "Trophies", "TrophySkeleton" },
				{ "Misc", "Coins" }
			};
			string[] categoryBuckets = CategoryBuckets;
			foreach (string text in categoryBuckets)
			{
				string value;
				string text2 = (dictionary.TryGetValue(text, out value) ? value : null);
				Sprite icon = ((text2 != null) ? GetItemIcon(text2) : null);
				Button val2 = CreateCategoryFilterButton(val.transform, text, icon);
				if ((Object)(object)val2 != (Object)null)
				{
					_categoryFilterButtons.Add(val2);
					_categoryFilterKeys.Add(text);
				}
			}
			UpdateCategoryFilterVisuals();
		}

		private Button CreateCategoryFilterButton(Transform parent, string category, Sprite icon)
		{
			//IL_0139: Unknown result type (might be due to invalid IL or missing references)
			//IL_0143: Expected O, but got Unknown
			//IL_0147: Unknown result type (might be due to invalid IL or missing references)
			//IL_0155: Unknown result type (might be due to invalid IL or missing references)
			//IL_015e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0163: Unknown result type (might be due to invalid IL or missing references)
			//IL_0167: Unknown result type (might be due to invalid IL or missing references)
			//IL_0187: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_020f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0214: Unknown result type (might be due to invalid IL or missing references)
			//IL_0226: Unknown result type (might be due to invalid IL or missing references)
			//IL_0237: Unknown result type (might be due to invalid IL or missing references)
			//IL_024c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0257: Unknown result type (might be due to invalid IL or missing references)
			//IL_0261: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)_buttonTemplate == (Object)null)
			{
				return null;
			}
			GameObject val = Object.Instantiate<GameObject>(_buttonTemplate, parent);
			((Object)val).name = "CatBtn_" + category;
			val.SetActive(true);
			for (int num = val.transform.childCount - 1; num >= 0; num--)
			{
				Object.Destroy((Object)(object)((Component)val.transform.GetChild(num)).gameObject);
			}
			Animator component = val.GetComponent<Animator>();
			if ((Object)(object)component != (Object)null)
			{
				Object.Destroy((Object)(object)component);
			}
			ContentSizeFitter component2 = val.GetComponent<ContentSizeFitter>();
			if ((Object)(object)component2 != (Object)null)
			{
				Object.Destroy((Object)(object)component2);
			}
			LayoutElement component3 = val.GetComponent<LayoutElement>();
			if ((Object)(object)component3 != (Object)null)
			{
				Object.Destroy((Object)(object)component3);
			}
			Image component4 = val.GetComponent<Image>();
			if ((Object)(object)component4 != (Object)null)
			{
				if ((Object)(object)_catBtnSprite != (Object)null)
				{
					component4.sprite = _catBtnSprite;
					component4.type = (Type)1;
				}
				((Graphic)component4).color = Color.white;
			}
			Button component5 = val.GetComponent<Button>();
			if ((Object)(object)component5 != (Object)null)
			{
				((UnityEventBase)component5.onClick).RemoveAllListeners();
				((Selectable)component5).transition = (Transition)1;
				string cat = category;
				((UnityEvent)component5.onClick).AddListener((UnityAction)delegate
				{
					OnCategoryFilterClicked(cat);
				});
				Navigation navigation = default(Navigation);
				((Navigation)(ref navigation)).mode = (Mode)0;
				((Selectable)component5).navigation = navigation;
				ColorBlock colors = ((Selectable)component5).colors;
				((ColorBlock)(ref colors)).normalColor = Color.white;
				((ColorBlock)(ref colors)).highlightedColor = new Color(0.85f, 0.85f, 0.85f, 1f);
				((ColorBlock)(ref colors)).pressedColor = new Color(0.65f, 0.65f, 0.65f, 1f);
				((ColorBlock)(ref colors)).selectedColor = Color.white;
				((ColorBlock)(ref colors)).colorMultiplier = 1f;
				((ColorBlock)(ref colors)).fadeDuration = 0.08f;
				((Selectable)component5).colors = colors;
			}
			if ((Object)(object)icon != (Object)null)
			{
				GameObject val2 = new GameObject("Icon", new Type[2]
				{
					typeof(RectTransform),
					typeof(Image)
				});
				val2.transform.SetParent(val.transform, false);
				RectTransform component6 = val2.GetComponent<RectTransform>();
				component6.anchorMin = new Vector2(0.15f, 0.15f);
				component6.anchorMax = new Vector2(0.85f, 0.85f);
				component6.offsetMin = Vector2.zero;
				component6.offsetMax = Vector2.zero;
				Image component7 = val2.GetComponent<Image>();
				component7.sprite = icon;
				component7.preserveAspect = true;
				((Graphic)component7).raycastTarget = false;
			}
			return component5;
		}

		private void OnCategoryFilterClicked(string category)
		{
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			_activeCategoryFilter = ((_activeCategoryFilter == category) ? null : category);
			_selectedBuyIndex = -1;
			_selectedSellIndex = -1;
			UpdateCategoryFilterVisuals();
			if ((Object)(object)_listScrollRect != (Object)null)
			{
				_listScrollRect.verticalNormalizedPosition = 1f;
				_listScrollRect.velocity = Vector2.zero;
			}
			PopulateCurrentList();
		}

		private void UpdateCategoryFilterVisuals()
		{
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			for (int i = 0; i < _categoryFilterButtons.Count; i++)
			{
				Button val = _categoryFilterButtons[i];
				if (!((Object)(object)val == (Object)null))
				{
					bool flag = _activeCategoryFilter == _categoryFilterKeys[i];
					bool flag2 = _joyCategoryFocusIndex == i;
					Image component = ((Component)val).GetComponent<Image>();
					if ((Object)(object)component != (Object)null)
					{
						((Graphic)component).color = (Color)(flag ? new Color(1f, 0.75f, 0.3f, 1f) : (flag2 ? new Color(0.85f, 0.75f, 0.6f, 1f) : Color.white));
					}
				}
			}
		}

		private static Sprite GetItemIcon(string prefabName)
		{
			if ((Object)(object)ObjectDB.instance == (Object)null)
			{
				return null;
			}
			GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(prefabName);
			ItemDrop obj = ((itemPrefab != null) ? itemPrefab.GetComponent<ItemDrop>() : null);
			if (obj == null)
			{
				return null;
			}
			ItemData itemData = obj.m_itemData;
			if (itemData == null)
			{
				return null;
			}
			return itemData.GetIcon();
		}

		private static Sprite FindSpriteByName(string spriteName)
		{
			Sprite[] array = Resources.FindObjectsOfTypeAll<Sprite>();
			foreach (Sprite val in array)
			{
				if ((Object)(object)val != (Object)null && ((Object)val).name.Equals(spriteName, StringComparison.OrdinalIgnoreCase))
				{
					return val;
				}
			}
			return null;
		}

		private void BuildDescriptionColumn()
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Expected O, but got Unknown
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0100: Unknown result type (might be due to invalid IL or missing references)
			//IL_0114: Unknown result type (might be due to invalid IL or missing references)
			//IL_0136: Unknown result type (might be due to invalid IL or missing references)
			//IL_013c: Expected O, but got Unknown
			//IL_018f: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_020f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0224: Unknown result type (might be due to invalid IL or missing references)
			//IL_023a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0263: Unknown result type (might be due to invalid IL or missing references)
			//IL_0269: Expected O, but got Unknown
			//IL_02c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0318: Unknown result type (might be due to invalid IL or missing references)
			//IL_032d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0342: Unknown result type (might be due to invalid IL or missing references)
			//IL_0357: Unknown result type (might be due to invalid IL or missing references)
			//IL_036d: Unknown result type (might be due to invalid IL or missing references)
			//IL_05c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_05cf: Expected O, but got Unknown
			//IL_05ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_05f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_060c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0622: Unknown result type (might be due to invalid IL or missing references)
			//IL_0647: Unknown result type (might be due to invalid IL or missing references)
			//IL_0676: Unknown result type (might be due to invalid IL or missing references)
			//IL_067d: Expected O, but got Unknown
			//IL_06db: Unknown result type (might be due to invalid IL or missing references)
			//IL_073e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0754: Unknown result type (might be due to invalid IL or missing references)
			//IL_076a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0776: Unknown result type (might be due to invalid IL or missing references)
			//IL_0782: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_03f9: Expected O, but got Unknown
			//IL_040d: Unknown result type (might be due to invalid IL or missing references)
			//IL_041b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0436: Unknown result type (might be due to invalid IL or missing references)
			//IL_043e: Unknown result type (might be due to invalid IL or missing references)
			//IL_045e: Unknown result type (might be due to invalid IL or missing references)
			//IL_047e: Unknown result type (might be due to invalid IL or missing references)
			//IL_048a: Unknown result type (might be due to invalid IL or missing references)
			//IL_04aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_04cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0534: Unknown result type (might be due to invalid IL or missing references)
			//IL_0549: Unknown result type (might be due to invalid IL or missing references)
			//IL_055e: Unknown result type (might be due to invalid IL or missing references)
			//IL_056f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0583: Unknown result type (might be due to invalid IL or missing references)
			float craftBtnHeight = _craftBtnHeight;
			GameObject val = new GameObject("ItemName", new Type[1] { typeof(RectTransform) });
			val.SetActive(false);
			val.transform.SetParent((Transform)(object)_middleColumn, false);
			_itemNameText = (TMP_Text)(object)val.AddComponent<TextMeshProUGUI>();
			if ((Object)(object)_valheimFont != (Object)null)
			{
				_itemNameText.font = _valheimFont;
			}
			_itemNameText.fontSize = 24f;
			((Graphic)_itemNameText).color = Color.white;
			_itemNameText.alignment = (TextAlignmentOptions)514;
			_itemNameText.text = "";
			val.SetActive(true);
			RectTransform component = val.GetComponent<RectTransform>();
			component.anchorMin = new Vector2(0f, 1f);
			component.anchorMax = new Vector2(1f, 1f);
			component.pivot = new Vector2(0.5f, 1f);
			component.sizeDelta = new Vector2(-20f, 32f);
			component.anchoredPosition = new Vector2(0f, -4f);
			GameObject val2 = new GameObject("QuantityLabel", new Type[1] { typeof(RectTransform) });
			val2.transform.SetParent((Transform)(object)_middleColumn, false);
			_quantityLabel = (TMP_Text)(object)val2.AddComponent<TextMeshProUGUI>();
			if ((Object)(object)_valheimFont != (Object)null)
			{
				_quantityLabel.font = _valheimFont;
			}
			_quantityLabel.fontSize = 18f;
			((Graphic)_quantityLabel).color = Color.white;
			_quantityLabel.alignment = (TextAlignmentOptions)514;
			_quantityLabel.text = ModLocalization.LocFmt("to_qty_label", 1);
			val2.SetActive(true);
			RectTransform component2 = val2.GetComponent<RectTransform>();
			component2.anchorMin = new Vector2(0f, 0f);
			component2.anchorMax = new Vector2(1f, 0f);
			component2.pivot = new Vector2(0.5f, 0f);
			component2.sizeDelta = new Vector2(-24f, 20f);
			component2.anchoredPosition = new Vector2(0f, craftBtnHeight + 36f);
			BuildQuantitySlider(craftBtnHeight);
			GameObject val3 = new GameObject("CoinDisplay", new Type[1] { typeof(RectTransform) });
			val3.SetActive(false);
			val3.transform.SetParent((Transform)(object)_middleColumn, false);
			_coinDisplayText = (TMP_Text)(object)val3.AddComponent<TextMeshProUGUI>();
			if ((Object)(object)_valheimFont != (Object)null)
			{
				_coinDisplayText.font = _valheimFont;
			}
			_coinDisplayText.fontSize = 24f;
			((Graphic)_coinDisplayText).color = GoldTextColor;
			_coinDisplayText.alignment = (TextAlignmentOptions)514;
			_coinDisplayText.text = ModLocalization.LocFmt("to_coins_display", "0");
			val3.SetActive(true);
			RectTransform component3 = val3.GetComponent<RectTransform>();
			component3.anchorMin = new Vector2(0f, 0f);
			component3.anchorMax = new Vector2(1f, 0f);
			component3.pivot = new Vector2(0.5f, 0f);
			component3.sizeDelta = new Vector2(-24f, 24f);
			component3.anchoredPosition = new Vector2(0f, craftBtnHeight + 60f);
			if ((Object)(object)_buttonTemplate != (Object)null)
			{
				GameObject val4 = Object.Instantiate<GameObject>(_buttonTemplate, (Transform)(object)_middleColumn);
				((Object)val4).name = "ActionButton";
				val4.SetActive(true);
				_actionButton = val4.GetComponent<Button>();
				if ((Object)(object)_actionButton != (Object)null)
				{
					((UnityEventBase)_actionButton.onClick).RemoveAllListeners();
					((UnityEvent)_actionButton.onClick).AddListener(new UnityAction(OnActionButtonClicked));
					((Selectable)_actionButton).interactable = false;
					Button actionButton = _actionButton;
					Navigation navigation = default(Navigation);
					((Navigation)(ref navigation)).mode = (Mode)0;
					((Selectable)actionButton).navigation = navigation;
					((Selectable)_actionButton).transition = (Transition)1;
					Button actionButton2 = _actionButton;
					ColorBlock colors = default(ColorBlock);
					((ColorBlock)(ref colors)).normalColor = Color.white;
					((ColorBlock)(ref colors)).highlightedColor = new Color(1f, 0.9f, 0.7f, 1f);
					((ColorBlock)(ref colors)).pressedColor = new Color(0.85f, 0.75f, 0.55f, 1f);
					((ColorBlock)(ref colors)).selectedColor = Color.white;
					((ColorBlock)(ref colors)).disabledColor = new Color(0.6f, 0.6f, 0.6f, 1f);
					((ColorBlock)(ref colors)).colorMultiplier = 1f;
					((ColorBlock)(ref colors)).fadeDuration = 0.1f;
					((Selectable)actionButton2).colors = colors;
				}
				_actionButtonLabel = val4.GetComponentInChildren<TMP_Text>(true);
				if ((Object)(object)_actionButtonLabel != (Object)null)
				{
					((Component)_actionButtonLabel).gameObject.SetActive(true);
					_actionButtonLabel.text = ModLocalization.Loc("to_btn_select_item");
				}
				StripButtonHints(val4, _actionButtonLabel);
				RectTransform component4 = val4.GetComponent<RectTransform>();
				component4.anchorMin = new Vector2(0f, 0f);
				component4.anchorMax = new Vector2(1f, 0f);
				component4.pivot = new Vector2(0.5f, 0f);
				component4.sizeDelta = new Vector2(-24f, craftBtnHeight);
				component4.anchoredPosition = new Vector2(0f, 8f);
			}
			float num = craftBtnHeight + 90f;
			GameObject val5 = new GameObject("DescScrollArea", new Type[3]
			{
				typeof(RectTransform),
				typeof(Image),
				typeof(Mask)
			});
			val5.transform.SetParent((Transform)(object)_middleColumn, false);
			RectTransform component5 = val5.GetComponent<RectTransform>();
			component5.anchorMin = Vector2.zero;
			component5.anchorMax = Vector2.one;
			component5.offsetMin = new Vector2(8f, num);
			component5.offsetMax = new Vector2(-14f, -38f);
			((Graphic)val5.GetComponent<Image>()).color = new Color(1f, 1f, 1f, 0.003f);
			val5.GetComponent<Mask>().showMaskGraphic = false;
			GameObject val6 = new GameObject("DescText", new Type[1] { typeof(RectTransform) });
			val6.SetActive(false);
			val6.transform.SetParent(val5.transform, false);
			_itemDescText = (TMP_Text)(object)val6.AddComponent<TextMeshProUGUI>();
			if ((Object)(object)_valheimFont != (Object)null)
			{
				_itemDescText.font = _valheimFont;
			}
			_itemDescText.fontSize = 18f;
			((Graphic)_itemDescText).color = Color.white;
			_itemDescText.alignment = (TextAlignmentOptions)257;
			_itemDescText.textWrappingMode = (TextWrappingModes)1;
			_itemDescText.overflowMode = (TextOverflowModes)0;
			_itemDescText.richText = true;
			_itemDescText.text = "";
			RectTransform component6 = val6.GetComponent<RectTransform>();
			component6.anchorMin = new Vector2(0f, 1f);
			component6.anchorMax = new Vector2(1f, 1f);
			component6.pivot = new Vector2(0.5f, 1f);
			component6.anchoredPosition = Vector2.zero;
			component6.sizeDelta = Vector2.zero;
			val6.AddComponent<ContentSizeFitter>().verticalFit = (FitMode)2;
			val6.SetActive(true);
			Scrollbar val7 = CreateScrollbar(_leftPad + _leftColWidth + 8f + _midColWidth);
			_descScrollbarGO = ((Component)val7).gameObject;
			_descScrollRect = val5.AddComponent<ScrollRect>();
			_descScrollRect.content = component6;
			_descScrollRect.viewport = component5;
			_descScrollRect.vertical = true;
			_descScrollRect.horizontal = false;
			_descScrollRect.movementType = (MovementType)2;
			_descScrollRect.scrollSensitivity = _scrollSensitivity * 8f;
			_descScrollRect.verticalScrollbar = val7;
			_descScrollRect.verticalScrollbarVisibility = (ScrollbarVisibility)0;
		}

		private void BuildQuantitySlider(float btnH)
		{
			//IL_0118: Unknown result type (might be due to invalid IL or missing references)
			//IL_012d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0142: Unknown result type (might be due to invalid IL or missing references)
			//IL_0153: Unknown result type (might be due to invalid IL or missing references)
			//IL_0163: Unknown result type (might be due to invalid IL or missing references)
			//IL_027a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0288: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_02cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_0310: Unknown result type (might be due to invalid IL or missing references)
			//IL_0238: Unknown result type (might be due to invalid IL or missing references)
			//IL_0369: Unknown result type (might be due to invalid IL or missing references)
			//IL_0343: Unknown result type (might be due to invalid IL or missing references)
			float num = 30f;
			float num2 = btnH + 12f;
			Slider val = InventoryGui.instance?.m_splitSlider;
			GameObject val2;
			Slider val3;
			if ((Object)(object)val != (Object)null)
			{
				val2 = Object.Instantiate<GameObject>(((Component)val).gameObject, (Transform)(object)_middleColumn);
				((Object)val2).name = "QuantitySlider";
				val2.SetActive(true);
				StripVanillaComponents(val2);
				LayoutElement component = val2.GetComponent<LayoutElement>();
				if ((Object)(object)component != (Object)null)
				{
					Object.Destroy((Object)(object)component);
				}
				val3 = val2.GetComponent<Slider>();
				if ((Object)(object)val3 == (Object)null)
				{
					TraderOverhaulPlugin.Log.LogWarning((object)"[TraderUI] Cloned split slider missing Slider component; using fallback.");
					Object.Destroy((Object)(object)val2);
					val3 = CreateFallbackQuantitySlider((Transform)(object)_middleColumn);
					val2 = (((Object)(object)val3 != (Object)null) ? ((Component)val3).gameObject : null);
				}
			}
			else
			{
				TraderOverhaulPlugin.Log.LogWarning((object)"[TraderUI] m_splitSlider not available, using fallback slider.");
				val3 = CreateFallbackQuantitySlider((Transform)(object)_middleColumn);
				val2 = (((Object)(object)val3 != (Object)null) ? ((Component)val3).gameObject : null);
			}
			if ((Object)(object)val2 == (Object)null || (Object)(object)val3 == (Object)null)
			{
				return;
			}
			_quantitySlider = val3;
			RectTransform component2 = val2.GetComponent<RectTrans