Decompiled source of RepairKits v1.0.0

RepairKits.dll

Decompiled 19 hours ago
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Security.Cryptography;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using Microsoft.CodeAnalysis;
using RepairKits.Assets;
using RepairKits.Config;
using RepairKits.Diagnostics;
using RepairKits.Kits;
using RepairKits.Localization;
using RepairKits.Repair;
using RepairKits.Util;
using TMPro;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[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.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace RepairKits
{
	[BepInPlugin("MM94.RepairKits", "RepairKits", "1.0.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class Plugin : BaseUnityPlugin
	{
		public const string ModGuid = "MM94.RepairKits";

		public const string ModName = "RepairKits";

		public const string ModVersion = "1.0.0";

		internal static ManualLogSource Log;

		private Harmony _harmony;

		private void Awake()
		{
			Log = ((BaseUnityPlugin)this).Logger;
			LogBuildInfo();
			RepairKitsConfig.Init(((BaseUnityPlugin)this).Config);
			RepairKitsLocalization.Register();
			ApplyHarmonyPatchesIsolated();
			PrefabManager.OnVanillaPrefabsAvailable += OnVanillaPrefabsAvailable;
			Log.LogInfo((object)"[RepairKits] RepairKits v1.0.0 로드 완료");
		}

		private void LogBuildInfo()
		{
			try
			{
				string location = Assembly.GetExecutingAssembly().Location;
				DateTime lastWriteTime = File.GetLastWriteTime(location);
				string arg;
				using (MD5 mD = MD5.Create())
				{
					using FileStream inputStream = File.OpenRead(location);
					byte[] array = mD.ComputeHash(inputStream);
					StringBuilder stringBuilder = new StringBuilder();
					for (int i = 0; i < 4; i++)
					{
						stringBuilder.Append(array[i].ToString("x2"));
					}
					arg = stringBuilder.ToString();
				}
				Log.LogInfo((object)string.Format("[RepairKits:빌드정보] 버전={0} dll수정시각={1:yyyy-MM-dd HH:mm:ss} md5={2}", "1.0.0", lastWriteTime, arg));
			}
			catch (Exception arg2)
			{
				Log.LogError((object)$"[RepairKits:빌드정보] 확인 중 오류: {arg2}");
			}
		}

		private void ApplyHarmonyPatchesIsolated()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Expected O, but got Unknown
			_harmony = new Harmony("MM94.RepairKits");
			int num = 0;
			int num2 = 0;
			Type[] typesFromAssembly = AccessTools.GetTypesFromAssembly(Assembly.GetExecutingAssembly());
			foreach (Type type in typesFromAssembly)
			{
				if (Attribute.IsDefined(type, typeof(HarmonyPatch)))
				{
					try
					{
						_harmony.CreateClassProcessor(type).Patch();
						num++;
					}
					catch (Exception arg)
					{
						num2++;
						Log.LogError((object)$"[RepairKits] Harmony 패치 적용 실패: {type.FullName}\n{arg}");
					}
				}
			}
			Log.LogInfo((object)$"[RepairKits] Harmony 패치 적용 완료: 성공 {num}개 / 실패 {num2}개");
		}

		private void OnVanillaPrefabsAvailable()
		{
			try
			{
				KitItems.RegisterAll();
			}
			catch (Exception arg)
			{
				Log.LogError((object)$"[RepairKits] 키트 아이템 등록 중 오류: {arg}");
			}
			try
			{
				RepairWindow.RegisterPrefab();
			}
			catch (Exception arg2)
			{
				Log.LogError((object)$"[RepairKits] 수리창 상자 프리팹 등록 중 오류: {arg2}");
			}
			try
			{
				ConsoleCommands.Register();
			}
			catch (Exception arg3)
			{
				Log.LogError((object)$"[RepairKits] 콘솔 명령 등록 중 오류: {arg3}");
			}
			try
			{
				PatchOrderDump.LogAll();
			}
			catch (Exception arg4)
			{
				Log.LogError((object)$"[RepairKits] 패치 순서 기록 중 오류: {arg4}");
			}
		}

		private void Update()
		{
			try
			{
				RepairWindow.Tick();
			}
			catch (Exception ex)
			{
				ErrorThrottle.Log("수리창 Tick 중 오류", ex);
			}
			try
			{
				KitVerification.Tick();
			}
			catch (Exception ex2)
			{
				ErrorThrottle.Log("키트 검증 Tick 중 오류", ex2);
			}
		}
	}
}
namespace RepairKits.Util
{
	internal static class ErrorThrottle
	{
		private sealed class State
		{
			public float WindowStart;

			public int Count;
		}

		private const float WindowSeconds = 60f;

		private static readonly Dictionary<string, State> s_states = new Dictionary<string, State>();

		public static void Log(string key, Exception ex)
		{
			if (!s_states.TryGetValue(key, out var value))
			{
				value = new State
				{
					WindowStart = Time.realtimeSinceStartup,
					Count = 0
				};
				s_states[key] = value;
				Plugin.Log.LogError((object)$"[RepairKits] {key}: {ex}");
				return;
			}
			value.Count++;
			float realtimeSinceStartup = Time.realtimeSinceStartup;
			if (realtimeSinceStartup - value.WindowStart >= 60f)
			{
				Plugin.Log.LogError((object)$"[RepairKits] {key}: 최근 {60f:F0}초간 {value.Count}회 발생(마지막: {ex.GetType().Name}: {ex.Message})");
				value.WindowStart = realtimeSinceStartup;
				value.Count = 0;
			}
		}
	}
}
namespace RepairKits.Repair
{
	internal static class Classification
	{
		private static readonly string[] MetalKeywords = new string[7] { "Copper", "Bronze", "Iron", "Silver", "BlackMetal", "Flametal", "Needle" };

		public static KitKind? Classify(ItemData item)
		{
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Invalid comparison between Unknown and I4
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Invalid comparison between Unknown and I4
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Invalid comparison between Unknown and I4
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Invalid comparison between Unknown and I4
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Invalid comparison between Unknown and I4
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: Invalid comparison between Unknown and I4
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Invalid comparison between Unknown and I4
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: Invalid comparison between Unknown and I4
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Invalid comparison between Unknown and I4
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Invalid comparison between Unknown and I4
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Invalid comparison between Unknown and I4
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Invalid comparison between Unknown and I4
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Invalid comparison between Unknown and I4
			if (item?.m_shared == null || (Object)(object)item.m_dropPrefab == (Object)null)
			{
				return null;
			}
			if (RepairKitsConfig.ParseForcedClassification().TryGetValue(((Object)item.m_dropPrefab).name, out var value))
			{
				return value;
			}
			ItemType itemType = item.m_shared.m_itemType;
			SkillType skillType = item.m_shared.m_skillType;
			bool flag = (int)skillType == 9 || (int)skillType == 10;
			if ((int)itemType == 3 || (int)itemType == 14 || (int)itemType == 4 || (int)itemType == 19 || (int)skillType == 8 || (int)skillType == 14)
			{
				return flag ? KitKind.RuneChisel : KitKind.Whetstone;
			}
			if ((int)itemType == 5)
			{
				return KitKind.OilJar;
			}
			if ((int)itemType == 6 || (int)itemType == 7 || (int)itemType == 11 || (int)itemType == 17)
			{
				return RecipeContainsMetal(item) ? KitKind.OilJar : KitKind.TanningBundle;
			}
			return null;
		}

		private static bool RecipeContainsMetal(ItemData item)
		{
			try
			{
				ObjectDB instance = ObjectDB.instance;
				Recipe val = ((instance != null) ? instance.GetRecipe(item) : null);
				if (val?.m_resources == null)
				{
					return false;
				}
				Requirement[] resources = val.m_resources;
				foreach (Requirement obj in resources)
				{
					object obj2;
					if (obj == null)
					{
						obj2 = null;
					}
					else
					{
						ItemDrop resItem = obj.m_resItem;
						if (resItem == null)
						{
							obj2 = null;
						}
						else
						{
							GameObject gameObject = ((Component)resItem).gameObject;
							obj2 = ((gameObject != null) ? ((Object)gameObject).name : null);
						}
					}
					string text = (string)obj2;
					if (string.IsNullOrEmpty(text))
					{
						continue;
					}
					string[] metalKeywords = MetalKeywords;
					foreach (string value in metalKeywords)
					{
						if (text.IndexOf(value, StringComparison.OrdinalIgnoreCase) >= 0)
						{
							return true;
						}
					}
				}
			}
			catch (Exception arg)
			{
				Plugin.Log.LogWarning((object)$"[RepairKits] 레시피 금속 여부 확인 중 오류({item?.m_shared?.m_name}): {arg}");
			}
			return false;
		}
	}
	internal static class ConsoleCommands
	{
		[CompilerGenerated]
		private static class <>O
		{
			public static ConsoleEvent <0>__RunKitDurability;
		}

		private static bool s_registered;

		public static void Register()
		{
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Expected O, but got Unknown
			if (s_registered)
			{
				return;
			}
			s_registered = true;
			try
			{
				object obj = <>O.<0>__RunKitDurability;
				if (obj == null)
				{
					ConsoleEvent val = RunKitDurability;
					<>O.<0>__RunKitDurability = val;
					obj = (object)val;
				}
				new ConsoleCommand("rk_kitdur", "rk_kitdur <값> — 인벤토리의 모든 수리 키트 내구도를 <값>으로 설정(테스트용, debugmode 전용)", (ConsoleEvent)obj, true, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false);
				Plugin.Log.LogInfo((object)"[RepairKits] 콘솔 명령 등록 완료 — rk_kitdur <값> (debugmode 전용)");
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"[RepairKits] rk_kitdur 콘솔 명령 등록 실패: {arg}");
			}
		}

		private static void RunKitDurability(ConsoleEventArgs args)
		{
			try
			{
				if (args.Length < 2 || !float.TryParse(args[1], NumberStyles.Float, CultureInfo.InvariantCulture, out var result))
				{
					Terminal context = args.Context;
					if (context != null)
					{
						context.AddString("사용법: rk_kitdur <값>");
					}
					return;
				}
				Player localPlayer = Player.m_localPlayer;
				if ((Object)(object)localPlayer == (Object)null)
				{
					return;
				}
				int num = 0;
				foreach (ItemData allItem in ((Humanoid)localPlayer).GetInventory().GetAllItems())
				{
					if ((Object)(object)allItem?.m_dropPrefab != (Object)null && KitItems.IsKit(((Object)allItem.m_dropPrefab).name, out var _))
					{
						allItem.m_durability = result;
						num++;
					}
				}
				Terminal context2 = args.Context;
				if (context2 != null)
				{
					context2.AddString($"키트 {num}개 내구도를 {result.ToString(CultureInfo.InvariantCulture)}로 설정했습니다.");
				}
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"[RepairKits] rk_kitdur 실행 중 오류: {arg}");
			}
		}
	}
	internal static class HumanoidAccess
	{
		private static readonly FieldRef<Humanoid, ItemData> s_chestItem = BuildFieldRef("m_chestItem");

		private static readonly FieldRef<Humanoid, ItemData> s_legItem = BuildFieldRef("m_legItem");

		private static readonly FieldRef<Humanoid, ItemData> s_helmetItem = BuildFieldRef("m_helmetItem");

		private static readonly FieldRef<Humanoid, ItemData> s_shoulderItem = BuildFieldRef("m_shoulderItem");

		private static readonly Func<Humanoid, ItemData> s_getCurrentBlocker = BuildGetCurrentBlocker();

		public static ItemData GetChestItem(Humanoid h)
		{
			if (s_chestItem == null)
			{
				return null;
			}
			return s_chestItem.Invoke(h);
		}

		public static ItemData GetLegItem(Humanoid h)
		{
			if (s_legItem == null)
			{
				return null;
			}
			return s_legItem.Invoke(h);
		}

		public static ItemData GetHelmetItem(Humanoid h)
		{
			if (s_helmetItem == null)
			{
				return null;
			}
			return s_helmetItem.Invoke(h);
		}

		public static ItemData GetShoulderItem(Humanoid h)
		{
			if (s_shoulderItem == null)
			{
				return null;
			}
			return s_shoulderItem.Invoke(h);
		}

		public static ItemData GetCurrentBlocker(Humanoid h)
		{
			if (s_getCurrentBlocker == null)
			{
				return null;
			}
			return s_getCurrentBlocker(h);
		}

		private static FieldRef<Humanoid, ItemData> BuildFieldRef(string fieldName)
		{
			try
			{
				return AccessTools.FieldRefAccess<Humanoid, ItemData>(fieldName);
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"[RepairKits] Humanoid.{fieldName} 리플렉션 접근 실패: {arg}");
				return null;
			}
		}

		private static Func<Humanoid, ItemData> BuildGetCurrentBlocker()
		{
			try
			{
				MethodInfo methodInfo = AccessTools.Method(typeof(Humanoid), "GetCurrentBlocker", (Type[])null, (Type[])null);
				return (methodInfo != null) ? AccessTools.MethodDelegate<Func<Humanoid, ItemData>>(methodInfo, (object)null, true) : null;
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"[RepairKits] Humanoid.GetCurrentBlocker 리플렉션 접근 실패: {arg}");
				return null;
			}
		}
	}
	[HarmonyPatch(typeof(Player), "DamageArmorDurability")]
	internal static class ArmorDurabilityRatePatch
	{
		private static void Prefix(Player __instance, out float[] __state)
		{
			try
			{
				__state = new float[4]
				{
					HumanoidAccess.GetChestItem((Humanoid)(object)__instance)?.m_durability ?? (-1f),
					HumanoidAccess.GetLegItem((Humanoid)(object)__instance)?.m_durability ?? (-1f),
					HumanoidAccess.GetHelmetItem((Humanoid)(object)__instance)?.m_durability ?? (-1f),
					HumanoidAccess.GetShoulderItem((Humanoid)(object)__instance)?.m_durability ?? (-1f)
				};
			}
			catch (Exception ex)
			{
				ErrorThrottle.Log("방어구 내구도 배율 Prefix 오류", ex);
				__state = null;
			}
		}

		private static void Postfix(Player __instance, float[] __state)
		{
			if (__state == null)
			{
				return;
			}
			try
			{
				float value = RepairKitsConfig.ArmorDurabilityRate.Value;
				if ((0u | (RescaleLoss(HumanoidAccess.GetChestItem((Humanoid)(object)__instance), __state[0], value) ? 1u : 0u) | (RescaleLoss(HumanoidAccess.GetLegItem((Humanoid)(object)__instance), __state[1], value) ? 1u : 0u) | (RescaleLoss(HumanoidAccess.GetHelmetItem((Humanoid)(object)__instance), __state[2], value) ? 1u : 0u) | (RescaleLoss(HumanoidAccess.GetShoulderItem((Humanoid)(object)__instance), __state[3], value) ? 1u : 0u)) == 0)
				{
					DurabilityDebugLog.LogNoLoss("방어구");
				}
			}
			catch (Exception ex)
			{
				ErrorThrottle.Log("방어구 내구도 배율 Postfix 오류", ex);
			}
		}

		private static bool RescaleLoss(ItemData item, float before, float rate)
		{
			if (item == null || before < 0f)
			{
				return false;
			}
			float num = before - item.m_durability;
			if (num <= 0f)
			{
				return false;
			}
			float num2 = num * rate;
			item.m_durability = Mathf.Max(0f, before - num2);
			DurabilityDebugLog.Log("방어구", ItemLabel(item), num, num2, rate, before, item.m_durability);
			return true;
		}

		private static string ItemLabel(ItemData item)
		{
			string text = item.m_shared?.m_name;
			if (string.IsNullOrEmpty(text))
			{
				return "?";
			}
			if (Localization.instance == null)
			{
				return text;
			}
			return Localization.instance.Localize(text);
		}
	}
	[HarmonyPatch(typeof(Humanoid), "BlockAttack")]
	internal static class ShieldDurabilityRatePatch
	{
		private static void Prefix(Humanoid __instance, out float __state)
		{
			try
			{
				__state = HumanoidAccess.GetCurrentBlocker(__instance)?.m_durability ?? (-1f);
			}
			catch (Exception ex)
			{
				ErrorThrottle.Log("방패 내구도 배율 Prefix 오류", ex);
				__state = -1f;
			}
		}

		private static void Postfix(Humanoid __instance, float __state)
		{
			if (__state < 0f)
			{
				return;
			}
			try
			{
				ItemData currentBlocker = HumanoidAccess.GetCurrentBlocker(__instance);
				if (currentBlocker != null)
				{
					float value = RepairKitsConfig.ShieldDurabilityRate.Value;
					float num = __state - currentBlocker.m_durability;
					float num2 = 0f;
					if (num > 0f)
					{
						num2 = num * value;
						currentBlocker.m_durability = Mathf.Max(0f, __state - num2);
					}
					string text = currentBlocker.m_shared?.m_name;
					string itemName = (string.IsNullOrEmpty(text) ? "?" : ((Localization.instance != null) ? Localization.instance.Localize(text) : text));
					DurabilityDebugLog.Log("막기", itemName, Mathf.Max(0f, num), num2, value, __state, currentBlocker.m_durability);
				}
			}
			catch (Exception ex)
			{
				ErrorThrottle.Log("방패 내구도 배율 Postfix 오류", ex);
			}
		}
	}
	internal static class KitHoverTracker
	{
		private readonly struct Entry
		{
			public readonly ItemData Item;

			public readonly bool IsPlayerInventory;

			public Entry(ItemData item, bool isPlayerInventory)
			{
				Item = item;
				IsPlayerInventory = isPlayerInventory;
			}
		}

		private static readonly Dictionary<UITooltip, Entry> s_tooltipItem = new Dictionary<UITooltip, Entry>();

		private static Func<UITooltip> s_getCurrent;

		private static bool s_getCurrentBuilt;

		public static ItemData GetHoveredItem()
		{
			if (!TryGetHoveredEntry(out var entry))
			{
				return null;
			}
			return entry.Item;
		}

		public static bool TryGetHoveredPlayerInventoryItem(out ItemData item)
		{
			if (TryGetHoveredEntry(out var entry) && entry.IsPlayerInventory && entry.Item != null)
			{
				item = entry.Item;
				return true;
			}
			item = null;
			return false;
		}

		private static bool TryGetHoveredEntry(out Entry entry)
		{
			entry = default(Entry);
			EnsureGetCurrentBuilt();
			if (s_getCurrent == null)
			{
				return false;
			}
			UITooltip val;
			try
			{
				val = s_getCurrent();
			}
			catch
			{
				return false;
			}
			if ((Object)(object)val != (Object)null)
			{
				return s_tooltipItem.TryGetValue(val, out entry);
			}
			return false;
		}

		public static void Record(UITooltip tooltip, ItemData item, bool isPlayerInventory)
		{
			if ((Object)(object)tooltip != (Object)null)
			{
				s_tooltipItem[tooltip] = new Entry(item, isPlayerInventory);
			}
		}

		private static void EnsureGetCurrentBuilt()
		{
			if (s_getCurrentBuilt)
			{
				return;
			}
			s_getCurrentBuilt = true;
			try
			{
				FieldInfo field = AccessTools.Field(typeof(UITooltip), "m_current");
				s_getCurrent = () => (UITooltip)field.GetValue(null);
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"[RepairKits] UITooltip.m_current 리플렉션 접근 실패: {arg}");
				s_getCurrent = null;
			}
		}
	}
	[HarmonyPatch(typeof(InventoryGrid), "CreateItemTooltip")]
	internal static class KitTooltipHintPatch
	{
		private static void Postfix(InventoryGrid __instance, ItemData item, UITooltip tooltip)
		{
			try
			{
				bool isPlayerInventory = (Object)(object)__instance != (Object)null && (Object)(object)Player.m_localPlayer != (Object)null && __instance.GetInventory() == ((Humanoid)Player.m_localPlayer).GetInventory();
				KitHoverTracker.Record(tooltip, item, isPlayerInventory);
				if ((Object)(object)item?.m_dropPrefab != (Object)null && KitItems.IsKit(((Object)item.m_dropPrefab).name, out var _))
				{
					tooltip.m_text = tooltip.m_text + "\n" + RepairKitsLocalization.Get("mm94_repairkit_open_hint");
				}
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"[RepairKits] 키트 툴팁 안내 추가 중 오류: {arg}");
			}
		}
	}
	[HarmonyPatch(typeof(Player), "CreateTombStone")]
	internal static class PlayerDeathFlushPatch
	{
		private static void Prefix(Player __instance)
		{
			try
			{
				if ((Object)(object)__instance == (Object)(object)Player.m_localPlayer)
				{
					RepairWindow.ForceCloseIfOpen("사망(묘비 생성 전)");
				}
			}
			catch (Exception ex)
			{
				ErrorThrottle.Log("사망 전 수리창 정리 중 오류", ex);
			}
		}
	}
	[HarmonyPatch(typeof(Player), "Save", new Type[] { typeof(ZPackage) })]
	internal static class PlayerSaveFlushPatch
	{
		private static void Prefix(Player __instance)
		{
			try
			{
				if ((Object)(object)__instance == (Object)(object)Player.m_localPlayer)
				{
					RepairWindow.ForceCloseIfOpen("저장(로그아웃/게임종료 전)");
				}
			}
			catch (Exception ex)
			{
				ErrorThrottle.Log("저장 전 수리창 정리 중 오류", ex);
			}
		}
	}
	internal static class RepairService
	{
		public const float Epsilon = 0.01f;

		public static bool IsDamaged(ItemData item)
		{
			if (item?.m_shared != null && item.m_shared.m_useDurability)
			{
				return item.m_durability < item.GetMaxDurability() - 0.01f;
			}
			return false;
		}

		public static bool IsKitDepleted(ItemData kit)
		{
			if (kit != null)
			{
				return kit.m_durability <= 0.01f;
			}
			return true;
		}

		public static float Repair(ItemData target, ItemData kit)
		{
			if (target?.m_shared == null || kit == null)
			{
				return 0f;
			}
			float num = target.GetMaxDurability() - target.m_durability;
			if (num <= 0.01f)
			{
				return 0f;
			}
			float num2 = Mathf.Max(0f, kit.m_durability);
			if (num2 <= 0.01f)
			{
				return 0f;
			}
			float num3 = Mathf.Min(num, num2);
			target.m_durability = Mathf.Min(target.GetMaxDurability(), target.m_durability + num3);
			kit.m_durability = Mathf.Max(0f, kit.m_durability - num3);
			return num3;
		}

		public static void RemoveIfDepleted(Inventory inventory, ItemData kit)
		{
			if (inventory != null && IsKitDepleted(kit))
			{
				inventory.RemoveItem(kit);
			}
		}
	}
	internal static class RepairWindow
	{
		[CompilerGenerated]
		private static class <>O
		{
			public static Func<ItemData, bool> <0>__IsDamaged;

			public static UnityAction <1>__OnRepairClicked;
		}

		private static GameObject s_boxTemplate;

		private static GameObject s_boxInstance;

		private static Container s_box;

		private static ItemData s_kit;

		private static KitKind s_kind;

		private static GameObject s_overlay;

		private static TMP_Text s_ratioLabel;

		private static Button s_repairButton;

		private static readonly HashSet<ItemData> s_knownItems = new HashSet<ItemData>();

		private static bool s_pendingButtonLog;

		private static readonly FieldRef<InventoryGui, Container> s_currentContainerRef = BuildCurrentContainerRef();

		private static readonly FieldRef<InventoryGui, InventoryGrid> s_containerGridRef = BuildContainerGridRef();

		private static readonly Action<InventoryGui> s_closeContainer = BuildCloseContainer();

		public static bool IsOpen => (Object)(object)s_box != (Object)null;

		private static FieldRef<InventoryGui, Container> BuildCurrentContainerRef()
		{
			try
			{
				return AccessTools.FieldRefAccess<InventoryGui, Container>("m_currentContainer");
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"[RepairKits] InventoryGui.m_currentContainer 리플렉션 접근 실패: {arg}");
				return null;
			}
		}

		private static Container GetCurrentContainer(InventoryGui gui)
		{
			if (s_currentContainerRef == null)
			{
				return null;
			}
			return s_currentContainerRef.Invoke(gui);
		}

		private static FieldRef<InventoryGui, InventoryGrid> BuildContainerGridRef()
		{
			try
			{
				return AccessTools.FieldRefAccess<InventoryGui, InventoryGrid>("m_containerGrid");
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"[RepairKits] InventoryGui.m_containerGrid 리플렉션 접근 실패: {arg}");
				return null;
			}
		}

		private static InventoryGrid GetContainerGrid(InventoryGui gui)
		{
			if (s_containerGridRef == null || !((Object)(object)gui != (Object)null))
			{
				return null;
			}
			return s_containerGridRef.Invoke(gui);
		}

		private static Action<InventoryGui> BuildCloseContainer()
		{
			try
			{
				MethodInfo methodInfo = AccessTools.Method(typeof(InventoryGui), "CloseContainer", (Type[])null, (Type[])null);
				return (methodInfo != null) ? AccessTools.MethodDelegate<Action<InventoryGui>>(methodInfo, (object)null, true) : null;
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"[RepairKits] InventoryGui.CloseContainer 리플렉션 접근 실패: {arg}");
				return null;
			}
		}

		private static void CloseVanillaContainerView()
		{
			if ((Object)(object)InventoryGui.instance != (Object)null && s_closeContainer != null)
			{
				s_closeContainer(InventoryGui.instance);
			}
		}

		public static void RegisterPrefab()
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Expected O, but got Unknown
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)s_boxTemplate != (Object)null)
			{
				return;
			}
			try
			{
				GameObject val = new GameObject("MM94_RepairBox");
				val.SetActive(false);
				val.AddComponent<ZNetView>().m_persistent = false;
				Container obj = val.AddComponent<Container>();
				obj.m_width = 8;
				obj.m_height = 1;
				obj.m_privacy = (PrivacySetting)2;
				obj.m_autoDestroyEmpty = false;
				obj.m_name = "$mm94_repairkit_window_title";
				PrefabManager.Instance.AddPrefab(val);
				s_boxTemplate = val;
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"[RepairKits] 수리창 전용 상자 프리팹 등록 실패: {arg}");
			}
		}

		public static void Open(ItemData kit, KitKind kind)
		{
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)s_boxTemplate == (Object)null || (Object)(object)Player.m_localPlayer == (Object)null || (Object)(object)InventoryGui.instance == (Object)null)
			{
				return;
			}
			if (IsOpen)
			{
				CloseInternal("새 창 열기");
			}
			try
			{
				Player localPlayer = Player.m_localPlayer;
				GameObject val = Object.Instantiate<GameObject>(s_boxTemplate, ((Component)localPlayer).transform.position, Quaternion.identity);
				val.SetActive(true);
				Container component = val.GetComponent<Container>();
				if ((Object)(object)component == (Object)null || component.GetInventory() == null)
				{
					Plugin.Log.LogError((object)"[RepairKits] 수리창 상자 초기화 실패(Container/Inventory 없음).");
					Object.Destroy((Object)(object)val);
					return;
				}
				s_boxInstance = val;
				s_box = component;
				s_kit = kit;
				s_kind = kind;
				s_knownItems.Clear();
				InventoryGui.instance.Show(component, 1);
				EnsureOverlay();
				s_overlay.SetActive(true);
				s_pendingButtonLog = true;
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"[RepairKits] 수리창 열기 실패: {arg}");
				CloseInternal("열기 실패");
			}
		}

		public static void HandleOpenHotkey()
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			if (!InventoryGui.IsVisible())
			{
				return;
			}
			KeyboardShortcut value = RepairKitsConfig.OpenRepairWindowKey.Value;
			if (!((KeyboardShortcut)(ref value)).IsDown() || IsOpen || !KitHoverTracker.TryGetHoveredPlayerInventoryItem(out var item) || (Object)(object)item?.m_dropPrefab == (Object)null || !KitItems.IsKit(((Object)item.m_dropPrefab).name, out var def))
			{
				return;
			}
			InventoryGui instance = InventoryGui.instance;
			if ((Object)(object)instance != (Object)null && instance.IsContainerOpen())
			{
				ConsumeUseInput();
				Player localPlayer = Player.m_localPlayer;
				if (localPlayer != null)
				{
					((Character)localPlayer).Message((MessageType)2, RepairKitsLocalization.Get("mm94_repairkit_other_container_open"), 0, (Sprite)null, false);
				}
				if (RepairKitsConfig.EnableDiagnosticLogs.Value)
				{
					Plugin.Log.LogInfo((object)("[RepairKits:수리창] 열기 요청 키트=" + def.PrefabId + " 결과=거부(다른 상자 열림)"));
				}
			}
			else
			{
				ConsumeUseInput();
				Open(item, def.Kind);
				if (RepairKitsConfig.EnableDiagnosticLogs.Value)
				{
					Plugin.Log.LogInfo((object)("[RepairKits:수리창] 열기 요청 키트=" + def.PrefabId + " 결과=열림"));
				}
			}
		}

		private static void ConsumeUseInput()
		{
			ZInput.ResetButtonStatus("Use");
		}

		public static void Tick()
		{
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			if (!IsOpen)
			{
				return;
			}
			if (s_pendingButtonLog)
			{
				s_pendingButtonLog = false;
				LogButtonDiagnostics();
			}
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer == (Object)null || (Object)(object)InventoryGui.instance == (Object)null || (Object)(object)GetCurrentContainer(InventoryGui.instance) != (Object)(object)s_box)
			{
				CloseInternal("GUI 닫힘/불일치");
				return;
			}
			if (s_kit != null && !((Humanoid)localPlayer).GetInventory().GetAllItems().Contains(s_kit))
			{
				s_kit = null;
				CloseInternal("키트 사라짐");
				return;
			}
			if ((Object)(object)s_boxInstance != (Object)null)
			{
				s_boxInstance.transform.position = ((Component)localPlayer).transform.position;
			}
			EnforceFilter(localPlayer);
			UpdateRatioLabel();
		}

		private static void EnforceFilter(Player player)
		{
			foreach (ItemData item in s_box.GetInventory().GetAllItems().ToList())
			{
				if (!s_knownItems.Contains(item))
				{
					KitKind? kitKind = Classification.Classify(item);
					string text = null;
					if (kitKind != s_kind)
					{
						text = "mm94_repairkit_wrong_category";
					}
					else if (!RepairService.IsDamaged(item))
					{
						text = "mm94_repairkit_not_damaged";
					}
					if (text != null)
					{
						s_box.GetInventory().RemoveItem(item);
						((Humanoid)player).GetInventory().AddItem(item);
						((Character)player).Message((MessageType)2, RepairKitsLocalization.Get(text), 0, (Sprite)null, false);
					}
					else
					{
						s_knownItems.Add(item);
					}
				}
			}
			HashSet<ItemData> currentSet = new HashSet<ItemData>(s_box.GetInventory().GetAllItems());
			s_knownItems.RemoveWhere((ItemData i) => !currentSet.Contains(i));
		}

		private static void UpdateRatioLabel()
		{
			if ((Object)(object)s_ratioLabel == (Object)null)
			{
				return;
			}
			float num = 0f;
			foreach (ItemData allItem in s_box.GetInventory().GetAllItems())
			{
				num += Mathf.Max(0f, allItem.GetMaxDurability() - allItem.m_durability);
			}
			float num2 = ((s_kit != null) ? Mathf.Max(0f, s_kit.m_durability) : 0f);
			int num3 = Mathf.CeilToInt(num);
			int num4 = Mathf.CeilToInt(num2);
			s_ratioLabel.text = ((num3 > num4) ? $"<color=red>{num3}</color>/{num4}" : $"{num3}/{num4}");
		}

		private static void OnRepairClicked()
		{
			if (Input.GetKey((KeyCode)306) || Input.GetKey((KeyCode)305) || !IsOpen || s_kit == null)
			{
				return;
			}
			int width = s_box.GetInventory().GetWidth();
			List<ItemData> list = (from i in s_box.GetInventory().GetAllItems()
				orderby i.m_gridPos.x + i.m_gridPos.y * width
				select i).ToList();
			if (list.Count == 0 || !list.Any(RepairService.IsDamaged))
			{
				Player localPlayer = Player.m_localPlayer;
				if (localPlayer != null)
				{
					((Character)localPlayer).Message((MessageType)2, RepairKitsLocalization.Get("mm94_repairkit_nothing_to_repair"), 0, (Sprite)null, false);
				}
				return;
			}
			foreach (ItemData item in list)
			{
				RepairService.Repair(item, s_kit);
			}
			if (list.Any(RepairService.IsDamaged))
			{
				if ((Object)(object)Player.m_localPlayer != (Object)null)
				{
					((Humanoid)Player.m_localPlayer).GetInventory().RemoveItem(s_kit);
				}
				s_kit = null;
				Player localPlayer2 = Player.m_localPlayer;
				if (localPlayer2 != null)
				{
					((Character)localPlayer2).Message((MessageType)2, RepairKitsLocalization.Get("mm94_repairkit_partial_kit_depleted"), 0, (Sprite)null, false);
				}
				CloseVanillaContainerView();
				CloseInternal("키트 소진(부분 수리)");
				return;
			}
			Player localPlayer3 = Player.m_localPlayer;
			if (localPlayer3 != null)
			{
				((Character)localPlayer3).Message((MessageType)2, RepairKitsLocalization.Get("mm94_repairkit_all_repaired"), 0, (Sprite)null, false);
			}
			if ((Object)(object)Player.m_localPlayer != (Object)null)
			{
				((Humanoid)Player.m_localPlayer).GetInventory().MoveAll(s_box.GetInventory());
				HashSet<ItemData> remaining = new HashSet<ItemData>(s_box.GetInventory().GetAllItems());
				s_knownItems.RemoveWhere((ItemData i) => !remaining.Contains(i));
			}
			if (s_kit != null && RepairService.IsKitDepleted(s_kit) && (Object)(object)Player.m_localPlayer != (Object)null)
			{
				((Humanoid)Player.m_localPlayer).GetInventory().RemoveItem(s_kit);
				s_kit = null;
			}
			UpdateRatioLabel();
		}

		public static void ForceCloseIfOpen(string reason)
		{
			if (IsOpen)
			{
				CloseInternal(reason);
			}
		}

		private static void CloseInternal(string reason)
		{
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0139: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)s_box == (Object)null)
			{
				return;
			}
			Container val = s_box;
			GameObject val2 = s_boxInstance;
			Vector3 position = (((Object)(object)Player.m_localPlayer != (Object)null) ? ((Component)Player.m_localPlayer).transform.position : (((Object)(object)val2 != (Object)null) ? val2.transform.position : Vector3.zero));
			int num = 0;
			int num2 = 0;
			try
			{
				Inventory inventory = val.GetInventory();
				Inventory val3 = (((Object)(object)Player.m_localPlayer != (Object)null) ? ((Humanoid)Player.m_localPlayer).GetInventory() : null);
				foreach (ItemData item in inventory.GetAllItems().ToList())
				{
					if (val3 != null && val3.AddItem(item))
					{
						inventory.RemoveItem(item);
						num++;
					}
					else
					{
						DropItemSafely(item, position);
						inventory.RemoveItem(item);
						num2++;
					}
				}
				List<ItemData> list = inventory.GetAllItems().ToList();
				if (list.Count > 0)
				{
					Plugin.Log.LogError((object)$"[RepairKits] 수리창 상자에 아이템 {list.Count}개가 남아 있어 강제로 바닥에 떨어뜨립니다.");
					foreach (ItemData item2 in list)
					{
						DropItemSafely(item2, position);
						inventory.RemoveItem(item2);
						num2++;
					}
				}
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"[RepairKits] 수리창 닫기(반환/드랍) 처리 중 오류: {arg}");
			}
			if (num2 > 0)
			{
				Player localPlayer = Player.m_localPlayer;
				if (localPlayer != null)
				{
					((Character)localPlayer).Message((MessageType)2, RepairKitsLocalization.Get("mm94_repairkit_inventory_full_dropped"), 0, (Sprite)null, false);
				}
			}
			try
			{
				if ((Object)(object)val2 != (Object)null)
				{
					if ((Object)(object)ZNetScene.instance != (Object)null)
					{
						ZNetScene.instance.Destroy(val2);
					}
					else
					{
						Object.Destroy((Object)(object)val2);
					}
				}
			}
			catch (Exception arg2)
			{
				Plugin.Log.LogError((object)$"[RepairKits] 수리창 상자 파괴 중 오류: {arg2}");
			}
			if (RepairKitsConfig.EnableDiagnosticLogs.Value)
			{
				Inventory inventory2 = val.GetInventory();
				int valueOrDefault = ((inventory2 == null) ? ((int?)null) : inventory2.GetAllItems()?.Count).GetValueOrDefault();
				Plugin.Log.LogInfo((object)$"[RepairKits:수리창] 닫힘 이유={reason} 돌려줌={num}개 바닥={num2}개 남음={valueOrDefault}개");
			}
			s_boxInstance = null;
			s_box = null;
			s_kit = null;
			s_knownItems.Clear();
			if ((Object)(object)s_overlay != (Object)null)
			{
				s_overlay.SetActive(false);
			}
		}

		private static void DropItemSafely(ItemData item, Vector3 position)
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				if (!((Object)(object)item?.m_dropPrefab == (Object)null))
				{
					ItemDrop.DropItem(item, item.m_stack, position, Quaternion.identity);
				}
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"[RepairKits] 장비를 바닥에 떨어뜨리는 중 오류({item?.m_shared?.m_name}): {arg}");
			}
		}

		private static void EnsureOverlay()
		{
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Expected O, but got Unknown
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_010e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0123: Unknown result type (might be due to invalid IL or missing references)
			//IL_0138: Unknown result type (might be due to invalid IL or missing references)
			//IL_014d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0161: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_0203: Unknown result type (might be due to invalid IL or missing references)
			//IL_0218: Unknown result type (might be due to invalid IL or missing references)
			//IL_022c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0253: Unknown result type (might be due to invalid IL or missing references)
			//IL_025d: Expected O, but got Unknown
			//IL_0277: Unknown result type (might be due to invalid IL or missing references)
			//IL_027c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0282: Expected O, but got Unknown
			if ((Object)(object)s_overlay != (Object)null)
			{
				return;
			}
			InventoryGui instance = InventoryGui.instance;
			RectTransform container = instance.m_container;
			if ((Object)(object)container == (Object)null)
			{
				return;
			}
			s_overlay = new GameObject("MM94_RepairOverlay", new Type[1] { typeof(RectTransform) });
			s_overlay.transform.SetParent((Transform)(object)container, false);
			RectTransform component = s_overlay.GetComponent<RectTransform>();
			component.anchorMin = new Vector2(0.5f, 0.5f);
			component.anchorMax = new Vector2(0.5f, 0.5f);
			component.pivot = new Vector2(0.5f, 0.5f);
			component.sizeDelta = new Vector2(260f, 70f);
			s_overlay.AddComponent<RepairOverlayDragHandler>();
			if ((Object)(object)instance.m_containerName != (Object)null)
			{
				GameObject obj = Object.Instantiate<GameObject>(((Component)instance.m_containerName).gameObject, s_overlay.transform);
				((Object)obj).name = "RatioLabel";
				obj.SetActive(true);
				RectTransform component2 = obj.GetComponent<RectTransform>();
				component2.anchorMin = new Vector2(0f, 1f);
				component2.anchorMax = new Vector2(1f, 1f);
				component2.pivot = new Vector2(0.5f, 1f);
				component2.anchoredPosition = new Vector2(0f, -4f);
				component2.sizeDelta = new Vector2(0f, 30f);
				s_ratioLabel = obj.GetComponent<TMP_Text>();
				if ((Object)(object)s_ratioLabel != (Object)null)
				{
					s_ratioLabel.alignment = (TextAlignmentOptions)514;
					s_ratioLabel.text = "0/0";
				}
			}
			if ((Object)(object)instance.m_repairButton != (Object)null)
			{
				GameObject obj2 = Object.Instantiate<GameObject>(((Component)instance.m_repairButton).gameObject, s_overlay.transform);
				((Object)obj2).name = "RepairButton";
				obj2.SetActive(true);
				RectTransform component3 = obj2.GetComponent<RectTransform>();
				component3.anchorMin = new Vector2(0.5f, 1f);
				component3.anchorMax = new Vector2(0.5f, 1f);
				component3.pivot = new Vector2(0.5f, 1f);
				component3.anchoredPosition = new Vector2(0f, -40f);
				s_repairButton = obj2.GetComponent<Button>();
				if ((Object)(object)s_repairButton != (Object)null)
				{
					s_repairButton.onClick = new ButtonClickedEvent();
					ButtonClickedEvent onClick = s_repairButton.onClick;
					object obj3 = <>O.<1>__OnRepairClicked;
					if (obj3 == null)
					{
						UnityAction val = OnRepairClicked;
						<>O.<1>__OnRepairClicked = val;
						obj3 = (object)val;
					}
					((UnityEvent)onClick).AddListener((UnityAction)obj3);
					((Selectable)s_repairButton).interactable = true;
				}
				TMP_Text componentInChildren = obj2.GetComponentInChildren<TMP_Text>();
				if ((Object)(object)componentInChildren != (Object)null)
				{
					componentInChildren.text = RepairKitsLocalization.Get("mm94_repairkit_repair_button");
				}
				Transform val2 = obj2.transform.Find("Glow");
				if ((Object)(object)val2 != (Object)null)
				{
					((Component)val2).gameObject.SetActive(false);
				}
			}
			ApplyOverlayPositionFromConfig();
		}

		public static void ApplyOverlayPositionFromConfig()
		{
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)s_overlay == (Object)null)
			{
				return;
			}
			RectTransform component = s_overlay.GetComponent<RectTransform>();
			if (!((Object)(object)component == (Object)null))
			{
				string value = RepairKitsConfig.RepairOverlayPosition.Value;
				if (!string.IsNullOrEmpty(value) && TryParsePosition(value, out var value2))
				{
					component.anchoredPosition = value2;
				}
				else
				{
					component.anchoredPosition = ComputeDefaultOverlayPosition();
				}
			}
		}

		private static bool TryParsePosition(string raw, out Vector2 value)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			value = default(Vector2);
			string[] array = raw.Split(new char[1] { ',' });
			if (array.Length != 2)
			{
				return false;
			}
			if (!float.TryParse(array[0], NumberStyles.Float, CultureInfo.InvariantCulture, out var result) || !float.TryParse(array[1], NumberStyles.Float, CultureInfo.InvariantCulture, out var result2))
			{
				return false;
			}
			value = new Vector2(result, result2);
			return true;
		}

		private static Vector2 ComputeDefaultOverlayPosition()
		{
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_010d: Unknown result type (might be due to invalid IL or missing references)
			//IL_011d: Unknown result type (might be due to invalid IL or missing references)
			//IL_011f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0124: Unknown result type (might be due to invalid IL or missing references)
			//IL_0126: Unknown result type (might be due to invalid IL or missing references)
			//IL_012d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0134: Unknown result type (might be due to invalid IL or missing references)
			InventoryGui instance = InventoryGui.instance;
			RectTransform val = (((Object)(object)instance != (Object)null) ? instance.m_container : null);
			if ((Object)(object)val == (Object)null)
			{
				return Vector2.zero;
			}
			InventoryGrid containerGrid = GetContainerGrid(instance);
			RectTransform val2 = (((Object)(object)containerGrid != (Object)null) ? ((Component)containerGrid).GetComponent<RectTransform>() : null);
			float num = (((Object)(object)val2 != (Object)null) ? GetWorldBottomY(val2) : GetWorldBottomY(val));
			List<float> list = new List<float>();
			RectTransform val3 = (((Object)(object)instance.m_takeAllButton != (Object)null) ? ((Component)instance.m_takeAllButton).GetComponent<RectTransform>() : null);
			RectTransform val4 = (((Object)(object)instance.m_stackAllButton != (Object)null) ? ((Component)instance.m_stackAllButton).GetComponent<RectTransform>() : null);
			if ((Object)(object)val3 != (Object)null)
			{
				list.Add(GetWorldTopY(val3));
			}
			if ((Object)(object)val4 != (Object)null)
			{
				list.Add(GetWorldTopY(val4));
			}
			float num2 = ((list.Count > 0) ? (list.Max() + 12f) : (GetWorldBottomY(val) + 12f));
			float num3 = (num + num2) / 2f;
			float worldCenterX = GetWorldCenterX(val);
			Vector3 val5 = default(Vector3);
			((Vector3)(ref val5))..ctor(worldCenterX, num3, ((Transform)val).position.z);
			Vector3 val6 = ((Transform)val).InverseTransformPoint(val5);
			return new Vector2(val6.x, val6.y);
		}

		private static float GetWorldBottomY(RectTransform rt)
		{
			Vector3[] array = (Vector3[])(object)new Vector3[4];
			rt.GetWorldCorners(array);
			return array[0].y;
		}

		private static float GetWorldTopY(RectTransform rt)
		{
			Vector3[] array = (Vector3[])(object)new Vector3[4];
			rt.GetWorldCorners(array);
			return array[1].y;
		}

		private static float GetWorldCenterX(RectTransform rt)
		{
			Vector3[] array = (Vector3[])(object)new Vector3[4];
			rt.GetWorldCorners(array);
			return (array[0].x + array[2].x) / 2f;
		}

		private static void LogButtonDiagnostics()
		{
			if (!RepairKitsConfig.EnableDiagnosticLogs.Value)
			{
				return;
			}
			if ((Object)(object)s_repairButton == (Object)null)
			{
				Plugin.Log.LogWarning((object)"[RepairKits:수리창] 버튼 상태 — 버튼 오브젝트가 없습니다.");
				return;
			}
			GameObject gameObject = ((Component)s_repairButton).gameObject;
			RectTransform component = gameObject.GetComponent<RectTransform>();
			Vector3[] array = (Vector3[])(object)new Vector3[4];
			if ((Object)(object)component != (Object)null)
			{
				component.GetWorldCorners(array);
			}
			float num = array[2].x - array[0].x;
			float num2 = array[1].y - array[0].y;
			Plugin.Log.LogInfo((object)($"[RepairKits:수리창] 버튼 상태 켜짐={gameObject.activeInHierarchy} 부모={GetHierarchyPath(gameObject.transform)} " + $"화면좌표=({array[0].x:F0},{array[0].y:F0})-({array[2].x:F0},{array[2].y:F0}) " + $"크기={num:F0}x{num2:F0} 클릭가능={((Selectable)s_repairButton).interactable}"));
		}

		private static string GetHierarchyPath(Transform t)
		{
			StringBuilder stringBuilder = new StringBuilder(((Object)t).name);
			Transform parent = t.parent;
			while ((Object)(object)parent != (Object)null)
			{
				stringBuilder.Insert(0, ((Object)parent).name + "/");
				parent = parent.parent;
			}
			return stringBuilder.ToString();
		}
	}
	internal sealed class RepairOverlayDragHandler : MonoBehaviour
	{
		private RectTransform _rect;

		private bool _dragging;

		private Vector3 _lastMousePos;

		private void Awake()
		{
			_rect = ((Component)this).GetComponent<RectTransform>();
		}

		private void Update()
		{
			try
			{
				Tick();
			}
			catch (Exception ex)
			{
				ErrorThrottle.Log("수리창 버튼 묶음 드래그 처리 중 오류", ex);
			}
		}

		private void Tick()
		{
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0092: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)_rect == (Object)null)
			{
				return;
			}
			bool flag = Input.GetKey((KeyCode)306) || Input.GetKey((KeyCode)305);
			if (!_dragging)
			{
				if (flag && Input.GetMouseButtonDown(0) && RectTransformUtility.RectangleContainsScreenPoint(_rect, Vector2.op_Implicit(Input.mousePosition)))
				{
					_dragging = true;
					_lastMousePos = Input.mousePosition;
				}
			}
			else if (!flag || !Input.GetMouseButton(0))
			{
				_dragging = false;
				ClampToScreen();
				SavePosition();
			}
			else
			{
				Vector3 mousePosition = Input.mousePosition;
				Vector3 val = mousePosition - _lastMousePos;
				_lastMousePos = mousePosition;
				float canvasScale = GetCanvasScale();
				RectTransform rect = _rect;
				rect.anchoredPosition += new Vector2(val.x, val.y) / canvasScale;
				ClampToScreen();
			}
		}

		private float GetCanvasScale()
		{
			Canvas componentInParent = ((Component)_rect).GetComponentInParent<Canvas>();
			if (!((Object)(object)componentInParent != (Object)null) || !(componentInParent.scaleFactor > 0f))
			{
				return 1f;
			}
			return componentInParent.scaleFactor;
		}

		private void ClampToScreen()
		{
			//IL_0115: Unknown result type (might be due to invalid IL or missing references)
			//IL_011d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0124: Unknown result type (might be due to invalid IL or missing references)
			//IL_0129: Unknown result type (might be due to invalid IL or missing references)
			Vector3[] array = (Vector3[])(object)new Vector3[4];
			_rect.GetWorldCorners(array);
			float num = array[2].x - array[0].x;
			float num2 = array[1].y - array[0].y;
			float num3 = 0f;
			float num4 = 0f;
			if (array[0].x < 0f)
			{
				num3 = 0f - array[0].x;
			}
			else if (array[0].x + num > (float)Screen.width)
			{
				num3 = (float)Screen.width - (array[0].x + num);
			}
			if (array[0].y < 0f)
			{
				num4 = 0f - array[0].y;
			}
			else if (array[0].y + num2 > (float)Screen.height)
			{
				num4 = (float)Screen.height - (array[0].y + num2);
			}
			if (num3 != 0f || num4 != 0f)
			{
				float canvasScale = GetCanvasScale();
				RectTransform rect = _rect;
				rect.anchoredPosition += new Vector2(num3, num4) / canvasScale;
			}
		}

		private void SavePosition()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			Vector2 anchoredPosition = _rect.anchoredPosition;
			RepairKitsConfig.RepairOverlayPosition.Value = anchoredPosition.x.ToString(CultureInfo.InvariantCulture) + "," + anchoredPosition.y.ToString(CultureInfo.InvariantCulture);
		}
	}
	[HarmonyPatch(typeof(InventoryGui), "Update")]
	internal static class InventoryGuiUpdateOpenPatch
	{
		private static void Prefix()
		{
			try
			{
				RepairWindow.HandleOpenHotkey();
			}
			catch (Exception ex)
			{
				ErrorThrottle.Log("수리창 열기 입력 처리 중 오류", ex);
			}
		}
	}
	[HarmonyPatch(typeof(Humanoid), "UseItem")]
	internal static class RightClickRepairPatch
	{
		private static bool Prefix(Humanoid __instance, Inventory inventory, ItemData item, bool fromInventoryGui)
		{
			try
			{
				if (!fromInventoryGui || (Object)(object)item?.m_dropPrefab == (Object)null)
				{
					return true;
				}
				if (!KitItems.IsKit(((Object)item.m_dropPrefab).name, out var def))
				{
					return true;
				}
				if (!RepairKitsConfig.EnableRightClickRepair.Value)
				{
					return false;
				}
				Inventory val = inventory ?? __instance.GetInventory();
				if (val == null || !val.ContainsItem(item))
				{
					return false;
				}
				RunBulkRepair(__instance, val, item, def.Kind);
				return false;
			}
			catch (Exception ex)
			{
				ErrorThrottle.Log("우클릭 일괄 수리 처리 중 오류", ex);
				return true;
			}
		}

		private static void RunBulkRepair(Humanoid player, Inventory kitInventory, ItemData kit, KitKind kind)
		{
			Inventory inventory = player.GetInventory();
			if (inventory == null)
			{
				return;
			}
			List<ItemData> list = new List<ItemData>();
			List<ItemData> worn = new List<ItemData>();
			inventory.GetWornItems(worn);
			list.AddRange(worn);
			int width = inventory.GetWidth();
			IOrderedEnumerable<ItemData> collection = from i in inventory.GetAllItems()
				where !worn.Contains(i)
				orderby i.m_gridPos.y * width + i.m_gridPos.x
				select i;
			list.AddRange(collection);
			bool flag = false;
			string text = null;
			foreach (ItemData item in list)
			{
				if (RepairService.IsKitDepleted(kit))
				{
					break;
				}
				if (Classification.Classify(item) == kind && RepairService.IsDamaged(item) && RepairService.Repair(item, kit) > 0f)
				{
					flag = true;
					text = item.m_shared.m_name;
				}
			}
			RepairService.RemoveIfDepleted(kitInventory, kit);
			if (flag)
			{
				string arg = Localization.instance.Localize(text);
				((Character)player).Message((MessageType)2, string.Format(RepairKitsLocalization.Get("mm94_repairkit_right_click_repaired"), arg), 0, (Sprite)null, false);
			}
			else
			{
				((Character)player).Message((MessageType)2, RepairKitsLocalization.Get("mm94_repairkit_nothing_to_repair"), 0, (Sprite)null, false);
			}
		}
	}
	[HarmonyPatch(typeof(InventoryGui), "CanRepair")]
	internal static class CanRepairBlockPatch
	{
		private static bool Prefix(ItemData item, ref bool __result)
		{
			try
			{
				if ((Object)(object)Player.m_localPlayer != (Object)null && Player.m_localPlayer.NoCostCheat())
				{
					return true;
				}
				__result = false;
				return false;
			}
			catch (Exception ex)
			{
				ErrorThrottle.Log("바닐라 수리 차단 처리 중 오류", ex);
				return true;
			}
		}
	}
	[HarmonyPatch(typeof(InventoryGui), "UpdateRepair")]
	internal static class UpdateRepairHidePatch
	{
		private static bool Prefix(InventoryGui __instance)
		{
			try
			{
				if ((Object)(object)Player.m_localPlayer != (Object)null && Player.m_localPlayer.NoCostCheat())
				{
					return true;
				}
				((Component)__instance.m_repairPanel).gameObject.SetActive(false);
				((Component)__instance.m_repairPanelSelection).gameObject.SetActive(false);
				((Component)__instance.m_repairButton).gameObject.SetActive(false);
				return false;
			}
			catch (Exception ex)
			{
				ErrorThrottle.Log("수리 패널 숨김 처리 중 오류", ex);
				return true;
			}
		}
	}
}
namespace RepairKits.Localization
{
	internal static class RepairKitsLocalization
	{
		private const string KoreanLanguage = "Korean";

