Decompiled source of DrakesRenameit v1.2.1

DrakesRenameit.dll

Decompiled 2 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Text;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using DrakeModsLibs.API;
using DrakeModsLibs.Compat;
using DrakeModsLibs.Forge;
using DrakeModsLibs.Input;
using DrakeModsLibs.Permissions;
using DrakeModsLibs.Sync;
using DrakeModsLibs.Tags;
using DrakeModsLibs.UI;
using DrakeRenameit.API;
using DrakeRenameit.Compat;
using DrakeRenameit.Compat.ArcaneWard;
using DrakeRenameit.Compat.DevCommands;
using DrakeRenameit.Compat.ItemLibs;
using DrakeRenameit.Compat.ProtectiveWards;
using DrakeRenameit.Compat.Vanilla;
using DrakeRenameit.Compat.WardIsLove;
using DrakeRenameit.Ext.UI;
using DrakeRenameit.Integration;
using DrakeRenameit.ModText;
using DrakeRenameit.Paper.Functionality;
using DrakeRenameit.Paper.Generated.Items;
using DrakeRenameit.Paper.Items;
using DrakeRenameit.Paper.Pieces;
using DrakeRenameit.Permissions;
using DrakeRenameit.UI;
using HarmonyLib;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using Jotunn.Utils;
using Microsoft.CodeAnalysis;
using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("DrakeRenameit")]
[assembly: AssemblyDescription("Manage your doors and chests better")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("DrakesWorkshop")]
[assembly: AssemblyProduct("DrakeRenameit")]
[assembly: AssemblyCopyright("Copyright ©  2025")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("5DF97E86-BF46-46C5-894F-6B2D80EA6645")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyVersion("0.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace DrakeRenameit
{
	public static class MenuKeyBinding
	{
		public static bool IsHeld(string? binding)
		{
			return MenuKeyBinding.IsHeld(binding);
		}

		public static string FormatForDisplay(string? binding)
		{
			return MenuKeyBinding.FormatForDisplay(binding, RenameItLocalization.T("menu_key_fallback"));
		}
	}
	public static class RenameitConfig
	{
		private const int ExpectedSyncedEntryCount = 59;

		private const string SectionAdmin = "01 Admin";

		private const string SectionFeatures = "02 Features";

		private const string SectionExclusions = "03 Exclusions";

		private const string SectionCraftedBy = "04 CraftedBy";

		private const string SectionGeneral = "05 General";

		private const string SectionStacks = "06 Stacks";

		private const string SectionUnlockCost = "07 UnlockCost";

		private const string SectionLimits = "08 Limits";

		private const string SectionModifiers = "09 Modifiers";

		private const string SectionPaper = "10 Paper";

		private const string SectionUI = "11 UI-NotSynced";

		private const string DisplayAdmin = "Admin";

		private const string DisplayFeatures = "Features";

		private const string DisplayExclusions = "Exclusions";

		private const string DisplayCraftedBy = "Crafted by";

		private const string DisplayGeneral = "General";

		private const string DisplayStacks = "Stacks";

		private const string DisplayUnlockCost = "Unlock cost";

		private const string DisplayLimits = "Limits";

		private const string DisplayModifiers = "Modifiers";

		private const string DisplayUI = "UI-NotSynced";

		private const string DisplayPaper = "Paper";

		private static readonly DrakeConfigSync _drakeConfigSync = DrakeConfigSync.Create("DrakesRenameit", "DrakesRenameit", "1.2.1", (string)null);

		private static ConfigEntry<bool> _lockToOwner = null;

		private static ConfigEntry<bool> _rewriteDescriptionsEnable = null;

		private static ConfigEntry<bool> _RenameEnable = null;

		private static ConfigEntry<bool> _nameClaimsOwner = null;

		private static ConfigEntry<bool> _allowAdminOverride = null;

		private static ConfigEntry<bool> _allowRenameUnownedItems = null;

		private static ConfigEntry<int> _nameCharLimit = null;

		private static ConfigEntry<int> _descCharLimit = null;

		private static ConfigEntry<int> _craftedByCharLimit = null;

		private static ConfigEntry<string> _vipList = null;

		private static ConfigEntry<bool> _configLock = null;

		private static ConfigEntry<string> _menuHintColor = null;

		private static ConfigEntry<string> _excludedNames = null;

		private static ConfigEntry<string> _excludedCategory = null;

		private static ConfigEntry<string> _renameAllowlist = null;

		private static ConfigEntry<bool> _excludeStacks = null;

		private static ConfigEntry<bool> _vipOnlyOverride = null;

		private static ConfigEntry<bool> _showDenialUi = null;

		private static ConfigEntry<bool> _showReason = null;

		private static ConfigEntry<bool> _separateStacks = null;

		private static ConfigEntry<bool> _separateStacksHardLock = null;

		private static ConfigEntry<bool> _craftedByLabelEnabled = null;

		private static ConfigEntry<bool> _craftedByLabelCustomizable = null;

		private static ConfigEntry<string> _craftedByAllowedLabels = null;

		private static ConfigEntry<string> _menuOpenModifier = null;

		private static ConfigEntry<bool> _logSpam = null;

		private static ConfigEntry<string> _serverDefaultMenuOpenModifier = null;

		private static ConfigEntry<bool> _unlockCostEnabled = null;

		private static ConfigEntry<string> _unlockCost = null;

		private static ConfigEntry<bool> _showItemStandItemNameWhenNoAccess = null;

		private static ConfigEntry<bool> _durabilityModifierEnabled = null;

		private static ConfigEntry<string> _durabilityUnbrokenLabel = null;

		private static ConfigEntry<string> _durabilityBrokenLabel = null;

		private static ConfigEntry<string> _durabilityTierModifiers = null;

		private static ConfigEntry<bool> _paperEnabled = null;

		private static ConfigEntry<string> _paperName = null;

		private static ConfigEntry<string> _paperDescription = null;

		private static ConfigEntry<string> _paperCost = null;

		private static ConfigEntry<string> _paperCraftingStation = null;

		private static ConfigEntry<float> _paperScale = null;

		private static ConfigEntry<string> _paperItemType = null;

		private static ConfigEntry<int> _blankPaperStackSize = null;

		private static ConfigEntry<int> _printedPaperStackSize = null;

		private static ConfigEntry<string> _writtenPaperName = null;

		private static ConfigEntry<string> _writtenPaperDescription = null;

		private static ConfigEntry<string> _printedPaperName = null;

		private static ConfigEntry<string> _printedPaperDescription = null;

		private static ConfigEntry<bool> _writtenPaperIgnoresRestrictions = null;

		private static ConfigEntry<bool> _publicRewriteEnabled = null;

		private static ConfigEntry<bool> _paperPlaceEnabled = null;

		private static ConfigEntry<bool> _paperTakePublicEnabled = null;

		private static ConfigEntry<bool> _paperHoldToTake = null;

		private static ConfigEntry<bool> _paperShowPageText = null;

		private static ConfigEntry<bool> _paperWallRenameEnabled = null;

		private static ConfigEntry<bool> _paperRecycleEnabled = null;

		private static ConfigEntry<bool> _paperRecycleImmutableEnabled = null;

		private static ConfigEntry<float> _paperDefaultFontSize = null;

		private static ConfigEntry<bool> _paperDefaultLandscape = null;

		private static ConfigEntry<bool> _verticalPaperPlaceable = null;

		private static ConfigEntry<bool> _horizontalPaperPlaceable = null;

		private static ConfigEntry<bool> _stackPaperPlaceable = null;

		private static ConfigEntry<string> _blankPaperPlaceOrientation = null;

		internal const string BlankPlaceVerticalOnly = "Vertical Only";

		internal const string BlankPlaceHorizontalOnly = "Horizontal Only";

		internal const string BlankPlaceBoth = "Both";

		internal static ManualLogSource? Log { get; set; }

		public static bool LockToOwner => _lockToOwner.Value;

		public static int DescCharLimit => _descCharLimit.Value;

		public static bool NameClaimsOwner => _nameClaimsOwner.Value;

		public static bool RewriteDescriptionsEnabled => _rewriteDescriptionsEnable.Value;

		public static bool RenameEnabled => _RenameEnable.Value;

		public static bool CraftedByLabelEnabled => _craftedByLabelEnabled.Value;

		public static bool CraftedByLabelCustomizable => _craftedByLabelCustomizable.Value;

		public static string CraftedByAllowedLabels => _craftedByAllowedLabels.Value;

		public static bool AllowRenameUnownedItems => _allowRenameUnownedItems.Value;

		public static bool AllowAdminOverride => _allowAdminOverride.Value;

		public static int NameCharLimit => _nameCharLimit.Value;

		public static int CraftedByCharLimit => _craftedByCharLimit.Value;

		public static string VipList => _vipList.Value;

		public static bool LockSyncedConfig => _configLock.Value;

		public static string MenuHintColor => _menuHintColor.Value;

		public static string ExcludedNames => _excludedNames.Value;

		public static string ExcludedCategory => _excludedCategory.Value;

		public static string RenameAllowlist => _renameAllowlist.Value;

		public static bool ExcludeStacks => _excludeStacks.Value;

		public static bool VipOnlyOverride => _vipOnlyOverride.Value;

		public static bool ShowDenialUi => _showDenialUi.Value;

		public static bool ShowReason => _showReason.Value;

		public static bool SeparateStacks => _separateStacks.Value;

		public static bool SeparateStacksHardLock => _separateStacksHardLock.Value;

		public static string ServerDefaultMenuOpenModifier => _serverDefaultMenuOpenModifier.Value;

		public static string MenuOpenModifier
		{
			get
			{
				if (!string.IsNullOrWhiteSpace(_menuOpenModifier.Value))
				{
					return _menuOpenModifier.Value;
				}
				return _serverDefaultMenuOpenModifier.Value;
			}
		}

		public static bool LogSpam
		{
			get
			{
				if (_logSpam != null)
				{
					return _logSpam.Value;
				}
				return false;
			}
		}

		public static bool UnlockCostEnabled => _unlockCostEnabled.Value;

		public static string UnlockCost => _unlockCost.Value;

		public static bool ShowItemStandItemNameWhenNoAccess => _showItemStandItemNameWhenNoAccess.Value;

		public static bool DurabilityModifierEnabled => _durabilityModifierEnabled.Value;

		public static string DurabilityUnbrokenLabel => _durabilityUnbrokenLabel.Value;

		public static string DurabilityBrokenLabel => _durabilityBrokenLabel.Value;

		public static string DurabilityTierModifiers => _durabilityTierModifiers.Value;

		public static bool PaperEnabled => _paperEnabled.Value;

		public static string PaperName => _paperName.Value;

		public static string PaperDescription => _paperDescription.Value;

		public static string PaperCost => _paperCost.Value;

		public static string PaperCraftingStation => _paperCraftingStation.Value;

		public static float PaperScale => Math.Max(0.25f, Math.Min(5f, _paperScale.Value));

		public static string PaperItemType => _paperItemType.Value;

		public static int BlankPaperStackSize => Math.Max(1, _blankPaperStackSize.Value);

		public static int PrintedPaperStackSize => Math.Max(1, Math.Min(100, _printedPaperStackSize?.Value ?? 50));

		public static string WrittenPaperName => _writtenPaperName.Value;

		public static string WrittenPaperDescription => _writtenPaperDescription.Value;

		public static string PrintedPaperName => _printedPaperName?.Value ?? "Printed Page";

		public static string PrintedPaperDescription => _printedPaperDescription?.Value ?? "A printed copy of a written page.";

		public static bool WrittenPaperIgnoresRestrictions => _writtenPaperIgnoresRestrictions.Value;

		public static bool PublicRewriteEnabled => _publicRewriteEnabled.Value;

		public static bool PaperPlaceEnabled => _paperPlaceEnabled.Value;

		public static bool PaperTakePublicEnabled => _paperTakePublicEnabled.Value;

		public static bool PaperHoldToTake
		{
			get
			{
				if (_paperHoldToTake != null)
				{
					return _paperHoldToTake.Value;
				}
				return true;
			}
		}

		public static bool PaperShowPageText
		{
			get
			{
				if (_paperShowPageText != null)
				{
					return _paperShowPageText.Value;
				}
				return false;
			}
		}

		public static bool PaperWallRenameEnabled
		{
			get
			{
				if (_paperWallRenameEnabled != null)
				{
					return _paperWallRenameEnabled.Value;
				}
				return false;
			}
		}

		public static bool PaperRecycleEnabled
		{
			get
			{
				if (_paperRecycleEnabled != null)
				{
					return _paperRecycleEnabled.Value;
				}
				return true;
			}
		}

		public static bool PaperRecycleImmutableEnabled
		{
			get
			{
				if (_paperRecycleImmutableEnabled != null)
				{
					return _paperRecycleImmutableEnabled.Value;
				}
				return false;
			}
		}

		public static float PaperDefaultFontSize => PaperFontScale.NormalizeStored((_paperDefaultFontSize != null) ? _paperDefaultFontSize.Value : PaperFontScale.LevelToSize(3));

		public static bool PaperDefaultLandscape
		{
			get
			{
				if (_paperDefaultLandscape != null)
				{
					return _paperDefaultLandscape.Value;
				}
				return false;
			}
		}

		public static bool VerticalPaperPlaceable => _verticalPaperPlaceable.Value;

		public static bool HorizontalPaperPlaceable => _horizontalPaperPlaceable.Value;

		public static bool StackPaperPlaceable => _stackPaperPlaceable.Value;

		public static string BlankPaperPlaceOrientation => NormalizeBlankPlaceOrientation(_blankPaperPlaceOrientation?.Value);

		public static bool BlankPaperPlaceVertical
		{
			get
			{
				string blankPaperPlaceOrientation = BlankPaperPlaceOrientation;
				if (blankPaperPlaceOrientation == "Vertical Only" || blankPaperPlaceOrientation == "Both")
				{
					return true;
				}
				return false;
			}
		}

		public static bool BlankPaperPlaceHorizontal
		{
			get
			{
				string blankPaperPlaceOrientation = BlankPaperPlaceOrientation;
				if (blankPaperPlaceOrientation == "Horizontal Only" || blankPaperPlaceOrientation == "Both")
				{
					return true;
				}
				return false;
			}
		}

		public static bool BlankPaperPlaceCanToggle => BlankPaperPlaceOrientation == "Both";

		internal static event Action? HammerPaperPlaceableChanged;

		internal static void SetSyncedVipList(string commaSeparatedEntries)
		{
			if (_vipList != null)
			{
				_vipList.Value = commaSeparatedEntries ?? "";
			}
		}

		internal static void VerboseDebug(string message)
		{
			if (LogSpam)
			{
				ManualLogSource? log = Log;
				if (log != null)
				{
					log.LogDebug((object)message);
				}
			}
		}

		internal static void VerboseInfo(string message)
		{
			if (LogSpam)
			{
				ManualLogSource? log = Log;
				if (log != null)
				{
					log.LogInfo((object)message);
				}
			}
		}

		internal static void VerboseWarning(string message)
		{
			if (LogSpam)
			{
				ManualLogSource? log = Log;
				if (log != null)
				{
					log.LogWarning((object)message);
				}
			}
		}

		internal static string NormalizeBlankPlaceOrientation(string? raw)
		{
			if (string.IsNullOrWhiteSpace(raw))
			{
				return "Both";
			}
			string text = raw.Trim();
			if (text.Equals("Vertical Only", StringComparison.OrdinalIgnoreCase) || text.Equals("VerticalOnly", StringComparison.OrdinalIgnoreCase) || text.Equals("Vertical", StringComparison.OrdinalIgnoreCase))
			{
				return "Vertical Only";
			}
			if (text.Equals("Horizontal Only", StringComparison.OrdinalIgnoreCase) || text.Equals("HorizontalOnly", StringComparison.OrdinalIgnoreCase) || text.Equals("Horizontal", StringComparison.OrdinalIgnoreCase))
			{
				return "Horizontal Only";
			}
			return "Both";
		}

		public static List<string> GetCraftedByAllowedLabelsList()
		{
			string value = _craftedByAllowedLabels.Value;
			if (string.IsNullOrWhiteSpace(value))
			{
				return new List<string> { "Crafted By", "Belongs To", "Return to" };
			}
			List<string> list = (from s in value.Split(new char[2] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries)
				select s.Trim() into s
				where s.Length > 0
				select s).ToList();
			if (list.Count == 0)
			{
				return new List<string> { "Crafted By", "Belongs To", "Return to" };
			}
			List<string> list2 = new List<string>();
			foreach (string p in list)
			{
				if (!list2.Exists((string x) => string.Equals(x, p, StringComparison.Ordinal)))
				{
					list2.Add(p);
				}
			}
			return list2;
		}

		public static void Bind(ConfigFile config)
		{
			_allowAdminOverride = _drakeConfigSync.BindSynced<bool>(config, "01 Admin", "Admin", "AllowAdminOverride", true, "If enabled, Valheim server admins and VIP list / API users may bypass ownership, exclusions, and most per-item blocks (still respects Features toggles unless elevated logic applies). Does NOT grant Valheim admin commands.");
			_configLock = _drakeConfigSync.BindSynced<bool>(config, "01 Admin", "Admin", "LockSyncedConfig", true, "When true, only Valheim server admins can change synced gameplay settings (sections 01–09 and 11 Paper). Clients cannot push config edits to the server. UI section (10) stays per-client. Strongly recommended for public servers.");
			_drakeConfigSync.AddLockingConfigEntry(_configLock);
			_vipList = _drakeConfigSync.BindSynced<string>(config, "01 Admin", "Admin", "VipList", "", "Comma- or semicolon-separated character names and/or platform user IDs (Steam ID / GetPlayerID — same as adminlist.txt IDs). Server-synced cfg only. VIP list API results are kept in memory separately and are not written here. Grants mod bypass only, not Valheim admin.");
			_vipOnlyOverride = _drakeConfigSync.BindSynced<bool>(config, "01 Admin", "Admin", "VipOnlyOverride", false, "If true (and AdminOverride is on), only VIP list / AddVIP API users are treated as elevated for bypassing rules—Valheim server admin is NOT. Useful for testing VIP behavior locally. If false, Valheim admin OR VIP is elevated.");
			_RenameEnable = _drakeConfigSync.BindSynced<bool>(config, "02 Features", "Features", "RenameEnabled", true, "If enabled, players may edit item display names (subject to all other rules). Turn off to freeze names on new edits while leaving descriptions/crafted-by alone.");
			_rewriteDescriptionsEnable = _drakeConfigSync.BindSynced<bool>(config, "02 Features", "Features", "RewriteDescriptionsEnabled", true, "If enabled, players may edit item descriptions. Turn off to pre-place lore text and block further description changes.");
			_craftedByLabelEnabled = _drakeConfigSync.BindSynced<bool>(config, "02 Features", "Features", "CraftedByLabelEnabled", true, "If true, players may set a display-only override for the crafted-by line (real crafter id/name unchanged).");
			_publicRewriteEnabled = _drakeConfigSync.BindSynced<bool>(config, "02 Features", "Features", "PublicRewriteEnabled", true, "If true, items flagged Shared (Drake_PublicRewrite) allow non-owners to edit name and description. Crafted-by is never opened by this flag. Default on.");
			_excludedNames = _drakeConfigSync.BindSynced<string>(config, "03 Exclusions", "Exclusions", "ExcludedNames", "", "Comma-separated entries: Jotunn Token ($item_...) OR Item spawn name (AxeStone) OR English display name. Admins/VIP ignore when AdminOverride is on. See ExcludedCategory and RenameAllowlist.");
			_excludedCategory = _drakeConfigSync.BindSynced<string>(config, "03 Exclusions", "Exclusions", "ExcludedCategory", "", "Comma-separated category tokens (non-elevated players). Examples: Swords,Armor,Material,Bows. Reference file: BepInEx/config/<mod GUID>/ExcludedCategoryReference.txt on first run or version change.");
			_renameAllowlist = _drakeConfigSync.BindSynced<string>(config, "03 Exclusions", "Exclusions", "RenameAllowlist", "", "Comma-separated entries (same format as ExcludedNames). When RenameEnabled / RewriteDescriptionsEnabled are ON, these items bypass ExcludedNames, ExcludedCategory, ExcludeStacks, and the unowned (AllowRenameUnownedItems) rule. Does NOT bypass global Features toggles when those are off. Does not bypass LockToOwner.");
			_craftedByLabelCustomizable = _drakeConfigSync.BindSynced<bool>(config, "04 CraftedBy", "Crafted by", "LabelCustomizable", true, "If true, players who can edit crafted-by may choose a tooltip line label from AllowedLabels. If false, the label picker is greyed out for normal players (default line only) while admins/VIPs can still change it.");
			_craftedByAllowedLabels = _drakeConfigSync.BindSynced<string>(config, "04 CraftedBy", "Crafted by", "AllowedLabels", "Crafted By, Belongs To, Return to", "Comma- or semicolon-separated labels shown before the crafter name (e.g. “Belongs To: Name”). The first entry is the default (vanilla localized crafted-by line when that option is selected).");
			_lockToOwner = _drakeConfigSync.BindSynced<bool>(config, "05 General", "General", "LockToOwner", true, "If true, only the crafter/owner can rename the item, edit its description, or crafted-by display. Items with no crafter (unowned stacks) are not locked until someone claims them (NameClaimsOwner) or the item is crafted.");
			_nameClaimsOwner = _drakeConfigSync.BindSynced<bool>(config, "05 General", "General", "NameClaimsOwner", true, "If true, renaming an unowned item assigns ownership to the renamer. Used with LockToOwner: the first successful rename on an unclaimed stack makes you the owner.");
			_allowRenameUnownedItems = _drakeConfigSync.BindSynced<bool>(config, "05 General", "General", "AllowRenameUnownedItems", true, "If true, unowned items may be renamed or given a description/crafted-by display. Unowned means no crafter id and no crafter name — e.g. picked up from the world, spawned (console/admin), loot drops, and uncrafted resource stacks. When false, those stacks are blocked unless on RenameAllowlist. Not the same as ExcludedCategory Material (that blocks by item type even when crafted). When false, NameClaimsOwner cannot claim those stacks.");
			_showDenialUi = _drakeConfigSync.BindSynced<bool>(config, "05 General", "General", "ShowDenialUi", true, "If true, access denials (not your item, excluded, rename disabled, etc.) show a red strikethrough menu hint, denial lines in tooltips, and a center message when modifier+right-click cannot open the menu. If false, those access cues are hidden. Unlock-cost, not-in-inventory, and empty-field errors are unchanged. Server-synced.");
			_showReason = _drakeConfigSync.BindSynced<bool>(config, "05 General", "General", "ShowReason", false, "If true, denial text (when ShowDenialUi is on) uses specific reasons (ownership, exclusion, unowned, etc.). If false, generic messages only. Has no effect when ShowDenialUi is off. Server-synced.");
			_showItemStandItemNameWhenNoAccess = _drakeConfigSync.BindSynced<bool>(config, "05 General", "General", "ShowItemStandItemNameWhenNoAccess", true, "If true, item stands inside warded/private areas still show 'no access' but also append the stand's current item name to the hover label (display only; permissions unchanged).");
			_serverDefaultMenuOpenModifier = _drakeConfigSync.BindSynced<string>(config, "05 General", "General", "ServerDefaultMenuOpenModifier", "Shift", "Default keys for opening the Renameit menu when a player's local MenuOpenModifier (section 11 UI-NotSynced) is empty. Set on the server/modpack for compatibility (e.g. None if another mod uses Shift). Non-empty local MenuOpenModifier always overrides on that client.");
			_separateStacks = _drakeConfigSync.BindSynced<bool>(config, "06 Stacks", "Stacks", "SeparateStacks", true, "If true, stacks only combine when Drake custom name, description, and crafted-by display match (same identity). Renamed or customized stacks no longer absorb mismatched pickups automatically.");
			_separateStacksHardLock = _drakeConfigSync.BindSynced<bool>(config, "06 Stacks", "Stacks", "SeparateStacksHardLock", false, "Only applies when SeparateStacks is on. If true, mismatched stacks never merge — including manual drags. If false, auto pickup still will not combine mismatched stacks, but you can drag one stack onto another to merge immediately (target stack keeps its custom data).");
			_excludeStacks = _drakeConfigSync.BindSynced<bool>(config, "06 Stacks", "Stacks", "ExcludeStacks", false, "When true, non-elevated players cannot rename, change descriptions, or edit crafted-by on stackable vanilla items (m_maxStackSize > 1). Admins/VIPs override when AllowAdminOverride is on. Items on RenameAllowlist bypass this. Does not change SeparateStacks merge behavior.");
			_unlockCostEnabled = _drakeConfigSync.BindSynced<bool>(config, "07 UnlockCost", "Unlock cost", "UnlockCostEnabled", false, "If true, each item stack must be unlocked once (pay UnlockCost from your inventory) before rename, description, or crafted-by edits apply. Invalid/empty UnlockCost is ignored. Elevated players skip the cost when AdminOverride applies. DevCommands nocost (Player.NoCostCheat) also skips the material cost.");
			_unlockCost = _drakeConfigSync.BindSynced<string>(config, "07 UnlockCost", "Unlock cost", "UnlockCost", "Coins:5", "Comma or semicolon separated: PrefabName:amount (e.g. Coins:4, Coal:10) or $item_token:amount. Uses player inventory. Paid once per stack via the Unlock button in the action menu. Skipped when DevCommands nocost is on.");
			_nameCharLimit = _drakeConfigSync.BindSynced<int>(config, "08 Limits", "Limits", "NameCharacterLimit", 50, "Max characters for rename text (count <color=> tag codes toward the limit).");
			_craftedByCharLimit = _drakeConfigSync.BindSynced<int>(config, "08 Limits", "Limits", "CraftedByCharLimit", 50, "Max characters for crafted-by display name (count rich-text tags toward the limit).");
			_descCharLimit = _drakeConfigSync.BindSynced<int>(config, "08 Limits", "Limits", "DescriptionCharacterLimit", 1000, "Max characters for item description (count rich-text tags toward the limit).");
			_durabilityModifierEnabled = _drakeConfigSync.BindSynced<bool>(config, "09 Modifiers", "Modifiers", "DurabilityModifierEnabled", false, "If true, prepends a durability wear label (Pristine / tiers / Broken) in front of the item name everywhere Drake builds display names — only for forge-repair gear and tools (m_useDurability), not spoilage timers. Does not change stored rename text.");
			_durabilityUnbrokenLabel = _drakeConfigSync.BindSynced<string>(config, "09 Modifiers", "Modifiers", "DurabilityUnbrokenLabel", "Pristine", "Prepended at full durability (100%). Empty = no label when pristine. Rich-text color tags allowed.");
			_durabilityBrokenLabel = _drakeConfigSync.BindSynced<string>(config, "09 Modifiers", "Modifiers", "DurabilityBrokenLabel", "<#f00>Broken</color>", "Prepended only when durability is 0 (item is broken in-game and must be repaired). Not used for worn but usable gear. Empty = no label when broken.");
			_durabilityTierModifiers = _drakeConfigSync.BindSynced<string>(config, "09 Modifiers", "Modifiers", "DurabilityTierModifiers", "{<#c50>Rusty</color>,0.4},{<#888>Worn</color>,0.6},{<#aaa>Tarnished</color>,0.8}", "Wear bands between broken and pristine: {Name,fraction} or {Name,percent}. Each applies when current/max is at or below that value; lowest matching band wins. Supports <color> tags; terminate with </color> unless you add a high threshold near 1.");
			_menuHintColor = _drakeConfigSync.BindClientOnly<string>(config, "11 UI-NotSynced", "UI-NotSynced", "MenuHintColor", "yellow", "Color for the inventory tooltip hint (Modifier + Right Click). Unity color names or hex (#fff / #ffffff). Per-client only.");
			_menuOpenModifier = _drakeConfigSync.BindClientOnly<string>(config, "11 UI-NotSynced", "UI-NotSynced", "MenuOpenModifier", "", "Optional per-client override for menu keys. Leave empty to use ServerDefaultMenuOpenModifier from the server. When set, always wins on this machine. Examples: Shift, Ctrl, Alt, Shift+Alt, F1, None. Combine with + , or &.");
			_logSpam = _drakeConfigSync.BindClientOnly<bool>(config, "11 UI-NotSynced", "UI-NotSynced", "LogSpam", false, "If true, writes verbose BepInEx logs on this client (permission allow/deny traces, localization load details, unlock-cost parse notes). Does not sync to the server. Leave off unless debugging.");
			_paperEnabled = _drakeConfigSync.BindSynced<bool>(config, "10 Paper", "Paper", "PaperEnabled", true, "If true, players can craft the Piece of Paper item (blank rename vessel). The prefab is always registered so clients stay in sync; this only toggles craftability.");
			_paperName = _drakeConfigSync.BindSynced<string>(config, "10 Paper", "Paper", "PaperName", "Piece of Paper", "Default display name for newly crafted / unrenamed Piece of Paper. Server-synced. Updates the localization token used by the item.");
			_paperDescription = _drakeConfigSync.BindSynced<string>(config, "10 Paper", "Paper", "PaperDescription", "A blank piece of paper you can write on. Renaming or rewriting the description uses one sheet and creates a Written Page.", "Default description for blank Piece of Paper. Server-synced.");
			_paperCost = _drakeConfigSync.BindSynced<string>(config, "10 Paper", "Paper", "PaperCost", "Wood:1,Coal:1", "Comma or semicolon separated recipe ingredients: PrefabName:amount (e.g. Wood:1,Coal:1). Same format as UnlockCost. Applied when the item is registered (menu/world load).");
			_paperCraftingStation = _drakeConfigSync.BindSynced<string>(config, "10 Paper", "Paper", "PaperCraftingStation", "", "Crafting station prefab for Piece of Paper (e.g. piece_workbench). Leave empty to craft anywhere from the inventory craft list.");
			_paperScale = _drakeConfigSync.BindSynced<float>(config, "10 Paper", "Paper", "PaperScale", 1.5f, "World size multiplier for blank/written paper sheets and hammer décor (1 = US Letter ~8.5×11 inches in meters). Default 1.5 (50% larger). Applied when items/pieces register; restart world/menu to re-apply.");
			_paperItemType = _drakeConfigSync.BindSynced<string>(config, "10 Paper", "Paper", "PaperItemType", "Material", "Vanilla item category for Piece of Paper / Written Page: Material or Misc. Applied when the item is registered. ExcludedCategory can also use alias 'Paper' to target these items.", (AcceptableValueBase)(object)new AcceptableValueList<string>(new string[2] { "Material", "Misc" }));
			_blankPaperStackSize = _drakeConfigSync.BindSynced<int>(config, "10 Paper", "Paper", "BlankPaperStackSize", 50, "Max stack size for blank Piece of Paper. Written Page is always stack size 1. Applied when items are registered.");
			_printedPaperStackSize = _drakeConfigSync.BindSynced<int>(config, "10 Paper", "Paper", "PrintedPaperStackSize", 50, "Max stack size for Printed Page (immutable copies). Applied when the item is registered. Default 50.");
			_writtenPaperName = _drakeConfigSync.BindSynced<string>(config, "10 Paper", "Paper", "WrittenPaperName", "Written Page", "Default display name for Written Page (before a custom name). Server-synced.");
			_writtenPaperDescription = _drakeConfigSync.BindSynced<string>(config, "10 Paper", "Paper", "WrittenPaperDescription", "A page with writing on it.", "Default description for Written Page when no custom description is set. Server-synced.");
			_printedPaperName = _drakeConfigSync.BindSynced<string>(config, "10 Paper", "Paper", "PrintedPaperName", "Printed Page", "Default display name for Printed Page (stackable copies). Server-synced.");
			_printedPaperDescription = _drakeConfigSync.BindSynced<string>(config, "10 Paper", "Paper", "PrintedPaperDescription", "A printed copy of a written page. Stackable; text is locked unless you have override.", "Default description for Printed Page when no custom description is set. Server-synced.");
			_writtenPaperIgnoresRestrictions = _drakeConfigSync.BindSynced<bool>(config, "10 Paper", "Paper", "WrittenPaperIgnoresRestrictions", false, "If true, Written Page name/description ignore RenameEnabled/RewriteDescriptions off, exclusions, and ExcludeStacks for non-elevated players. Ownership and Shared rewrite rules still apply. Owner always may edit written pages regardless.");
			_paperPlaceEnabled = _drakeConfigSync.BindSynced<bool>(config, "10 Paper", "Paper", "PaperPlaceEnabled", true, "If true, Written Page in the hotbar can open place-mode to pin parchment in the world (vertical/horizontal). Blank paper Use opens rename instead.");
			_paperTakePublicEnabled = _drakeConfigSync.BindSynced<bool>(config, "10 Paper", "Paper", "PaperTakePublicEnabled", true, "If true, the page's creator or an admin override (inside a ward that already allows them) can use Make public (Paper tab, or Shift+Use when wall-rename is off) so anyone may take it off the wall. Other players cannot flip this. Visitors still cannot place a new page or hammer-remove it. Default on.");
			_paperHoldToTake = _drakeConfigSync.BindSynced<bool>(config, "10 Paper", "Paper", "PaperHoldToTake", true, "If true, pinned Written Pages require hold-Use to take — same as vanilla item stands ($ui_hold). Prevents accidental grabs. Shift+Use edit / Make public unchanged. If false, a tap takes immediately. Default on.");
			_paperShowPageText = _drakeConfigSync.BindSynced<bool>(config, "10 Paper", "Paper", "PaperShowPageText", true, "Spike: if true, placed Written Page pieces show the custom description as readable wrapping text on blank parchment (no sign textbox; [E] still takes). Written items on the floor keep the scribble texture. Toggle may need a menu/world reload for prefab albedo. Default on.");
			_paperWallRenameEnabled = _drakeConfigSync.BindSynced<bool>(config, "10 Paper", "Paper", "PaperWallRenameEnabled", true, "If true, Shift+Use on a pinned Written Page opens the Rename|Paper menu (edit name/desc and page options without picking up). Make public moves to the Paper tab. If false, Shift+Use stays the Make public toggle. Default on.");
			_paperRecycleEnabled = _drakeConfigSync.BindSynced<bool>(config, "10 Paper", "Paper", "PaperRecycleEnabled", true, "If true, the Paper tab shows Recycle for Written Pages you own (or Shared / admin). Turns the page back into a blank Piece of Paper for free after confirm — wipes name, description, tags, and style. Printed / immutable copies also need PaperRecycleImmutableEnabled. Default on.");
			_paperRecycleImmutableEnabled = _drakeConfigSync.BindSynced<bool>(config, "10 Paper", "Paper", "PaperRecycleImmutableEnabled", false, "If true (and PaperRecycleEnabled), Recycle is also available on Printed / immutable copy stacks (returns one blank per sheet). Default off — prints were deliberately non-recyclable.");
			_paperDefaultFontSize = _drakeConfigSync.BindSynced<float>(config, "10 Paper", "Paper", "PaperDefaultFontSize", PaperFontScale.LevelToSize(3), "Default on-page ink size (TMP canvas units) when a note has no per-page override. UI levels 1–7 map ~0.055–0.28. Level 7 is the practical maximum.");
			_paperDefaultLandscape = _drakeConfigSync.BindSynced<bool>(config, "10 Paper", "Paper", "PaperDefaultLandscape", false, "Default text layout for notes with no per-page override. False = portrait (like wall pages); true = landscape lines.");
			_verticalPaperPlaceable = _drakeConfigSync.BindSynced<bool>(config, "10 Paper", "Paper", "VerticalPaperPlaceable", true, "If true, the hammer furniture piece Blank Paper (wall) can be placed. Default on.");
			_horizontalPaperPlaceable = _drakeConfigSync.BindSynced<bool>(config, "10 Paper", "Paper", "HorizontalPaperPlaceable", true, "If true, the hammer furniture piece Blank Paper (flat / table) can be placed. Default on.");
			_stackPaperPlaceable = _drakeConfigSync.BindSynced<bool>(config, "10 Paper", "Paper", "StackPaperPlaceable", true, "If true, the hammer furniture piece Paper Stack can be placed. Default on.");
			_blankPaperPlaceOrientation = _drakeConfigSync.BindSynced<string>(config, "10 Paper", "Paper", "BlankPaperPlaceOrientation", "Both", "How Written Page places from the hotbar (Use). Vertical Only or Horizontal Only: tooltip is just Use to place, and Use does not switch orientation. Both (default): Use again switches wall / flat, and the tooltip says so. Blank paper is not placeable from Use.", (AcceptableValueBase)(object)new AcceptableValueList<string>(new string[3] { "Vertical Only", "Horizontal Only", "Both" }));
			_verticalPaperPlaceable.SettingChanged += RaiseHammerPlaceableChanged;
			_horizontalPaperPlaceable.SettingChanged += RaiseHammerPlaceableChanged;
			_stackPaperPlaceable.SettingChanged += RaiseHammerPlaceableChanged;
			_paperName.SettingChanged += delegate
			{
				PaperItem.ApplyLocalizationFromConfig();
			};
			_paperDescription.SettingChanged += delegate
			{
				PaperItem.ApplyLocalizationFromConfig();
			};
			_writtenPaperName.SettingChanged += delegate
			{
				PaperItem.ApplyLocalizationFromConfig();
			};
			_writtenPaperDescription.SettingChanged += delegate
			{
				PaperItem.ApplyLocalizationFromConfig();
			};
			_durabilityModifierEnabled.SettingChanged += RefreshStandLabelsOnDurabilityConfigChange;
			_durabilityUnbrokenLabel.SettingChanged += RefreshStandLabelsOnDurabilityConfigChange;
			_durabilityBrokenLabel.SettingChanged += RefreshStandLabelsOnDurabilityConfigChange;
			_durabilityTierModifiers.SettingChanged += RefreshStandLabelsOnDurabilityConfigChange;
			MigrateLegacyConfigSections(config);
			RenameitPermission.WireVipListSync(_vipList, _drakeConfigSync);
			_drakeConfigSync.FinalizeBinding(Log, 59, (Func<bool>)(() => LockSyncedConfig));
			static void RaiseHammerPlaceableChanged(object sender, EventArgs e)
			{
				RenameitConfig.HammerPaperPlaceableChanged?.Invoke();
			}
			static void RefreshStandLabelsOnDurabilityConfigChange(object sender, EventArgs e)
			{
				CustomizeLibsAPI.RefreshItemStandDisplayNames();
			}
		}

		private static void MigrateLegacyConfigSections(ConfigFile config)
		{
			MigrateSectionKeys(config, "Admin", "01 Admin", "AllowAdminOverride", "LockSyncedConfig", "VipList", "VipOnlyOverride");
			MigrateSectionKeys(config, "Features", "02 Features", "RenameEnabled", "RewriteDescriptionsEnabled", "CraftedByLabelEnabled", "PublicRewriteEnabled");
			MigrateSectionKeys(config, "Exclusions", "03 Exclusions", "ExcludedNames", "ExcludedCategory", "RenameAllowlist");
			MigrateSectionKeys(config, "CraftedBy", "04 CraftedBy", "LabelCustomizable", "AllowedLabels");
			MigrateSectionKeys(config, "General", "05 General", "LockToOwner", "NameClaimsOwner", "AllowRenameUnownedItems", "ShowDenialUi", "ShowReason", "ShowItemStandItemNameWhenNoAccess", "ServerDefaultMenuOpenModifier");
			MigrateHideDisabledDenialUiToShowDenialUi(config);
			MigrateSectionKeys(config, "Stacks", "06 Stacks", "SeparateStacks", "SeparateStacksHardLock", "ExcludeStacks");
			MigrateSectionKeys(config, "UnlockCost", "07 UnlockCost", "UnlockCostEnabled", "UnlockCost");
			MigrateSectionKeys(config, "Limits", "08 Limits", "NameCharacterLimit", "CraftedByCharLimit", "DescriptionCharacterLimit");
			MigrateSectionKeys(config, "Modifiers", "09 Modifiers", "DurabilityModifierEnabled", "DurabilityUnbrokenLabel", "DurabilityBrokenLabel", "DurabilityTierModifiers");
			MigrateSectionKeys(config, "UI-NotSynced", "11 UI-NotSynced", "MenuHintColor", "MenuOpenModifier", "LogSpam");
			MigrateSectionKeys(config, "11 Paper", "10 Paper", "PaperEnabled", "PaperName", "PaperDescription", "PaperCost", "PaperCraftingStation", "PaperScale", "PaperItemType", "BlankPaperStackSize", "WrittenPaperName", "WrittenPaperDescription", "WrittenPaperIgnoresRestrictions", "PaperPlaceEnabled", "PaperTakePublicEnabled", "VerticalPaperPlaceable", "HorizontalPaperPlaceable", "StackPaperPlaceable", "BlankPaperPlaceOrientation");
			MigrateSectionKeys(config, "10 UI-NotSynced", "11 UI-NotSynced", "MenuHintColor", "MenuOpenModifier", "LogSpam");
			MigrateSectionKeys(config, "Stacks", "07 UnlockCost", "UnlockCostEnabled", "UnlockCost");
		}

		private static void MigrateSectionKeys(ConfigFile config, string legacySection, string newSection, params string[] keys)
		{
			foreach (string key in keys)
			{
				if (!TryMigrate<bool>(config, legacySection, key, newSection) && !TryMigrate<int>(config, legacySection, key, newSection))
				{
					TryMigrate<string>(config, legacySection, key, newSection);
				}
			}
		}

		private static bool TryMigrate<T>(ConfigFile config, string legacySection, string key, string newSection)
		{
			ConfigEntry<T> val = default(ConfigEntry<T>);
			if (!config.TryGetEntry<T>(legacySection, key, ref val))
			{
				return false;
			}
			ConfigEntry<T> val2 = default(ConfigEntry<T>);
			if (!config.TryGetEntry<T>(newSection, key, ref val2))
			{
				return false;
			}
			val2.Value = val.Value;
			return true;
		}

		private static void MigrateHideDisabledDenialUiToShowDenialUi(ConfigFile config)
		{
			string[] array = new string[2] { "05 General", "General" };
			ConfigEntry<bool> val = default(ConfigEntry<bool>);
			ConfigEntry<bool> val2 = default(ConfigEntry<bool>);
			foreach (string text in array)
			{
				if (config.TryGetEntry<bool>(text, "HideDisabledDenialUi", ref val))
				{
					if (config.TryGetEntry<bool>("05 General", "ShowDenialUi", ref val2))
					{
						val2.Value = !val.Value;
					}
					break;
				}
			}
		}
	}
	internal static class RenameUnlockCost
	{
		private static string? _cachedUnlockCostRaw;

		private static bool _cacheValid;

		private static bool _cacheOk;

		private static List<(string SharedName, int Amount, string ConfigKey)>? _cachedLines;

		private static string? _cachedError;

		internal static bool HasValidCostConfigured()
		{
			List<(string, int, string)> lines;
			string error;
			return TryBuildResolvedCost(out lines, out error);
		}

		internal static bool UnlockCostApplies()
		{
			if (RenameitConfig.UnlockCostEnabled)
			{
				return HasValidCostConfigured();
			}
			return false;
		}

		internal static bool CanPlayerAfford(Player? player)
		{
			if ((Object)(object)player == (Object)null)
			{
				return false;
			}
			if (!TryBuildResolvedCost(out List<(string, int, string)> lines, out string _))
			{
				return true;
			}
			List<(string, int)> list = new List<(string, int)>(lines.Count);
			foreach (var (item, item2, _) in lines)
			{
				list.Add((item, item2));
			}
			return InventoryCost.CanAfford(player, list);
		}

		internal static bool TryConsumeUnlockCost(Player? player, out string errorMessage)
		{
			errorMessage = "";
			if ((Object)(object)player == (Object)null)
			{
				errorMessage = RenameItLocalization.T("unlock_err_no_player");
				return false;
			}
			if (!TryBuildResolvedCost(out List<(string, int, string)> lines, out string error))
			{
				errorMessage = error ?? RenameItLocalization.T("unlock_err_not_configured");
				return false;
			}
			if (lines.Count == 0)
			{
				errorMessage = RenameItLocalization.T("unlock_err_empty");
				return false;
			}
			List<(string, int)> list = new List<(string, int)>(lines.Count);
			foreach (var (item, item2, _) in lines)
			{
				list.Add((item, item2));
			}
			return InventoryCost.TryConsume(player, list, out errorMessage, RenameItLocalization.T("unlock_err_not_enough"));
		}

		internal static string GetCostDisplayShort()
		{
			if (!TryBuildResolvedCost(out List<(string, int, string)> lines, out string _) || lines.Count == 0)
			{
				return "";
			}
			List<string> list = new List<string>();
			foreach (var item3 in lines)
			{
				string item = item3.Item1;
				int item2 = item3.Item2;
				string arg = item;
				if (Localization.instance != null)
				{
					arg = Localization.instance.Localize(item);
				}
				list.Add($"{item2}x {arg}");
			}
			return string.Join(", ", list);
		}

		internal static List<(string LocalizedName, int Amount, string PrefabName)> GetCostDisplayEntries()
		{
			List<(string, int, string)> list = new List<(string, int, string)>();
			if (!TryBuildResolvedCost(out List<(string, int, string)> lines, out string _) || lines.Count == 0)
			{
				return list;
			}
			foreach (var item5 in lines)
			{
				string item = item5.Item1;
				int item2 = item5.Item2;
				string item3 = item5.Item3;
				string item4 = item;
				if (Localization.instance != null)
				{
					item4 = Localization.instance.Localize(item);
				}
				list.Add((item4, item2, item3));
			}
			return list;
		}

		internal static string GetItemTokenPublic(string prefabName)
		{
			return ResolveItemSharedName(prefabName);
		}

		internal static Sprite? GetItemIconSprite(string configPrefabName)
		{
			if (string.IsNullOrWhiteSpace(configPrefabName) || (Object)(object)ObjectDB.instance == (Object)null)
			{
				return null;
			}
			GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(configPrefabName);
			if ((Object)(object)itemPrefab == (Object)null)
			{
				return null;
			}
			ItemDrop component = itemPrefab.GetComponent<ItemDrop>();
			if (component == null)
			{
				return null;
			}
			ItemData itemData = component.m_itemData;
			if (itemData == null)
			{
				return null;
			}
			return itemData.GetIcon();
		}

		private static bool TryBuildResolvedCost(out List<(string SharedName, int Amount, string ConfigKey)> lines, out string? error)
		{
			string text = RenameitConfig.UnlockCost?.Trim() ?? "";
			if (_cacheValid && string.Equals(_cachedUnlockCostRaw, text, StringComparison.Ordinal))
			{
				lines = _cachedLines ?? new List<(string, int, string)>();
				error = _cachedError;
				return _cacheOk;
			}
			lines = new List<(string, int, string)>();
			error = null;
			if (string.IsNullOrEmpty(text))
			{
				error = "UnlockCost is empty.";
				StoreParseCache(text, ok: false, lines, error);
				return false;
			}
			string[] array = text.Split(new char[2] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries);
			for (int i = 0; i < array.Length; i++)
			{
				string text2 = array[i].Trim();
				if (string.IsNullOrEmpty(text2))
				{
					continue;
				}
				int num = text2.LastIndexOf(':');
				if (num <= 0 || num >= text2.Length - 1)
				{
					RenameitConfig.VerboseWarning("[UnlockCost] Ignoring invalid segment (need Name:Amount): \"" + text2 + "\"");
					continue;
				}
				string text3 = text2.Substring(0, num).Trim();
				if (!int.TryParse(text2.Substring(num + 1).Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out var result) || result <= 0)
				{
					RenameitConfig.VerboseWarning("[UnlockCost] Ignoring invalid amount in: \"" + text2 + "\"");
					continue;
				}
				string text4 = ResolveItemSharedName(text3);
				if (string.IsNullOrEmpty(text4))
				{
					RenameitConfig.VerboseWarning("[UnlockCost] Unknown item or token: \"" + text3 + "\"");
				}
				else
				{
					lines.Add((text4, result, text3));
				}
			}
			if (lines.Count == 0)
			{
				error = "No valid UnlockCost entries (use Item prefab name or $item_ token, e.g. Coins:4).";
				StoreParseCache(text, ok: false, lines, error);
				return false;
			}
			StoreParseCache(text, ok: true, lines, null);
			return true;
		}

		private static void StoreParseCache(string raw, bool ok, List<(string SharedName, int Amount, string ConfigKey)> lines, string? error)
		{
			_cachedUnlockCostRaw = raw;
			_cacheValid = true;
			_cacheOk = ok;
			_cachedLines = lines;
			_cachedError = error;
		}

		private static string ResolveItemSharedName(string tokenOrPrefab)
		{
			if (string.IsNullOrWhiteSpace(tokenOrPrefab))
			{
				return "";
			}
			if ((Object)(object)ObjectDB.instance == (Object)null)
			{
				if (!tokenOrPrefab.StartsWith("$", StringComparison.Ordinal))
				{
					return "";
				}
				return tokenOrPrefab;
			}
			GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(tokenOrPrefab);
			if ((Object)(object)itemPrefab != (Object)null)
			{
				string text = itemPrefab.GetComponent<ItemDrop>()?.m_itemData?.m_shared?.m_name ?? "";
				if (!string.IsNullOrEmpty(text))
				{
					return text;
				}
			}
			if (tokenOrPrefab.StartsWith("$", StringComparison.Ordinal))
			{
				return tokenOrPrefab;
			}
			return "";
		}
	}
	internal static class ValheimHudMessage
	{
		private static readonly MethodInfo? Message5 = AccessTools.Method(typeof(Character), "Message", new Type[5]
		{
			typeof(MessageType),
			typeof(string),
			typeof(int),
			typeof(Sprite),
			typeof(bool)
		}, (Type[])null);

		private static readonly MethodInfo? Message4 = AccessTools.Method(typeof(Character), "Message", new Type[4]
		{
			typeof(MessageType),
			typeof(string),
			typeof(int),
			typeof(Sprite)
		}, (Type[])null);

		internal static void Show(Character? character, MessageType type, string? text)
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)character == (Object)null || string.IsNullOrEmpty(text))
			{
				return;
			}
			try
			{
				if (Message5 != null)
				{
					Message5.Invoke(character, new object[5] { type, text, 0, null, false });
				}
				else
				{
					Message4?.Invoke(character, new object[4] { type, text, 0, null });
				}
			}
			catch (Exception)
			{
			}
		}
	}
	internal static class InventoryCost
	{
		public static bool IsNoCostCheat(Player? player)
		{
			if ((Object)(object)player != (Object)null)
			{
				return player.NoCostCheat();
			}
			return false;
		}

		public static bool CanAfford(Player? player, IReadOnlyList<(string SharedName, int Amount)>? lines)
		{
			if ((Object)(object)player == (Object)null)
			{
				return false;
			}
			if (IsNoCostCheat(player))
			{
				return true;
			}
			if (lines == null || lines.Count == 0)
			{
				return true;
			}
			Inventory inventory = ((Humanoid)player).GetInventory();
			if (inventory == null)
			{
				return false;
			}
			foreach (var (text, num) in lines)
			{
				if (!string.IsNullOrEmpty(text) && num > 0 && inventory.CountItems(text, -1, true) < num)
				{
					return false;
				}
			}
			return true;
		}

		public static bool TryConsume(Player? player, IReadOnlyList<(string SharedName, int Amount)> lines, out string errorMessage, string? notEnoughMessage = null)
		{
			errorMessage = "";
			if ((Object)(object)player == (Object)null)
			{
				errorMessage = RenameItLocalization.T("unlock_err_no_player");
				return false;
			}
			if (IsNoCostCheat(player))
			{
				return true;
			}
			if (lines == null || lines.Count == 0)
			{
				errorMessage = RenameItLocalization.T("unlock_err_empty");
				return false;
			}
			Inventory inventory = ((Humanoid)player).GetInventory();
			if (inventory == null)
			{
				errorMessage = RenameItLocalization.T("unlock_err_no_inventory");
				return false;
			}
			foreach (var (text, num) in lines)
			{
				if (!string.IsNullOrEmpty(text) && num > 0 && inventory.CountItems(text, -1, true) < num)
				{
					errorMessage = notEnoughMessage ?? RenameItLocalization.T("unlock_err_not_enough");
					return false;
				}
			}
			foreach (var (text2, num2) in lines)
			{
				if (!string.IsNullOrEmpty(text2) && num2 > 0)
				{
					inventory.RemoveItem(text2, num2, -1, true);
				}
			}
			return true;
		}

		public static int CountHave(Player? player, string sharedName)
		{
			if ((Object)(object)player == (Object)null || string.IsNullOrEmpty(sharedName))
			{
				return 0;
			}
			Inventory inventory = ((Humanoid)player).GetInventory();
			if (inventory == null)
			{
				return 0;
			}
			return inventory.CountItems(sharedName, -1, true);
		}

		public static string HaveColor(int have, int need, bool noCostCheat)
		{
			if (!noCostCheat && have < need)
			{
				return "red";
			}
			return "lime";
		}

		public static string FormatCostLine(int amount, string localizedName, int have, bool noCostCheat)
		{
			string text = HaveColor(have, amount, noCostCheat);
			return RenameItLocalization.T("unlock_cost_line", amount, localizedName, text, have);
		}
	}
	internal static class DurabilityNameModifier
	{
		private readonly struct DurabilityModifierRules
		{
			internal string UnbrokenLabel { get; }

			internal string BrokenLabel { get; }

			internal List<DurabilityTier> Tiers { get; }

			internal DurabilityModifierRules(string unbrokenLabel, string brokenLabel, List<DurabilityTier> tiers)
			{
				UnbrokenLabel = unbrokenLabel;
				BrokenLabel = brokenLabel;
				Tiers = tiers;
			}
		}

		private readonly struct DurabilityTier
		{
			internal string Label { get; }

			internal float Threshold { get; }

			internal DurabilityTier(string label, float threshold)
			{
				Label = label.Trim();
				Threshold = threshold;
			}
		}

		private const float FullEpsilon = 0.0001f;

		private static readonly Regex TierRegex = new Regex("\\{([^}]*)\\}", RegexOptions.Compiled);

		internal static bool AffectsDisplay(ItemData? item)
		{
			return !string.IsNullOrEmpty(GetPrefixRaw(item));
		}

		internal static string GetPrefixRaw(ItemData? item)
		{
			if (!RenameitConfig.DurabilityModifierEnabled || item?.m_shared == null)
			{
				return "";
			}
			if (!TryGetDurabilityRatio(item, out var ratio))
			{
				return "";
			}
			string text = ResolveLabel(BuildRules(), item, ratio);
			if (!string.IsNullOrEmpty(text))
			{
				return text.Trim();
			}
			return "";
		}

		private static string ResolveLabel(DurabilityModifierRules rules, ItemData item, float ratio)
		{
			if (item.m_durability <= 0f)
			{
				return rules.BrokenLabel;
			}
			if (ratio >= 0.9999f)
			{
				return rules.UnbrokenLabel;
			}
			foreach (DurabilityTier tier in rules.Tiers)
			{
				if (ratio <= tier.Threshold + 0.0001f)
				{
					return tier.Label;
				}
			}
			return "";
		}

		private static DurabilityModifierRules BuildRules()
		{
			string unbrokenLabel = (RenameitConfig.DurabilityUnbrokenLabel ?? "").Trim();
			string brokenLabel = (RenameitConfig.DurabilityBrokenLabel ?? "").Trim();
			List<DurabilityTier> tiers = ParseTiers(RenameitConfig.DurabilityTierModifiers ?? "");
			return new DurabilityModifierRules(unbrokenLabel, brokenLabel, tiers);
		}

		private static List<DurabilityTier> ParseTiers(string raw)
		{
			List<DurabilityTier> list = new List<DurabilityTier>();
			if (string.IsNullOrWhiteSpace(raw))
			{
				return list;
			}
			foreach (Match item in TierRegex.Matches(raw))
			{
				if (TryParseTierInner(item.Groups[1].Value, out var tier))
				{
					list.Add(tier);
				}
			}
			list.Sort((DurabilityTier a, DurabilityTier b) => a.Threshold.CompareTo(b.Threshold));
			return list;
		}

		private static bool UsesWearTierDurabilityItem(ItemData item)
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Invalid comparison between Unknown and I4
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Invalid comparison between Unknown and I4
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Expected I4, but got Unknown
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Invalid comparison between Unknown and I4
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Expected I4, but got Unknown
			SharedData shared = item.m_shared;
			if (!shared.m_useDurability || shared.m_maxDurability <= 0f)
			{
				return false;
			}
			ItemType itemType = shared.m_itemType;
			if ((int)itemType <= 13)
			{
				switch ((int)itemType)
				{
				case 0:
					return false;
				case 1:
					return false;
				case 2:
					return false;
				}
				switch (itemType - 9)
				{
				case 0:
					return false;
				case 1:
					return false;
				case 4:
					return false;
				}
			}
			else
			{
				if ((int)itemType == 16)
				{
					return false;
				}
				if ((int)itemType == 21)
				{
					return false;
				}
			}
			return true;
		}

		private static bool TryGetDurabilityRatio(ItemData item, out float ratio)
		{
			ratio = 1f;
			if (!UsesWearTierDurabilityItem(item))
			{
				return false;
			}
			float maxDurability;
			try
			{
				maxDurability = item.GetMaxDurability();
			}
			catch
			{
				return false;
			}
			if (maxDurability <= 0f)
			{
				return false;
			}
			ratio = item.m_durability / maxDurability;
			if (ratio < 0f)
			{
				ratio = 0f;
			}
			if (ratio > 1f)
			{
				ratio = 1f;
			}
			return true;
		}

		private static bool TryParseTierInner(string inner, out DurabilityTier tier)
		{
			tier = default(DurabilityTier);
			inner = inner.Trim();
			if (inner.Length == 0)
			{
				return false;
			}
			int num = inner.LastIndexOf(',');
			if (num <= 0 || num >= inner.Length - 1)
			{
				return false;
			}
			string text = inner.Substring(0, num).Trim();
			string text2 = inner.Substring(num + 1).Trim();
			if (text.Length == 0 || text2.Length == 0)
			{
				return false;
			}
			if (!float.TryParse(text2, NumberStyles.Float, CultureInfo.InvariantCulture, out var result))
			{
				return false;
			}
			if (result > 1.0001f)
			{
				result /= 100f;
			}
			if (result < 0f)
			{
				result = 0f;
			}
			if (result > 1f)
			{
				result = 1f;
			}
			tier = new DurabilityTier(text, result);
			return true;
		}
	}
	[BepInPlugin("com.drakesworkshop.renameit", "DrakesRenameit", "1.2.1")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[NetworkCompatibility(/*Could not decode attribute arguments.*/)]
	public class DrakeRenameit : BaseUnityPlugin
	{
		public const string DrakeNewName = "Drake_Rename";

		public const string DrakeNewDesc = "Drake_Rename_Desc";

		public const string DrakeCraftedByDisplay = "Drake_CraftedByDisplay";

		public const string DrakeCraftedByLineLabel = "Drake_CraftedByLineLabel";

		public const string DrakeRenameUnlocked = "Drake_RenameUnlocked";

		public const string TooltipUnlockCostLockedEmoji = "\ud83d\udd12";

		public const string TooltipDrakeEditableEmoji = "\ud83d\udd8a\ufe0f";

		private readonly Harmony harmony = new Harmony("drakesmod.DrakeRenameit");

		public const string CompanyName = "DrakeMods";

		public const string ModName = "DrakesRenameit";

		public const string Version = "1.2.1";

		public const string GUID = "com.drakesworkshop.renameit";

		public static ItemData? CurrentItem { get; set; }

		public static bool IsItemInLocalPlayerInventory(ItemData? item)
		{
			if (item == null || (Object)(object)Player.m_localPlayer == (Object)null)
			{
				return false;
			}
			Inventory inventory = ((Humanoid)Player.m_localPlayer).GetInventory();
			if (inventory != null)
			{
				return inventory.ContainsItem(item);
			}
			return false;
		}

		public static bool IsEditableItemContext(ItemData? item)
		{
			if (!IsItemInLocalPlayerInventory(item))
			{
				return PaperWallSession.Matches(item);
			}
			return true;
		}

		private static void FlushWallSessionIfNeeded()
		{
			if (PaperWallSession.IsActive)
			{
				PaperWallSession.FlushCurrentItemToVessel();
			}
		}

		private void Awake()
		{
			RenameitConfig.Log = ((BaseUnityPlugin)this).Logger;
			RenameitConfig.Bind(((BaseUnityPlugin)this).Config);
			RenameItLocalization.Init((BaseUnityPlugin)(object)this, ((BaseUnityPlugin)this).Logger);
			ExcludedCategoryReferenceWriter.EnsureGenerated();
			try
			{
				RenameItLibsBridge.Register();
			}
			catch (Exception arg)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)$"RenameItLibsBridge.Register failed: {arg}");
			}
			try
			{
				PaperItem.Register(((BaseUnityPlugin)this).Logger, Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location) ?? "");
				PaperPlace.Register(((BaseUnityPlugin)this).Logger);
				PaperWrittenPlace.Register(((BaseUnityPlugin)this).Logger);
				PaperBlankPlace.Register(((BaseUnityPlugin)this).Logger);
			}
			catch (Exception arg2)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)$"Paper content register failed: {arg2}");
			}
			harmony.PatchAll();
			CompatibilityManager.Initialize(harmony);
		}

		private void Update()
		{
			if (Input.GetKeyDown((KeyCode)27))
			{
				UIPanels.TryHandleEscape();
			}
		}

		public static string GetPropperName(ItemData? item)
		{
			return CustomizeLibsAPI.GetProperName(item);
		}

		public static string GetDisplayNameForUi(ItemData? item, bool localize)
		{
			return CustomizeLibsAPI.GetDisplayNameForUi(item, localize);
		}

		public static bool hasNewDesc(ItemData? item)
		{
			return CustomizeLibsAPI.HasCustomDescription(item);
		}

		public static bool hasNewName(ItemData? item)
		{
			return CustomizeLibsAPI.HasCustomName(item);
		}

		public static bool HasAnyDrakeRenameCustomization(ItemData? item)
		{
			return CustomizeLibsAPI.HasAnyCustomization(item);
		}

		private static bool ReadRenameUnlockedFlag(ItemData item)
		{
			if (!item.m_customData.TryGetValue("Drake_RenameUnlocked", out var value))
			{
				return false;
			}
			if (!(value == "1"))
			{
				return string.Equals(value, "true", StringComparison.OrdinalIgnoreCase);
			}
			return true;
		}

		public static bool IsRenameUnlocked(ItemData? item)
		{
			if (item?.m_customData == null)
			{
				return false;
			}
			bool flag = ReadRenameUnlockedFlag(item);
			if (RenameUnlockCost.UnlockCostApplies())
			{
				if (!flag && HasAnyDrakeRenameCustomization(item))
				{
					SetRenameUnlocked(item);
					return true;
				}
				return flag;
			}
			return flag;
		}

		internal static void SetRenameUnlocked(ItemData item)
		{
			if (item.m_customData == null)
			{
				item.m_customData = new Dictionary<string, string>();
			}
			item.m_customData["Drake_RenameUnlocked"] = "1";
		}

		public static bool WouldHaveAnyDrakeEditIfUnlockIgnored(ItemData? item)
		{
			if (item == null || (Object)(object)Player.m_localPlayer == (Object)null)
			{
				return false;
			}
			RenamePermissionManager.BeginIgnoreUnlockRequirement();
			try
			{
				return CanChangeName(item) || CanChangeDesc(item) || CanChangeCraftedByLabel(item);
			}
			finally
			{
				RenamePermissionManager.EndIgnoreUnlockRequirement();
			}
		}

		public static bool ShowUnlockButton(ItemData? item)
		{
			if (item == null || (Object)(object)Player.m_localPlayer == (Object)null)
			{
				return false;
			}
			if (!RenameUnlockCost.UnlockCostApplies())
			{
				return false;
			}
			if (IsRenameUnlocked(item))
			{
				return false;
			}
			if (RenameitPermission.IsElevatedForOverrides(Player.m_localPlayer))
			{
				return false;
			}
			return WouldHaveAnyDrakeEditIfUnlockIgnored(item);
		}

		public static bool TryPayRenameUnlock(ItemData? item)
		{
			if (item == null || (Object)(object)Player.m_localPlayer == (Object)null)
			{
				return false;
			}
			if (!IsItemInLocalPlayerInventory(item))
			{
				ValheimHudMessage.Show((Character?)(object)Player.m_localPlayer, (MessageType)2, RenameItLocalization.T("msg_item_not_in_inventory_unlock"));
				return false;
			}
			if (!RenameUnlockCost.UnlockCostApplies() || IsRenameUnlocked(item))
			{
				return false;
			}
			if (!WouldHaveAnyDrakeEditIfUnlockIgnored(item))
			{
				if (RenameitConfig.ShowDenialUi)
				{
					string menuBlockedReason = GetMenuBlockedReason(item);
					if (!string.IsNullOrEmpty(menuBlockedReason))
					{
						ValheimHudMessage.Show((Character?)(object)Player.m_localPlayer, (MessageType)2, menuBlockedReason);
					}
				}
				return false;
			}
			if (!RenameUnlockCost.TryConsumeUnlockCost(Player.m_localPlayer, out string errorMessage))
			{
				ValheimHudMessage.Show((Character?)(object)Player.m_localPlayer, (MessageType)2, errorMessage);
				return false;
			}
			SetRenameUnlocked(item);
			ValheimHudMessage.Show((Character?)(object)Player.m_localPlayer, (MessageType)2, RenameItLocalization.T("msg_item_unlocked"));
			return true;
		}

		public static bool HasCraftedByDisplayOverride(ItemData? item)
		{
			return CustomizeLibsAPI.HasCraftedByDisplayOverride(item);
		}

		public static bool HasCraftedByLineLabelOverride(ItemData? item)
		{
			return CustomizeLibsAPI.HasCraftedByLineLabelOverride(item);
		}

		public static bool CanResetAnyCustomization(ItemData? item)
		{
			if (item == null)
			{
				return false;
			}
			if (CanChangeName(item) && hasNewName(item))
			{
				return true;
			}
			if (CanChangeDesc(item) && hasNewDesc(item))
			{
				return true;
			}
			if (HasCraftedByDisplayOverride(item) || HasCraftedByLineLabelOverride(item))
			{
				return true;
			}
			return false;
		}

		public static void ResetAllCustomizations(ItemData? item)
		{
			if (item == null)
			{
				return;
			}
			if (!IsEditableItemContext(item))
			{
				ValheimHudMessage.Show((Character?)(object)Player.m_localPlayer, (MessageType)2, RenameItLocalization.T("msg_item_not_in_inventory"));
				return;
			}
			if (CanChangeName(item) && hasNewName(item))
			{
				resetName(item);
			}
			if (CanChangeDesc(item) && hasNewDesc(item))
			{
				resetDesc(item);
			}
			if ((HasCraftedByDisplayOverride(item) || HasCraftedByLineLabelOverride(item)) && item.m_customData != null)
			{
				string craftedByDisplay = getCraftedByDisplay(item);
				CustomizeLibsAPI.ClearCraftedByOverrides(item);
				string newDisplay = item.m_crafterName ?? "";
				RenameEvents.RaiseCraftedByDisplayChanged(Player.m_localPlayer, item, item.m_shared.m_name, craftedByDisplay, newDisplay);
			}
			FlushWallSessionIfNeeded();
		}

		public static string GetVanillaDisplayName(ItemData? item)
		{
			if (item?.m_shared == null)
			{
				return "";
			}
			string text = item.m_shared.m_name ?? "";
			if (Localization.instance == null)
			{
				return text;
			}
			return Localization.instance.Localize(text);
		}

		public static string GetVanillaDisplayDesc(ItemData? item)
		{
			if (item?.m_shared == null)
			{
				return "";
			}
			string text = item.m_shared.m_description ?? "";
			if (Localization.instance == null)
			{
				return text;
			}
			return Localization.instance.Localize(text);
		}

		public static string resetName(ItemData? item)
		{
			if (item == null)
			{
				return "";
			}
			string propperName = GetPropperName(item);
			CustomizeLibsAPI.SetCustomName(item, (string)null);
			string propperName2 = GetPropperName(item);
			if (!string.Equals(propperName, propperName2, StringComparison.Ordinal))
			{
				RenameEvents.RaiseNameChanged(Player.m_localPlayer, item, propperName, propperName2);
			}
			return propperName2;
		}

		public static string resetDesc(ItemData? item)
		{
			if (item == null)
			{
				return "";
			}
			string propperDesc = getPropperDesc(item);
			CustomizeLibsAPI.SetCustomDescription(item, (string)null);
			string propperDesc2 = getPropperDesc(item);
			if (!string.Equals(propperDesc, propperDesc2, StringComparison.Ordinal))
			{
				RenameEvents.RaiseDescriptionChanged(Player.m_localPlayer, item, propperDesc, propperDesc2);
			}
			return propperDesc2;
		}

		public static string getPropperName(ItemData? item)
		{
			if (item?.m_shared == null)
			{
				return "";
			}
			return getPropperName(item, item.m_shared.m_name);
		}

		public static string getPropperName(ItemData? item, string defaultName)
		{
			return CustomizeLibsAPI.GetProperName(item, defaultName);
		}

		public static string getPropperDesc(ItemData? item)
		{
			if (item?.m_shared == null)
			{
				return "";
			}
			return getPropperDesc(item, item.m_shared.m_description);
		}

		public static string getPropperDesc(ItemData? item, string defaultDesc)
		{
			return CustomizeLibsAPI.GetProperDescription(item, defaultDesc);
		}

		public static void OpenRename(ItemData? item)
		{
			if (!((Object)(object)InventoryGui.instance == (Object)null) && item != null)
			{
				CurrentItem = item;
				UIPanels.ClearPendingFieldResets();
				if ((Object)(object)UIPanels.InputNamePanel == (Object)null)
				{
					UIPanels.CreateRenameInput();
				}
				string propperName = GetPropperName(item);
				UIPanels.RenameNameInput.text = propperName;
				UIPanels.InputNamePanel.SetActive(true);
				UIPanels.EnsureInputBlocked();
			}
		}

		public static void OpenRewriteDesc(ItemData? item)
		{
			if (!((Object)(object)InventoryGui.instance == (Object)null) && item != null)
			{
				CurrentItem = item;
				UIPanels.ClearPendingFieldResets();
				if ((Object)(object)UIPanels.InputDescPanel == (Object)null)
				{
					UIPanels.CreateRenameDescInput();
				}
				string propperDesc = getPropperDesc(item);
				UIPanels.RenameDescInput.text = propperDesc;
				UIPanels.InputDescPanel.SetActive(true);
				UIPanels.EnsureInputBlocked();
			}
		}

		public static void RenameItem(string name)
		{
			if (CurrentItem == null)
			{
				return;
			}
			Player localPlayer = Player.m_localPlayer;
			string propperName = GetPropperName(CurrentItem);
			if (string.IsNullOrEmpty(name))
			{
				if (!hasNewName(CurrentItem))
				{
					return;
				}
				CustomizeLibsAPI.SetCustomName(CurrentItem, (string)null);
				string propperName2 = GetPropperName(CurrentItem);
				if (!string.Equals(propperName, propperName2, StringComparison.Ordinal))
				{
					RenameEvents.RaiseNameChanged(localPlayer, CurrentItem, propperName, propperName2);
				}
			}
			else if (!string.Equals(propperName, name, StringComparison.Ordinal))
			{
				CustomizeLibsAPI.SetCustomName(CurrentItem, name);
				RenameEvents.RaiseNameChanged(localPlayer, CurrentItem, propperName, name);
			}
			if (RenameitConfig.NameClaimsOwner && (RenameitConfig.AllowRenameUnownedItems || RenameExclusionRules.MatchesRenameAllowlist(CurrentItem)) && string.IsNullOrEmpty(CurrentItem.m_crafterName))
			{
				Player localPlayer2 = Player.m_localPlayer;
				if ((Object)(object)localPlayer2 != (Object)null)
				{
					CurrentItem.m_crafterID = localPlayer2.GetPlayerID();
					CurrentItem.m_crafterName = localPlayer2.GetPlayerName();
				}
			}
		}

		public static void RewriteItemDesc(string name)
		{
			if (CurrentItem == null)
			{
				return;
			}
			Player localPlayer = Player.m_localPlayer;
			string propperDesc = getPropperDesc(CurrentItem);
			if (string.IsNullOrEmpty(name))
			{
				if (!hasNewDesc(CurrentItem))
				{
					return;
				}
				CustomizeLibsAPI.SetCustomDescription(CurrentItem, (string)null);
				string propperDesc2 = getPropperDesc(CurrentItem);
				if (!string.Equals(propperDesc, propperDesc2, StringComparison.Ordinal))
				{
					RenameEvents.RaiseDescriptionChanged(localPlayer, CurrentItem, propperDesc, propperDesc2);
				}
			}
			else if (!string.Equals(propperDesc, name, StringComparison.Ordinal))
			{
				CustomizeLibsAPI.SetCustomDescription(CurrentItem, name);
				RenameEvents.RaiseDescriptionChanged(localPlayer, CurrentItem, propperDesc, name);
			}
			if (RenameitConfig.NameClaimsOwner && (RenameitConfig.AllowRenameUnownedItems || RenameExclusionRules.MatchesRenameAllowlist(CurrentItem)) && string.IsNullOrEmpty(CurrentItem.m_crafterName))
			{
				Player localPlayer2 = Player.m_localPlayer;
				if ((Object)(object)localPlayer2 != (Object)null)
				{
					CurrentItem.m_crafterID = localPlayer2.GetPlayerID();
					CurrentItem.m_crafterName = localPlayer2.GetPlayerName();
				}
			}
		}

		public static void ApplyRewriteDesc(string newDesc)
		{
			if (CurrentItem == null)
			{
				return;
			}
			if (!IsEditableItemContext(CurrentItem))
			{
				ValheimHudMessage.Show((Character?)(object)Player.m_localPlayer, (MessageType)2, RenameItLocalization.T("msg_item_not_in_inventory_apply"));
				UIPanels.CloseAllRenameEditingUi();
			}
			else if (PaperItem.IsBlankPaper(CurrentItem))
			{
				if (string.IsNullOrWhiteSpace(newDesc))
				{
					UIPanels.InputDescPanel.SetActive(false);
					UIPanels.OpenActionMenu(CurrentItem);
					return;
				}
				Player localPlayer = Player.m_localPlayer;
				if (!((Object)(object)localPlayer == (Object)null))
				{
					ItemData val = PaperWriteConverter.PeelBlankToWritten(CurrentItem, null, newDesc, localPlayer);
					UIPanels.InputDescPanel.SetActive(false);
					if (val != null)
					{
						CurrentItem = val;
						UIPanels.OpenActionMenu(val);
					}
					else
					{
						UIPanels.OpenActionMenu(CurrentItem);
					}
				}
			}
			else
			{
				RewriteItemDesc(newDesc);
				FlushWallSessionIfNeeded();
				ItemData? currentItem = CurrentItem;
				UIPanels.InputDescPanel.SetActive(false);
				UIPanels.OpenActionMenu(currentItem);
			}
		}

		public static void ApplyRename(string newName)
		{
			if (CurrentItem == null)
			{
				return;
			}
			if (!IsEditableItemContext(CurrentItem))
			{
				ValheimHudMessage.Show((Character?)(object)Player.m_localPlayer, (MessageType)2, RenameItLocalization.T("msg_item_not_in_inventory_apply"));
				UIPanels.CloseAllRenameEditingUi();
			}
			else if (PaperItem.IsBlankPaper(CurrentItem))
			{
				if (string.IsNullOrWhiteSpace(newName))
				{
					UIPanels.InputNamePanel.SetActive(false);
					UIPanels.OpenActionMenu(CurrentItem);
					return;
				}
				Player localPlayer = Player.m_localPlayer;
				if (!((Object)(object)localPlayer == (Object)null))
				{
					ItemData val = PaperWriteConverter.PeelBlankToWritten(CurrentItem, newName, null, localPlayer);
					UIPanels.InputNamePanel.SetActive(false);
					if (val != null)
					{
						CurrentItem = val;
						UIPanels.OpenActionMenu(val);
					}
					else
					{
						UIPanels.OpenActionMenu(CurrentItem);
					}
				}
			}
			else
			{
				RenameItem(newName);
				FlushWallSessionIfNeeded();
				ItemData? currentItem = CurrentItem;
				UIPanels.InputNamePanel.SetActive(false);
				UIPanels.OpenActionMenu(currentItem);
			}
		}

		public static void ApplyPendingNameReset()
		{
			if (CurrentItem != null)
			{
				if (!IsEditableItemContext(CurrentItem))
				{
					ValheimHudMessage.Show((Character?)(object)Player.m_localPlayer, (MessageType)2, RenameItLocalization.T("msg_item_not_in_inventory_apply"));
					UIPanels.CloseAllRenameEditingUi();
					return;
				}
				resetName(CurrentItem);
				FlushWallSessionIfNeeded();
				ItemData? currentItem = CurrentItem;
				UIPanels.InputNamePanel.SetActive(false);
				UIPanels.OpenActionMenu(currentItem);
			}
		}

		public static void ApplyPendingDescReset()
		{
			if (CurrentItem != null)
			{
				if (!IsEditableItemContext(CurrentItem))
				{
					ValheimHudMessage.Show((Character?)(object)Player.m_localPlayer, (MessageType)2, RenameItLocalization.T("msg_item_not_in_inventory_apply"));
					UIPanels.CloseAllRenameEditingUi();
					return;
				}
				resetDesc(CurrentItem);
				FlushWallSessionIfNeeded();
				ItemData? currentItem = CurrentItem;
				UIPanels.InputDescPanel.SetActive(false);
				UIPanels.OpenActionMenu(currentItem);
			}
		}

		public static void ApplyPendingCraftedByReset()
		{
			if (CurrentItem != null)
			{
				if (!IsEditableItemContext(CurrentItem))
				{
					ValheimHudMessage.Show((Character?)(object)Player.m_localPlayer, (MessageType)2, RenameItLocalization.T("msg_item_not_in_inventory_apply"));
					UIPanels.CloseAllRenameEditingUi();
					return;
				}
				string craftedByDisplay = getCraftedByDisplay(CurrentItem);
				CustomizeLibsAPI.ClearCraftedByOverrides(CurrentItem);
				string newDisplay = CurrentItem.m_crafterName ?? "";
				RenameEvents.RaiseCraftedByDisplayChanged(Player.m_localPlayer, CurrentItem, CurrentItem.m_shared.m_name, craftedByDisplay, newDisplay);
				FlushWallSessionIfNeeded();
				ItemData? currentItem = CurrentItem;
				UIPanels.InputCraftedByPanel.SetActive(false);
				UIPanels.OpenActionMenu(currentItem);
			}
		}

		public static bool CanChangeName(ItemData? item, bool showError = false)
		{
			if (!CustomizeLibsAPI.CanPerform((CustomizeOperation)1, item, Player.m_localPlayer))
			{
				if (showError)
				{
					RenamePermissionManager.Evaluate(RenamePermissionOperation.RenameItemName, item, Player.m_localPlayer, showErrorToPlayer: true);
				}
				return false;
			}
			return true;
		}

		public static bool CanChangeDesc(ItemData item, bool showError = false)
		{
			if (!CustomizeLibsAPI.CanPerform((CustomizeOperation)2, item, Player.m_localPlayer))
			{
				if (showError)
				{
					RenamePermissionManager.Evaluate(RenamePermissionOperation.RewriteDescription, item, Player.m_localPlayer, showErrorToPlayer: true);
				}
				return false;
			}
			return true;
		}

		public static bool CanChangeCraftedByLabel(ItemData? item, bool showError = false)
		{
			if (item == null)
			{
				return false;
			}
			if (!CustomizeLibsAPI.CanPerform((CustomizeOperation)4, item, Player.m_localPlayer))
			{
				if (showError)
				{
					RenamePermissionManager.Evaluate(RenamePermissionOperation.EditCraftedByLabel, item, Player.m_localPlayer, showErrorToPlayer: true);
				}
				return false;
			}
			return true;
		}

		public static bool AnyInventoryActionAvailable(ItemData? item)
		{
			if (item == null || (Object)(object)Player.m_localPlayer == (Object)null)
			{
				return false;
			}
			if (!RenameUnlockCost.UnlockCostApplies() || IsRenameUnlocked(item))
			{
				if (!CanChangeName(item) && !CanChangeDesc(item) && !CanChangeCraftedByLabel(item))
				{
					return CanResetAnyCustomization(item);
				}
				return true;
			}
			if (RenameitPermission.IsElevatedForOverrides(Player.m_localPlayer))
			{
				if (!CanChangeName(item) && !CanChangeDesc(item) && !CanChangeCraftedByLabel(item))
				{
					return CanResetAnyCustomization(item);
				}
				return true;
			}
			return WouldHaveAnyDrakeEditIfUnlockIgnored(item);
		}

		public static bool IsMenuOpenModifierHeld()
		{
			return MenuBindingRegistry.IsHeld("inventory.context", "renameit.inventory");
		}

		public static string GetMenuTooltipLockSuffix(ItemData? item)
		{
			if (item == null || (Object)(object)Player.m_localPlayer == (Object)null)
			{
				return "";
			}
			if (!RenameUnlockCost.UnlockCostApplies())
			{
				return "";
			}
			if (RenameitPermission.IsElevatedForOverrides(Player.m_localPlayer))
			{
				return " \ud83d\udd8a\ufe0f";
			}
			if (!IsRenameUnlocked(item))
			{
				return " \ud83d\udd12";
			}
			return " \ud83d\udd8a\ufe0f";
		}

		public static string GetMenuBlockedReason(ItemData? item)
		{
			if (!RenameitConfig.ShowDenialUi)
			{
				return "";
			}
			if (item == null || (Object)(object)Player.m_localPlayer == (Object)null)
			{
				return "";
			}
			List<string> list = new List<string>();
			RenamePermissionResult renamePermissionResult = RenamePermissionManager.TryGetDenial(RenamePermissionOperation.RenameItemName, item, Player.m_localPlayer);
			if (!renamePermissionResult.Allowed && RenamePermissionManager.HasAccessDenial(renamePermissionResult.Reasons))
			{
				list.Add(RenamePermissionManager.FormatDenialForPlayer(RenamePermissionOperation.RenameItemName, renamePermissionResult.Reasons));
			}
			RenamePermissionResult renamePermissionResult2 = RenamePermissionManager.TryGetDenial(RenamePermissionOperation.RewriteDescription, item, Player.m_localPlayer);
			if (!renamePermissionResult2.Allowed && RenamePermissionManager.HasAccessDenial(renamePermissionResult2.Reasons) && (list.Count == 0 || renamePermissionResult2.Reasons != renamePermissionResult.Reasons))
			{
				list.Add(RenamePermissionManager.FormatDenialForPlayer(RenamePermissionOperation.RewriteDescription, renamePermissionResult2.Reasons));
			}
			RenamePermissionResult renamePermissionResult3 = RenamePermissionManager.TryGetDenial(RenamePermissionOperation.EditCraftedByLabel, item, Player.m_localPlayer);
			if (!renamePermissionResult3.Allowed && RenamePermissionManager.HasAccessDenial(renamePermissionResult3.Reasons) && (list.Count == 0 || (renamePermissionResult3.Reasons != renamePermissionResult.Reasons && renamePermissionResult3.Reasons != renamePermissionResult2.Reasons)))
			{
				list.Add(RenamePermissionManager.FormatDenialForPlayer(RenamePermissionOperation.EditCraftedByLabel, renamePermissionResult3.Reasons));
			}
			if (list.Count == 0)
			{
				return RenameItLocalization.T("msg_cannot_edit_item");
			}
			HashSet<string> hashSet = new HashSet<string>();
			List<string> list2 = new List<string>();
			foreach (string item2 in list)
			{
				if (hashSet.Add(item2))
				{
					list2.Add(item2);
				}
			}
			return string.Join(" | ", list2);
		}

		public static string getCraftedByDisplay(ItemData? item)
		{
			return CustomizeLibsAPI.GetCraftedByDisplay(item);
		}

		private static void EnsureLocalPlayerCrafterIfAbsent(ItemData item)
		{
			Player localPlayer = Player.m_localPlayer;
			if (!((Object)(object)localPlayer == (Object)null) && item.m_crafterID == 0L && string.IsNullOrEmpty(item.m_crafterName))
			{
				item.m_crafterID = localPlayer.GetPlayerID();
				item.m_crafterName = localPlayer.GetPlayerName();
			}
		}

		public static void OpenCraftedByEditor(ItemData? item)
		{
			if (!((Object)(object)InventoryGui.instance == (Object)null) && item != null)
			{
				CurrentItem = item;
				EnsureLocalPlayerCrafterIfAbsent(item);
				UIPanels.ClearPendingFieldResets();
				if ((Object)(object)UIPanels.InputCraftedByPanel == (Object)null)
				{
					UIPanels.CreateCraftedByInput();
				}
				UIPanels.RenameCraftedByInput.text = getCraftedByDisplay(item);
				UIPanels.RefreshCraftedByLineLabelPicker(item);
				UIPanels.InputCraftedByPanel.SetActive(true);
				UIPanels.EnsureInputBlocked();
			}
		}

		public static void ApplyCraftedByLabel(string display)
		{
			if (CurrentItem == null)
			{
				return;
			}
			if (!IsEditableItemContext(CurrentItem))
			{
				ValheimHudMessage.Show((Character?)(object)Player.m_localPlayer, (MessageType)2, RenameItLocalization.T("msg_item_not_in_inventory_apply"));
				UIPanels.CloseAllRenameEditingUi();
				return;
			}
			EnsureLocalPlayerCrafterIfAbsent(CurrentItem);
			string craftedByDisplay = getCraftedByDisplay(CurrentItem);
			CustomizeLibsAPI.SetCraftedByDisplay(CurrentItem, display);
			if (RenameitConfig.CraftedByLabelCustomizable || RenameitPermission.IsElevatedForOverrides(Player.m_localPlayer))
			{
				string craftedByLineLabelPendingToken = UIPanels.CraftedByLineLabelPendingToken;
				if (string.IsNullOrEmpty(craftedByLineLabelPendingToken))
				{
					CustomizeLibsAPI.SetCraftedByLineLabel(CurrentItem, (string)null);
				}
				else if (IsAllowedCustomCraftedByLineLabel(craftedByLineLabelPendingToken))
				{
					CustomizeLibsAPI.SetCraftedByLineLabel(CurrentItem, craftedByLineLabelPendingToken);
				}
			}
			string newDisplay = (string.IsNullOrEmpty(display) ? (CurrentItem.m_crafterName ?? "") : display);
			RenameEvents.RaiseCraftedByDisplayChanged(Player.m_localPlayer, CurrentItem, CurrentItem.m_shared.m_name, craftedByDisplay, newDisplay);
			FlushWallSessionIfNeeded();
			ItemData? currentItem = CurrentItem;
			UIPanels.InputCraftedByPanel.SetActive(false);
			UIPanels.OpenActionMenu(currentItem);
		}

		public static bool IsExcluded(ItemData? item)
		{
			return RenameExclusionRules.IsExcludedFromConfig(item);
		}

		public static bool IsRenameAllowlisted(ItemData? item)
		{
			return RenameExclusionRules.MatchesRenameAllowlist(item);
		}

		private static bool IsAllowedCustomCraftedByLineLabel(string value)
		{
			List<string> craftedByAllowedLabelsList = RenameitConfig.GetCraftedByAllowedLabelsList();
			for (int i = 1; i < craftedByAllowedLabelsList.Count; i++)
			{
				if (string.Equals(craftedByAllowedLabelsList[i], value, StringComparison.Ordinal))
				{
					return true;
				}
			}
			return false;
		}
	}
}
namespace DrakeRenameit.UI
{
	internal static class TooltipRichText
	{
		private enum RtKind
		{
			Color,
			Size
		}

