Decompiled source of SunHavenTodo v1.1.8

SunhavenTodo.dll

Decompiled 11 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using SunhavenMods.Shared;
using SunhavenTodo.Data;
using SunhavenTodo.UI;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Networking;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using Wish;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyCompany("SunhavenTodo")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+23a8e00922faf1f676c5a066e93916fcaf0ab708")]
[assembly: AssemblyProduct("SunhavenTodo")]
[assembly: AssemblyTitle("SunhavenTodo")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace SunhavenMods.Shared
{
	public static class VersionChecker
	{
		public class VersionCheckResult
		{
			public bool Success { get; set; }

			public bool UpdateAvailable { get; set; }

			public string CurrentVersion { get; set; }

			public string LatestVersion { get; set; }

			public string ModName { get; set; }

			public string NexusUrl { get; set; }

			public string Changelog { get; set; }

			public string ErrorMessage { get; set; }
		}

		private class VersionCheckRunner : MonoBehaviour
		{
			public void StartCheck(string pluginGuid, string currentVersion, Action<VersionCheckResult> onComplete)
			{
				((MonoBehaviour)this).StartCoroutine(CheckVersionCoroutine(pluginGuid, currentVersion, onComplete));
			}

			private IEnumerator CheckVersionCoroutine(string pluginGuid, string currentVersion, Action<VersionCheckResult> onComplete)
			{
				VersionCheckResult result = new VersionCheckResult
				{
					CurrentVersion = currentVersion
				};
				UnityWebRequest www = UnityWebRequest.Get("https://azraelgodking.github.io/SunhavenMod/versions.json");
				try
				{
					www.timeout = 10;
					yield return www.SendWebRequest();
					if ((int)www.result == 2 || (int)www.result == 3)
					{
						result.Success = false;
						result.ErrorMessage = "Network error: " + www.error;
						LogWarning(result.ErrorMessage);
						onComplete?.Invoke(result);
						Object.Destroy((Object)(object)((Component)this).gameObject);
						yield break;
					}
					try
					{
						string json = www.downloadHandler.text;
						string modPattern = "\"" + Regex.Escape(pluginGuid) + "\"\\s*:\\s*\\{([^}]+)\\}";
						Match modMatch = Regex.Match(json, modPattern, RegexOptions.Singleline);
						if (!modMatch.Success)
						{
							result.Success = false;
							result.ErrorMessage = "Mod '" + pluginGuid + "' not found in versions.json";
							LogWarning(result.ErrorMessage);
							onComplete?.Invoke(result);
							Object.Destroy((Object)(object)((Component)this).gameObject);
							yield break;
						}
						string modJson = modMatch.Groups[1].Value;
						result.LatestVersion = ExtractJsonString(modJson, "version");
						result.ModName = ExtractJsonString(modJson, "name");
						result.NexusUrl = ExtractJsonString(modJson, "nexus");
						result.Changelog = ExtractJsonString(modJson, "changelog");
						if (string.IsNullOrEmpty(result.LatestVersion))
						{
							result.Success = false;
							result.ErrorMessage = "Could not parse version from response";
							LogWarning(result.ErrorMessage);
							onComplete?.Invoke(result);
							Object.Destroy((Object)(object)((Component)this).gameObject);
							yield break;
						}
						result.Success = true;
						result.UpdateAvailable = CompareVersions(currentVersion, result.LatestVersion) < 0;
						if (result.UpdateAvailable)
						{
							Log("Update available for " + result.ModName + ": " + currentVersion + " -> " + result.LatestVersion);
						}
						else
						{
							Log(result.ModName + " is up to date (v" + currentVersion + ")");
						}
					}
					catch (Exception ex)
					{
						result.Success = false;
						result.ErrorMessage = "Parse error: " + ex.Message;
						LogError(result.ErrorMessage);
					}
				}
				finally
				{
					((IDisposable)www)?.Dispose();
				}
				onComplete?.Invoke(result);
				Object.Destroy((Object)(object)((Component)this).gameObject);
			}

			private string ExtractJsonString(string json, string key)
			{
				string pattern = "\"" + key + "\"\\s*:\\s*(?:\"([^\"]*)\"|null)";
				Match match = Regex.Match(json, pattern);
				return match.Success ? match.Groups[1].Value : null;
			}
		}

		private const string VersionsUrl = "https://azraelgodking.github.io/SunhavenMod/versions.json";

		private static ManualLogSource _logger;

		public static void CheckForUpdate(string pluginGuid, string currentVersion, ManualLogSource logger = null, Action<VersionCheckResult> onComplete = null)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			_logger = logger;
			VersionCheckRunner versionCheckRunner = new GameObject("VersionChecker").AddComponent<VersionCheckRunner>();
			Object.DontDestroyOnLoad((Object)(object)((Component)versionCheckRunner).gameObject);
			SceneRootSurvivor.TryRegisterPersistentRunnerGameObject(((Component)versionCheckRunner).gameObject);
			versionCheckRunner.StartCheck(pluginGuid, currentVersion, onComplete);
		}

		public static int CompareVersions(string v1, string v2)
		{
			if (string.IsNullOrEmpty(v1) || string.IsNullOrEmpty(v2))
			{
				return 0;
			}
			v1 = v1.TrimStart('v', 'V');
			v2 = v2.TrimStart('v', 'V');
			string[] array = v1.Split(new char[1] { '.' });
			string[] array2 = v2.Split(new char[1] { '.' });
			int num = Math.Max(array.Length, array2.Length);
			for (int i = 0; i < num; i++)
			{
				int result;
				int num2 = ((i < array.Length && int.TryParse(array[i], out result)) ? result : 0);
				int result2;
				int num3 = ((i < array2.Length && int.TryParse(array2[i], out result2)) ? result2 : 0);
				if (num2 < num3)
				{
					return -1;
				}
				if (num2 > num3)
				{
					return 1;
				}
			}
			return 0;
		}

		internal static void Log(string message)
		{
			ManualLogSource logger = _logger;
			if (logger != null)
			{
				logger.LogInfo((object)("[VersionChecker] " + message));
			}
		}

		internal static void LogWarning(string message)
		{
			ManualLogSource logger = _logger;
			if (logger != null)
			{
				logger.LogWarning((object)("[VersionChecker] " + message));
			}
		}

		internal static void LogError(string message)
		{
			ManualLogSource logger = _logger;
			if (logger != null)
			{
				logger.LogError((object)("[VersionChecker] " + message));
			}
		}
	}
	public static class VersionCheckerExtensions
	{
		public static void NotifyUpdateAvailable(this VersionChecker.VersionCheckResult result, ManualLogSource logger = null)
		{
			if (!result.UpdateAvailable)
			{
				return;
			}
			string text = result.ModName + " update available: v" + result.LatestVersion;
			try
			{
				Type type = ReflectionHelper.FindWishType("NotificationStack");
				if (type != null)
				{
					Type type2 = ReflectionHelper.FindType("SingletonBehaviour`1", "Wish");
					if (type2 != null)
					{
						Type type3 = type2.MakeGenericType(type);
						object obj = type3.GetProperty("Instance")?.GetValue(null);
						if (obj != null)
						{
							MethodInfo method = type.GetMethod("SendNotification", new Type[5]
							{
								typeof(string),
								typeof(int),
								typeof(int),
								typeof(bool),
								typeof(bool)
							});
							if (method != null)
							{
								method.Invoke(obj, new object[5] { text, 0, 1, false, true });
								return;
							}
						}
					}
				}
			}
			catch (Exception ex)
			{
				if (logger != null)
				{
					logger.LogWarning((object)("Failed to send native notification: " + ex.Message));
				}
			}
			if (logger != null)
			{
				logger.LogWarning((object)("[UPDATE AVAILABLE] " + text));
			}
			if (!string.IsNullOrEmpty(result.NexusUrl) && logger != null)
			{
				logger.LogWarning((object)("Download at: " + result.NexusUrl));
			}
		}
	}
	public static class SceneRootSurvivor
	{
		private static readonly object Lock = new object();

		private static readonly List<string> NoKillSubstrings = new List<string>();

		private static Harmony _harmony;

		public static void TryRegisterPersistentRunnerGameObject(GameObject go)
		{
			if (!((Object)(object)go == (Object)null))
			{
				TryAddNoKillListSubstring(((Object)go).name);
			}
		}

		public static void TryAddNoKillListSubstring(string nameSubstring)
		{
			if (string.IsNullOrEmpty(nameSubstring))
			{
				return;
			}
			lock (Lock)
			{
				bool flag = false;
				for (int i = 0; i < NoKillSubstrings.Count; i++)
				{
					if (string.Equals(NoKillSubstrings[i], nameSubstring, StringComparison.OrdinalIgnoreCase))
					{
						flag = true;
						break;
					}
				}
				if (!flag)
				{
					NoKillSubstrings.Add(nameSubstring);
				}
			}
			EnsurePatched();
		}

		private static void EnsurePatched()
		{
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Expected O, but got Unknown
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Expected O, but got Unknown
			if (_harmony != null)
			{
				return;
			}
			lock (Lock)
			{
				if (_harmony == null)
				{
					MethodInfo methodInfo = AccessTools.Method(typeof(Scene), "GetRootGameObjects", Type.EmptyTypes, (Type[])null);
					if (!(methodInfo == null))
					{
						string text = typeof(SceneRootSurvivor).Assembly.GetName().Name ?? "Unknown";
						Harmony val = new Harmony("SunhavenMods.SceneRootSurvivor." + text);
						val.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(typeof(SceneRootSurvivor), "OnGetRootGameObjectsPostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
						_harmony = val;
					}
				}
			}
		}

		private static void OnGetRootGameObjectsPostfix(ref GameObject[] __result)
		{
			if (__result == null || __result.Length == 0)
			{
				return;
			}
			List<string> list;
			lock (Lock)
			{
				if (NoKillSubstrings.Count == 0)
				{
					return;
				}
				list = new List<string>(NoKillSubstrings);
			}
			List<GameObject> list2 = new List<GameObject>(__result);
			for (int i = 0; i < list.Count; i++)
			{
				string noKill = list[i];
				list2.RemoveAll((GameObject a) => (Object)(object)a != (Object)null && ((Object)a).name.IndexOf(noKill, StringComparison.OrdinalIgnoreCase) >= 0);
			}
			__result = list2.ToArray();
		}
	}
	public static class ReflectionHelper
	{
		public static readonly BindingFlags AllBindingFlags = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy;

		public static Type FindType(string typeName, params string[] namespaces)
		{
			Type type = AccessTools.TypeByName(typeName);
			if (type != null)
			{
				return type;
			}
			foreach (string text in namespaces)
			{
				type = AccessTools.TypeByName(text + "." + typeName);
				if (type != null)
				{
					return type;
				}
			}
			Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
			foreach (Assembly assembly in assemblies)
			{
				try
				{
					type = assembly.GetTypes().FirstOrDefault((Type t) => t.Name == typeName || t.FullName == typeName);
					if (type != null)
					{
						return type;
					}
				}
				catch (ReflectionTypeLoadException)
				{
				}
			}
			return null;
		}

		public static Type FindWishType(string typeName)
		{
			return FindType(typeName, "Wish");
		}

		public static object GetStaticValue(Type type, string memberName)
		{
			if (type == null)
			{
				return null;
			}
			PropertyInfo property = type.GetProperty(memberName, AllBindingFlags);
			if (property != null && property.GetMethod != null)
			{
				return property.GetValue(null);
			}
			FieldInfo field = type.GetField(memberName, AllBindingFlags);
			if (field != null)
			{
				return field.GetValue(null);
			}
			return null;
		}

		public static object GetSingletonInstance(Type type)
		{
			if (type == null)
			{
				return null;
			}
			string[] array = new string[5] { "Instance", "instance", "_instance", "Singleton", "singleton" };
			string[] array2 = array;
			foreach (string memberName in array2)
			{
				object staticValue = GetStaticValue(type, memberName);
				if (staticValue != null)
				{
					return staticValue;
				}
			}
			return null;
		}

		public static object GetInstanceValue(object instance, string memberName)
		{
			if (instance == null)
			{
				return null;
			}
			Type type = instance.GetType();
			while (type != null)
			{
				PropertyInfo property = type.GetProperty(memberName, AllBindingFlags);
				if (property != null && property.GetMethod != null)
				{
					return property.GetValue(instance);
				}
				FieldInfo field = type.GetField(memberName, AllBindingFlags);
				if (field != null)
				{
					return field.GetValue(instance);
				}
				type = type.BaseType;
			}
			return null;
		}

		public static bool SetInstanceValue(object instance, string memberName, object value)
		{
			if (instance == null)
			{
				return false;
			}
			Type type = instance.GetType();
			while (type != null)
			{
				PropertyInfo property = type.GetProperty(memberName, AllBindingFlags);
				if (property != null && property.SetMethod != null)
				{
					property.SetValue(instance, value);
					return true;
				}
				FieldInfo field = type.GetField(memberName, AllBindingFlags);
				if (field != null)
				{
					field.SetValue(instance, value);
					return true;
				}
				type = type.BaseType;
			}
			return false;
		}

		public static object InvokeMethod(object instance, string methodName, params object[] args)
		{
			if (instance == null)
			{
				return null;
			}
			Type type = instance.GetType();
			Type[] array = args?.Select((object a) => a?.GetType() ?? typeof(object)).ToArray() ?? Type.EmptyTypes;
			MethodInfo methodInfo = AccessTools.Method(type, methodName, array, (Type[])null);
			if (methodInfo == null)
			{
				methodInfo = type.GetMethod(methodName, AllBindingFlags);
			}
			if (methodInfo == null)
			{
				return null;
			}
			return methodInfo.Invoke(instance, args);
		}

		public static object InvokeStaticMethod(Type type, string methodName, params object[] args)
		{
			if (type == null)
			{
				return null;
			}
			Type[] array = args?.Select((object a) => a?.GetType() ?? typeof(object)).ToArray() ?? Type.EmptyTypes;
			MethodInfo methodInfo = AccessTools.Method(type, methodName, array, (Type[])null);
			if (methodInfo == null)
			{
				methodInfo = type.GetMethod(methodName, AllBindingFlags);
			}
			if (methodInfo == null)
			{
				return null;
			}
			return methodInfo.Invoke(null, args);
		}

		public static FieldInfo[] GetAllFields(Type type)
		{
			if (type == null)
			{
				return Array.Empty<FieldInfo>();
			}
			FieldInfo[] fields = type.GetFields(AllBindingFlags);
			IEnumerable<FieldInfo> second;
			if (!(type.BaseType != null) || !(type.BaseType != typeof(object)))
			{
				second = Enumerable.Empty<FieldInfo>();
			}
			else
			{
				IEnumerable<FieldInfo> allFields = GetAllFields(type.BaseType);
				second = allFields;
			}
			return fields.Concat(second).Distinct().ToArray();
		}

		public static PropertyInfo[] GetAllProperties(Type type)
		{
			if (type == null)
			{
				return Array.Empty<PropertyInfo>();
			}
			PropertyInfo[] properties = type.GetProperties(AllBindingFlags);
			IEnumerable<PropertyInfo> second;
			if (!(type.BaseType != null) || !(type.BaseType != typeof(object)))
			{
				second = Enumerable.Empty<PropertyInfo>();
			}
			else
			{
				IEnumerable<PropertyInfo> allProperties = GetAllProperties(type.BaseType);
				second = allProperties;
			}
			return (from p in properties.Concat(second)
				group p by p.Name into g
				select g.First()).ToArray();
		}

		public static T TryGetValue<T>(object instance, string memberName, T defaultValue = default(T))
		{
			try
			{
				object instanceValue = GetInstanceValue(instance, memberName);
				if (instanceValue is T result)
				{
					return result;
				}
				if (instanceValue != null && typeof(T).IsAssignableFrom(instanceValue.GetType()))
				{
					return (T)instanceValue;
				}
				return defaultValue;
			}
			catch
			{
				return defaultValue;
			}
		}
	}
	public static class IconCache
	{
		private static readonly Dictionary<int, Texture2D> _iconCache = new Dictionary<int, Texture2D>();

		private static readonly HashSet<int> _loadingItems = new HashSet<int>();

		private static readonly HashSet<int> _failedItems = new HashSet<int>();

		private static readonly Dictionary<string, int> _currencyToItemId = new Dictionary<string, int>();

		private static Texture2D _fallbackTexture;

		private static ManualLogSource _log;

		private static Type _databaseType;

		private static Type _itemDataType;

		private static MethodInfo _getDataMethod;

		private static bool _reflectionInitialized;

		private static bool _initialized;

		private static bool _iconsLoaded;

		public static void Initialize(ManualLogSource log, int[] preloadItemIds = null)
		{
			_log = log;
			if (_initialized)
			{
				ManualLogSource log2 = _log;
				if (log2 != null)
				{
					log2.LogDebug((object)"[IconCache] Already initialized");
				}
				return;
			}
			_initialized = true;
			ManualLogSource log3 = _log;
			if (log3 != null)
			{
				log3.LogInfo((object)"[IconCache] Initializing icon cache...");
			}
			_fallbackTexture = CreateFallbackTexture();
			ManualLogSource log4 = _log;
			if (log4 != null)
			{
				log4.LogInfo((object)"[IconCache] Created fallback texture");
			}
			if (preloadItemIds != null && preloadItemIds.Length != 0)
			{
				ManualLogSource log5 = _log;
				if (log5 != null)
				{
					log5.LogInfo((object)"[IconCache] Preload item IDs registered (loading deferred until LoadAllIcons)");
				}
			}
		}

		public static void RegisterCurrency(string currencyId, int itemId)
		{
			_currencyToItemId[currencyId] = itemId;
		}

		public static void LoadAllIcons()
		{
			if (_iconsLoaded)
			{
				ManualLogSource log = _log;
				if (log != null)
				{
					log.LogDebug((object)"[IconCache] Icons already loaded, skipping");
				}
				return;
			}
			if (!InitializeReflection())
			{
				ManualLogSource log2 = _log;
				if (log2 != null)
				{
					log2.LogError((object)"[IconCache] Failed to initialize reflection, cannot load icons");
				}
				_iconsLoaded = true;
				return;
			}
			foreach (KeyValuePair<string, int> item in _currencyToItemId)
			{
				ManualLogSource log3 = _log;
				if (log3 != null)
				{
					log3.LogDebug((object)$"[IconCache] Queuing load for: {item.Key} (ItemID: {item.Value})");
				}
				LoadIcon(item.Value);
			}
			_iconsLoaded = true;
			ManualLogSource log4 = _log;
			if (log4 != null)
			{
				log4.LogInfo((object)$"[IconCache] Queued {_currencyToItemId.Count} icons for loading");
			}
		}

		public static Texture2D GetIconForCurrency(string currencyId)
		{
			if (_currencyToItemId.TryGetValue(currencyId, out var value))
			{
				return GetIcon(value);
			}
			return GetFallbackTexture();
		}

		public static Texture2D GetIcon(int itemId)
		{
			if (itemId <= 0)
			{
				return GetFallbackTexture();
			}
			if (_iconCache.TryGetValue(itemId, out var value))
			{
				return value;
			}
			if (!_loadingItems.Contains(itemId) && !_failedItems.Contains(itemId))
			{
				LoadIcon(itemId);
			}
			return GetFallbackTexture();
		}

		private static Texture2D GetFallbackTexture()
		{
			if ((Object)(object)_fallbackTexture == (Object)null)
			{
				_fallbackTexture = CreateFallbackTexture();
			}
			return _fallbackTexture;
		}

		public static bool IsIconLoaded(int itemId)
		{
			return _iconCache.ContainsKey(itemId);
		}

		public static bool IsIconLoaded(string currencyId)
		{
			int value;
			return _currencyToItemId.TryGetValue(currencyId, out value) && IsIconLoaded(value);
		}

		public static int GetItemIdForCurrency(string currencyId)
		{
			int value;
			return _currencyToItemId.TryGetValue(currencyId, out value) ? value : (-1);
		}

		private static bool InitializeReflection()
		{
			if (_reflectionInitialized)
			{
				return _databaseType != null && _itemDataType != null && _getDataMethod != null;
			}
			_reflectionInitialized = true;
			try
			{
				string[] array = new string[4] { "Database", "Wish.Database", "PSS.Database", "SunHaven.Database" };
				string[] array2 = array;
				foreach (string text in array2)
				{
					_databaseType = AccessTools.TypeByName(text);
					if (_databaseType != null)
					{
						ManualLogSource log = _log;
						if (log != null)
						{
							log.LogInfo((object)("[IconCache] Found Database type: " + _databaseType.FullName));
						}
						break;
					}
				}
				if (_databaseType == null)
				{
					Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
					foreach (Assembly assembly in assemblies)
					{
						try
						{
							Type[] types = assembly.GetTypes();
							foreach (Type type in types)
							{
								if (!(type.Name == "Database") || type.IsNested)
								{
									continue;
								}
								MethodInfo[] methods = type.GetMethods(BindingFlags.Static | BindingFlags.Public);
								foreach (MethodInfo methodInfo in methods)
								{
									if (methodInfo.Name == "GetData" && methodInfo.IsGenericMethod)
									{
										_databaseType = type;
										ManualLogSource log2 = _log;
										if (log2 != null)
										{
											log2.LogInfo((object)("[IconCache] Found Database type: " + type.FullName));
										}
										break;
									}
								}
								if (_databaseType != null)
								{
									break;
								}
							}
							if (_databaseType != null)
							{
								break;
							}
						}
						catch (Exception ex)
						{
							ManualLogSource log3 = _log;
							if (log3 != null)
							{
								log3.LogDebug((object)("[IconCache] Skipping assembly " + assembly.GetName().Name + ": " + ex.Message));
							}
						}
					}
				}
				if (_databaseType == null)
				{
					ManualLogSource log4 = _log;
					if (log4 != null)
					{
						log4.LogError((object)"[IconCache] Could not find Database type");
					}
					return false;
				}
				_itemDataType = AccessTools.TypeByName("Wish.ItemData");
				if (_itemDataType == null)
				{
					ManualLogSource log5 = _log;
					if (log5 != null)
					{
						log5.LogError((object)"[IconCache] Could not find Wish.ItemData type");
					}
					return false;
				}
				MethodInfo[] methods2 = _databaseType.GetMethods(BindingFlags.Static | BindingFlags.Public);
				MethodInfo[] array3 = methods2;
				foreach (MethodInfo methodInfo2 in array3)
				{
					if (!(methodInfo2.Name == "GetData") || !methodInfo2.IsGenericMethod)
					{
						continue;
					}
					ParameterInfo[] parameters = methodInfo2.GetParameters();
					if (methodInfo2.GetGenericArguments().Length == 1 && parameters.Length == 3 && parameters[0].ParameterType == typeof(int))
					{
						_getDataMethod = methodInfo2.MakeGenericMethod(_itemDataType);
						ManualLogSource log6 = _log;
						if (log6 != null)
						{
							log6.LogInfo((object)"[IconCache] Found Database.GetData method");
						}
						break;
					}
				}
				if (_getDataMethod == null)
				{
					ManualLogSource log7 = _log;
					if (log7 != null)
					{
						log7.LogError((object)"[IconCache] Could not find Database.GetData method");
					}
					return false;
				}
				return true;
			}
			catch (Exception ex2)
			{
				ManualLogSource log8 = _log;
				if (log8 != null)
				{
					log8.LogError((object)("[IconCache] Error initializing reflection: " + ex2.Message));
				}
				return false;
			}
		}

		private static void LoadIcon(int itemId)
		{
			if (itemId <= 0 || _loadingItems.Contains(itemId) || _iconCache.ContainsKey(itemId))
			{
				return;
			}
			_loadingItems.Add(itemId);
			try
			{
				if (!InitializeReflection() || _getDataMethod == null)
				{
					_failedItems.Add(itemId);
					_loadingItems.Remove(itemId);
					return;
				}
				Type delegateType = typeof(Action<>).MakeGenericType(_itemDataType);
				ParameterExpression parameterExpression = Expression.Parameter(_itemDataType, "itemData");
				ConstantExpression arg = Expression.Constant(itemId);
				MethodInfo method = typeof(IconCache).GetMethod("OnIconLoadedInternal", BindingFlags.Static | BindingFlags.NonPublic);
				MethodCallExpression body = Expression.Call(method, arg, Expression.Convert(parameterExpression, typeof(object)));
				Delegate @delegate = Expression.Lambda(delegateType, body, parameterExpression).Compile();
				MethodInfo method2 = typeof(IconCache).GetMethod("OnIconLoadFailed", BindingFlags.Static | BindingFlags.NonPublic);
				Action action = Expression.Lambda<Action>(Expression.Call(method2, arg), Array.Empty<ParameterExpression>()).Compile();
				_getDataMethod.Invoke(null, new object[3] { itemId, @delegate, action });
			}
			catch (Exception ex)
			{
				ManualLogSource log = _log;
				if (log != null)
				{
					log.LogDebug((object)$"[IconCache] Error loading icon {itemId}: {ex.Message}");
				}
				_failedItems.Add(itemId);
				_loadingItems.Remove(itemId);
			}
		}

		private static void OnIconLoadedInternal(int itemId, object itemData)
		{
			_loadingItems.Remove(itemId);
			if (itemData == null)
			{
				_failedItems.Add(itemId);
				return;
			}
			try
			{
				Type type = itemData.GetType();
				object obj = null;
				BindingFlags[] array = new BindingFlags[4]
				{
					BindingFlags.Instance | BindingFlags.Public,
					BindingFlags.Instance | BindingFlags.Public | BindingFlags.FlattenHierarchy,
					BindingFlags.Instance | BindingFlags.NonPublic,
					BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy
				};
				BindingFlags[] array2 = array;
				foreach (BindingFlags bindingAttr in array2)
				{
					PropertyInfo property = type.GetProperty("icon", bindingAttr);
					if (property != null)
					{
						obj = property.GetValue(itemData);
						break;
					}
				}
				if (obj == null)
				{
					BindingFlags[] array3 = array;
					foreach (BindingFlags bindingAttr2 in array3)
					{
						FieldInfo field = type.GetField("icon", bindingAttr2);
						if (field != null)
						{
							obj = field.GetValue(itemData);
							break;
						}
					}
				}
				if (obj == null)
				{
					Type type2 = type;
					while (type2 != null && obj == null)
					{
						PropertyInfo[] properties = type2.GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
						PropertyInfo[] array4 = properties;
						foreach (PropertyInfo propertyInfo in array4)
						{
							if (propertyInfo.Name.Equals("icon", StringComparison.OrdinalIgnoreCase))
							{
								obj = propertyInfo.GetValue(itemData);
								break;
							}
						}
						if (obj == null)
						{
							FieldInfo[] fields = type2.GetFields(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
							FieldInfo[] array5 = fields;
							foreach (FieldInfo fieldInfo in array5)
							{
								if (fieldInfo.Name.Equals("icon", StringComparison.OrdinalIgnoreCase))
								{
									obj = fieldInfo.GetValue(itemData);
									break;
								}
							}
						}
						type2 = type2.BaseType;
					}
				}
				Sprite val = (Sprite)((obj is Sprite) ? obj : null);
				if (val != null)
				{
					CacheSprite(itemId, val);
				}
				else
				{
					_failedItems.Add(itemId);
				}
			}
			catch (Exception ex)
			{
				ManualLogSource log = _log;
				if (log != null)
				{
					log.LogDebug((object)$"[IconCache] Error processing icon {itemId}: {ex.Message}");
				}
				_failedItems.Add(itemId);
			}
		}

		private static void OnIconLoadFailed(int itemId)
		{
			_loadingItems.Remove(itemId);
			_failedItems.Add(itemId);
		}

		private static void CacheSprite(int itemId, Sprite sprite)
		{
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_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)
			if ((Object)(object)sprite == (Object)null || (Object)(object)sprite.texture == (Object)null)
			{
				_failedItems.Add(itemId);
				return;
			}
			try
			{
				Rect rect = sprite.rect;
				Texture2D val;
				if (((Rect)(ref rect)).width == (float)((Texture)sprite.texture).width)
				{
					rect = sprite.rect;
					if (((Rect)(ref rect)).height == (float)((Texture)sprite.texture).height)
					{
						val = sprite.texture;
						goto IL_0084;
					}
				}
				val = ExtractSpriteTexture(sprite);
				goto IL_0084;
				IL_0084:
				if ((Object)(object)val != (Object)null)
				{
					_iconCache[itemId] = val;
				}
				else
				{
					_failedItems.Add(itemId);
				}
			}
			catch (Exception ex)
			{
				ManualLogSource log = _log;
				if (log != null)
				{
					log.LogDebug((object)$"[IconCache] Error caching sprite {itemId}: {ex.Message}");
				}
				_failedItems.Add(itemId);
			}
		}

		private static Texture2D ExtractSpriteTexture(Sprite sprite)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Expected O, but got Unknown
			try
			{
				Rect rect = sprite.rect;
				int num = (int)((Rect)(ref rect)).width;
				int num2 = (int)((Rect)(ref rect)).height;
				if (!((Texture)sprite.texture).isReadable)
				{
					return CopyTextureViaRenderTexture(sprite);
				}
				Texture2D val = new Texture2D(num, num2, (TextureFormat)4, false);
				Color[] pixels = sprite.texture.GetPixels((int)((Rect)(ref rect)).x, (int)((Rect)(ref rect)).y, num, num2);
				val.SetPixels(pixels);
				val.Apply();
				return val;
			}
			catch (Exception ex)
			{
				ManualLogSource log = _log;
				if (log != null)
				{
					log.LogDebug((object)("[IconCache] Error extracting sprite texture: " + ex.Message));
				}
				return null;
			}
		}

		private static Texture2D CopyTextureViaRenderTexture(Sprite sprite)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Expected O, but got Unknown
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				Rect rect = sprite.rect;
				int num = (int)((Rect)(ref rect)).width;
				int num2 = (int)((Rect)(ref rect)).height;
				RenderTexture temporary = RenderTexture.GetTemporary(((Texture)sprite.texture).width, ((Texture)sprite.texture).height, 0, (RenderTextureFormat)0);
				Graphics.Blit((Texture)(object)sprite.texture, temporary);
				RenderTexture active = RenderTexture.active;
				RenderTexture.active = temporary;
				Texture2D val = new Texture2D(num, num2, (TextureFormat)4, false);
				val.ReadPixels(new Rect(((Rect)(ref rect)).x, ((Rect)(ref rect)).y, (float)num, (float)num2), 0, 0);
				val.Apply();
				RenderTexture.active = active;
				RenderTexture.ReleaseTemporary(temporary);
				return val;
			}
			catch (Exception ex)
			{
				ManualLogSource log = _log;
				if (log != null)
				{
					log.LogDebug((object)("[IconCache] Error copying texture via RenderTexture: " + ex.Message));
				}
				return null;
			}
		}

		private static Texture2D CreateFallbackTexture()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Expected O, but got Unknown
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			int num = 32;
			Texture2D val = new Texture2D(num, num);
			Color val2 = default(Color);
			((Color)(ref val2))..ctor(0.3f, 0.3f, 0.4f, 0.8f);
			Color val3 = default(Color);
			((Color)(ref val3))..ctor(0.5f, 0.5f, 0.6f, 1f);
			for (int i = 0; i < num; i++)
			{
				for (int j = 0; j < num; j++)
				{
					if (j == 0 || j == num - 1 || i == 0 || i == num - 1)
					{
						val.SetPixel(j, i, val3);
					}
					else
					{
						val.SetPixel(j, i, val2);
					}
				}
			}
			val.Apply();
			return val;
		}

		public static void Clear()
		{
			_iconCache.Clear();
			_loadingItems.Clear();
			_failedItems.Clear();
			_initialized = false;
			_iconsLoaded = false;
		}

		public static (int loaded, int loading, int failed) GetStats()
		{
			return (_iconCache.Count, _loadingItems.Count, _failedItems.Count);
		}

		public static void LogStatus()
		{
			(int, int, int) stats = GetStats();
			ManualLogSource log = _log;
			if (log != null)
			{
				log.LogInfo((object)$"[IconCache] Loaded: {stats.Item1}, Loading: {stats.Item2}, Failed: {stats.Item3}");
			}
		}
	}
	public static class TextInputFocusGuard
	{
		private const float DefaultPollIntervalSeconds = 0.25f;

		private static float _nextPollTime = -1f;

		private static bool _cachedDefer;

		private static bool _tmpTypeLookupDone;

		private static Type _tmpInputFieldType;

		private static bool _qcLookupDone;

		private static Type _qcType;

		private static PropertyInfo _qcInstanceProp;

		private static PropertyInfo _qcIsActiveProp;

		private static FieldInfo _qcIsActiveField;

		public static bool ShouldDeferModHotkeys(ManualLogSource debugLog = null, float pollIntervalSeconds = 0.25f)
		{
			float realtimeSinceStartup = Time.realtimeSinceStartup;
			if (realtimeSinceStartup < _nextPollTime)
			{
				return _cachedDefer;
			}
			_nextPollTime = realtimeSinceStartup + Mathf.Max(0.05f, pollIntervalSeconds);
			bool flag = false;
			try
			{
				if (GUIUtility.keyboardControl != 0)
				{
					flag = true;
				}
				if (!flag)
				{
					EventSystem current = EventSystem.current;
					GameObject val = ((current != null) ? current.currentSelectedGameObject : null);
					if ((Object)(object)val != (Object)null)
					{
						if ((Object)(object)val.GetComponent<InputField>() != (Object)null)
						{
							flag = true;
						}
						else if (TryGetTmpInputField(val))
						{
							flag = true;
						}
					}
				}
				if (!flag && IsQuantumConsoleActive())
				{
					flag = true;
				}
			}
			catch (Exception ex)
			{
				if (debugLog != null)
				{
					debugLog.LogDebug((object)("[TextInputFocusGuard] " + ex.Message));
				}
			}
			_cachedDefer = flag;
			return flag;
		}

		private static bool TryGetTmpInputField(GameObject go)
		{
			if (!_tmpTypeLookupDone)
			{
				_tmpTypeLookupDone = true;
				_tmpInputFieldType = AccessTools.TypeByName("TMPro.TMP_InputField");
			}
			if (_tmpInputFieldType == null)
			{
				return false;
			}
			return (Object)(object)go.GetComponent(_tmpInputFieldType) != (Object)null;
		}

		private static bool IsQuantumConsoleActive()
		{
			try
			{
				if (!_qcLookupDone)
				{
					_qcLookupDone = true;
					_qcType = AccessTools.TypeByName("QFSW.QC.QuantumConsole");
					if (_qcType != null)
					{
						_qcInstanceProp = AccessTools.Property(_qcType, "Instance");
						_qcIsActiveProp = AccessTools.Property(_qcType, "IsActive");
						_qcIsActiveField = AccessTools.Field(_qcType, "isActive") ?? AccessTools.Field(_qcType, "_isActive");
					}
				}
				if (_qcType == null)
				{
					return false;
				}
				object obj = _qcInstanceProp?.GetValue(null);
				if (obj == null)
				{
					return false;
				}
				if (_qcIsActiveProp != null && _qcIsActiveProp.PropertyType == typeof(bool))
				{
					return (bool)_qcIsActiveProp.GetValue(obj);
				}
				if (_qcIsActiveField != null && _qcIsActiveField.FieldType == typeof(bool))
				{
					return (bool)_qcIsActiveField.GetValue(obj);
				}
			}
			catch
			{
			}
			return false;
		}
	}
}
namespace SunhavenTodo
{
	[BepInPlugin("com.azraelgodking.sunhaventodo", "Sunhaven Todo", "1.1.8")]
	public class Plugin : BaseUnityPlugin
	{
		private static TodoManager _staticTodoManager;