		private const string EnglishLanguage = "English";

		private static readonly Dictionary<string, string> s_english = new Dictionary<string, string>
		{
			{ "item_mm94_whetstone", "Whetstone" },
			{ "item_mm94_whetstone_desc", "Hones weapons and tools back to a keen edge.\n[Weapons / Tools / Bows / Crossbows]" },
			{ "item_mm94_oiljar", "Oil Jar" },
			{ "item_mm94_oiljar_desc", "Oil for metal armor and shields. Keeps rust and dents at bay.\n[Metal Armor / Shields]" },
			{ "item_mm94_tanningbundle", "Tanning Bundle" },
			{ "item_mm94_tanningbundle_desc", "Needle, cord and oiled hide for mending leather and cloth armor.\n[Leather / Cloth Armor / Capes]" },
			{ "item_mm94_runechisel", "Rune Chisel" },
			{ "item_mm94_runechisel_desc", "Re-carves faded runes, restoring Eitr to staves.\n[Staves]" },
			{ "mm94_repairkit_open_hint", "[E] Open repair window" },
			{ "mm94_repairkit_window_title", "Repair" },
			{ "mm94_repairkit_repair_button", "Repair" },
			{ "mm94_repairkit_wrong_category", "This kit cannot repair that item." },
			{ "mm94_repairkit_not_damaged", "This item is not damaged." },
			{ "mm94_repairkit_depleted", "The repair kit ran out." },
			{ "mm94_repairkit_nothing_to_repair", "No damaged equipment to repair." },
			{ "mm94_repairkit_right_click_repaired", "Repaired {0}." },
			{ "mm94_repairkit_other_container_open", "Close the open container first." },
			{ "mm94_repairkit_all_repaired", "Repair complete." },
			{ "mm94_repairkit_partial_kit_depleted", "The kit ran out. Only part was repaired." },
			{ "mm94_repairkit_inventory_full_dropped", "Inventory full. Some items were dropped on the ground." }
		};

