Decompiled source of Quickplay v0.1.0

Quickplay.dll

Decompiled 3 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using Cysharp.Threading.Tasks;
using Cysharp.Threading.Tasks.CompilerServices;
using Epic.OnlineServices;
using Epic.OnlineServices.Connect;
using Epic.OnlineServices.Lobby;
using HarmonyLib;
using Mirror;
using PlayEveryWare.EpicOnlineServices;
using Steamworks;
using Steamworks.Data;
using TMPro;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.Localization;
using UnityEngine.Localization.Components;
using UnityEngine.Localization.Settings;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyVersion("0.0.0.0")]
namespace Quickplay;

[HarmonyPatch(typeof(MainMenu))]
internal static class MainMenuPatches
{
	private static bool _steamRelayWarmedUp;

	[HarmonyPatch("Awake")]
	[HarmonyPostfix]
	private static void AwakePostfix(MainMenu __instance)
	{
		try
		{
			if (!((Object)(object)__instance == (Object)null) && Plugin.Enabled.Value)
			{
				MainMenuQuickplayUI.Inject(__instance);
				WarmUpSteamRelayPingData();
				QuickplayAutoRequeue.OnMainMenuLoaded(__instance);
			}
		}
		catch (Exception ex)
		{
			Plugin.Log.LogError((object)("Error in MainMenu.Awake postfix: " + ex));
		}
	}

	[HarmonyPatch("OnDestroy")]
	[HarmonyPrefix]
	private static void OnDestroyPrefix(MainMenu __instance)
	{
		try
		{
			QuickplayAutoRequeue.CancelActiveCountdown("MainMenu destroyed");
			QuickplayController.CancelActiveSession("MainMenu destroyed");
		}
		catch (Exception ex)
		{
			Plugin.Log.LogError((object)("Error in MainMenu.OnDestroy prefix: " + ex));
		}
	}

	private static void WarmUpSteamRelayPingData()
	{
		if (_steamRelayWarmedUp)
		{
			return;
		}
		try
		{
			if (SteamClient.IsValid)
			{
				_steamRelayWarmedUp = true;
				if (!SteamNetworkingUtils.LocalPingLocation.HasValue)
				{
					SteamNetworkingUtils.InitRelayNetworkAccess();
					Plugin.LogDebug("Initiated Steam SDR relay ping warmup on main menu load.");
				}
			}
		}
		catch (Exception ex)
		{
			Plugin.LogDebug("Steam SDR relay warmup skipped: " + ex.Message);
		}
	}
}
[HarmonyPatch(typeof(BNetworkManager))]
internal static class NetworkManagerPatches
{
	[HarmonyPatch("OnStopClient")]
	[HarmonyPrefix]
	private static void OnStopClientPrefix()
	{
		try
		{
			if (!QuickplayController.IsRunning && !SingletonBehaviour<MainMenu>.HasInstance && BEosLobbyManager.CurrentLobby != null && BEosLobbyManager.CurrentLobby.IsValid())
			{
				QuickplayController.RecordRecentlyLeftLobby(BEosLobbyManager.CurrentLobby.Id);
			}
			QuickplayAutoRequeue.OnClientStopped();
		}
		catch (Exception ex)
		{
			Plugin.Log.LogError((object)("Error in BNetworkManager.OnStopClient prefix: " + ex));
		}
	}

	[HarmonyPatch("DisplayDisconnectReasonMessage", new Type[] { typeof(DisconnectReason) })]
	[HarmonyPrefix]
	private static void DisplayDisconnectReasonMessagePrefix(DisconnectReason reason)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		try
		{
			QuickplayAutoRequeue.OnDisconnectReason(reason);
		}
		catch (Exception ex)
		{
			Plugin.Log.LogError((object)("Error in BNetworkManager.DisplayDisconnectReasonMessage prefix: " + ex));
		}
	}
}
[HarmonyPatch(typeof(CourseManager))]
internal static class CourseManagerPatches
{
	[HarmonyPatch("OnStartClient")]
	[HarmonyPostfix]
	private static void OnStartClientPostfix()
	{
		try
		{
			QuickplayAutoRequeue.OnCourseStartClient();
		}
		catch (Exception ex)
		{
			Plugin.Log.LogError((object)("Error in CourseManager.OnStartClient postfix: " + ex));
		}
	}

	[HarmonyPatch("UserCode_RpcInformEndingCourse")]
	[HarmonyPrefix]
	private static bool UserCodeRpcInformEndingCoursePrefix()
	{
		try
		{
			return QuickplayAutoRequeue.OnCourseEndingRpc();
		}
		catch (Exception ex)
		{
			Plugin.Log.LogError((object)("Error in CourseManager.UserCode_RpcInformEndingCourse prefix: " + ex));
			return true;
		}
	}
}
[HarmonyPatch(typeof(DrivingRangeManager))]
internal static class DrivingRangeManagerPatches
{
	[HarmonyPatch("Awake")]
	[HarmonyPostfix]
	private static void AwakePostfix()
	{
		try
		{
			QuickplayAutoRequeue.OnDrivingRangeEntered();
		}
		catch (Exception ex)
		{
			Plugin.Log.LogError((object)("Error in DrivingRangeManager.Awake postfix: " + ex));
		}
	}
}
[HarmonyPatch(typeof(PauseMenu))]
internal static class PauseMenuPatches
{
	[HarmonyPatch("Awake")]
	[HarmonyPrefix]
	private static void AwakePrefix(PauseMenu __instance)
	{
		try
		{
			PauseMenuQuickplayUI.InjectBeforeAwake(__instance);
		}
		catch (Exception ex)
		{
			Plugin.Log.LogError((object)("Error in PauseMenu.Awake prefix: " + ex));
		}
	}

	[HarmonyPatch("UpdateInviteButtonEnabled")]
	[HarmonyPostfix]
	private static void UpdateInviteButtonEnabledPostfix(PauseMenu __instance)
	{
		try
		{
			PauseMenuQuickplayUI.UpdateVisibility(__instance);
		}
		catch (Exception ex)
		{
			Plugin.Log.LogError((object)("Error in PauseMenu.UpdateInviteButtonEnabled postfix: " + ex));
		}
	}

	[HarmonyPatch("OnRectTransformDimensionsChange")]
	[HarmonyPostfix]
	private static void OnRectTransformDimensionsChangePostfix()
	{
		try
		{
			PauseMenuQuickplayUI.OnDimensionsChanged();
		}
		catch (Exception ex)
		{
			Plugin.Log.LogError((object)("Error in PauseMenu.OnRectTransformDimensionsChange postfix: " + ex));
		}
	}
}
internal static class MainMenuQuickplayUI
{
	private const string QuickplayObjectName = "Quickplay";

	private const float VanillaLogoHeight = 380.2f;

	private const float CompactLogoHeight = 340f;

	private const float CompactSpacingHeight = 4f;

	private const float CompactButtonHeight = 84f;

	private const float VanillaButtonHeight = 92f;

	private const float CompactGroupSpacing = 5f;

	private const int CompactBottomPadding = 68;

	private const float FontScaleRatio = 0.94f;

	private static readonly Dictionary<string, float> CompactButtonWidths = new Dictionary<string, float>(StringComparer.OrdinalIgnoreCase)
	{
		{ "Quickplay", 724f },
		{ "Start game", 636f },
		{ "Join game", 554f },
		{ "Settings", 492f },
		{ "Credits", 462f },
		{ "Achievements", 508f },
		{ "Exit game", 592f }
	};

	private static readonly FieldInfo StartGameButtonField = AccessTools.Field(typeof(MainMenu), "startGameButton");

	private static readonly FieldInfo LobbyInitMenuField = AccessTools.Field(typeof(MainMenu), "lobbyInitializationMenu");

	private static readonly FieldInfo MainMenuButtonLabelField = AccessTools.Field(typeof(MainMenuButton), "label");

	private static readonly FieldInfo MainMenuButtonLocAdjustmentsField = AccessTools.Field(typeof(MainMenuButton), "locAdjustments");

	private static readonly FieldInfo MainMenuButtonDefaultWidthField = AccessTools.Field(typeof(MainMenuButton), "defaultWidth");

	private static readonly FieldInfo MainMenuButtonDefaultFontSizeField = AccessTools.Field(typeof(MainMenuButton), "defaultFontSize");

	private static readonly FieldInfo MainMenuButtonRectTransformField = AccessTools.Field(typeof(MainMenuButton), "rectTransform");

	private static readonly MethodInfo MainMenuButtonOnLocaleChangedMethod = AccessTools.Method(typeof(MainMenuButton), "OnLocaleChanged", (Type[])null, (Type[])null);

	private static readonly FieldInfo LocAdjustmentFontSizeField = ((MainMenuButtonLocAdjustmentsField?.FieldType.GetElementType() != null) ? AccessTools.Field(MainMenuButtonLocAdjustmentsField.FieldType.GetElementType(), "fontSize") : null);

	private static GameObject _quickplayObject;

	private static TextMeshProUGUI[] _quickplayLabels;

	internal static void Cleanup()
	{
		if ((Object)(object)_quickplayObject != (Object)null)
		{
			Object.Destroy((Object)(object)_quickplayObject);
			_quickplayObject = null;
		}
		_quickplayLabels = null;
	}

	internal static void SetVisible(bool visible)
	{
		if (!((Object)(object)_quickplayObject != (Object)null) || _quickplayObject.activeSelf == visible)
		{
			return;
		}
		_quickplayObject.SetActive(visible);
		Transform parent = _quickplayObject.transform.parent;
		if ((Object)(object)parent != (Object)null)
		{
			SingleAxisNavigationGroup component = ((Component)parent).GetComponent<SingleAxisNavigationGroup>();
			if ((Object)(object)component != (Object)null)
			{
				component.UpdateNavigation();
			}
		}
	}

	internal static void RefreshLabel()
	{
		if (_quickplayLabels == null)
		{
			return;
		}
		string text = QuickplayLocalization.Get(QuickplayTextKey.Quickplay);
		for (int i = 0; i < _quickplayLabels.Length; i++)
		{
			if ((Object)(object)_quickplayLabels[i] != (Object)null)
			{
				((TMP_Text)_quickplayLabels[i]).text = text;
			}
		}
	}

	internal static LobbyInitializationMenu GetLobbyInitializationMenu(MainMenu mainMenu)
	{
		if ((Object)(object)mainMenu == (Object)null || LobbyInitMenuField == null)
		{
			return null;
		}
		object? value = LobbyInitMenuField.GetValue(mainMenu);
		return (LobbyInitializationMenu)((value is LobbyInitializationMenu) ? value : null);
	}

	internal static void Inject(MainMenu mainMenu)
	{
		try
		{
			if (StartGameButtonField == null)
			{
				Plugin.Log.LogError((object)"Could not reflect MainMenu.startGameButton; skipping Quickplay button injection.");
				return;
			}
			object? value = StartGameButtonField.GetValue(mainMenu);
			Button val = (Button)((value is Button) ? value : null);
			if ((Object)(object)val == (Object)null)
			{
				Plugin.Log.LogError((object)"MainMenu.startGameButton was null; skipping Quickplay button injection.");
				return;
			}
			Transform parent = ((Component)val).transform.parent;
			if ((Object)(object)parent == (Object)null)
			{
				Plugin.Log.LogError((object)"Start game button has no parent container; skipping Quickplay button injection.");
				return;
			}
			Transform val2 = parent.Find("Quickplay");
			if ((Object)(object)val2 != (Object)null)
			{
				_quickplayObject = ((Component)val2).gameObject;
				_quickplayLabels = ((Component)val2).GetComponentsInChildren<TextMeshProUGUI>(true);
				RefreshLabel();
				return;
			}
			CompactExistingLayout(parent);
			int siblingIndex = ((Component)val).transform.GetSiblingIndex();
			GameObject val3 = CreateClonedButton(mainMenu, val, parent, siblingIndex);
			if (!((Object)(object)val3 == (Object)null))
			{
				_quickplayObject = val3;
				RectTransform val4 = (RectTransform)(object)((parent is RectTransform) ? parent : null);
				if ((Object)(object)val4 != (Object)null)
				{
					LayoutRebuilder.ForceRebuildLayoutImmediate(val4);
				}
				SingleAxisNavigationGroup component = ((Component)parent).GetComponent<SingleAxisNavigationGroup>();
				if ((Object)(object)component != (Object)null)
				{
					component.UpdateNavigation();
				}
				MenuNavigation component2 = ((Component)parent).GetComponent<MenuNavigation>();
				if ((Object)(object)component2 != (Object)null && InputManager.UsingGamepad)
				{
					component2.Reselect();
				}
				Plugin.LogDebug($"Injected Quickplay button at sibling index {siblingIndex} under '{((Object)parent).name}'.");
			}
		}
		catch (Exception ex)
		{
			Plugin.Log.LogError((object)("Failed to inject Quickplay main menu button: " + ex));
		}
	}