		private static TodoSaveSystem _staticSaveSystem;

		private static TodoUI _staticTodoUI;

		private static TodoHUD _staticTodoHUD;

		private static GameObject _persistentRunner;

		private static PersistentRunner _persistentRunnerComponent;

		private static KeyCode _staticToggleKey = (KeyCode)116;

		private static bool _staticRequireCtrl = true;

		private static bool _staticAutoSave = true;

		private static float _staticAutoSaveInterval = 60f;

		private static bool _staticHUDEnabled = true;

		private static float _staticHUDPositionX = -1f;

		private static float _staticHUDPositionY = -1f;

		private static KeyCode _staticHUDToggleKey = (KeyCode)104;

		private static float _staticUIScale = 1f;

		private ConfigEntry<KeyCode> _toggleKey;

		private ConfigEntry<bool> _requireCtrl;

		private ConfigEntry<bool> _autoSave;

		private ConfigEntry<float> _autoSaveInterval;

		private ConfigEntry<bool> _hudEnabled;

		private ConfigEntry<float> _hudPositionX;

		private ConfigEntry<float> _hudPositionY;

		private ConfigEntry<KeyCode> _hudToggleKey;

		private ConfigEntry<bool> _checkForUpdates;

		private ConfigEntry<float> _uiScale;