		private static readonly Dictionary<string, string> s_korean = new Dictionary<string, string>
		{
			{ "item_mm94_whetstone", "숫돌" },
			{ "item_mm94_whetstone_desc", "무뎌진 날을 다시 세운다. 무기와 도구를 손질한다.\n[무기 / 도구 / 활 / 석궁]" },
			{ "item_mm94_oiljar", "기름 단지" },
			{ "item_mm94_oiljar_desc", "쇠 갑옷과 방패에 기름을 먹여 녹과 흠을 다스린다.\n[금속 방어구 / 방패]" },
			{ "item_mm94_tanningbundle", "무두 꾸러미" },
			{ "item_mm94_tanningbundle_desc", "가죽과 천 방어구를 꿰매고 기름을 먹인다.\n[가죽 / 천 방어구 / 망토]" },
			{ "item_mm94_runechisel", "룬 끌" },
			{ "item_mm94_runechisel_desc", "흐려진 룬을 다시 새겨 지팡이에 에이트르를 되돌린다.\n[지팡이]" },
			{ "mm94_repairkit_open_hint", "[E] 수리창 열기" },
			{ "mm94_repairkit_window_title", "수리" },
			{ "mm94_repairkit_repair_button", "수리" },
			{ "mm94_repairkit_wrong_category", "이 키트로는 수리할 수 없는 장비입니다." },
			{ "mm94_repairkit_not_damaged", "손상되지 않은 장비입니다." },
			{ "mm94_repairkit_depleted", "수리 키트를 모두 소모했습니다." },
			{ "mm94_repairkit_nothing_to_repair", "수리할 손상된 장비가 없습니다." },
			{ "mm94_repairkit_right_click_repaired", "{0}을 수리했습니다." },
			{ "mm94_repairkit_other_container_open", "열려 있는 상자를 먼저 닫아주세요." },
			{ "mm94_repairkit_all_repaired", "수리를 완료했습니다." },
			{ "mm94_repairkit_partial_kit_depleted", "키트를 다 써서 일부만 수리했습니다." },
			{ "mm94_repairkit_inventory_full_dropped", "인벤토리가 가득 차서 일부 장비를 바닥에 내려놓았습니다." }
		};

