Decompiled source of RavenRoute v1.0.2

RavenRoute.dll

Decompiled 15 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using RavenRoute.Input;
using RavenRoute.Navigation;
using RavenRoute.UI;
using Splatform;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.UI;
using ValheimModShared;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyCompany("RavenRoute")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+68810150f795e4e1a192f367a96d5e5d7a3512c7")]
[assembly: AssemblyProduct("RavenRoute")]
[assembly: AssemblyTitle("RavenRoute")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace ValheimModShared
{
	public sealed class DiagnosticLogger : IDisposable
	{
		private readonly ManualLogSource _logSource;

		private readonly ConfigEntry<bool> _debugEnabled;

		private readonly ConfigEntry<bool> _fileLoggingEnabled;

		private readonly string _logFilePath;

		private readonly object _fileLock = new object();

		private bool _disposed;

		public string LogFilePath => _logFilePath;

		public bool IsDebugEnabled => _debugEnabled.Value;

		public DiagnosticLogger(ManualLogSource logSource, string modFolderName, string logFileName, ConfigEntry<bool> debugEnabled, ConfigEntry<bool> fileLoggingEnabled)
		{
			_logSource = logSource ?? throw new ArgumentNullException("logSource");
			_debugEnabled = debugEnabled ?? throw new ArgumentNullException("debugEnabled");
			_fileLoggingEnabled = fileLoggingEnabled ?? throw new ArgumentNullException("fileLoggingEnabled");
			string path = Path.Combine(Paths.ConfigPath, modFolderName);
			_logFilePath = Path.Combine(path, logFileName);
			_debugEnabled.SettingChanged += OnLoggingConfigChanged;
			_fileLoggingEnabled.SettingChanged += OnLoggingConfigChanged;
			if (_fileLoggingEnabled.Value)
			{
				WriteSessionHeader();
			}
		}

		public void Info(string message)
		{
			_logSource.LogInfo((object)message);
			WriteFileLine("INFO", message);
		}

		public void Warn(string message)
		{
			_logSource.LogWarning((object)message);
			WriteFileLine("WARN", message);
		}

		public void Error(string message, Exception? ex = null)
		{
			string text = ((ex == null) ? message : (message + " | " + ex.GetType().Name + ": " + ex.Message + "\n" + ex.StackTrace));
			_logSource.LogError((object)text);
			WriteFileLine("ERROR", text);
		}

		public void Debug(string message)
		{
			if (_debugEnabled.Value)
			{
				_logSource.LogInfo((object)("[DEBUG] " + message));
				WriteFileLine("DEBUG", message);
			}
		}

		private void OnLoggingConfigChanged(object? sender, EventArgs e)
		{
			string text = $"Logging config updated: DebugLogging={_debugEnabled.Value}, WriteDebugLogFile={_fileLoggingEnabled.Value}";
			_logSource.LogInfo((object)text);
			if (_fileLoggingEnabled.Value)
			{
				WriteFileLine("INFO", text);
			}
		}

		private void WriteSessionHeader()
		{
			WriteFileLine("INFO", $"========== Session started ({DateTime.Now:yyyy-MM-dd HH:mm:ss}) ==========");
		}

		private void WriteFileLine(string level, string message)
		{
			if (!_fileLoggingEnabled.Value)
			{
				return;
			}
			string contents = $"[{DateTime.Now:HH:mm:ss.fff}] [{level}] {message}{Environment.NewLine}";
			lock (_fileLock)
			{
				try
				{
					string directoryName = Path.GetDirectoryName(_logFilePath);
					if (!string.IsNullOrEmpty(directoryName) && !Directory.Exists(directoryName))
					{
						Directory.CreateDirectory(directoryName);
					}
					File.AppendAllText(_logFilePath, contents, Encoding.UTF8);
				}
				catch (Exception ex)
				{
					_logSource.LogWarning((object)("Failed writing diagnostic log file '" + _logFilePath + "': " + ex.Message));
				}
			}
		}

		public void Dispose()
		{
			if (!_disposed)
			{
				_debugEnabled.SettingChanged -= OnLoggingConfigChanged;
				_fileLoggingEnabled.SettingChanged -= OnLoggingConfigChanged;
				_disposed = true;
			}
		}
	}
	public static class FileConfigIO
	{
		private sealed class JsonParser
		{
			private readonly string _json;

			public int Position { get; private set; }

			public bool IsAtEnd => Position >= _json.Length;

			public JsonParser(string json)
			{
				_json = json;
			}

			public void SkipWhitespace()
			{
				while (Position < _json.Length && char.IsWhiteSpace(_json[Position]))
				{
					Position++;
				}
			}

			public object? ParseValue()
			{
				SkipWhitespace();
				if (IsAtEnd)
				{
					throw new FormatException("Unexpected end of JSON input.");
				}
				char c = _json[Position];
				switch (c)
				{
				case '{':
					return ParseObject();
				case '[':
					return ParseArray();
				case '"':
					return ParseString();
				case 't':
					return ParseLiteral("true", true);
				case 'f':
					return ParseLiteral("false", false);
				case 'n':
					return ParseLiteral("null", null);
				default:
					if (!char.IsDigit(c))
					{
						throw new FormatException($"Unexpected character '{c}' at position {Position}.");
					}
					goto case '-';
				case '-':
					return ParseNumber();
				}
			}

			private Dictionary<string, object?> ParseObject()
			{
				Dictionary<string, object> dictionary = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
				Position++;
				SkipWhitespace();
				if (!IsAtEnd && _json[Position] == '}')
				{
					Position++;
					return dictionary;
				}
				while (true)
				{
					SkipWhitespace();
					if (IsAtEnd || _json[Position] != '"')
					{
						throw new FormatException($"Expected string key at position {Position}.");
					}
					string text = ParseString();
					SkipWhitespace();
					if (IsAtEnd || _json[Position] != ':')
					{
						throw new FormatException($"Expected ':' after key '{text}' at position {Position}.");
					}
					Position++;
					dictionary[text] = ParseValue();
					SkipWhitespace();
					if (IsAtEnd)
					{
						break;
					}
					switch (_json[Position])
					{
					case '}':
						Position++;
						return dictionary;
					default:
						throw new FormatException($"Expected ',' or '}}' at position {Position}.");
					case ',':
						break;
					}
					Position++;
				}
				throw new FormatException("Unterminated JSON object.");
			}

			private List<object?> ParseArray()
			{
				List<object> list = new List<object>();
				Position++;
				SkipWhitespace();
				if (!IsAtEnd && _json[Position] == ']')
				{
					Position++;
					return list;
				}
				while (true)
				{
					list.Add(ParseValue());
					SkipWhitespace();
					if (IsAtEnd)
					{
						break;
					}
					switch (_json[Position])
					{
					case ']':
						Position++;
						return list;
					default:
						throw new FormatException($"Expected ',' or ']' at position {Position}.");
					case ',':
						break;
					}
					Position++;
				}
				throw new FormatException("Unterminated JSON array.");
			}

			private string ParseString()
			{
				Position++;
				StringBuilder stringBuilder = new StringBuilder();
				while (!IsAtEnd)
				{
					char c = _json[Position++];
					switch (c)
					{
					case '"':
						return stringBuilder.ToString();
					case '\\':
					{
						if (IsAtEnd)
						{
							throw new FormatException("Unterminated escape sequence in JSON string.");
						}
						char c2 = _json[Position++];
						switch (c2)
						{
						case '"':
							stringBuilder.Append('"');
							break;
						case '\\':
							stringBuilder.Append('\\');
							break;
						case '/':
							stringBuilder.Append('/');
							break;
						case 'b':
							stringBuilder.Append('\b');
							break;
						case 'f':
							stringBuilder.Append('\f');
							break;
						case 'n':
							stringBuilder.Append('\n');
							break;
						case 'r':
							stringBuilder.Append('\r');
							break;
						case 't':
							stringBuilder.Append('\t');
							break;
						case 'u':
						{
							if (Position + 4 > _json.Length)
							{
								throw new FormatException("Incomplete \\u escape in JSON string.");
							}
							string s = _json.Substring(Position, 4);
							Position += 4;
							stringBuilder.Append((char)int.Parse(s, NumberStyles.HexNumber, CultureInfo.InvariantCulture));
							break;
						}
						default:
							throw new FormatException($"Invalid escape character '\\{c2}' at position {Position - 1}.");
						}
						break;
					}
					default:
						stringBuilder.Append(c);
						break;
					}
				}
				throw new FormatException("Unterminated JSON string.");
			}

			private object? ParseLiteral(string expected, object? result)
			{
				if (Position + expected.Length > _json.Length || !string.Equals(_json.Substring(Position, expected.Length), expected, StringComparison.Ordinal))
				{
					throw new FormatException($"Expected '{expected}' at position {Position}.");
				}
				Position += expected.Length;
				return result;
			}

			private double ParseNumber()
			{
				int position = Position;
				if (_json[Position] == '-')
				{
					Position++;
				}
				while (!IsAtEnd && char.IsDigit(_json[Position]))
				{
					Position++;
				}
				if (!IsAtEnd && _json[Position] == '.')
				{
					Position++;
					while (!IsAtEnd && char.IsDigit(_json[Position]))
					{
						Position++;
					}
				}
				if (!IsAtEnd && (_json[Position] == 'e' || _json[Position] == 'E'))
				{
					Position++;
					if (!IsAtEnd && (_json[Position] == '+' || _json[Position] == '-'))
					{
						Position++;
					}
					while (!IsAtEnd && char.IsDigit(_json[Position]))
					{
						Position++;
					}
				}
				string text = _json.Substring(position, Position - position);
				if (!double.TryParse(text, NumberStyles.Float, CultureInfo.InvariantCulture, out var result))
				{
					throw new FormatException($"Invalid number '{text}' at position {position}.");
				}
				return result;
			}
		}

		private static readonly Encoding Utf8NoBom = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false);

		public static void EnsureDirectory(string directoryPath)
		{
			if (directoryPath != null && !string.IsNullOrWhiteSpace(directoryPath) && !Directory.Exists(directoryPath))
			{
				Directory.CreateDirectory(directoryPath);
			}
		}

		public static string SanitizeFileName(string? rawName, string fallback = "unknown")
		{
			if (rawName == null || string.IsNullOrWhiteSpace(rawName))
			{
				return fallback;
			}
			StringBuilder stringBuilder = new StringBuilder(rawName.Length);
			string text = rawName.Trim();
			foreach (char c in text)
			{
				if (char.IsLetterOrDigit(c) || c == '-' || c == '_')
				{
					stringBuilder.Append(c);
				}
				else
				{
					stringBuilder.Append('_');
				}
			}
			string text2 = stringBuilder.ToString().Trim(new char[1] { '_' });
			if (text2.Length <= 0)
			{
				return fallback;
			}
			return text2;
		}

		public static bool TryReadAllText(string filePath, out string content, out string? error)
		{
			content = string.Empty;
			error = null;
			if (!File.Exists(filePath))
			{
				return false;
			}
			try
			{
				content = File.ReadAllText(filePath, Utf8NoBom);
				return true;
			}
			catch (Exception ex)
			{
				error = ex.Message;
				return false;
			}
		}

		public static bool TryWriteAllTextAtomic(string filePath, string content, out string? error)
		{
			error = null;
			string text = filePath + ".tmp";
			try
			{
				string directoryName = Path.GetDirectoryName(filePath);
				if (directoryName != null)
				{
					EnsureDirectory(directoryName);
				}
				File.WriteAllText(text, content, Utf8NoBom);
				if (File.Exists(filePath))
				{
					try
					{
						File.Replace(text, filePath, null);
					}
					catch
					{
						File.Copy(text, filePath, overwrite: true);
						File.Delete(text);
					}
				}
				else
				{
					File.Move(text, filePath);
				}
				return true;
			}
			catch (Exception ex)
			{
				error = ex.Message;
				TryDeleteQuietly(text);
				return false;
			}
		}

		private static void TryDeleteQuietly(string path)
		{
			try
			{
				if (File.Exists(path))
				{
					File.Delete(path);
				}
			}
			catch
			{
			}
		}

		public static object? ParseJson(string json)
		{
			JsonParser jsonParser = new JsonParser(json ?? string.Empty);
			object? result = jsonParser.ParseValue();
			jsonParser.SkipWhitespace();
			if (!jsonParser.IsAtEnd)
			{
				throw new FormatException($"Unexpected trailing character at position {jsonParser.Position}.");
			}
			return result;
		}

		public static string ToPrettyJson(object? value)
		{
			StringBuilder stringBuilder = new StringBuilder(256);
			WriteJsonValue(stringBuilder, value, 0);
			stringBuilder.Append('\n');
			return stringBuilder.ToString();
		}

		private static void WriteJsonValue(StringBuilder sb, object? value, int indentLevel)
		{
			if (value != null)
			{
				if (!(value is bool flag))
				{
					if (!(value is string text))
					{
						if (!(value is int num))
						{
							if (!(value is long num2))
							{
								if (!(value is float f))
								{
									if (!(value is double d))
									{
										if (!(value is IDictionary<string, object> dict))
										{
											if (value is IList<object> list)
											{
												WriteJsonArray(sb, list, indentLevel);
											}
											else
											{
												WriteEscapedString(sb, Convert.ToString(value, CultureInfo.InvariantCulture) ?? string.Empty);
											}
										}
										else
										{
											WriteJsonObject(sb, dict, indentLevel);
										}
									}
									else
									{
										sb.Append((double.IsNaN(d) || double.IsInfinity(d)) ? "0" : d.ToString("0.###", CultureInfo.InvariantCulture));
									}
								}
								else
								{
									sb.Append((float.IsNaN(f) || float.IsInfinity(f)) ? "0" : f.ToString("0.###", CultureInfo.InvariantCulture));
								}
							}
							else
							{
								sb.Append(num2.ToString(CultureInfo.InvariantCulture));
							}
						}
						else
						{
							sb.Append(num.ToString(CultureInfo.InvariantCulture));
						}
					}
					else
					{
						WriteEscapedString(sb, text);
					}
				}
				else
				{
					sb.Append(flag ? "true" : "false");
				}
			}
			else
			{
				sb.Append("null");
			}
		}

		private static void WriteJsonObject(StringBuilder sb, IDictionary<string, object?> dict, int indentLevel)
		{
			if (dict.Count == 0)
			{
				sb.Append("{}");
				return;
			}
			sb.Append("{\n");
			int num = 0;
			foreach (KeyValuePair<string, object> item in dict)
			{
				AppendIndent(sb, indentLevel + 1);
				WriteEscapedString(sb, item.Key);
				sb.Append(": ");
				WriteJsonValue(sb, item.Value, indentLevel + 1);
				num++;
				if (num < dict.Count)
				{
					sb.Append(',');
				}
				sb.Append('\n');
			}
			AppendIndent(sb, indentLevel);
			sb.Append('}');
		}

		private static void WriteJsonArray(StringBuilder sb, IList<object?> list, int indentLevel)
		{
			if (list.Count == 0)
			{
				sb.Append("[]");
				return;
			}
			sb.Append("[\n");
			for (int i = 0; i < list.Count; i++)
			{
				AppendIndent(sb, indentLevel + 1);
				WriteJsonValue(sb, list[i], indentLevel + 1);
				if (i < list.Count - 1)
				{
					sb.Append(',');
				}
				sb.Append('\n');
			}
			AppendIndent(sb, indentLevel);
			sb.Append(']');
		}

		private static void AppendIndent(StringBuilder sb, int level)
		{
			for (int i = 0; i < level * 2; i++)
			{
				sb.Append(' ');
			}
		}

		private static void WriteEscapedString(StringBuilder sb, string text)
		{
			sb.Append('"');
			foreach (char c in text)
			{
				switch (c)
				{
				case '"':
					sb.Append("\\\"");
					continue;
				case '\\':
					sb.Append("\\\\");
					continue;
				case '\b':
					sb.Append("\\b");
					continue;
				case '\f':
					sb.Append("\\f");
					continue;
				case '\n':
					sb.Append("\\n");
					continue;
				case '\r':
					sb.Append("\\r");
					continue;
				case '\t':
					sb.Append("\\t");
					continue;
				}
				if (c < ' ')
				{
					sb.Append("\\u");
					int num = c;
					sb.Append(num.ToString("x4", CultureInfo.InvariantCulture));
				}
				else
				{
					sb.Append(c);
				}
			}
			sb.Append('"');
		}
	}
	public sealed class ConfigFileReloader
	{
		private readonly ConfigFile _config;

		private readonly DiagnosticLogger? _logger;

		private readonly double _pollIntervalSeconds;

		private readonly double _debounceSeconds;

		private DateTime _nextPollUtc;

		private DateTime _lastKnownWriteUtc;

		private DateTime? _pendingWriteUtc;

		private DateTime _pendingDetectedUtc;

		public ConfigFileReloader(ConfigFile config, DiagnosticLogger? logger = null, double pollIntervalSeconds = 0.5, double debounceSeconds = 0.15)
		{
			_config = config ?? throw new ArgumentNullException("config");
			_logger = logger;
			_pollIntervalSeconds = Math.Max(0.1, pollIntervalSeconds);
			_debounceSeconds = Math.Max(0.05, debounceSeconds);
			_lastKnownWriteUtc = GetWriteTimeUtc(_config.ConfigFilePath);
			_nextPollUtc = DateTime.UtcNow.AddSeconds(_pollIntervalSeconds);
		}

		public void Tick()
		{
			DateTime utcNow = DateTime.UtcNow;
			if (utcNow < _nextPollUtc)
			{
				return;
			}
			_nextPollUtc = utcNow.AddSeconds(_pollIntervalSeconds);
			DateTime writeTimeUtc = GetWriteTimeUtc(_config.ConfigFilePath);
			if (writeTimeUtc == DateTime.MinValue || !(writeTimeUtc != _lastKnownWriteUtc))
			{
				return;
			}
			if (!_pendingWriteUtc.HasValue || _pendingWriteUtc.Value != writeTimeUtc)
			{
				_pendingWriteUtc = writeTimeUtc;
				_pendingDetectedUtc = utcNow;
			}
			else if (!((utcNow - _pendingDetectedUtc).TotalSeconds < _debounceSeconds))
			{
				_lastKnownWriteUtc = writeTimeUtc;
				_pendingWriteUtc = null;
				try
				{
					_config.Reload();
					_logger?.Info("[Config] External edit detected -> reloaded '" + Path.GetFileName(_config.ConfigFilePath) + "'.");
				}
				catch (Exception ex)
				{
					_logger?.Warn("[Config] Failed reloading '" + _config.ConfigFilePath + "': " + ex.Message);
				}
			}
		}

		public void SyncWriteTime()
		{
			_lastKnownWriteUtc = GetWriteTimeUtc(_config.ConfigFilePath);
			_pendingWriteUtc = null;
		}

		private static DateTime GetWriteTimeUtc(string filePath)
		{
			try
			{
				return File.Exists(filePath) ? File.GetLastWriteTimeUtc(filePath) : DateTime.MinValue;
			}
			catch
			{
				return DateTime.MinValue;
			}
		}
	}
	public static class UiComponents
	{
		private static Font? _cachedFont;

		public static Color ParseHexColor(string? hex, Color fallback)
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: 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)
			if (hex == null || string.IsNullOrWhiteSpace(hex))
			{
				return fallback;
			}
			string text = hex.Trim();
			if (!text.StartsWith("#"))
			{
				text = "#" + text;
			}
			Color result = default(Color);
			if (!ColorUtility.TryParseHtmlString(text, ref result))
			{
				return fallback;
			}
			return result;
		}

		public static Font? ResolveUiFont(out string fontName)
		{
			if ((Object)(object)_cachedFont != (Object)null)
			{
				fontName = ((Object)_cachedFont).name;
				return _cachedFont;
			}
			Font[] array = Resources.FindObjectsOfTypeAll<Font>();
			foreach (Font val in array)
			{
				if ((Object)(object)val != (Object)null && ((Object)val).name.IndexOf("AveriaSansLibre", StringComparison.OrdinalIgnoreCase) >= 0)
				{
					_cachedFont = val;
					fontName = ((Object)val).name;
					return _cachedFont;
				}
			}
			Font builtinResource = Resources.GetBuiltinResource<Font>("LegacyRuntime.ttf");
			if ((Object)(object)builtinResource == (Object)null)
			{
				builtinResource = Resources.GetBuiltinResource<Font>("Arial.ttf");
			}
			if ((Object)(object)builtinResource != (Object)null)
			{
				_cachedFont = builtinResource;
				fontName = ((Object)builtinResource).name;
				return _cachedFont;
			}
			fontName = "<none>";
			return null;
		}

		public static Canvas CreateOverlayCanvas(string name, int sortingOrder, bool interactive)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Expected O, but got Unknown
			GameObject val = new GameObject(name);
			Object.DontDestroyOnLoad((Object)(object)val);
			Canvas val2 = val.AddComponent<Canvas>();
			val2.renderMode = (RenderMode)0;
			val2.sortingOrder = sortingOrder;
			CanvasScaler obj = val.AddComponent<CanvasScaler>();
			obj.uiScaleMode = (ScaleMode)0;
			obj.scaleFactor = 1f;
			if (interactive)
			{
				val.AddComponent<GraphicRaycaster>();
			}
			return val2;
		}

		public static Text CreateShadowedText(Transform parent, string name, Font? font, int fontSize, Color color, TextAnchor alignment = (TextAnchor)4, FontStyle fontStyle = (FontStyle)0, HorizontalWrapMode horizontalOverflow = (HorizontalWrapMode)1)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Expected O, but got Unknown
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: 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_0098: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject(name, new Type[1] { typeof(RectTransform) });
			val.transform.SetParent(parent, false);
			Text obj = val.AddComponent<Text>();
			obj.font = font;
			obj.fontSize = fontSize;
			((Graphic)obj).color = color;
			obj.alignment = alignment;
			obj.fontStyle = fontStyle;
			obj.horizontalOverflow = horizontalOverflow;
			obj.verticalOverflow = (VerticalWrapMode)1;
			((Graphic)obj).raycastTarget = false;
			Shadow obj2 = val.AddComponent<Shadow>();
			obj2.effectColor = new Color(0f, 0f, 0f, 0.85f);
			obj2.effectDistance = new Vector2(1.25f, -1.25f);
			return obj;
		}

		public static Texture2D CreateRoundedRectTexture(int size, int cornerRadius)
		{
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Expected O, but got Unknown
			//IL_00f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fd: Unknown result type (might be due to invalid IL or missing references)
			Texture2D val = new Texture2D(size, size, (TextureFormat)4, false)
			{
				wrapMode = (TextureWrapMode)1,
				filterMode = (FilterMode)1
			};
			float num = (float)size * 0.5f;
			float num2 = Mathf.Clamp(cornerRadius, 1, size / 2);
			float num3 = num - num2;
			Color32[] array = (Color32[])(object)new Color32[size * size];
			for (int i = 0; i < size; i++)
			{
				float num4 = Mathf.Abs((float)i + 0.5f - num) - num3;
				for (int j = 0; j < size; j++)
				{
					float num5 = Mathf.Abs((float)j + 0.5f - num) - num3;
					float num6 = Mathf.Sqrt(Mathf.Max(num5, 0f) * Mathf.Max(num5, 0f) + Mathf.Max(num4, 0f) * Mathf.Max(num4, 0f)) + Mathf.Min(Mathf.Max(num5, num4), 0f) - num2;
					byte b = (byte)Mathf.RoundToInt(Mathf.Clamp01(0.5f - num6) * 255f);
					array[i * size + j] = new Color32(byte.MaxValue, byte.MaxValue, byte.MaxValue, b);
				}
			}
			val.SetPixels32(array);
			val.Apply(false, false);
			return val;
		}

		public static Sprite CreateSlicedSprite(Texture2D texture, float borderPixels)
		{
			//IL_0019: 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_0038: Unknown result type (might be due to invalid IL or missing references)
			return Sprite.Create(texture, new Rect(0f, 0f, (float)((Texture)texture).width, (float)((Texture)texture).height), new Vector2(0.5f, 0.5f), 100f, 0u, (SpriteMeshType)0, new Vector4(borderPixels, borderPixels, borderPixels, borderPixels));
		}

		public static Button CreateActionButton(Transform parent, string name, Font? font, string label, int fontSize, float width, float height, Sprite? backgroundSprite, Color normalColor, Color highlightColor, Color pressedColor, Color disabledColor, Color textColor, Action onClick)
		{
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Expected O, but got Unknown
			//IL_007b: 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_00b1: 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_00be: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ca: 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_00dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0105: Unknown result type (might be due to invalid IL or missing references)
			//IL_0118: Unknown result type (might be due to invalid IL or missing references)
			//IL_0122: Expected O, but got Unknown
			//IL_0130: Unknown result type (might be due to invalid IL or missing references)
			//IL_0141: Unknown result type (might be due to invalid IL or missing references)
			//IL_014c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0157: Unknown result type (might be due to invalid IL or missing references)
			//IL_0161: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject(name, new Type[1] { typeof(RectTransform) });
			val.transform.SetParent(parent, false);
			LayoutElement obj = val.AddComponent<LayoutElement>();
			obj.minWidth = width;
			obj.preferredWidth = width;
			obj.minHeight = height;
			obj.preferredHeight = height;
			Image val2 = val.AddComponent<Image>();
			if ((Object)(object)backgroundSprite != (Object)null)
			{
				val2.sprite = backgroundSprite;
				val2.type = (Type)1;
			}
			((Graphic)val2).color = Color.white;
			((Graphic)val2).raycastTarget = true;
			Button obj2 = val.AddComponent<Button>();
			((Selectable)obj2).targetGraphic = (Graphic)(object)val2;
			((Selectable)obj2).transition = (Transition)1;
			Navigation navigation = default(Navigation);
			((Navigation)(ref navigation)).mode = (Mode)0;
			((Selectable)obj2).navigation = navigation;
			ColorBlock colors = ((Selectable)obj2).colors;
			((ColorBlock)(ref colors)).normalColor = normalColor;
			((ColorBlock)(ref colors)).highlightedColor = highlightColor;
			((ColorBlock)(ref colors)).pressedColor = pressedColor;
			((ColorBlock)(ref colors)).selectedColor = highlightColor;
			((ColorBlock)(ref colors)).disabledColor = disabledColor;
			((ColorBlock)(ref colors)).colorMultiplier = 1f;
			((ColorBlock)(ref colors)).fadeDuration = 0.06f;
			((Selectable)obj2).colors = colors;
			((UnityEvent)obj2.onClick).AddListener((UnityAction)delegate
			{
				onClick();
			});
			Text obj3 = CreateShadowedText(val.transform, "Label", font, fontSize, textColor, (TextAnchor)4, (FontStyle)1, (HorizontalWrapMode)1);
			RectTransform rectTransform = ((Graphic)obj3).rectTransform;
			rectTransform.anchorMin = Vector2.zero;
			rectTransform.anchorMax = Vector2.one;
			rectTransform.offsetMin = Vector2.zero;
			rectTransform.offsetMax = Vector2.zero;
			obj3.text = label;
			return obj2;
		}
	}
	public readonly struct PromptGuideEntry
	{
		public string KeyHint { get; }

		public string ActionLabel { get; }

		public PromptGuideEntry(string keyHint, string actionLabel)
		{
			KeyHint = keyHint;
			ActionLabel = actionLabel;
		}
	}
	public sealed class PromptGuideBar
	{
		private static readonly Color BarBackdropColor = new Color(0.07f, 0.06f, 0.05f, 0.8f);

		private static readonly Color BadgeBgColor = new Color(0.2f, 0.16f, 0.11f, 0.95f);

		private static readonly Color KeyTextColor = new Color(0.92f, 0.76f, 0.34f, 1f);

		private static readonly Color ActionTextColor = new Color(0.95f, 0.95f, 0.95f, 1f);

		private readonly GameObject _root;

		private readonly RectTransform _rootRect;

		private readonly Font? _font;

		private readonly Sprite? _roundedSprite;

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

		public GameObject Root => _root;

		public RectTransform RectTransform => _rootRect;

		public PromptGuideBar(Transform parent, string name, Font? font, Sprite? roundedSprite, float bottomOffsetPixels = 16f)
		{
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Expected O, but got Unknown
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: 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_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_0110: Unknown result type (might be due to invalid IL or missing references)
			//IL_011a: Expected O, but got Unknown
			_font = font;
			_roundedSprite = roundedSprite;
			_root = new GameObject(name, new Type[1] { typeof(RectTransform) });
			_root.transform.SetParent(parent, false);
			_rootRect = _root.GetComponent<RectTransform>();
			_rootRect.anchorMin = new Vector2(0.5f, 0f);
			_rootRect.anchorMax = new Vector2(0.5f, 0f);
			_rootRect.pivot = new Vector2(0.5f, 0f);
			_rootRect.anchoredPosition = new Vector2(0f, bottomOffsetPixels);
			Image val = _root.AddComponent<Image>();
			if ((Object)(object)roundedSprite != (Object)null)
			{
				val.sprite = roundedSprite;
				val.type = (Type)1;
			}
			((Graphic)val).color = BarBackdropColor;
			((Graphic)val).raycastTarget = false;
			HorizontalLayoutGroup obj = _root.AddComponent<HorizontalLayoutGroup>();
			((LayoutGroup)obj).padding = new RectOffset(14, 14, 6, 6);
			((HorizontalOrVerticalLayoutGroup)obj).spacing = 14f;
			((LayoutGroup)obj).childAlignment = (TextAnchor)4;
			((HorizontalOrVerticalLayoutGroup)obj).childControlWidth = true;
			((HorizontalOrVerticalLayoutGroup)obj).childControlHeight = true;
			((HorizontalOrVerticalLayoutGroup)obj).childForceExpandWidth = false;
			((HorizontalOrVerticalLayoutGroup)obj).childForceExpandHeight = false;
			ContentSizeFitter obj2 = _root.AddComponent<ContentSizeFitter>();
			obj2.horizontalFit = (FitMode)2;
			obj2.verticalFit = (FitMode)2;
		}

		public void SetVisible(bool visible)
		{
			if (_root.activeSelf != visible)
			{
				_root.SetActive(visible);
			}
		}

		public void SetScale(float scale)
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			float num = Mathf.Clamp(scale, 0.6f, 1.8f);
			((Transform)_rootRect).localScale = new Vector3(num, num, 1f);
		}

		public void SetEntries(IReadOnlyList<PromptGuideEntry> entries)
		{
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Expected O, but got Unknown
			//IL_00fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0102: Unknown result type (might be due to invalid IL or missing references)
			//IL_0114: Unknown result type (might be due to invalid IL or missing references)
			//IL_0141: Unknown result type (might be due to invalid IL or missing references)
			//IL_0153: Unknown result type (might be due to invalid IL or missing references)
			//IL_015e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0168: Expected O, but got Unknown
			//IL_018e: 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)
			for (int i = 0; i < _itemObjects.Count; i++)
			{
				if ((Object)(object)_itemObjects[i] != (Object)null)
				{
					Object.Destroy((Object)(object)_itemObjects[i]);
				}
			}
			_itemObjects.Clear();
			for (int j = 0; j < entries.Count; j++)
			{
				PromptGuideEntry promptGuideEntry = entries[j];
				if (promptGuideEntry.KeyHint != null && !string.IsNullOrWhiteSpace(promptGuideEntry.KeyHint))
				{
					GameObject val = new GameObject($"Prompt_{j}", new Type[1] { typeof(RectTransform) });
					val.transform.SetParent(_root.transform, false);
					HorizontalLayoutGroup obj = val.AddComponent<HorizontalLayoutGroup>();
					((HorizontalOrVerticalLayoutGroup)obj).spacing = 5f;
					((LayoutGroup)obj).childAlignment = (TextAnchor)4;
					((HorizontalOrVerticalLayoutGroup)obj).childControlWidth = true;
					((HorizontalOrVerticalLayoutGroup)obj).childControlHeight = true;
					((HorizontalOrVerticalLayoutGroup)obj).childForceExpandWidth = false;
					((HorizontalOrVerticalLayoutGroup)obj).childForceExpandHeight = false;
					GameObject val2 = new GameObject("Badge", new Type[1] { typeof(RectTransform) });
					val2.transform.SetParent(val.transform, false);
					Image val3 = val2.AddComponent<Image>();
					if ((Object)(object)_roundedSprite != (Object)null)
					{
						val3.sprite = _roundedSprite;
						val3.type = (Type)1;
					}
					((Graphic)val3).color = BadgeBgColor;
					((Graphic)val3).raycastTarget = false;
					HorizontalLayoutGroup obj2 = val2.AddComponent<HorizontalLayoutGroup>();
					((LayoutGroup)obj2).padding = new RectOffset(6, 6, 2, 2);
					((LayoutGroup)obj2).childAlignment = (TextAnchor)4;
					((HorizontalOrVerticalLayoutGroup)obj2).childControlWidth = true;
					((HorizontalOrVerticalLayoutGroup)obj2).childControlHeight = true;
					UiComponents.CreateShadowedText(val2.transform, "Key", _font, 12, KeyTextColor, (TextAnchor)4, (FontStyle)1, (HorizontalWrapMode)1).text = promptGuideEntry.KeyHint;
					UiComponents.CreateShadowedText(val.transform, "Action", _font, 12, ActionTextColor, (TextAnchor)3, (FontStyle)0, (HorizontalWrapMode)1).text = promptGuideEntry.ActionLabel;
					_itemObjects.Add(val);
				}
			}
		}
	}
}
namespace RavenRoute
{
	[BepInPlugin("com.MyrkForge.ravenroute", "RavenRoute", "1.0.0")]
	public sealed class Plugin : BaseUnityPlugin
	{
		public const string PluginGuid = "com.MyrkForge.ravenroute";