		private TodoManager _todoManager;

		private TodoSaveSystem _saveSystem;

		private TodoUI _todoUI;

		private TodoHUD _todoHUD;

		private Harmony _harmony;

		private static float _lastAutoSaveTime;

		private bool _isDataLoaded;

		private string _loadedCharacterName;

		public static Plugin Instance { get; private set; }

		public static ManualLogSource Log { get; private set; }

		public static ConfigFile ConfigFile { get; private set; }

		public static KeyCode StaticToggleKey => _staticToggleKey;

		public static bool StaticRequireCtrl => _staticRequireCtrl;

		public static KeyCode StaticHUDToggleKey => _staticHUDToggleKey;

		public static bool StaticHUDEnabled => _staticHUDEnabled;

		public static string GetOpenListShortcutDisplay()
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			KeyCode staticToggleKey = StaticToggleKey;
			string text = ((object)(KeyCode)(ref staticToggleKey)).ToString();
			return StaticRequireCtrl ? ("Ctrl+" + text) : text;
		}

		private void Awake()
		{
			Instance = this;
			Log = ((BaseUnityPlugin)this).Logger;
			ConfigFile = CreateNamedConfig();
			Log.LogInfo((object)"Loading Sunhaven Todo v1.1.8");
			IconCache.Initialize(Log);
			BindConfiguration();
			CreatePersistentRunner();
			InitializeManagers();
			ApplyPatches();
			SceneManager.sceneLoaded += OnSceneLoaded;
			if (_checkForUpdates.Value)
			{
				VersionChecker.CheckForUpdate("com.azraelgodking.sunhaventodo", "1.1.8", Log, delegate(VersionChecker.VersionCheckResult result)
				{
					result.NotifyUpdateAvailable(Log);
				});
			}
			Log.LogInfo((object)"Sunhaven Todo loaded successfully!");
		}