		private static bool s_registered;

		private static Action<Localization, string, string> s_addWord;

		private static bool s_addWordBuilt;

		public static void Register()
		{
			if (!s_registered)
			{
				CustomLocalization localization = LocalizationManager.Instance.GetLocalization();
				string text = "English";
				localization.AddTranslation(ref text, new Dictionary<string, string>(s_english));
				text = "Korean";
				localization.AddTranslation(ref text, new Dictionary<string, string>(s_korean));
				s_registered = true;
			}
		}

		public static void ReapplyTo(Localization instance, string language)
		{
			if (instance == null)
			{
				return;
			}
			Dictionary<string, string> dictionary = ((language == "Korean") ? s_korean : s_english);
			EnsureAddWordBuilt();
			if (s_addWord == null)
			{
				return;
			}
			foreach (KeyValuePair<string, string> item in dictionary)
			{
				s_addWord(instance, item.Key, item.Value);
			}
		}

		public static string Get(string token)
		{
			Localization instance = Localization.instance;
			if (instance != null)
			{
				return instance.Localize("$" + token);
			}
			if (!s_english.TryGetValue(token, out var value))
			{
				return token;
			}
			return value;
		}

		private static void EnsureAddWordBuilt()
		{
			if (s_addWordBuilt)
			{
				return;
			}
			s_addWordBuilt = true;
			try
			{
				s_addWord = AccessTools.MethodDelegate<Action<Localization, string, string>>(AccessTools.Method(typeof(Localization), "AddWord", (Type[])null, (Type[])null), (object)null, true);
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"[RepairKits] Localization.AddWord 델리게이트 생성 실패: {arg}");
			}
		}
	}
	[HarmonyPatch(typeof(Localization), "SetupLanguage")]
	internal static class LocalizationSetupLanguagePatch
	{
		private static void Postfix(Localization __instance, string language)
		{
			try
			{
				RepairKitsLocalization.ReapplyTo(__instance, language);
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"[RepairKits] 언어 전환 시 번역 재적용 중 오류: {arg}");
			}
		}
	}
}
namespace RepairKits.Kits
{
	internal sealed class KitDefinition
	{
		public KitKind Kind;