		private static readonly Regex HexColorRegex = new Regex("^[0-9a-fA-F]{3,8}$", RegexOptions.Compiled);

		internal static string EnsureRichTextTagsClosedForTooltip(string? text)
		{
			if (text == null || text.Length == 0)
			{
				return "";
			}
			Stack<RtKind> stack = new Stack<RtKind>();
			int num = 0;
			while (num < text.Length)
			{
				if (text[num] != '<')
				{
					num++;
					continue;
				}
				int num2 = text.IndexOf('>', num);
				if (num2 < 0)
				{
					break;
				}
				string text2 = text.Substring(num, num2 - num + 1);
				if (text2.Length >= 2 && text2[1] == '/')
				{
					if (text2.StartsWith("</color", StringComparison.OrdinalIgnoreCase))
					{
						if (stack.Count > 0 && stack.Peek() == RtKind.Color)
						{
							stack.Pop();
						}
					}
					else if (text2.StartsWith("</size", StringComparison.OrdinalIgnoreCase) && stack.Count > 0 && stack.Peek() == RtKind.Size)
					{
						stack.Pop();
					}
				}
				else if (text2.StartsWith("<color", StringComparison.OrdinalIgnoreCase))
				{
					stack.Push(RtKind.Color);
				}
				else if (IsHashColorOpenTag(text2))
				{
					stack.Push(RtKind.Color);
				}
				else if (text2.StartsWith("<size", StringComparison.OrdinalIgnoreCase))
				{
					stack.Push(RtKind.Size);
				}
				num = num2 + 1;
			}
			if (stack.Count == 0)
			{
				return text;
			}
			StringBuilder stringBuilder = new StringBuilder(text, text.Length + stack.Count * 10);
			while (stack.Count > 0)
			{
				RtKind rtKind = stack.Pop();
				stringBuilder.Append((rtKind == RtKind.Color) ? "</color>" : "</size>");
			}
			return stringBuilder.ToString();
		}