		private void BindConfiguration()
		{
			//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_01fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0202: Unknown result type (might be due to invalid IL or missing references)
			//IL_026d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0277: Expected O, but got Unknown
			_toggleKey = ConfigFile.Bind<KeyCode>("Hotkeys", "ToggleKey", (KeyCode)116, "Key to toggle the Todo List window");
			_staticToggleKey = _toggleKey.Value;
			_toggleKey.SettingChanged += delegate
			{
				//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)
				_staticToggleKey = _toggleKey.Value;
			};
			_requireCtrl = ConfigFile.Bind<bool>("Hotkeys", "RequireCtrl", true, "Require Ctrl to be held when pressing the toggle key");
			_staticRequireCtrl = _requireCtrl.Value;
			_requireCtrl.SettingChanged += delegate
			{
				_staticRequireCtrl = _requireCtrl.Value;
			};
			_autoSave = ConfigFile.Bind<bool>("Saving", "AutoSave", true, "Automatically save the todo list periodically");
			_staticAutoSave = _autoSave.Value;
			_autoSave.SettingChanged += delegate
			{
				_staticAutoSave = _autoSave.Value;
			};
			_autoSaveInterval = ConfigFile.Bind<float>("Saving", "AutoSaveInterval", 60f, "Auto-save interval in seconds");
			_staticAutoSaveInterval = _autoSaveInterval.Value;
			_autoSaveInterval.SettingChanged += delegate
			{
				_staticAutoSaveInterval = _autoSaveInterval.Value;
			};
			_hudEnabled = ConfigFile.Bind<bool>("HUD", "Enabled", true, "Show the movable HUD panel with top 5 urgent tasks");
			_staticHUDEnabled = _hudEnabled.Value;
			_hudEnabled.SettingChanged += delegate
			{
				_staticHUDEnabled = _hudEnabled.Value;
				_staticTodoHUD?.SetEnabled(_staticHUDEnabled);
			};
			_hudPositionX = ConfigFile.Bind<float>("HUD", "PositionX", -1f, "HUD X position (-1 for default)");
			_staticHUDPositionX = _hudPositionX.Value;
			_hudPositionY = ConfigFile.Bind<float>("HUD", "PositionY", -1f, "HUD Y position (-1 for default)");
			_staticHUDPositionY = _hudPositionY.Value;
			_hudToggleKey = ConfigFile.Bind<KeyCode>("Hotkeys", "HUDToggleKey", (KeyCode)104, "Key to toggle the HUD panel (with Ctrl if RequireCtrl is enabled)");
			_staticHUDToggleKey = _hudToggleKey.Value;
			_hudToggleKey.SettingChanged += delegate
			{
				//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)
				_staticHUDToggleKey = _hudToggleKey.Value;
			};
			_checkForUpdates = ConfigFile.Bind<bool>("Updates", "CheckForUpdates", true, "Check for mod updates on startup");
			_uiScale = ConfigFile.Bind<float>("Display", "UIScale", 1f, new ConfigDescription("Scale factor for the Todo list and HUD (1.0 = default, 1.5 = 50% larger)", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.5f, 2.5f), Array.Empty<object>()));
			_staticUIScale = Mathf.Clamp(_uiScale.Value, 0.5f, 2.5f);
			_uiScale.SettingChanged += delegate
			{
				_staticUIScale = Mathf.Clamp(_uiScale.Value, 0.5f, 2.5f);
				_staticTodoUI?.SetScale(_staticUIScale);
				_staticTodoHUD?.SetScale(_staticUIScale);
			};
		}

		private static ConfigFile CreateNamedConfig()
		{
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Expected O, but got Unknown
			string text = Path.Combine(Paths.ConfigPath, "SunhavenTodo.cfg");
			string text2 = Path.Combine(Paths.ConfigPath, "com.azraelgodking.sunhaventodo.cfg");
			try
			{
				if (!File.Exists(text) && File.Exists(text2))
				{
					File.Copy(text2, text);
				}
			}
			catch (Exception ex)
			{
				ManualLogSource log = Log;
				if (log != null)
				{
					log.LogWarning((object)("[Config] Migration to SunhavenTodo.cfg failed: " + ex.Message));
				}
			}
			return new ConfigFile(text, true);
		}

		private void CreatePersistentRunner()
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Expected O, but got Unknown
			if (!((Object)(object)_persistentRunner != (Object)null) || !((Object)(object)_persistentRunnerComponent != (Object)null))
			{
				_persistentRunner = new GameObject("SunhavenTodo_PersistentRunner");
				Object.DontDestroyOnLoad((Object)(object)_persistentRunner);
				((Object)_persistentRunner).hideFlags = (HideFlags)61;
				SceneRootSurvivor.TryRegisterPersistentRunnerGameObject(_persistentRunner);
				_persistentRunnerComponent = _persistentRunner.AddComponent<PersistentRunner>();
				Log.LogInfo((object)"[PersistentRunner] Created");
			}
		}

		private void InitializeManagers()
		{
			_todoManager = new TodoManager();
			_staticTodoManager = _todoManager;
			_saveSystem = new TodoSaveSystem(_todoManager);
			_staticSaveSystem = _saveSystem;
			_todoManager.OnTodosChanged += OnTodosChanged;
		}

		private void ApplyPatches()
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Expected O, but got Unknown
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Expected O, but got Unknown
			_harmony = new Harmony("com.azraelgodking.sunhaventodo");
			try
			{
				Type type = AccessTools.TypeByName("Wish.Player");
				if (type != null)
				{
					MethodInfo methodInfo = AccessTools.Method(type, "InitializeAsOwner", (Type[])null, (Type[])null);
					if (methodInfo != null)
					{
						MethodInfo methodInfo2 = AccessTools.Method(typeof(PlayerPatches), "OnPlayerInitialized", (Type[])null, (Type[])null);
						_harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(methodInfo2), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
						Log.LogInfo((object)"Applied player initialization patch");
					}
				}
			}
			catch (Exception ex)
			{
				Log.LogWarning((object)("Failed to apply patches: " + ex.Message));
			}
		}

		private void OnSceneLoaded(Scene scene, LoadSceneMode mode)
		{
			EnsureUIComponentsExist();
		}

		public static void EnsureUIComponentsExist()
		{
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Expected O, but got Unknown
			//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c1: Expected O, but got Unknown
			//IL_0138: Unknown result type (might be due to invalid IL or missing references)
			//IL_013f: Expected O, but got Unknown
			try
			{
				if ((Object)(object)_persistentRunner == (Object)null || (Object)(object)_persistentRunnerComponent == (Object)null)
				{
					ManualLogSource log = Log;
					if (log != null)
					{
						log.LogInfo((object)"[EnsureUI] Recreating PersistentRunner...");
					}
					_persistentRunner = new GameObject("SunhavenTodo_PersistentRunner");
					Object.DontDestroyOnLoad((Object)(object)_persistentRunner);
					((Object)_persistentRunner).hideFlags = (HideFlags)61;
					SceneRootSurvivor.TryRegisterPersistentRunnerGameObject(_persistentRunner);
					_persistentRunnerComponent = _persistentRunner.AddComponent<PersistentRunner>();
					ManualLogSource log2 = Log;
					if (log2 != null)
					{
						log2.LogInfo((object)"[EnsureUI] PersistentRunner recreated");
					}
				}
				if ((Object)(object)_staticTodoUI == (Object)null)
				{
					ManualLogSource log3 = Log;
					if (log3 != null)
					{
						log3.LogInfo((object)"[EnsureUI] Recreating TodoUI...");
					}
					GameObject val = new GameObject("SunhavenTodo_UI");
					Object.DontDestroyOnLoad((Object)(object)val);
					_staticTodoUI = val.AddComponent<TodoUI>();
					_staticTodoUI.Initialize(_staticTodoManager);
					_staticTodoUI.SetScale(_staticUIScale);
					ManualLogSource log4 = Log;
					if (log4 != null)
					{
						log4.LogInfo((object)"[EnsureUI] TodoUI recreated");
					}
				}
				if ((Object)(object)_staticTodoHUD == (Object)null)
				{
					ManualLogSource log5 = Log;
					if (log5 != null)
					{
						log5.LogInfo((object)"[EnsureUI] Recreating TodoHUD...");
					}
					GameObject val2 = new GameObject("SunhavenTodo_HUD");
					Object.DontDestroyOnLoad((Object)(object)val2);
					_staticTodoHUD = val2.AddComponent<TodoHUD>();
					_staticTodoHUD.Initialize(_staticTodoManager);
					_staticTodoHUD.SetScale(_staticUIScale);
					_staticTodoHUD.SetEnabled(_staticHUDEnabled);
					if (_staticHUDPositionX >= 0f && _staticHUDPositionY >= 0f)
					{
						_staticTodoHUD.SetPosition(_staticHUDPositionX, _staticHUDPositionY);
					}
					_staticTodoHUD.OnPositionChanged = delegate(float x, float y)
					{
						_staticHUDPositionX = x;
						_staticHUDPositionY = y;
						Plugin instance = Instance;
						if (instance != null)
						{
							ConfigEntry<float> hudPositionX = instance._hudPositionX;
							if (hudPositionX != null)
							{
								((ConfigEntryBase)hudPositionX).SetSerializedValue(x.ToString());
							}
						}
						Plugin instance2 = Instance;
						if (instance2 != null)
						{
							ConfigEntry<float> hudPositionY = instance2._hudPositionY;
							if (hudPositionY != null)
							{
								((ConfigEntryBase)hudPositionY).SetSerializedValue(y.ToString());
							}
						}
					};
					ManualLogSource log6 = Log;
					if (log6 != null)
					{
						log6.LogInfo((object)"[EnsureUI] TodoHUD recreated");
					}
				}
				if ((Object)(object)Instance != (Object)null)
				{
					Instance._todoUI = _staticTodoUI;
					Instance._todoHUD = _staticTodoHUD;
				}
			}
			catch (Exception ex)
			{
				ManualLogSource log7 = Log;
				if (log7 != null)
				{
					log7.LogError((object)("[EnsureUI] Error: " + ex.Message));
				}
			}
		}

		private void OnTodosChanged()
		{
			_lastAutoSaveTime = Time.unscaledTime - _staticAutoSaveInterval + 5f;
		}

		public void LoadDataForCharacter(string characterName)
		{
			if (string.IsNullOrEmpty(characterName))
			{
				Log.LogWarning((object)"Cannot load data: No character name");
				return;
			}
			if (_isDataLoaded && _loadedCharacterName != characterName)
			{
				SaveData();
			}
			TodoListData data = _staticSaveSystem.Load(characterName);
			_staticTodoManager.LoadForCharacter(characterName, data);
			_isDataLoaded = true;
			_loadedCharacterName = characterName;
			Log.LogInfo((object)("Loaded todo list for character: " + characterName));
		}

		public static void SaveData()
		{
			_staticSaveSystem?.Save();
		}

		public static void ToggleUI()
		{
			EnsureUIComponentsExist();
			_staticTodoUI?.Toggle();
		}

		public static void ShowUI()
		{
			EnsureUIComponentsExist();
			_staticTodoUI?.Show();
		}

		public static void HideUI()
		{
			_staticTodoUI?.Hide();
		}

		public static TodoManager GetTodoManager()
		{
			return _staticTodoManager;
		}

		public static TodoUI GetTodoUI()
		{
			return _staticTodoUI;
		}

		public static TodoHUD GetTodoHUD()
		{
			return _staticTodoHUD;
		}

		public static void ToggleHUD()
		{
			EnsureUIComponentsExist();
			_staticTodoHUD?.Toggle();
		}

		internal static void TickAutoSave()
		{
			if (_staticAutoSave && _staticTodoManager != null && _staticTodoManager.IsDirty && !(Time.unscaledTime - _lastAutoSaveTime < _staticAutoSaveInterval))
			{
				SaveData();
				_lastAutoSaveTime = Time.unscaledTime;
			}
		}

		private void OnDestroy()
		{
			Log.LogWarning((object)"[CRITICAL] Plugin OnDestroy called!");
			SaveData();
		}

		private void OnApplicationQuit()
		{
			SaveData();
		}
	}
	public class PersistentRunner : MonoBehaviour
	{
		private void Update()
		{
			CheckHotkeys();
			Plugin.TickAutoSave();
		}

		private void CheckHotkeys()
		{
			//IL_0053: 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)
			TodoUI todoUI = Plugin.GetTodoUI();
			if ((!((Object)(object)todoUI != (Object)null) || !todoUI.IsVisible) && !TextInputFocusGuard.ShouldDeferModHotkeys(Plugin.Log))
			{
				bool flag = Input.GetKey((KeyCode)306) || Input.GetKey((KeyCode)305);
				bool keyDown = Input.GetKeyDown(Plugin.StaticToggleKey);
				bool keyDown2 = Input.GetKeyDown(Plugin.StaticHUDToggleKey);
				if (keyDown && flag == Plugin.StaticRequireCtrl)
				{
					Plugin.ToggleUI();
				}
				if (keyDown2 && flag == Plugin.StaticRequireCtrl)
				{
					Plugin.ToggleHUD();
				}
			}
		}

		private void OnDestroy()
		{
			ManualLogSource log = Plugin.Log;
			if (log != null)
			{
				log.LogWarning((object)"[PersistentRunner] OnDestroy called - this should NOT happen!");
			}
		}
	}
	public static class PlayerPatches
	{
		private static bool _isDataLoaded;

		private static string _loadedCharacterName;

		public static void OnPlayerInitialized(object __instance)
		{
			try
			{
				Plugin.EnsureUIComponentsExist();
				string currentCharacterName = GetCurrentCharacterName(__instance);
				if (_isDataLoaded && _loadedCharacterName != currentCharacterName)
				{
					Plugin.SaveData();
					ResetState();
				}
				if (!string.IsNullOrEmpty(currentCharacterName))
				{
					Plugin.Instance?.LoadDataForCharacter(currentCharacterName);
					_isDataLoaded = true;
					_loadedCharacterName = currentCharacterName;
					return;
				}
				ManualLogSource log = Plugin.Log;
				if (log != null)
				{
					log.LogWarning((object)"Skipping todo load because character name is unavailable.");
				}
			}
			catch (Exception ex)
			{
				ManualLogSource log2 = Plugin.Log;
				if (log2 != null)
				{
					log2.LogError((object)("Error in OnPlayerInitialized: " + ex.Message));
				}
			}
		}

		private static string GetCurrentCharacterName(object player)
		{
			try
			{
				Type type = AccessTools.TypeByName("Wish.GameSave");
				if (type != null)
				{
					PropertyInfo propertyInfo = AccessTools.Property(type, "CurrentCharacter");
					if (propertyInfo != null)
					{
						object value = propertyInfo.GetValue(null);
						if (value != null)
						{
							PropertyInfo propertyInfo2 = AccessTools.Property(value.GetType(), "characterName");
							if (propertyInfo2 != null)
							{
								string text = propertyInfo2.GetValue(value) as string;
								if (!string.IsNullOrEmpty(text))
								{
									return text;
								}
							}
						}
					}
					object obj = AccessTools.Property(type, "Instance")?.GetValue(null);
					if (obj != null)
					{
						object obj2 = AccessTools.Property(type, "CurrentSave")?.GetValue(obj);
						if (obj2 != null)
						{
							object obj3 = AccessTools.Property(obj2.GetType(), "characterData")?.GetValue(obj2);
							if (obj3 != null)
							{
								string text2 = AccessTools.Property(obj3.GetType(), "characterName")?.GetValue(obj3) as string;
								if (!string.IsNullOrEmpty(text2))
								{
									return text2;
								}
							}
						}
					}
				}
			}
			catch (Exception ex)
			{
				ManualLogSource log = Plugin.Log;
				if (log != null)
				{
					log.LogWarning((object)("Failed to get character name: " + ex.Message));
				}
			}
			if (!string.IsNullOrEmpty(_loadedCharacterName))
			{
				return _loadedCharacterName;
			}
			return null;
		}

		private static void ResetState()
		{
			_isDataLoaded = false;
			_loadedCharacterName = null;
		}
	}
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "com.azraelgodking.sunhaventodo";

		public const string PLUGIN_NAME = "Sunhaven Todo";

		public const string PLUGIN_VERSION = "1.1.8";
	}
}
namespace SunhavenTodo.UI
{
	public class TodoHUD : MonoBehaviour
	{
		private const int WINDOW_ID = 98766;