		public string PrefabId;

		public string BaseItem;

		public string CraftingStation;

		public string ModelFileBase;

		public bool HasEmission;

		public static readonly KitDefinition Whetstone = new KitDefinition
		{
			Kind = KitKind.Whetstone,
			PrefabId = "MM94_Whetstone",
			BaseItem = "Stone",
			CraftingStation = "piece_workbench",
			ModelFileBase = "MM94_Whetstone",
			HasEmission = false
		};

		public static readonly KitDefinition OilJar = new KitDefinition
		{
			Kind = KitKind.OilJar,
			PrefabId = "MM94_OilJar",
			BaseItem = "Stone",
			CraftingStation = "piece_workbench",
			ModelFileBase = "MM94_OilJar",
			HasEmission = false
		};

		public static readonly KitDefinition TanningBundle = new KitDefinition
		{
			Kind = KitKind.TanningBundle,
			PrefabId = "MM94_TanningBundle",
			BaseItem = "Stone",
			CraftingStation = "piece_workbench",
			ModelFileBase = "MM94_TanningBundle",
			HasEmission = false
		};

		public static readonly KitDefinition RuneChisel = new KitDefinition
		{
			Kind = KitKind.RuneChisel,
			PrefabId = "MM94_RuneChisel",
			BaseItem = "Flint",
			CraftingStation = "piece_magetable",
			ModelFileBase = "MM94_RuneChisel",
			HasEmission = true
		};