		public const string PluginName = "RavenRoute";

		public const string PluginVersion = "1.0.0";

		private Harmony? _harmony;

		private DiagnosticLogger? _diagnosticLogger;

		private RouteStorage? _routeStorage;

		private RouteController? _routeController;

		private LargeMapInputController? _mapInputController;

		private RavenHudRenderer? _hudRenderer;

		private ConfigFileReloader? _configReloader;

		private DualInputBinding? _toggleHudBinding;

		private LargeMapRoutePanel? _routePanel;

		private readonly List<DualInputBinding> _panelBindings = new List<DualInputBinding>();

		private RavenMapPinManager? _mapPinManager;

		private ConfigEntry<bool>? _showRoutePanel;

		private ConfigEntry<bool>? _showMapKeyGuides;

		private ConfigEntry<string>? _panelSide;

		private ConfigEntry<float>? _panelScale;

		private ConfigEntry<string>? _navUpKbm;

		private ConfigEntry<string>? _navUpGamepad;

		private ConfigEntry<string>? _navDownKbm;

		private ConfigEntry<string>? _navDownGamepad;

		private ConfigEntry<string>? _jumpStopKbm;

		private ConfigEntry<string>? _jumpStopGamepad;

		private ConfigEntry<string>? _moveUpKbm;