		private const float BASE_WINDOW_WIDTH = 280f;

		private const float BASE_MIN_HEIGHT = 100f;

		private const float BASE_MAX_HEIGHT = 300f;

		private const float BASE_HEADER_HEIGHT = 28f;

		private const float BASE_ITEM_HEIGHT = 24f;

		private const float BASE_ICON_SIZE = 16f;

		private const int MAX_ITEMS = 5;

		private float _scale = 1f;

		private TodoManager _manager;

		private bool _isEnabled = true;

		private Rect _windowRect;

		public Action<float, float> OnPositionChanged;

		private List<TodoItem> _cachedItems = new List<TodoItem>();

		private float _lastUpdateTime;

		private const float UPDATE_INTERVAL = 1f;

		private readonly Color _parchmentLight = new Color(0.96f, 0.93f, 0.86f, 0.95f);

		private readonly Color _parchment = new Color(0.92f, 0.87f, 0.78f, 0.95f);

		private readonly Color _parchmentDark = new Color(0.85f, 0.78f, 0.65f, 0.95f);

		private readonly Color _woodDark = new Color(0.35f, 0.25f, 0.15f);

		private readonly Color _woodMedium = new Color(0.5f, 0.38f, 0.25f);

		private readonly Color _goldRich = new Color(0.85f, 0.68f, 0.2f);

		private readonly Color _goldBright = new Color(0.95f, 0.8f, 0.3f);

		private readonly Color _textDark = new Color(0.25f, 0.2f, 0.15f);

		private readonly Color _borderDark = new Color(0.4f, 0.3f, 0.2f, 0.8f);

		private readonly Dictionary<TodoPriority, Color> _priorityColors = new Dictionary<TodoPriority, Color>
		{
			{
				TodoPriority.Low,
				new Color(0.5f, 0.6f, 0.7f)
			},
			{
				TodoPriority.Normal,
				new Color(0.45f, 0.55f, 0.45f)
			},
			{
				TodoPriority.High,
				new Color(0.85f, 0.65f, 0.25f)
			},
			{
				TodoPriority.Urgent,
				new Color(0.8f, 0.3f, 0.25f)
			}
		};

		private readonly Dictionary<TodoCategory, Color> _categoryColors = new Dictionary<TodoCategory, Color>
		{
			{
				TodoCategory.General,
				new Color(0.55f, 0.5f, 0.45f)
			},
			{
				TodoCategory.Farming,
				new Color(0.45f, 0.65f, 0.35f)
			},
			{
				TodoCategory.Mining,
				new Color(0.5f, 0.45f, 0.55f)
			},
			{
				TodoCategory.Fishing,
				new Color(0.4f, 0.6f, 0.75f)
			},
			{
				TodoCategory.Combat,
				new Color(0.75f, 0.35f, 0.35f)
			},
			{
				TodoCategory.Crafting,
				new Color(0.65f, 0.55f, 0.4f)
			},
			{
				TodoCategory.Social,
				new Color(0.7f, 0.5f, 0.6f)
			},
			{
				TodoCategory.Quests,
				new Color(0.8f, 0.7f, 0.3f)
			},
			{
				TodoCategory.Collection,
				new Color(0.55f, 0.7f, 0.65f)
			}
		};

		private bool _stylesInitialized;

		private GUIStyle _windowStyle;

		private GUIStyle _headerStyle;

		private GUIStyle _itemStyle;

		private GUIStyle _priorityStyle;

		private GUIStyle _categoryStyle;

		private GUIStyle _titleStyle;

		private GUIStyle _emptyStyle;

		private Texture2D _windowBackground;

		private Texture2D _headerBackground;

		private Texture2D _itemEven;

		private Texture2D _itemOdd;

		private float WindowWidth => 280f * _scale;

		private float MinHeight => 100f * _scale;

		private float MaxHeight => 300f * _scale;

		private float HeaderHeight => 28f * _scale;

		private float ItemHeight => 24f * _scale;

		private float IconSize => 16f * _scale;

		public bool IsEnabled => _isEnabled;

		private int ScaledFont(int baseSize)
		{
			return Mathf.Max(8, Mathf.RoundToInt((float)baseSize * _scale));
		}

		private float Scaled(float value)
		{
			return value * _scale;
		}

		private int ScaledInt(float value)
		{
			return Mathf.RoundToInt(value * _scale);
		}

		public void Initialize(TodoManager manager)
		{
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			_manager = manager;
			_windowRect = new Rect((float)Screen.width - WindowWidth - Scaled(20f), Scaled(100f), WindowWidth, MinHeight);
			if (_manager != null)
			{
				_manager.OnTodosChanged += RefreshCache;
				_manager.OnDataLoaded += RefreshCache;
			}
		}

		public void SetPosition(float x, float y)
		{
			((Rect)(ref _windowRect)).x = Mathf.Clamp(x, 0f, (float)Screen.width - ((Rect)(ref _windowRect)).width);
			((Rect)(ref _windowRect)).y = Mathf.Clamp(y, 0f, (float)Screen.height - ((Rect)(ref _windowRect)).height);
		}