		public static readonly KitDefinition[] All = new KitDefinition[4] { Whetstone, OilJar, TanningBundle, RuneChisel };
	}
	internal static class KitIcons
	{
		public static Sprite Build(KitDefinition def)
		{
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Expected O, but got Unknown
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			byte[] array = EmbeddedAssets.ReadBytes(def.PrefabId + ".png");
			if (array == null)
			{
				Plugin.Log.LogError((object)("[RepairKits] " + def.PrefabId + ": 아이콘 PNG 리소스를 읽지 못했습니다."));
				return null;
			}
			Texture2D val = new Texture2D(2, 2, (TextureFormat)4, false)
			{
				name = def.PrefabId + "_icon_tex"
			};
			TextureLoader.LoadImage(val, array);
			Sprite obj = Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), new Vector2(0.5f, 0.5f), 100f);
			((Object)obj).name = def.PrefabId + "_icon";
			return obj;
		}
	}
	internal static class KitItems
	{
		private static readonly Dictionary<string, CustomItem> s_registered = new Dictionary<string, CustomItem>();

		private static bool s_registered1;

		public static void RegisterAll()
		{
			if (!s_registered1)
			{
				s_registered1 = true;
				KitDefinition[] all = KitDefinition.All;
				for (int i = 0; i < all.Length; i++)
				{
					RegisterOne(all[i]);
				}
			}
		}

		private static void RegisterOne(KitDefinition def)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Expected O, but got Unknown
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c8: Expected O, but got Unknown
			try
			{
				string text = "item_" + def.PrefabId.ToLowerInvariant();
				ItemConfig val = new ItemConfig
				{
					Name = "$" + text,
					Description = "$" + text + "_desc",
					Weight = RepairKitsConfig.GetWeight(def.Kind),
					StackSize = 1,
					CraftingStation = def.CraftingStation
				};
				foreach (KeyValuePair<string, int> item in RepairKitsConfig.ParseRecipe(RepairKitsConfig.GetRecipe(def.Kind)))
				{
					val.AddRequirement(item.Key, item.Value, 0);
				}
				CustomItem val2 = new CustomItem(def.PrefabId, def.BaseItem, val);
				if ((Object)(object)val2.ItemDrop == (Object)null || !ItemManager.Instance.AddItem(val2))
				{
					Plugin.Log.LogWarning((object)("[RepairKits] 아이템 등록 실패: " + def.PrefabId));
					return;
				}
				SharedData shared = val2.ItemDrop.m_itemData.m_shared;
				shared.m_useDurability = true;
				shared.m_canBeReparied = false;
				shared.m_maxDurability = RepairKitsConfig.GetMaxDurability(def.Kind);
				shared.m_durabilityPerLevel = 0f;
				shared.m_destroyBroken = false;
				shared.m_maxQuality = 1;
				shared.m_teleportable = true;
				Sprite val3 = KitIcons.Build(def);
				if ((Object)(object)val3 != (Object)null)
				{
					shared.m_icons = (Sprite[])(object)new Sprite[1] { val3 };
				}
				KitVisuals.Apply(val2.ItemPrefab, def);
				s_registered[def.PrefabId] = val2;
				Plugin.Log.LogInfo((object)$"[RepairKits] {def.PrefabId} 등록 완료 (최대 내구도 {shared.m_maxDurability})");
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"[RepairKits] {def.PrefabId} 등록 중 오류: {arg}");
			}
		}

		public static bool IsKit(string prefabName, out KitDefinition def)
		{
			def = KitDefinition.All.FirstOrDefault((KitDefinition d) => string.Equals(d.PrefabId, prefabName, StringComparison.OrdinalIgnoreCase));
			return def != null;
		}

		public static bool TryGetRegistered(string prefabId, out CustomItem item)
		{
			return s_registered.TryGetValue(prefabId, out item);
		}
	}
	internal enum KitKind
	{
		Whetstone,
		OilJar,
		TanningBundle,
		RuneChisel
	}
	internal static class KitVisuals
	{
		private static readonly Dictionary<string, Material> s_materials = new Dictionary<string, Material>();

		public static void Apply(GameObject prefab, KitDefinition def)
		{
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cc: Expected O, but got Unknown
			//IL_00fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0101: Expected O, but got Unknown
			//IL_0269: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01be: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01dd: Expected O, but got Unknown
			//IL_01fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0323: Unknown result type (might be due to invalid IL or missing references)
			//IL_0328: Unknown result type (might be due to invalid IL or missing references)
			//IL_033a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0346: Unknown result type (might be due to invalid IL or missing references)
			//IL_0352: Unknown result type (might be due to invalid IL or missing references)
			//IL_0366: Unknown result type (might be due to invalid IL or missing references)
			//IL_036b: Unknown result type (might be due to invalid IL or missing references)
			//IL_036f: Unknown result type (might be due to invalid IL or missing references)
			//IL_037a: Unknown result type (might be due to invalid IL or missing references)
			//IL_037f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0383: Unknown result type (might be due to invalid IL or missing references)
			MeshRenderer componentInChildren = prefab.GetComponentInChildren<MeshRenderer>();
			if ((Object)(object)componentInChildren == (Object)null)
			{
				Plugin.Log.LogError((object)("[RepairKits] " + def.PrefabId + ": 베이스 프리팹에서 MeshRenderer를 찾지 못해 모델 교체를 건너뜁니다."));
				return;
			}
			string text = EmbeddedAssets.ReadText(def.ModelFileBase + ".obj");
			if (text == null)
			{
				Plugin.Log.LogError((object)("[RepairKits] " + def.PrefabId + ": OBJ 리소스를 읽지 못했습니다."));
				return;
			}
			Mesh val = ObjMeshLoader.Load(text, def.PrefabId + "_mesh");
			byte[] array = EmbeddedAssets.ReadBytes(def.ModelFileBase + "_tex.png");
			Texture2D val2 = null;
			if (array != null)
			{
				val2 = new Texture2D(2, 2, (TextureFormat)4, false, false)
				{
					filterMode = (FilterMode)0,
					wrapMode = (TextureWrapMode)1,
					name = def.PrefabId + "_tex"
				};
				TextureLoader.LoadImage(val2, array);
			}
			Material sharedMaterial = ((Renderer)componentInChildren).sharedMaterial;
			Material val3 = (((Object)(object)sharedMaterial != (Object)null) ? new Material(sharedMaterial) : new Material(Shader.Find("Standard")));
			((Object)val3).name = def.PrefabId + "_mat";
			if ((Object)(object)val2 != (Object)null)
			{
				val3.mainTexture = (Texture)(object)val2;
			}
			ApplyColorForBrightness(val3);
			TryClearTexture(val3, "_BumpMap");
			TryClearTexture(val3, "_MetallicGlossMap");
			TryClearTexture(val3, "_OcclusionMap");
			TryClearTexture(val3, "_ParallaxMap");
			if (def.HasEmission)
			{
				byte[] array2 = EmbeddedAssets.ReadBytes(def.ModelFileBase + "_emis.png");
				if (array2 != null && val3.HasProperty("_EmissionMap") && val3.HasProperty("_EmissionColor"))
				{
					Texture2D val4 = new Texture2D(2, 2, (TextureFormat)4, false, false)
					{
						filterMode = (FilterMode)0,
						wrapMode = (TextureWrapMode)1,
						name = def.PrefabId + "_emis"
					};
					TextureLoader.LoadImage(val4, array2);
					val3.SetTexture("_EmissionMap", (Texture)(object)val4);
					val3.SetColor("_EmissionColor", Color.white);
					val3.EnableKeyword("_EMISSION");
					Plugin.Log.LogInfo((object)("[RepairKits] " + def.PrefabId + ": 셰이더가 발광을 지원해 룬 발광 맵을 적용했습니다."));
				}
				else
				{
					Plugin.Log.LogInfo((object)("[RepairKits] " + def.PrefabId + ": 셰이더가 발광(_EmissionMap/_EmissionColor)을 지원하지 않아 발광 적용을 생략합니다(텍스처에 칠해진 룬 색은 그대로 보임)."));
				}
			}
			else
			{
				if (val3.HasProperty("_EmissionColor"))
				{
					val3.SetColor("_EmissionColor", Color.black);
				}
				val3.DisableKeyword("_EMISSION");
			}
			((Renderer)componentInChildren).enabled = false;
			LODGroup[] componentsInChildren = prefab.GetComponentsInChildren<LODGroup>(true);
			for (int i = 0; i < componentsInChildren.Length; i++)
			{
				componentsInChildren[i].enabled = false;
			}
			ParticleSystem[] componentsInChildren2 = prefab.GetComponentsInChildren<ParticleSystem>(true);
			foreach (ParticleSystem val5 in componentsInChildren2)
			{
				if ((Object)(object)((Component)val5).gameObject != (Object)(object)prefab)
				{
					((Component)val5).gameObject.SetActive(false);
				}
			}
			Collider[] componentsInChildren3 = prefab.GetComponentsInChildren<Collider>(true);
			for (int i = 0; i < componentsInChildren3.Length; i++)
			{
				componentsInChildren3[i].enabled = false;
			}
			GameObject val6 = new GameObject(def.PrefabId + "_Model");
			val6.transform.SetParent(prefab.transform, false);
			val6.layer = prefab.layer;
			val6.AddComponent<MeshFilter>().sharedMesh = val;
			((Renderer)val6.AddComponent<MeshRenderer>()).sharedMaterial = val3;
			BoxCollider obj = val6.AddComponent<BoxCollider>();
			Bounds bounds = val.bounds;
			obj.center = ((Bounds)(ref bounds)).center;
			bounds = val.bounds;
			obj.size = ((Bounds)(ref bounds)).size;
			s_materials[def.PrefabId] = val3;
		}

		public static void ApplyBrightness()
		{
			foreach (Material value in s_materials.Values)
			{
				ApplyColorForBrightness(value);
			}
		}

		private static void ApplyColorForBrightness(Material mat)
		{
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			if (mat.HasProperty("_Color"))
			{
				float num = ((RepairKitsConfig.DropModelBrightness != null) ? RepairKitsConfig.DropModelBrightness.Value : 1f);
				mat.SetColor("_Color", new Color(num, num, num, 1f));
			}
		}

		public static bool TryGetMaterial(string prefabId, out Material mat)
		{
			return s_materials.TryGetValue(prefabId, out mat);
		}

		private static void TryClearTexture(Material mat, string property)
		{
			if (mat.HasProperty(property))
			{
				mat.SetTexture(property, (Texture)null);
			}
		}
	}
}
namespace RepairKits.Diagnostics
{
	internal static class DurabilityDebugLog
	{
		private const int MaxLines = 40;

		private static int s_count;

		public static void Log(string kind, string itemName, float rawLoss, float appliedLoss, float rate, float before, float after)
		{
			if (RepairKitsConfig.EnableDiagnosticLogs.Value && s_count < 40)
			{
				s_count++;
				Plugin.Log.LogInfo((object)($"[RepairKits:내구도] {kind} {itemName} 원래 손실={rawLoss:F2} 적용 손실={appliedLoss:F2} " + $"(배율 {rate:F2}) 내구도 {before:F1}→{after:F1}"));
			}
		}

		public static void LogNoLoss(string kind)
		{
			if (RepairKitsConfig.EnableDiagnosticLogs.Value && s_count < 40)
			{
				s_count++;
				Plugin.Log.LogInfo((object)("[RepairKits:내구도] " + kind + " 손실 없음"));
			}
		}
	}
	internal static class KitVerification
	{
		private static bool s_done;

		private static readonly FieldRef<ZNetScene, Dictionary<int, GameObject>> s_namedPrefabsRef = BuildFieldRef<ZNetScene, Dictionary<int, GameObject>>("m_namedPrefabs");

		private static readonly FieldRef<ObjectDB, Dictionary<int, GameObject>> s_itemByHashRef = BuildFieldRef<ObjectDB, Dictionary<int, GameObject>>("m_itemByHash");