	private static GameObject CreateClonedButton(MainMenu mainMenu, Button templateButton, Transform buttonsParent, int insertIndex)
	{
		//IL_0012: Unknown result type (might be due to invalid IL or missing references)
		//IL_0018: Expected O, but got Unknown
		//IL_01f5: Unknown result type (might be due to invalid IL or missing references)
		//IL_0208: Unknown result type (might be due to invalid IL or missing references)
		//IL_0226: Unknown result type (might be due to invalid IL or missing references)
		//IL_0230: Expected O, but got Unknown
		//IL_023e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0248: Expected O, but got Unknown
		GameObject val = new GameObject("__QuickplayCloneStage");
		val.SetActive(false);
		try
		{
			GameObject val2 = Object.Instantiate<GameObject>(((Component)templateButton).gameObject, val.transform, false);
			((Object)val2).name = "Quickplay";
			LocalizeStringEvent[] componentsInChildren = val2.GetComponentsInChildren<LocalizeStringEvent>(true);
			for (int i = 0; i < componentsInChildren.Length; i++)
			{
				Object.DestroyImmediate((Object)(object)componentsInChildren[i]);
			}
			MainMenuButton component = val2.GetComponent<MainMenuButton>();
			if ((Object)(object)component != (Object)null && MainMenuButtonLocAdjustmentsField != null)
			{
				Type elementType = MainMenuButtonLocAdjustmentsField.FieldType.GetElementType();
				if (elementType != null)
				{
					MainMenuButtonLocAdjustmentsField.SetValue(component, Array.CreateInstance(elementType, 0));
				}
			}
			float num = 0f;
			MainMenuButton component2 = ((Component)templateButton).GetComponent<MainMenuButton>();
			if ((Object)(object)component2 != (Object)null && MainMenuButtonDefaultFontSizeField != null && MainMenuButtonDefaultFontSizeField.GetValue(component2) is float num2 && num2 > 0f)
			{
				num = num2;
			}
			TextMeshProUGUI[] componentsInChildren2 = val2.GetComponentsInChildren<TextMeshProUGUI>(true);
			string text = QuickplayLocalization.Get(QuickplayTextKey.Quickplay);
			for (int j = 0; j < componentsInChildren2.Length; j++)
			{
				((TMP_Text)componentsInChildren2[j]).text = text;
				if (((Component)componentsInChildren2[j]).gameObject.activeSelf)
				{
					((TMP_Text)componentsInChildren2[j]).textWrappingMode = (TextWrappingModes)0;
					((TMP_Text)componentsInChildren2[j]).overflowMode = (TextOverflowModes)1;
					((TMP_Text)componentsInChildren2[j]).enableAutoSizing = true;
					float num3 = ((num > 0f) ? num : ((TMP_Text)componentsInChildren2[j]).fontSize);
					if (num3 > 0f)
					{
						((TMP_Text)componentsInChildren2[j]).fontSizeMax = num3;
						((TMP_Text)componentsInChildren2[j]).fontSizeMin = Mathf.Max(14f, num3 * 0.6f);
						((TMP_Text)componentsInChildren2[j]).fontSize = num3;
					}
				}
			}
			_quickplayLabels = componentsInChildren2;
			RectTransform component3 = val2.GetComponent<RectTransform>();
			if ((Object)(object)component3 != (Object)null)
			{
				float num4 = CompactButtonWidths["Quickplay"];
				component3.pivot = new Vector2(0f, 0.5f);
				component3.sizeDelta = new Vector2(num4, 84f);
			}
			Button component4 = val2.GetComponent<Button>();
			if ((Object)(object)component4 != (Object)null)
			{
				component4.onClick = new ButtonClickedEvent();
				((UnityEvent)component4.onClick).AddListener((UnityAction)delegate
				{
					QuickplayController.StartQuickplay(mainMenu);
				});
			}
			val2.SetActive(true);
			val2.transform.SetParent(buttonsParent, false);
			val2.transform.SetSiblingIndex(insertIndex);
			return val2;
		}
		finally
		{
			Object.Destroy((Object)(object)val);
		}
	}

	private static void CompactExistingLayout(Transform buttonsParent)
	{
		//IL_005e: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
		//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
		//IL_0077: 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)
		//IL_009e: 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_00c5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
		VerticalLayoutGroup component = ((Component)buttonsParent).GetComponent<VerticalLayoutGroup>();
		if ((Object)(object)component != (Object)null)
		{
			((HorizontalOrVerticalLayoutGroup)component).spacing = 5f;
			((LayoutGroup)component).padding.bottom = 68;
		}
		for (int i = 0; i < buttonsParent.childCount; i++)
		{
			Transform child = buttonsParent.GetChild(i);
			RectTransform val = (RectTransform)(object)((child is RectTransform) ? child : null);
			if ((Object)(object)val == (Object)null)
			{
				continue;
			}
			if (string.Equals(((Object)child).name, "Logo", StringComparison.OrdinalIgnoreCase))
			{
				float num = ((val.sizeDelta.y > 0f) ? val.sizeDelta.y : 380.2f);
				float num2 = 340f / num;
				val.sizeDelta = new Vector2(val.sizeDelta.x, 340f);
				Transform val2 = child.Find("Pivot");
				if ((Object)(object)val2 != (Object)null)
				{
					val2.localScale *= num2;
				}
				continue;
			}
			if (string.Equals(((Object)child).name, "Spacing", StringComparison.OrdinalIgnoreCase))
			{
				val.sizeDelta = new Vector2(val.sizeDelta.x, 4f);
				continue;
			}
			MainMenuButton component2 = ((Component)child).GetComponent<MainMenuButton>();
			if (!((Object)(object)component2 == (Object)null))
			{
				if (!CompactButtonWidths.TryGetValue(((Object)child).name, out var value))
				{
					value = val.sizeDelta.x;
				}
				ApplyCompactedButtonMetrics(component2, val, value, 84f);
			}
		}
	}

	private static void ApplyCompactedButtonMetrics(MainMenuButton mmButton, RectTransform rectTransform, float targetWidth, float targetHeight)
	{
		//IL_0021: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
		bool num = MainMenuButtonRectTransformField != null && MainMenuButtonRectTransformField.GetValue(mmButton) != null;
		rectTransform.sizeDelta = new Vector2(targetWidth, targetHeight);
		TextMeshProUGUI val = (TextMeshProUGUI)((MainMenuButtonLabelField != null) ? ((object)/*isinst with value type is only supported in some contexts*/) : ((object)((Component)mmButton).GetComponentInChildren<TextMeshProUGUI>(false)));
		ScaleLocAdjustmentFontSizes(mmButton, 0.94f);
		if (num)
		{
			if (MainMenuButtonDefaultWidthField != null)
			{
				MainMenuButtonDefaultWidthField.SetValue(mmButton, targetWidth);
			}
			if (MainMenuButtonDefaultFontSizeField != null && MainMenuButtonDefaultFontSizeField.GetValue(mmButton) is float num2 && num2 > 0f)
			{
				float num3 = num2 * 0.94f;
				MainMenuButtonDefaultFontSizeField.SetValue(mmButton, num3);
			}
			MainMenuButtonOnLocaleChangedMethod?.Invoke(mmButton, null);
		}
		else if ((Object)(object)val != (Object)null && rectTransform.sizeDelta.y < 92f)
		{
			((TMP_Text)val).fontSize = ((TMP_Text)val).fontSize * 0.94f;
		}
	}

	private static void ScaleLocAdjustmentFontSizes(MainMenuButton mmButton, float ratio)
	{
		if ((Object)(object)mmButton == (Object)null || MainMenuButtonLocAdjustmentsField == null || LocAdjustmentFontSizeField == null || !(MainMenuButtonLocAdjustmentsField.GetValue(mmButton) is Array { Length: not 0 } array))
		{
			return;
		}
		for (int i = 0; i < array.Length; i++)
		{
			object value = array.GetValue(i);
			if (value != null && LocAdjustmentFontSizeField.GetValue(value) is float num && num > 0f)
			{
				LocAdjustmentFontSizeField.SetValue(value, num * ratio);
				array.SetValue(value, i);
			}
		}
	}
}
internal static class PauseMenuQuickplayUI
{
	private sealed class ButtonOriginalMetrics
	{
		internal Button Button;

		internal RectTransform Rect;

		internal LayoutElement LayoutElement;

		internal MainMenuButton MmButton;

		internal TMP_Text Label;

		internal float OriginalHeight;

		internal float OriginalPreferredHeight;

		internal float OriginalMinHeight;

		internal float OriginalFontSize;

		internal float[] OriginalLocFontSizes;
	}

	private sealed class LayoutSnapshot
	{
		internal PauseMenu Menu;

		internal RectTransform ContainerRect;

		internal VerticalLayoutGroup LayoutGroup;

		internal float OriginalSpacing;

		internal int OriginalPaddingLeft;

		internal int OriginalPaddingRight;

		internal int OriginalPaddingTop;

		internal int OriginalPaddingBottom;

		internal float OriginalHorizontalOffset;

		internal float ReferenceButtonHeight;

		internal readonly List<ButtonOriginalMetrics> Buttons = new List<ButtonOriginalMetrics>();

		internal int LastAppliedActiveCount = -1;

		internal int LastContainerChildCount = -1;
	}

	private const string ButtonObjectName = "Quickplay Find New Match Button";

	private const int VanillaMaxButtonCount = 6;

	private const float MinLeftScreenPadding = 20f;

	private static readonly MethodInfo UpdateButtonOffsetsMethod = AccessTools.Method(typeof(PauseMenu), "UpdateButtonOffsets", (Type[])null, (Type[])null);

	private static readonly FieldInfo MainMenuButtonLocAdjustmentsField = AccessTools.Field(typeof(MainMenuButton), "locAdjustments");

	private static readonly FieldInfo MainMenuButtonDefaultWidthField = AccessTools.Field(typeof(MainMenuButton), "defaultWidth");

	private static readonly FieldInfo MainMenuButtonDefaultFontSizeField = AccessTools.Field(typeof(MainMenuButton), "defaultFontSize");

	private static readonly FieldInfo MainMenuButtonLabelField = AccessTools.Field(typeof(MainMenuButton), "label");

	private static readonly FieldInfo MainMenuButtonRectTransformField = AccessTools.Field(typeof(MainMenuButton), "rectTransform");

	private static readonly MethodInfo MainMenuButtonOnLocaleChangedMethod = AccessTools.Method(typeof(MainMenuButton), "OnLocaleChanged", (Type[])null, (Type[])null);

	private static readonly FieldInfo LocAdjustmentFontSizeField = ((MainMenuButtonLocAdjustmentsField?.FieldType.GetElementType() != null) ? AccessTools.Field(MainMenuButtonLocAdjustmentsField.FieldType.GetElementType(), "fontSize") : null);

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

	private static GameObject _buttonObject;

	private static TMP_Text _buttonLabel;

	private static Vector4 _origLabelMargin;

	private static bool _hasOrigLabelMargin;

	private static LayoutSnapshot _snapshot;

	internal static void Cleanup()
	{
		if ((Object)(object)_buttonObject != (Object)null)
		{
			Object.Destroy((Object)(object)_buttonObject);
			_buttonObject = null;
		}
		_buttonLabel = null;
		_hasOrigLabelMargin = false;
		_snapshot = null;
	}

	internal static void RefreshVisibilityIfActive()
	{
		if (_snapshot != null && (Object)(object)_snapshot.Menu != (Object)null)
		{
			UpdateVisibility(_snapshot.Menu);
		}
	}

	internal static void OnDimensionsChanged()
	{
		if ((Object)(object)_buttonObject != (Object)null && _buttonObject.activeInHierarchy)
		{
			UpdateLabelSafeLeftMargin();
		}
	}

	internal static void InjectBeforeAwake(PauseMenu pauseMenu)
	{
		if ((Object)(object)pauseMenu == (Object)null || !Plugin.Enabled.Value)
		{
			return;
		}
		if ((Object)(object)pauseMenu.menuButtonContainer == (Object)null || (Object)(object)pauseMenu.exitGameButton == (Object)null)
		{
			Plugin.Log.LogWarning((object)"PauseMenu button container or exitGameButton is null; skipping Pause Menu Quickplay injection.");
			return;
		}
		Transform transform = pauseMenu.menuButtonContainer.transform;
		Transform val = transform.Find("Quickplay Find New Match Button");
		if ((Object)(object)val != (Object)null)
		{
			_buttonObject = ((Component)val).gameObject;
			TMP_Text componentInChildren = ((Component)val).GetComponentInChildren<TMP_Text>(true);
			if (componentInChildren != _buttonLabel)
			{
				_buttonLabel = componentInChildren;
				_hasOrigLabelMargin = false;
				CaptureOriginalLabelMargin();
			}
			RefreshLabel();
			if (_snapshot == null || (Object)(object)_snapshot.Menu != (Object)(object)pauseMenu)
			{
				_snapshot = CaptureLayoutSnapshot(pauseMenu, transform);
			}
			return;
		}
		int siblingIndex = ((Component)pauseMenu.exitGameButton).transform.GetSiblingIndex();
		GameObject val2 = CreateClonedButton(((Component)pauseMenu.exitGameButton).gameObject, transform, siblingIndex);
		if (!((Object)(object)val2 == (Object)null))
		{
			_buttonObject = val2;
			_buttonLabel = val2.GetComponentInChildren<TMP_Text>(true);
			_hasOrigLabelMargin = false;
			CaptureOriginalLabelMargin();
			RefreshLabel();
			val2.SetActive(false);
			_snapshot = CaptureLayoutSnapshot(pauseMenu, transform);
			Plugin.LogDebug($"Injected Pause Menu 'Find new match' button at sibling index {siblingIndex} (refHeight={_snapshot.ReferenceButtonHeight:F1}, origSpacing={_snapshot.OriginalSpacing:F1}, origHorizOffset={_snapshot.OriginalHorizontalOffset:F1}).");
		}
	}

