Decompiled source of GridWise v1.15.6

GridWise.dll

Decompiled 5 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using PerfectRandom.Sulfur.Core;
using PerfectRandom.Sulfur.Core.Items;
using PerfectRandom.Sulfur.Core.UI;
using PerfectRandom.Sulfur.Core.UI.Inventory;
using Ryuka.Sulfur.GridWise.Apply;
using Ryuka.Sulfur.GridWise.Classification;
using Ryuka.Sulfur.GridWise.Config;
using Ryuka.Sulfur.GridWise.Debug;
using Ryuka.Sulfur.GridWise.Input;
using Ryuka.Sulfur.GridWise.Inventory;
using Ryuka.Sulfur.GridWise.Localization;
using Ryuka.Sulfur.GridWise.Locking;
using Ryuka.Sulfur.GridWise.Overlay;
using Ryuka.Sulfur.GridWise.Persistence;
using Ryuka.Sulfur.GridWise.Sorting;
using Ryuka.Sulfur.GridWise.Storage;
using Ryuka.Sulfur.GridWise.UserInterface;
using Ryuka.Sulfur.GridWise.Zones;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("GridWise")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("GridWise")]
[assembly: AssemblyCopyright("Copyright ©  2026")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("edb0b8bf-0415-4a35-95b9-35f240b97fc3")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace Ryuka.Sulfur.GridWise
{
	[BepInPlugin("ryuka.sulfur.gridwise", "GridWise Inventory", "1.15.5")]
	public sealed class Plugin : BaseUnityPlugin
	{
		private enum SortRequestSource
		{
			Hotkey,
			UiButton
		}

		public const string PluginGuid = "ryuka.sulfur.gridwise";

		public const string PluginName = "GridWise Inventory";

		public const string PluginVersion = "1.15.5";

		internal static ManualLogSource Log;

		internal static string PluginDirectory;

		private GridWiseConfig config;

		private SortPlanner planner;

		private DryRunExporter dryRunExporter;

		private ApplyPreviewValidator applyPreviewValidator;

		private ApplyPreviewExporter applyPreviewExporter;

		private PlanApplier planApplier;

		private ApplyResultExporter applyResultExporter;

		private UnknownItemsExporter unknownItemsExporter;

		private GridWiseUserDataStore userDataStore;

		private GridWiseOverlayController overlayController;

		private GridWiseUiController uiController;

		private GridWiseGameInputGuard gameInputGuard;

		private void Awake()
		{
			Log = ((BaseUnityPlugin)this).Logger;
			PluginDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) ?? Paths.PluginPath;
			GridWiseStorage.Initialize();
			GridWiseLocalization.Initialize("ryuka.sulfur.gridwise", PluginDirectory);
			config = new GridWiseConfig(((BaseUnityPlugin)this).Config);
			planner = new SortPlanner(config);
			dryRunExporter = new DryRunExporter(config);
			applyPreviewValidator = new ApplyPreviewValidator();
			applyPreviewExporter = new ApplyPreviewExporter();
			planApplier = new PlanApplier();
			applyResultExporter = new ApplyResultExporter();
			unknownItemsExporter = new UnknownItemsExporter(config);
			userDataStore = new GridWiseUserDataStore(config);
			overlayController = new GridWiseOverlayController(config, userDataStore);
			uiController = new GridWiseUiController(config, userDataStore, delegate
			{
				RunRealSort(SortRequestSource.UiButton);
			}, RequestToggleEditMode, RequestOverlayDataReload, () => overlayController != null && overlayController.IsEditMode);
			gameInputGuard = new GridWiseGameInputGuard(IsGridWiseTextInputActive);
			gameInputGuard.Install();
			Log.LogInfo((object)("GridWise Inventory 1.15.5 loaded. User data: " + GridWiseStorage.DataDirectory));
		}

		private void Update()
		{
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			GridWiseLocalization.RefreshCurrentLanguage(force: false);
			bool flag = IsGridWiseTextInputActive();
			gameInputGuard?.SetTextInputActive(flag);
			if (!flag && WasPressedThisFrame(config.DryRunKey.Value))
			{
				RunDrySort();
			}
			if (!flag && WasPressedThisFrame(config.RealSortKey.Value))
			{
				RunRealSort(SortRequestSource.Hotkey);
			}
			if (uiController != null)
			{
				uiController.Tick();
			}
			bool flag2 = IsGridWiseTextInputActive();
			gameInputGuard?.SetTextInputActive(flag2);
			if (overlayController != null)
			{
				overlayController.SetUiInputBlocked(flag2 || (uiController != null && uiController.IsPointerOverUi()));
				overlayController.SetUiTextInputActive(flag2);
				overlayController.Tick();
			}
		}

		private void OnDestroy()
		{
			if (uiController != null)
			{
				uiController.Destroy();
				uiController = null;
			}
			if (overlayController != null)
			{
				overlayController.Destroy();
				overlayController = null;
			}
			if (gameInputGuard != null)
			{
				gameInputGuard.Dispose();
				gameInputGuard = null;
			}
		}

		private bool IsGridWiseTextInputActive()
		{
			return uiController != null && uiController.IsTextInputActive();
		}

		private void RequestToggleEditMode()
		{
			if (overlayController != null && !IsGridWiseTextInputActive())
			{
				overlayController.RequestToggleEditMode();
			}
		}

		private void RequestOverlayDataReload()
		{
			if (overlayController != null)
			{
				overlayController.RequestReloadData();
			}
		}

		private void RunDrySort()
		{
			try
			{
				InventoryContext inventoryContext = InventoryContext.TryCreate();
				if (!inventoryContext.IsValid)
				{
					Log.LogWarning((object)("GridWise dry run skipped: " + inventoryContext.Error));
					TryShowSmallAlert("GridWise dry run skipped:\n" + inventoryContext.Error);
					return;
				}
				InventorySnapshot snapshot = InventorySnapshot.Capture(inventoryContext, config, userDataStore);
				unknownItemsExporter.Export(snapshot);
				PlacementPlan placementPlan = planner.BuildPlan(snapshot);
				ApplyValidationResult applyValidationResult = applyPreviewValidator.Validate(snapshot, placementPlan);
				string text = dryRunExporter.Export(snapshot, placementPlan);
				applyPreviewExporter.Export(text, snapshot, placementPlan, applyValidationResult);
				Log.LogInfo((object)$"GridWise dry run complete. PlanSuccess={placementPlan.Success}, ApplyPreviewValid={applyValidationResult.IsValid}, Errors={applyValidationResult.ErrorCount}");
				Log.LogInfo((object)("GridWise dry run exported to: " + text));
				TryShowSmallAlert(applyValidationResult.IsValid ? "GridWise preview saved:\nApply preview OK" : "GridWise preview saved:\nApply preview has errors");
			}
			catch (Exception ex)
			{
				Log.LogError((object)("GridWise dry run failed: " + ex));
				TryShowSmallAlert("GridWise preview failed. See LogOutput.log.");
			}
		}

		private void RunRealSort()
		{
			RunRealSort(SortRequestSource.Hotkey);
		}

		private void RunRealSort(SortRequestSource source)
		{
			try
			{
				if (!config.EnableRealSort.Value)
				{
					Log.LogWarning((object)"GridWise real sort refused: EnableRealSort is false.");
					TryShowRealSortAlert("GridWise real sort disabled.\nSet EnableRealSort = true.");
					return;
				}
				List<InventoryContext> list = ResolveSortTargets(source);
				if (list == null || list.Count == 0)
				{
					Log.LogWarning((object)"GridWise real sort skipped: no valid inventory grid target.");
					TryShowRealSortAlert("GridWise real sort skipped:\nNo valid inventory grid target.");
					return;
				}
				int num = 0;
				int num2 = 0;
				string text = null;
				foreach (InventoryContext item in list)
				{
					string error;
					if (item == null || !item.IsValid || (Object)(object)item.Grid == (Object)null)
					{
						num2++;
						if (text == null)
						{
							text = ((item != null) ? item.Error : "Target is null.");
						}
					}
					else if (RunRealSortForContext(item, out error))
					{
						num++;
					}
					else
					{
						num2++;
						if (text == null)
						{
							text = error;
						}
					}
				}
				if (list.Count == 1)
				{
					TryShowRealSortAlert((num2 == 0) ? ("GridWise real sort complete.\n" + list[0].DisplayName) : ("GridWise real sort failed.\n" + (text ?? "Check LogOutput.log.")));
				}
				else
				{
					TryShowRealSortAlert((num2 == 0) ? ("GridWise real sort complete.\nSorted " + num + " grids.") : ("GridWise real sort partial.\nOK " + num + " / Failed " + num2));
				}
			}
			catch (Exception ex)
			{
				Log.LogError((object)("GridWise real sort failed: " + ex));
				TryShowRealSortAlert("GridWise real sort failed. See LogOutput.log.");
			}
		}

		private List<InventoryContext> ResolveSortTargets(SortRequestSource source)
		{
			if (source == SortRequestSource.UiButton || (overlayController != null && overlayController.IsEditMode))
			{
				return InventoryGridResolver.GetOpenGridContexts();
			}
			InventoryContext inventoryContext = InventoryGridResolver.TryCreateContextUnderMouseOrPlayer();
			List<InventoryContext> list = new List<InventoryContext>();
			if (inventoryContext != null && inventoryContext.IsValid)
			{
				list.Add(inventoryContext);
			}
			return list;
		}

		private bool RunRealSortForContext(InventoryContext context, out string error)
		{
			error = null;
			try
			{
				if (context == null || !context.IsValid || (Object)(object)context.Grid == (Object)null)
				{
					error = ((context != null) ? context.Error : "Context is null.");
					Log.LogWarning((object)("GridWise real sort skipped: " + error));
					return false;
				}
				InventorySnapshot snapshot = InventorySnapshot.Capture(context, config, userDataStore);
				PlacementPlan placementPlan = planner.BuildPlan(snapshot);
				ApplyValidationResult applyValidationResult = applyPreviewValidator.Validate(snapshot, placementPlan);
				string text = null;
				if (config.ExportRealSortDebugFiles.Value)
				{
					unknownItemsExporter.Export(snapshot);
					text = dryRunExporter.Export(snapshot, placementPlan);
					applyPreviewExporter.Export(text, snapshot, placementPlan, applyValidationResult);
				}
				if (!placementPlan.Success)
				{
					error = context.DisplayName + ": Plan failed.";
					Log.LogWarning((object)("GridWise real sort refused for " + context.DisplayName + ": plan has failed items."));
					return false;
				}
				if (!applyValidationResult.IsValid)
				{
					error = context.DisplayName + ": Preview validation failed.";
					Log.LogWarning((object)$"GridWise real sort refused for {context.DisplayName}: apply preview invalid. Errors={applyValidationResult.ErrorCount}");
					return false;
				}
				ApplyResult applyResult = planApplier.Apply(snapshot, placementPlan);
				if (config.ExportRealSortDebugFiles.Value && config.ExportApplyResult.Value)
				{
					applyResultExporter.Export(text, applyResult);
				}
				Log.LogInfo((object)$"GridWise real sort result [{context.DisplayName}]: success={applyResult.Success}, errors={applyResult.ErrorCount}, rollback={applyResult.RollbackAttempted}/{applyResult.RollbackSucceeded}");
				if (config.ExportRealSortDebugFiles.Value && !string.IsNullOrEmpty(text))
				{
					Log.LogInfo((object)("GridWise real sort exported to: " + text));
				}
				if (!applyResult.Success)
				{
					error = context.DisplayName + ": Apply failed.";
				}
				return applyResult.Success;
			}
			catch (Exception ex)
			{
				error = ((context != null) ? (context.DisplayName + ": " + ex.Message) : ex.Message);
				Log.LogError((object)("GridWise real sort failed for target: " + ex));
				return false;
			}
		}

		private static bool WasPressedThisFrame(Key key)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			Keyboard current = Keyboard.current;
			if (current == null)
			{
				return false;
			}
			try
			{
				KeyControl val = current[key];
				return val != null && ((ButtonControl)val).wasPressedThisFrame;
			}
			catch
			{
				return false;
			}
		}

		private void TryShowRealSortAlert(string text)
		{
			if (config != null && config.ShowRealSortResultAlert.Value)
			{
				TryShowSmallAlert(text);
			}
		}

		private static void TryShowSmallAlert(string text)
		{
			try
			{
				UIManager instance = StaticInstance<UIManager>.Instance;
				if ((Object)(object)instance != (Object)null)
				{
					instance.ShowSmallAlert(text, 2.5f);
				}
			}
			catch
			{
			}
		}
	}
}
namespace Ryuka.Sulfur.GridWise.Zones
{
	public sealed class CustomZone
	{
		private readonly HashSet<string> cellKeys = new HashSet<string>();