		private static FieldRef<TTarget, TField> BuildFieldRef<TTarget, TField>(string fieldName)
		{
			try
			{
				return AccessTools.FieldRefAccess<TTarget, TField>(fieldName);
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"[RepairKits] {typeof(TTarget).Name}.{fieldName} 리플렉션 접근 실패: {arg}");
				return null;
			}
		}

		public static void Tick()
		{
			if (!RepairKitsConfig.EnableDiagnosticLogs.Value)
			{
				return;
			}
			if ((Object)(object)Player.m_localPlayer == (Object)null)
			{
				s_done = false;
			}
			else if (!s_done)
			{
				s_done = true;
				KitDefinition[] all = KitDefinition.All;
				foreach (KitDefinition def in all)
				{
					VerifyOne(def);
					LogMaterialInfo(def);
				}
				VerifyObjectDbEmptyCount();
			}
		}

		private static void LogMaterialInfo(KitDefinition def)
		{
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
			if (!KitVisuals.TryGetMaterial(def.PrefabId, out var mat) || (Object)(object)mat == (Object)null)
			{
				Plugin.Log.LogWarning((object)("[RepairKits:재질] " + def.PrefabId + " 머티리얼을 찾지 못함."));
				return;
			}
			string text = (((Object)(object)mat.shader != (Object)null) ? ((Object)mat.shader).name : "(없음)");
			Texture mainTexture = mat.mainTexture;
			Texture2D val = (Texture2D)(object)((mainTexture is Texture2D) ? mainTexture : null);
			string text2 = (((Object)(object)val != (Object)null) ? ((Texture)val).isDataSRGB.ToString() : "알수없음(텍스처 없음)");
			bool flag = mat.IsKeywordEnabled("_EMISSION");
			string text3 = (mat.HasProperty("_Color") ? ((object)mat.GetColor("_Color")/*cast due to .constrained prefix*/).ToString() : "(없음)");
			string text4 = "(없음)";
			string[] array = new string[3] { "_Glossiness", "_Smoothness", "_Shininess" };
			foreach (string text5 in array)
			{
				if (mat.HasProperty(text5))
				{
					text4 = $"{text5}={mat.GetFloat(text5):F2}";
					break;
				}
			}
			Plugin.Log.LogInfo((object)("[RepairKits:재질] " + def.PrefabId + " 셰이더=" + text + " sRGB=" + text2 + " 발광=" + (flag ? "켜짐" : "꺼짐") + " _Color=" + text3 + " 광택=" + text4));
		}

		private static void VerifyOne(KitDefinition def)
		{
			if (!KitItems.TryGetRegistered(def.PrefabId, out var item))
			{
				Plugin.Log.LogWarning((object)("[RepairKits:검증] " + def.PrefabId + " 프리팹=실패(등록 안 됨)"));
				return;
			}
			GameObject itemPrefab = item.ItemPrefab;
			bool flag = (Object)(object)itemPrefab != (Object)null;
			int stableHashCode = StringExtensionMethods.GetStableHashCode(def.PrefabId);
			Dictionary<int, GameObject> dictionary = (((Object)(object)ZNetScene.instance != (Object)null && s_namedPrefabsRef != null) ? s_namedPrefabsRef.Invoke(ZNetScene.instance) : null);
			bool flag2 = flag && dictionary != null && dictionary.ContainsKey(stableHashCode);
			Dictionary<int, GameObject> dictionary2 = (((Object)(object)ObjectDB.instance != (Object)null && s_itemByHashRef != null) ? s_itemByHashRef.Invoke(ObjectDB.instance) : null);
			bool flag3 = flag && dictionary2 != null && dictionary2.ContainsKey(stableHashCode);
			bool flag4 = item.Recipe != null;
			Sprite[] array = ((!flag) ? null : item.ItemDrop?.m_itemData?.m_shared?.m_icons);
			bool flag5 = array != null && array.Length != 0 && (Object)(object)array[0] != (Object)null;
			string text = "실패";
			if (flag)
			{
				Transform val = itemPrefab.transform.Find(def.PrefabId + "_Model");
				MeshFilter val2 = (((Object)(object)val != (Object)null) ? ((Component)val).GetComponent<MeshFilter>() : null);
				Mesh val3 = (((Object)(object)val2 != (Object)null) ? val2.sharedMesh : null);
				text = (((Object)(object)val3 != (Object)null) ? $"OK({val3.vertexCount})" : "실패(0)");
			}
			else
			{
				text = "실패(0)";
			}
			bool flag6 = false;
			if (flag)
			{
				Transform val4 = itemPrefab.transform.Find(def.PrefabId + "_Model");
				MeshRenderer val5 = (((Object)(object)val4 != (Object)null) ? ((Component)val4).GetComponent<MeshRenderer>() : null);
				flag6 = (Object)(object)val5 != (Object)null && (Object)(object)((Renderer)val5).sharedMaterial != (Object)null && (Object)(object)((Renderer)val5).sharedMaterial.mainTexture != (Object)null;
			}
			Plugin.Log.LogInfo((object)("[RepairKits:검증] " + def.PrefabId + " 프리팹=" + (flag ? "OK" : "실패") + " ZNetScene=" + (flag2 ? "OK" : "실패") + " ObjectDB=" + (flag3 ? "OK" : "실패") + " 레시피=" + (flag4 ? "OK" : "실패") + " 아이콘=" + (flag5 ? "OK" : "실패") + " 메시=" + text + " 텍스처=" + (flag6 ? "OK" : "실패")));
		}

		private static void VerifyObjectDbEmptyCount()
		{
			try
			{
				ObjectDB instance = ObjectDB.instance;
				if (instance?.m_items != null)
				{
					int num = instance.m_items.Count((GameObject i) => (Object)(object)i == (Object)null);
					Plugin.Log.LogInfo((object)$"[RepairKits:검증] ObjectDB 빈 항목 수 = {num}");
				}
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"[RepairKits] ObjectDB 빈 항목 수 확인 중 오류: {arg}");
			}
		}
	}
	internal static class PatchOrderDump
	{
		private static readonly (Type Type, string Method)[] s_targets = new(Type, string)[6]
		{
			(typeof(Player), "DamageArmorDurability"),
			(typeof(Humanoid), "BlockAttack"),
			(typeof(InventoryGrid), "CreateItemTooltip"),
			(typeof(InventoryGui), "CanRepair"),
			(typeof(InventoryGui), "UpdateRepair"),
			(typeof(InventoryGui), "Update")
		};

		private static bool s_done;

		public static void LogAll()
		{
			if (!s_done && RepairKitsConfig.EnableDiagnosticLogs.Value)
			{
				s_done = true;
				(Type, string)[] array = s_targets;
				for (int i = 0; i < array.Length; i++)
				{
					var (type, methodName) = array[i];
					LogOne(type, methodName);
				}
			}
		}

		private static void LogOne(Type type, string methodName)
		{
			try
			{
				MethodInfo methodInfo = AccessTools.Method(type, methodName, (Type[])null, (Type[])null);
				if (methodInfo == null)
				{
					Plugin.Log.LogWarning((object)("[RepairKits:패치순서] " + type.Name + "." + methodName + ": 메서드를 찾지 못함."));
					return;
				}
				Patches patchInfo = Harmony.GetPatchInfo((MethodBase)methodInfo);
				if (patchInfo == null)
				{
					Plugin.Log.LogInfo((object)("[RepairKits:패치순서] " + type.Name + "." + methodName + " Prefix=[] Postfix=[] Transpiler=[]"));
					return;
				}
				string text = Format(patchInfo.Prefixes);
				string text2 = Format(patchInfo.Postfixes);
				string text3 = Format(patchInfo.Transpilers);
				Plugin.Log.LogInfo((object)("[RepairKits:패치순서] " + type.Name + "." + methodName + " Prefix=[" + text + "] Postfix=[" + text2 + "] Transpiler=[" + text3 + "]"));
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"[RepairKits:패치순서] {type.Name}.{methodName} 확인 중 오류: {arg}");
			}
		}

		private static string Format(ReadOnlyCollection<Patch> patches)
		{
			if (patches == null || patches.Count == 0)
			{
				return string.Empty;
			}
			StringBuilder stringBuilder = new StringBuilder();
			List<Patch> list = patches.OrderByDescending((Patch p) => p.priority).ToList();
			for (int num = 0; num < list.Count; num++)
			{
				Patch val = list[num];
				if (num > 0)
				{
					stringBuilder.Append(", ");
				}
				stringBuilder.Append($"{val.owner}:{val.PatchMethod.DeclaringType?.Name}.{val.PatchMethod.Name}(우선순위={val.priority})");
			}
			return stringBuilder.ToString();
		}
	}
}
namespace RepairKits.Config
{
	internal static class RepairKitsConfig
	{
		public static ConfigEntry<float> ArmorDurabilityRate;

		public static ConfigEntry<float> ShieldDurabilityRate;

		public static ConfigEntry<bool> EnableRightClickRepair;

		public static ConfigEntry<string> ForcedClassification;

		public static ConfigEntry<KeyboardShortcut> OpenRepairWindowKey;

		public static ConfigEntry<bool> EnableDiagnosticLogs;

		public static ConfigEntry<float> DropModelBrightness;

		public static ConfigEntry<string> RepairOverlayPosition;

		public static ConfigEntry<bool> ResetRepairOverlayPosition;

		public static ConfigEntry<float> WhetstoneMaxDurability;

		public static ConfigEntry<string> WhetstoneRecipe;

		public static ConfigEntry<float> WhetstoneWeight;

		public static ConfigEntry<float> OilJarMaxDurability;

		public static ConfigEntry<string> OilJarRecipe;

		public static ConfigEntry<float> OilJarWeight;

		public static ConfigEntry<float> TanningBundleMaxDurability;

		public static ConfigEntry<string> TanningBundleRecipe;

		public static ConfigEntry<float> TanningBundleWeight;

		public static ConfigEntry<float> RuneChiselMaxDurability;

		public static ConfigEntry<string> RuneChiselRecipe;

		public static ConfigEntry<float> RuneChiselWeight;