	internal static void UpdateVisibility(PauseMenu pauseMenu)
	{
		try
		{
			if ((Object)(object)pauseMenu == (Object)null || (Object)(object)_buttonObject == (Object)null)
			{
				return;
			}
			bool flag = Plugin.Enabled != null && Plugin.Enabled.Value && NetworkClient.active && !NetworkServer.active && !BNetworkManager.CurrentlyPlayingOffline && !BNetworkManager.IsOfflineOrLoggedOut;
			bool num = _buttonObject.activeSelf != flag;
			if (num)
			{
				_buttonObject.SetActive(flag);
			}
			if ((Object)(object)pauseMenu.menuButtonContainer != (Object)null)
			{
				Transform transform = pauseMenu.menuButtonContainer.transform;
				if (_snapshot == null || (Object)(object)_snapshot.Menu != (Object)(object)pauseMenu)
				{
					_snapshot = CaptureLayoutSnapshot(pauseMenu, transform);
				}
				else if (transform.childCount != _snapshot.LastContainerChildCount)
				{
					SyncNewContainerButtons(_snapshot, transform);
				}
			}
			bool flag2 = ApplyResponsiveLayout(pauseMenu);
			if (num || flag2)
			{
				if (UpdateButtonOffsetsMethod != null)
				{
					UpdateButtonOffsetsMethod.Invoke(pauseMenu, null);
				}
				SyncMainMenuButtonDefaultWidths(_snapshot);
				if (_snapshot != null && (Object)(object)_snapshot.ContainerRect != (Object)null)
				{
					LayoutRebuilder.ForceRebuildLayoutImmediate(_snapshot.ContainerRect);
				}
			}
			if (flag)
			{
				UpdateLabelSafeLeftMargin();
			}
		}
		catch (Exception ex)
		{
			Plugin.Log.LogError((object)("Error in PauseMenuQuickplayUI.UpdateVisibility: " + ex));
		}
	}

	internal static void RefreshLabel()
	{
		if ((Object)(object)_buttonLabel != (Object)null)
		{
			_buttonLabel.text = QuickplayLocalization.Get(QuickplayTextKey.FindNewMatch);
			float maxFontSize = ((_buttonLabel.fontSizeMax > 0f) ? _buttonLabel.fontSizeMax : _buttonLabel.fontSize);
			ConfigureSingleLineAutoSize(_buttonLabel, maxFontSize);
		}
		if (_snapshot != null && (Object)(object)_snapshot.Menu != (Object)null && (Object)(object)_buttonObject != (Object)null && _buttonObject.activeInHierarchy)
		{
			if (UpdateButtonOffsetsMethod != null)
			{
				UpdateButtonOffsetsMethod.Invoke(_snapshot.Menu, null);
			}
			SyncMainMenuButtonDefaultWidths(_snapshot);
			UpdateLabelSafeLeftMargin();
		}
		else if ((Object)(object)_buttonLabel != (Object)null)
		{
			UpdateLabelSafeLeftMargin();
		}
	}

	private static GameObject CreateClonedButton(GameObject template, Transform container, int insertIndex)
	{
		//IL_0005: Unknown result type (might be due to invalid IL or missing references)
		//IL_000b: Expected O, but got Unknown
		//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b7: Expected O, but got Unknown
		//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00cf: Expected O, but got Unknown
		GameObject val = new GameObject("__QuickplayPauseCloneStage");
		val.SetActive(false);
		try
		{
			GameObject val2 = Object.Instantiate<GameObject>(template, val.transform, false);
			((Object)val2).name = "Quickplay Find New Match Button";
			LocalizeStringEvent[] componentsInChildren = val2.GetComponentsInChildren<LocalizeStringEvent>(true);
			for (int i = 0; i < componentsInChildren.Length; i++)
			{
				Object.DestroyImmediate((Object)(object)componentsInChildren[i]);
			}
			MainMenuButton component = val2.GetComponent<MainMenuButton>();
			if ((Object)(object)component != (Object)null && MainMenuButtonLocAdjustmentsField != null)
			{
				Type elementType = MainMenuButtonLocAdjustmentsField.FieldType.GetElementType();
				if (elementType != null)
				{
					MainMenuButtonLocAdjustmentsField.SetValue(component, Array.CreateInstance(elementType, 0));
				}
			}
			Button component2 = val2.GetComponent<Button>();
			if ((Object)(object)component2 != (Object)null)
			{
				component2.onClick = new ButtonClickedEvent();
				((UnityEvent)component2.onClick).AddListener(new UnityAction(QuickplayAutoRequeue.TriggerImmediateRequeueFromPauseMenu));
			}
			val2.SetActive(false);
			val2.transform.SetParent(container, false);
			val2.transform.SetSiblingIndex(insertIndex);
			return val2;
		}
		finally
		{
			Object.Destroy((Object)(object)val);
		}
	}

	private static LayoutSnapshot CaptureLayoutSnapshot(PauseMenu pauseMenu, Transform container)
	{
		VerticalLayoutGroup component = ((Component)container).GetComponent<VerticalLayoutGroup>();
		LayoutSnapshot obj = new LayoutSnapshot
		{
			Menu = pauseMenu,
			ContainerRect = (RectTransform)(object)((container is RectTransform) ? container : null),
			LayoutGroup = component,
			OriginalSpacing = (((Object)(object)component != (Object)null) ? ((HorizontalOrVerticalLayoutGroup)component).spacing : 0f),
			OriginalPaddingLeft = (((Object)(object)component != (Object)null) ? ((LayoutGroup)component).padding.left : 0),
			OriginalPaddingRight = (((Object)(object)component != (Object)null) ? ((LayoutGroup)component).padding.right : 0),
			OriginalPaddingTop = (((Object)(object)component != (Object)null) ? ((LayoutGroup)component).padding.top : 0),
			OriginalPaddingBottom = (((Object)(object)component != (Object)null) ? ((LayoutGroup)component).padding.bottom : 0),
			OriginalHorizontalOffset = pauseMenu.buttonHorizontalOffset,
			ReferenceButtonHeight = 0f,
			LastContainerChildCount = container.childCount
		};
		SyncNewContainerButtons(obj, container);
		return obj;
	}

	private static void SyncNewContainerButtons(LayoutSnapshot snapshot, Transform container)
	{
		//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c6: 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)
		snapshot.LastContainerChildCount = container.childCount;
		Button[] componentsInChildren = ((Component)container).GetComponentsInChildren<Button>(true);
		bool flag = false;
		foreach (Button val in componentsInChildren)
		{
			if ((Object)(object)val == (Object)null)
			{
				continue;
			}
			bool flag2 = false;
			for (int j = 0; j < snapshot.Buttons.Count; j++)
			{
				if ((Object)(object)snapshot.Buttons[j].Button == (Object)(object)val)
				{
					flag2 = true;
					break;
				}
			}
			if (!flag2)
			{
				RectTransform component = ((Component)val).GetComponent<RectTransform>();
				LayoutElement component2 = ((Component)val).GetComponent<LayoutElement>();
				MainMenuButton component3 = ((Component)val).GetComponent<MainMenuButton>();
				TMP_Text buttonLabel = GetButtonLabel(val, component3);
				float num = (((Object)(object)component != (Object)null) ? component.sizeDelta.y : 0f);
				if (num <= 0f && (Object)(object)component != (Object)null)
				{
					Rect rect = component.rect;
					num = ((Rect)(ref rect)).height;
				}
				float num2 = (((Object)(object)component2 != (Object)null) ? component2.preferredHeight : (-1f));
				float originalMinHeight = (((Object)(object)component2 != (Object)null) ? component2.minHeight : (-1f));
				float originalFontSize = GetOriginalFontSize(component3, buttonLabel);
				float[] originalLocFontSizes = CaptureLocAdjustmentFontSizes(component3);
				if (snapshot.ReferenceButtonHeight <= 0f)
				{
					snapshot.ReferenceButtonHeight = ((num2 > 0f) ? num2 : num);
				}
				snapshot.Buttons.Add(new ButtonOriginalMetrics
				{
					Button = val,
					Rect = component,
					LayoutElement = component2,
					MmButton = component3,
					Label = buttonLabel,
					OriginalHeight = num,
					OriginalPreferredHeight = num2,
					OriginalMinHeight = originalMinHeight,
					OriginalFontSize = originalFontSize,
					OriginalLocFontSizes = originalLocFontSizes
				});
				flag = true;
			}
		}
		if (flag)
		{
			snapshot.LastAppliedActiveCount = -1;
		}
	}

	private static void SyncMainMenuButtonDefaultWidths(LayoutSnapshot snapshot)
	{
		//IL_0044: Unknown result type (might be due to invalid IL or missing references)
		if (snapshot == null || MainMenuButtonDefaultWidthField == null)
		{
			return;
		}
		for (int i = 0; i < snapshot.Buttons.Count; i++)
		{
			ButtonOriginalMetrics buttonOriginalMetrics = snapshot.Buttons[i];
			if ((Object)(object)buttonOriginalMetrics.MmButton != (Object)null && (Object)(object)buttonOriginalMetrics.Rect != (Object)null)
			{
				float x = buttonOriginalMetrics.Rect.sizeDelta.x;
				if (x > 0f)
				{
					MainMenuButtonDefaultWidthField.SetValue(buttonOriginalMetrics.MmButton, x);
				}
			}
		}
	}

	private static bool ApplyResponsiveLayout(PauseMenu pauseMenu)
	{
		if (_snapshot == null || (Object)(object)_snapshot.Menu != (Object)(object)pauseMenu)
		{
			return false;
		}
		int num = 0;
		for (int i = 0; i < _snapshot.Buttons.Count; i++)
		{
			Button button = _snapshot.Buttons[i].Button;
			if ((Object)(object)button != (Object)null && ((Component)button).gameObject.activeSelf)
			{
				num++;
			}
		}
		if (num == _snapshot.LastAppliedActiveCount)
		{
			return false;
		}
		_snapshot.LastAppliedActiveCount = num;
		if (num <= 6 || !(_snapshot.ReferenceButtonHeight > 0f))
		{
			RestoreOriginalLayout(pauseMenu);
			return true;
		}
		float referenceButtonHeight = _snapshot.ReferenceButtonHeight;
		float originalSpacing = _snapshot.OriginalSpacing;
		float num2 = 6f * referenceButtonHeight + 5f * originalSpacing;
		float num3 = Mathf.Max(2f, Mathf.Round(originalSpacing * 0.65f));
		float num4 = Mathf.Floor((num2 - (float)(num - 1) * num3) / (float)num);
		num4 = Mathf.Clamp(num4, referenceButtonHeight * 0.72f, referenceButtonHeight);
		float num5 = Mathf.Clamp(num4 / referenceButtonHeight, 0.84f, 0.94f);
		if ((Object)(object)_snapshot.LayoutGroup != (Object)null)
		{
			((HorizontalOrVerticalLayoutGroup)_snapshot.LayoutGroup).spacing = num3;
			((LayoutGroup)_snapshot.LayoutGroup).padding.bottom = Mathf.RoundToInt((float)_snapshot.OriginalPaddingBottom * 0.75f);
		}
		pauseMenu.buttonHorizontalOffset = _snapshot.OriginalHorizontalOffset * 5f / (float)(num - 1);
		for (int j = 0; j < _snapshot.Buttons.Count; j++)
		{
			ButtonOriginalMetrics buttonOriginalMetrics = _snapshot.Buttons[j];
			if ((Object)(object)buttonOriginalMetrics.Button == (Object)null)
			{
				continue;
			}
			if ((Object)(object)buttonOriginalMetrics.Rect != (Object)null)
			{
				buttonOriginalMetrics.Rect.SetSizeWithCurrentAnchors((Axis)1, num4);
			}
			if ((Object)(object)buttonOriginalMetrics.LayoutElement != (Object)null)
			{
				if (buttonOriginalMetrics.OriginalPreferredHeight > 0f)
				{
					buttonOriginalMetrics.LayoutElement.preferredHeight = num4;
				}
				if (buttonOriginalMetrics.OriginalMinHeight > 0f)
				{
					buttonOriginalMetrics.LayoutElement.minHeight = Mathf.Min(buttonOriginalMetrics.OriginalMinHeight, num4);
				}
			}
			if (buttonOriginalMetrics.OriginalFontSize > 0f)
			{
				ApplyFontSize(buttonOriginalMetrics, buttonOriginalMetrics.OriginalFontSize * num5, num5);
			}
		}
		Plugin.LogDebug($"Compacted Pause Menu for {num} active buttons: height {referenceButtonHeight:F1}->{num4:F1}, spacing {originalSpacing:F1}->{num3:F1}, horizOffset {_snapshot.OriginalHorizontalOffset:F1}->{pauseMenu.buttonHorizontalOffset:F1}, fontRatio={num5:F2}.");
		return true;
	}