		private readonly HashSet<string> allowedCategorySet = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

		public string Name;

		public bool Enabled = true;

		public bool Exclusive = true;

		public int Priority = 100;

		public SortAnchor Anchor = SortAnchor.TopLeft;

		public string Color = "#7ED95780";

		public readonly List<string> AllowedCategories = new List<string>();

		public readonly List<Vector2Int> Cells = new List<Vector2Int>();

		public bool Contains(Vector2Int cell)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			return cellKeys.Contains(Key(cell));
		}

		public bool Allows(string category)
		{
			if (AllowedCategories.Count == 0)
			{
				return true;
			}
			if (string.IsNullOrEmpty(category))
			{
				return false;
			}
			return allowedCategorySet.Contains(category);
		}

		public void AddAllowedCategory(string category)
		{
			if (!string.IsNullOrWhiteSpace(category))
			{
				string item = category.Trim();
				if (allowedCategorySet.Add(item))
				{
					AllowedCategories.Add(item);
				}
			}
		}

		public void ClearAllowedCategories()
		{
			allowedCategorySet.Clear();
			AllowedCategories.Clear();
		}

		public bool AddCell(Vector2Int cell)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			string item = Key(cell);
			if (!cellKeys.Add(item))
			{
				return false;
			}
			Cells.Add(cell);
			return true;
		}

		public bool RemoveCell(Vector2Int cell)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			string item = Key(cell);
			if (!cellKeys.Remove(item))
			{
				return false;
			}
			Cells.RemoveAll((Vector2Int x) => x == cell);
			return true;
		}

		public bool SetCell(Vector2Int cell, bool state)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			return state ? AddCell(cell) : RemoveCell(cell);
		}

		public string CellsText()
		{
			return string.Join(";", Cells.Select((Vector2Int x) => ((Vector2Int)(ref x)).x + "," + ((Vector2Int)(ref x)).y).ToArray());
		}

		public string CategoriesText()
		{
			return string.Join(",", AllowedCategories.ToArray());
		}

		private static string Key(Vector2Int cell)
		{
			return ((Vector2Int)(ref cell)).x + "," + ((Vector2Int)(ref cell)).y;
		}
	}
	public static class CustomZoneService
	{
		private const int PriorityNormal = 100;

		public static List<CustomZone> GetOrderedZones(CustomZones zones)
		{
			if (zones == null)
			{
				return new List<CustomZone>();
			}
			return (from x in zones.Zones
				where x != null
				orderby x.Priority descending, x.Name
				select x).ToList();
		}

		public static CustomZone GetActiveZone(CustomZones zones, GridWiseConfig config)
		{
			if (zones == null)
			{
				return null;
			}
			CustomZone customZone = FindByName(zones, zones.ActiveZoneName);
			if (customZone != null)
			{
				return customZone;
			}
			if (config != null)
			{
				customZone = FindByName(zones, config.ActiveEditZoneName.Value);
				if (customZone != null)
				{
					zones.ActiveZoneName = customZone.Name;
					return customZone;
				}
			}
			customZone = GetOrderedZones(zones).FirstOrDefault();
			if (customZone != null)
			{
				zones.ActiveZoneName = customZone.Name;
			}
			return customZone;
		}

		public static bool ResolveActiveZone(CustomZones zones, GridWiseConfig config, bool saveConfig)
		{
			if (zones == null || !zones.Enabled)
			{
				return false;
			}
			List<CustomZone> orderedZones = GetOrderedZones(zones);
			if (orderedZones.Count == 0)
			{
				return ClearActiveZone(zones, config, saveConfig);
			}
			CustomZone customZone = FindByName(zones, zones.ActiveZoneName);
			if (customZone != null)
			{
				return false;
			}
			if (config != null)
			{
				customZone = FindByName(zones, config.ActiveEditZoneName.Value);
				if (customZone != null)
				{
					return SelectActiveZone(zones, config, customZone, saveConfig);
				}
			}
			return SelectActiveZone(zones, config, orderedZones[0], saveConfig);
		}

		public static CustomZone CreateNewZone(CustomZones zones, GridWiseConfig config, IList<string> colorValues)
		{
			if (zones == null || config == null || !zones.Enabled)
			{
				return null;
			}
			int num = 1;
			string name;
			do
			{
				name = "Zone " + num;
				num++;
			}
			while (FindByName(zones, name) != null);
			string colorFallback = PickColor(colorValues, num - 2);
			CustomZone customZone = CreateDefaultZone(config, name, colorFallback);
			zones.Zones.Add(customZone);
			SelectActiveZone(zones, config, customZone, saveConfig: true);
			return customZone;
		}

		public static DeleteZoneResult DeleteActiveZone(CustomZones zones, GridWiseConfig config)
		{
			DeleteZoneResult deleteZoneResult = new DeleteZoneResult();
			if (zones == null || zones.Zones.Count == 0)
			{
				return deleteZoneResult;
			}
			CustomZone activeZone = GetActiveZone(zones, config);
			if (activeZone == null)
			{
				return deleteZoneResult;
			}
			List<CustomZone> orderedZones = GetOrderedZones(zones);
			int val = orderedZones.FindIndex((CustomZone x) => SameName(x, activeZone.Name));
			deleteZoneResult.DeletedName = activeZone.Name;
			deleteZoneResult.Deleted = zones.Zones.RemoveAll((CustomZone x) => SameName(x, activeZone.Name)) > 0;
			if (!deleteZoneResult.Deleted)
			{
				return deleteZoneResult;
			}
			List<CustomZone> orderedZones2 = GetOrderedZones(zones);
			if (orderedZones2.Count > 0)
			{
				int index = Math.Max(0, Math.Min(val, orderedZones2.Count - 1));
				deleteZoneResult.NewActiveZone = orderedZones2[index];
				SelectActiveZone(zones, config, deleteZoneResult.NewActiveZone, saveConfig: true);
			}
			else
			{
				ClearActiveZone(zones, config, saveConfig: true);
			}
			return deleteZoneResult;
		}

		public static bool SelectActiveZone(CustomZones zones, GridWiseConfig config, CustomZone zone, bool saveConfig)
		{
			if (zones == null || zone == null || string.IsNullOrWhiteSpace(zone.Name))
			{
				return false;
			}
			string text = zone.Name.Trim();
			bool result = !string.Equals(zones.ActiveZoneName, text, StringComparison.Ordinal);
			zones.ActiveZoneName = text;
			if (config != null && !string.Equals(config.ActiveEditZoneName.Value, text, StringComparison.Ordinal))
			{
				config.ActiveEditZoneName.Value = text;
				if (saveConfig)
				{
					config.Save();
				}
			}
			return result;
		}

		public static bool SelectActiveZone(GridWiseConfig config, CustomZone zone, bool saveConfig)
		{
			if (config == null || zone == null || string.IsNullOrWhiteSpace(zone.Name))
			{
				return false;
			}
			string text = zone.Name.Trim();
			if (string.Equals(config.ActiveEditZoneName.Value, text, StringComparison.Ordinal))
			{
				return false;
			}
			config.ActiveEditZoneName.Value = text;
			if (saveConfig)
			{
				config.Save();
			}
			return true;
		}

		public static bool ClearActiveZone(CustomZones zones, GridWiseConfig config, bool saveConfig)
		{
			if (zones == null)
			{
				return false;
			}
			bool result = !string.IsNullOrEmpty(zones.ActiveZoneName);
			zones.ActiveZoneName = string.Empty;
			if (config != null && !string.IsNullOrEmpty(config.ActiveEditZoneName.Value))
			{
				config.ActiveEditZoneName.Value = string.Empty;
				if (saveConfig)
				{
					config.Save();
				}
			}
			return result;
		}

		public static bool ClearActiveZone(GridWiseConfig config, bool saveConfig)
		{
			if (config == null || string.IsNullOrEmpty(config.ActiveEditZoneName.Value))
			{
				return false;
			}
			config.ActiveEditZoneName.Value = string.Empty;
			if (saveConfig)
			{
				config.Save();
			}
			return true;
		}

		public static bool RenameActiveZone(CustomZones zones, GridWiseConfig config, string requestedName, bool saveConfig, out string finalName)
		{
			finalName = string.Empty;
			CustomZone activeZone = GetActiveZone(zones, config);
			if (zones == null || activeZone == null)
			{
				return false;
			}
			string text = NormalizeZoneName(requestedName);
			if (string.IsNullOrWhiteSpace(text))
			{
				finalName = activeZone.Name ?? string.Empty;
				return false;
			}
			if (string.Equals(activeZone.Name, text, StringComparison.Ordinal))
			{
				finalName = activeZone.Name;
				return false;
			}
			CustomZone customZone = FindByName(zones, text);
			if (customZone != null && !SameName(customZone, activeZone.Name))
			{
				text = zones.GetUniqueName(text);
			}
			if (string.Equals(activeZone.Name, text, StringComparison.Ordinal))
			{
				finalName = activeZone.Name;
				return false;
			}
			string name = activeZone.Name;
			activeZone.Name = text;
			finalName = text;
			zones.LastRenamedZoneOldName = name;
			zones.LastRenamedZoneNewName = text;
			SelectActiveZone(zones, config, activeZone, saveConfig);
			return true;
		}

		public static bool ToggleEnabled(CustomZones zones, GridWiseConfig config)
		{
			CustomZone activeZone = GetActiveZone(zones, config);
			if (activeZone == null)
			{
				return false;
			}
			string name = activeZone.Name;
			bool flag = !activeZone.Enabled;
			bool result = false;
			foreach (CustomZone zone in zones.Zones)
			{
				if (SameName(zone, name) && zone.Enabled != flag)
				{
					zone.Enabled = flag;
					result = true;
				}
			}
			return result;
		}

		public static bool ToggleExclusive(CustomZones zones, GridWiseConfig config)
		{
			CustomZone activeZone = GetActiveZone(zones, config);
			if (activeZone == null)
			{
				return false;
			}
			activeZone.Exclusive = !activeZone.Exclusive;
			return true;
		}

		public static bool SetColor(CustomZones zones, GridWiseConfig config, string color)
		{
			CustomZone activeZone = GetActiveZone(zones, config);
			if (activeZone == null || string.IsNullOrWhiteSpace(color))
			{
				return false;
			}
			if (string.Equals(activeZone.Color, color, StringComparison.OrdinalIgnoreCase))
			{
				return false;
			}
			activeZone.Color = color.Trim();
			return true;
		}

		public static bool SetAnchor(CustomZones zones, GridWiseConfig config, SortAnchor anchor)
		{
			CustomZone activeZone = GetActiveZone(zones, config);
			if (activeZone == null || activeZone.Anchor == anchor)
			{
				return false;
			}
			activeZone.Anchor = anchor;
			return true;
		}

		public static bool SetPriority(CustomZones zones, GridWiseConfig config, int priority)
		{
			CustomZone activeZone = GetActiveZone(zones, config);
			if (activeZone == null || activeZone.Priority == priority)
			{
				return false;
			}
			activeZone.Priority = priority;
			return true;
		}

		public static bool ToggleCategory(CustomZones zones, GridWiseConfig config, string category)
		{
			CustomZone activeZone = GetActiveZone(zones, config);
			if (activeZone == null || string.IsNullOrWhiteSpace(category))
			{
				return false;
			}
			string normalized = category.Trim();
			List<string> list = activeZone.AllowedCategories.ToList();
			if (list.Any((string x) => string.Equals(x, normalized, StringComparison.OrdinalIgnoreCase)))
			{
				list.RemoveAll((string x) => string.Equals(x, normalized, StringComparison.OrdinalIgnoreCase));
			}
			else
			{
				list.Add(normalized);
			}
			activeZone.ClearAllowedCategories();
			foreach (string item in list)
			{
				activeZone.AddAllowedCategory(item);
			}
			return true;
		}

		private static string NormalizeZoneName(string requestedName)
		{
			if (string.IsNullOrWhiteSpace(requestedName))
			{
				return string.Empty;
			}
			char[] array = requestedName.Trim().ToCharArray();
			for (int i = 0; i < array.Length; i++)
			{
				if (char.IsControl(array[i]))
				{
					array[i] = ' ';
				}
			}
			string text = string.Join(" ", new string(array).Split(new char[1] { ' ' }, StringSplitOptions.RemoveEmptyEntries));
			if (text.Length > 48)
			{
				text = text.Substring(0, 48).Trim();
			}
			return text;
		}

		private static CustomZone FindByName(CustomZones zones, string name)
		{
			if (zones == null || string.IsNullOrWhiteSpace(name))
			{
				return null;
			}
			string normalized = name.Trim();
			return zones.Zones.FirstOrDefault((CustomZone x) => SameName(x, normalized));
		}

		private static bool SameName(CustomZone zone, string name)
		{
			return zone != null && !string.IsNullOrWhiteSpace(name) && string.Equals(zone.Name, name.Trim(), StringComparison.OrdinalIgnoreCase);
		}

		private static string PickColor(IList<string> colorValues, int zeroBasedIndex)
		{
			if (colorValues == null || colorValues.Count == 0)
			{
				return "#7ED95780";
			}
			int index = Math.Max(0, zeroBasedIndex) % colorValues.Count;
			return colorValues[index];
		}

		private static CustomZone CreateDefaultZone(GridWiseConfig config, string name, string colorFallback)
		{
			CustomZone customZone = new CustomZone
			{
				Name = name,
				Enabled = true,
				Exclusive = config.DefaultNewZoneExclusive.Value,
				Priority = config.DefaultNewZonePriority.Value,
				Anchor = config.DefaultNewZoneAnchor.Value,
				Color = (string.IsNullOrWhiteSpace(config.DefaultNewZoneColor.Value) ? colorFallback : config.DefaultNewZoneColor.Value.Trim())
			};
			AddDefaultCategories(customZone, config.DefaultNewZoneAllowedCategories.Value);
			return customZone;
		}

		private static void AddDefaultCategories(CustomZone zone, string categoriesText)
		{
			if (zone == null)
			{
				return;
			}
			if (string.IsNullOrWhiteSpace(categoriesText))
			{
				zone.AddAllowedCategory("Food");
				zone.AddAllowedCategory("Healing");
				return;
			}
			string[] array = categoriesText.Split(new char[1] { ',' });
			foreach (string text in array)
			{
				string text2 = text.Trim();
				if (!string.IsNullOrEmpty(text2))
				{
					zone.AddAllowedCategory(text2);
				}
			}
		}
	}
	public sealed class DeleteZoneResult
	{
		public bool Deleted { get; set; }

		public string DeletedName { get; set; }

		public CustomZone NewActiveZone { get; set; }
	}
	public sealed class CustomZones
	{
		public bool Enabled;

		public string FilePath;

		public string LayoutFilePath;

		public string ProfileKey;

		public string LoadMessage;

		public string ActiveZoneName;

		public string LastRenamedZoneOldName;

		public string LastRenamedZoneNewName;

		public readonly List<CustomZone> Zones = new List<CustomZone>();

		public int Count => Zones.Count;

		public IEnumerable<CustomZone> EnabledZones => from x in Zones
			where x?.Enabled ?? false
			orderby x.Priority descending, x.Name
			select x;

		public CustomZone FindByName(string name)
		{
			if (string.IsNullOrWhiteSpace(name))
			{
				return null;
			}
			string trimmed = name.Trim();
			return Zones.FirstOrDefault((CustomZone x) => x != null && string.Equals(x.Name, trimmed, StringComparison.OrdinalIgnoreCase));
		}

		public CustomZone GetFirstOrderedZone()
		{
			return (from x in Zones
				where x != null
				orderby x.Priority descending, x.Name
				select x).FirstOrDefault();
		}

		public string GetUniqueName(string baseName)
		{
			string text = (string.IsNullOrWhiteSpace(baseName) ? "Zone" : baseName.Trim());
			if (FindByName(text) == null)
			{
				return text;
			}
			int num = 2;
			string text2;
			do
			{
				text2 = text + " " + num;
				num++;
			}
			while (FindByName(text2) != null);
			return text2;
		}

		public CustomZone GetZoneAt(Vector2Int cell)
		{
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			if (!Enabled)
			{
				return null;
			}
			foreach (CustomZone enabledZone in EnabledZones)
			{
				if (enabledZone.Cells.Contains(cell))
				{
					return enabledZone;
				}
			}
			return null;
		}

		public CustomZone GetExclusiveZoneAt(Vector2Int cell)
		{
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			if (!Enabled)
			{
				return null;
			}
			foreach (CustomZone enabledZone in EnabledZones)
			{
				if (enabledZone.Exclusive && enabledZone.Cells.Contains(cell))
				{
					return enabledZone;
				}
			}
			return null;
		}

		public List<CustomZone> GetZonesAt(Vector2Int cell)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			if (!Enabled)
			{
				return new List<CustomZone>();
			}
			return EnabledZones.Where((CustomZone zone) => zone.Cells.Contains(cell)).ToList();
		}
	}
	public static class CustomZonesLoader
	{
		private const int DefinitionsSchemaVersion = 4;

		private const int LayoutSchemaVersion = 1;

		private const string FallbackZoneColor = "#7ED95780";

		private const string LayoutFileName = "GridWise.ZoneLayout.json";

		public static CustomZones Load(GridWiseConfig config, Vector2Int gridSize)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			return Load(config, gridSize, null);
		}

		public static CustomZones Load(GridWiseConfig config, Vector2Int gridSize, string profileKey)
		{
			//IL_00c0: 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)
			string profileKey2 = GridWiseUserDataStore.NormalizeProfileKey(profileKey);
			CustomZones customZones = new CustomZones();
			customZones.Enabled = config.EnableCustomZones.Value;
			customZones.FilePath = ResolvePath(config);
			customZones.LayoutFilePath = ResolveLayoutPath(config, profileKey2);
			customZones.ProfileKey = profileKey2;
			if (!customZones.Enabled)
			{
				customZones.LoadMessage = "CustomZones disabled by config.";
				return customZones;
			}
			if (!File.Exists(customZones.FilePath))
			{
				customZones.LoadMessage = "Global zone definition file not found. It will be created only after editing or creating a zone.";
				return customZones;
			}
			if (!GridWiseJsonFile.TryReadAllText(customZones.FilePath, out var text, out var error))
			{
				customZones.LoadMessage = "Failed to read global zone definitions: " + error;
				return customZones;
			}
			try
			{
				LoadDefinitionsInto(customZones, text, gridSize);
			}
			catch (Exception ex)
			{
				string text2 = GridWiseJsonFile.CopyBrokenFile(customZones.FilePath);
				customZones.LoadMessage = (string.IsNullOrEmpty(text2) ? ("Failed to load global zone definitions: " + ex.Message) : ("Failed to load global zone definitions: " + ex.Message + " Broken copy: " + Path.GetFileName(text2)));
				return customZones;
			}
			string text3 = "no layout file";
			if (File.Exists(customZones.LayoutFilePath))
			{
				if (GridWiseJsonFile.TryReadAllText(customZones.LayoutFilePath, out var text4, out var error2))
				{
					try
					{
						text3 = "layout cells: " + ApplyLayoutCells(customZones, text4, gridSize);
					}
					catch (Exception ex2)
					{
						string text5 = GridWiseJsonFile.CopyBrokenFile(customZones.LayoutFilePath);
						text3 = (string.IsNullOrEmpty(text5) ? ("layout failed: " + ex2.Message) : ("layout failed: " + ex2.Message + " Broken copy: " + Path.GetFileName(text5)));
					}
				}
				else
				{
					text3 = "layout read failed: " + error2;
				}
			}
			customZones.LoadMessage = "Loaded global zones: " + customZones.Count + "; " + text3 + ".";
			return customZones;
		}

		public static void Save(GridWiseConfig config, CustomZones zones)
		{
			Save(config, zones, null);
		}

		public static void Save(GridWiseConfig config, CustomZones zones, string profileKey)
		{
			string profileKey2 = GridWiseUserDataStore.NormalizeProfileKey((!string.IsNullOrWhiteSpace(profileKey)) ? profileKey : zones?.ProfileKey);
			string path = ResolvePath(config);
			string path2 = ((zones != null && !string.IsNullOrEmpty(zones.LayoutFilePath)) ? zones.LayoutFilePath : ResolveLayoutPath(config, profileKey2));
			GridWiseJsonFile.WriteAllTextIfChangedAtomic(path, BuildDefinitionsJson(zones), out var error);
			if (!string.IsNullOrEmpty(error) && Plugin.Log != null)
			{
				Plugin.Log.LogWarning((object)("Failed to save global zone definitions: " + error));
			}
			GridWiseJsonFile.WriteAllTextIfChangedAtomic(path2, BuildLayoutJson(zones, profileKey2), out var error2);
			if (!string.IsNullOrEmpty(error2) && Plugin.Log != null)
			{
				Plugin.Log.LogWarning((object)("Failed to save zone layout: " + error2));
			}
		}

		public static string ResolvePath(GridWiseConfig config)
		{
			return GridWiseStorage.DataFile(config.CustomZonesFileName.Value, "GridWise.CustomZones.json");
		}

		public static string ResolvePath(GridWiseConfig config, string profileKey)
		{
			return ResolvePath(config);
		}

		public static string ResolveLayoutPath(GridWiseConfig config, string profileKey)
		{
			return GridWiseStorage.ProfiledDataFile("GridWise.ZoneLayout.json", "GridWise.ZoneLayout.json", profileKey);
		}

		public static void RenameZoneInAllLayouts(string oldName, string newName)
		{
			if (string.IsNullOrWhiteSpace(oldName) || string.IsNullOrWhiteSpace(newName))
			{
				return;
			}
			string dataDirectory = GridWiseStorage.DataDirectory;
			if (!string.IsNullOrEmpty(dataDirectory) && Directory.Exists(dataDirectory))
			{
				string[] files;
				try
				{
					files = Directory.GetFiles(dataDirectory, "GridWise.ZoneLayout*.json");
				}
				catch
				{
					return;
				}
				for (int i = 0; i < files.Length; i++)
				{
					TryRenameZoneInLayoutFile(files[i], oldName.Trim(), newName.Trim());
				}
			}
		}

		private static void LoadDefinitionsInto(CustomZones result, string json, Vector2Int gridSize)
		{
			object value = GridWiseJson.Parse(json);
			Dictionary<string, object> dictionary = GridWiseJson.AsObject(value);
			if (dictionary == null)
			{
				throw new GridWiseJsonParseException("Root value must be a JSON object.");
			}
			result.ActiveZoneName = GridWiseJson.GetString(dictionary, "activeZoneName", string.Empty);
			List<object> list = GridWiseJson.GetArray(dictionary, "zones") ?? new List<object>();
			HashSet<string> usedNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
			foreach (object item in list)
			{
				Dictionary<string, object> dictionary2 = GridWiseJson.AsObject(item);
				if (dictionary2 != null)
				{
					CustomZone customZone = ParseZoneDefinitionObject(dictionary2, usedNames);
					if (customZone != null)
					{
						result.Zones.Add(customZone);
					}
				}
			}
		}

		private static int ApplyLayoutCells(CustomZones zones, string json, Vector2Int gridSize)
		{
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			object value = GridWiseJson.Parse(json);
			Dictionary<string, object> dictionary = GridWiseJson.AsObject(value);
			if (dictionary == null)
			{
				throw new GridWiseJsonParseException("Layout root value must be a JSON object.");
			}
			int num = 0;
			List<object> list = GridWiseJson.GetArray(dictionary, "zoneCells") ?? new List<object>();
			foreach (object item in list)
			{
				Dictionary<string, object> dictionary2 = GridWiseJson.AsObject(item);
				if (dictionary2 != null)
				{
					string @string = GridWiseJson.GetString(dictionary2, "zoneName", string.Empty);
					CustomZone customZone = zones.FindByName(@string);
					if (customZone != null)
					{
						int count = customZone.Cells.Count;
						AddCells(customZone, GridWiseJson.GetArray(dictionary2, "cells"), gridSize);
						num += customZone.Cells.Count - count;
					}
				}
			}
			return num;
		}

		private static string BuildDefinitionsJson(CustomZones zones)
		{
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.AppendLine("{");
			stringBuilder.AppendLine("  \"schemaVersion\": " + 4 + ",");
			stringBuilder.AppendLine("  \"note\": \"GridWise global zone definitions. Zone cells are stored separately per grid in GridWise.ZoneLayout*.json.\",");
			stringBuilder.AppendLine("  \"activeZoneName\": " + GridWiseJson.Quote((zones != null) ? zones.ActiveZoneName : string.Empty) + ",");
			stringBuilder.AppendLine("  \"zones\": [");
			CustomZone[] array = ((zones != null) ? (from x in zones.Zones
				where x != null
				orderby x.Priority descending, x.Name
				select x).ToArray() : new CustomZone[0]);
			for (int i = 0; i < array.Length; i++)
			{
				CustomZone customZone = array[i];
				stringBuilder.AppendLine("    {");
				stringBuilder.AppendLine("      \"name\": " + GridWiseJson.Quote(customZone.Name) + ",");
				stringBuilder.AppendLine("      \"enabled\": " + (customZone.Enabled ? "true" : "false") + ",");
				stringBuilder.AppendLine("      \"allowedCategories\": [" + string.Join(", ", customZone.AllowedCategories.Select(GridWiseJson.Quote).ToArray()) + "],");
				stringBuilder.AppendLine("      \"exclusive\": " + (customZone.Exclusive ? "true" : "false") + ",");
				stringBuilder.AppendLine("      \"priority\": " + customZone.Priority + ",");
				stringBuilder.AppendLine("      \"anchor\": " + GridWiseJson.Quote(customZone.Anchor.ToString()) + ",");
				stringBuilder.AppendLine("      \"color\": " + GridWiseJson.Quote(NormalizeColor(customZone.Color, "#7ED95780")));
				stringBuilder.Append("    }");
				if (i < array.Length - 1)
				{
					stringBuilder.Append(",");
				}
				stringBuilder.AppendLine();
			}
			stringBuilder.AppendLine("  ]");
			stringBuilder.AppendLine("}");
			return stringBuilder.ToString();
		}

		private static string BuildLayoutJson(CustomZones zones, string profileKey)
		{
			//IL_0195: Unknown result type (might be due to invalid IL or missing references)
			//IL_019a: Unknown result type (might be due to invalid IL or missing references)
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.AppendLine("{");
			stringBuilder.AppendLine("  \"schemaVersion\": " + 1 + ",");
			stringBuilder.AppendLine("  \"profileKey\": " + GridWiseJson.Quote(GridWiseUserDataStore.NormalizeProfileKey(profileKey)) + ",");
			stringBuilder.AppendLine("  \"note\": \"GridWise per-grid zone layout. Global zone settings live in GridWise.CustomZones.json. Coordinates are [x, y]. In-game y=0 is the bottom row.\",");
			stringBuilder.AppendLine("  \"zoneCells\": [");
			CustomZone[] array = ((zones != null) ? (from x in zones.Zones
				where x != null
				orderby x.Priority descending, x.Name
				select x).ToArray() : new CustomZone[0]);
			for (int i = 0; i < array.Length; i++)
			{
				CustomZone customZone = array[i];
				stringBuilder.AppendLine("    {");
				stringBuilder.AppendLine("      \"zoneName\": " + GridWiseJson.Quote(customZone.Name) + ",");
				stringBuilder.AppendLine("      \"cells\": [");
				Vector2Int[] array2 = (from x in customZone.Cells
					orderby ((Vector2Int)(ref x)).y, ((Vector2Int)(ref x)).x
					select x).ToArray();
				for (int j = 0; j < array2.Length; j++)
				{
					Vector2Int val = array2[j];
					stringBuilder.Append("        [").Append(((Vector2Int)(ref val)).x).Append(", ")
						.Append(((Vector2Int)(ref val)).y)
						.Append("]");
					if (j < array2.Length - 1)
					{
						stringBuilder.Append(",");
					}
					stringBuilder.AppendLine();
				}
				stringBuilder.AppendLine("      ]");
				stringBuilder.Append("    }");
				if (i < array.Length - 1)
				{
					stringBuilder.Append(",");
				}
				stringBuilder.AppendLine();
			}
			stringBuilder.AppendLine("  ]");
			stringBuilder.AppendLine("}");
			return stringBuilder.ToString();
		}

		private static CustomZone ParseZoneDefinitionObject(Dictionary<string, object> obj, HashSet<string> usedNames)
		{
			CustomZone customZone = new CustomZone();
			string @string = GridWiseJson.GetString(obj, "name", "Zone");
			customZone.Name = MakeUniqueName(NormalizeName(@string), usedNames);
			customZone.Enabled = GridWiseJson.GetBool(obj, "enabled", fallback: true);
			customZone.Exclusive = GridWiseJson.GetBool(obj, "exclusive", fallback: true);
			customZone.Priority = Clamp(GridWiseJson.GetInt(obj, "priority", 100), -9999, 9999);
			customZone.Color = NormalizeColor(GridWiseJson.GetString(obj, "color", "#7ED95780"), "#7ED95780");
			string string2 = GridWiseJson.GetString(obj, "anchor", SortAnchor.TopLeft.ToString());
			customZone.Anchor = (Enum.TryParse<SortAnchor>(string2, ignoreCase: true, out var result) ? result : SortAnchor.TopLeft);
			AddCategories(customZone, GridWiseJson.GetArray(obj, "allowedCategories"));
			return customZone;
		}

		private static void AddCategories(CustomZone zone, List<object> categories)
		{
			if (zone == null || categories == null)
			{
				return;
			}
			foreach (object category in categories)
			{
				string text = category as string;
				if (!string.IsNullOrWhiteSpace(text))
				{
					zone.AddAllowedCategory(text);
				}
			}
		}

		private static void AddCells(CustomZone zone, List<object> cells, Vector2Int gridSize)
		{
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			if (zone == null || cells == null)
			{
				return;
			}
			foreach (object cell2 in cells)
			{
				if (TryReadCell(cell2, out var cell) && ((Vector2Int)(ref cell)).x >= 0 && ((Vector2Int)(ref cell)).y >= 0 && ((Vector2Int)(ref cell)).x < ((Vector2Int)(ref gridSize)).x && ((Vector2Int)(ref cell)).y < ((Vector2Int)(ref gridSize)).y)
				{
					zone.AddCell(cell);
				}
			}
		}

		private static bool TryReadCell(object value, out Vector2Int cell)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			cell = default(Vector2Int);
			List<object> list = GridWiseJson.AsArray(value);
			if (list != null && list.Count >= 2)
			{
				cell = new Vector2Int(GridWiseJson.ToInt(list[0], int.MinValue), GridWiseJson.ToInt(list[1], int.MinValue));
				return ((Vector2Int)(ref cell)).x != int.MinValue && ((Vector2Int)(ref cell)).y != int.MinValue;
			}
			Dictionary<string, object> dictionary = GridWiseJson.AsObject(value);
			if (dictionary != null)
			{
				cell = new Vector2Int(GridWiseJson.GetInt(dictionary, "x", int.MinValue), GridWiseJson.GetInt(dictionary, "y", int.MinValue));
				return ((Vector2Int)(ref cell)).x != int.MinValue && ((Vector2Int)(ref cell)).y != int.MinValue;
			}
			return false;
		}

		private static void TryRenameZoneInLayoutFile(string path, string oldName, string newName)
		{
			if (string.IsNullOrEmpty(path) || !File.Exists(path) || !GridWiseJsonFile.TryReadAllText(path, out var text, out var _))
			{
				return;
			}
			try
			{
				object value = GridWiseJson.Parse(text);
				Dictionary<string, object> dictionary = GridWiseJson.AsObject(value);
				if (dictionary == null)
				{
					return;
				}
				List<object> list = GridWiseJson.GetArray(dictionary, "zoneCells") ?? new List<object>();
				bool flag = false;
				for (int i = 0; i < list.Count; i++)
				{
					Dictionary<string, object> dictionary2 = GridWiseJson.AsObject(list[i]);
					if (dictionary2 != null)
					{
						string @string = GridWiseJson.GetString(dictionary2, "zoneName", string.Empty);
						if (string.Equals(@string, oldName, StringComparison.OrdinalIgnoreCase))
						{
							dictionary2["zoneName"] = newName;
							flag = true;
						}
					}
				}
				if (flag)
				{
					string string2 = GridWiseJson.GetString(dictionary, "profileKey", string.Empty);
					GridWiseJsonFile.WriteAllTextIfChangedAtomic(path, BuildLayoutJsonFromParsed(string2, list), out var _);
				}
			}
			catch
			{
			}
		}

		private static string BuildLayoutJsonFromParsed(string profileKey, List<object> zoneCells)
		{
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.AppendLine("{");
			stringBuilder.AppendLine("  \"schemaVersion\": " + 1 + ",");
			stringBuilder.AppendLine("  \"profileKey\": " + GridWiseJson.Quote(profileKey) + ",");
			stringBuilder.AppendLine("  \"note\": \"GridWise per-grid zone layout. Global zone settings live in GridWise.CustomZones.json. Coordinates are [x, y]. In-game y=0 is the bottom row.\",");
			stringBuilder.AppendLine("  \"zoneCells\": [");
			for (int i = 0; i < zoneCells.Count; i++)
			{
				Dictionary<string, object> dictionary = GridWiseJson.AsObject(zoneCells[i]);
				if (dictionary == null)
				{
					continue;
				}
				stringBuilder.AppendLine("    {");
				stringBuilder.AppendLine("      \"zoneName\": " + GridWiseJson.Quote(GridWiseJson.GetString(dictionary, "zoneName", string.Empty)) + ",");
				stringBuilder.AppendLine("      \"cells\": [");
				List<object> list = GridWiseJson.GetArray(dictionary, "cells") ?? new List<object>();
				for (int j = 0; j < list.Count; j++)
				{
					if (TryReadCell(list[j], out var cell))
					{
						stringBuilder.Append("        [").Append(((Vector2Int)(ref cell)).x).Append(", ")
							.Append(((Vector2Int)(ref cell)).y)
							.Append("]");
						if (j < list.Count - 1)
						{
							stringBuilder.Append(",");
						}
						stringBuilder.AppendLine();
					}
				}
				stringBuilder.AppendLine("      ]");
				stringBuilder.Append("    }");
				if (i < zoneCells.Count - 1)
				{
					stringBuilder.Append(",");
				}
				stringBuilder.AppendLine();
			}
			stringBuilder.AppendLine("  ]");
			stringBuilder.AppendLine("}");
			return stringBuilder.ToString();
		}

		private static string NormalizeName(string name)
		{
			string text = (string.IsNullOrWhiteSpace(name) ? "Zone" : name.Trim());
			return (text.Length > 64) ? text.Substring(0, 64) : text;
		}

		private static string MakeUniqueName(string name, HashSet<string> usedNames)
		{
			if (usedNames == null)
			{
				return name;
			}
			string text = NormalizeName(name);
			string text2 = text;
			int num = 2;
			while (usedNames.Contains(text2))
			{
				text2 = text + " " + num;
				num++;
			}
			usedNames.Add(text2);
			return text2;
		}

		private static string NormalizeColor(string color, string fallback)
		{
			string text = (string.IsNullOrWhiteSpace(color) ? fallback : color.Trim());
			Color val = default(Color);
			return ColorUtility.TryParseHtmlString(text, ref val) ? text : fallback;
		}

		private static int Clamp(int value, int min, int max)
		{
			if (value < min)
			{
				return min;
			}
			if (value > max)
			{
				return max;
			}
			return value;
		}
	}
}
namespace Ryuka.Sulfur.GridWise.UserInterface
{
	public sealed class GridWiseUiController
	{
		private sealed class CategoryButtonLink
		{
			public string Category;