		public static void Init(ConfigFile config)
		{
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ec: Expected O, but got Unknown
			ArmorDurabilityRate = config.Bind<float>("(General) 일반", "(General) ArmorDurabilityRate", 0.33f, "방어구가 피격 시 잃는 내구도 배율(바닐라 대비). 0.33 = 1/3. 1/2~1/4 권장.");
			ShieldDurabilityRate = config.Bind<float>("(General) 일반", "(General) ShieldDurabilityRate", 0.33f, "방패가 막기 시 잃는 내구도 배율(바닐라 대비). 0.33 = 1/3. 1/2~1/4 권장.");
			EnableRightClickRepair = config.Bind<bool>("(General) 일반", "(General) EnableRightClickRepair", true, "키트를 우클릭하면 분류가 맞는 손상 장비를 자동으로 일괄 수리합니다.");
			ForcedClassification = config.Bind<string>("(General) 일반", "(General) ForcedClassification", "", "분류 자동판별 보정용 강제 지정 목록. 형식: \"프리팹이름=키트종류\" 쉼표 구분(키트종류: Whetstone/OilJar/TanningBundle/RuneChisel). 예: ArmorChestIronA=OilJar,TrophyX=Whetstone");
			OpenRepairWindowKey = config.Bind<KeyboardShortcut>("(General) 일반", "(General) OpenRepairWindowKey", new KeyboardShortcut((KeyCode)101, Array.Empty<KeyCode>()), "인벤토리에서 키트에 커서를 올린 채 이 키를 누르면 수리창을 엽니다.");
			EnableDiagnosticLogs = config.Bind<bool>("(General) 일반", "(General) EnableDiagnosticLogs", false, "진단용 로그를 전부 켭니다([RepairKits:검증]/[재질]/[패치순서]/[내구도]/[수리창]). 오류·경고와 시작 시 빌드정보·로드 완료 줄은 이 설정과 무관하게 항상 출력됩니다.");
			DropModelBrightness = config.Bind<float>("(General) 일반", "(General) DropModelBrightness", 1f, new ConfigDescription("바닥에 떨어진 키트 모델의 밝기 배율.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.3f, 1.5f), Array.Empty<object>()));
			RepairOverlayPosition = config.Bind<string>("(General) 일반", "(General) RepairOverlayPosition", "", "수리창의 소모량 표시+수리 버튼 묶음 위치(내부 저장용 — Ctrl+드래그로 옮기면 자동 기록됩니다, 직접 수정하지 마세요).");
			ResetRepairOverlayPosition = config.Bind<bool>("(General) 일반", "(General) ResetRepairOverlayPosition", false, "켜면 수리창의 소모량 표시+수리 버튼 묶음 위치를 기본값으로 되돌리고 자동으로 다시 꺼집니다.");
			WhetstoneMaxDurability = config.Bind<float>("(Whetstone) 숫돌", "(Whetstone) MaxDurability", 3000f, "숫돌 최대 내구도.");
			WhetstoneRecipe = config.Bind<string>("(Whetstone) 숫돌", "(Whetstone) Recipe", "Stone:5,Flint:2,Resin:2", "숫돌 제작 레시피(\"재료:수량\" 쉼표 구분). 변경은 다음 게임 재시작부터 적용됩니다.");
			WhetstoneWeight = config.Bind<float>("(Whetstone) 숫돌", "(Whetstone) Weight", 1f, "숫돌 무게.");
			OilJarMaxDurability = config.Bind<float>("(OilJar) 기름 단지", "(OilJar) MaxDurability", 10000f, "기름 단지 최대 내구도.");
			OilJarRecipe = config.Bind<string>("(OilJar) 기름 단지", "(OilJar) Recipe", "Resin:10,Coal:5", "기름 단지 제작 레시피(\"재료:수량\" 쉼표 구분). 변경은 다음 게임 재시작부터 적용됩니다.");
			OilJarWeight = config.Bind<float>("(OilJar) 기름 단지", "(OilJar) Weight", 2f, "기름 단지 무게.");
			TanningBundleMaxDurability = config.Bind<float>("(TanningBundle) 무두 꾸러미", "(TanningBundle) MaxDurability", 10000f, "무두 꾸러미 최대 내구도.");
			TanningBundleRecipe = config.Bind<string>("(TanningBundle) 무두 꾸러미", "(TanningBundle) Recipe", "LeatherScraps:6,BoneFragments:4,Resin:4", "무두 꾸러미 제작 레시피(\"재료:수량\" 쉼표 구분). 변경은 다음 게임 재시작부터 적용됩니다.");
			TanningBundleWeight = config.Bind<float>("(TanningBundle) 무두 꾸러미", "(TanningBundle) Weight", 1.5f, "무두 꾸러미 무게.");
			RuneChiselMaxDurability = config.Bind<float>("(RuneChisel) 룬 끌", "(RuneChisel) MaxDurability", 3000f, "룬 끌 최대 내구도.");
			RuneChiselRecipe = config.Bind<string>("(RuneChisel) 룬 끌", "(RuneChisel) Recipe", "Eitr:3,YggdrasilWood:5", "룬 끌 제작 레시피(\"재료:수량\" 쉼표 구분). 변경은 다음 게임 재시작부터 적용됩니다.");
			RuneChiselWeight = config.Bind<float>("(RuneChisel) 룬 끌", "(RuneChisel) Weight", 1f, "룬 끌 무게.");
			DropModelBrightness.SettingChanged += delegate
			{
				KitVisuals.ApplyBrightness();
			};
			RepairOverlayPosition.SettingChanged += delegate
			{
				RepairWindow.ApplyOverlayPositionFromConfig();
			};
			ResetRepairOverlayPosition.SettingChanged += delegate
			{
				if (ResetRepairOverlayPosition.Value)
				{
					RepairOverlayPosition.Value = "";
					ResetRepairOverlayPosition.Value = false;
				}
			};
		}

		public static float GetMaxDurability(KitKind kind)
		{
			return kind switch
			{
				KitKind.Whetstone => WhetstoneMaxDurability.Value, 
				KitKind.OilJar => OilJarMaxDurability.Value, 
				KitKind.TanningBundle => TanningBundleMaxDurability.Value, 
				KitKind.RuneChisel => RuneChiselMaxDurability.Value, 
				_ => 1000f, 
			};
		}

		public static float GetWeight(KitKind kind)
		{
			return kind switch
			{
				KitKind.Whetstone => WhetstoneWeight.Value, 
				KitKind.OilJar => OilJarWeight.Value, 
				KitKind.TanningBundle => TanningBundleWeight.Value, 
				KitKind.RuneChisel => RuneChiselWeight.Value, 
				_ => 1f, 
			};
		}

		public static string GetRecipe(KitKind kind)
		{
			return kind switch
			{
				KitKind.Whetstone => WhetstoneRecipe.Value, 
				KitKind.OilJar => OilJarRecipe.Value, 
				KitKind.TanningBundle => TanningBundleRecipe.Value, 
				KitKind.RuneChisel => RuneChiselRecipe.Value, 
				_ => "", 
			};
		}

		public static IEnumerable<KeyValuePair<string, int>> ParseRecipe(string raw)
		{
			if (string.IsNullOrWhiteSpace(raw))
			{
				yield break;
			}
			string[] array = raw.Split(new char[1] { ',' });
			for (int i = 0; i < array.Length; i++)
			{
				string text = array[i].Trim();
				if (text.Length == 0)
				{
					continue;
				}
				int num = text.IndexOf(':');
				if (num <= 0 || num == text.Length - 1)
				{
					Plugin.Log.LogWarning((object)("[RepairKits] 레시피 항목 \"" + text + "\" 형식이 \"재료:수량\"이 아니라 무시합니다."));
					continue;
				}
				string key = text.Substring(0, num).Trim();
				if (!int.TryParse(text.Substring(num + 1).Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out var result) || result <= 0)
				{
					Plugin.Log.LogWarning((object)("[RepairKits] 레시피 항목 \"" + text + "\"의 수량을 해석할 수 없어 무시합니다."));
				}
				else
				{
					yield return new KeyValuePair<string, int>(key, result);
				}
			}
		}

		public static Dictionary<string, KitKind> ParseForcedClassification()
		{
			Dictionary<string, KitKind> dictionary = new Dictionary<string, KitKind>(StringComparer.OrdinalIgnoreCase);
			string value = ForcedClassification.Value;
			if (string.IsNullOrWhiteSpace(value))
			{
				return dictionary;
			}
			string[] array = value.Split(new char[1] { ',' });
			for (int i = 0; i < array.Length; i++)
			{
				string text = array[i].Trim();
				if (text.Length == 0)
				{
					continue;
				}
				int num = text.IndexOf('=');
				if (num <= 0 || num == text.Length - 1)
				{
					Plugin.Log.LogWarning((object)("[RepairKits] ForcedClassification 항목 \"" + text + "\" 형식이 \"프리팹이름=키트종류\"가 아니라 무시합니다."));
					continue;
				}
				string key = text.Substring(0, num).Trim();
				string text2 = text.Substring(num + 1).Trim();
				if (!Enum.TryParse<KitKind>(text2, ignoreCase: true, out var result))
				{
					Plugin.Log.LogWarning((object)("[RepairKits] ForcedClassification 항목 \"" + text + "\"의 키트종류 \"" + text2 + "\"를 해석할 수 없어 무시합니다."));
				}
				else
				{
					dictionary[key] = result;
				}
			}
			return dictionary;
		}
	}
}
namespace RepairKits.Assets
{
	internal static class EmbeddedAssets
	{
		public static byte[] ReadBytes(string fileName)
		{
			Assembly assembly = typeof(EmbeddedAssets).Assembly;
			string text = assembly.GetManifestResourceNames().FirstOrDefault((string n) => n.EndsWith("." + fileName, StringComparison.OrdinalIgnoreCase));
			if (text == null)
			{
				Plugin.Log.LogError((object)("[RepairKits] 임베디드 리소스를 찾을 수 없습니다: " + fileName));
				return null;
			}
			using Stream stream = assembly.GetManifestResourceStream(text);
			if (stream == null)
			{
				return null;
			}
			using MemoryStream memoryStream = new MemoryStream();
			stream.CopyTo(memoryStream);
			return memoryStream.ToArray();
		}

		public static string ReadText(string fileName)
		{
			byte[] array = ReadBytes(fileName);
			if (array != null)
			{
				return Encoding.UTF8.GetString(array);
			}
			return null;
		}
	}
	internal static class ObjMeshLoader
	{
		public static Mesh Load(string objText, string meshName)
		{
			//IL_01b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ea: Expected O, but got Unknown
			//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_010b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0137: Unknown result type (might be due to invalid IL or missing references)
			List<Vector3> list = new List<Vector3>();
			List<Vector2> list2 = new List<Vector2>();
			List<Vector3> list3 = new List<Vector3>();
			List<Vector3> list4 = new List<Vector3>();
			List<Vector2> list5 = new List<Vector2>();
			List<Vector3> list6 = new List<Vector3>();
			List<int> list7 = new List<int>();
			Dictionary<string, int> cornerCache = new Dictionary<string, int>();
			string[] array = objText.Split(new char[1] { '\n' });
			for (int i = 0; i < array.Length; i++)
			{
				string text = array[i].Trim();
				if (text.Length == 0 || text[0] == '#')
				{
					continue;
				}
				string[] array2 = text.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries);
				if (array2.Length == 0)
				{
					continue;
				}
				switch (array2[0])
				{
				case "v":
					list.Add(new Vector3(0f - ParseFloat(array2[1]), ParseFloat(array2[2]), ParseFloat(array2[3])));
					break;
				case "vt":
					list2.Add(new Vector2(ParseFloat(array2[1]), ParseFloat(array2[2])));
					break;
				case "vn":
					list3.Add(new Vector3(0f - ParseFloat(array2[1]), ParseFloat(array2[2]), ParseFloat(array2[3])));
					break;
				case "f":
					if (array2.Length >= 4)
					{
						int item = ResolveCorner(array2[1], list, list2, list3, list4, list5, list6, cornerCache);
						int item2 = ResolveCorner(array2[2], list, list2, list3, list4, list5, list6, cornerCache);
						int item3 = ResolveCorner(array2[3], list, list2, list3, list4, list5, list6, cornerCache);
						list7.Add(item);
						list7.Add(item3);
						list7.Add(item2);
					}
					break;
				}
			}
			Mesh val = new Mesh
			{
				name = meshName
			};
			val.SetVertices(list4);
			val.SetUVs(0, list5);
			val.SetNormals(list6);
			val.SetTriangles(list7, 0, true);
			val.RecalculateBounds();
			return val;
		}

		private static int ResolveCorner(string token, List<Vector3> positions, List<Vector2> uvs, List<Vector3> normals, List<Vector3> outVerts, List<Vector2> outUVs, List<Vector3> outNormals, Dictionary<string, int> cornerCache)
		{
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
			if (cornerCache.TryGetValue(token, out var value))
			{
				return value;
			}
			string[] array = token.Split(new char[1] { '/' });
			int index = int.Parse(array[0], NumberStyles.Integer, CultureInfo.InvariantCulture) - 1;
			int num = ((array.Length > 1 && array[1].Length > 0) ? (int.Parse(array[1], NumberStyles.Integer, CultureInfo.InvariantCulture) - 1) : (-1));
			int num2 = ((array.Length > 2 && array[2].Length > 0) ? (int.Parse(array[2], NumberStyles.Integer, CultureInfo.InvariantCulture) - 1) : (-1));
			outVerts.Add(positions[index]);
			outUVs.Add((num >= 0 && num < uvs.Count) ? uvs[num] : Vector2.zero);
			outNormals.Add((num2 >= 0 && num2 < normals.Count) ? normals[num2] : Vector3.up);
			return cornerCache[token] = outVerts.Count - 1;
		}

		private static float ParseFloat(string s)
		{
			return float.Parse(s, NumberStyles.Float, CultureInfo.InvariantCulture);
		}
	}
	internal static class TextureLoader
	{
		private static readonly MethodInfo s_loadImageMethod = AccessTools.Method(typeof(ImageConversion), "LoadImage", new Type[2]
		{
			typeof(Texture2D),
			typeof(byte[])
		}, (Type[])null);

		public static bool LoadImage(Texture2D texture, byte[] data)
		{
			if (s_loadImageMethod == null)
			{
				Plugin.Log.LogError((object)"[RepairKits] ImageConversion.LoadImage(Texture2D, byte[]) 메서드를 찾지 못했습니다.");
				return false;
			}
			try
			{
				return (bool)s_loadImageMethod.Invoke(null, new object[2] { texture, data });
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"[RepairKits] 텍스처 LoadImage 호출 실패: {arg}");
				return false;
			}
		}
	}
}