	private static void RestoreOriginalLayout(PauseMenu pauseMenu)
	{
		if ((Object)(object)_snapshot.LayoutGroup != (Object)null)
		{
			((HorizontalOrVerticalLayoutGroup)_snapshot.LayoutGroup).spacing = _snapshot.OriginalSpacing;
			((LayoutGroup)_snapshot.LayoutGroup).padding.bottom = _snapshot.OriginalPaddingBottom;
		}
		pauseMenu.buttonHorizontalOffset = _snapshot.OriginalHorizontalOffset;
		for (int i = 0; i < _snapshot.Buttons.Count; i++)
		{
			ButtonOriginalMetrics buttonOriginalMetrics = _snapshot.Buttons[i];
			if ((Object)(object)buttonOriginalMetrics.Button == (Object)null)
			{
				continue;
			}
			if ((Object)(object)buttonOriginalMetrics.Rect != (Object)null && buttonOriginalMetrics.OriginalHeight > 0f)
			{
				buttonOriginalMetrics.Rect.SetSizeWithCurrentAnchors((Axis)1, buttonOriginalMetrics.OriginalHeight);
			}
			if ((Object)(object)buttonOriginalMetrics.LayoutElement != (Object)null)
			{
				if (buttonOriginalMetrics.OriginalPreferredHeight > 0f)
				{
					buttonOriginalMetrics.LayoutElement.preferredHeight = buttonOriginalMetrics.OriginalPreferredHeight;
				}
				if (buttonOriginalMetrics.OriginalMinHeight > 0f)
				{
					buttonOriginalMetrics.LayoutElement.minHeight = buttonOriginalMetrics.OriginalMinHeight;
				}
			}
			if (buttonOriginalMetrics.OriginalFontSize > 0f)
			{
				ApplyFontSize(buttonOriginalMetrics, buttonOriginalMetrics.OriginalFontSize, 1f);
			}
		}
	}

	private static TMP_Text GetButtonLabel(Button button, MainMenuButton mmButton)
	{
		if ((Object)(object)mmButton != (Object)null && MainMenuButtonLabelField != null)
		{
			object? value = MainMenuButtonLabelField.GetValue(mmButton);
			TMP_Text val = (TMP_Text)((value is TMP_Text) ? value : null);
			if ((Object)(object)val != (Object)null)
			{
				return val;
			}
		}
		if (!((Object)(object)button != (Object)null))
		{
			return null;
		}
		return ((Component)button).GetComponentInChildren<TMP_Text>(true);
	}

	private static float GetOriginalFontSize(MainMenuButton mmButton, TMP_Text label)
	{
		if ((Object)(object)mmButton != (Object)null && MainMenuButtonRectTransformField != null && MainMenuButtonDefaultFontSizeField != null && MainMenuButtonRectTransformField.GetValue(mmButton) != null && MainMenuButtonDefaultFontSizeField.GetValue(mmButton) is float num && num > 0f)
		{
			return num;
		}
		if (!((Object)(object)label != (Object)null))
		{
			return 0f;
		}
		return label.fontSize;
	}

	private static float[] CaptureLocAdjustmentFontSizes(MainMenuButton mmButton)
	{
		if ((Object)(object)mmButton == (Object)null || MainMenuButtonLocAdjustmentsField == null || LocAdjustmentFontSizeField == null)
		{
			return null;
		}
		if (!(MainMenuButtonLocAdjustmentsField.GetValue(mmButton) is Array { Length: not 0 } array))
		{
			return null;
		}
		float[] array2 = new float[array.Length];
		for (int i = 0; i < array.Length; i++)
		{
			object value = array.GetValue(i);
			if (value != null && LocAdjustmentFontSizeField.GetValue(value) is float num)
			{
				array2[i] = num;
			}
		}
		return array2;
	}

	private static void ApplyFontSize(ButtonOriginalMetrics m, float fontSize, float locRatio)
	{
		if ((Object)(object)m.MmButton != (Object)null && m.OriginalLocFontSizes != null && MainMenuButtonLocAdjustmentsField != null && LocAdjustmentFontSizeField != null && MainMenuButtonLocAdjustmentsField.GetValue(m.MmButton) is Array array)
		{
			int num = Math.Min(array.Length, m.OriginalLocFontSizes.Length);
			for (int i = 0; i < num; i++)
			{
				float num2 = m.OriginalLocFontSizes[i];
				if (num2 > 0f)
				{
					object value = array.GetValue(i);
					if (value != null)
					{
						LocAdjustmentFontSizeField.SetValue(value, num2 * locRatio);
						array.SetValue(value, i);
					}
				}
			}
		}
		if ((Object)(object)m.MmButton != (Object)null && MainMenuButtonDefaultFontSizeField != null)
		{
			MainMenuButtonDefaultFontSizeField.SetValue(m.MmButton, fontSize);
		}
		if ((Object)(object)m.Label != (Object)null)
		{
			if (m.Label == _buttonLabel)
			{
				ConfigureSingleLineAutoSize(m.Label, fontSize);
			}
			else if ((Object)(object)m.MmButton != (Object)null && MainMenuButtonRectTransformField != null && MainMenuButtonRectTransformField.GetValue(m.MmButton) != null && MainMenuButtonOnLocaleChangedMethod != null)
			{
				MainMenuButtonOnLocaleChangedMethod.Invoke(m.MmButton, null);
			}
			else
			{
				m.Label.fontSize = fontSize;
			}
		}
	}

	private static void ConfigureSingleLineAutoSize(TMP_Text label, float maxFontSize)
	{
		if (!((Object)(object)label == (Object)null))
		{
			label.textWrappingMode = (TextWrappingModes)0;
			label.overflowMode = (TextOverflowModes)1;
			label.enableAutoSizing = true;
			if (maxFontSize > 0f)
			{
				label.fontSizeMax = maxFontSize;
				label.fontSizeMin = Mathf.Max(12f, maxFontSize * 0.55f);
				label.fontSize = maxFontSize;
			}
		}
	}

	private static void CaptureOriginalLabelMargin()
	{
		//IL_0012: Unknown result type (might be due to invalid IL or missing references)
		//IL_0017: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)_buttonLabel != (Object)null)
		{
			_origLabelMargin = _buttonLabel.margin;
			_hasOrigLabelMargin = true;
		}
	}

	private static void UpdateLabelSafeLeftMargin()
	{
		//IL_0076: Unknown result type (might be due to invalid IL or missing references)
		//IL_007c: Invalid comparison between Unknown and I4
		//IL_00a7: 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_00bf: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
		//IL_00fb: Unknown result type (might be due to invalid IL or missing references)
		//IL_0142: Unknown result type (might be due to invalid IL or missing references)
		//IL_0147: Unknown result type (might be due to invalid IL or missing references)
		//IL_0157: Unknown result type (might be due to invalid IL or missing references)
		//IL_015c: Unknown result type (might be due to invalid IL or missing references)
		//IL_015e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0163: Unknown result type (might be due to invalid IL or missing references)
		//IL_0113: 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_0178: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)_buttonLabel == (Object)null)
		{
			return;
		}
		if (!_hasOrigLabelMargin)
		{
			CaptureOriginalLabelMargin();
		}
		RectTransform rectTransform = _buttonLabel.rectTransform;
		Canvas val = (((Object)(object)((Graphic)_buttonLabel).canvas != (Object)null) ? ((Graphic)_buttonLabel).canvas : ((Component)_buttonLabel).GetComponentInParent<Canvas>(true));
		Canvas val2 = (((Object)(object)val != (Object)null) ? val.rootCanvas : null);
		if ((Object)(object)rectTransform == (Object)null || (Object)(object)val2 == (Object)null || (int)val2.renderMode == 2)
		{
			return;
		}
		Transform transform = ((Component)val2).transform;
		RectTransform val3 = (RectTransform)(object)((transform is RectTransform) ? transform : null);
		if ((Object)(object)val3 == (Object)null)
		{
			return;
		}
		rectTransform.GetWorldCorners(WorldCornersBuffer);
		float x = ((Transform)val3).InverseTransformPoint(WorldCornersBuffer[0]).x;
		float x2 = ((Transform)val3).InverseTransformPoint(WorldCornersBuffer[3]).x;
		Rect rect = val3.rect;
		float num = x - ((Rect)(ref rect)).xMin;
		float num2 = Mathf.Abs(x2 - x);
		float num3;
		if (num2 > 0.01f)
		{
			rect = rectTransform.rect;
			if (((Rect)(ref rect)).width > 0.01f)
			{
				rect = rectTransform.rect;
				num3 = ((Rect)(ref rect)).width / num2;
				goto IL_0124;
			}
		}
		num3 = 1f;
		goto IL_0124;
		IL_0124:
		float num4 = num3;
		float num5 = Mathf.Max(_origLabelMargin.x, (20f - num) * num4);
		Vector4 origLabelMargin = _origLabelMargin;
		origLabelMargin.x = num5;
		Vector4 val4 = _buttonLabel.margin - origLabelMargin;
		if (((Vector4)(ref val4)).sqrMagnitude > 0.001f)
		{
			_buttonLabel.margin = origLabelMargin;
			Plugin.LogDebug($"Pause Menu label safe margin updated: labelLeftInCanvas={num:F1}, leftMargin={num5:F1}.");
		}
	}
}
public enum PreferredGameMode
{
	FreeForAll,
	Teams,
	Any
}
[BepInPlugin("com.lmkhenlo.quickplay", "Quickplay", "0.1.0")]
public sealed class Plugin : BaseUnityPlugin
{
	public const string PluginGuid = "com.lmkhenlo.quickplay";

	public const string PluginName = "Quickplay";

	public const string PluginVersion = "0.1.0";

	private Harmony _harmony;

	internal static ManualLogSource Log { get; private set; }

	internal static ConfigEntry<bool> Enabled { get; private set; }

	internal static ConfigEntry<int> MaxFallbackAttempts { get; private set; }

	internal static ConfigEntry<bool> PreferActiveMatches { get; private set; }

	internal static ConfigEntry<PreferredGameMode> PreferredMode { get; private set; }

	internal static ConfigEntry<bool> DeprioritizeCustomLobbies { get; private set; }

	internal static ConfigEntry<bool> ClassicOnly { get; private set; }

	internal static ConfigEntry<bool> AllowProGolf { get; private set; }

	internal static ConfigEntry<bool> ExcludeDevConsole { get; private set; }

	internal static ConfigEntry<int> MaxPingMs { get; private set; }

	internal static ConfigEntry<int> MinPlayers { get; private set; }

	internal static ConfigEntry<bool> SkipFinalHole { get; private set; }

	internal static ConfigEntry<bool> LocalRegionOnly { get; private set; }

	internal static ConfigEntry<int> MaxCourseLength { get; private set; }

	internal static ConfigEntry<int> RecentlyLeftCooldownSeconds { get; private set; }

	internal static ConfigEntry<bool> AutoRequeueAfterMatch { get; private set; }

	internal static ConfigEntry<bool> AutoRequeueOnTimeout { get; private set; }

	internal static ConfigEntry<int> AutoRequeueDelaySeconds { get; private set; }

	internal static ConfigEntry<bool> DebugLogging { get; private set; }