		private ConfigEntry<string>? _moveUpGamepad;

		private ConfigEntry<string>? _moveDownKbm;

		private ConfigEntry<string>? _moveDownGamepad;

		private ConfigEntry<string>? _removeStopKbm;

		private ConfigEntry<string>? _removeStopGamepad;

		private ConfigEntry<string>? _clearRouteKbm;

		private ConfigEntry<string>? _clearRouteGamepad;

		private ConfigEntry<string>? _unfocusPanelKbm;

		private ConfigEntry<string>? _unfocusPanelGamepad;

		private ConfigEntry<string>? _toggleHudKbm;

		private ConfigEntry<string>? _toggleHudGamepad;

		private ConfigEntry<bool>? _enabled;

		private ConfigEntry<bool>? _saveRoutePerCharacter;

		private ConfigEntry<float>? _arrivalRadius;

		private ConfigEntry<bool>? _autoGravePriority;

		private ConfigEntry<bool>? _removeDeathPinOnRetrieval;

		private ConfigEntry<bool>? _removeDeathPinOnEmptyDeath;

		private ConfigEntry<int>? _maxWaypoints;

		private ConfigEntry<bool>? _debugLogging;

		private ConfigEntry<bool>? _writeDebugLogFile;

		private ConfigEntry<bool>? _logRawMapInputs;

		private ConfigEntry<string>? _addWaypointKbm;

		private ConfigEntry<string>? _addWaypointGamepad;

		private ConfigEntry<string>? _focusPanelKbm;

		private ConfigEntry<string>? _focusPanelGamepad;

		private RavenHudConfig? _hudConfig;