			public Button Button;

			public Text Text;
		}

		private const int PriorityLow = 10;

		private const int PriorityNormal = 100;

		private const int PriorityHigh = 1000;

		private readonly GridWiseConfig config;

		private readonly GridWiseUserDataStore userDataStore;

		private readonly Action onSort;

		private readonly Action onToggleEditMode;

		private readonly Action onZoneChanged;

		private readonly Func<bool> isEditMode;

		private Canvas currentCanvas;

		private RectTransform currentGridRect;

		private GameObject rootObject;

		private RectTransform rootRect;

		private GameObject editBackgroundObject;

		private RectTransform editBackgroundRect;

		private Image editBackgroundImage;

		private Text titleText;

		private Text statusText;

		private Text sortButtonText;

		private Text editButtonText;

		private Button sortButton;

		private Button editButton;

		private Button zoneSelectButton;

		private Text zoneSelectText;

		private Image zoneSelectColorImage;

		private GameObject zoneListObject;

		private RectTransform zoneListRect;

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

		private bool zoneListOpen;

		private Button newZoneButton;

		private Button renameZoneButton;

		private Button deleteZoneButton;

		private GameObject renamePanelObject;

		private RectTransform renamePanelRect;

		private InputField renameInputField;

		private Button renameOkButton;

		private Button renameCancelButton;