		internal static string WrapCraftedByDisplayWithDefaultStatColorIfNeeded(string text)
		{
			if (string.IsNullOrEmpty(text))
			{
				return text;
			}
			if (HasExplicitColorMarkup(text))
			{
				return text;
			}
			return GetValheimTooltipStatColorOpenTag() + text + "</color>";
		}

		internal static bool HasExplicitColorMarkup(string text)
		{
			if (string.IsNullOrEmpty(text))
			{
				return false;
			}
			if (text.IndexOf("<color", StringComparison.OrdinalIgnoreCase) >= 0)
			{
				return true;
			}
			for (int i = 0; i < text.Length - 3; i++)
			{
				if (text[i] == '<' && text[i + 1] == '#')
				{
					int j;
					for (j = i + 2; j < text.Length && IsHex(text[j]); j++)
					{
					}
					if (j != i + 2 && j - (i + 2) >= 3 && j - (i + 2) <= 8 && j < text.Length && text[j] == '>')
					{
						return true;
					}
				}
			}
			return false;
		}

		private static bool IsHex(char c)
		{
			switch (c)
			{
			case '0':
			case '1':
			case '2':
			case '3':
			case '4':
			case '5':
			case '6':
			case '7':
			case '8':
			case '9':
			case 'A':
			case 'B':
			case 'C':
			case 'D':
			case 'E':
			case 'F':
			case 'a':
			case 'b':
			case 'c':
			case 'd':
			case 'e':
			case 'f':
				return true;
			default:
				return false;
			}
		}