		private void Awake()
		{
			//IL_0102: Unknown result type (might be due to invalid IL or missing references)
			//IL_010c: Expected O, but got Unknown
			//IL_01bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c5: Expected O, but got Unknown
			BindConfig();
			_diagnosticLogger = new DiagnosticLogger(((BaseUnityPlugin)this).Logger, "RavenRoute", "ravenroute-debug.log", _debugLogging, _writeDebugLogFile);
			_diagnosticLogger.Info("RavenRoute v1.0.0 initializing (Segment 3: In-World Wingtip HUD).");
			_diagnosticLogger.Debug("Diagnostic file path: " + _diagnosticLogger.LogFilePath);
			_configReloader = new ConfigFileReloader(((BaseUnityPlugin)this).Config, _diagnosticLogger);
			_routeStorage = new RouteStorage("RavenRoute", _saveRoutePerCharacter, _diagnosticLogger);
			_routeController = new RouteController(_routeStorage, _diagnosticLogger, _saveRoutePerCharacter, _arrivalRadius, _autoGravePriority, _removeDeathPinOnRetrieval, _removeDeathPinOnEmptyDeath, _maxWaypoints);
			_maxWaypoints = ((BaseUnityPlugin)this).Config.Bind<int>("Navigation", "MaxWaypoints", 10, new ConfigDescription("Maximum number of user-added waypoints allowed in the queue (1 - 10). Grave waypoints and manual JSON edits can exceed this limit.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 10), Array.Empty<object>()));
			GravePatches.Bind(_routeController, _diagnosticLogger, () => _enabled != null && _enabled.Value);
			DualInputBinding addWaypointBinding = new DualInputBinding("AddWaypoint", _addWaypointKbm, _addWaypointGamepad, _diagnosticLogger);
			DualInputBinding focusPanelBinding = new DualInputBinding("FocusPanel", _focusPanelKbm, _focusPanelGamepad, _diagnosticLogger);
			_mapInputController = new LargeMapInputController(_diagnosticLogger, _logRawMapInputs, addWaypointBinding, focusPanelBinding);
			_mapInputController.AddWaypointRequested += OnAddWaypointRequested;
			MapPingSuppressionPatch.Bind(_mapInputController, _diagnosticLogger, () => _enabled != null && _enabled.Value);
			try
			{
				_harmony = new Harmony("com.MyrkForge.ravenroute");
				_harmony.PatchAll(typeof(Plugin).Assembly);
				MapFocusInputPatch.Apply(_harmony, _diagnosticLogger);
				_diagnosticLogger.Debug("Harmony patches applied cleanly.");
			}
			catch (Exception ex)
			{
				_diagnosticLogger.Error("Failed applying Harmony patches!", ex);
			}
			_hudRenderer = new RavenHudRenderer(_routeController, _hudConfig, _diagnosticLogger);
			_toggleHudBinding = new DualInputBinding("ToggleHud", _toggleHudKbm, _toggleHudGamepad, _diagnosticLogger);
			DualInputBinding navigateUpBinding = TrackPanelBinding(new DualInputBinding("PanelNavigateUp", _navUpKbm, _navUpGamepad, _diagnosticLogger));
			DualInputBinding navigateDownBinding = TrackPanelBinding(new DualInputBinding("PanelNavigateDown", _navDownKbm, _navDownGamepad, _diagnosticLogger));
			DualInputBinding jumpToStopBinding = TrackPanelBinding(new DualInputBinding("PanelJumpToStop", _jumpStopKbm, _jumpStopGamepad, _diagnosticLogger));
			DualInputBinding moveUpBinding = TrackPanelBinding(new DualInputBinding("PanelMoveUp", _moveUpKbm, _moveUpGamepad, _diagnosticLogger));
			DualInputBinding moveDownBinding = TrackPanelBinding(new DualInputBinding("PanelMoveDown", _moveDownKbm, _moveDownGamepad, _diagnosticLogger));
			DualInputBinding removeStopBinding = TrackPanelBinding(new DualInputBinding("PanelRemoveStop", _removeStopKbm, _removeStopGamepad, _diagnosticLogger));
			DualInputBinding clearRouteBinding = TrackPanelBinding(new DualInputBinding("PanelClearRoute", _clearRouteKbm, _clearRouteGamepad, _diagnosticLogger));
			DualInputBinding unfocusPanelBinding = TrackPanelBinding(new DualInputBinding("PanelUnfocus", _unfocusPanelKbm, _unfocusPanelGamepad, _diagnosticLogger));
			LargeMapRoutePanelConfig config = new LargeMapRoutePanelConfig
			{
				ShowRoutePanel = _showRoutePanel,
				ShowMapKeyGuides = _showMapKeyGuides,
				PanelSide = _panelSide,
				PanelScale = _panelScale,
				AddWaypointBinding = _mapInputController.AddWaypointBinding,
				FocusPanelBinding = _mapInputController.FocusPanelBinding,
				NavigateUpBinding = navigateUpBinding,
				NavigateDownBinding = navigateDownBinding,
				JumpToStopBinding = jumpToStopBinding,
				MoveUpBinding = moveUpBinding,
				MoveDownBinding = moveDownBinding,
				RemoveStopBinding = removeStopBinding,
				ClearRouteBinding = clearRouteBinding,
				UnfocusPanelBinding = unfocusPanelBinding
			};
			_routePanel = new LargeMapRoutePanel(_routeController, config, _diagnosticLogger);
			_mapPinManager = new RavenMapPinManager(_routeController, _diagnosticLogger);
			_mapInputController.FocusPanelRequested += OnFocusPanelRequested;
			_mapInputController.AttachPanelGuard(() => _routePanel != null && _routePanel.IsFocused, (Vector3 pos) => _routePanel != null && _routePanel.IsScreenPointOverPanel(pos));
			MapFocusInputPatch.Bind(() => _enabled != null && _enabled.Value && _routePanel != null && _routePanel.IsFocused, () => _enabled != null && _enabled.Value && _routePanel != null && _routePanel.HandlePreMinimapUpdate());
			_diagnosticLogger.Info("RavenRoute v1.0.0 ready.");
		}

		private void Update()
		{
			_configReloader?.Tick();
			if (_enabled == null || !_enabled.Value)
			{
				_hudRenderer?.ForceHide();
				_routePanel?.ForceHide();
				_mapPinManager?.ClearAllPins();
				return;
			}
			_routeController?.Tick();
			_mapInputController?.Tick();
			PollHudToggleBinding();
			_hudRenderer?.Tick();
			_routePanel?.Tick();
			_mapPinManager?.Tick();
		}

		private DualInputBinding TrackPanelBinding(DualInputBinding binding)
		{
			_panelBindings.Add(binding);
			return binding;
		}

		private void OnFocusPanelRequested()
		{
			_routePanel?.ToggleFocus();
		}

		private void OnDestroy()
		{
			_toggleHudBinding?.Dispose();
			_toggleHudBinding = null;
			_hudRenderer?.Dispose();
			_hudRenderer = null;
			MapPingSuppressionPatch.Unbind();
			_configReloader = null;
			MapFocusInputPatch.Unbind();
			if (_mapInputController != null)
			{
				_mapInputController.AddWaypointRequested -= OnAddWaypointRequested;
				_mapInputController.Dispose();
				_mapInputController = null;
			}
			_routePanel?.Dispose();
			_routePanel = null;
			for (int i = 0; i < _panelBindings.Count; i++)
			{
				_panelBindings[i].Dispose();
			}
			_panelBindings.Clear();
			GravePatches.Unbind();
			_mapPinManager?.Dispose();
			_mapPinManager = null;
			_routeController?.Dispose();
			_routeController = null;
			_routeStorage = null;
			_diagnosticLogger?.Info("RavenRoute shutting down.");
			_diagnosticLogger?.Dispose();
			_diagnosticLogger = null;
			Harmony? harmony = _harmony;
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
			_harmony = null;
		}

		private void OnAddWaypointRequested(Vector3 worldPos, string? pinName)
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			_routeController?.AppendStop(worldPos, pinName);
		}

		private void PollHudToggleBinding()
		{
			if (_toggleHudBinding != null && _hudConfig != null && !IsGlobalTextInputActive() && _toggleHudBinding.IsTriggered(out string matchedScheme, out string matchedChord))
			{
				bool flag = !_hudConfig.ShowHud.Value;
				_hudConfig.ShowHud.Value = flag;
				_configReloader?.SyncWriteTime();
				_diagnosticLogger?.Info($"[HUD] Toggled ShowHud -> {flag} | Scheme={matchedScheme} | Chord='{matchedChord}'");
			}
		}

		private static bool IsGlobalTextInputActive()
		{
			if (TextInput.IsVisible() || Minimap.InTextInput() || Console.IsVisible())
			{
				return true;
			}
			if ((Object)(object)Chat.instance != (Object)null)
			{
				return Chat.instance.IsChatDialogWindowVisible();
			}
			return false;
		}

		private void BindConfig()
		{
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Expected O, but got Unknown
			//IL_01aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b4: Expected O, but got Unknown
			//IL_01e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f2: Expected O, but got Unknown
			//IL_049d: Unknown result type (might be due to invalid IL or missing references)
			//IL_04a7: Expected O, but got Unknown
			//IL_0574: Unknown result type (might be due to invalid IL or missing references)
			//IL_057e: Expected O, but got Unknown
			//IL_05b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_05bc: Expected O, but got Unknown
			//IL_05f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_05fa: Expected O, but got Unknown
			//IL_062e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0638: Expected O, but got Unknown
			//IL_0663: Unknown result type (might be due to invalid IL or missing references)
			//IL_066d: Expected O, but got Unknown
			//IL_0697: Unknown result type (might be due to invalid IL or missing references)
			//IL_06a1: Expected O, but got Unknown
			//IL_06cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_06d5: Expected O, but got Unknown
			//IL_06fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_0708: Expected O, but got Unknown
			//IL_0731: Unknown result type (might be due to invalid IL or missing references)
			//IL_073b: Expected O, but got Unknown
			_enabled = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "Master toggle for RavenRoute.");
			_saveRoutePerCharacter = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "SaveRoutePerCharacter", true, "Save queues per world + character (true) or shared per world only (false).");
			_arrivalRadius = ((BaseUnityPlugin)this).Config.Bind<float>("Navigation", "ArrivalRadius", 10f, new ConfigDescription("Horizontal distance in meters (X, Z) required to auto-advance to the next stop.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 100f), Array.Empty<object>()));
			_autoGravePriority = ((BaseUnityPlugin)this).Config.Bind<bool>("Navigation", "AutoGravePriority", true, "Automatically insert tombstone location at index 0 upon death.");
			_removeDeathPinOnRetrieval = ((BaseUnityPlugin)this).Config.Bind<bool>("Navigation", "RemoveDeathPinOnRetrieval", true, "Remove the vanilla death skull pin when your grave is looted/retrieved.");
			_removeDeathPinOnEmptyDeath = ((BaseUnityPlugin)this).Config.Bind<bool>("Navigation", "RemoveDeathPinOnEmptyDeath", true, "Remove the vanilla death skull pin when you die and no tombstone is created.");
			_toggleHudKbm = ((BaseUnityPlugin)this).Config.Bind<string>("Controls.HUD", "ToggleHudKeyboardMouse", "None", "Optional Keyboard/Mouse key or chord to toggle RavenRoute's HUD visibility (e.g. 'LeftAlt + H'). Set to 'None' to disable.");
			_toggleHudGamepad = ((BaseUnityPlugin)this).Config.Bind<string>("Controls.HUD", "ToggleHudGamepad", "None", "Optional Gamepad button or chord to toggle RavenRoute's HUD visibility (e.g. 'JoyLTrigger + JoyDPadDown'). Set to 'None' to disable.");
			_showRoutePanel = ((BaseUnityPlugin)this).Config.Bind<bool>("MapPanel", "ShowRoutePanel", true, "Display the docked RavenRoute queue panel while the Large Map is open.");
			_showMapKeyGuides = ((BaseUnityPlugin)this).Config.Bind<bool>("MapPanel", "ShowMapKeyGuides", true, "Display dynamic control hints at the bottom of the Large Map.");
			_panelSide = ((BaseUnityPlugin)this).Config.Bind<string>("MapPanel", "PanelSide", "Left", new ConfigDescription("Which side of the Large Map to dock the route panel.", (AcceptableValueBase)(object)new AcceptableValueList<string>(new string[2] { "Left", "Right" }), Array.Empty<object>()));
			_panelScale = ((BaseUnityPlugin)this).Config.Bind<float>("MapPanel", "PanelScale", 1f, new ConfigDescription("Scale multiplier for the docked Large Map route panel and bottom guide bar.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.6f, 1.8f), Array.Empty<object>()));
			_navUpKbm = ((BaseUnityPlugin)this).Config.Bind<string>("Controls.RoutePanel", "NavigateUpKeyboardMouse", "UpArrow", "Select previous stop while the route panel is focused.");
			_navUpGamepad = ((BaseUnityPlugin)this).Config.Bind<string>("Controls.RoutePanel", "NavigateUpGamepad", "JoyDPadUp", "Select previous stop on gamepad while focused.");
			_navDownKbm = ((BaseUnityPlugin)this).Config.Bind<string>("Controls.RoutePanel", "NavigateDownKeyboardMouse", "DownArrow", "Select next stop while the route panel is focused.");
			_navDownGamepad = ((BaseUnityPlugin)this).Config.Bind<string>("Controls.RoutePanel", "NavigateDownGamepad", "JoyDPadDown", "Select next stop on gamepad while focused.");
			_jumpStopKbm = ((BaseUnityPlugin)this).Config.Bind<string>("Controls.RoutePanel", "JumpToStopKeyboardMouse", "Return", "Promote selected stop to active target #0 while focused.");
			_jumpStopGamepad = ((BaseUnityPlugin)this).Config.Bind<string>("Controls.RoutePanel", "JumpToStopGamepad", "JoyButtonA", "Promote selected stop to active target #0 on gamepad while focused.");
			_moveUpKbm = ((BaseUnityPlugin)this).Config.Bind<string>("Controls.RoutePanel", "MoveUpKeyboardMouse", "LeftArrow", "Move selected stop one slot earlier while focused.");
			_moveUpGamepad = ((BaseUnityPlugin)this).Config.Bind<string>("Controls.RoutePanel", "MoveUpGamepad", "JoyDPadLeft", "Move selected stop one slot earlier on gamepad while focused.");
			_moveDownKbm = ((BaseUnityPlugin)this).Config.Bind<string>("Controls.RoutePanel", "MoveDownKeyboardMouse", "RightArrow", "Move selected stop one slot later while focused.");
			_moveDownGamepad = ((BaseUnityPlugin)this).Config.Bind<string>("Controls.RoutePanel", "MoveDownGamepad", "JoyDPadRight", "Move selected stop one slot later on gamepad while focused.");
			_removeStopKbm = ((BaseUnityPlugin)this).Config.Bind<string>("Controls.RoutePanel", "RemoveStopKeyboardMouse", "Delete", "Delete selected stop while focused.");
			_removeStopGamepad = ((BaseUnityPlugin)this).Config.Bind<string>("Controls.RoutePanel", "RemoveStopGamepad", "JoyButtonX", "Delete selected stop on gamepad while focused.");
			_clearRouteKbm = ((BaseUnityPlugin)this).Config.Bind<string>("Controls.RoutePanel", "ClearRouteKeyboardMouse", "LeftShift + Delete", "Clear all stops while focused.");
			_clearRouteGamepad = ((BaseUnityPlugin)this).Config.Bind<string>("Controls.RoutePanel", "ClearRouteGamepad", "JoyButtonY", "Clear all stops on gamepad while focused.");
			_unfocusPanelKbm = ((BaseUnityPlugin)this).Config.Bind<string>("Controls.RoutePanel", "UnfocusPanelKeyboardMouse", "Escape", "Exit panel focus back to the Large Map without closing the map.");
			_unfocusPanelGamepad = ((BaseUnityPlugin)this).Config.Bind<string>("Controls.RoutePanel", "UnfocusPanelGamepad", "JoyButtonB", "Exit panel focus on gamepad without closing the map.");
			_hudConfig = new RavenHudConfig
			{
				PlayArrivalSound = ((BaseUnityPlugin)this).Config.Bind<bool>("Audio", "PlayArrivalSound", false, "Play a subtle audio cue when reaching a waypoint."),
				ArrivalSoundVolume = ((BaseUnityPlugin)this).Config.Bind<float>("Audio", "ArrivalSoundVolume", 0.5f, new ConfigDescription("Volume multiplier (0.0 - 1.0) for the arrival cue.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>())),
				ShowHud = ((BaseUnityPlugin)this).Config.Bind<bool>("HUD.Layout", "ShowHud", true, "Show the in-world directional pointer and queue when no menus are open."),
				ShowPointer = ((BaseUnityPlugin)this).Config.Bind<bool>("HUD.Layout", "ShowPointer", true, "Toggle the raven wingtip directional pointer."),
				ShowDistance = ((BaseUnityPlugin)this).Config.Bind<bool>("HUD.Layout", "ShowDistance", true, "Toggle live meter distance readout on the active target and upcoming stops."),
				ShowDestinationName = ((BaseUnityPlugin)this).Config.Bind<bool>("HUD.Layout", "ShowDestinationName", true, "Toggle destination label on the active target and upcoming stops."),
				ShowWaypointIcon = ((BaseUnityPlugin)this).Config.Bind<bool>("HUD.Layout", "ShowWaypointIcon", false, "Optional toggle to display a small waypoint icon next to the active destination."),
				UpcomingStopsCount = ((BaseUnityPlugin)this).Config.Bind<int>("HUD.Layout", "UpcomingStopsCount", 3, new ConfigDescription("Number of upcoming stops (0 - 5) displayed beneath the active target.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 5), Array.Empty<object>())),
				HudPositionX = ((BaseUnityPlugin)this).Config.Bind<float>("HUD.Layout", "HudPositionX", 0.5f, new ConfigDescription("Horizontal screen position (0.0 left - 1.0 right) for the entire HUD block.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>())),
				HudPositionY = ((BaseUnityPlugin)this).Config.Bind<float>("HUD.Layout", "HudPositionY", 0.9f, new ConfigDescription("Vertical screen position (0.0 bottom - 1.0 top) for the entire HUD block.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>())),
				HudScale = ((BaseUnityPlugin)this).Config.Bind<float>("HUD.Layout", "HudScale", 1f, new ConfigDescription("Global scale multiplier for the HUD block.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.5f, 2.5f), Array.Empty<object>())),
				PointerSize = ((BaseUnityPlugin)this).Config.Bind<int>("HUD.Layout", "PointerSize", 26, new ConfigDescription("Size in pixels of the raven wingtip pointer.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(12, 96), Array.Empty<object>())),
				PrimaryFontSize = ((BaseUnityPlugin)this).Config.Bind<int>("HUD.Layout", "PrimaryFontSize", 14, new ConfigDescription("Font size in points for the active distance and destination row.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(8, 36), Array.Empty<object>())),
				QueueFontSize = ((BaseUnityPlugin)this).Config.Bind<int>("HUD.Layout", "QueueFontSize", 12, new ConfigDescription("Font size in points for the upcoming queued stops.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(8, 28), Array.Empty<object>())),
				RowSpacing = ((BaseUnityPlugin)this).Config.Bind<int>("HUD.Layout", "RowSpacing", 4, new ConfigDescription("Vertical pixel spacing between pointer, active row, and queued rows.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 24), Array.Empty<object>())),
				ColumnSpacing = ((BaseUnityPlugin)this).Config.Bind<int>("HUD.Layout", "ColumnSpacing", 8, new ConfigDescription("Horizontal pixel spacing between distance and destination name.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 32), Array.Empty<object>())),
				PointerFillColor = ((BaseUnityPlugin)this).Config.Bind<string>("HUD.Colors", "PointerFillColor", "#FFFFFFFF", "Hex RGBA color for the wingtip pointer interior (default: White)."),
				PointerOutlineColor = ((BaseUnityPlugin)this).Config.Bind<string>("HUD.Colors", "PointerOutlineColor", "#E5B84BFF", "Hex RGBA color for the wingtip pointer border (default: Valheim Gold)."),
				PrimaryTextColor = ((BaseUnityPlugin)this).Config.Bind<string>("HUD.Colors", "PrimaryTextColor", "#FFFFFFFF", "Hex RGBA color for the active target text."),
				QueueTextColor = ((BaseUnityPlugin)this).Config.Bind<string>("HUD.Colors", "QueueTextColor", "#FFFFFFCC", "Hex RGBA color for the upcoming stops list."),
				ShowHudBackdrop = ((BaseUnityPlugin)this).Config.Bind<bool>("HUD.Colors", "ShowHudBackdrop", false, "Draw a translucent background panel behind the HUD stack."),
				BackdropColor = ((BaseUnityPlugin)this).Config.Bind<string>("HUD.Colors", "BackdropColor", "#14110EB3", "Hex RGBA color and transparency for the optional HUD backdrop.")
			};
			_debugLogging = ((BaseUnityPlugin)this).Config.Bind<bool>("Diagnostics", "DebugLogging", false, "Emit verbose diagnostic events (Large Map transitions, reflection probes, queue snapshots, HUD visibility).");
			_writeDebugLogFile = ((BaseUnityPlugin)this).Config.Bind<bool>("Diagnostics", "WriteDebugLogFile", false, "Mirror RavenRoute log lines to BepInEx/config/RavenRoute/ravenroute-debug.log.");
			_logRawMapInputs = ((BaseUnityPlugin)this).Config.Bind<bool>("Diagnostics", "LogRawMapInputs", false, "Diagnostic probe: log raw ZInput gamepad buttons and KeyCode presses while the Large Map is open.");
			_addWaypointKbm = ((BaseUnityPlugin)this).Config.Bind<string>("Controls.LargeMap", "AddWaypointKeyboardMouse", "LeftShift + Mouse2", "Keyboard/Mouse chord in Large Map mode to add cursor coordinate to the waypoint queue. Use 'None' to disable.");
			_addWaypointGamepad = ((BaseUnityPlugin)this).Config.Bind<string>("Controls.LargeMap", "AddWaypointGamepad", "JoyLStick + JoyButtonX", "Gamepad chord in Large Map mode to add cursor coordinate to the waypoint queue. Supports ZInput names or Unity KeyCode.");
			_focusPanelKbm = ((BaseUnityPlugin)this).Config.Bind<string>("Controls.LargeMap", "FocusPanelKeyboardMouse", "None", "Optional Keyboard/Mouse binding to focus the route panel for keyboard navigation. Mouse clicks on ▲/▼/X/Clear always work without focusing.");
			_focusPanelGamepad = ((BaseUnityPlugin)this).Config.Bind<string>("Controls.LargeMap", "FocusPanelGamepad", "JoyRStick", "Gamepad binding in Large Map mode to toggle focus on the docked route panel (default: R3 / JoyRStick).");
		}
	}
}
namespace RavenRoute.UI
{
	public sealed class LargeMapRoutePanelConfig
	{
		public ConfigEntry<bool> ShowRoutePanel { get; set; }

		public ConfigEntry<bool> ShowMapKeyGuides { get; set; }

		public ConfigEntry<string> PanelSide { get; set; }

		public ConfigEntry<float> PanelScale { get; set; }

		public DualInputBinding AddWaypointBinding { get; set; }

		public DualInputBinding FocusPanelBinding { get; set; }

		public DualInputBinding NavigateUpBinding { get; set; }

		public DualInputBinding NavigateDownBinding { get; set; }

		public DualInputBinding JumpToStopBinding { get; set; }

		public DualInputBinding MoveUpBinding { get; set; }

		public DualInputBinding MoveDownBinding { get; set; }

		public DualInputBinding RemoveStopBinding { get; set; }

		public DualInputBinding ClearRouteBinding { get; set; }

		public DualInputBinding UnfocusPanelBinding { get; set; }
	}
	public sealed class LargeMapRoutePanel : IDisposable
	{
		private sealed class RowView
		{
			public GameObject Root;

			public Text? DistanceText;

			public int LastDistMeters = int.MinValue;
		}

		private const float MinCollapsedWidth = 136f;

		private const float DefaultCollapsedWidth = 172f;

		private const float ExpandedWidth = 318f;

		private const float EdgeMargin = 10f;

		private const float PanelMaxHeight = 460f;

		private const float DoubleClickWindowSeconds = 0.35f;

		private static readonly Color PanelBgColor = new Color(0.08f, 0.07f, 0.06f, 0.9f);

		private static readonly Color BorderUnfocusedColor = new Color(0.38f, 0.31f, 0.22f, 0.85f);

		private static readonly Color BorderFocusedColor = new Color(0.9f, 0.72f, 0.29f, 1f);

		private static readonly Color GoldColor = new Color(0.9f, 0.72f, 0.29f, 1f);

		private static readonly Color GraveColor = new Color(0.95f, 0.45f, 0.35f, 1f);

		private static readonly Color RowEvenColor = new Color(0.14f, 0.12f, 0.1f, 0.74f);

		private static readonly Color RowOddColor = new Color(0.11f, 0.09f, 0.08f, 0.74f);

		private static readonly Color RowSelectedColor = new Color(0.36f, 0.28f, 0.14f, 0.92f);

		private static readonly Color RowHoverColor = new Color(0.24f, 0.2f, 0.14f, 0.85f);

		private static readonly Color ToggleBtnNormal = new Color(0.3f, 0.24f, 0.14f, 0.95f);

		private static readonly Color ToggleBtnHover = new Color(0.46f, 0.36f, 0.2f, 1f);

		private static readonly Color ToggleBtnPressed = new Color(0.6f, 0.47f, 0.24f, 1f);

		private static readonly Color ActionBtnNormal = new Color(0.22f, 0.19f, 0.15f, 0.92f);

		private static readonly Color ActionBtnHover = new Color(0.36f, 0.3f, 0.21f, 1f);

		private static readonly Color ActionBtnPressed = new Color(0.5f, 0.4f, 0.24f, 1f);

		private static readonly Color ActionBtnDisabled = new Color(0.15f, 0.13f, 0.11f, 0.4f);

		private static readonly Color DangerBtnNormal = new Color(0.45f, 0.15f, 0.13f, 0.92f);

		private static readonly Color DangerBtnHover = new Color(0.65f, 0.2f, 0.17f, 1f);

		private static readonly Color DangerBtnPressed = new Color(0.78f, 0.25f, 0.2f, 1f);

		private readonly RouteController _routeController;

		private readonly LargeMapRoutePanelConfig _cfg;

		private readonly DiagnosticLogger _logger;

		private readonly List<(ConfigEntryBase Entry, EventHandler Handler)> _watchedConfigs = new List<(ConfigEntryBase, EventHandler)>();

		private readonly DualInputBinding[] _allBindings;

		private Canvas? _canvas;

		private Font? _uiFont;

		private Texture2D? _roundedTex;

		private Sprite? _roundedSprite;

		private GameObject? _panelRoot;

		private RectTransform? _panelRect;

		private Image? _panelBorderImage;

		private Text? _headerTitleText;

		private Text? _focusBadgeText;

		private Button? _clearButton;

		private Button? _drawerToggleButton;

		private Text? _drawerToggleLabel;

		private ScrollRect? _scrollRect;

		private RectTransform? _listContentRect;

		private Text? _emptyStateText;

		private PromptGuideBar? _promptBar;

		private readonly List<RowView> _rowViews = new List<RowView>();

		private bool _mapImageProbed;

		private FieldInfo? _mapImageLargeField;

		private readonly Vector3[] _mapWorldCorners = (Vector3[])(object)new Vector3[4];

		private int _lastScreenWidth;

		private int _lastScreenHeight;

		private bool _loggedLayoutMetrics;

		private bool _isMapOpen;

		private bool _isExpanded;

		private bool _isFocused;

		private bool _lastGamepadActive;

		private int _selectedIndex;

		private int _lastProcessedFrame = -1;

		private int _consumedMapCloseFrame = -1;

		private int _lastClickedRow = -1;

		private float _lastRowClickTime = -10f;

		private bool _styleDirty = true;

		private bool _rowsDirty = true;

		private bool _promptsDirty = true;

		private bool _disposed;

		public bool IsFocused
		{
			get
			{
				//IL_0029: Unknown result type (might be due to invalid IL or missing references)
				//IL_002f: Invalid comparison between Unknown and I4
				if (_isMapOpen && _isFocused && (Object)(object)Minimap.instance != (Object)null && Minimap.IsOpen())
				{
					return (int)Minimap.instance.m_mode == 2;
				}
				return false;
			}
		}

		public LargeMapRoutePanel(RouteController routeController, LargeMapRoutePanelConfig config, DiagnosticLogger logger)
		{
			_routeController = routeController;
			_cfg = config;
			_logger = logger;
			_allBindings = new DualInputBinding[10] { _cfg.AddWaypointBinding, _cfg.FocusPanelBinding, _cfg.NavigateUpBinding, _cfg.NavigateDownBinding, _cfg.JumpToStopBinding, _cfg.MoveUpBinding, _cfg.MoveDownBinding, _cfg.RemoveStopBinding, _cfg.ClearRouteBinding, _cfg.UnfocusPanelBinding };
			_routeController.RouteChanged += OnRouteChanged;
			SubscribeListeners();
		}

		public void ToggleFocus()
		{
			if (_isMapOpen && _cfg.ShowRoutePanel.Value)
			{
				bool flag = !_isFocused;
				SetDrawerState(flag, flag, "FocusPanelBinding");
				MapFocusInputPatch.SuppressThroughFrame(Time.frameCount);
				MapFocusInputPatch.TryResetZInputButton("JoyRStick");
			}
		}

		public bool IsScreenPointOverPanel(Vector3 screenPos)
		{
			//IL_0039: 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)
			if (!_isMapOpen || (Object)(object)_panelRoot == (Object)null || !_panelRoot.activeInHierarchy || (Object)(object)_panelRect == (Object)null)
			{
				return false;
			}
			return RectTransformUtility.RectangleContainsScreenPoint(_panelRect, Vector2.op_Implicit(screenPos), (Camera)null);
		}

		public bool HandlePreMinimapUpdate()
		{
			if (Time.frameCount == _lastProcessedFrame)
			{
				return Time.frameCount == _consumedMapCloseFrame;
			}
			_lastProcessedFrame = Time.frameCount;
			TickInternal();
			return Time.frameCount == _consumedMapCloseFrame;
		}

		public void Tick()
		{
			if (Time.frameCount != _lastProcessedFrame)
			{
				_lastProcessedFrame = Time.frameCount;
				TickInternal();
			}
		}

		public void ForceHide()
		{
			SetDrawerState(expanded: false, focused: false, "ModDisabled");
			_isMapOpen = false;
			if ((Object)(object)_panelRoot != (Object)null)
			{
				_panelRoot.SetActive(false);
			}
			_promptBar?.SetVisible(visible: false);
		}

		private void TickInternal()
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Invalid comparison between Unknown and I4
			Minimap instance = Minimap.instance;
			if (!((Object)(object)instance != (Object)null) || !Minimap.IsOpen() || (int)instance.m_mode != 2)
			{
				if (_isMapOpen)
				{
					_isMapOpen = false;
					SetDrawerState(expanded: false, focused: false, "LargeMapClosed");
					if ((Object)(object)_panelRoot != (Object)null)
					{
						_panelRoot.SetActive(false);
					}
					_promptBar?.SetVisible(visible: false);
				}
				return;
			}
			bool num = !_isMapOpen;
			_isMapOpen = true;
			EnsureUiBuilt();
			bool flag = Screen.width != _lastScreenWidth || Screen.height != _lastScreenHeight;
			if (num || flag)
			{
				_lastScreenWidth = Screen.width;
				_lastScreenHeight = Screen.height;
				_styleDirty = true;
			}
			bool flag2 = ZInput.instance != null && ZInput.IsGamepadActive();
			if (num || flag2 != _lastGamepadActive)
			{
				_lastGamepadActive = flag2;
				_promptsDirty = true;
				_rowsDirty = true;
			}
			if (_styleDirty)
			{
				ApplyPanelStyle(instance);
			}
			bool value = _cfg.ShowRoutePanel.Value;
			if ((Object)(object)_panelRoot != (Object)null && _panelRoot.activeSelf != value)
			{
				_panelRoot.SetActive(value);
			}
			if (!value && (_isFocused || _isExpanded))
			{
				SetDrawerState(expanded: false, focused: false, "ShowRoutePanel=false");
			}
			bool value2 = _cfg.ShowMapKeyGuides.Value;
			_promptBar?.SetVisible(value2);
			if (_isFocused && !IsTextEntryActive())
			{
				PollFocusedPanelControls();
			}
			if (_rowsDirty)
			{
				RebuildRows();
			}
			if (_promptsDirty && value2)
			{
				RebuildPromptBar();
			}
			if (value && _isExpanded)
			{
				UpdateLiveDistances();
			}
		}

		private void PollFocusedPanelControls()
		{
			MapFocusInputPatch.IsModPolling = true;
			try
			{
				if (_cfg.UnfocusPanelBinding.IsTriggered(out string matchedScheme, out string matchedChord))
				{
					_logger.Debug("[MapPanel] Unfocus triggered (" + matchedScheme + ": '" + matchedChord + "').");
					SetDrawerState(expanded: false, focused: false, "UnfocusBinding");
					_consumedMapCloseFrame = Time.frameCount;
					MapFocusInputPatch.SuppressThroughFrame(Time.frameCount);
					MapFocusInputPatch.TryResetZInputButton("JoyButtonB");
					return;
				}
				int count = _routeController.Count;
				if (count == 0)
				{
					return;
				}
				ClampSelectedIndex();
				string matchedScheme3;
				string matchedChord3;
				string matchedScheme4;
				string matchedChord4;
				string matchedScheme5;
				string matchedChord5;
				if (_cfg.ClearRouteBinding.IsTriggered(out string matchedScheme2, out string matchedChord2))
				{
					_logger.Info("[MapPanel] ClearRoute via " + matchedScheme2 + " ('" + matchedChord2 + "').");
					_routeController.Clear();
				}
				else if (_cfg.NavigateUpBinding.IsTriggered(out matchedScheme3, out matchedChord3))
				{
					if (_selectedIndex > 0)
					{
						_selectedIndex--;
						_rowsDirty = true;
						ScrollSelectedRowIntoView();
					}
				}
				else if (_cfg.NavigateDownBinding.IsTriggered(out matchedChord3, out matchedScheme3))
				{
					if (_selectedIndex < count - 1)
					{
						_selectedIndex++;
						_rowsDirty = true;
						ScrollSelectedRowIntoView();
					}
				}
				else if (_cfg.JumpToStopBinding.IsTriggered(out matchedScheme4, out matchedChord4))
				{
					if (_selectedIndex > 0 && _routeController.JumpTo(_selectedIndex))
					{
						_logger.Debug($"[MapPanel] JumpTo index {_selectedIndex} via {matchedScheme4} ('{matchedChord4}').");
						_selectedIndex = 0;
						ScrollSelectedRowIntoView();
					}
				}
				else if (_cfg.MoveUpBinding.IsTriggered(out matchedScheme3, out matchedChord3))
				{
					if (_selectedIndex > 0 && _routeController.MoveUp(_selectedIndex))
					{
						_selectedIndex--;
						ScrollSelectedRowIntoView();
					}
				}
				else if (_cfg.MoveDownBinding.IsTriggered(out matchedChord3, out matchedScheme3))
				{
					if (_selectedIndex < count - 1 && _routeController.MoveDown(_selectedIndex))
					{
						_selectedIndex++;
						ScrollSelectedRowIntoView();
					}
				}
				else if (_cfg.RemoveStopBinding.IsTriggered(out matchedScheme5, out matchedChord5))
				{
					_logger.Debug($"[MapPanel] RemoveAt index {_selectedIndex} via {matchedScheme5} ('{matchedChord5}').");
					_routeController.RemoveAt(_selectedIndex);
					ClampSelectedIndex();
				}
			}
			finally
			{
				MapFocusInputPatch.IsModPolling = false;
			}
		}

		private void ToggleExpandedFromMouse()
		{
			bool flag = !_isExpanded;
			bool focused = flag && _isFocused;
			SetDrawerState(flag, focused, "DrawerToggleClick");
		}

		private void SetDrawerState(bool expanded, bool focused, string reason)
		{
			if (_isExpanded != expanded || _isFocused != focused)
			{
				_isExpanded = expanded;
				_isFocused = focused;
				ClampSelectedIndex();
				_styleDirty = true;
				_rowsDirty = true;
				_promptsDirty = true;
				if (_isFocused && (Object)(object)EventSystem.current != (Object)null)
				{
					EventSystem.current.SetSelectedGameObject((GameObject)null);
				}
				_logger.Debug(string.Format("[MapPanel] Drawer -> {0} | Focus={1} ({2}) | SelectedIndex={3}", _isExpanded ? "EXPANDED" : "COLLAPSED", _isFocused ? "FOCUSED" : "UNFOCUSED", reason, _selectedIndex));
			}
		}

		private void EnsureUiBuilt()
		{
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Expected O, but got Unknown
			//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_010f: Unknown result type (might be due to invalid IL or missing references)
			//IL_013d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0143: Expected O, but got Unknown
			//IL_0161: Unknown result type (might be due to invalid IL or missing references)
			//IL_016c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0181: 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_01b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01de: Expected O, but got Unknown
			//IL_021c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0222: Expected O, but got Unknown
			//IL_0296: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0332: Unknown result type (might be due to invalid IL or missing references)
			//IL_0337: Unknown result type (might be due to invalid IL or missing references)
			//IL_033c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0341: Unknown result type (might be due to invalid IL or missing references)
			//IL_0346: Unknown result type (might be due to invalid IL or missing references)
			//IL_038a: Unknown result type (might be due to invalid IL or missing references)
			//IL_038f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0394: Unknown result type (might be due to invalid IL or missing references)
			//IL_0399: Unknown result type (might be due to invalid IL or missing references)
			//IL_039e: Unknown result type (might be due to invalid IL or missing references)
			//IL_03e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_03e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_03f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_042e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0456: Unknown result type (might be due to invalid IL or missing references)
			//IL_045c: Expected O, but got Unknown
			//IL_04a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_04d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_04da: Expected O, but got Unknown
			//IL_050a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0524: Unknown result type (might be due to invalid IL or missing references)
			//IL_053e: Unknown result type (might be due to invalid IL or missing references)
			//IL_054e: Unknown result type (might be due to invalid IL or missing references)
			//IL_055e: Unknown result type (might be due to invalid IL or missing references)
			//IL_057f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0589: Expected O, but got Unknown
			//IL_0642: Unknown result type (might be due to invalid IL or missing references)
			//IL_0660: Unknown result type (might be due to invalid IL or missing references)
			//IL_066b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0680: Unknown result type (might be due to invalid IL or missing references)
			//IL_0694: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)_canvas != (Object)null))
			{
				_uiFont = UiComponents.ResolveUiFont(out string fontName);
				_logger.Debug("[MapPanel] Building collapsible drawer overlay canvas | Font='" + fontName + "'");
				_canvas = UiComponents.CreateOverlayCanvas("RavenRoute_MapPanelCanvas", 500, interactive: true);
				_roundedTex = UiComponents.CreateRoundedRectTexture(32, 8);
				_roundedSprite = UiComponents.CreateSlicedSprite(_roundedTex, 8f);
				_panelRoot = new GameObject("DockedRouteDrawer", new Type[1] { typeof(RectTransform) });
				_panelRoot.transform.SetParent(((Component)_canvas).transform, false);
				_panelRect = _panelRoot.GetComponent<RectTransform>();
				_panelRect.sizeDelta = new Vector2(172f, 460f);
				_panelBorderImage = _panelRoot.AddComponent<Image>();
				_panelBorderImage.sprite = _roundedSprite;
				_panelBorderImage.type = (Type)1;
				((Graphic)_panelBorderImage).color = BorderUnfocusedColor;
				((Graphic)_panelBorderImage).raycastTarget = true;
				GameObject val = new GameObject("InnerBackdrop", new Type[1] { typeof(RectTransform) });
				val.transform.SetParent(_panelRoot.transform, false);
				RectTransform component = val.GetComponent<RectTransform>();
				component.anchorMin = Vector2.zero;
				component.anchorMax = Vector2.one;
				component.offsetMin = new Vector2(2f, 2f);
				component.offsetMax = new Vector2(-2f, -2f);
				Image obj = val.AddComponent<Image>();
				obj.sprite = _roundedSprite;
				obj.type = (Type)1;
				((Graphic)obj).color = PanelBgColor;
				((Graphic)obj).raycastTarget = true;
				VerticalLayoutGroup obj2 = val.AddComponent<VerticalLayoutGroup>();
				((LayoutGroup)obj2).padding = new RectOffset(8, 8, 8, 8);
				((HorizontalOrVerticalLayoutGroup)obj2).spacing = 6f;
				((HorizontalOrVerticalLayoutGroup)obj2).childControlWidth = true;
				((HorizontalOrVerticalLayoutGroup)obj2).childControlHeight = true;
				((HorizontalOrVerticalLayoutGroup)obj2).childForceExpandWidth = true;
				((HorizontalOrVerticalLayoutGroup)obj2).childForceExpandHeight = false;
				GameObject val2 = new GameObject("Header", new Type[1] { typeof(RectTransform) });
				val2.transform.SetParent(val.transform, false);
				LayoutElement obj3 = val2.AddComponent<LayoutElement>();
				obj3.minHeight = 26f;
				obj3.preferredHeight = 26f;
				HorizontalLayoutGroup obj4 = val2.AddComponent<HorizontalLayoutGroup>();
				((HorizontalOrVerticalLayoutGroup)obj4).spacing = 5f;
				((LayoutGroup)obj4).childAlignment = (TextAnchor)3;
				((HorizontalOrVerticalLayoutGroup)obj4).childControlWidth = true;
				((HorizontalOrVerticalLayoutGroup)obj4).childControlHeight = true;
				((HorizontalOrVerticalLayoutGroup)obj4).childForceExpandWidth = false;
				((HorizontalOrVerticalLayoutGroup)obj4).childForceExpandHeight = false;
				_headerTitleText = UiComponents.CreateShadowedText(val2.transform, "Title", _uiFont, 13, GoldColor, (TextAnchor)3, (FontStyle)1, (HorizontalWrapMode)1);
				((Component)_headerTitleText).gameObject.AddComponent<LayoutElement>().flexibleWidth = 1f;
				_focusBadgeText = UiComponents.CreateShadowedText(val2.transform, "FocusBadge", _uiFont, 10, GoldColor, (TextAnchor)5, (FontStyle)1, (HorizontalWrapMode)1);
				_focusBadgeText.text = "[ACTIVE]";
				((Component)_focusBadgeText).gameObject.SetActive(false);
				_clearButton = UiComponents.CreateActionButton(val2.transform, "ClearAllButton", _uiFont, "Clear", 11, 46f, 22f, _roundedSprite, DangerBtnNormal, DangerBtnHover, DangerBtnPressed, ActionBtnDisabled, Color.white, delegate
				{
					_logger.Info("[MapPanel] Clear button clicked.");
					_routeController.Clear();
				});
				_drawerToggleButton = UiComponents.CreateActionButton(val2.transform, "DrawerToggleButton", _uiFont, "»", 13, 24f, 22f, _roundedSprite, ToggleBtnNormal, ToggleBtnHover, ToggleBtnPressed, ActionBtnDisabled, GoldColor, ToggleExpandedFromMouse);
				_drawerToggleLabel = ((Component)_drawerToggleButton).GetComponentInChildren<Text>();
				GameObject val3 = new GameObject("Divider", new Type[1] { typeof(RectTransform) });
				val3.transform.SetParent(val.transform, false);
				LayoutElement obj5 = val3.AddComponent<LayoutElement>();
				obj5.minHeight = 1f;
				obj5.preferredHeight = 1f;
				Image obj6 = val3.AddComponent<Image>();
				((Graphic)obj6).color = new Color(0.9f, 0.72f, 0.29f, 0.35f);
				((Graphic)obj6).raycastTarget = false;
				GameObject val4 = new GameObject("ScrollViewport", new Type[1] { typeof(RectTransform) });
				val4.transform.SetParent(val.transform, false);
				LayoutElement obj7 = val4.AddComponent<LayoutElement>();
				obj7.flexibleHeight = 1f;
				obj7.minHeight = 80f;
				Image obj8 = val4.AddComponent<Image>();
				((Graphic)obj8).color = new Color(0f, 0f, 0f, 0.01f);
				((Graphic)obj8).raycastTarget = true;
				val4.AddComponent<RectMask2D>();
				GameObject val5 = new GameObject("RowContent", new Type[1] { typeof(RectTransform) });
				val5.transform.SetParent(val4.transform, false);
				_listContentRect = val5.GetComponent<RectTransform>();
				_listContentRect.anchorMin = new Vector2(0f, 1f);
				_listContentRect.anchorMax = new Vector2(1f, 1f);
				_listContentRect.pivot = new Vector2(0.5f, 1f);
				_listContentRect.anchoredPosition = Vector2.zero;
				_listContentRect.sizeDelta = Vector2.zero;
				VerticalLayoutGroup obj9 = val5.AddComponent<VerticalLayoutGroup>();
				((HorizontalOrVerticalLayoutGroup)obj9).spacing = 4f;
				((LayoutGroup)obj9).padding = new RectOffset(0, 0, 2, 2);
				((HorizontalOrVerticalLayoutGroup)obj9).childControlWidth = true;
				((HorizontalOrVerticalLayoutGroup)obj9).childControlHeight = true;
				((HorizontalOrVerticalLayoutGroup)obj9).childForceExpandWidth = true;
				((HorizontalOrVerticalLayoutGroup)obj9).childForceExpandHeight = false;
				ContentSizeFitter obj10 = val5.AddComponent<ContentSizeFitter>();
				obj10.horizontalFit = (FitMode)0;
				obj10.verticalFit = (FitMode)2;
				_scrollRect = val4.AddComponent<ScrollRect>();
				_scrollRect.content = _listContentRect;
				_scrollRect.viewport = val4.GetComponent<RectTransform>();
				_scrollRect.horizontal = false;
				_scrollRect.vertical = true;
				_scrollRect.movementType = (MovementType)2;
				_scrollRect.scrollSensitivity = 28f;
				_emptyStateText = UiComponents.CreateShadowedText(val4.transform, "EmptyStateText", _uiFont, 12, new Color(1f, 1f, 1f, 0.65f), (TextAnchor)4, (FontStyle)2, (HorizontalWrapMode)0);
				RectTransform rectTransform = ((Graphic)_emptyStateText).rectTransform;
				rectTransform.anchorMin = Vector2.zero;
				rectTransform.anchorMax = Vector2.one;
				rectTransform.offsetMin = new Vector2(8f, 8f);
				rectTransform.offsetMax = new Vector2(-8f, -8f);
				_promptBar = new PromptGuideBar(((Component)_canvas).transform, "RavenRoute_MapPromptBar", _uiFont, _roundedSprite, 18f);
				_panelRoot.SetActive(false);
				_promptBar.SetVisible(visible: false);
				_styleDirty = true;
				_rowsDirty = true;
				_promptsDirty = true;
			}
		}

		private void ApplyPanelStyle(Minimap minimap)
		{
			//IL_01d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0259: Unknown result type (might be due to invalid IL or missing references)
			//IL_0273: Unknown result type (might be due to invalid IL or missing references)
			//IL_028d: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_0209: Unknown result type (might be due to invalid IL or missing references)
			//IL_0223: Unknown result type (might be due to invalid IL or missing references)
			//IL_023d: Unknown result type (might be due to invalid IL or missing references)
			//IL_02be: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e8: Unknown result type (might be due to invalid IL or missing references)
			_styleDirty = false;
			if ((Object)(object)_panelRect == (Object)null || (Object)(object)_panelBorderImage == (Object)null)
			{
				return;
			}
			bool flag = string.Equals(_cfg.PanelSide.Value?.Trim(), "Right", StringComparison.OrdinalIgnoreCase);
			float num = Mathf.Clamp(_cfg.PanelScale.Value, 0.6f, 1.8f);
			float num2 = Mathf.Clamp(((float)Screen.height - 140f) / num, 240f, 460f);
			float num3 = 172f;
			if (TryMeasureLargeMapScreenBounds(minimap, out var mapLeftX, out var mapRightX, out var mapCanvasOrder))
			{
				if ((Object)(object)_canvas != (Object)null)
				{
					int num4 = Mathf.Max(500, mapCanvasOrder + 50);
					if (_canvas.sortingOrder != num4)
					{
						_canvas.sortingOrder = num4;
					}
				}
				float num5 = (flag ? ((float)Screen.width - mapRightX) : mapLeftX);
				num3 = Mathf.Clamp((num5 - 20f) / num, 136f, 172f);
				if (!_loggedLayoutMetrics)
				{
					_loggedLayoutMetrics = true;
					DiagnosticLogger logger = _logger;
					object[] obj = new object[9]
					{
						Screen.width,
						Screen.height,
						mapLeftX,
						mapRightX,
						num5,
						num3,
						318f,
						mapCanvasOrder,
						null
					};
					Canvas? canvas = _canvas;
					obj[8] = ((canvas != null) ? new int?(canvas.sortingOrder) : ((int?)null));
					logger.Debug(string.Format("[MapPanel] Drawer layout | Screen={0}x{1} | MapX=({2:F0}..{3:F0}) | Gutter={4:F0}px | CollapsedW={5:F0}px | ExpandedW={6:F0}px | MapOrder={7} | DrawerOrder={8}", obj));
				}
			}
			float num6 = (_isExpanded ? 318f : num3);
			_panelRect.sizeDelta = new Vector2(num6, num2);
			if (flag)
			{
				_panelRect.anchorMin = new Vector2(1f, 0.5f);
				_panelRect.anchorMax = new Vector2(1f, 0.5f);
				_panelRect.pivot = new Vector2(1f, 0.5f);
				_panelRect.anchoredPosition = new Vector2(-10f, 10f);
			}
			else
			{
				_panelRect.anchorMin = new Vector2(0f, 0.5f);
				_panelRect.anchorMax = new Vector2(0f, 0.5f);
				_panelRect.pivot = new Vector2(0f, 0.5f);
				_panelRect.anchoredPosition = new Vector2(10f, 10f);
			}
			((Transform)_panelRect).localScale = new Vector3(num, num, 1f);
			_promptBar?.SetScale(num);
			((Graphic)_panelBorderImage).color = (_isFocused ? BorderFocusedColor : BorderUnfocusedColor);
			if ((Object)(object)_focusBadgeText != (Object)null)
			{
				((Component)_focusBadgeText).gameObject.SetActive(_isExpanded && _isFocused);
			}
			if ((Object)(object)_clearButton != (Object)null)
			{
				((Component)_clearButton).gameObject.SetActive(_isExpanded);
			}
			if ((Object)(object)_drawerToggleLabel != (Object)null)
			{
				_drawerToggleLabel.text = ((!flag) ? (_isExpanded ? "«" : "»") : (_isExpanded ? "»" : "«"));
			}
		}

		private bool TryMeasureLargeMapScreenBounds(Minimap minimap, out float mapLeftX, out float mapRightX, out int mapCanvasOrder)
		{
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00db: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
			mapLeftX = 0f;
			mapRightX = Screen.width;
			mapCanvasOrder = 0;
			if (!_mapImageProbed)
			{
				_mapImageProbed = true;
				_mapImageLargeField = AccessTools.Field(typeof(Minimap), "m_mapImageLarge");
			}
			object? obj = _mapImageLargeField?.GetValue(minimap);
			RawImage val = (RawImage)((obj is RawImage) ? obj : null);
			if (val == null || (Object)(object)val == (Object)null)
			{
				return false;
			}
			Canvas canvas = ((Graphic)val).canvas;
			if ((Object)(object)canvas != (Object)null)
			{
				mapCanvasOrder = (canvas.overrideSorting ? canvas.sortingOrder : canvas.rootCanvas.sortingOrder);
			}
			Camera obj2 = (((Object)(object)canvas != (Object)null && (int)canvas.renderMode != 0) ? canvas.worldCamera : null);
			((Graphic)val).rectTransform.GetWorldCorners(_mapWorldCorners);
			Vector2 val2 = RectTransformUtility.WorldToScreenPoint(obj2, _mapWorldCorners[0]);
			Vector2 val3 = RectTransformUtility.WorldToScreenPoint(obj2, _mapWorldCorners[2]);
			mapLeftX = val2.x;
			mapRightX = val3.x;
			return mapRightX > mapLeftX;
		}

		private void RebuildRows()
		{
			//IL_018b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0192: Expected O, but got Unknown
			//IL_01ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0223: Unknown result type (might be due to invalid IL or missing references)
			//IL_0231: 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_0255: Unknown result type (might be due to invalid IL or missing references)
			//IL_0258: Unknown result type (might be due to invalid IL or missing references)
			//IL_025d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0261: Unknown result type (might be due to invalid IL or missing references)
			//IL_0249: Unknown result type (might be due to invalid IL or missing references)
			//IL_0242: Unknown result type (might be due to invalid IL or missing references)
			//IL_0275: Unknown result type (might be due to invalid IL or missing references)
			//IL_026e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0281: Unknown result type (might be due to invalid IL or missing references)
			//IL_028d: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c2: Expected O, but got Unknown
			//IL_02ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d8: Expected O, but got Unknown
			//IL_0334: Unknown result type (might be due to invalid IL or missing references)
			//IL_0339: Unknown result type (might be due to invalid IL or missing references)
			//IL_034f: Unknown result type (might be due to invalid IL or missing references)
			//IL_032d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0326: Unknown result type (might be due to invalid IL or missing references)
			//IL_03b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_03bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_03d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_03b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_044b: Unknown result type (might be due to invalid IL or missing references)
			//IL_04b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_04b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_04ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_04bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_04c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_050e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0513: Unknown result type (might be due to invalid IL or missing references)
			//IL_0518: Unknown result type (might be due to invalid IL or missing references)
			//IL_051d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0522: Unknown result type (might be due to invalid IL or missing references)
			//IL_056e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0573: Unknown result type (might be due to invalid IL or missing references)
			//IL_0578: Unknown result type (might be due to invalid IL or missing references)
			//IL_057d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0582: Unknown result type (might be due to invalid IL or missing references)
			_rowsDirty = false;
			if ((Object)(object)_listContentRect == (Object)null || (Object)(object)_headerTitleText == (Object)null || (Object)(object)_clearButton == (Object)null || (Object)(object)_emptyStateText == (Object)null)
			{
				return;
			}
			ClearRowObjects();
			IReadOnlyList<Waypoint> queue = _routeController.Queue;
			int count = queue.Count;
			ClampSelectedIndex();
			_headerTitleText.text = (_isExpanded ? $"RAVENROUTE ({count})" : $"ROUTES ({count})");
			((Selectable)_clearButton).interactable = count > 0;
			bool flag = count == 0;
			((Component)_emptyStateText).gameObject.SetActive(flag);
			if (flag)
			{
				string friendlyHint = _cfg.AddWaypointBinding.GetFriendlyHint(_lastGamepadActive);
				_emptyStateText.text = ((!_isExpanded) ? "No stops" : (string.IsNullOrEmpty(friendlyHint) ? "No waypoints queued." : ("No waypoints queued.\nPress [" + friendlyHint + "] on the map to add stops.")));
				return;
			}
			int maxChars = (_isExpanded ? 18 : 13);
			for (int i = 0; i < count; i++)
			{
				int rowIndex = i;
				Waypoint waypoint = queue[i];
				bool flag2 = i == 0;
				bool flag3 = _isFocused && i == _selectedIndex;
				GameObject val = new GameObject($"WaypointRow_{i}", new Type[1] { typeof(RectTransform) });
				val.transform.SetParent((Transform)(object)_listContentRect, false);
				LayoutElement obj = val.AddComponent<LayoutElement>();
				obj.minHeight = (_isExpanded ? 30f : 26f);
				obj.preferredHeight = (_isExpanded ? 30f : 26f);
				Image val2 = val.AddComponent<Image>();
				val2.sprite = _roundedSprite;
				val2.type = (Type)1;
				((Graphic)val2).color = Color.white;
				((Graphic)val2).raycastTarget = true;
				Button obj2 = val.AddComponent<Button>();
				((Selectable)obj2).targetGraphic = (Graphic)(object)val2;
				Navigation navigation = default(Navigation);
				((Navigation)(ref navigation)).mode = (Mode)0;
				((Selectable)obj2).navigation = navigation;
				Color normalColor = (flag3 ? RowSelectedColor : ((i % 2 == 0) ? RowEvenColor : RowOddColor));
				ColorBlock colors = ((Selectable)obj2).colors;
				((ColorBlock)(ref colors)).normalColor = normalColor;
				((ColorBlock)(ref colors)).highlightedColor = (flag3 ? RowSelectedColor : RowHoverColor);
				((ColorBlock)(ref colors)).pressedColor = RowSelectedColor;
				((ColorBlock)(ref colors)).selectedColor = RowSelectedColor;
				((ColorBlock)(ref colors)).fadeDuration = 0.05f;
				((Selectable)obj2).colors = colors;
				((UnityEvent)obj2.onClick).AddListener((UnityAction)delegate
				{
					OnRowClicked(rowIndex);
				});
				HorizontalLayoutGroup obj3 = val.AddComponent<HorizontalLayoutGroup>();
				((LayoutGroup)obj3).padding = new RectOffset(6, 5, 2, 2);
				((HorizontalOrVerticalLayoutGroup)obj3).spacing = 4f;
				((LayoutGroup)obj3).childAlignment = (TextAnchor)3;
				((HorizontalOrVerticalLayoutGroup)obj3).childControlWidth = true;
				((HorizontalOrVerticalLayoutGroup)obj3).childControlHeight = true;
				((HorizontalOrVerticalLayoutGroup)obj3).childForceExpandWidth = false;
				((HorizontalOrVerticalLayoutGroup)obj3).childForceExpandHeight = false;
				Color color = (Color)(waypoint.IsGrave ? GraveColor : (flag2 ? GoldColor : new Color(1f, 1f, 1f, 0.7f)));
				Text obj4 = UiComponents.CreateShadowedText(val.transform, "Index", _uiFont, 11, color, (TextAnchor)4, (FontStyle)1, (HorizontalWrapMode)1);
				obj4.text = (flag2 ? "▸" : $"{i + 1}.");
				LayoutElement obj5 = ((Component)obj4).gameObject.AddComponent<LayoutElement>();
				obj5.minWidth = 18f;
				obj5.preferredWidth = 18f;
				Color color2 = (waypoint.IsGrave ? GraveColor : (flag2 ? GoldColor : Color.white));
				Text obj6 = UiComponents.CreateShadowedText(val.transform, "Name", _uiFont, 12, color2, (TextAnchor)3, (FontStyle)(flag2 ? 1 : 0), (HorizontalWrapMode)0);
				obj6.text = TruncateLabel(waypoint.DisplayName, maxChars);
				LayoutElement obj7 = ((Component)obj6).gameObject.AddComponent<LayoutElement>();
				obj7.flexibleWidth = 1f;
				obj7.minWidth = 52f;
				Text val3 = null;
				if (_isExpanded)
				{
					val3 = UiComponents.CreateShadowedText(val.transform, "Distance", _uiFont, 11, new Color(0.88f, 0.88f, 0.88f, 0.9f), (TextAnchor)5, (FontStyle)0, (HorizontalWrapMode)1);
					val3.text = "--m";
					LayoutElement obj8 = ((Component)val3).gameObject.AddComponent<LayoutElement>();
					obj8.minWidth = 42f;
					obj8.preferredWidth = 42f;
					((Selectable)UiComponents.CreateActionButton(val.transform, "MoveUp", _uiFont, "▲", 9, 20f, 20f, _roundedSprite, ActionBtnNormal, ActionBtnHover, ActionBtnPressed, ActionBtnDisabled, Color.white, delegate
					{
						if (_routeController.MoveUp(rowIndex))
						{
							_selectedIndex = Mathf.Max(0, rowIndex - 1);
						}
					})).interactable = i > 0;
					((Selectable)UiComponents.CreateActionButton(val.transform, "MoveDown", _uiFont, "▼", 9, 20f, 20f, _roundedSprite, ActionBtnNormal, ActionBtnHover, ActionBtnPressed, ActionBtnDisabled, Color.white, delegate
					{
						if (_routeController.MoveDown(rowIndex))
						{
							_selectedIndex = Mathf.Min(_routeController.Count - 1, rowIndex + 1);
						}
					})).interactable = i < count - 1;
					UiComponents.CreateActionButton(val.transform, "Delete", _uiFont, "X", 10, 20f, 20f, _roundedSprite, DangerBtnNormal, DangerBtnHover, DangerBtnPressed, ActionBtnDisabled, Color.white, delegate
					{
						_logger.Debug($"[MapPanel] Row X clicked for stop #{rowIndex}.");
						_routeController.RemoveAt(rowIndex);
					});
				}
				_rowViews.Add(new RowView
				{
					Root = val,
					DistanceText = val3
				});
			}
			if (_isExpanded)
			{
				UpdateLiveDistances();
			}
		}

		private void OnRowClicked(int rowIndex)
		{
			float unscaledTime = Time.unscaledTime;
			bool num = rowIndex == _lastClickedRow && unscaledTime - _lastRowClickTime <= 0.35f;
			_lastClickedRow = rowIndex;
			_lastRowClickTime = unscaledTime;
			if (num && rowIndex > 0)
			{
				_logger.Debug($"[MapPanel] Row #{rowIndex} double-clicked -> JumpTo active target.");
				_routeController.JumpTo(rowIndex);
				_selectedIndex = 0;
			}
			else
			{
				_selectedIndex = rowIndex;
				_rowsDirty = true;
			}
		}

		private void UpdateLiveDistances()
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer == (Object)null)
			{
				return;
			}
			Vector3 position = ((Component)localPlayer).transform.position;
			IReadOnlyList<Waypoint> queue = _routeController.Queue;
			int num = Mathf.Min(queue.Count, _rowViews.Count);
			for (int i = 0; i < num; i++)
			{
				RowView rowView = _rowViews[i];
				if (!((Object)(object)rowView.DistanceText == (Object)null))
				{
					int num2 = Mathf.RoundToInt(queue[i].HorizontalDistanceTo(position));
					if (num2 != rowView.LastDistMeters)
					{
						rowView.LastDistMeters = num2;
						rowView.DistanceText.text = $"{num2}m";
					}
				}
			}
		}

		private void RebuildPromptBar()
		{
			_promptsDirty = false;
			if (_promptBar == null)
			{
				return;
			}
			List<PromptGuideEntry> list = new List<PromptGuideEntry>(6);
			bool lastGamepadActive = _lastGamepadActive;
			if (!_isFocused)
			{
				string friendlyHint = _cfg.AddWaypointBinding.GetFriendlyHint(lastGamepadActive);
				if (!string.IsNullOrEmpty(friendlyHint))
				{
					list.Add(new PromptGuideEntry(friendlyHint, "Add Waypoint"));
				}
				if (_cfg.ShowRoutePanel.Value)
				{
					InputChord inputChord = (lastGamepadActive ? _cfg.FocusPanelBinding.GamepadChord : _cfg.FocusPanelBinding.KeyboardMouseChord);
					if (inputChord.IsBound)
					{
						list.Add(new PromptGuideEntry(inputChord.FormatFriendly(), "Route Drawer"));
					}
				}
			}
			else
			{
				string friendlyHint2 = _cfg.NavigateUpBinding.GetFriendlyHint(lastGamepadActive);
				string friendlyHint3 = _cfg.NavigateDownBinding.GetFriendlyHint(lastGamepadActive);
				if (!string.IsNullOrEmpty(friendlyHint2) || !string.IsNullOrEmpty(friendlyHint3))
				{
					list.Add(new PromptGuideEntry((friendlyHint2 + "/" + friendlyHint3).Trim(new char[1] { '/' }), "Select"));
				}
				string friendlyHint4 = _cfg.JumpToStopBinding.GetFriendlyHint(lastGamepadActive);
				if (!string.IsNullOrEmpty(friendlyHint4))
				{
					list.Add(new PromptGuideEntry(friendlyHint4, "Set Active"));
				}
				string friendlyHint5 = _cfg.MoveUpBinding.GetFriendlyHint(lastGamepadActive);
				string friendlyHint6 = _cfg.MoveDownBinding.GetFriendlyHint(lastGamepadActive);
				if (!string.IsNullOrEmpty(friendlyHint5) || !string.IsNullOrEmpty(friendlyHint6))
				{
					list.Add(new PromptGuideEntry((friendlyHint5 + "/