		private bool renamePanelOpen;

		private Button enabledButton;

		private Text enabledButtonText;

		private Button exclusiveButton;

		private Text exclusiveButtonText;

		private Button colorButton;

		private Text colorButtonText;

		private Image colorButtonColorImage;

		private GameObject colorListObject;

		private RectTransform colorListRect;

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

		private bool colorListOpen;

		private Button anchorButton;

		private Text anchorButtonText;

		private GameObject anchorListObject;

		private RectTransform anchorListRect;

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

		private bool anchorListOpen;

		private Button priorityButton;

		private Text priorityButtonText;

		private GameObject priorityListObject;

		private RectTransform priorityListRect;

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

		private bool priorityListOpen;

		private Text allowedTitleText;

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

		private readonly List<CategoryButtonLink> categoryButtons = new List<CategoryButtonLink>();

		private CustomZones loadedZones;

		private Vector2Int loadedGridSize;

		private string loadedProfileKey = "player-bag";

		private InventoryContext activeEditContext;

		private float nextZoneReloadTime;

		private int lastObservedCustomZonesVersion = -1;

		private int lastObservedActiveEditProfileVersion = -1;

		private int lastObservedLocalizationVersion = -1;

		private readonly string[] categoryOptions = new string[14]
		{
			"Food", "Healing", "Manual", "WeaponConsumable", "Throwable", "Weapon", "BasicMelee", "HeadArmor", "TorsoArmor", "FeetArmor",
			"Attachment", "Oil", "Scroll", "Misc"
		};