		public (float x, float y) GetPosition()
		{
			return (((Rect)(ref _windowRect)).x, ((Rect)(ref _windowRect)).y);
		}

		public void SetEnabled(bool enabled)
		{
			_isEnabled = enabled;
		}

		public void SetScale(float scale)
		{
			_scale = Mathf.Clamp(scale, 0.5f, 2.5f);
			_stylesInitialized = false;
		}

		public void Toggle()
		{
			_isEnabled = !_isEnabled;
			ManualLogSource log = Plugin.Log;
			if (log != null)
			{
				log.LogInfo((object)("TodoHUD toggled: " + (_isEnabled ? "ON" : "OFF")));
			}
		}

		private void Update()
		{
			if (_isEnabled && _manager != null && Time.unscaledTime - _lastUpdateTime > 1f)
			{
				RefreshCache();
				_lastUpdateTime = Time.unscaledTime;
			}
		}

		private void RefreshCache()
		{
			if (_manager != null)
			{
				_cachedItems = (from t in _manager.GetActiveTodos()
					orderby (int)t.Priority descending, t.CreatedAt descending
					select t).Take(5).ToList();
			}
		}

		private void OnGUI()
		{
			//IL_0115: Unknown result type (might be due to invalid IL or missing references)
			//IL_011a: 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_0139: Unknown result type (might be due to invalid IL or missing references)
			//IL_014e: Expected O, but got Unknown
			//IL_0149: Unknown result type (might be due to invalid IL or missing references)
			//IL_014e: Unknown result type (might be due to invalid IL or missing references)
			if (!_isEnabled || _manager == null)
			{
				return;
			}
			TodoUI todoUI = Plugin.GetTodoUI();
			if (((Object)(object)todoUI != (Object)null && todoUI.IsVisible) || string.IsNullOrEmpty(_manager.CurrentCharacter))
			{
				return;
			}
			InitializeStyles();
			float num = HeaderHeight + Scaled(8f);
			if (_cachedItems.Count == 0)
			{
				num += Scaled(40f);
			}
			else
			{
				for (int i = 0; i < _cachedItems.Count; i++)
				{
					num += GetItemRowHeight(_cachedItems[i]);
				}
				num += Scaled(4f);
			}
			((Rect)(ref _windowRect)).width = WindowWidth;
			((Rect)(ref _windowRect)).height = Mathf.Clamp(num, MinHeight, MaxHeight);
			Rect windowRect = _windowRect;
			GUI.depth = -500;
			_windowRect = GUI.Window(98766, _windowRect, new WindowFunction(DrawWindow), "", _windowStyle);
			((Rect)(ref _windowRect)).x = Mathf.Clamp(((Rect)(ref _windowRect)).x, 0f, (float)Screen.width - ((Rect)(ref _windowRect)).width);
			((Rect)(ref _windowRect)).y = Mathf.Clamp(((Rect)(ref _windowRect)).y, 0f, (float)Screen.height - ((Rect)(ref _windowRect)).height);
			if (Math.Abs(((Rect)(ref _windowRect)).x - ((Rect)(ref windowRect)).x) > 0.1f || Math.Abs(((Rect)(ref _windowRect)).y - ((Rect)(ref windowRect)).y) > 0.1f)
			{
				OnPositionChanged?.Invoke(((Rect)(ref _windowRect)).x, ((Rect)(ref _windowRect)).y);
			}
		}

		private void DrawWindow(int windowId)
		{
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			GUILayout.BeginVertical(Array.Empty<GUILayoutOption>());
			DrawHeader();
			DrawItems();
			GUILayout.EndVertical();
			GUI.DragWindow(new Rect(0f, 0f, ((Rect)(ref _windowRect)).width, HeaderHeight));
		}