	private void Awake()
	{
		//IL_004d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0057: Expected O, but got Unknown
		//IL_0142: Unknown result type (might be due to invalid IL or missing references)
		//IL_014c: Expected O, but got Unknown
		//IL_0174: Unknown result type (might be due to invalid IL or missing references)
		//IL_017e: Expected O, but got Unknown
		//IL_01e6: Unknown result type (might be due to invalid IL or missing references)
		//IL_01f0: Expected O, but got Unknown
		//IL_021c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0226: Expected O, but got Unknown
		//IL_028e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0298: Expected O, but got Unknown
		//IL_02c3: Unknown result type (might be due to invalid IL or missing references)
		//IL_02cd: Expected O, but got Unknown
		Log = ((BaseUnityPlugin)this).Logger;
		Enabled = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "Enable Quickplay (main menu Quickplay button, pause menu Find new match button, and post-match auto-requeue). Toggling off updates live; enabling after a disabled startup takes effect on the next scene load.");
		MaxFallbackAttempts = ((BaseUnityPlugin)this).Config.Bind<int>("Matchmaking", "MaxFallbackAttempts", 3, new ConfigDescription("Maximum number of top-ranked public lobbies Quickplay will attempt to join sequentially if an EOS join fails, a lobby becomes locked/private or fails rule filters, a host is sanctioned, or Mirror disconnects before scene load.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 5), Array.Empty<object>()));
		PreferActiveMatches = ((BaseUnityPlugin)this).Config.Bind<bool>("Matchmaking", "PreferActiveMatches", true, "Prioritize lobbies currently playing a course over lobbies waiting on the Driving Range.");
		PreferredMode = ((BaseUnityPlugin)this).Config.Bind<PreferredGameMode>("Matchmaking", "PreferredMode", PreferredGameMode.FreeForAll, "Preferred game mode weighting: FreeForAll (Classic FFA > Classic Teams > Custom/Pro Golf FFA > Custom/Pro Golf Teams), Teams (prioritizes Teams over FFA), or Any (no mode bias).");
		DeprioritizeCustomLobbies = ((BaseUnityPlugin)this).Config.Bind<bool>("Matchmaking", "DeprioritizeCustomLobbies", true, "Apply a soft scoring penalty to lobbies with Custom or Pro Golf rules, custom items, or dev console commands enabled (still joinable if no classic lobbies are available).");
		ClassicOnly = ((BaseUnityPlugin)this).Config.Bind<bool>("Matchmaking", "ClassicOnly", false, "Hard-exclude lobbies with Custom or Pro Golf rules, custom items, or dev console commands enabled. When true, only Classic lobbies are considered.");
		AllowProGolf = ((BaseUnityPlugin)this).Config.Bind<bool>("Matchmaking", "AllowProGolf", true, "Allow joining Pro Golf preset lobbies (ignored when ClassicOnly is true).");
		ExcludeDevConsole = ((BaseUnityPlugin)this).Config.Bind<bool>("Matchmaking", "ExcludeDevConsole", false, "Hard-exclude lobbies with Console Commands (dev console / cheats) enabled without blocking other custom lobbies.");
		MaxPingMs = ((BaseUnityPlugin)this).Config.Bind<int>("Matchmaking", "MaxPingMs", 0, new ConfigDescription("Hard maximum estimated ping in milliseconds (0 disables the hard cap and uses soft latency scoring only). When > 0, lobbies whose ping cannot be estimated are also excluded.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 500), Array.Empty<object>()));
		MinPlayers = ((BaseUnityPlugin)this).Config.Bind<int>("Matchmaking", "MinPlayers", 1, new ConfigDescription("Minimum number of current players required in a lobby to be eligible (1 allows solo lobbies with a soft penalty; higher values skip under-populated lobbies).", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 16), Array.Empty<object>()));
		SkipFinalHole = ((BaseUnityPlugin)this).Config.Bind<bool>("Matchmaking", "SkipFinalHole", false, "Hard-exclude active lobbies currently on their final hole so Quickplay does not drop you into a match about to end.");
		LocalRegionOnly = ((BaseUnityPlugin)this).Config.Bind<bool>("Matchmaking", "LocalRegionOnly", false, "Only search lobbies in your local EOS region and skip the global fallback pass.");
		MaxCourseLength = ((BaseUnityPlugin)this).Config.Bind<int>("Matchmaking", "MaxCourseLength", 0, new ConfigDescription("Hard maximum configured course hole count to join, across both active matches and Driving Range lobbies (0 disables the cap; e.g., 18 excludes custom marathon courses).", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), Array.Empty<object>()));
		RecentlyLeftCooldownSeconds = ((BaseUnityPlugin)this).Config.Bind<int>("Matchmaking", "RecentlyLeftCooldownSeconds", 120, new ConfigDescription("Seconds to heavily deprioritize a lobby you just left so Quickplay prefers putting you into a different lobby (still falls back to it if no other lobby is available; 0 disables).", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 600), Array.Empty<object>()));
		AutoRequeueAfterMatch = ((BaseUnityPlugin)this).Config.Bind<bool>("Matchmaking", "AutoRequeueAfterMatch", true, "Automatically leave Quickplay lobbies and search for a new match when a course ends (returning to the Driving Range), when the host aborts a course mid-way, or when the host closes the lobby. Applies only to lobbies joined via Quickplay.");
		AutoRequeueOnTimeout = ((BaseUnityPlugin)this).Config.Bind<bool>("Matchmaking", "AutoRequeueOnTimeout", false, "Also trigger auto-requeue when disconnected from a Quickplay lobby due to a host connection timeout (requires AutoRequeueAfterMatch = true; kicks remain manual).");
		AutoRequeueDelaySeconds = ((BaseUnityPlugin)this).Config.Bind<int>("Matchmaking", "AutoRequeueDelaySeconds", 5, new ConfigDescription("Seconds to wait with a cancelable countdown prompt before auto-requeuing (0 = exit and requeue immediately without loading the Driving Range).", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 15), Array.Empty<object>()));
		DebugLogging = ((BaseUnityPlugin)this).Config.Bind<bool>("Debug", "DebugLogging", false, "Log lobby discovery counts, ping estimates, candidate scores, and fallback attempts to the BepInEx log.");
		_harmony = new Harmony("com.lmkhenlo.quickplay");
		TryPatchAll(typeof(MainMenuPatches));
		TryPatchAll(typeof(NetworkManagerPatches));
		TryPatchAll(typeof(CourseManagerPatches));
		TryPatchAll(typeof(DrivingRangeManagerPatches));
		TryPatchAll(typeof(PauseMenuPatches));
		LocalizationSettings.SelectedLocaleChanged += OnSelectedLocaleChanged;
		Enabled.SettingChanged += OnEnabledSettingChanged;
		Log.LogInfo((object)"Quickplay 0.1.0 loaded.");
	}

	private void TryPatchAll(Type patchType)
	{
		try
		{
			_harmony.PatchAll(patchType);
		}
		catch (Exception arg)
		{
			Log.LogError((object)$"Failed to apply Harmony patches in {patchType.Name}: {arg}");
		}
	}

	private void OnDestroy()
	{
		if (Enabled != null)
		{
			Enabled.SettingChanged -= OnEnabledSettingChanged;
		}
		LocalizationSettings.SelectedLocaleChanged -= OnSelectedLocaleChanged;
		QuickplayAutoRequeue.Cleanup();
		QuickplayController.Cleanup();
		MainMenuQuickplayUI.Cleanup();
		PauseMenuQuickplayUI.Cleanup();
		Harmony harmony = _harmony;
		if (harmony != null)
		{
			harmony.UnpatchSelf();
		}
	}

	private static void OnEnabledSettingChanged(object sender, EventArgs e)
	{
		int num;
		if (Enabled != null)
		{
			num = (Enabled.Value ? 1 : 0);
			if (num != 0)
			{
				goto IL_002b;
			}
		}
		else
		{
			num = 0;
		}
		QuickplayAutoRequeue.CancelActiveCountdown("Quickplay disabled in config");
		QuickplayController.CancelActiveSession("Quickplay disabled in config");
		goto IL_002b;
		IL_002b:
		MainMenuQuickplayUI.SetVisible((byte)num != 0);
		PauseMenuQuickplayUI.RefreshVisibilityIfActive();
	}

	private static void OnSelectedLocaleChanged(Locale locale)
	{
		QuickplayLocalization.InvalidateCache();
		MainMenuQuickplayUI.RefreshLabel();
		PauseMenuQuickplayUI.RefreshLabel();
	}

	internal static void LogDebug(string message)
	{
		if (DebugLogging != null && DebugLogging.Value && Log != null)
		{
			Log.LogInfo((object)("[Debug] " + message));
		}
	}
}
internal static class QuickplayAutoRequeue
{
	private enum PendingMainMenuAction
	{
		None,
		ImmediateRequeue,
		PauseMenuRequeue,
		LobbyClosedCountdown,
		TimedOutCountdown
	}

	[CompilerGenerated]
	private sealed class <>c__DisplayClass28_0
	{
		public bool decided;

		internal void <RunDrivingRangeCountdownAsync>b__0()
		{
			if (!decided)
			{
				decided = true;
				Plugin.LogDebug("User selected 'Find Now' on Driving Range auto-requeue prompt.");
				CancelActiveCountdown("User chose Find Now");
				_pendingMainMenuAction = PendingMainMenuAction.ImmediateRequeue;
				GameManager.ExitToMainMenu(false, false, (Action)null);
			}
		}

		internal void <RunDrivingRangeCountdownAsync>b__1()
		{
			if (!decided)
			{
				decided = true;
				Plugin.LogDebug("User selected 'Stay in Lobby' on Driving Range auto-requeue prompt.");
				CancelActiveCountdown("User chose Stay in Lobby");
				FullScreenMessage.Hide();
			}
		}
	}

	[CompilerGenerated]
	private sealed class <>c__DisplayClass29_0
	{
		public PendingMainMenuAction action;

		public MainMenu mainMenu;

		public bool decided;

		internal void <HandlePendingMainMenuActionAsync>b__0()
		{
			if (!decided)
			{
				decided = true;
				Plugin.LogDebug($"User selected 'Find Now' on {action} prompt.");
				CancelActiveCountdown($"User chose Find Now ({action})");
				FullScreenMessage.Hide();
				QuickplayController.StartQuickplay(mainMenu);
			}
		}

		internal void <HandlePendingMainMenuActionAsync>b__1()
		{
			if (!decided)
			{
				decided = true;
				Plugin.LogDebug($"User canceled {action} on main menu.");
				CancelActiveCountdown($"User canceled ({action})");
				FullScreenMessage.Hide();
			}
		}
	}

	[StructLayout(LayoutKind.Auto)]
	[CompilerGenerated]
	private struct <HandlePendingMainMenuActionAsync>d__29 : IAsyncStateMachine
	{
		public int <>1__state;

		public AsyncUniTaskVoidMethodBuilder <>t__builder;

		public PendingMainMenuAction action;

		public MainMenu mainMenu;

		private <>c__DisplayClass29_0 <>8__1;

		private CancellationTokenSource <cts>5__2;

		private CancellationToken <ct>5__3;

		private double <waitStart>5__4;

		private double <countdownEnd>5__5;

		private int <lastDisplayedSeconds>5__6;

		private Awaiter <>u__1;