		private readonly string[] colorNames = new string[6] { "Green", "Blue", "Yellow", "Purple", "Red", "Cyan" };

		private readonly string[] colorValues = new string[6] { "#7ED95780", "#4DA3FF80", "#FFD84D80", "#B45DFF80", "#FF5D5D80", "#4DFFE180" };

		private readonly SortAnchor[] anchorValues = new SortAnchor[4]
		{
			SortAnchor.TopLeft,
			SortAnchor.TopRight,
			SortAnchor.BottomLeft,
			SortAnchor.BottomRight
		};

		private readonly string[] priorityNames = new string[3] { "Low", "Normal", "High" };

		private readonly int[] priorityValues = new int[3] { 10, 100, 1000 };

		public GridWiseUiController(GridWiseConfig config, GridWiseUserDataStore userDataStore, Action onSort, Action onToggleEditMode, Action onZoneChanged, Func<bool> isEditMode)
		{
			this.config = config;
			this.userDataStore = userDataStore;
			this.onSort = onSort;
			this.onToggleEditMode = onToggleEditMode;
			this.onZoneChanged = onZoneChanged;
			this.isEditMode = isEditMode;
		}

		public void Tick()
		{
			if (!config.EnableBasicUi.Value)
			{
				Hide();
				return;
			}
			List<InventoryContext> openGridContexts = InventoryGridResolver.GetOpenGridContexts();
			if (openGridContexts.Count == 0 || openGridContexts[0] == null || (Object)(object)openGridContexts[0].InventoryUI == (Object)null || (Object)(object)openGridContexts[0].Grid == (Object)null)
			{
				Hide();
				return;
			}
			InventoryContext inventoryContext = openGridContexts[0];
			if (!inventoryContext.InventoryUI.IsOpened)
			{
				Hide();
				return;
			}
			Canvas componentInParent = ((Component)inventoryContext.InventoryUI).GetComponentInParent<Canvas>();
			if ((Object)(object)componentInParent == (Object)null)
			{
				Hide();
				return;
			}
			RectTransform component = ((Component)inventoryContext.Grid).GetComponent<RectTransform>();
			if ((Object)(object)component == (Object)null)
			{
				Hide();
				return;
			}
			if ((Object)(object)rootObject == (Object)null || (Object)(object)currentCanvas != (Object)(object)componentInParent || (Object)(object)currentGridRect != (Object)(object)component)
			{
				Rebuild(componentInParent, component);
			}
			activeEditContext = ResolveUiEditContext(openGridContexts);
			RefreshZonesIfNeeded(activeEditContext, force: false);
			RefreshLocalizationIfNeeded();
			HandleRenameKeyboardShortcuts();
			Show();
			UpdateTexts();
			UpdateToolbarPosition(componentInParent, component);
		}

		private void RefreshLocalizationIfNeeded()
		{
			if (lastObservedLocalizationVersion != GridWiseLocalization.Version)
			{
				lastObservedLocalizationVersion = GridWiseLocalization.Version;
				RefreshAllDropdownRows();
			}
		}

		private InventoryContext ResolveUiEditContext(List<InventoryContext> contexts)
		{
			if (contexts == null || contexts.Count == 0)
			{
				userDataStore.SetActiveEditProfile("player-bag");
				return null;
			}
			InventoryContext inventoryContext = contexts[0];
			userDataStore.SetActiveEditProfile(inventoryContext.ProfileKey);
			return inventoryContext;
		}

		public bool IsPointerOverUi()
		{
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: 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_00ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0131: Unknown result type (might be due to invalid IL or missing references)
			//IL_0163: Unknown result type (might be due to invalid IL or missing references)
			if (!IsEditing())
			{
				return false;
			}
			if ((Object)(object)rootObject == (Object)null || !rootObject.activeInHierarchy || (Object)(object)rootRect == (Object)null)
			{
				return false;
			}
			Mouse current = Mouse.current;
			if (current == null)
			{
				return false;
			}
			Vector2 val = ((InputControl<Vector2>)(object)((Pointer)current).position).ReadValue();
			Camera val2 = (((Object)(object)currentCanvas != (Object)null) ? currentCanvas.worldCamera : null);
			if (RectTransformUtility.RectangleContainsScreenPoint(rootRect, val, val2))
			{
				return true;
			}
			if (zoneListOpen && (Object)(object)zoneListRect != (Object)null && RectTransformUtility.RectangleContainsScreenPoint(zoneListRect, val, val2))
			{
				return true;
			}
			if (colorListOpen && (Object)(object)colorListRect != (Object)null && RectTransformUtility.RectangleContainsScreenPoint(colorListRect, val, val2))
			{
				return true;
			}
			if (anchorListOpen && (Object)(object)anchorListRect != (Object)null && RectTransformUtility.RectangleContainsScreenPoint(anchorListRect, val, val2))
			{
				return true;
			}
			if (priorityListOpen && (Object)(object)priorityListRect != (Object)null && RectTransformUtility.RectangleContainsScreenPoint(priorityListRect, val, val2))
			{
				return true;
			}
			return false;
		}

		public bool IsTextInputActive()
		{
			return renamePanelOpen && (Object)(object)renameInputField != (Object)null && (Object)(object)renamePanelObject != (Object)null && renamePanelObject.activeInHierarchy;
		}

		public void Destroy()
		{
			if ((Object)(object)rootObject != (Object)null)
			{
				Object.Destroy((Object)(object)rootObject);
				rootObject = null;
			}
			currentCanvas = null;
			currentGridRect = null;
			rootRect = null;
			editBackgroundObject = null;
			editBackgroundRect = null;
			editBackgroundImage = null;
			titleText = null;
			statusText = null;
			sortButtonText = null;
			editButtonText = null;
			sortButton = null;
			editButton = null;
			zoneSelectButton = null;
			zoneSelectText = null;
			zoneSelectColorImage = null;
			zoneListObject = null;
			zoneListRect = null;
			zoneListRows.Clear();
			zoneListOpen = false;
			newZoneButton = null;
			renameZoneButton = null;
			deleteZoneButton = null;
			renamePanelObject = null;
			renamePanelRect = null;
			renameInputField = null;
			renameOkButton = null;
			renameCancelButton = null;
			renamePanelOpen = false;
			enabledButton = null;
			enabledButtonText = null;
			exclusiveButton = null;
			exclusiveButtonText = null;
			colorButton = null;
			colorButtonText = null;
			colorButtonColorImage = null;
			colorListObject = null;
			colorListRect = null;
			colorListRows.Clear();
			colorListOpen = false;
			anchorButton = null;
			anchorButtonText = null;
			anchorListObject = null;
			anchorListRect = null;
			anchorListRows.Clear();
			anchorListOpen = false;
			priorityButton = null;
			priorityButtonText = null;
			priorityListObject = null;
			priorityListRect = null;
			priorityListRows.Clear();
			priorityListOpen = false;
			allowedTitleText = null;
			editOnlyObjects.Clear();
			categoryButtons.Clear();
			loadedZones = null;
			lastObservedCustomZonesVersion = -1;
		}