		internal static string OrangeBold(string text)
		{
			return GetValheimTooltipStatColorOpenTag() + "<b>" + text + "</b></color>";
		}

		internal static string GetValheimTooltipStatColorOpenTag()
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				GUIManager instance = GUIManager.Instance;
				if (instance != null)
				{
					Color valheimOrange = instance.ValheimOrange;
					return "<color=#" + ColorUtility.ToHtmlStringRGB(valheimOrange) + ">";
				}
			}
			catch
			{
			}
			return "<color=#ff8800>";
		}

		private static bool IsHashColorOpenTag(string tag)
		{
			if (tag.Length < 5 || tag[0] != '<' || tag[1] != '#' || tag[tag.Length - 1] != '>')
			{
				return false;
			}
			string input = tag.Substring(2, tag.Length - 3);
			return HexColorRegex.IsMatch(input);
		}
	}
	public static class UIPanels
	{
		[CompilerGenerated]
		private static class <>O
		{
			public static UnityAction <0>__CloseActionMenuOnly;

			public static UnityAction <1>__CancelCraftedByEditor;

			public static UnityAction <2>__CancelNameEditor;

			public static UnityAction <3>__CancelDescEditor;
		}

		[Serializable]
		[CompilerGenerated]
		private sealed class <>c
		{
			public static readonly <>c <>9 = new <>c();

			public static Action <>9__89_0;

			public static Action <>9__89_1;

			public static Action <>9__90_0;

			public static Action <>9__90_1;

			public static Action <>9__91_0;

			public static Action <>9__91_1;

			public static UnityAction <>9__95_0;

			public static UnityAction <>9__95_1;

			public static UnityAction <>9__95_2;

			public static UnityAction <>9__95_3;

			public static UnityAction <>9__95_4;

			public static UnityAction<bool> <>9__96_0;

			public static Action <>9__104_0;

			public static Action <>9__104_1;

			public static Action <>9__105_1;

			public static UnityAction <>9__112_0;

			public static UnityAction <>9__112_1;

			public static UnityAction <>9__114_0;

			public static Action <>9__114_2;

			public static UnityAction <>9__114_1;

			public static UnityAction <>9__117_0;

			public static UnityAction <>9__124_0;

			public static Action <>9__124_2;

			public static UnityAction <>9__124_1;

			public static UnityAction <>9__125_0;

			public static Action <>9__125_3;

			public static UnityAction <>9__125_1;

			internal void <CancelNameEditor>b__89_0()
			{
				_pendingClearName = false;
				if (DrakeRenameit.CurrentItem != null && (Object)(object)RenameNameInput != (Object)null)
				{
					RenameNameInput.text = DrakeRenameit.GetPropperName(DrakeRenameit.CurrentItem);
				}
			}

			internal void <CancelNameEditor>b__89_1()
			{
				GameObject? inputNamePanel = InputNamePanel;
				if (inputNamePanel != null)
				{
					inputNamePanel.SetActive(false);
				}
			}

			internal void <CancelDescEditor>b__90_0()
			{
				_pendingClearDesc = false;
				if (DrakeRenameit.CurrentItem != null && (Object)(object)RenameDescInput != (Object)null)
				{
					RenameDescInput.text = DrakeRenameit.getPropperDesc(DrakeRenameit.CurrentItem);
				}
			}

			internal void <CancelDescEditor>b__90_1()
			{
				GameObject? inputDescPanel = InputDescPanel;
				if (inputDescPanel != null)
				{
					inputDescPanel.SetActive(false);
				}
			}

			internal void <CancelCraftedByEditor>b__91_0()
			{
				_pendingClearCraftedBy = false;
				if (DrakeRenameit.CurrentItem != null)
				{
					if ((Object)(object)RenameCraftedByInput != (Object)null)
					{
						RenameCraftedByInput.text = DrakeRenameit.getCraftedByDisplay(DrakeRenameit.CurrentItem);
					}
					RefreshCraftedByLineLabelPicker(DrakeRenameit.CurrentItem);
					CloseCraftedByLineLabelPopover();
				}
			}

			internal void <CancelCraftedByEditor>b__91_1()
			{
				GameObject? inputCraftedByPanel = InputCraftedByPanel;
				if (inputCraftedByPanel != null)
				{
					inputCraftedByPanel.SetActive(false);
				}
			}

			internal void <EnsureActionMenu>b__95_0()
			{
				ItemData currentItem = DrakeRenameit.CurrentItem;
				if (currentItem != null)
				{
					ActionMenuPanel.SetActive(false);
					OpenUnlockConfirmPanel(currentItem);
				}
			}

			internal void <EnsureActionMenu>b__95_1()
			{
				ItemData currentItem = DrakeRenameit.CurrentItem;
				HideActionMenuForSubmenu();
				if (currentItem != null)
				{
					DrakeRenameit.OpenRename(currentItem);
				}
			}

			internal void <EnsureActionMenu>b__95_2()
			{
				ItemData currentItem = DrakeRenameit.CurrentItem;
				HideActionMenuForSubmenu();
				if (currentItem != null)
				{
					DrakeRenameit.OpenRewriteDesc(currentItem);
				}
			}

			internal void <EnsureActionMenu>b__95_3()
			{
				ItemData currentItem = DrakeRenameit.CurrentItem;
				HideActionMenuForSubmenu();
				if (currentItem != null)
				{
					DrakeRenameit.OpenCraftedByEditor(currentItem);
				}
			}

			internal void <EnsureActionMenu>b__95_4()
			{
				ItemData currentItem = DrakeRenameit.CurrentItem;
				if (currentItem != null)
				{
					OpenResetAllConfirmPanel(currentItem);
				}
			}

			internal void <EnsurePublicCheckRow>b__96_0(bool on)
			{
				ItemData currentItem = DrakeRenameit.CurrentItem;
				if (currentItem == null || !RenamePermissionManager.CanChangePublicFlag(currentItem, Player.m_localPlayer))
				{
					SyncPublicRewriteToggle(currentItem);
					return;
				}
				RenamePermissionManager.SetPublicRewriteFlag(currentItem, on);
				if (PaperWallSession.Matches(currentItem))
				{
					PaperWallSession.FlushCurrentItemToVessel();
				}
			}

			internal void <OpenResetAllConfirmPanel>b__104_0()
			{
				ItemData currentItem = DrakeRenameit.CurrentItem;
				if (currentItem != null)
				{
					DrakeRenameit.ResetAllCustomizations(currentItem);
				}
				if ((Object)(object)ActionMenuPanel != (Object)null)
				{
					ActionMenuPanel.SetActive(false);
				}
				DrakeRenameit.CurrentItem = null;
				DrakeTabHost.NotifyFeatureClosed("renameit");
				EnsureInputUnblocked();
			}

			internal void <OpenResetAllConfirmPanel>b__104_1()
			{
				ItemData currentItem = DrakeRenameit.CurrentItem;
				if (currentItem != null)
				{
					GameObject? actionMenuPanel = ActionMenuPanel;
					if (actionMenuPanel != null)
					{
						actionMenuPanel.SetActive(false);
					}
					OpenActionMenu(currentItem);
				}
				else
				{
					EnsureInputBlocked();
				}
			}

			internal void <OpenFieldResetConfirm>b__105_1()
			{
				EnsureInputBlocked();
			}

			internal void <EnsureUnlockConfirmPanel>b__112_0()
			{
				ItemData currentItem = DrakeRenameit.CurrentItem;
				if (currentItem == null)
				{
					CloseUnlockConfirmPanel(reopenActionMenu: false);
				}
				else if (!DrakeRenameit.TryPayRenameUnlock(currentItem))
				{
					if (DrakeRenameit.CurrentItem == null || !DrakeRenameit.IsItemInLocalPlayerInventory(DrakeRenameit.CurrentItem))
					{
						CloseAllRenameEditingUi();
						return;
					}
					RefreshUnlockConfirmBody();
					((Selectable)_buttonConfirmUnlock).interactable = RenameUnlockCost.CanPlayerAfford(Player.m_localPlayer);
				}
				else
				{
					CloseUnlockConfirmPanel(reopenActionMenu: true);
				}
			}

			internal void <EnsureUnlockConfirmPanel>b__112_1()
			{
				CloseUnlockConfirmPanel(reopenActionMenu: false);
			}

			internal void <CreateCraftedByInput>b__114_0()
			{
				if (_pendingClearCraftedBy)
				{
					_pendingClearCraftedBy = false;
					DrakeRenameit.ApplyPendingCraftedByReset();
				}
				else
				{
					DrakeRenameit.ApplyCraftedByLabel(RenameCraftedByInput.text.Trim());
				}
			}

			internal void <CreateCraftedByInput>b__114_1()
			{
				OpenFieldResetConfirm(RenameItLocalization.T("reset_crafted_by_title"), delegate
				{
					if (DrakeRenameit.CurrentItem != null)
					{
						RenameCraftedByInput.text = DrakeRenameit.CurrentItem.m_crafterName ?? "";
					}
					List<string> craftedByAllowedLabelsList = RenameitConfig.GetCraftedByAllowedLabelsList();
					_craftedByLineLabelPendingToken = null;
					SetCraftedByLineLabelPickButtonText(craftedByAllowedLabelsList, 0);
					CloseCraftedByLineLabelPopover();
					_pendingClearCraftedBy = true;
				});
			}

			internal void <CreateCraftedByInput>b__114_2()
			{
				if (DrakeRenameit.CurrentItem != null)
				{
					RenameCraftedByInput.text = DrakeRenameit.CurrentItem.m_crafterName ?? "";
				}
				List<string> craftedByAllowedLabelsList = RenameitConfig.GetCraftedByAllowedLabelsList();
				_craftedByLineLabelPendingToken = null;
				SetCraftedByLineLabelPickButtonText(craftedByAllowedLabelsList, 0);
				CloseCraftedByLineLabelPopover();
				_pendingClearCraftedBy = true;
			}

			internal void <EnsureCraftedByLineLabelControls>b__117_0()
			{
				if (!((Object)(object)_buttonCraftedByLineLabelPick == (Object)null) && ((Selectable)_buttonCraftedByLineLabelPick).interactable)
				{
					ToggleCraftedByLineLabelPopover();
				}
			}

			internal void <CreateRenameInput>b__124_0()
			{
				if (_pendingClearName)
				{
					_pendingClearName = false;
					DrakeRenameit.ApplyPendingNameReset();
				}
				else
				{
					DrakeRenameit.ApplyRename(RenameNameInput.text.Trim());
				}
			}

			internal void <CreateRenameInput>b__124_1()
			{
				OpenFieldResetConfirm(RenameItLocalization.T("reset_name_title"), delegate
				{
					if (DrakeRenameit.CurrentItem != null && (Object)(object)RenameNameInput != (Object)null)
					{
						RenameNameInput.text = DrakeRenameit.GetVanillaDisplayName(DrakeRenameit.CurrentItem);
					}
					_pendingClearName = true;
				});
			}

			internal void <CreateRenameInput>b__124_2()
			{
				if (DrakeRenameit.CurrentItem != null && (Object)(object)RenameNameInput != (Object)null)
				{
					RenameNameInput.text = DrakeRenameit.GetVanillaDisplayName(DrakeRenameit.CurrentItem);
				}
				_pendingClearName = true;
			}

			internal void <CreateRenameDescInput>b__125_0()
			{
				if (_pendingClearDesc)
				{
					_pendingClearDesc = false;
					DrakeRenameit.ApplyPendingDescReset();
				}
				else if (string.IsNullOrEmpty(RenameDescInput.text))
				{
					<CreateRenameDescInput>g__GetPlayerAndSendError|125_2(RenameItLocalization.T("msg_desc_empty"));
				}
				else
				{
					DrakeRenameit.ApplyRewriteDesc(RenameDescInput.text.Trim());
				}
			}

			internal void <CreateRenameDescInput>b__125_1()
			{
				OpenFieldResetConfirm(RenameItLocalization.T("reset_desc_title"), delegate
				{
					if ((Object)(object)RenameDescInput != (Object)null && DrakeRenameit.CurrentItem != null)
					{
						RenameDescInput.text = DrakeRenameit.GetVanillaDisplayDesc(DrakeRenameit.CurrentItem);
					}
					_pendingClearDesc = true;
				});
			}

			internal void <CreateRenameDescInput>b__125_3()
			{
				if ((Object)(object)RenameDescInput != (Object)null && DrakeRenameit.CurrentItem != null)
				{
					RenameDescInput.text = DrakeRenameit.GetVanillaDisplayDesc(DrakeRenameit.CurrentItem);
				}
				_pendingClearDesc = true;
			}
		}

		private static Button _buttonOkName = null;

		private static Button _buttonOkDesc = null;

		private static Button _buttonCancelName = null;

		private static Button _buttonCancelDesc = null;

		private static Button? _buttonResetName = null;

		private static Button? _buttonResetDesc = null;

		private static GameObject? _publicRow;

		private static Toggle? _publicToggle;

		private static Text? _publicTipText;

		private static GameObject? _publicHoverTip;

		private static Button? _buttonMenuRename;

		private static Button? _buttonMenuDesc;

		private static Button? _buttonMenuCraftedBy;

		private static Button? _buttonMenuResetAll;

		private static Button? _buttonMenuUnlock;

		private static Button? _buttonMenuCancel;

		private static Text? _actionMenuTitleText;

		private static Text? _craftedByPanelTitleText;

		private static Text? _craftedByTooltipLineLabelText;

		private static Button? _buttonOkCraftedBy;

		private static Button? _buttonCancelCraftedBy;

		private static Button? _buttonResetCraftedBy;

		private static Button? _buttonCraftedByLineLabelPick;

		private static GameObject? _craftedByLineLabelPopover;

		private static string? _craftedByLineLabelPendingToken;

		private const float ActionMenuButtonWidth = 200f;

		private const float ActionMenuOkButtonWidth = 64f;

		private const float ActionMenuBottomButtonGap = 8f;

		private const float ActionMenuResetButtonWidth = 128f;

		private const float CraftedByPanelWidth = 400f;

		private const float CraftedByPanelHeight = 258f;

		private const float CraftedByContentWidth = 340f;

		private const float CraftedByDropdownWidth = 280f;

		private const float CraftedByDropdownHeight = 32f;

		private const float CraftedByPopoverWidth = 290f;

		private const float CraftedByPopoverRowHeight = 32f;

		private const float CraftedByFooterButtonWidth = 72f;

		private const float CraftedByInputAnchorY = -56f;

		private const float CraftedByFooterButtonY = 32f;

		private static bool _pendingClearName;

		private static bool _pendingClearDesc;

		private static bool _pendingClearCraftedBy;

		private static GameObject? _unlockConfirmPanel;

		private static RectTransform? _unlockCostListRoot;

		private static Text? _unlockAffordWarning;

		private static Button? _buttonConfirmUnlock;

		private static Button? _buttonConfirmCancel;

		private static Text? _unlockPanelTitleText;

		private static Text? _unlockCostLabelText;

		private static readonly DrakeConfirmPanel ResetAllConfirm = new DrakeConfirmPanel("renameit_reset_all_confirm", (DrakePanelOptions)null);

		private static readonly DrakeConfirmPanel FieldResetConfirm = new DrakeConfirmPanel("renameit_field_reset_confirm", (DrakePanelOptions)null);

		public static GameObject? InputNamePanel { get; private set; }

		public static GameObject? InputDescPanel { get; private set; }

		public static InputField? RenameNameInput { get; private set; }

		public static InputField? RenameDescInput { get; private set; }

		public static GameObject? ActionMenuPanel { get