		private void MoveNext()
		{
			//IL_0132: Unknown result type (might be due to invalid IL or missing references)
			//IL_0137: Unknown result type (might be due to invalid IL or missing references)
			//IL_013f: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0494: Unknown result type (might be due to invalid IL or missing references)
			//IL_0499: Unknown result type (might be due to invalid IL or missing references)
			//IL_04a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0177: Unknown result type (might be due to invalid IL or missing references)
			//IL_017c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0180: Unknown result type (might be due to invalid IL or missing references)
			//IL_0185: Unknown result type (might be due to invalid IL or missing references)
			//IL_019a: Unknown result type (might be due to invalid IL or missing references)
			//IL_019c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d8: Invalid comparison between Unknown and I4
			//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0102: 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_0119: Unknown result type (might be due to invalid IL or missing references)
			//IL_0456: Unknown result type (might be due to invalid IL or missing references)
			//IL_045b: Unknown result type (might be due to invalid IL or missing references)
			//IL_045f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0464: Unknown result type (might be due to invalid IL or missing references)
			//IL_0479: Unknown result type (might be due to invalid IL or missing references)
			//IL_047b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0334: Unknown result type (might be due to invalid IL or missing references)
			//IL_0354: Unknown result type (might be due to invalid IL or missing references)
			//IL_0361: Expected O, but got Unknown
			//IL_035c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0362: Expected O, but got Unknown
			//IL_0375: Unknown result type (might be due to invalid IL or missing references)
			//IL_0382: Expected O, but got Unknown
			//IL_037d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0383: Expected O, but got Unknown
			int num = <>1__state;
			try
			{
				if ((uint)num > 2u)
				{
					<>8__1 = new <>c__DisplayClass29_0();
					<>8__1.action = action;
					<>8__1.mainMenu = mainMenu;
					<cts>5__2 = ResetCountdownCts();
					<ct>5__3 = <cts>5__2.Token;
				}
				try
				{
					Awaiter val;
					UniTask val2;
					bool flag3;
					switch (num)
					{
					default:
						<waitStart>5__4 = Time.realtimeSinceStartupAsDouble;
						goto IL_0155;
					case 0:
						val = <>u__1;
						<>u__1 = default(Awaiter);
						num = (<>1__state = -1);
						goto IL_014e;
					case 1:
						val = <>u__1;
						<>u__1 = default(Awaiter);
						num = (<>1__state = -1);
						goto IL_01d1;
					case 2:
						{
							val = <>u__1;
							<>u__1 = default(Awaiter);
							num = (<>1__state = -1);
							goto IL_04b0;
						}
						IL_0155:
						if (!(Time.realtimeSinceStartupAsDouble - <waitStart>5__4 < 8.0))
						{
							goto IL_016f;
						}
						<ct>5__3.ThrowIfCancellationRequested();
						if (!((Object)(object)<>8__1.mainMenu == (Object)null))
						{
							bool num2 = !LoadingScreen.IsVisible && !LoadingScreen.IsFadingScreenIn && !LoadingScreen.IsFadingScreenOut;
							bool flag = !NetworkClient.active && !NetworkServer.active;
							bool flag2 = BEosLobbyManager.CurrentLobby == null || (int)BEosLobbyManager.CurrentLobby.ProcessStatus == 0;
							if (!(num2 && flag && flag2))
							{
								val2 = UniTask.Delay(100, true, (PlayerLoopTiming)8, <ct>5__3, false);
								val = ((UniTask)(ref val2)).GetAwaiter();
								if (!((Awaiter)(ref val)).IsCompleted)
								{
									num = (<>1__state = 0);
									<>u__1 = val;
									((AsyncUniTaskVoidMethodBuilder)(ref <>t__builder)).AwaitUnsafeOnCompleted<Awaiter, <HandlePendingMainMenuActionAsync>d__29>(ref val, ref this);
									return;
								}
								goto IL_014e;
							}
							goto IL_016f;
						}
						goto end_IL_0055;
						IL_04b7:
						if (<>8__1.decided)
						{
							break;
						}
						<ct>5__3.ThrowIfCancellationRequested();
						if (!((Object)(object)<>8__1.mainMenu == (Object)null) && !QuickplayController.IsRunning && !NetworkClient.active && !NetworkServer.active && string.IsNullOrEmpty(BNetworkManager.EosLobbyToConnectToFromMainMenu) && FullScreenMessage.IsDisplayingAnyMessage && !FullScreenMessage.IsDisplayingError)
						{
							double num3 = <countdownEnd>5__5 - Time.realtimeSinceStartupAsDouble;
							if (num3 <= 0.0)
							{
								break;
							}
							int num4 = Math.Max(1, (int)Math.Ceiling(num3));
							if (num4 != <lastDisplayedSeconds>5__6)
							{
								<lastDisplayedSeconds>5__6 = num4;
								UpdateFullScreenMessageTextInPlace(FormatMainMenuDisconnectMessage(<>8__1.action, num4));
							}
							val2 = UniTask.Delay(100, true, (PlayerLoopTiming)8, <ct>5__3, false);
							val = ((UniTask)(ref val2)).GetAwaiter();
							if (!((Awaiter)(ref val)).IsCompleted)
							{
								num = (<>1__state = 2);
								<>u__1 = val;
								((AsyncUniTaskVoidMethodBuilder)(ref <>t__builder)).AwaitUnsafeOnCompleted<Awaiter, <HandlePendingMainMenuActionAsync>d__29>(ref val, ref this);
								return;
							}
							goto IL_04b0;
						}
						goto end_IL_0055;
						IL_01d1:
						((Awaiter)(ref val)).GetResult();
						flag3 = <>8__1.action == PendingMainMenuAction.PauseMenuRequeue;
						if (!((Object)(object)<>8__1.mainMenu == (Object)null) && !<ct>5__3.IsCancellationRequested && Plugin.Enabled.Value && (flag3 || Plugin.AutoRequeueAfterMatch.Value))
						{
							if (BNetworkManager.IsOfflineOrLoggedOut)
							{
								Plugin.LogDebug("Skipping auto-requeue on main menu: offline or logged out.");
							}
							else if (!string.IsNullOrEmpty(BNetworkManager.EosLobbyToConnectToFromMainMenu))
							{
								Plugin.LogDebug("Skipping auto-requeue on main menu: Steam/EOS preset lobby connect is pending.");
							}
							else if (HasPendingSanctions(<>8__1.mainMenu))
							{
								Plugin.LogDebug("Skipping auto-requeue on main menu: player sanction message is pending.");
							}
							else if (flag3 && FullScreenMessage.IsDisplayingError)
							{
								Plugin.LogDebug("Skipping Pause Menu requeue on main menu: an error/kick dialog is displayed.");
							}
							else if (!QuickplayController.IsRunning && !NetworkClient.active && !NetworkServer.active)
							{
								if (<>8__1.action == PendingMainMenuAction.ImmediateRequeue || flag3)
								{
									Plugin.LogDebug(flag3 ? "Pause Menu 'Find new match' starting Quickplay on main menu." : "Auto-requeue starting Quickplay on main menu.");
									FullScreenMessage.Hide();
									QuickplayController.StartQuickplay(<>8__1.mainMenu);
								}
								else
								{
									int delaySeconds = GetDelaySeconds();
									if (delaySeconds > 0)
									{
										<>8__1.decided = false;
										FullScreenMessage.Show(new MessageOptions(FormatMainMenuDisconnectMessage(<>8__1.action, delaySeconds), QuickplayLocalization.Get(QuickplayTextKey.Quickplay), false), (ButtonEntry[])(object)new ButtonEntry[2]
										{
											new ButtonEntry(QuickplayLocalization.Get(QuickplayTextKey.FindNow), (UnityAction)delegate
											{
												if (!<>8__1.decided)
												{
													<>8__1.decided = true;
													Plugin.LogDebug($"User selected 'Find Now' on {<>8__1.action} prompt.");
													CancelActiveCountdown($"User chose Find Now ({<>8__1.action})");
													FullScreenMessage.Hide();
													QuickplayController.StartQuickplay(<>8__1.mainMenu);
												}
											}, false, true, false),
											new ButtonEntry(UI.MISC_Cancel, (UnityAction)delegate
											{
												if (!<>8__1.decided)
												{
													<>8__1.decided = true;
													Plugin.LogDebug($"User canceled {<>8__1.action} on main menu.");
													CancelActiveCountdown($"User canceled ({<>8__1.action})");
													FullScreenMessage.Hide();
												}
											}, true, false, false)
										});
										<countdownEnd>5__5 = Time.realtimeSinceStartupAsDouble + (double)delaySeconds;
										<lastDisplayedSeconds>5__6 = delaySeconds;
										goto IL_04b7;
									}
									FullScreenMessage.Hide();
									QuickplayController.StartQuickplay(<>8__1.mainMenu);
								}
							}
						}
						goto end_IL_0055;
						IL_016f:
						val2 = UniTask.Yield((PlayerLoopTiming)8, <ct>5__3, false);
						val = ((UniTask)(ref val2)).GetAwaiter();
						if (!((Awaiter)(ref val)).IsCompleted)
						{
							num = (<>1__state = 1);
							<>u__1 = val;
							((AsyncUniTaskVoidMethodBuilder)(ref <>t__builder)).AwaitUnsafeOnCompleted<Awaiter, <HandlePendingMainMenuActionAsync>d__29>(ref val, ref this);
							return;
						}
						goto IL_01d1;
						IL_04b0:
						((Awaiter)(ref val)).GetResult();
						goto IL_04b7;
						IL_014e:
						((Awaiter)(ref val)).GetResult();
						goto IL_0155;
					}
					if (!<>8__1.decided && !<ct>5__3.IsCancellationRequested && !((Object)(object)<>8__1.mainMenu == (Object)null) && !BNetworkManager.IsOfflineOrLoggedOut && string.IsNullOrEmpty(BNetworkManager.EosLobbyToConnectToFromMainMenu) && !QuickplayController.IsRunning && !NetworkClient.active && !NetworkServer.active)
					{
						<>8__1.decided = true;
						Plugin.LogDebug($"{<>8__1.action} countdown finished; starting Quickplay.");
						FullScreenMessage.Hide();
						QuickplayController.StartQuickplay(<>8__1.mainMenu);
					}
					end_IL_0055:;
				}
				catch (OperationCanceledException)
				{
				}
				catch (Exception ex2)
				{
					Plugin.Log.LogError((object)("Error during main menu auto-requeue handoff: " + ex2));
				}
				finally
				{
					if (num < 0)
					{
						DisposeCountdownCtsIfCurrent(<cts>5__2);
					}
				}
			}
			catch (Exception exception)
			{
				<>1__state = -2;
				<>8__1 = null;
				<cts>5__2 = null;
				<ct>5__3 = default(CancellationToken);
				((AsyncUniTaskVoidMethodBuilder)(ref <>t__builder)).SetException(exception);
				return;
			}
			<>1__state = -2;
			<>8__1 = null;
			<cts>5__2 = null;
			<ct>5__3 = default(CancellationToken);
			((AsyncUniTaskVoidMethodBuilder)(ref <>t__builder)).SetResult();
		}

		void IAsyncStateMachine.MoveNext()
		{
			//ILSpy generated this explicit interface implementation from .override directive in MoveNext
			this.MoveNext();
		}

		[DebuggerHidden]
		private void SetStateMachine(IAsyncStateMachine stateMachine)
		{
			((AsyncUniTaskVoidMethodBuilder)(ref <>t__builder)).SetStateMachine(stateMachine);
		}

		void IAsyncStateMachine.SetStateMachine(IAsyncStateMachine stateMachine)
		{
			//ILSpy generated this explicit interface implementation from .override directive in SetStateMachine
			this.SetStateMachine(stateMachine);
		}
	}

	[StructLayout(LayoutKind.Auto)]
	[CompilerGenerated]
	private struct <RunDrivingRangeCountdownAsync>d__28 : IAsyncStateMachine
	{
		public int <>1__state;

		public AsyncUniTaskVoidMethodBuilder <>t__builder;

		private <>c__DisplayClass28_0 <>8__1;

		public int delaySeconds;

		private CancellationTokenSource <cts>5__2;

		private CancellationToken <ct>5__3;

		private double <waitStart>5__4;

		private double <countdownEnd>5__5;

		private int <lastDisplayedSeconds>5__6;

		private Awaiter <>u__1;

		private void MoveNext()
		{
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0154: Unknown result type (might be due to invalid IL or missing references)
			//IL_0159: Unknown result type (might be due to invalid IL or missing references)
			//IL_0160: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_02fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0119: 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_0121: Unknown result type (might be due to invalid IL or missing references)
			//IL_0126: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e0: Expected O, but got Unknown
			//IL_01db: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e1: Expected O, but got Unknown
			//IL_01f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0203: Expected O, but got Unknown
			//IL_01fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_0204: Expected O, but got Unknown
			//IL_013a: 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_0085: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0092: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_02bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d6: Unknown result type (might be due to invalid IL or missing references)
			int num = <>1__state;
			try
			{
				if ((uint)num > 2u)
				{
					<cts>5__2 = ResetCountdownCts();
					<ct>5__3 = <cts>5__2.Token;
				}
				try
				{
					Awaiter val;
					UniTask val2;
					switch (num)
					{
					default:
						<>8__1 = new <>c__DisplayClass28_0();
						<waitStart>5__4 = Time.realtimeSinceStartupAsDouble;
						goto IL_00e2;
					case 0:
						val = <>u__1;
						<>u__1 = default(Awaiter);
						num = (<>1__state = -1);
						goto IL_00db;
					case 1:
						val = <>u__1;
						<>u__1 = default(Awaiter);
						num = (<>1__state = -1);
						goto IL_016f;
					case 2:
						{
							val = <>u__1;
							<>u__1 = default(Awaiter);
							num = (<>1__state = -1);
							goto IL_030a;
						}
						IL_00e2:
						if ((!LoadingScreen.IsVisible && !LoadingScreen.IsFadingScreenIn && !LoadingScreen.IsFadingScreenOut) || !(Time.realtimeSinceStartupAsDouble - <waitStart>5__4 < 8.0))
						{
							val2 = UniTask.Yield((PlayerLoopTiming)8, <ct>5__3, false);
							val = ((UniTask)(ref val2)).GetAwaiter();
							if (!((Awaiter)(ref val)).IsCompleted)
							{
								num = (<>1__state = 1);
								<>u__1 = val;
								((AsyncUniTaskVoidMethodBuilder)(ref <>t__builder)).AwaitUnsafeOnCompleted<Awaiter, <RunDrivingRangeCountdownAsync>d__28>(ref val, ref this);
								return;
							}
							goto IL_016f;
						}
						<ct>5__3.ThrowIfCancellationRequested();
						if (SingletonBehaviour<DrivingRangeManager>.HasInstance && NetworkClient.active && !NetworkServer.active)
						{
							val2 = UniTask.Delay(100, true, (PlayerLoopTiming)8, <ct>5__3, false);
							val = ((UniTask)(ref val2)).GetAwaiter();
							if (!((Awaiter)(ref val)).IsCompleted)
							{
								num = (<>1__state = 0);
								<>u__1 = val;
								((AsyncUniTaskVoidMethodBuilder)(ref <>t__builder)).AwaitUnsafeOnCompleted<Awaiter, <RunDrivingRangeCountdownAsync>d__28>(ref val, ref this);
								return;
							}
							goto IL_00db;
						}
						goto end_IL_0028;
						IL_00db:
						((Awaiter)(ref val)).GetResult();
						goto IL_00e2;
						IL_0311:
						if (<>8__1.decided)
						{
							break;
						}
						<ct>5__3.ThrowIfCancellationRequested();
						if (SingletonBehaviour<DrivingRangeManager>.HasInstance && NetworkClient.active && !NetworkServer.active && FullScreenMessage.IsDisplayingAnyMessage && !FullScreenMessage.IsDisplayingError)
						{
							double num2 = <countdownEnd>5__5 - Time.realtimeSinceStartupAsDouble;
							if (num2 <= 0.0)
							{
								break;
							}
							int num3 = Math.Max(1, (int)Math.Ceiling(num2));
							if (num3 != <lastDisplayedSeconds>5__6)
							{
								<lastDisplayedSeconds>5__6 = num3;
								UpdateFullScreenMessageTextInPlace(FormatDrivingRangeMessage(num3));
							}
							val2 = UniTask.Delay(100, true, (PlayerLoopTiming)8, <ct>5__3, false);
							val = ((UniTask)(ref val2)).GetAwaiter();
							if (!((Awaiter)(ref val)).IsCompleted)
							{
								num = (<>1__state = 2);
								<>u__1 = val;
								((AsyncUniTaskVoidMethodBuilder)(ref <>t__builder)).AwaitUnsafeOnCompleted<Awaiter, <RunDrivingRangeCountdownAsync>d__28>(ref val, ref this);
								return;
							}
							goto IL_030a;
						}
						goto end_IL_0028;
						IL_016f:
						((Awaiter)(ref val)).GetResult();
						if (CanAutoRequeueInGameSession() && SingletonBehaviour<DrivingRangeManager>.HasInstance && !FullScreenMessage.IsDisplayingError)
						{
							<>8__1.decided = false;
							FullScreenMessage.Show(new MessageOptions(FormatDrivingRangeMessage(delaySeconds), QuickplayLocalization.Get(QuickplayTextKey.Quickplay), false), (ButtonEntry[])(object)new ButtonEntry[2]
							{
								new ButtonEntry(QuickplayLocalization.Get(QuickplayTextKey.FindNow), (UnityAction)delegate
								{
									if (!<>8__1.decided)
									{
										<>8__1.decided = true;
										Plugin.LogDebug("User selected 'Find Now' on Driving Range auto-requeue prompt.");
										CancelActiveCountdown("User chose Find Now");
										_pendingMainMenuAction = PendingMainMenuAction.ImmediateRequeue;
										GameManager.ExitToMainMenu(false, false, (Action)null);
									}
								}, false, true, false),
								new ButtonEntry(QuickplayLocalization.Get(QuickplayTextKey.StayInLobby), (UnityAction)delegate
								{
									if (!<>8__1.decided)
									{
										<>8__1.decided = true;
										Plugin.LogDebug("User selected 'Stay in Lobby' on Driving Range auto-requeue prompt.");
										CancelActiveCountdown("User chose Stay in Lobby");
										FullScreenMessage.Hide();
									}
								}, true, false, false)
							});
							<countdownEnd>5__5 = Time.realtimeSinceStartupAsDouble + (double)delaySeconds;
							<lastDisplayedSeconds>5__6 = delaySeconds;
							goto IL_0311;
						}
						goto end_IL_0028;
						IL_030a:
						((Awaiter)(ref val)).GetResult();
						goto IL_0311;
					}
					if (!<>8__1.decided && !<ct>5__3.IsCancellationRequested && CanAutoRequeueInGameSession() && SingletonBehaviour<DrivingRangeManager>.HasInstance)
					{
						<>8__1.decided = true;
						Plugin.LogDebug("Driving Range auto-requeue countdown finished; exiting to main menu.");
						_pendingMainMenuAction = PendingMainMenuAction.ImmediateRequeue;
						GameManager.ExitToMainMenu(false, false, (Action)null);
						<>8__1 = null;
					}
					end_IL_0028:;
				}
				catch (OperationCanceledException)
				{
				}
				catch (Exception ex2)
				{
					Plugin.Log.LogError((object)("Error during Driving Range auto-requeue countdown: " + ex2));
				}
				finally
				{
					if (num < 0)
					{
						DisposeCountdownCtsIfCurrent(<cts>5__2);
					}
				}
			}
			catch (Exception exception)
			{
				<>1__state = -2;
				<cts>5__2 = null;
				<ct>5__3 = default(CancellationToken);
				((AsyncUniTaskVoidMethodBuilder)(ref <>t__builder)).SetException(exception);
				return;
			}
			<>1__state = -2;
			<cts>5__2 = null;
			<ct>5__3 = default(CancellationToken);
			((AsyncUniTaskVoidMethodBuilder)(ref <>t__builder)).SetResult();
		}