		private void Rebuild(Canvas canvas, RectTransform gridRect)
		{
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Expected O, but got Unknown
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d1: 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_00f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0104: Unknown result type (might be due to invalid IL or missing references)
			//IL_0135: Unknown result type (might be due to invalid IL or missing references)
			//IL_0144: Unknown result type (might be due to invalid IL or missing references)
			//IL_0173: Unknown result type (might be due to invalid IL or missing references)
			//IL_0182: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fa: Expected O, but got Unknown
			//IL_0212: Unknown result type (might be due to invalid IL or missing references)
			//IL_0221: 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_0263: Expected O, but got Unknown
			//IL_027b: Unknown result type (might be due to invalid IL or missing references)
			//IL_028a: Unknown result type (might be due to invalid IL or missing references)
			//IL_02eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f5: Expected O, but got Unknown
			//IL_030d: Unknown result type (might be due to invalid IL or missing references)
			//IL_031c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0343: Unknown result type (might be due to invalid IL or missing references)
			//IL_034d: Expected O, but got Unknown
			//IL_0365: Unknown result type (might be due to invalid IL or missing references)
			//IL_0374: Unknown result type (might be due to invalid IL or missing references)
			//IL_039b: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a5: Expected O, but got Unknown
			//IL_03bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_03cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_03f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_03fd: Expected O, but got Unknown
			//IL_0415: Unknown result type (might be due to invalid IL or missing references)
			//IL_0424: Unknown result type (might be due to invalid IL or missing references)
			//IL_045c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0466: Expected O, but got Unknown
			//IL_047e: Unknown result type (might be due to invalid IL or missing references)
			//IL_048d: Unknown result type (might be due to invalid IL or missing references)
			//IL_04c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_04cf: Expected O, but got Unknown
			//IL_04e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_04f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_055c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0566: Expected O, but got Unknown
			//IL_057e: Unknown result type (might be due to invalid IL or missing references)
			//IL_058d: Unknown result type (might be due to invalid IL or missing references)
			//IL_05c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_05cf: Expected O, but got Unknown
			//IL_05e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_05f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_062e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0638: Expected O, but got Unknown
			//IL_0658: Unknown result type (might be due to invalid IL or missing references)
			//IL_0667: Unknown result type (might be due to invalid IL or missing references)
			Destroy();
			currentCanvas = canvas;
			currentGridRect = gridRect;
			rootObject = new GameObject("GridWise_Toolbar", new Type[1] { typeof(RectTransform) });
			rootRect = rootObject.GetComponent<RectTransform>();
			RectTransform component = ((Component)canvas).GetComponent<RectTransform>();
			((Transform)rootRect).SetParent((Transform)(((Object)(object)component != (Object)null) ? ((object)component) : ((object)((Component)canvas).transform)), false);
			rootRect.anchorMin = new Vector2(0.5f, 0.5f);
			rootRect.anchorMax = new Vector2(0.5f, 0.5f);
			rootRect.pivot = new Vector2(0f, 1f);
			rootRect.sizeDelta = new Vector2(820f, 190f);
			rootRect.anchoredPosition = Vector2.zero;
			((Transform)rootRect).localScale = Vector3.one;
			((Transform)rootRect).localRotation = Quaternion.identity;
			CreateEditBackground();
			titleText = CreateText(rootRect, "Title", GridWiseUiText.Title, 18, (TextAnchor)3, new Vector2(14f, -16f), new Vector2(110f, 28f), editOnly: true);
			statusText = CreateText(rootRect, "Status", "", 12, (TextAnchor)3, new Vector2(122f, -18f), new Vector2(120f, 26f), editOnly: true);
			sortButton = CreateButton(rootRect, "SortButton", new Vector2(0f, 0f), new Vector2(48f, 48f), GridWiseUiText.Sort, editOnly: false);
			sortButtonText = ((Component)sortButton).GetComponentInChildren<Text>();
			((UnityEvent)sortButton.onClick).AddListener((UnityAction)delegate
			{
				onSort?.Invoke();
			});
			editButton = CreateButton(rootRect, "EditButton", new Vector2(0f, -54f), new Vector2(48f, 48f), GridWiseUiText.Edit, editOnly: false);
			editButtonText = ((Component)editButton).GetComponentInChildren<Text>();
			((UnityEvent)editButton.onClick).AddListener((UnityAction)delegate
			{
				onToggleEditMode?.Invoke();
			});
			zoneSelectButton = CreateButton(rootRect, "ZoneSelectButton", new Vector2(16f, -54f), new Vector2(200f, 28f), GridWiseUiText.Zone, editOnly: true);
			zoneSelectText = ((Component)zoneSelectButton).GetComponentInChildren<Text>();
			zoneSelectColorImage = AddColorSquareToButton(zoneSelectButton);
			SetButtonTextPadding(zoneSelectButton, 30f, 10f);
			((UnityEvent)zoneSelectButton.onClick).AddListener(new UnityAction(ToggleZoneList));
			newZoneButton = CreateButton(rootRect, "NewZoneButton", new Vector2(224f, -54f), new Vector2(52f, 28f), GridWiseUiText.New, editOnly: true);
			((UnityEvent)newZoneButton.onClick).AddListener(new UnityAction(CreateNewZone));
			renameZoneButton = CreateButton(rootRect, "RenameZoneButton", new Vector2(282f, -54f), new Vector2(68f, 28f), GridWiseUiText.Rename, editOnly: true);
			((UnityEvent)renameZoneButton.onClick).AddListener(new UnityAction(OpenRenamePanel));
			deleteZoneButton = CreateButton(rootRect, "DeleteZoneButton", new Vector2(356f, -54f), new Vector2(52f, 28f), GridWiseUiText.Del, editOnly: true);
			((UnityEvent)deleteZoneButton.onClick).AddListener(new UnityAction(DeleteActiveZone));
			enabledButton = CreateButton(rootRect, "EnabledButton", new Vector2(416f, -54f), new Vector2(112f, 28f), GridWiseUiText.EnabledOn, editOnly: true);
			enabledButtonText = ((Component)enabledButton).GetComponentInChildren<Text>();
			((UnityEvent)enabledButton.onClick).AddListener(new UnityAction(ToggleEnabled));
			exclusiveButton = CreateButton(rootRect, "ExclusiveButton", new Vector2(536f, -54f), new Vector2(112f, 28f), GridWiseUiText.ExclusiveOn, editOnly: true);
			exclusiveButtonText = ((Component)exclusiveButton).GetComponentInChildren<Text>();
			((UnityEvent)exclusiveButton.onClick).AddListener(new UnityAction(ToggleExclusive));
			colorButton = CreateButton(rootRect, "ColorButton", new Vector2(656f, -54f), new Vector2(128f, 28f), GridWiseUiText.ColorName("Green"), editOnly: true);
			colorButtonText = ((Component)colorButton).GetComponentInChildren<Text>();
			colorButtonColorImage = AddColorSquareToButton(colorButton);
			SetButtonTextPadding(colorButton, 30f, 8f);
			((UnityEvent)colorButton.onClick).AddListener(new UnityAction(ToggleColorList));
			anchorButton = CreateButton(rootRect, "AnchorButton", new Vector2(16f, -88f), new Vector2(170f, 28f), GridWiseUiText.Anchor, editOnly: true);
			anchorButtonText = ((Component)anchorButton).GetComponentInChildren<Text>();
			((UnityEvent)anchorButton.onClick).AddListener(new UnityAction(ToggleAnchorList));
			priorityButton = CreateButton(rootRect, "PriorityButton", new Vector2(194f, -88f), new Vector2(150f, 28f), GridWiseUiText.Priority, editOnly: true);
			priorityButtonText = ((Component)priorityButton).GetComponentInChildren<Text>();
			((UnityEvent)priorityButton.onClick).AddListener(new UnityAction(TogglePriorityList));
			allowedTitleText = CreateText(rootRect, "AllowedTitle", GridWiseUiText.Allowed, 12, (TextAnchor)3, new Vector2(16f, -126f), new Vector2(72f, 24f), editOnly: true);
			CreateCategoryButtons();
			CreateZoneListPanel();
			CreateRenamePanel();
			CreateColorListPanel();
			CreateAnchorListPanel();
			CreatePriorityListPanel();
			BringMainControlsToFront();
			rootObject.transform.SetAsLastSibling();
		}

		private void CreateEditBackground()
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Expected O, but got Unknown
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_011e: Unknown result type (might be due to invalid IL or missing references)
			//IL_013c: Unknown result type (might be due to invalid IL or missing references)
			editBackgroundObject = new GameObject("EditBackground", new Type[3]
			{
				typeof(RectTransform),
				typeof(CanvasRenderer),
				typeof(Image)
			});
			editBackgroundRect = editBackgroundObject.GetComponent<RectTransform>();
			((Transform)editBackgroundRect).SetParent((Transform)(object)rootRect, false);
			editBackgroundRect.anchorMin = new Vector2(0f, 1f);
			editBackgroundRect.anchorMax = new Vector2(0f, 1f);
			editBackgroundRect.pivot = new Vector2(0f, 1f);
			editBackgroundRect.sizeDelta = new Vector2(820f, 190f);
			editBackgroundRect.anchoredPosition = Vector2.zero;
			((Transform)editBackgroundRect).localScale = Vector3.one;
			((Transform)editBackgroundRect).localRotation = Quaternion.identity;
			editBackgroundImage = editBackgroundObject.GetComponent<Image>();
			((Graphic)editBackgroundImage).color = GridWiseUiTheme.Panel(config);
			((Graphic)editBackgroundImage).raycastTarget = true;
			AddBorder(editBackgroundRect, GridWiseUiTheme.Border, 1.2f);
			editBackgroundObject.transform.SetAsFirstSibling();
			editOnlyObjects.Add(editBackgroundObject);
		}

		private void UpdateToolbarPosition(Canvas canvas, RectTransform gridRect)
		{
			//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_00d8: 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)
			//IL_00ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_0117: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)canvas == (Object)null || (Object)(object)gridRect == (Object)null || (Object)(object)rootRect == (Object)null)
			{
				return;
			}
			RectTransform component = ((Component)canvas).GetComponent<RectTransform>();
			if (!((Object)(object)component == (Object)null))
			{
				Rect rect;
				if (IsEditing())
				{
					rect = component.rect;
					float num = ((Rect)(ref rect)).xMin + 18f;
					rect = component.rect;
					float num2 = ((Rect)(ref rect)).yMax - 13f;
					rootRect.anchoredPosition = new Vector2(num, num2);
					return;
				}
				Vector3[] array = (Vector3[])(object)new Vector3[4];
				gridRect.GetWorldCorners(array);
				Vector3 val = ((Transform)component).InverseTransformPoint(array[1]);
				float num3 = val.x - 56f;
				float y = val.y;
				rect = component.rect;
				float num4 = ((Rect)(ref rect)).xMin + 12f;
				rect = component.rect;
				float num5 = ((Rect)(ref rect)).xMax - 60f;
				num3 = Mathf.Clamp(num3, num4, num5);
				rootRect.anchoredPosition = new Vector2(num3, y);
			}
		}