		private void DrawHeader()
		{
			//IL_0036: 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_00b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0108: Expected O, but got Unknown
			Rect val = default(Rect);
			((Rect)(ref val))..ctor(0f, 0f, ((Rect)(ref _windowRect)).width, HeaderHeight);
			if ((Object)(object)_headerBackground != (Object)null)
			{
				GUI.DrawTexture(val, (Texture)(object)_headerBackground);
			}
			GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
			GUILayout.Space(Scaled(8f));
			int num = _manager?.GetActiveTodos().Count() ?? 0;
			GUILayout.Label($"Todo ({num})", _headerStyle, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Height(HeaderHeight) });
			GUILayout.FlexibleSpace();
			GUIStyle val2 = new GUIStyle(_headerStyle)
			{
				fontSize = ScaledFont(9),
				fontStyle = (FontStyle)2
			};
			val2.normal.textColor = new Color(_textDark.r, _textDark.g, _textDark.b, 0.5f);
			GUIStyle val3 = val2;
			string openListShortcutDisplay = Plugin.GetOpenListShortcutDisplay();
			GUILayout.Label(openListShortcutDisplay + " to open", val3, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Height(HeaderHeight) });
			GUILayout.FlexibleSpace();
			GUILayout.Label("drag to move", val3, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Height(HeaderHeight) });
			GUILayout.Space(Scaled(8f));
			GUILayout.EndHorizontal();
		}

		private void DrawItems()
		{
			GUILayout.Space(Scaled(4f));
			if (_cachedItems.Count == 0)
			{
				GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
				GUILayout.FlexibleSpace();
				GUILayout.Label("No active tasks", _emptyStyle, Array.Empty<GUILayoutOption>());
				GUILayout.FlexibleSpace();
				GUILayout.EndHorizontal();
			}
			else
			{
				for (int i = 0; i < _cachedItems.Count; i++)
				{
					DrawItem(_cachedItems[i], i);
				}
			}
			GUILayout.Space(Scaled(4f));
		}

		private void DrawItem(TodoItem item, int index)
		{
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: 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_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Expected O, but got Unknown
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Expected O, but got Unknown
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00da: Expected O, but got Unknown
			//IL_00dd: Expected O, but got Unknown
			//IL_0123: Unknown result type (might be due to invalid IL or missing references)
			//IL_011c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0125: 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_0132: 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_0142: Expected O, but got Unknown
			//IL_018c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0185: Unknown result type (might be due to invalid IL or missing references)
			//IL_018e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0196: Unknown result type (might be due to invalid IL or missing references)
			//IL_019b: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ab: Expected O, but got Unknown
			//IL_0255: Unknown result type (might be due to invalid IL or missing references)
			//IL_025a: Unknown result type (might be due to invalid IL or missing references)
			//IL_025c: Unknown result type (might be due to invalid IL or missing references)
			Texture2D background = ((index % 2 == 0) ? _itemEven : _itemOdd);
			string text = (string.IsNullOrWhiteSpace(item.Title) ? "(No title)" : item.Title);
			GUIStyle val = new GUIStyle(_titleStyle)
			{
				wordWrap = true,
				clipping = (TextClipping)0,
				alignment = (TextAnchor)0
			};
			float titleAvailableWidth = GetTitleAvailableWidth(item);
			float num = Mathf.Ceil(val.CalcHeight(new GUIContent(text), titleAvailableWidth));
			float num2 = Mathf.Max(ItemHeight, num + Scaled(6f));
			GUIStyle val2 = new GUIStyle(_itemStyle);
			val2.normal.background = background;
			val2.padding = new RectOffset(ScaledInt(6f), ScaledInt(6f), ScaledInt(2f), ScaledInt(2f));
			GUIStyle val3 = val2;
			GUILayout.BeginHorizontal(val3, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.MinHeight(num2) });
			GUILayout.Space(Scaled(6f));
			Color value;
			Color textColor = (_priorityColors.TryGetValue(item.Priority, out value) ? value : _textDark);
			GUIStyle val4 = new GUIStyle(_priorityStyle);
			val4.normal.textColor = textColor;
			GUIStyle val5 = val4;
			GUILayout.Label(GetPriorityIcon(item.Priority), val5, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(Scaled(16f)) });
			Color value2;
			Color textColor2 = (_categoryColors.TryGetValue(item.Category, out value2) ? value2 : _textDark);
			GUIStyle val6 = new GUIStyle(_categoryStyle);
			val6.normal.textColor = textColor2;
			GUIStyle val7 = val6;
			GUILayout.Label("[" + GetCategoryShort(item.Category) + "]", val7, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(Scaled(36f)) });
			GUILayout.Space(Scaled(4f));
			if (item.IconItemId > 0)
			{
				Texture2D icon = IconCache.GetIcon(item.IconItemId);
				if ((Object)(object)icon != (Object)null)
				{
					Rect rect = GUILayoutUtility.GetRect(IconSize, IconSize, (GUILayoutOption[])(object)new GUILayoutOption[2]
					{
						GUILayout.Width(IconSize),
						GUILayout.Height(IconSize)
					});
					GUI.DrawTexture(rect, (Texture)(object)icon, (ScaleMode)2);
				}
				else
				{
					GUILayout.Space(IconSize);
				}
				GUILayout.Space(Scaled(4f));
			}
			GUILayout.Label(text, val, (GUILayoutOption[])(object)new GUILayoutOption[2]
			{
				GUILayout.Width(titleAvailableWidth),
				GUILayout.MinHeight(num)
			});
			GUILayout.FlexibleSpace();
			GUILayout.Space(Scaled(6f));
			GUILayout.EndHorizontal();
		}

		private float GetItemRowHeight(TodoItem item)
		{
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: 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_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Expected O, but got Unknown
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Expected O, but got Unknown
			if (item == null)
			{
				return ItemHeight;
			}
			string text = (string.IsNullOrWhiteSpace(item.Title) ? "(No title)" : item.Title);
			GUIStyle val = new GUIStyle(_titleStyle)
			{
				wordWrap = true,
				clipping = (TextClipping)0,
				alignment = (TextAnchor)0
			};
			float titleAvailableWidth = GetTitleAvailableWidth(item);
			float num = Mathf.Ceil(val.CalcHeight(new GUIContent(text), titleAvailableWidth));
			return Mathf.Max(ItemHeight, num + Scaled(6f));
		}

		private float GetTitleAvailableWidth(TodoItem item)
		{
			float num = Scaled(68f);
			if (item != null && item.IconItemId > 0)
			{
				num += IconSize + Scaled(4f);
			}
			return Mathf.Max(Scaled(100f), WindowWidth - num);
		}

		private string GetPriorityIcon(TodoPriority priority)
		{
			return priority switch
			{
				TodoPriority.Low => "-", 
				TodoPriority.Normal => "o", 
				TodoPriority.High => "!", 
				TodoPriority.Urgent => "!!", 
				_ => "o", 
			};
		}

		private string GetCategoryShort(TodoCategory category)
		{
			return category switch
			{
				TodoCategory.General => "GEN", 
				TodoCategory.Farming => "FRM", 
				TodoCategory.Mining => "MIN", 
				TodoCategory.Fishing => "FSH", 
				TodoCategory.Combat => "CMB", 
				TodoCategory.Crafting => "CRF", 
				TodoCategory.Social => "SOC", 
				TodoCategory.Quests => "QST", 
				TodoCategory.Collection => "COL", 
				_ => "GEN", 
			};
		}

		private void InitializeStyles()
		{
			if (!_stylesInitialized)
			{
				CreateTextures();
				CreateStyles();
				_stylesInitialized = true;
			}
		}

		private void CreateTextures()
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			_windowBackground = MakeParchmentTexture(16, 64, _parchment, _parchmentLight, _borderDark, 2);
			_headerBackground = MakeGradientTex(8, Mathf.Max(1, ScaledInt(HeaderHeight)), _parchmentDark, _parchment);
			_itemEven = MakeTex(1, 1, new Color(_parchmentLight.r, _parchmentLight.g, _parchmentLight.b, 0.3f));
			_itemOdd = MakeTex(1, 1, new Color(_parchment.r, _parchment.g, _parchment.b, 0.3f));
		}

		private void CreateStyles()
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Expected O, but got Unknown
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: Expected O, but got Unknown
			//IL_00a0: Expected O, but got Unknown
			//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_00b5: 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_00c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0104: Unknown result type (might be due to invalid IL or missing references)
			//IL_010e: Expected O, but got Unknown
			//IL_0114: Expected O, but got Unknown
			//IL_0115: Unknown result type (might be due to invalid IL or missing references)
			//IL_011a: 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)
			//IL_0130: Unknown result type (might be due to invalid IL or missing references)
			//IL_013b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0168: Unknown result type (might be due to invalid IL or missing references)
			//IL_0172: Expected O, but got Unknown
			//IL_0178: Expected O, but got Unknown
			//IL_0179: Unknown result type (might be due to invalid IL or missing references)
			//IL_017e: Unknown result type (might be due to invalid IL or missing references)
			//IL_018d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0195: Unknown result type (might be due to invalid IL or missing references)
			//IL_019d: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b4: Expected O, but got Unknown
			//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_01c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01df: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ef: Expected O, but got Unknown
			//IL_01f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0204: Unknown result type (might be due to invalid IL or missing references)
			//IL_020b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0216: Unknown result type (might be due to invalid IL or missing references)
			//IL_021e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0226: Unknown result type (might be due to invalid IL or missing references)
			//IL_0233: Expected O, but got Unknown
			//IL_0234: Unknown result type (might be due to invalid IL or missing references)
			//IL_0239: Unknown result type (might be due to invalid IL or missing references)
			//IL_0248: Unknown result type (might be due to invalid IL or missing references)
			//IL_0250: 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_0287: Unknown result type (might be due to invalid IL or missing references)
			//IL_028f: Unknown result type (might be due to invalid IL or missing references)
			//IL_02bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c6: Expected O, but got Unknown
			//IL_02cc: Expected O, but got Unknown
			GUIStyle val = new GUIStyle();
			val.normal.background = _windowBackground;
			val.normal.textColor = _textDark;
			val.padding = new RectOffset(ScaledInt(4f), ScaledInt(4f), ScaledInt(4f), ScaledInt(4f));
			val.border = new RectOffset(ScaledInt(4f), ScaledInt(4f), ScaledInt(4f), ScaledInt(4f));
			_windowStyle = val;
			GUIStyle val2 = new GUIStyle
			{
				fontSize = ScaledFont(13),
				fontStyle = (FontStyle)1
			};
			val2.normal.textColor = _woodDark;
			val2.alignment = (TextAnchor)3;
			val2.padding = new RectOffset(ScaledInt(2f), ScaledInt(2f), ScaledInt(2f), ScaledInt(2f));
			_headerStyle = val2;
			GUIStyle val3 = new GUIStyle
			{
				fontSize = ScaledFont(11)
			};
			val3.normal.textColor = _textDark;
			val3.padding = new RectOffset(ScaledInt(2f), ScaledInt(2f), ScaledInt(2f), ScaledInt(2f));
			_itemStyle = val3;
			GUIStyle val4 = new GUIStyle
			{
				fontSize = ScaledFont(11),
				fontStyle = (FontStyle)1,
				alignment = (TextAnchor)4
			};
			val4.normal.textColor = _textDark;
			_priorityStyle = val4;
			GUIStyle val5 = new GUIStyle
			{
				fontSize = ScaledFont(8),
				fontStyle = (FontStyle)1,
				alignment = (TextAnchor)3
			};
			val5.normal.textColor = _textDark;
			_categoryStyle = val5;
			GUIStyle val6 = new GUIStyle
			{
				fontSize = ScaledFont(11)
			};
			val6.normal.textColor = _textDark;
			val6.alignment = (TextAnchor)3;
			val6.clipping = (TextClipping)0;
			val6.wordWrap = true;
			_titleStyle = val6;
			GUIStyle val7 = new GUIStyle
			{
				fontSize = ScaledFont(11),
				fontStyle = (FontStyle)2
			};
			val7.normal.textColor = new Color(_textDark.r, _textDark.g, _textDark.b, 0.6f);
			val7.alignment = (TextAnchor)4;
			val7.padding = new RectOffset(ScaledInt(10f), ScaledInt(10f), ScaledInt(10f), ScaledInt(10f));
			_emptyStyle = val7;
		}

		private Texture2D MakeTex(int width, int height, Color color)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Expected O, but got Unknown
			Color[] array = (Color[])(object)new Color[width * height];
			for (int i = 0; i < array.Length; i++)
			{
				array[i] = color;
			}
			Texture2D val = new Texture2D(width, height);
			val.SetPixels(array);
			val.Apply();
			return val;
		}

		private Texture2D MakeGradientTex(int width, int height, Color topColor, Color bottomColor)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Expected O, but got Unknown
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			Texture2D val = new Texture2D(width, height);
			Color[] array = (Color[])(object)new Color[width * height];
			for (int i = 0; i < height; i++)
			{
				float num = (float)i / (float)(height - 1);
				Color val2 = Color.Lerp(topColor, bottomColor, num);
				for (int j = 0; j < width; j++)
				{
					array[i * width + j] = val2;
				}
			}
			val.SetPixels(array);
			val.Apply();
			return val;
		}

		private Texture2D MakeParchmentTexture(int width, int height, Color baseColor, Color lightColor, Color borderColor, int borderWidth)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Expected O, but got Unknown
			//IL_002b: 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_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: 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_00cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			Texture2D val = new Texture2D(width, height);
			Color[] array = (Color[])(object)new Color[width * height];
			Random random = new Random(42);
			for (int i = 0; i < height; i++)
			{
				float num = (float)i / (float)(height - 1);
				Color val2 = Color.Lerp(lightColor, baseColor, num * 0.3f);
				for (int j = 0; j < width; j++)
				{
					if (j < borderWidth || j >= width - borderWidth || i < borderWidth || i >= height - borderWidth)
					{
						array[i * width + j] = borderColor;
						continue;
					}
					float num2 = (float)random.NextDouble() * 0.02f - 0.01f;
					array[i * width + j] = new Color(Mathf.Clamp01(val2.r + num2), Mathf.Clamp01(val2.g + num2), Mathf.Clamp01(val2.b + num2), val2.a);
				}
			}
			val.SetPixels(array);
			val.Apply();
			return val;
		}

		private void OnDestroy()
		{
			if (_manager != null)
			{
				_manager.OnTodosChanged -= RefreshCache;
				_manager.OnDataLoaded -= RefreshCache;
			}
		}
	}
	public class TodoUI : MonoBehaviour
	{
		private const int WINDOW_ID = 98765;

		private const float BASE_WINDOW_WIDTH = 520f;

		private const float BASE_WINDOW_HEIGHT = 600f;

		private const float BASE_HEADER_HEIGHT = 50f;

		private const float BASE_ITEM_HEIGHT = 36f;

		private const float BASE_ICON_SIZE = 24f;

		private float _scale = 1f;

		private const string PAUSE_ID = "SunhavenTodo_UI";

		private bool _isVisible;

		private Rect _windowRect;

		private Vector2 _scrollPosition;

		private float _openAnimation = 0f;

		private string _newTodoTitle = "";

		private string _newTodoDescription = "";

		private int _selectedPriority = 1;

		private int _selectedCategory = 0;

		private bool _showAddForm = false;

		private string _editingItemId = null;

		private int _selectedCategoryFilter = -1;

		private bool _showCompletedItems = true;

		private string _searchQuery = "";

		private readonly List<TodoItem> _cachedDrawList = new List<TodoItem>();

		private bool _cachedDrawListDirty = true;

		private int _cachedFilterCategory = -2;

		private bool _cachedFilterShowCompleted = true;

		private string _cachedFilterSearch = null;

		private TodoManager _manager;

		private readonly Color _parchmentLight = new Color(0.96f, 0.93f, 0.86f, 0.98f);

		private readonly Color _parchment = new Color(0.92f, 0.87f, 0.78f, 0.97f);

		private readonly Color _parchmentDark = new Color(0.85f, 0.78f, 0.65f, 0.95f);

		private readonly Color _woodDark = new Color(0.35f, 0.25f, 0.15f);

		private readonly Color _woodMedium = new Color(0.5f, 0.38f, 0.25f);

		private readonly Color _woodLight = new Color(0.65f, 0.52f, 0.38f);

		private readonly Color _goldRich = new Color(0.85f, 0.68f, 0.2f);

		private readonly Color _goldBright = new Color(0.95f, 0.8f, 0.3f);

		private readonly Color _goldPale = new Color(0.98f, 0.95f, 0.85f);

		private readonly Color _forestGreen = new Color(0.3f, 0.55f, 0.3f);

		private readonly Color _successGreen = new Color(0.35f, 0.65f, 0.35f);

		private readonly Color _skyBlue = new Color(0.45f, 0.65f, 0.85f);

		private readonly Color _urgentRed = new Color(0.8f, 0.3f, 0.25f);

		private readonly Color _textDark = new Color(0.25f, 0.2f, 0.15f);

		private readonly Color _textLight = new Color(0.95f, 0.92f, 0.88f);

		private readonly Color _borderDark = new Color(0.4f, 0.3f, 0.2f, 0.8f);

		private readonly Dictionary<TodoPriority, Color> _priorityColors = new Dictionary<TodoPriority, Color>
		{
			{
				TodoPriority.Low,
				new Color(0.5f, 0.6f, 0.7f)
			},
			{
				TodoPriority.Normal,
				new Color(0.45f, 0.55f, 0.45f)
			},
			{
				TodoPriority.High,
				new Color(0.85f, 0.65f, 0.25f)
			},
			{
				TodoPriority.Urgent,
				new Color(0.8f, 0.3f, 0.25f)
			}
		};

		private readonly Dictionary<TodoCategory, Color> _categoryColors = new Dictionary<TodoCategory, Color>
		{
			{
				TodoCategory.General,
				new Color(0.55f, 0.5f, 0.45f)
			},
			{
				TodoCategory.Farming,
				new Color(0.45f, 0.65f, 0.35f)
			},
			{
				TodoCategory.Mining,
				new Color(0.5f, 0.45f, 0.55f)
			},
			{
				TodoCategory.Fishing,
				new Color(0.4f, 0.6f, 0.75f)
			},
			{
				TodoCategory.Combat,
				new Color(0.75f, 0.35f, 0.35f)
			},
			{
				TodoCategory.Crafting,
				new Color(0.65f, 0.55f, 0.4f)
			},
			{
				TodoCategory.Social,
				new Color(0.7f, 0.5f, 0.6f)
			},
			{
				TodoCategory.Quests,
				new Color(0.8f, 0.7f, 0.3f)
			},
			{
				TodoCategory.Collection,
				new Color(0.55f, 0.7f, 0.65f)
			}
		};

		private bool _stylesInitialized;

		private GUIStyle _windowStyle;

		private GUIStyle _titleStyle;

		private GUIStyle _headerStyle;

		private GUIStyle _labelStyle;

		private GUIStyle _labelBoldStyle;

		private GUIStyle _buttonStyle;

		private GUIStyle _textFieldStyle;

		private GUIStyle _textAreaStyle;

		private GUIStyle _itemStyle;

		private GUIStyle _itemCompletedStyle;

		private GUIStyle _tabStyle;

		private GUIStyle _tabActiveStyle;

		private GUIStyle _statsStyle;

		private GUIStyle _categoryLabelStyle;

		private GUIStyle _priorityLabelStyle;

		private GUIStyle _footerStyle;

		private GUIStyle _completedTitleStyle;

		private Dictionary<TodoPriority, GUIStyle> _priorityStyleCache;

		private Dictionary<TodoCategory, GUIStyle> _categoryStyleCache;

		private Texture2D _windowBackground;

		private Texture2D _headerBackground;

		private Texture2D _buttonNormal;

		private Texture2D _buttonHover;

		private Texture2D _buttonActive;

		private Texture2D _itemEven;

		private Texture2D _itemOdd;

		private Texture2D _itemCompleted;

		private Texture2D _tabNormal;

		private Texture2D _tabActive;

		private Texture2D _textFieldBg;

		private Texture2D _goldLine;

		private Texture2D _progressBg;

		private Texture2D _progressFill;

		private float WindowWidth => 520f * _scale;

		private float WindowHeight => 600f * _scale;

		private float HeaderHeight => 50f * _scale;

		private float ItemHeight => 36f * _scale;

		private float IconSize => 24f * _scale;

		public bool IsVisible => _isVisible;

		private int ScaledFont(int baseSize)
		{
			return Mathf.Max(8, Mathf.RoundToInt((float)baseSize * _scale));
		}

		private float Scaled(float value)
		{
			return value * _scale;
		}

		private int ScaledInt(float value)
		{
			return Mathf.RoundToInt(value * _scale);
		}

		public void Initialize(TodoManager manager)
		{
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			_manager = manager;
			float windowWidth = WindowWidth;
			float windowHeight = WindowHeight;
			_windowRect = new Rect(((float)Screen.width - windowWidth) / 2f, ((float)Screen.height - windowHeight) / 2f, windowWidth, windowHeight);
		}

		public void Show()
		{
			_isVisible = true;
			_openAnimation = 0f;
			PauseGame(pause: true);
		}

		public void Hide()
		{
			_isVisible = false;
			_showAddForm = false;
			_editingItemId = null;
			PauseGame(pause: false);
		}

		private void PauseGame(bool pause)
		{
			try
			{
				if ((Object)(object)Player.Instance != (Object)null)
				{
					if (pause)
					{
						Player.Instance.AddPauseObject("SunhavenTodo_UI");
					}
					else
					{
						Player.Instance.RemovePauseObject("SunhavenTodo_UI");
					}
				}
				Type type = Type.GetType("PlayerInput, Assembly-CSharp");
				if (type != null)
				{
					type.GetMethod(pause ? "DisableInput" : "EnableInput", BindingFlags.Static | BindingFlags.Public, null, new Type[1] { typeof(string) }, null)?.Invoke(null, new object[1] { "SunhavenTodo_UI" });
				}
			}
			catch (Exception ex)
			{
				Debug.LogWarning((object)("[SunhavenTodo] Input blocking failed: " + ex.Message));
			}
		}

		public void Toggle()
		{
			if (_isVisible)
			{
				Hide();
			}
			else
			{
				Show();
			}
		}

		public void SetScale(float scale)
		{
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			_scale = Mathf.Clamp(scale, 0.5f, 2.5f);
			_stylesInitialized = false;
			_windowRect = new Rect(((float)Screen.width - WindowWidth) / 2f, ((float)Screen.height - WindowHeight) / 2f, WindowWidth, WindowHeight);
		}

		private void Update()
		{
			if (_isVisible && Input.GetKeyDown((KeyCode)27))
			{
				if (_showAddForm)
				{
					_showAddForm = false;
					_editingItemId = null;
				}
				else
				{
					Hide();
				}
			}
			if (_isVisible)
			{
				_openAnimation = Mathf.MoveTowards(_openAnimation, 1f, Time.unscaledDeltaTime * 8f);
			}
		}

		private void OnGUI()
		{
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: Expected O, but got Unknown
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0107: Unknown result type (might be due to invalid IL or missing references)
			if (_isVisible && _manager != null)
			{
				InitializeStyles();
				((Rect)(ref _windowRect)).width = WindowWidth;
				((Rect)(ref _windowRect)).height = WindowHeight;
				GUI.color = new Color(1f, 1f, 1f, _openAnimation);
				GUI.depth = -1000;
				_windowRect = GUI.Window(98765, _windowRect, new WindowFunction(DrawWindow), "", _windowStyle);
				((Rect)(ref _windowRect)).x = Mathf.Clamp(((Rect)(ref _windowRect)).x, 0f, (float)Screen.width - ((Rect)(ref _windowRect)).width);
				((Rect)(ref _windowRect)).y = Mathf.Clamp(((Rect)(ref _windowRect)).y, 0f, (float)Screen.height - ((Rect)(ref _windowRect)).height);
				GUI.color = Color.white;
			}
		}

		private void DrawWindow(int windowId)
		{
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			GUILayout.BeginVertical(Array.Empty<GUILayoutOption>());
			DrawHeader();
			DrawGoldDivider();
			DrawStats();
			DrawFilterBar();
			if (_showAddForm)
			{
				DrawAddForm();
			}
			else
			{
				DrawCategoryTabs();
				DrawTodoList();
			}
			DrawFooter();
			GUILayout.EndVertical();
			GUI.DragWindow(new Rect(0f, 0f, WindowWidth, HeaderHeight));
		}

		private void DrawHeader()
		{
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Expected O, but got Unknown
			GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
			GUILayout.Label("Todo List", _titleStyle, Array.Empty<GUILayoutOption>());
			GUILayout.FlexibleSpace();
			GUIContent val = new GUIContent(_showAddForm ? "Cancel" : "+ Add");
			if (GUILayout.Button(val, _buttonStyle, (GUILayoutOption[])(object)new GUILayoutOption[2]
			{
				GUILayout.Width(70f),
				GUILayout.Height(28f)
			}))
			{
				_showAddForm = !_showAddForm;
				if (!_showAddForm)
				{
					ResetAddForm();
				}
			}
			GUILayout.Space(8f);
			if (GUILayout.Button("X", _buttonStyle, (GUILayoutOption[])(object)new GUILayoutOption[2]
			{
				GUILayout.Width(28f),
				GUILayout.Height(28f)
			}))
			{
				Hide();
			}
			GUILayout.EndHorizontal();
		}

		private void DrawGoldDivider()
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Invalid comparison between Unknown and I4
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			GUILayout.Space(4f);
			Rect rect = GUILayoutUtility.GetRect(WindowWidth - Scaled(40f), Scaled(3f));
			if ((int)Event.current.type == 7 && (Object)(object)_goldLine != (Object)null)
			{
				GUI.DrawTexture(rect, (Texture)(object)_goldLine);
			}
			GUILayout.Space(4f);
		}

		private void DrawStats()
		{
			//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_011e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0124: Invalid comparison between Unknown and I4
			//IL_0142: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b3: Unknown result type (might be due to invalid IL or missing references)
			(int total, int completed, int active) stats = _manager.GetStats();
			int item = stats.total;
			int item2 = stats.completed;
			int item3 = stats.active;
			float completionPercent = _manager.GetCompletionPercent();
			GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
			GUILayout.FlexibleSpace();
			GUILayout.Label($"Active: {item3}", _statsStyle, Array.Empty<GUILayoutOption>());
			GUILayout.Space(20f);
			GUILayout.Label($"Completed: {item2}", _statsStyle, Array.Empty<GUILayoutOption>());
			GUILayout.Space(20f);
			GUILayout.Label($"Total: {item}", _statsStyle, Array.Empty<GUILayoutOption>());
			GUILayout.FlexibleSpace();
			GUILayout.EndHorizontal();
			GUILayout.Space(4f);
			Rect rect = GUILayoutUtility.GetRect(WindowWidth - Scaled(60f), Scaled(12f));
			((Rect)(ref rect)).x = ((Rect)(ref rect)).x + 10f;
			((Rect)(ref rect)).width = ((Rect)(ref rect)).width - 20f;
			if ((int)Event.current.type == 7)
			{
				if ((Object)(object)_progressBg != (Object)null)
				{
					GUI.DrawTexture(rect, (Texture)(object)_progressBg);
				}
				if ((Object)(object)_progressFill != (Object)null && completionPercent > 0f)
				{
					Rect val = default(Rect);
					((Rect)(ref val))..ctor(((Rect)(ref rect)).x + 2f, ((Rect)(ref rect)).y + 2f, (((Rect)(ref rect)).width - 4f) * (completionPercent / 100f), ((Rect)(ref rect)).height - 4f);
					GUI.DrawTexture(val, (Texture)(object)_progressFill);
				}
			}
			GUILayout.Space(8f);
		}

		private void DrawFilterBar()
		{
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Expected O, but got Unknown
			GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
			GUILayout.Label("Search:", _labelStyle, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(50f) });
			_searchQuery = GUILayout.TextField(_searchQuery, _textFieldStyle, (GUILayoutOption[])(object)new GUILayoutOption[2]
			{
				GUILayout.Width(150f),
				GUILayout.Height(24f)
			});
			GUILayout.Space(10f);
			GUIContent val = new GUIContent(_showCompletedItems ? "[v] Show Done" : "[ ] Show Done");
			if (GUILayout.Button(val, _buttonStyle, (GUILayoutOption[])(object)new GUILayoutOption[2]
			{
				GUILayout.Width(100f),
				GUILayout.Height(24f)
			}))
			{
				_showCompletedItems = !_showCompletedItems;
			}
			GUILayout.FlexibleSpace();
			if (_manager.GetCompletedTodos().Any() && GUILayout.Button("Clear Done", _buttonStyle, (GUILayoutOption[])(object)new GUILayoutOption[2]
			{
				GUILayout.Width(80f),
				GUILayout.Height(24f)
			}))
			{
				_manager.ClearCompleted();
			}
			GUILayout.EndHorizontal();
			GUILayout.Space(8f);
		}

		private void DrawCategoryTabs()
		{
			GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
			GUIStyle val = ((_selectedCategoryFilter == -1) ? _tabActiveStyle : _tabStyle);
			if (GUILayout.Button("All", val, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Height(26f) }))
			{
				_selectedCategoryFilter = -1;
			}
			Dictionary<TodoCategory, int> countsByCategory = _manager.GetCountsByCategory();
			foreach (TodoCategory value2 in Enum.GetValues(typeof(TodoCategory)))
			{
				int value;
				int num = (countsByCategory.TryGetValue(value2, out value) ? value : 0);
				GUIStyle val2 = ((value2 == (TodoCategory)_selectedCategoryFilter) ? _tabActiveStyle : _tabStyle);
				string text = ((num > 0) ? $"{value2} ({num})" : value2.ToString());
				if (GUILayout.Button(text, val2, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Height(26f) }))
				{
					_selectedCategoryFilter = (int)value2;
				}
			}
			GUILayout.FlexibleSpace();
			GUILayout.EndHorizontal();
			GUILayout.Space(8f);
		}

		private void DrawTodoList()
		{
			//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0100: Unknown result type (might be due to invalid IL or missing references)
			if (_cachedFilterCategory != _selectedCategoryFilter || _cachedFilterShowCompleted != _showCompletedItems || _cachedFilterSearch != _searchQuery)
			{
				_cachedDrawListDirty = true;
			}
			if (_cachedDrawListDirty)
			{
				_cachedDrawListDirty = false;
				_cachedFilterCategory = _selectedCategoryFilter;
				_cachedFilterShowCompleted = _showCompletedItems;
				_cachedFilterSearch = _searchQuery;
				_cachedDrawList.Clear();
				foreach (TodoItem filteredTodo in GetFilteredTodos())
				{
					_cachedDrawList.Add(filteredTodo);
				}
				_cachedDrawList.Sort(delegate(TodoItem a, TodoItem b)
				{
					if (a.IsCompleted != b.IsCompleted)
					{
						return a.IsCompleted.CompareTo(b.IsCompleted);
					}
					int num = ((int)b.Priority).CompareTo((int)a.Priority);
					return (num != 0) ? num : b.CreatedAt.CompareTo(a.CreatedAt);
				});
			}
			_scrollPosition = GUILayout.BeginScrollView(_scrollPosition, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandHeight(true) });
			if (_cachedDrawList.Count == 0)
			{
				GUILayout.Space(20f);
				GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
				GUILayout.FlexibleSpace();
				GUILayout.Label("No tasks to show", _labelStyle, Array.Empty<GUILayoutOption>());
				GUILayout.FlexibleSpace();
				GUILayout.EndHorizontal();
				GUILayout.Space(20f);
			}
			else
			{
				for (int i = 0; i < _cachedDrawList.Count; i++)
				{
					DrawTodoItem(_cachedDrawList[i], i);
				}
			}
			GUILayout.EndScrollView();
		}

		private void DrawTodoItem(TodoItem item, int index)
		{
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Expected O, but got Unknown
			//IL_00ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fb: Expected O, but got Unknown
			//IL_011e: 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_0130: Unknown result type (might be due to invalid IL or missing references)
			//IL_0135: Unknown result type (might be due to invalid IL or missing references)
			//IL_013f: Expected O, but got Unknown
			//IL_0142: Expected O, but got Unknown
			//IL_02bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c3: Unknown result type (might be due