		void IAsyncStateMachine.MoveNext()
		{
			//ILSpy generated this explicit interface implementation from .override directive in MoveNext
			this.MoveNext();
		}

		[DebuggerHidden]
		private void SetStateMachine(IAsyncStateMachine stateMachine)
		{
			((AsyncUniTaskVoidMethodBuilder)(ref <>t__builder)).SetStateMachine(stateMachine);
		}

		void IAsyncStateMachine.SetStateMachine(IAsyncStateMachine stateMachine)
		{
			//ILSpy generated this explicit interface implementation from .override directive in SetStateMachine
			this.SetStateMachine(stateMachine);
		}
	}

	private const float SceneReadyTimeoutSeconds = 8f;

	private const int CountdownPollIntervalMs = 100;

	private static readonly FieldInfo FullScreenMessageTextField = AccessTools.Field(typeof(FullScreenMessage), "message");

	private static readonly FieldInfo MainMenuSanctionsQueueField = AccessTools.Field(typeof(MainMenu), "sanctionsQueue");

	private static readonly FieldInfo IsExitingToMainMenuField = AccessTools.Field(typeof(GameManager), "isExitingToMainMenu");

	private static bool _isQuickplaySession;

	private static bool _hasEnteredOnlineGameScene;

	private static bool _playedActiveCourse;

	private static bool _pendingDrivingRangeCountdown;

	private static PendingMainMenuAction _pendingMainMenuAction = PendingMainMenuAction.None;

	private static CancellationTokenSource _countdownCts;

	private static FullScreenMessage _cachedMessageInstance;

	private static TMP_Text _cachedMessageText;

	internal static void Cleanup()
	{
		ClearQuickplaySession("Plugin unloaded");
		_cachedMessageInstance = null;
		_cachedMessageText = null;
	}

	internal static void MarkQuickplaySessionStarted()
	{
		CancelActiveCountdown("New Quickplay session started");
		_isQuickplaySession = true;
		_hasEnteredOnlineGameScene = false;
		_playedActiveCourse = false;
		_pendingDrivingRangeCountdown = false;
		_pendingMainMenuAction = PendingMainMenuAction.None;
	}

	internal static void MarkEnteredOnlineGameScene()
	{
		if (_isQuickplaySession)
		{
			_hasEnteredOnlineGameScene = true;
		}
	}

	internal static void ClearQuickplaySession(string reason)
	{
		CancelActiveCountdown(reason);
		_isQuickplaySession = false;
		_hasEnteredOnlineGameScene = false;
		_playedActiveCourse = false;
		_pendingDrivingRangeCountdown = false;
		_pendingMainMenuAction = PendingMainMenuAction.None;
	}

	internal static void CancelActiveCountdown(string reason)
	{
		if (_countdownCts != null)
		{
			Plugin.LogDebug("Canceling auto-requeue countdown (" + reason + ").");
			try
			{
				_countdownCts.Cancel();
			}
			catch (ObjectDisposedException)
			{
			}
		}
	}

	internal static void OnCourseStartClient()
	{
		if (_isQuickplaySession && !NetworkServer.active && !SingletonBehaviour<DrivingRangeManager>.HasInstance)
		{
			_hasEnteredOnlineGameScene = true;
			_playedActiveCourse = true;
			_pendingDrivingRangeCountdown = false;
			CancelActiveCountdown("Entered active course");
		}
	}

	internal static bool OnCourseEndingRpc()
	{
		if (!CanAutoRequeueInGameSession())
		{
			return true;
		}
		int delaySeconds = GetDelaySeconds();
		if (delaySeconds <= 0)
		{
			if (IsExitingToMainMenu())
			{
				return true;
			}
			Plugin.LogDebug("Course ended in Quickplay lobby (delay=0s); exiting immediately to main menu to auto-requeue.");
			CancelActiveCountdown("Immediate auto-requeue on course end");
			_pendingDrivingRangeCountdown = false;
			_playedActiveCourse = false;
			_pendingMainMenuAction = PendingMainMenuAction.ImmediateRequeue;
			LoadingScreen.Show(false);
			GameManager.ExitToMainMenu(false, true, (Action)null);
			return false;
		}
		Plugin.LogDebug($"Course ended in Quickplay lobby; scheduling {delaySeconds}s Driving Range auto-requeue countdown.");
		_pendingDrivingRangeCountdown = true;
		return true;
	}

	internal static void OnDrivingRangeEntered()
	{
		//IL_0061: Unknown result type (might be due to invalid IL or missing references)
		//IL_0066: Unknown result type (might be due to invalid IL or missing references)
		if (_isQuickplaySession && NetworkClient.active && !NetworkServer.active)
		{
			MarkEnteredOnlineGameScene();
		}
		if (CanAutoRequeueInGameSession() && (_pendingDrivingRangeCountdown || _playedActiveCourse))
		{
			_pendingDrivingRangeCountdown = false;
			_playedActiveCourse = false;
			int delaySeconds = GetDelaySeconds();
			if (delaySeconds <= 0)
			{
				Plugin.LogDebug("Entered Driving Range after course in Quickplay lobby (delay=0s); exiting to main menu to auto-requeue.");
				_pendingMainMenuAction = PendingMainMenuAction.ImmediateRequeue;
				GameManager.ExitToMainMenu(false, false, (Action)null);
			}
			else
			{
				UniTaskVoid val = RunDrivingRangeCountdownAsync(delaySeconds);
				((UniTaskVoid)(ref val)).Forget();
			}
		}
	}