		private void CreateCategoryButtons()
		{
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e2: Expected O, but got Unknown
			categoryButtons.Clear();
			float num = 94f;
			float num2 = -126f;
			float num3 = -154f;
			float num4 = 88f;
			Vector2 topLeftPosition = default(Vector2);
			for (int i = 0; i < categoryOptions.Length; i++)
			{
				string text = categoryOptions[i];
				int num5 = i % 7;
				int num6 = i / 7;
				((Vector2)(ref topLeftPosition))..ctor(num + (float)num5 * num4, (num6 == 0) ? num2 : num3);
				Button val = CreateButton(rootRect, "Category_" + text, topLeftPosition, new Vector2(82f, 24f), ShortCategory(text), editOnly: true);
				Text componentInChildren = ((Component)val).GetComponentInChildren<Text>();
				if ((Object)(object)componentInChildren != (Object)null)
				{
					componentInChildren.fontSize = 11;
				}
				string captured = text;
				((UnityEvent)val.onClick).AddListener((UnityAction)delegate
				{
					ToggleCategory(captured);
				});
				categoryButtons.Add(new CategoryButtonLink
				{
					Category = text,
					Button = val,
					Text = componentInChildren
				});
			}
		}

		private void CreateZoneListPanel()
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			zoneListObject = CreateDropdownPanel("ZoneList", new Vector2(16f, -84f), new Vector2(220f, 160f));
			zoneListRect = zoneListObject.GetComponent<RectTransform>();
			zoneListObject.SetActive(false);
			editOnlyObjects.Add(zoneListObject);
		}

		private void CreateRenamePanel()
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cd: Expected O, but got Unknown
			//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_011b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0125: Expected O, but got Unknown
			renamePanelObject = CreateDropdownPanel("RenamePanel", new Vector2(224f, -84f), new Vector2(380f, 44f));
			renamePanelRect = renamePanelObject.GetComponent<RectTransform>();
			renameInputField = CreateInputField(renamePanelRect, "RenameInput", new Vector2(8f, -8f), new Vector2(210f, 28f));
			renameOkButton = CreateButton(renamePanelRect, "RenameOkButton", new Vector2(226f, -8f), new Vector2(58f, 28f), GridWiseUiText.RenameOk, editOnly: false);
			((UnityEvent)renameOkButton.onClick).AddListener(new UnityAction(ApplyRename));
			renameCancelButton = CreateButton(renamePanelRect, "RenameCancelButton", new Vector2(292f, -8f), new Vector2(80f, 28f), GridWiseUiText.RenameCancel, editOnly: false);
			((UnityEvent)renameCancelButton.onClick).AddListener(new UnityAction(CloseRenamePanel));
			renamePanelObject.SetActive(false);
			editOnlyObjects.Add(renamePanelObject);
		}

		private void CreateColorListPanel()
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			colorListObject = CreateDropdownPanel("ColorList", new Vector2(624f, -84f), new Vector2(170f, 160f));
			colorListRect = colorListObject.GetComponent<RectTransform>();
			colorListObject.SetActive(false);
			editOnlyObjects.Add(colorListObject);
		}

		private void CreateAnchorListPanel()
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			anchorListObject = CreateDropdownPanel("AnchorList", new Vector2(16f, -118f), new Vector2(170f, 120f));
			anchorListRect = anchorListObject.GetComponent<RectTransform>();
			anchorListObject.SetActive(false);
			editOnlyObjects.Add(anchorListObject);
		}

		private void CreatePriorityListPanel()
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			priorityListObject = CreateDropdownPanel("PriorityList", new Vector2(174f, -118f), new Vector2(150f, 100f));
			priorityListRect = priorityListObject.GetComponent<RectTransform>();
			priorityListObject.SetActive(false);
			editOnlyObjects.Add(priorityListObject);
		}

		private GameObject CreateDropdownPanel(string name, Vector2 position, Vector2 size)
		{
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Expected O, but got Unknown
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject(name, new Type[3]
			{
				typeof(RectTransform),
				typeof(CanvasRenderer),
				typeof(Image)
			});
			RectTransform component = val.GetComponent<RectTransform>();
			((Transform)component).SetParent((Transform)(object)rootRect, false);
			component.anchorMin = new Vector2(0f, 1f);
			component.anchorMax = new Vector2(0f, 1f);
			component.pivot = new Vector2(0f, 1f);
			component.sizeDelta = size;
			component.anchoredPosition = position;
			((Transform)component).localScale = Vector3.one;
			((Transform)component).localRotation = Quaternion.identity;
			Image component2 = val.GetComponent<Image>();
			((Graphic)component2).color = GridWiseUiTheme.PanelStrong;
			((Graphic)component2).raycastTarget = true;
			AddBorder(component, GridWiseUiTheme.Border, 1f);
			return val;
		}

		private void ToggleZoneList()
		{
			zoneListOpen = !zoneListOpen;
			colorListOpen = false;
			anchorListOpen = false;
			priorityListOpen = false;
			CloseRenamePanel();
			RefreshAllDropdownRows();
		}

		private void ToggleColorList()
		{
			colorListOpen = !colorListOpen;
			zoneListOpen = false;
			anchorListOpen = false;
			priorityListOpen = false;
			CloseRenamePanel();
			RefreshAllDropdownRows();
		}

		private void ToggleAnchorList()
		{
			anchorListOpen = !anchorListOpen;
			zoneListOpen = false;
			colorListOpen = false;
			priorityListOpen = false;
			CloseRenamePanel();
			RefreshAllDropdownRows();
		}

		private void TogglePriorityList()
		{
			priorityListOpen = !priorityListOpen;
			zoneListOpen = false;
			colorListOpen = false;
			anchorListOpen = false;
			CloseRenamePanel();
			RefreshAllDropdownRows();
		}

		private void HideZoneList()
		{
			zoneListOpen = false;
			if ((Object)(object)zoneListObject != (Object)null)
			{
				zoneListObject.SetActive(false);
			}
		}

		private void HideColorList()
		{
			colorListOpen = false;
			if ((Object)(object)colorListObject != (Object)null)
			{
				colorListObject.SetActive(false);
			}
		}

		private void HideAnchorList()
		{
			anchorListOpen = false;
			if ((Object)(object)anchorListObject != (Object)null)
			{
				anchorListObject.SetActive(false);
			}
		}

		private void HidePriorityList()
		{
			priorityListOpen = false;
			if ((Object)(object)priorityListObject != (Object)null)
			{
				priorityListObject.SetActive(false);
			}
		}

		private void OpenRenamePanel()
		{
			CustomZone activeZone = GetActiveZone();
			if (activeZone != null && !((Object)(object)renamePanelObject == (Object)null) && !((Object)(object)renameInputField == (Object)null))
			{
				zoneListOpen = false;
				colorListOpen = false;
				anchorListOpen = false;
				priorityListOpen = false;
				renamePanelOpen = true;
				renamePanelObject.SetActive(true);
				renamePanelObject.transform.SetAsLastSibling();
				renameInputField.text = activeZone.Name ?? string.Empty;
				renameInputField.caretPosition = renameInputField.text.Length;
				renameInputField.selectionAnchorPosition = 0;
				renameInputField.selectionFocusPosition = renameInputField.text.Length;
				((Selectable)renameInputField).Select();
				renameInputField.ActivateInputField();
				EventSystem current = EventSystem.current;
				if ((Object)(object)current != (Object)null)
				{
					current.SetSelectedGameObject(((Component)renameInputField).gameObject);
				}
				Input.imeCompositionMode = (IMECompositionMode)1;
				RefreshAllDropdownRows();
			}
		}

		private void CloseRenamePanel()
		{
			renamePanelOpen = false;
			if ((Object)(object)renameInputField != (Object)null)
			{
				renameInputField.DeactivateInputField();
			}
			EventSystem current = EventSystem.current;
			if ((Object)(object)current != (Object)null && (Object)(object)renameInputField != (Object)null && (Object)(object)current.currentSelectedGameObject == (Object)(object)((Component)renameInputField).gameObject)
			{
				current.SetSelectedGameObject((GameObject)null);
			}
			Input.imeCompositionMode = (IMECompositionMode)0;
			if ((Object)(object)renamePanelObject != (Object)null)
			{
				renamePanelObject.SetActive(false);
			}
		}

		private void ApplyRename()
		{
			if (!((Object)(object)renameInputField == (Object)null))
			{
				if (!CustomZoneService.RenameActiveZone(loadedZones, config, renameInputField.text, saveConfig: true, out var _))
				{
					CloseRenamePanel();
					UpdateTexts();
				}
				else
				{
					SaveLoadedZones();
					CloseRenamePanel();
					NotifyZoneChanged(rebuildLists: true);
				}
			}
		}

		private void HandleRenameKeyboardShortcuts()
		{
			if (IsTextInputActive() && string.IsNullOrEmpty(Input.compositionString))
			{
				Keyboard current = Keyboard.current;
				if (current != null && (((ButtonControl)current.enterKey).wasPressedThisFrame || ((ButtonControl)current.numpadEnterKey).wasPressedThisFrame))
				{
					ApplyRename();
				}
			}
		}

		private void RefreshAllDropdownRows()
		{
			RefreshZoneListRows();
			RefreshColorListRows();
			RefreshAnchorListRows();
			RefreshPriorityListRows();
		}

		private void RefreshZoneListRows()
		{
			//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0171: Unknown result type (might be due to invalid IL or missing references)
			ClearRows(zoneListRows);
			if ((Object)(object)zoneListObject == (Object)null || (Object)(object)zoneListRect == (Object)null)
			{
				return;
			}
			if (!zoneListOpen || loadedZones == null || !IsEditing())
			{
				zoneListObject.SetActive(false);
				return;
			}
			List<CustomZone> orderedZones = GetOrderedZones();
			string b = ((loadedZones != null) ? (loadedZones.ActiveZoneName ?? "") : "");
			float num = 26f;
			float num2 = Mathf.Clamp((float)orderedZones.Count * num + 8f, 42f, 220f);
			zoneListRect.sizeDelta = new Vector2(220f, num2);
			for (int i = 0; i < orderedZones.Count; i++)
			{
				CustomZone capturedZone;
				CustomZone customZone = (capturedZone = orderedZones[i]);
				bool selected = string.Equals(customZone.Name, b, StringComparison.OrdinalIgnoreCase);
				float num3 = -8f - (float)i * num - num * 0.5f;
				string label = (customZone.Enabled ? customZone.Name : (customZone.Name + " (OFF)"));
				GameObject item = CreateColorSelectionRow(zoneListRect, "ZoneRow_" + customZone.Name, label, customZone.Color, selected, new Vector2(0f, num3), 206f, delegate
				{
					SelectActiveZone(capturedZone, saveConfig: true);
					HideZoneList();
					NotifyZoneChanged(rebuildLists: true);
				});
				zoneListRows.Add(item);
			}
			zoneListObject.SetActive(true);
			zoneListObject.transform.SetAsLastSibling();
		}

		private void RefreshColorListRows()
		{
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_0135: Unknown result type (might be due to invalid IL or missing references)
			ClearRows(colorListRows);
			if ((Object)(object)colorListObject == (Object)null || (Object)(object)colorListRect == (Object)null)
			{
				return;
			}
			if (!colorListOpen || !IsEditing())
			{
				colorListObject.SetActive(false);
				return;
			}
			CustomZone activeZone = GetActiveZone();
			string a = ((activeZone != null) ? activeZone.Color : "");
			float num = 26f;
			float num2 = Mathf.Clamp((float)colorNames.Length * num + 8f, 42f, 180f);
			colorListRect.sizeDelta = new Vector2(170f, num2);
			for (int i = 0; i < colorNames.Length; i++)
			{
				string text = colorNames[i];
				string text2 = colorValues[i];
				bool selected = string.Equals(a, text2, StringComparison.OrdinalIgnoreCase);
				float num3 = -8f - (float)i * num - num * 0.5f;
				int capturedIndex = i;
				GameObject item = CreateColorSelectionRow(colorListRect, "ColorRow_" + text, GridWiseUiText.ColorName(text), text2, selected, new Vector2(0f, num3), 156f, delegate
				{
					SelectColor(capturedIndex);
				});
				colorListRows.Add(item);
			}
			colorListObject.SetActive(true);
			colorListObject.transform.SetAsLastSibling();
		}

		private void RefreshAnchorListRows()
		{
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_012b: Unknown result type (might be due to invalid IL or missing references)
			ClearRows(anchorListRows);
			if ((Object)(object)anchorListObject == (Object)null || (Object)(object)anchorListRect == (Object)null)
			{
				return;
			}
			if (!anchorListOpen || !IsEditing())
			{
				anchorListObject.SetActive(false);
				return;
			}
			SortAnchor sortAnchor = GetActiveZone()?.Anchor ?? SortAnchor.TopLeft;
			float num = 26f;
			float num2 = Mathf.Clamp((float)anchorValues.Length * num + 8f, 42f, 140f);
			anchorListRect.sizeDelta = new Vector2(170f, num2);
			for (int i = 0; i < anchorValues.Length; i++)
			{
				SortAnchor sortAnchor2 = anchorValues[i];
				bool selected = sortAnchor2 == sortAnchor;
				float num3 = -8f - (float)i * num - num * 0.5f;
				SortAnchor captured = sortAnchor2;
				GameObject item = CreateTextSelectionRow(anchorListRect, "AnchorRow_" + sortAnchor2, GridWiseUiText.AnchorName(sortAnchor2), selected, new Vector2(0f, num3), 156f, delegate
				{
					SelectAnchor(captured);
				});
				anchorListRows.Add(item);
			}
			anchorListObject.SetActive(true);
			anchorListObject.transform.SetAsLastSibling();
		}

		private void RefreshPriorityListRows()
		{
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_012c: Unknown result type (might be due to invalid IL or missing references)
			ClearRows(priorityListRows);
			if ((Object)(object)priorityListObject == (Object)null || (Object)(object)priorityListRect == (Object)null)
			{
				return;
			}
			if (!priorityListOpen || !IsEditing())
			{
				priorityListObject.SetActive(false);
				return;
			}
			int num = GetActiveZone()?.Priority ?? 100;
			float num2 = 26f;
			float num3 = Mathf.Clamp((float)priorityNames.Length * num2 + 8f, 42f, 120f);
			priorityListRect.sizeDelta = new Vector2(150f, num3);
			for (int i = 0; i < priorityNames.Length; i++)
			{
				string text = priorityNames[i];
				int num4 = priorityValues[i];
				bool selected = num4 == num;
				float num5 = -8f - (float)i * num2 - num2 * 0.5f;
				int captured = num4;
				GameObject item = CreateTextSelectionRow(priorityListRect, "PriorityRow_" + text, GridWiseUiText.PriorityName(text), selected, new Vector2(0f, num5), 136f, delegate
				{
					SelectPriority(captured);
				});
				priorityListRows.Add(item);
			}
			priorityListObject.SetActive(true);
			priorityListObject.transform.SetAsLastSibling();
		}

		private static void ClearRows(List<GameObject> rows)
		{
			foreach (GameObject row in rows)
			{
				if ((Object)(object)row != (Object)null)
				{
					row.SetActive(false);
					Object.Destroy((Object)(object)row);
				}
			}
			rows.Clear();
		}

		private GameObject CreateColorSelectionRow(RectTransform parent, string name, string label, string color, bool selected, Vector2 anchoredPosition, float width, Action onClick)
		{
			//IL_0006: 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_004a: Expected O, but got Unknown
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_012f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0146: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = CreateRowBase(parent, name, selected, anchoredPosition, width, onClick);
			GameObject val2 = new GameObject("ColorSquare", new Type[3]
			{
				typeof(RectTransform),
				typeof(CanvasRenderer),
				typeof(Image)
			});
			RectTransform component = val2.GetComponent<RectTransform>();
			((Transform)component).SetParent((Transform)(object)val.GetComponent<RectTransform>(), false);
			component.anchorMin = new Vector2(0f, 0.5f);
			component.anchorMax = new Vector2(0f, 0.5f);
			component.pivot = new Vector2(0.5f, 0.5f);
			component.sizeDelta = new Vector2(14f, 14f);
			component.anchoredPosition = new Vector2(13f, 0f);
			Image component2 = val2.GetComponent<Image>();
			((Graphic)component2).color = ParseColor(color, new Color(0.5f, 1f, 0.5f, 0.8f));
			((Graphic)component2).raycastTarget = false;
			Text val3 = CreateStretchText(val.GetComponent<RectTransform>(), "Name", label, 12, (TextAnchor)3);
			RectTransform component3 = ((Component)val3).GetComponent<RectTransform>();
			component3.offsetMin = new Vector2(30f, 2f);
			component3.offsetMax = new Vector2(-30f, -2f);
			AddSelectedDot(val.GetComponent<RectTransform>(), selected);
			return val;
		}

		private GameObject CreateTextSelectionRow(RectTransform parent, string name, string label, bool selected, Vector2 anchoredPosition, float width, Action onClick)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = CreateRowBase(parent, name, selected, anchoredPosition, width, onClick);
			Text val2 = CreateStretchText(val.GetComponent<RectTransform>(), "Name", label, 12, (TextAnchor)3);
			RectTransform component = ((Component)val2).GetComponent<RectTransform>();
			component.offsetMin = new Vector2(10f, 2f);
			component.offsetMax = new Vector2(-30f, -2f);
			AddSelectedDot(val.GetComponent<RectTransform>(), selected);
			return val;
		}

		private GameObject CreateRowBase(RectTransform parent, string name, bool selected, Vector2 anchoredPosition, float width, Action onClick)
		{
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Expected O, but got Unknown
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_010c: 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_013b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0145: Expected O, but got Unknown
			GameObject val = new GameObject(name, new Type[4]
			{
				typeof(RectTransform),
				typeof(CanvasRenderer),
				typeof(Image),
				typeof(Button)
			});
			RectTransform component = val.GetComponent<RectTransform>();
			((Transform)component).SetParent((Transform)(object)parent, false);
			component.anchorMin = new Vector2(0f, 1f);
			component.anchorMax = new Vector2(0f, 1f);
			component.pivot = new Vector2(0f, 0.5f);
			component.sizeDelta = new Vector2(width, 24f);
			component.anchoredPosition = anchoredPosition;
			((Transform)component).localScale = Vector3.one;
			((Transform)component).localRotation = Quaternion.identity;
			Image component2 = val.GetComponent<Image>();
			((Graphic)component2).color = (selected ? GridWiseUiTheme.ButtonSelected : GridWiseUiTheme.Button(config));
			((Graphic)component2).raycastTarget = true;
			AddBorder(component, selected ? GridWiseUiTheme.BorderBright : GridWiseUiTheme.Border, 1f);
			Button component3 = val.GetComponent<Button>();
			((Selectable)component3).targetGraphic = (Graphic)(object)component2;
			((UnityEvent)component3.onClick).AddListener((UnityAction)delegate
			{
				onClick?.Invoke();
			});
			return val;
		}

		private void AddSelectedDot(RectTransform parent, bool selected)
		{
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			Text val = CreateStretchText(parent, "SelectedDot", selected ? "●" : "", 16, (TextAnchor)5);
			((Graphic)val).color = ParseColor("#7ED957FF", Color.green);
			RectTransform component = ((Component)val).GetComponent<RectTransform>();
			component.offsetMin = new Vector2(0f, 0f);
			component.offsetMax = new Vector2(-10f, 0f);
		}

		private InputField CreateInputField(RectTransform parent, string name, Vector2 topLeftPosition, Vector2 size)
		{
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Expected O, but got Unknown
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: 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_012f: Unknown result type (might be due to invalid IL or missing references)
			//IL_016d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0184: Unknown result type (might be due to invalid IL or missing references)
			//IL_0192: Unknown result type (might be due to invalid IL or missing references)
			//IL_019d: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b7: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject(name, new Type[4]
			{
				typeof(RectTransform),
				typeof(CanvasRenderer),
				typeof(Image),
				typeof(InputField)
			});
			RectTransform component = val.GetComponent<RectTransform>();
			((Transform)component).SetParent((Transform)(object)parent, false);
			component.anchorMin = new Vector2(0f, 1f);
			component.anchorMax = new Vector2(0f, 1f);
			component.pivot = new Vector2(0f, 1f);
			component.sizeDelta = size;
			component.anchoredPosition = topLeftPosition;
			((Transform)component).localScale = Vector3.one;
			((Transform)component).localRotation = Quaternion.identity;
			Image component2 = val.GetComponent<Image>();
			((Graphic)component2).color = GridWiseUiTheme.Button(config);
			((Graphic)component2).raycastTarget = true;
			AddBorder(component, GridWiseUiTheme.Border, 1f);
			Text val2 = CreateStretchText(component, "Text", string.Empty, 13, (TextAnchor)3);
			RectTransform component3 = ((Component)val2).GetComponent<RectTransform>();
			component3.offsetMin = new Vector2(8f, 2f);
			component3.offsetMax = new Vector2(-8f, -2f);
			val2.supportRichText = false;
			Text val3 = CreateStretchText(component, "Placeholder", GridWiseUiText.RenamePlaceholder, 13, (TextAnchor)3);
			RectTransform component4 = ((Component)val3).GetComponent<RectTransform>();
			component4.offsetMin = new Vector2(8f, 2f);
			component4.offsetMax = new Vector2(-8f, -2f);
			((Graphic)val3).color = new Color(((Graphic)val2).color.r, ((Graphic)val2).color.g, ((Graphic)val2).color.b, 0.45f);
			val3.supportRichText = false;
			InputField component5 = val.GetComponent<InputField>();
			component5.textComponent = val2;
			component5.placeholder = (Graphic)(object)val3;
			component5.lineType = (LineType)0;
			component5.contentType = (ContentType)0;
			component5.characterLimit = 48;
			((Selectable)component5).targetGraphic = (Graphic)(object)component2;
			return component5;
		}

		private Button CreateButton(RectTransform parent, string name, Vector2 topLeftPosition, Vector2 size, string label, bool editOnly)
		{
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Expected O, but got Unknown
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject(name, new Type[4]
			{
				typeof(RectTransform),
				typeof(CanvasRenderer),
				typeof(Image),
				typeof(Button)
			});
			RectTransform component = val.GetComponent<RectTransform>();
			((Transform)component).SetParent((Transform)(object)parent, false);
			component.anchorMin = new Vector2(0f, 1f);
			component.anchorMax = new Vector2(0f, 1f);
			component.pivot = new Vector2(0f, 1f);
			component.sizeDelta = size;
			component.anchoredPosition = topLeftPosition;
			((Transform)component).localScale = Vector3.one;
			((Transform)component).localRotation = Quaternion.identity;
			Image component2 = val.GetComponent<Image>();
			((Graphic)component2).color = GridWiseUiTheme.Button(config);
			((Graphic)component2).raycastTarget = true;
			AddBorder(component, GridWiseUiTheme.Border, 1f);
			Button component3 = val.GetComponent<Button>();
			((Selectable)component3).targetGraphic = (Graphic)(object)component2;
			Text val2 = CreateStretchText(component, "Text", label, 13, (TextAnchor)4);
			((Graphic)val2).raycastTarget = false;
			if (editOnly)
			{
				editOnlyObjects.Add(val);
			}
			return component3;
		}

		private static void AddBorder(RectTransform parent, Color color, float thickness)
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Unknown result type (might be due to invalid IL or m