	internal static void OnDisconnectReason(DisconnectReason reason)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		//IL_0002: Invalid comparison between Unknown and I4
		//IL_0004: Unknown result type (might be due to invalid IL or missing references)
		//IL_0006: Invalid comparison between Unknown and I4
		//IL_0039: Unknown result type (might be due to invalid IL or missing references)
		//IL_001e: Unknown result type (might be due to invalid IL or missing references)
		//IL_004a: Unknown result type (might be due to invalid IL or missing references)
		//IL_004c: Invalid comparison between Unknown and I4
		//IL_004f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0051: Invalid comparison between Unknown and I4
		//IL_00db: Unknown result type (might be due to invalid IL or missing references)
		if ((int)reason == 2 || (int)reason == 4)
		{
			if (_pendingMainMenuAction != PendingMainMenuAction.None)
			{
				Plugin.LogDebug($"Clearing pending main menu action ({_pendingMainMenuAction}) due to {reason}.");
				_pendingMainMenuAction = PendingMainMenuAction.None;
			}
			CancelActiveCountdown($"Disconnected ({reason})");
			return;
		}
		bool flag = (int)reason == 1;
		bool flag2 = (int)reason == 3 && Plugin.AutoRequeueOnTimeout != null && Plugin.AutoRequeueOnTimeout.Value;
		if ((flag || flag2) && Plugin.Enabled.Value && Plugin.AutoRequeueAfterMatch.Value && _isQuickplaySession && _hasEnteredOnlineGameScene && !NetworkServer.active)
		{
			CancelActiveCountdown(flag ? "Host closed lobby" : "Connection to host timed out");
			_pendingDrivingRangeCountdown = false;
			_playedActiveCourse = false;
			int delaySeconds = GetDelaySeconds();
			_pendingMainMenuAction = ((delaySeconds <= 0) ? PendingMainMenuAction.ImmediateRequeue : (flag ? PendingMainMenuAction.LobbyClosedCountdown : PendingMainMenuAction.TimedOutCountdown));
			Plugin.LogDebug($"Quickplay lobby disconnected ({reason}); scheduled {_pendingMainMenuAction} on main menu (delay={delaySeconds}s).");
		}
	}

	internal static void TriggerImmediateRequeueFromPauseMenu()
	{
		if (!NetworkServer.active && NetworkClient.active && !BNetworkManager.CurrentlyPlayingOffline && !BNetworkManager.IsOfflineOrLoggedOut)
		{
			Plugin.LogDebug("Pause Menu 'Find New Match' clicked; exiting to main menu to start Quickplay.");
			CancelActiveCountdown("Pause menu Find New Match");
			_pendingDrivingRangeCountdown = false;
			_playedActiveCourse = false;
			_pendingMainMenuAction = PendingMainMenuAction.PauseMenuRequeue;
			GameManager.ExitToMainMenu(false, false, (Action)null);
		}
	}

	internal static void OnClientStopped()
	{
		CancelActiveCountdown("Client stopped");
		_isQuickplaySession = false;
		_hasEnteredOnlineGameScene = false;
		_playedActiveCourse = false;
		_pendingDrivingRangeCountdown = false;
	}

	internal static void OnMainMenuLoaded(MainMenu mainMenu)
	{
		//IL_001f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0024: Unknown result type (might be due to invalid IL or missing references)
		if (!((Object)(object)mainMenu == (Object)null) && _pendingMainMenuAction != PendingMainMenuAction.None)
		{
			PendingMainMenuAction pendingMainMenuAction = _pendingMainMenuAction;
			_pendingMainMenuAction = PendingMainMenuAction.None;
			UniTaskVoid val = HandlePendingMainMenuActionAsync(mainMenu, pendingMainMenuAction);
			((UniTaskVoid)(ref val)).Forget();
		}
	}

	private static bool CanAutoRequeueInGameSession()
	{
		if (Plugin.Enabled == null || !Plugin.Enabled.Value)
		{
			return false;
		}
		if (Plugin.AutoRequeueAfterMatch == null || !Plugin.AutoRequeueAfterMatch.Value)
		{
			return false;
		}
		if (!_isQuickplaySession)
		{
			return false;
		}
		if (NetworkServer.active || !NetworkClient.active)
		{
			return false;
		}
		if (BNetworkManager.CurrentlyPlayingOffline || BNetworkManager.IsOfflineOrLoggedOut)
		{
			return false;
		}
		return true;
	}

	private static int GetDelaySeconds()
	{
		if (Plugin.AutoRequeueDelaySeconds == null)
		{
			return 5;
		}
		return Mathf.Clamp(Plugin.AutoRequeueDelaySeconds.Value, 0, 15);
	}

	[AsyncStateMachine(typeof(<RunDrivingRangeCountdownAsync>d__28))]
	private static UniTaskVoid RunDrivingRangeCountdownAsync(int delaySeconds)
	{
		//IL_0002: Unknown result type (might be due to invalid IL or missing references)
		//IL_0007: Unknown result type (might be due to invalid IL or missing references)
		//IL_0031: Unknown result type (might be due to invalid IL or missing references)
		<RunDrivingRangeCountdownAsync>d__28 <RunDrivingRangeCountdownAsync>d__ = default(<RunDrivingRangeCountdownAsync>d__28);
		<RunDrivingRangeCountdownAsync>d__.<>t__builder = AsyncUniTaskVoidMethodBuilder.Create();
		<RunDrivingRangeCountdownAsync>d__.delaySeconds = delaySeconds;
		<RunDrivingRangeCountdownAsync>d__.<>1__state = -1;
		((AsyncUniTaskVoidMethodBuilder)(ref <RunDrivingRangeCountdownAsync>d__.<>t__builder)).Start<<RunDrivingRangeCountdownAsync>d__28>(ref <RunDrivingRangeCountdownAsync>d__);
		return ((AsyncUniTaskVoidMethodBuilder)(ref <RunDrivingRangeCountdownAsync>d__.<>t__builder)).Task;
	}

	[AsyncStateMachine(typeof(<HandlePendingMainMenuActionAsync>d__29))]
	private static UniTaskVoid HandlePendingMainMenuActionAsync(MainMenu mainMenu, PendingMainMenuAction action)
	{
		//IL_0002: Unknown result type (might be due to invalid IL or missing references)
		//IL_0007: Unknown result type (might be due to invalid IL or missing references)
		//IL_0039: Unknown result type (might be due to invalid IL or missing references)
		<HandlePendingMainMenuActionAsync>d__29 <HandlePendingMainMenuActionAsync>d__ = default(<HandlePendingMainMenuActionAsync>d__29);
		<HandlePendingMainMenuActionAsync>d__.<>t__builder = AsyncUniTaskVoidMethodBuilder.Create();
		<HandlePendingMainMenuActionAsync>d__.mainMenu = mainMenu;
		<HandlePendingMainMenuActionAsync>d__.action = action;
		<HandlePendingMainMenuActionAsync>d__.<>1__state = -1;
		((AsyncUniTaskVoidMethodBuilder)(ref <HandlePendingMainMenuActionAsync>d__.<>t__builder)).Start<<HandlePendingMainMenuActionAsync>d__29>(ref <HandlePendingMainMenuActionAsync>d__);
		return ((AsyncUniTaskVoidMethodBuilder)(ref <HandlePendingMainMenuActionAsync>d__.<>t__builder)).Task;
	}

	private static string FormatDrivingRangeMessage(int secondsRemaining)
	{
		return QuickplayLocalization.Format(QuickplayTextKey.MatchEndedCountdown, secondsRemaining);
	}

	private static string FormatMainMenuDisconnectMessage(PendingMainMenuAction action, int secondsRemaining)
	{
		return QuickplayLocalization.Format((action == PendingMainMenuAction.TimedOutCountdown) ? QuickplayTextKey.TimedOutCountdown : QuickplayTextKey.LobbyClosedCountdown, secondsRemaining);
	}

	private static void UpdateFullScreenMessageTextInPlace(string text)
	{
		FullScreenMessage instance = FullScreenMessage.Instance;
		if (!(FullScreenMessageTextField == null) && !((Object)(object)instance == (Object)null))
		{
			if ((Object)(object)_cachedMessageInstance != (Object)(object)instance || (Object)(object)_cachedMessageText == (Object)null)
			{
				_cachedMessageInstance = instance;
				object? value = FullScreenMessageTextField.GetValue(instance);
				_cachedMessageText = (TMP_Text)((value is TMP_Text) ? value : null);
			}
			if ((Object)(object)_cachedMessageText != (Object)null)
			{
				_cachedMessageText.text = text;
			}
		}
	}

	private static bool IsExitingToMainMenu()
	{
		if (IsExitingToMainMenuField == null)
		{
			return false;
		}
		object value = IsExitingToMainMenuField.GetValue(null);
		bool flag = default(bool);
		int num;
		if (value is bool)
		{
			flag = (bool)value;
			num = 1;
		}
		else
		{
			num = 0;
		}
		return (byte)((uint)num & (flag ? 1u : 0u)) != 0;
	}

	private static bool HasPendingSanctions(MainMenu mainMenu)
	{
		if (MainMenuSanctionsQueueField == null || (Object)(object)mainMenu == (Object)null)
		{
			return false;
		}
		if (MainMenuSanctionsQueueField.GetValue(mainMenu) is ICollection collection)
		{
			return collection.Count > 0;
		}
		return false;
	}

	private static CancellationTokenSource ResetCountdownCts()
	{
		if (_countdownCts != null)
		{
			try
			{
				_countdownCts.Cancel();
			}
			catch (ObjectDisposedException)
			{
			}
			try
			{
				_countdownCts.Dispose();
			}
			catch (ObjectDisposedException)
			{
			}
		}
		_countdownCts = new CancellationTokenSource();
		return _countdownCts;
	}

	private static void DisposeCountdownCtsIfCurrent(CancellationTokenSource cts)
	{
		if (_countdownCts == cts)
		{
			_countdownCts = null;
		}
		try
		{
			cts.Dispose();
		}
		catch (ObjectDisposedException)
		{
		}
	}
}
internal static class QuickplayController
{
	private enum MirrorConnectOutcome
	{
		Connected,
		Disconnected,
		Canceled
	}

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

		public static UnityAction <>9__27_0;

		internal void <ShowProgressMessage>b__27_0()
		{
			CancelActiveSession("Canceled by user");
			FullScreenMessage.Hide();
			if (NetworkClient.active && (Object)(object)BNetworkManager.singleton != (Object)null)
			{
				((NetworkManager)BNetworkManager.singleton).StopClient();
			}
		}
	}

	[CompilerGenerated]
	private sealed class <>c__DisplayClass26_0
	{
		public CancellationToken ct;

		internal void <RunQuickplayAsync>b__0(string status)
		{
			ShowProgressMessage(status, ct);
		}
	}

	[CompilerGenerated]
	private sealed class <>c__DisplayClass29_0
	{
		public string lobbyId;

		public bool abandoned;

		public UniTaskCompletionSource<(Result, JoinFailureReason)> tcs;

		internal void <JoinEosLobbyAsync>b__0(Result result, JoinFailureReason reason)
		{
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: 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_002a: Unknown result type (might be due to invalid IL or missing references)
			if (abandoned)
			{
				if ((int)result == 0)
				{
					Plugin.Log.LogWarning((object)("Abandoned EOS JoinLobby(" + lobbyId + ") completed late with Success; leaving orphan lobby."));
					UniTaskExtensions.Forget(SafeLeaveCurrentEosLobbyAsync());
				}
			}
			else
			{
				tcs.TrySetResult((result, reason));
			}
		}
	}

	[CompilerGenerated]
	private sealed class <>c__DisplayClass32_0
	{
		public UniTaskCompletionSource<Result> leaveTcs;

		internal void <SafeLeaveCurrentEosLobbyAsync>b__0(Result result)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			leaveTcs.TrySetResult(result);
		}
	}

	[CompilerGenerated]
	private sealed class <>c__DisplayClass33_0
	{
		public UniTaskCompletionSource<Result> directTcs;

		internal void <ForceDirectEosLeaveLobbyAsync>b__0(ref LeaveLobbyCallbackInfo info)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			directTcs.TrySetResult(((LeaveLobbyCallbackInfo)(ref info)).ResultCode);
		}
	}

	[StructLayout(LayoutKind.Auto)]
	[CompilerGenerated]
	private struct <CheckHostSanctionAsync>d__30 : IAsyncStateMachine
	{
		public int <>1__state;

		public AsyncUniTaskMethodBuilder<bool> <>t__builder;

		public ProductUserId hostId;

		public CancellationToken cancellationToken;

		private Awaiter<(bool hasResultLeft, bool result)> <>u__1;

		private void MoveNext()
		{
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: 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_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			int num = <>1__state;
			bool result;
			try
			{
				Awaiter<(bool, bool)> val;
				if (num == 0)
				{
					val = <>u__1;
					<>u__1 = default(Awaiter<(bool, bool)>);
					num = (<>1__state = -1);
					goto IL_00a3;
				}
				if (!((Handle)(object)hostId == (Handle)null) && hostId.IsValid())
				{
					UniTask<bool> val2 = CheckHostSanctionSafeAsync(hostId);
					UniTask val3 = UniTask.WaitForSeconds(6f, true, (PlayerLoopTiming)8, cancellationToken, false);
					val = UniTask.WhenAny<bool>(val2, val3).GetAwaiter();
					if (!val.IsCompleted)
					{
						num = (<>1__state = 0);
						<>u__1 = val;
						<>t__builder.AwaitUnsafeOnCompleted<Awaiter<(bool, bool)>, <CheckHostSanctionAsync>d__30>(ref val, ref this);
						return;
					}
					goto IL_00a3;
				}
				result = false;
				goto end_IL_0007;
				IL_00a3:
				var (flag, flag2) = val.GetResult();
				if (!flag)
				{
					Plugin.Log.LogWarning((object)"Host sanction check timed out; proceeding cautiously.");
					result = false;
				}
				else
				{
					result = flag2;
				}
				end_IL_0007:;
			}
			catch (Exception exception)
			{
				<>1__state = -2;
				<>t__builder.SetException(exception);
				return;
			}
			<>1__state = -2;
			<>t__builder.SetResult(result);
		}

		void IAsyncStateMachine.MoveNext()
		{
			//ILSpy generated this explicit interface implementation from .override directive in MoveNext
			this.MoveNext();
		}

		[DebuggerHidden]
		private void SetStateMachine(IAsyncStateMachine stateMachine)
		{
			<>t__builder.SetStateMachine(stateMachine);
		}

		void IAsyncStateMachine.SetStateMachine(IAsyncStateMachine stateMachine)
		{
			//ILSpy generated this explicit interface implementation from .override directive in SetStateMachine
			this.SetStateMachine(stateMachine);
		}
	}

	[StructLayout(LayoutKind.Auto)]
	[CompilerGenerated]
	private struct <CheckHostSanctionSafeAsync>d__31 : IAsyncStateMachine
	{
		public int <>1__state;

		public AsyncUniTaskMethodBuilder<bool> <>t__builder;

		public ProductUserId hostId;

		private Awaiter<bool> <>u__1;

		private void MoveNext()
		{
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			int num = <>1__state;
			bool result;
			try
			{
				try
				{
					Awaiter<bool> val;
					if (num != 0)
					{
						val = BClientAuthenticator.CheckHasMultiplayerSanction(hostId).GetAwaiter();
						if (!val.IsCompleted)
						{
							num = (<>1__state = 0);
							<>u__1 = val;
							<>t__builder.AwaitUnsafeOnCompleted<Awaiter<bool>, <CheckHostSanctionSafeAsync>d__31>(ref val, ref this);
							return;
						}
					}
					else
					{
						val = <>u__1;
						<>u__1 = default(Awaiter<bool>);
						num = (<>1__state = -1);
					}
					result = val.GetResult();
				}
				catch (Exception ex)
				{
					Plugin.LogDebug("Host sanction check faulted: " + ex.Message);
					result = false;
				}
			}
			catch (Exception exception)
			{
				<>1__state = -2;
				<>t__builder.SetException(exception);
				return;
			}
			<>1__state = -2;
			<>t__builder.SetResult(result);
		}

		void IAsyncStateMachine.MoveNext()
		{
			//ILSpy generated this explicit interface implementation from .override directive in MoveNext
			this.MoveNext();
		}

		[DebuggerHidden]
		private void SetStateMachine(IAsyncStateMachine stateMachine)
		{
			<>t__builder.SetStateMachine(stateMachine);
		}

		void IAsyncStateMachine.SetStateMachine(IAsyncStateMachine stateMachine)
		{
			//ILSpy generated this explicit interface implementation from .override directive in SetStateMachine
			this.SetStateMachine(stateMachine);
		}
	}

	[StructLayout(LayoutKind.Auto)]
	[CompilerGenerated]
	private struct <ForceDirectEosLeaveLobbyAsync>d__33 : IAsyncStateMachine
	{
		public int <>1__state;

		public AsyncUniTaskMethodBuilder <>t__builder;

		public string lobbyId;

		public ProductUserId localUserId;

		private Awaiter<(bool hasResultLeft, Result result)> <>u__1;

		private void MoveNext()
		{
			//IL_0123: Unknown result type (might be due to invalid IL or missing references)
			//IL_0128: Unknown result type (might be due to invalid IL or missing references)
			//IL_0130: Unknown result type (might be due to invalid IL or missing references)
			//IL_014e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0153: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0159: Unknown result type (might be due to invalid IL or missing references)
			//IL_0174: Unknown result type (might be due to invalid IL or missing references)
			//IL_015d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0161: Invalid comparison between Unknown and I4
			//IL_0163: Unknown result type (might be due to invalid IL or missing references)
			//IL_0167: Invalid comparison between Unknown and I4
			//IL_0087: 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_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c4: Expected O, but got Unknown
			//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00de: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e3: 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_00ea: 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_00f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0108: Unknown result type (might be due to invalid IL or missing references)
			//IL_010a: Unknown result type (might be due to invalid IL or missing references)
			int num = <>1__state;
			try
			{
				Awaiter<(bool, Result)> val;
				if (num == 0)
				{
					val = <>u__1;
					<>u__1