Decompiled source of ImperialLogistics v1.1.1

ATS_ImperialLogistics.dll

Decompiled 2 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using ATS_API.Effects;
using ATS_API.Helpers;
using ATS_API.Localization;
using ATS_API.Orders;
using ATS_API.Recipes;
using ATS_ImperialLogistics.Camps;
using ATS_ImperialLogistics.Helpers;
using ATS_ImperialLogistics.Overtime;
using ATS_ImperialLogistics.Persistence;
using ATS_ImperialLogistics.Roads;
using ATS_ImperialLogistics.SupplyChain;
using ATS_ImperialLogistics.UI;
using ATS_ImperialLogistics.Workshops;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using Eremite;
using Eremite.Buildings;
using Eremite.Buildings.UI;
using Eremite.Characters;
using Eremite.Controller.Roads;
using Eremite.MapObjects;
using Eremite.Model;
using Eremite.Model.Effects;
using Eremite.Model.Meta;
using Eremite.Model.Orders;
using Eremite.Model.State;
using Eremite.Services;
using Eremite.Services.Monitors;
using Eremite.Services.World;
using Eremite.Sound;
using Eremite.View;
using Eremite.View.HUD.Orders;
using Eremite.View.HUD.Result;
using Eremite.View.Popups;
using Eremite.WorldMap;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using TMPro;
using UniRx;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")]
[assembly: AssemblyCompany("ATS_ImperialLogistics")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.1.1.0")]
[assembly: AssemblyInformationalVersion("1.1.1+d8680c6db21d06ac6d68ecd7b727c50977e98ade")]
[assembly: AssemblyProduct("ATS_ImperialLogistics")]
[assembly: AssemblyTitle("ATS_ImperialLogistics")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.1.1.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class IsReadOnlyAttribute : Attribute
	{
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace ATS_ImperialLogistics
{
	public static class ModConfig
	{
		public static ConfigEntry<bool> EnableSmartSupplyChains;

		public static ConfigEntry<bool> EnableSurplusIngredientPriority;

		public static ConfigEntry<bool> EnableReserveFloors;

		public static ConfigEntry<int> RawFoodSafetyFloor;

		public static ConfigEntry<int> FuelSafetyFloor;

		public static ConfigEntry<bool> EnableSmartIntermediateCaps;

		public static ConfigEntry<int> IntermediateBaseCap;

		public static ConfigEntry<int> IntermediateCapPerConsumer;

		public static ConfigEntry<bool> EnableWorkshopMastery;

		public static ConfigEntry<int> StarterFourthRecipeBuildPacks;

		public static ConfigEntry<int> BlueprintFourthRecipeBuildPacks;

		public static ConfigEntry<int> Grade1UpgradeBuildPacks;

		public static ConfigEntry<int> Grade2UpgradeBuildPacks;

		public static ConfigEntry<int> Grade2UpgradeTradePacks;

		public static ConfigEntry<int> Grade3UpgradeTradePacks;

		public static ConfigEntry<int> Grade3UpgradeWildfireEssence;

		public static ConfigEntry<bool> EnableCampAutoMove;

		public static ConfigEntry<int> WoodcutterAutoMoveBuildPacks;

		public static ConfigEntry<int> GathererAutoMoveBuildPacks;

		public static ConfigEntry<int> CampCartUpgradeTradePacks;

		public static ConfigEntry<int> CampCartUpgradeWildfireEssence;

		public static ConfigEntry<float> WoodcutterFringeRelocateRatio;

		public static ConfigEntry<bool> NotifyOnCampAutoMove;

		public static ConfigEntry<bool> EnableWarehouseAutomatons;

		public static ConfigEntry<int> WarehouseAutomatonBuildPacks;

		public static ConfigEntry<int> WarehouseAutomatonTradePacks;

		public static ConfigEntry<int> WarehouseAutomatonWildfireEssence;

		public static ConfigEntry<bool> EnableImperialOvertime;

		public static ConfigEntry<int> HearthStormWardBuildPacks;

		public static ConfigEntry<int> HearthStormWardWildfireEssence;

		public static ConfigEntry<int> HearthStormWardHostilityReduction;

		public static ConfigEntry<bool> ScaleOvertimeRewardsWithDifficulty;

		public static ConfigEntry<int> Wave1BreadReward;

		public static ConfigEntry<int> Wave2BreadReward;

		public static ConfigEntry<int> Wave2MachineryReward;

		public static ConfigEntry<int> Wave2BonusEmbarkPoints;

		public static ConfigEntry<int> Wave3BreadReward;

		public static ConfigEntry<int> Wave3MachineryReward;

		public static ConfigEntry<int> Wave3ArtifactsReward;

		public static ConfigEntry<int> Wave3BonusEmbarkPoints;

		public static ConfigEntry<int> Wave3BonusCycleVillagers;

		public static ConfigEntry<int> Wave4SealFragmentsReward;

		public static ConfigEntry<int> Wave1ExpReward;

		public static ConfigEntry<int> Wave2ExpReward;

		public static ConfigEntry<int> Wave3ExpReward;

		public static ConfigEntry<int> Wave4ExpReward;

		public static ConfigEntry<bool> EnableOvertimeExcessReputation;

		public static ConfigEntry<int> ExcessReputationAmberReward;

		public static ConfigEntry<int> ExcessReputationBreadReward;

		public static ConfigEntry<int> ExcessReputationExpReward;

		public static ConfigEntry<int> ExcessReputationBonusEveryN;

		public static ConfigEntry<int> ExcessReputationEmbarkPointsCap;

		public static ConfigEntry<float> ExcessReputationStepIncrease;

		public static ConfigEntry<bool> EnableImperialHighways;

		public static ConfigEntry<float> HighwaySpeedBonus;

		public static ConfigEntry<int> HighwayBuildPacksCost;

		public static void Bind(ConfigFile config)
		{
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Expected O, but got Unknown
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Expected O, but got Unknown
			//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fa: Expected O, but got Unknown
			//IL_011e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0128: Expected O, but got Unknown
			//IL_0166: Unknown result type (might be due to invalid IL or missing references)
			//IL_0170: Expected O, but got Unknown
			//IL_0193: Unknown result type (might be due to invalid IL or missing references)
			//IL_019d: Expected O, but got Unknown
			//IL_01c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ca: Expected O, but got Unknown
			//IL_01ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f7: Expected O, but got Unknown
			//IL_021a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0224: Expected O, but got Unknown
			//IL_0247: Unknown result type (might be due to invalid IL or missing references)
			//IL_0251: Expected O, but got Unknown
			//IL_0274: Unknown result type (might be due to invalid IL or missing references)
			//IL_027e: Expected O, but got Unknown
			//IL_02bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c6: Expected O, but got Unknown
			//IL_02e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f3: Expected O, but got Unknown
			//IL_0316: Unknown result type (might be due to invalid IL or missing references)
			//IL_0320: Expected O, but got Unknown
			//IL_0343: Unknown result type (might be due to invalid IL or missing references)
			//IL_034d: Expected O, but got Unknown
			//IL_037b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0385: Expected O, but got Unknown
			//IL_03de: Unknown result type (might be due to invalid IL or missing references)
			//IL_03e8: Expected O, but got Unknown
			//IL_040b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0415: Expected O, but got Unknown
			//IL_0438: Unknown result type (might be due to invalid IL or missing references)
			//IL_0442: Expected O, but got Unknown
			//IL_0481: Unknown result type (might be due to invalid IL or missing references)
			//IL_048b: Expected O, but got Unknown
			//IL_04ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_04b8: Expected O, but got Unknown
			//IL_04df: Unknown result type (might be due to invalid IL or missing references)
			//IL_04e9: Expected O, but got Unknown
			//IL_052a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0534: Expected O, but got Unknown
			//IL_055b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0565: Expected O, but got Unknown
			//IL_0588: Unknown result type (might be due to invalid IL or missing references)
			//IL_0592: Expected O, but got Unknown
			//IL_05b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_05bf: Expected O, but got Unknown
			//IL_05e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_05f0: Expected O, but got Unknown
			//IL_0613: Unknown result type (might be due to invalid IL or missing references)
			//IL_061d: Expected O, but got Unknown
			//IL_0640: Unknown result type (might be due to invalid IL or missing references)
			//IL_064a: Expected O, but got Unknown
			//IL_066d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0677: Expected O, but got Unknown
			//IL_069a: Unknown result type (might be due to invalid IL or missing references)
			//IL_06a4: Expected O, but got Unknown
			//IL_06c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_06d1: Expected O, but got Unknown
			//IL_06f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0702: Expected O, but got Unknown
			//IL_0729: Unknown result type (might be due to invalid IL or missing references)
			//IL_0733: Expected O, but got Unknown
			//IL_075a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0764: Expected O, but got Unknown
			//IL_078b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0795: Expected O, but got Unknown
			//IL_07d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_07e0: Expected O, but got Unknown
			//IL_0803: Unknown result type (might be due to invalid IL or missing references)
			//IL_080d: Expected O, but got Unknown
			//IL_0830: Unknown result type (might be due to invalid IL or missing references)
			//IL_083a: Expected O, but got Unknown
			//IL_085d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0867: Expected O, but got Unknown
			//IL_088a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0894: Expected O, but got Unknown
			//IL_08c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_08cc: Expected O, but got Unknown
			//IL_0915: Unknown result type (might be due to invalid IL or missing references)
			//IL_091f: Expected O, but got Unknown
			//IL_0942: Unknown result type (might be due to invalid IL or missing references)
			//IL_094c: Expected O, but got Unknown
			EnableSmartSupplyChains = config.Bind<bool>("1. Supply Chains", "EnableSmartSupplyChains", true, "Master toggle for automatic ingredient surplus sorting, safety floors, and smart default intermediate caps.");
			EnableSurplusIngredientPriority = config.Bind<bool>("1. Supply Chains", "EnableSurplusIngredientPriority", true, "Automatically prioritize whichever checked ingredient currently has the largest warehouse stockpile.");
			EnableReserveFloors = config.Bind<bool>("1. Supply Chains", "EnableReserveFloors", true, "Protect minimum edible Raw Food and Fuel stocks from being consumed by non-food/non-fuel workshop recipes.");
			RawFoodSafetyFloor = config.Bind<int>("1. Supply Chains", "RawFoodSafetyFloor", 25, new ConfigDescription("Minimum total edible raw food kept safe from non-food crafting recipes.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 200), Array.Empty<object>()));
			FuelSafetyFloor = config.Bind<int>("1. Supply Chains", "FuelSafetyFloor", 25, new ConfigDescription("Minimum total fuel (Wood + Coal + Sea Marrow + Oil) kept safe from non-fuel crafting recipes.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 200), Array.Empty<object>()));
			EnableSmartIntermediateCaps = config.Bind<bool>("1. Supply Chains", "EnableSmartIntermediateCaps", true, "Automatically set demand-scaled production limits on intermediate goods (Planks, Flour, Containers, etc.) unless manually edited.");
			IntermediateBaseCap = config.Bind<int>("1. Supply Chains", "IntermediateBaseCap", 25, new ConfigDescription("Base production limit assigned to intermediate goods.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(5, 200), Array.Empty<object>()));
			IntermediateCapPerConsumer = config.Bind<int>("1. Supply Chains", "IntermediateCapPerConsumer", 10, new ConfigDescription("Additional production cap added per active downstream workshop recipe using that intermediate.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), Array.Empty<object>()));
			EnableWorkshopMastery = config.Bind<bool>("2. Workshop Mastery", "EnableWorkshopMastery", true, "Allow unlocking 1 curated thematic 4th recipe per workshop and upgrading individual recipe star ratings.");
			StarterFourthRecipeBuildPacks = config.Bind<int>("2. Workshop Mastery", "StarterFourthRecipeBuildPacks", 4, new ConfigDescription("Packs of Building Materials required to unlock the 4th recipe on Crude Workstation / Field Kitchen / Makeshift Post.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 50), Array.Empty<object>()));
			BlueprintFourthRecipeBuildPacks = config.Bind<int>("2. Workshop Mastery", "BlueprintFourthRecipeBuildPacks", 6, new ConfigDescription("Packs of Building Materials required to unlock the curated 4th recipe on standard workshops.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 50), Array.Empty<object>()));
			Grade1UpgradeBuildPacks = config.Bind<int>("2. Workshop Mastery", "Grade1UpgradeBuildPacks", 4, new ConfigDescription("Packs of Building Materials required to upgrade a single 0-star recipe to 1-star.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 50), Array.Empty<object>()));
			Grade2UpgradeBuildPacks = config.Bind<int>("2. Workshop Mastery", "Grade2UpgradeBuildPacks", 5, new ConfigDescription("Packs of Building Materials required (alongside Trade Packs) to upgrade a single 1-star recipe to 2-star.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 50), Array.Empty<object>()));
			Grade2UpgradeTradePacks = config.Bind<int>("2. Workshop Mastery", "Grade2UpgradeTradePacks", 3, new ConfigDescription("Packs of Trade Goods required to upgrade a single 1-star recipe to 2-star.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 50), Array.Empty<object>()));
			Grade3UpgradeTradePacks = config.Bind<int>("2. Workshop Mastery", "Grade3UpgradeTradePacks", 6, new ConfigDescription("Packs of Trade Goods required (alongside Wildfire Essence) to master a single 2-star recipe to 3-star.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 50), Array.Empty<object>()));
			Grade3UpgradeWildfireEssence = config.Bind<int>("2. Workshop Mastery", "Grade3UpgradeWildfireEssence", 1, new ConfigDescription("Wildfire Essence required to master a single 2-star recipe to 3-star.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 20), Array.Empty<object>()));
			EnableCampAutoMove = config.Bind<bool>("3. Camp Auto-Move", "EnableCampAutoMove", true, "Allow unlocking Smart Auto-Move and Outpost Cart upgrades on Woodcutters and Gathering Camps.");
			WoodcutterAutoMoveBuildPacks = config.Bind<int>("3. Camp Auto-Move", "WoodcutterAutoMoveBuildPacks", 3, new ConfigDescription("Packs of Building Materials required to unlock Smart Auto-Move on a Woodcutters' Camp.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 50), Array.Empty<object>()));
			GathererAutoMoveBuildPacks = config.Bind<int>("3. Camp Auto-Move", "GathererAutoMoveBuildPacks", 4, new ConfigDescription("Packs of Building Materials required to unlock Smart Auto-Move on a Gathering Camp.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 50), Array.Empty<object>()));
			CampCartUpgradeTradePacks = config.Bind<int>("3. Camp Auto-Move", "CampCartUpgradeTradePacks", 4, new ConfigDescription("Packs of Trade Goods required for Tier 2 Camp Outpost Carts (+5 carry capacity & +20% gather speed).", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 50), Array.Empty<object>()));
			CampCartUpgradeWildfireEssence = config.Bind<int>("3. Camp Auto-Move", "CampCartUpgradeWildfireEssence", 1, new ConfigDescription("Wildfire Essence required for Tier 2 Camp Outpost Carts.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 20), Array.Empty<object>()));
			WoodcutterFringeRelocateRatio = config.Bind<float>("3. Camp Auto-Move", "WoodcutterFringeRelocateRatio", 0.85f, new ConfigDescription("Relocate Woodcutters early if the closest valid tree is beyond this fraction of max radius (1.0 = wait until completely empty).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.5f, 1.05f), Array.Empty<object>()));
			NotifyOnCampAutoMove = config.Bind<bool>("3. Camp Auto-Move", "NotifyOnCampAutoMove", true, "Publish a subtle settlement notification whenever a camp automatically relocates.");
			EnableWarehouseAutomatons = config.Bind<bool>("3. Camp Auto-Move", "EnableWarehouseAutomatons", true, "Allow deploying Warehouse Hauler Automatons & +5 Carry Capacity on Main and Small Warehouses (available anytime from Year 1).");
			WarehouseAutomatonBuildPacks = config.Bind<int>("3. Camp Auto-Move", "WarehouseAutomatonBuildPacks", 8, new ConfigDescription("Packs of Building Materials required to deploy a Warehouse Hauler Automaton & +5 Carry Capacity.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 50), Array.Empty<object>()));
			WarehouseAutomatonTradePacks = config.Bind<int>("3. Camp Auto-Move", "WarehouseAutomatonTradePacks", 6, new ConfigDescription("Packs of Trade Goods required to deploy a Warehouse Hauler Automaton.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 50), Array.Empty<object>()));
			WarehouseAutomatonWildfireEssence = config.Bind<int>("3. Camp Auto-Move", "WarehouseAutomatonWildfireEssence", 1, new ConfigDescription("Wildfire Essence required to deploy a Warehouse Hauler Automaton.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 20), Array.Empty<object>()));
			EnableImperialOvertime = config.Bind<bool>("4. Continue Settlement Overtime", "EnableImperialOvertime", true, "Enable Grand Orders, persistent Citadel Bread/Machinery/Artifact rewards, and Hearth Storm-Wards in Continue Settlement.");
			HearthStormWardBuildPacks = config.Bind<int>("4. Continue Settlement Overtime", "HearthStormWardBuildPacks", 10, new ConfigDescription("Packs of Building Materials required to light a Hearth Storm-Ward in Continue Settlement.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 50), Array.Empty<object>()));
			HearthStormWardWildfireEssence = config.Bind<int>("4. Continue Settlement Overtime", "HearthStormWardWildfireEssence", 2, new ConfigDescription("Wildfire Essence required to light a Hearth Storm-Ward.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 20), Array.Empty<object>()));
			HearthStormWardHostilityReduction = config.Bind<int>("4. Continue Settlement Overtime", "HearthStormWardHostilityReduction", 45, new ConfigDescription("Hostility removed per upgraded Hearth Storm-Ward (offsets 1 year of passive hostility scaling).", (AcceptableValueBase)(object)new AcceptableValueRange<int>(5, 300), Array.Empty<object>()));
			ScaleOvertimeRewardsWithDifficulty = config.Bind<bool>("4. Continue Settlement Overtime", "ScaleOvertimeRewardsWithDifficulty", true, "Scale Grand Order Citadel currency payouts (Food Stockpiles, Machinery, Artifacts) by the settlement's DifficultyModel.rewardsMultiplier and Smoldering City % currency bonus.");
			Wave1BreadReward = config.Bind<int>("4. Continue Settlement Overtime", "Wave1BreadReward", 8, new ConfigDescription("Base (1.0x Settler) Citadel Food Stockpiles granted by Grand Order I.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 200), Array.Empty<object>()));
			Wave2BreadReward = config.Bind<int>("4. Continue Settlement Overtime", "Wave2BreadReward", 12, new ConfigDescription("Base (1.0x Settler) Citadel Food Stockpiles granted by Grand Order II.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 200), Array.Empty<object>()));
			Wave2MachineryReward = config.Bind<int>("4. Continue Settlement Overtime", "Wave2MachineryReward", 3, new ConfigDescription("Base (1.0x Settler) Citadel Machinery granted by Grand Order II.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), Array.Empty<object>()));
			Wave2BonusEmbarkPoints = config.Bind<int>("4. Continue Settlement Overtime", "Wave2BonusEmbarkPoints", 1, new ConfigDescription("Bonus Embarkation Points for remaining Cycle granted by Grand Order II.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 20), Array.Empty<object>()));
			Wave3BreadReward = config.Bind<int>("4. Continue Settlement Overtime", "Wave3BreadReward", 16, new ConfigDescription("Base (1.0x Settler) Citadel Food Stockpiles granted by Grand Order III.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 200), Array.Empty<object>()));
			Wave3MachineryReward = config.Bind<int>("4. Continue Settlement Overtime", "Wave3MachineryReward", 4, new ConfigDescription("Base (1.0x Settler) Citadel Machinery granted by Grand Order III.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), Array.Empty<object>()));
			Wave3ArtifactsReward = config.Bind<int>("4. Continue Settlement Overtime", "Wave3ArtifactsReward", 4, new ConfigDescription("Base (1.0x Settler) Citadel Artifacts granted by Grand Order III.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), Array.Empty<object>()));
			Wave3BonusEmbarkPoints = config.Bind<int>("4. Continue Settlement Overtime", "Wave3BonusEmbarkPoints", 1, new ConfigDescription("Bonus Embarkation Points for remaining Cycle granted by Grand Order III.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 20), Array.Empty<object>()));
			Wave3BonusCycleVillagers = config.Bind<int>("4. Continue Settlement Overtime", "Wave3BonusCycleVillagers", 1, new ConfigDescription("Bonus Starting Villagers for remaining Cycle granted by Grand Order III.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 10), Array.Empty<object>()));
			Wave4SealFragmentsReward = config.Bind<int>("4. Continue Settlement Overtime", "Wave4SealFragmentsReward", 1, new ConfigDescription("Base (1.0x Settler) Cycle Seal Fragments (Shards) granted by Grand Order IV (scales with Difficulty multiplier when enabled).", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 15), Array.Empty<object>()));
			Wave1ExpReward = config.Bind<int>("4. Continue Settlement Overtime", "Wave1ExpReward", 15, new ConfigDescription("Base (1.0x Settler) Smoldering City XP granted by Grand Order I (scales with Difficulty multiplier when enabled).", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 300), Array.Empty<object>()));
			Wave2ExpReward = config.Bind<int>("4. Continue Settlement Overtime", "Wave2ExpReward", 25, new ConfigDescription("Base (1.0x Settler) Smoldering City XP granted by Grand Order II (scales with Difficulty multiplier when enabled).", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 300), Array.Empty<object>()));
			Wave3ExpReward = config.Bind<int>("4. Continue Settlement Overtime", "Wave3ExpReward", 35, new ConfigDescription("Base (1.0x Settler) Smoldering City XP granted by Grand Order III (scales with Difficulty multiplier when enabled).", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 300), Array.Empty<object>()));
			Wave4ExpReward = config.Bind<int>("4. Continue Settlement Overtime", "Wave4ExpReward", 45, new ConfigDescription("Base (1.0x Settler) Smoldering City XP granted by Grand Order IV (scales with Difficulty multiplier when enabled).", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 300), Array.Empty<object>()));
			EnableOvertimeExcessReputation = config.Bind<bool>("4. Continue Settlement Overtime", "EnableOvertimeExcessReputation", true, "Reward surplus Reputation earned past Victory (from High Resolve, Caches, Glade Events, Orders, and Perks) during Continue Settlement.");
			ExcessReputationAmberReward = config.Bind<int>("4. Continue Settlement Overtime", "ExcessReputationAmberReward", 5, new ConfigDescription("Amber delivered to Main Warehouse for each Excess Reputation Acclaim milestone in Overtime.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 200), Array.Empty<object>()));
			ExcessReputationBreadReward = config.Bind<int>("4. Continue Settlement Overtime", "ExcessReputationBreadReward", 1, new ConfigDescription("Base (1.0x Settler) Citadel Food Stockpiles banked permanently for each Excess Reputation Acclaim milestone in Overtime.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 50), Array.Empty<object>()));
			ExcessReputationExpReward = config.Bind<int>("4. Continue Settlement Overtime", "ExcessReputationExpReward", 5, new ConfigDescription("Base (1.0x Settler) Smoldering City XP granted for each Excess Reputation Acclaim milestone in Overtime (scales with Difficulty).", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), Array.Empty<object>()));
			ExcessReputationBonusEveryN = config.Bind<int>("4. Continue Settlement Overtime", "ExcessReputationBonusEveryN", 5, new ConfigDescription("Every Nth Excess Reputation milestone triggers a Major Acclaim (+1 Wildfire Essence plus +1 Cycle Embarkation Point up to cap, then alternating Machinery or Artifact).", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 20), Array.Empty<object>()));
			ExcessReputationEmbarkPointsCap = config.Bind<int>("4. Continue Settlement Overtime", "ExcessReputationEmbarkPointsCap", 1, new ConfigDescription("Max Cycle Embarkation Points earnable per settlement from Major Excess Reputation milestones (0 = unlimited). Once capped, Major Acclaim alternates between Machinery and Artifact.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 20), Array.Empty<object>()));
			ExcessReputationStepIncrease = config.Bind<float>("4. Continue Settlement Overtime", "ExcessReputationStepIncrease", 0.5f, new ConfigDescription("Extra Reputation required per subsequent Excess Reputation milestone (e.g., 0.5 = 1.0, 1.5, 2.0, 2.5...; 0.0 = flat 1.0).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 5f), Array.Empty<object>()));
			EnableImperialHighways = config.Bind<bool>("5. Imperial Highways", "EnableImperialHighways", true, "Unlock Tier 4 Imperial Highways in the Roads build menu in all settlements (available anytime from Year 1).");
			HighwaySpeedBonus = config.Bind<float>("5. Imperial Highways", "HighwaySpeedBonus", 0.45f, new ConfigDescription("Villager walk speed bonus on Imperial Highways (0.45 = +45%, 1.50 = +150%, 5.00 = +500% walk speed).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.3f, 5f), Array.Empty<object>()));
			HighwayBuildPacksCost = config.Bind<int>("5. Imperial Highways", "HighwayBuildPacksCost", 1, new ConfigDescription("Packs of Building Materials required per Imperial Highway tile (0 = free).", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 10), Array.Empty<object>()));
		}
	}
	[BepInPlugin("com.pdewilde.ats.imperiallogistics", "Imperial Logistics & Overtime", "1.1.1")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class Plugin : BaseUnityPlugin
	{
		public const string PluginGuid = "com.pdewilde.ats.imperiallogistics";

		public const string PluginName = "Imperial Logistics & Overtime";

		public const string PluginVersion = "1.1.1";

		internal static ManualLogSource Log;

		private Harmony _harmony;

		private float _nextSlowTickTime;

		private bool _settlementReady;

		private const float SlowTickInterval = 4f;

		private void Awake()
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Expected O, but got Unknown
			Log = ((BaseUnityPlugin)this).Logger;
			((Object)((Component)this).gameObject).hideFlags = (HideFlags)61;
			ModConfig.Bind(((BaseUnityPlugin)this).Config);
			_harmony = new Harmony("com.pdewilde.ats.imperiallogistics");
			_harmony.PatchAll(typeof(Plugin).Assembly);
			EventBus.OnInitReferences.AddListener((Action)OnInitReferences);
			EventBus.OnStartGame.AddListener((Action<bool>)OnStartSettlement);
			Log.LogInfo((object)"Imperial Logistics & Overtime v1.1.1 loaded!");
		}

		private void OnDestroy()
		{
			ImperialOvertimeManager.OnSettlementEnded();
		}

		private void OnInitReferences()
		{
			try
			{
				SmartSupplyChainManager.EnsureInitialized();
				WorkshopMasteryManager.RegisterUpgradedRecipesOnInit();
				ImperialOvertimeManager.RegisterModelsOnInit();
				ImperialHighwayManager.RegisterOnInit();
			}
			catch (Exception arg)
			{
				Log.LogError((object)$"Error during OnInitReferences: {arg}");
			}
		}

		private void OnStartSettlement(bool isNewSettlement)
		{
			try
			{
				VanillaSaveConverter.OnSettlementEnded();
				SettlementModState.LoadForSession(isNewSettlement);
				VanillaSaveConverter.SanitizeMetaAndWorldSavesInMemory();
				WorkshopMasteryManager.SyncRecipeMapToState();
				SmartSupplyChainManager.OnSettlementStarted();
				SmartCampAutoMover.OnSettlementStarted();
				ImperialHighwayManager.OnSettlementStarted();
				ImperialOvertimeManager.OnSettlementStarted();
				_settlementReady = true;
				_nextSlowTickTime = Time.unscaledTime + 1.5f;
				Log.LogInfo((object)$"Settlement session initialized (isNewSettlement={isNewSettlement}).");
			}
			catch (Exception arg)
			{
				Log.LogError((object)$"Error during OnStartSettlement: {arg}");
			}
		}

		private void Update()
		{
			if (!Svc.Active)
			{
				if (_settlementReady)
				{
					_settlementReady = false;
					ImperialOvertimeManager.OnSettlementEnded();
					VanillaSaveConverter.OnSettlementEnded();
				}
			}
			else if (_settlementReady && !VanillaSaveConverter.IsRevertLocked && !(Time.unscaledTime < _nextSlowTickTime))
			{
				_nextSlowTickTime = Time.unscaledTime + 4f;
				try
				{
					SmartSupplyChainManager.Tick();
					SmartCampAutoMover.Tick();
					ImperialOvertimeManager.Tick();
				}
				catch (Exception arg)
				{
					Log.LogError((object)$"Error in ImperialLogistics slow tick: {arg}");
				}
			}
		}
	}
}
namespace ATS_ImperialLogistics.Workshops
{
	public static class WorkshopMasteryManager
	{
		private static readonly Dictionary<string, WorkshopRecipeModel> NextGradeLookup = new Dictionary<string, WorkshopRecipeModel>(StringComparer.Ordinal);

		private static readonly Dictionary<string, string> CloneToVanillaRecipeName = new Dictionary<string, string>(StringComparer.Ordinal);

		private static readonly Dictionary<string, WorkshopRecipeModel> OneStarByGood = new Dictionary<string, WorkshopRecipeModel>(StringComparer.Ordinal);

		private static Dictionary<string, string> _curatedFourthGoodByWorkshop;

		private static HashSet<string> _starterWorkshops;

		private static HashSet<string> _excludedWorkshops;

		private static bool _registered;

		public static void RegisterUpgradedRecipesOnInit()
		{
			if (_registered || Svc.Cfg?.workshopsRecipes == null)
			{
				return;
			}
			_registered = true;
			BuildCuratedTable();
			RecipeGradeModel value = GradeExtensions.ToModel((Grade)1);
			RecipeGradeModel val = GradeExtensions.ToModel((Grade)2);
			RecipeGradeModel val2 = GradeExtensions.ToModel((Grade)3);
			RecipeGradeModel val3 = GradeExtensions.ToModel((Grade)4);
			Dictionary<int, RecipeGradeModel> dictionary = new Dictionary<int, RecipeGradeModel>
			{
				{ 0, value },
				{ 1, val },
				{ 2, val2 },
				{ 3, val3 }
			};
			List<WorkshopRecipeModel> list = Svc.Cfg.workshopsRecipes.Where((WorkshopRecipeModel r) => (Object)(object)r != (Object)null && (Object)(object)r.producedGood?.good != (Object)null && !((SO)r).Name.Contains("_ImpG") && ((SO)r).Name.IndexOf("todelete", StringComparison.OrdinalIgnoreCase) < 0).ToList();
			foreach (WorkshopRecipeModel item in list)
			{
				int num = ((!((Object)(object)((RecipeModel)item).grade != (Object)null)) ? 1 : ((RecipeModel)item).grade.level);
				string producedGood = ((RecipeModel)item).GetProducedGood();
				if (num == 1 && !string.IsNullOrEmpty(producedGood) && !OneStarByGood.ContainsKey(producedGood))
				{
					OneStarByGood[producedGood] = item;
				}
			}
			int num2 = 0;
			foreach (WorkshopRecipeModel item2 in list)
			{
				int num3 = ((!((Object)(object)((RecipeModel)item2).grade != (Object)null)) ? 1 : Mathf.Clamp(((RecipeModel)item2).grade.level, 0, 3));
				WorkshopRecipeModel val4 = item2;
				for (int num4 = num3 + 1; num4 <= 3; num4++)
				{
					string text = $"{SanitizeName(((SO)item2).Name)}_ImpG{num4}";
					string cloneName = "com.pdewilde.ats.imperiallogistics_" + text;
					WorkshopRecipeModel val5 = CreateSteppedGradeClone(val4, num4, dictionary[num4], cloneName);
					RecipeManager.AddRecipe<WorkshopRecipeModel>("com.pdewilde.ats.imperiallogistics", text, val5);
					NextGradeLookup[((SO)val4).Name] = val5;
					CloneToVanillaRecipeName[((SO)val5).Name] = ((SO)item2).Name;
					string producedGood2 = ((RecipeModel)val5).GetProducedGood();
					if (num4 == 1 && !string.IsNullOrEmpty(producedGood2) && !OneStarByGood.ContainsKey(producedGood2))
					{
						OneStarByGood[producedGood2] = val5;
					}
					val4 = val5;
					num2++;
				}
			}
			foreach (WorkshopRecipeModel item3 in list)
			{
				string producedGood3 = ((RecipeModel)item3).GetProducedGood();
				if (!string.IsNullOrEmpty(producedGood3) && !OneStarByGood.ContainsKey(producedGood3))
				{
					string text2 = SanitizeName(((SO)item3).Name) + "_ImpBaseG1";
					string cloneName2 = "com.pdewilde.ats.imperiallogistics_" + text2;
					WorkshopRecipeModel val6 = CreateDownscaledOneStarClone(item3, val, cloneName2);
					RecipeManager.AddRecipe<WorkshopRecipeModel>("com.pdewilde.ats.imperiallogistics", text2, val6);
					OneStarByGood[producedGood3] = val6;
					CloneToVanillaRecipeName[((SO)val6).Name] = ((SO)item3).Name;
					string text3 = text2 + "_ImpG2";
					WorkshopRecipeModel val7 = CreateSteppedGradeClone(val6, 2, val2, "com.pdewilde.ats.imperiallogistics_" + text3);
					RecipeManager.AddRecipe<WorkshopRecipeModel>("com.pdewilde.ats.imperiallogistics", text3, val7);
					NextGradeLookup[((SO)val6).Name] = val7;
					CloneToVanillaRecipeName[((SO)val7).Name] = ((SO)item3).Name;
					string text4 = text2 + "_ImpG3";
					WorkshopRecipeModel val8 = CreateSteppedGradeClone(val7, 3, val3, "com.pdewilde.ats.imperiallogistics_" + text4);
					RecipeManager.AddRecipe<WorkshopRecipeModel>("com.pdewilde.ats.imperiallogistics", text4, val8);
					NextGradeLookup[((SO)val7).Name] = val8;
					CloneToVanillaRecipeName[((SO)val8).Name] = ((SO)item3).Name;
					num2 += 3;
				}
			}
			RecipeManager.SyncRecipes();
			Plugin.Log.LogInfo((object)$"WorkshopMasteryManager registered {num2} stepped star-upgrade recipes.");
		}

		public static bool TryGetBaseVanillaRecipeName(string cloneModelName, out string vanillaName)
		{
			vanillaName = null;
			if (string.IsNullOrEmpty(cloneModelName))
			{
				return false;
			}
			if (CloneToVanillaRecipeName.TryGetValue(cloneModelName, out vanillaName))
			{
				return true;
			}
			if (cloneModelName.IndexOf("_Imp", StringComparison.Ordinal) > 0)
			{
				foreach (KeyValuePair<string, string> item in CloneToVanillaRecipeName)
				{
					if (item.Key.EndsWith(cloneModelName.Substring(cloneModelName.IndexOf('_') + 1), StringComparison.Ordinal))
					{
						vanillaName = item.Value;
						return true;
					}
				}
			}
			return false;
		}

		public static void SyncRecipeMapToState()
		{
			IBuildingsService buildings = Svc.Buildings;
			if (((buildings != null) ? buildings.Workshops : null) == null)
			{
				return;
			}
			Dictionary<string, string> cloneToVanillaRecipeMap = SettlementModState.Current.CloneToVanillaRecipeMap;
			bool flag = false;
			foreach (Workshop value2 in Svc.Buildings.Workshops.Values)
			{
				if (value2?.state?.recipes == null)
				{
					continue;
				}
				foreach (WorkshopRecipeState recipe in value2.state.recipes)
				{
					if (recipe != null && TryGetBaseVanillaRecipeName(((RecipeState)recipe).model, out var vanillaName) && (!cloneToVanillaRecipeMap.TryGetValue(((RecipeState)recipe).model, out var value) || !string.Equals(value, vanillaName, StringComparison.Ordinal)))
					{
						cloneToVanillaRecipeMap[((RecipeState)recipe).model] = vanillaName;
						flag = true;
					}
				}
			}
			if (flag)
			{
				SettlementModState.Save();
			}
		}

		private static string SanitizeName(string raw)
		{
			if (string.IsNullOrEmpty(raw))
			{
				return "Recipe";
			}
			return raw.Replace(" ", "_").Replace("[", "").Replace("]", "");
		}

		private static WorkshopRecipeModel CreateSteppedGradeClone(WorkshopRecipeModel source, int targetLevel, RecipeGradeModel targetGrade, string cloneName)
		{
			//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_0174: Unknown result type (might be due to invalid IL or missing references)
			//IL_018a: Expected O, but got Unknown
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Expected O, but got Unknown
			//IL_0103: 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_011c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0125: Expected O, but got Unknown
			WorkshopRecipeModel val = Object.Instantiate<WorkshopRecipeModel>(source);
			((Object)val).name = cloneName;
			((Object)val).hideFlags = (HideFlags)61;
			((RecipeModel)val).grade = targetGrade;
			val.productionTime = Mathf.Max(4f, Mathf.Round(source.productionTime * 0.82f));
			int num = 0;
			int num2 = 0;
			if (source.requiredGoods != null)
			{
				GoodsSet[] array = (GoodsSet[])(object)new GoodsSet[source.requiredGoods.Length];
				for (int i = 0; i < source.requiredGoods.Length; i++)
				{
					GoodsSet val2 = source.requiredGoods[i];
					GoodsSet val3 = new GoodsSet();
					if (val2?.goods != null)
					{
						val3.goods = (GoodRef[])(object)new GoodRef[val2.goods.Length];
						for (int j = 0; j < val2.goods.Length; j++)
						{
							GoodRef val4 = val2.goods[j];
							int num3 = val4?.amount ?? 1;
							num += num3;
							int num4 = ((num3 <= 1) ? 1 : Mathf.Max(1, Mathf.FloorToInt((float)num3 * 0.8f)));
							if (num4 == num3 && num3 >= 3)
							{
								num4 = num3 - 1;
							}
							num2 += num4;
							val3.goods[j] = new GoodRef
							{
								good = val4?.good,
								amount = num4
							};
						}
					}
					array[i] = val3;
				}
				val.requiredGoods = array;
			}
			val.producedGood = new GoodRef
			{
				good = source.producedGood.good,
				amount = source.producedGood.amount
			};
			if (num > 0 && num2 == num)
			{
				val.producedGood.amount = source.producedGood.amount + 1;
			}
			return val;
		}

		private static WorkshopRecipeModel CreateDownscaledOneStarClone(WorkshopRecipeModel highStarSource, RecipeGradeModel grade1, string cloneName)
		{
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Expected O, but got Unknown
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c0: Expected O, but got Unknown
			//IL_00ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0104: Unknown result type (might be due to invalid IL or missing references)
			//IL_0118: Unknown result type (might be due to invalid IL or missing references)
			//IL_013b: Expected O, but got Unknown
			WorkshopRecipeModel val = Object.Instantiate<WorkshopRecipeModel>(highStarSource);
			((Object)val).name = cloneName;
			((Object)val).hideFlags = (HideFlags)61;
			((RecipeModel)val).grade = grade1;
			float num = (((((Object)(object)((RecipeModel)highStarSource).grade != (Object)null) ? Mathf.Max(1, ((RecipeModel)highStarSource).grade.level) : 2) >= 3) ? 1.4f : 1.2f);
			val.productionTime = Mathf.Round(highStarSource.productionTime * num);
			val.producedGood = new GoodRef
			{
				good = highStarSource.producedGood.good,
				amount = highStarSource.producedGood.amount
			};
			if (highStarSource.requiredGoods != null)
			{
				GoodsSet[] array = (GoodsSet[])(object)new GoodsSet[highStarSource.requiredGoods.Length];
				for (int i = 0; i < highStarSource.requiredGoods.Length; i++)
				{
					GoodsSet val2 = highStarSource.requiredGoods[i];
					GoodsSet val3 = new GoodsSet();
					if (val2?.goods != null)
					{
						val3.goods = (GoodRef[])(object)new GoodRef[val2.goods.Length];
						for (int j = 0; j < val2.goods.Length; j++)
						{
							GoodRef val4 = val2.goods[j];
							val3.goods[j] = new GoodRef
							{
								good = val4?.good,
								amount = Mathf.Max(1, Mathf.CeilToInt((float)(val4?.amount ?? 1) * num))
							};
						}
					}
					array[i] = val3;
				}
				val.requiredGoods = array;
			}
			return val;
		}

		private static void BuildCuratedTable()
		{
			string value = GoodsTypesExtensions.ToName((GoodsTypes)7);
			string value2 = GoodsTypesExtensions.ToName((GoodsTypes)67);
			string value3 = GoodsTypesExtensions.ToName((GoodsTypes)68);
			string value4 = GoodsTypesExtensions.ToName((GoodsTypes)69);
			string value5 = GoodsTypesExtensions.ToName((GoodsTypes)6);
			GoodsTypesExtensions.ToName((GoodsTypes)8);
			string value6 = GoodsTypesExtensions.ToName((GoodsTypes)5);
			string value7 = GoodsTypesExtensions.ToName((GoodsTypes)33);
			string value8 = GoodsTypesExtensions.ToName((GoodsTypes)30);
			string value9 = GoodsTypesExtensions.ToName((GoodsTypes)44);
			string value10 = GoodsTypesExtensions.ToName((GoodsTypes)63);
			string value11 = GoodsTypesExtensions.ToName((GoodsTypes)57);
			string value12 = GoodsTypesExtensions.ToName((GoodsTypes)61);
			string value13 = GoodsTypesExtensions.ToName((GoodsTypes)58);
			string value14 = GoodsTypesExtensions.ToName((GoodsTypes)60);
			string value15 = GoodsTypesExtensions.ToName((GoodsTypes)59);
			string value16 = GoodsTypesExtensions.ToName((GoodsTypes)17);
			string value17 = GoodsTypesExtensions.ToName((GoodsTypes)12);
			string value18 = GoodsTypesExtensions.ToName((GoodsTypes)49);
			string value19 = GoodsTypesExtensions.ToName((GoodsTypes)51);
			string value20 = GoodsTypesExtensions.ToName((GoodsTypes)50);
			string value21 = GoodsTypesExtensions.ToName((GoodsTypes)47);
			string value22 = GoodsTypesExtensions.ToName((GoodsTypes)53);
			_starterWorkshops = new HashSet<string>(StringComparer.Ordinal)
			{
				WorkshopTypesExtensions.ToName((WorkshopTypes)18),
				WorkshopTypesExtensions.ToName((WorkshopTypes)21),
				WorkshopTypesExtensions.ToName((WorkshopTypes)37)
			};
			_excludedWorkshops = new HashSet<string>(StringComparer.Ordinal) { WorkshopTypesExtensions.ToName((WorkshopTypes)57) };
			_curatedFourthGoodByWorkshop = new Dictionary<string, string>(StringComparer.Ordinal)
			{
				{
					WorkshopTypesExtensions.ToName((WorkshopTypes)21),
					value
				},
				{
					WorkshopTypesExtensions.ToName((WorkshopTypes)18),
					value2
				},
				{
					WorkshopTypesExtensions.ToName((WorkshopTypes)37),
					value12
				},
				{
					WorkshopTypesExtensions.ToName((WorkshopTypes)36),
					value2
				},
				{
					WorkshopTypesExtensions.ToName((WorkshopTypes)11),
					value2
				},
				{
					WorkshopTypesExtensions.ToName((WorkshopTypes)56),
					value11
				},
				{
					WorkshopTypesExtensions.ToName((WorkshopTypes)8),
					value6
				},
				{
					WorkshopTypesExtensions.ToName((WorkshopTypes)34),
					value3
				},
				{
					WorkshopTypesExtensions.ToName((WorkshopTypes)49),
					value3
				},
				{
					WorkshopTypesExtensions.ToName((WorkshopTypes)50),
					value2
				},
				{
					WorkshopTypesExtensions.ToName((WorkshopTypes)13),
					value3
				},
				{
					WorkshopTypesExtensions.ToName((WorkshopTypes)42),
					value13
				},
				{
					WorkshopTypesExtensions.ToName((WorkshopTypes)28),
					value13
				},
				{
					WorkshopTypesExtensions.ToName((WorkshopTypes)31),
					value
				},
				{
					WorkshopTypesExtensions.ToName((WorkshopTypes)32),
					value13
				},
				{
					WorkshopTypesExtensions.ToName((WorkshopTypes)44),
					value4
				},
				{
					WorkshopTypesExtensions.ToName((WorkshopTypes)4),
					value
				},
				{
					WorkshopTypesExtensions.ToName((WorkshopTypes)16),
					value14
				},
				{
					WorkshopTypesExtensions.ToName((WorkshopTypes)33),
					value6
				},
				{
					WorkshopTypesExtensions.ToName((WorkshopTypes)48),
					value16
				},
				{
					WorkshopTypesExtensions.ToName((WorkshopTypes)9),
					value4
				},
				{
					WorkshopTypesExtensions.ToName((WorkshopTypes)12),
					value2
				},
				{
					WorkshopTypesExtensions.ToName((WorkshopTypes)24),
					value2
				},
				{
					WorkshopTypesExtensions.ToName((WorkshopTypes)5),
					value3
				},
				{
					WorkshopTypesExtensions.ToName((WorkshopTypes)10),
					value2
				},
				{
					WorkshopTypesExtensions.ToName((WorkshopTypes)39),
					value14
				},
				{
					WorkshopTypesExtensions.ToName((WorkshopTypes)41),
					value4
				},
				{
					WorkshopTypesExtensions.ToName((WorkshopTypes)6),
					value2
				},
				{
					WorkshopTypesExtensions.ToName((WorkshopTypes)23),
					value2
				},
				{
					WorkshopTypesExtensions.ToName((WorkshopTypes)19),
					value21
				},
				{
					WorkshopTypesExtensions.ToName((WorkshopTypes)51),
					value3
				},
				{
					WorkshopTypesExtensions.ToName((WorkshopTypes)2),
					value5
				},
				{
					WorkshopTypesExtensions.ToName((WorkshopTypes)1),
					value22
				},
				{
					WorkshopTypesExtensions.ToName((WorkshopTypes)20),
					value20
				},
				{
					WorkshopTypesExtensions.ToName((WorkshopTypes)26),
					value20
				},
				{
					WorkshopTypesExtensions.ToName((WorkshopTypes)40),
					value
				},
				{
					WorkshopTypesExtensions.ToName((WorkshopTypes)52),
					value19
				},
				{
					WorkshopTypesExtensions.ToName((WorkshopTypes)45),
					value5
				},
				{
					WorkshopTypesExtensions.ToName((WorkshopTypes)3),
					value15
				},
				{
					WorkshopTypesExtensions.ToName((WorkshopTypes)55),
					value18
				},
				{
					WorkshopTypesExtensions.ToName((WorkshopTypes)14),
					value8
				},
				{
					WorkshopTypesExtensions.ToName((WorkshopTypes)35),
					value18
				},
				{
					WorkshopTypesExtensions.ToName((WorkshopTypes)27),
					value18
				},
				{
					WorkshopTypesExtensions.ToName((WorkshopTypes)15),
					value4
				},
				{
					WorkshopTypesExtensions.ToName((WorkshopTypes)17),
					value7
				},
				{
					WorkshopTypesExtensions.ToName((WorkshopTypes)25),
					value7
				},
				{
					WorkshopTypesExtensions.ToName((WorkshopTypes)46),
					value10
				},
				{
					WorkshopTypesExtensions.ToName((WorkshopTypes)29),
					value10
				},
				{
					WorkshopTypesExtensions.ToName((WorkshopTypes)30),
					value9
				},
				{
					WorkshopTypesExtensions.ToName((WorkshopTypes)7),
					value17
				},
				{
					WorkshopTypesExtensions.ToName((WorkshopTypes)47),
					value9
				},
				{
					WorkshopTypesExtensions.ToName((WorkshopTypes)54),
					value2
				},
				{
					WorkshopTypesExtensions.ToName((WorkshopTypes)53),
					value12
				},
				{
					WorkshopTypesExtensions.ToName((WorkshopTypes)38),
					value11
				},
				{
					WorkshopTypesExtensions.ToName((WorkshopTypes)22),
					value15
				},
				{
					WorkshopTypesExtensions.ToName((WorkshopTypes)43),
					value15
				}
			};
		}

		public static WorkshopRecipeModel GetCuratedBonusRecipe(Workshop workshop)
		{
			if ((Object)(object)workshop?.model == (Object)null || workshop.state?.recipes == null)
			{
				return null;
			}
			if (_curatedFourthGoodByWorkshop == null)
			{
				BuildCuratedTable();
			}
			if (_excludedWorkshops != null && _excludedWorkshops.Contains(((SO)workshop.model).Name))
			{
				return null;
			}
			if (!((BuildingModel)workshop.model).isInShop && (_starterWorkshops == null || !_starterWorkshops.Contains(((SO)workshop.model).Name)) && !_curatedFourthGoodByWorkshop.ContainsKey(((SO)workshop.model).Name))
			{
				return null;
			}
			HashSet<string> hashSet = new HashSet<string>(from r in workshop.state.recipes
				where r != null && !string.IsNullOrEmpty(r.productName)
				select r.productName, StringComparer.Ordinal);
			if (_curatedFourthGoodByWorkshop.TryGetValue(((SO)workshop.model).Name, out var value) && !hashSet.Contains(value) && OneStarByGood.TryGetValue(value, out var value2))
			{
				return value2;
			}
			string[] array = new string[5]
			{
				GoodsTypesExtensions.ToName((GoodsTypes)57),
				GoodsTypesExtensions.ToName((GoodsTypes)61),
				GoodsTypesExtensions.ToName((GoodsTypes)67),
				GoodsTypesExtensions.ToName((GoodsTypes)7),
				GoodsTypesExtensions.ToName((GoodsTypes)33)
			};
			foreach (string text in array)
			{
				if (!hashSet.Contains(text) && OneStarByGood.TryGetValue(text, out var value3))
				{
					return value3;
				}
			}
			return null;
		}

		public static bool HasUnlockedBonusRecipe(Workshop workshop)
		{
			if ((Object)(object)workshop == (Object)null)
			{
				return true;
			}
			return SettlementModState.Current.FourthRecipeUnlockedWorkshops.Contains(((Building)workshop).Id);
		}

		public static List<GoodCost> GetBonusRecipeCost(Workshop workshop)
		{
			int amount = ((_starterWorkshops != null && (Object)(object)workshop?.model != (Object)null && _starterWorkshops.Contains(((SO)workshop.model).Name)) ? ModConfig.StarterFourthRecipeBuildPacks.Value : ModConfig.BlueprintFourthRecipeBuildPacks.Value);
			return new List<GoodCost> { EconomyHelper.BuildPacks(amount) };
		}

		public static WorkshopRecipeModel GetNextGradeRecipe(WorkshopRecipeState state)
		{
			if (state == null || string.IsNullOrEmpty(((RecipeState)state).model))
			{
				return null;
			}
			if (NextGradeLookup.TryGetValue(((RecipeState)state).model, out var value))
			{
				return value;
			}
			return null;
		}

		public static List<GoodCost> GetRecipeUpgradeCost(int targetGradeLevel)
		{
			return targetGradeLevel switch
			{
				1 => new List<GoodCost> { EconomyHelper.BuildPacks(ModConfig.Grade1UpgradeBuildPacks.Value) }, 
				2 => new List<GoodCost>
				{
					EconomyHelper.BuildPacks(ModConfig.Grade2UpgradeBuildPacks.Value),
					EconomyHelper.TradePacks(ModConfig.Grade2UpgradeTradePacks.Value)
				}, 
				_ => new List<GoodCost>
				{
					EconomyHelper.TradePacks(ModConfig.Grade3UpgradeTradePacks.Value),
					EconomyHelper.WildfireEssence(ModConfig.Grade3UpgradeWildfireEssence.Value)
				}, 
			};
		}

		public static bool TryUnlockBonusRecipe(Workshop workshop, WorkshopPanel panel)
		{
			if ((Object)(object)workshop == (Object)null || HasUnlockedBonusRecipe(workshop))
			{
				return false;
			}
			WorkshopRecipeModel curatedBonusRecipe = GetCuratedBonusRecipe(workshop);
			if ((Object)(object)curatedBonusRecipe == (Object)null)
			{
				return false;
			}
			List<GoodCost> bonusRecipeCost = GetBonusRecipeCost(workshop);
			if (!EconomyHelper.TrySpend(((Building)workshop).ModelName, ((Building)workshop).Id, bonusRecipeCost))
			{
				Svc.PlayClickFail();
				RenderMasteryDock(panel, workshop);
				return false;
			}
			workshop.AddNewRecipe(curatedBonusRecipe);
			SettlementModState.Current.FourthRecipeUnlockedWorkshops.Add(((Building)workshop).Id);
			SettlementModState.Save();
			Svc.PlayClickSuccess();
			RefreshWorkshopPanel(panel, workshop);
			return true;
		}

		public static bool TryUpgradeIndividualRecipe(Workshop workshop, WorkshopRecipeState recipeState, WorkshopPanel panel)
		{
			if ((Object)(object)workshop == (Object)null || recipeState == null)
			{
				return false;
			}
			WorkshopRecipeModel nextGradeRecipe = GetNextGradeRecipe(recipeState);
			if ((Object)(object)nextGradeRecipe == (Object)null)
			{
				return false;
			}
			List<GoodCost> recipeUpgradeCost = GetRecipeUpgradeCost(((Object)(object)((RecipeModel)nextGradeRecipe).grade != (Object)null) ? ((RecipeModel)nextGradeRecipe).grade.level : 3);
			if (!EconomyHelper.TrySpend(((Building)workshop).ModelName, ((Building)workshop).Id, recipeUpgradeCost))
			{
				Svc.PlayClickFail();
				RenderMasteryDock(panel, workshop);
				return false;
			}
			IngredientState[][] ingredients = recipeState.ingredients;
			IngredientState[][] ingredients2 = Svc.Recipes.CreateWorkshopRecipeState(((SO)nextGradeRecipe).Name).ingredients;
			if (ingredients != null && ingredients2 != null)
			{
				int num = Math.Min(ingredients.Length, ingredients2.Length);
				for (int i = 0; i < num; i++)
				{
					if (ingredients[i] == null || ingredients2[i] == null)
					{
						continue;
					}
					Dictionary<string, IngredientState> dictionary = new Dictionary<string, IngredientState>(StringComparer.Ordinal);
					IngredientState[] array = ingredients[i];
					foreach (IngredientState val in array)
					{
						if (val != null && !string.IsNullOrEmpty(val.good.name))
						{
							dictionary[val.good.name] = val;
						}
					}
					bool flag = false;
					array = ingredients2[i];
					foreach (IngredientState val2 in array)
					{
						if (val2 != null && dictionary.TryGetValue(val2.good.name, out var value))
						{
							val2.allowed = value.allowed;
							val2.priority = value.priority;
						}
						if (val2 != null && val2.allowed)
						{
							flag = true;
						}
					}
					if (!flag && ingredients2[i].Length != 0 && ingredients2[i][0] != null)
					{
						ingredients2[i][0].allowed = true;
					}
				}
			}
			((RecipeState)recipeState).model = ((SO)nextGradeRecipe).Name;
			recipeState.ingredients = ingredients2;
			if (TryGetBaseVanillaRecipeName(((SO)nextGradeRecipe).Name, out var vanillaName))
			{
				SettlementModState.Current.CloneToVanillaRecipeMap[((SO)nextGradeRecipe).Name] = vanillaName;
			}
			SettlementModState.Save();
			Svc.PlayClickSuccess();
			RefreshWorkshopPanel(panel, workshop);
			return true;
		}

		public static void RefreshWorkshopPanel(WorkshopPanel panel, Workshop workshop)
		{
			if (!((Object)(object)panel == (Object)null) && !((Object)(object)workshop == (Object)null))
			{
				panel.Show(workshop);
			}
		}

		public static void RenderMasteryDock(WorkshopPanel panel, Workshop workshop)
		{
			if ((Object)(object)panel == (Object)null)
			{
				return;
			}
			if (!ModConfig.EnableWorkshopMastery.Value || VanillaSaveConverter.IsRevertLocked || (Object)(object)workshop == (Object)null || !((Building)workshop).IsFinished() || workshop.state?.recipes == null)
			{
				ImperialUiHelper.HideDock(((Component)panel).transform);
				return;
			}
			RectTransform orCreatePanelHeaderDock = ImperialUiHelper.GetOrCreatePanelHeaderDock(((Component)panel).transform);
			((Component)orCreatePanelHeaderDock).gameObject.SetActive(true);
			ImperialUiHelper.ClearChildren((Transform)(object)orCreatePanelHeaderDock);
			if (!HasUnlockedBonusRecipe(workshop))
			{
				WorkshopRecipeModel curatedBonusRecipe = GetCuratedBonusRecipe(workshop);
				if ((Object)(object)curatedBonusRecipe != (Object)null)
				{
					RectTransform parent = ImperialUiHelper.CreateRow((Transform)(object)orCreatePanelHeaderDock, "BonusRecipeRow");
					List<GoodCost> bonusRecipeCost = GetBonusRecipeCost(workshop);
					bool interactable = EconomyHelper.CanAfford(bonusRecipeCost);
					string text = (((Object)(object)curatedBonusRecipe.producedGood?.good != (Object)null) ? curatedBonusRecipe.producedGood.DisplayName : ((RecipeModel)curatedBonusRecipe).GetProducedGood());
					string labelRichText = "<b>+ Unlock " + text + " (1*)</b>  [" + EconomyHelper.FormatCostSummary(bonusRecipeCost) + "]";
					ImperialUiHelper.CreateStyledButton((Transform)(object)parent, "BtnUnlockFourth", labelRichText, interactable, delegate
					{
						TryUnlockBonusRecipe(workshop, panel);
					}, 260f);
				}
			}
			RectTransform val = null;
			int num = 0;
			foreach (WorkshopRecipeState recipe in workshop.state.recipes)
			{
				if (recipe == null)
				{
					continue;
				}
				WorkshopRecipeModel recipeModel = workshop.GetRecipeModel((RecipeState)(object)recipe);
				if ((Object)(object)recipeModel == (Object)null)
				{
					continue;
				}
				string text2 = (((Object)(object)recipeModel.producedGood?.good != (Object)null) ? recipeModel.producedGood.DisplayName : recipe.productName);
				int num2 = ((!((Object)(object)((RecipeModel)recipeModel).grade != (Object)null)) ? 1 : ((RecipeModel)recipeModel).grade.level);
				WorkshopRecipeModel nextGradeRecipe = GetNextGradeRecipe(recipe);
				if ((Object)(object)val == (Object)null || num >= 2)
				{
					val = ImperialUiHelper.CreateRow((Transform)(object)orCreatePanelHeaderDock, "RecipeMasteryRow");
					num = 0;
				}
				num++;
				if ((Object)(object)nextGradeRecipe == (Object)null || num2 >= 3)
				{
					ImperialUiHelper.CreateStyledButton((Transform)(object)val, "BtnMax_" + recipe.productName, "<color=#FFD966>[3*] " + text2 + " (Mastered)</color>", interactable: false, null, 165f, 23f, 11);
					continue;
				}
				int num3 = (((Object)(object)((RecipeModel)nextGradeRecipe).grade != (Object)null) ? ((RecipeModel)nextGradeRecipe).grade.level : (num2 + 1));
				List<GoodCost> recipeUpgradeCost = GetRecipeUpgradeCost(num3);
				bool interactable2 = EconomyHelper.CanAfford(recipeUpgradeCost);
				WorkshopRecipeState capturedState = recipe;
				string labelRichText2 = $"<b>{text2} {num2}* -> {num3}*</b> ({EconomyHelper.FormatCostSummary(recipeUpgradeCost)})";
				ImperialUiHelper.CreateStyledButton((Transform)(object)val, "BtnUpg_" + recipe.productName, labelRichText2, interactable2, delegate
				{
					TryUpgradeIndividualRecipe(workshop, capturedState, panel);
				}, 190f, 23f, 11);
			}
			ImperialUiHelper.RefreshDockLayout(orCreatePanelHeaderDock, delegate
			{
				RenderMasteryDock(panel, workshop);
			});
		}
	}
	[HarmonyPatch]
	internal static class WorkshopMasteryPatches
	{
		[HarmonyPatch(typeof(WorkshopPanel), "Show")]
		[HarmonyPostfix]
		private static void WorkshopPanel_Show_Postfix(WorkshopPanel __instance, Workshop ___current)
		{
			try
			{
				WorkshopMasteryManager.RenderMasteryDock(__instance, ___current);
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"Error rendering Workshop Mastery dock: {arg}");
			}
		}
	}
}
namespace ATS_ImperialLogistics.UI
{
	public static class ImperialUiHelper
	{
		public const string DefaultDockName = "ImperialLogistics_Dock";

		private static Sprite _roundedBgSprite;

		private static TMP_FontAsset _cachedFont;

		public static TMP_FontAsset GetGameFont(Transform context)
		{
			if ((Object)(object)_cachedFont != (Object)null)
			{
				return _cachedFont;
			}
			if ((Object)(object)context != (Object)null)
			{
				Canvas componentInParent = ((Component)context).GetComponentInParent<Canvas>();
				TMP_Text val = ((componentInParent != null) ? ((Component)componentInParent).GetComponentInChildren<TMP_Text>(true) : null) ?? ((Component)context).GetComponentInChildren<TMP_Text>(true);
				if ((Object)(object)val != (Object)null && (Object)(object)val.font != (Object)null)
				{
					_cachedFont = val.font;
				}
			}
			return _cachedFont;
		}

		private static Sprite GetPanelSprite()
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Expected O, but got Unknown
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: 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)
			if ((Object)(object)_roundedBgSprite != (Object)null)
			{
				return _roundedBgSprite;
			}
			Texture2D val = new Texture2D(4, 4, (TextureFormat)4, false)
			{
				hideFlags = (HideFlags)61
			};
			Color[] array = (Color[])(object)new Color[16];
			for (int i = 0; i < 16; i++)
			{
				array[i] = Color.white;
			}
			val.SetPixels(array);
			val.Apply();
			_roundedBgSprite = Sprite.Create(val, new Rect(0f, 0f, 4f, 4f), new Vector2(0.5f, 0.5f));
			((Object)_roundedBgSprite).hideFlags = (HideFlags)61;
			return _roundedBgSprite;
		}

		public static Transform ResolveContentTransform(Transform panelRoot)
		{
			if ((Object)(object)panelRoot == (Object)null)
			{
				return null;
			}
			return panelRoot.Find("Content") ?? panelRoot;
		}

		public static void HideDock(Transform panelRoot, string dockName = "ImperialLogistics_Dock")
		{
			if ((Object)(object)panelRoot == (Object)null)
			{
				return;
			}
			Transform obj = ResolveContentTransform(panelRoot);
			Transform val = ((obj != null) ? obj.Find(dockName) : null);
			if ((Object)(object)val != (Object)null)
			{
				ImperialDockPositioner component = ((Component)val).GetComponent<ImperialDockPositioner>();
				if ((Object)(object)component != (Object)null)
				{
					component.SetRefreshCallback(null);
				}
				((Component)val).gameObject.SetActive(false);
			}
			if ((Object)(object)obj != (Object)(object)panelRoot)
			{
				Transform val2 = panelRoot.Find(dockName);
				if ((Object)(object)val2 != (Object)null)
				{
					((Component)val2).gameObject.SetActive(false);
				}
			}
		}

		public static RectTransform GetOrCreatePanelHeaderDock(Transform panelRoot, string dockName = "ImperialLogistics_Dock")
		{
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e3: 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_00fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0107: Unknown result type (might be due to invalid IL or missing references)
			//IL_011c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0131: Unknown result type (might be due to invalid IL or missing references)
			//IL_013b: 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_016a: 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_0199: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b8: Expected O, but got Unknown
			//IL_01e5: Unknown result type (might be due to invalid IL or missing references)
			Transform obj = ResolveContentTransform(panelRoot);
			RectTransform val = (RectTransform)(object)(((obj is RectTransform) ? obj : null) ?? ((panelRoot is RectTransform) ? panelRoot : null));
			if ((Object)(object)val != (Object)(object)panelRoot)
			{
				Transform val2 = panelRoot.Find(dockName);
				if ((Object)(object)val2 != (Object)null)
				{
					Object.Destroy((Object)(object)((Component)val2).gameObject);
				}
			}
			Transform obj2 = ((Transform)val).Find(dockName);
			RectTransform val3 = (RectTransform)(object)((obj2 is RectTransform) ? obj2 : null);
			if ((Object)(object)val3 != (Object)null)
			{
				ImperialDockPositioner component = ((Component)val3).GetComponent<ImperialDockPositioner>();
				if ((Object)(object)component != (Object)null)
				{
					component.MarkDirty();
				}
				return val3;
			}
			GameObject val4 = new GameObject(dockName, new Type[7]
			{
				typeof(RectTransform),
				typeof(LayoutElement),
				typeof(Image),
				typeof(Outline),
				typeof(VerticalLayoutGroup),
				typeof(ContentSizeFitter),
				typeof(ImperialDockPositioner)
			});
			RectTransform component2 = val4.GetComponent<RectTransform>();
			((Transform)component2).SetParent((Transform)(object)val, false);
			((Transform)component2).localScale = Vector3.one;
			val4.GetComponent<LayoutElement>().ignoreLayout = true;
			component2.anchorMin = val.pivot;
			component2.anchorMax = val.pivot;
			component2.pivot = new Vector2(1f, 1f);
			component2.sizeDelta = new Vector2(340f, 34f);
			Image component3 = val4.GetComponent<Image>();
			component3.sprite = GetPanelSprite();
			((Graphic)component3).color = new Color(0.09f, 0.08f, 0.07f, 0.95f);
			Outline component4 = val4.GetComponent<Outline>();
			((Shadow)component4).effectColor = new Color(0.55f, 0.45f, 0.24f, 0.75f);
			((Shadow)component4).effectDistance = new Vector2(1f, -1f);
			VerticalLayoutGroup component5 = val4.GetComponent<VerticalLayoutGroup>();
			((LayoutGroup)component5).padding = new RectOffset(8, 8, 6, 6);
			((HorizontalOrVerticalLayoutGroup)component5).spacing = 4f;
			((LayoutGroup)component5).childAlignment = (TextAnchor)4;
			((HorizontalOrVerticalLayoutGroup)component5).childControlWidth = true;
			((HorizontalOrVerticalLayoutGroup)component5).childControlHeight = true;
			((HorizontalOrVerticalLayoutGroup)component5).childForceExpandWidth = true;
			((HorizontalOrVerticalLayoutGroup)component5).childForceExpandHeight = false;
			ContentSizeFitter component6 = val4.GetComponent<ContentSizeFitter>();
			component6.horizontalFit = (FitMode)0;
			component6.verticalFit = (FitMode)2;
			val4.GetComponent<ImperialDockPositioner>().Initialize(val, component2);
			return component2;
		}

		public static void RefreshDockLayout(RectTransform dock, Action liveRebuildCallback = null)
		{
			if (!((Object)(object)dock == (Object)null))
			{
				ImperialDockPositioner component = ((Component)dock).GetComponent<ImperialDockPositioner>();
				if ((Object)(object)component != (Object)null)
				{
					component.SetRefreshCallback(liveRebuildCallback);
					component.MarkDirty();
					component.RepositionNow(skipHorizontalScreenClamp: true);
				}
			}
		}

		public static RectTransform CreateRow(Transform parent, string name = "Row")
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Expected O, but got Unknown
			GameObject val = new GameObject(name, new Type[2]
			{
				typeof(RectTransform),
				typeof(HorizontalLayoutGroup)
			});
			RectTransform component = val.GetComponent<RectTransform>();
			((Transform)component).SetParent(parent, false);
			HorizontalLayoutGroup component2 = val.GetComponent<HorizontalLayoutGroup>();
			((LayoutGroup)component2).padding = new RectOffset(0, 0, 0, 0);
			((HorizontalOrVerticalLayoutGroup)component2).spacing = 6f;
			((LayoutGroup)component2).childAlignment = (TextAnchor)4;
			((HorizontalOrVerticalLayoutGroup)component2).childControlWidth = true;
			((HorizontalOrVerticalLayoutGroup)component2).childControlHeight = true;
			((HorizontalOrVerticalLayoutGroup)component2).childForceExpandWidth = true;
			((HorizontalOrVerticalLayoutGroup)component2).childForceExpandHeight = false;
			return component;
		}

		public static Button CreateStyledButton(Transform parent, string objectName, string labelRichText, bool interactable, Action onClick, float minWidth = 110f, float height = 24f, int fontSize = 12)
		{
			//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_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f5: 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_0119: Unknown result type (might be due to invalid IL or missing references)
			//IL_0139: Unknown result type (might be due to invalid IL or missing references)
			//IL_0159: Unknown result type (might be due to invalid IL or missing references)
			//IL_0165: Unknown result type (might be due to invalid IL or missing references)
			//IL_0191: Unknown result type (might be due to invalid IL or missing references)
			//IL_0196: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0267: Unknown result type (might be due to invalid IL or missing references)
			//IL_024c: Unknown result type (might be due to invalid IL or missing references)
			//IL_027c: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b5: Expected O, but got Unknown
			GameObject val = new GameObject(objectName, new Type[4]
			{
				typeof(RectTransform),
				typeof(Image),
				typeof(Button),
				typeof(LayoutElement)
			});
			RectTransform component = val.GetComponent<RectTransform>();
			((Transform)component).SetParent(parent, false);
			LayoutElement component2 = val.GetComponent<LayoutElement>();
			component2.minWidth = minWidth;
			component2.preferredHeight = height;
			component2.minHeight = height;
			Image component3 = val.GetComponent<Image>();
			component3.sprite = GetPanelSprite();
			((Graphic)component3).color = (interactable ? new Color(0.24f, 0.2f, 0.14f, 0.98f) : new Color(0.16f, 0.15f, 0.15f, 0.88f));
			Button component4 = val.GetComponent<Button>();
			((Selectable)component4).targetGraphic = (Graphic)(object)component3;
			((Selectable)component4).interactable = interactable;
			ColorBlock colors = ((Selectable)component4).colors;
			((ColorBlock)(ref colors)).normalColor = Color.white;
			((ColorBlock)(ref colors)).highlightedColor = new Color(1.2f, 1.15f, 1f, 1f);
			((ColorBlock)(ref colors)).pressedColor = new Color(0.85f, 0.8f, 0.7f, 1f);
			((ColorBlock)(ref colors)).disabledColor = new Color(0.78f, 0.78f, 0.78f, 0.88f);
			((Selectable)component4).colors = colors;
			GameObject val2 = new GameObject("Label", new Type[2]
			{
				typeof(RectTransform),
				typeof(TextMeshProUGUI)
			});
			RectTransform component5 = val2.GetComponent<RectTransform>();
			((Transform)component5).SetParent((Transform)(object)component, false);
			component5.anchorMin = Vector2.zero;
			component5.anchorMax = Vector2.one;
			component5.offsetMin = new Vector2(8f, 2f);
			component5.offsetMax = new Vector2(-8f, -2f);
			TextMeshProUGUI component6 = val2.GetComponent<TextMeshProUGUI>();
			TMP_FontAsset gameFont = GetGameFont(parent);
			if ((Object)(object)gameFont != (Object)null)
			{
				((TMP_Text)component6).font = gameFont;
			}
			((TMP_Text)component6).fontSize = fontSize;
			((TMP_Text)component6).alignment = (TextAlignmentOptions)514;
			((TMP_Text)component6).textWrappingMode = (TextWrappingModes)0;
			((TMP_Text)component6).overflowMode = (TextOverflowModes)0;
			((TMP_Text)component6).richText = true;
			((Graphic)component6).color = (interactable ? new Color(0.96f, 0.91f, 0.78f, 1f) : new Color(0.72f, 0.7f, 0.67f, 1f));
			((TMP_Text)component6).text = labelRichText;
			float num = ((TMP_Text)component6).GetPreferredValues(labelRichText).x + 20f;
			component2.preferredWidth = Mathf.Max(minWidth, num);
			((UnityEvent)component4.onClick).AddListener((UnityAction)delegate
			{
				try
				{
					onClick?.Invoke();
				}
				catch (Exception arg)
				{
					Plugin.Log.LogError((object)$"UI button '{objectName}' click error: {arg}");
				}
			});
			Transform parent2 = parent.parent;
			RectTransform val3 = (RectTransform)(object)((parent2 is RectTransform) ? parent2 : null);
			if ((Object)(object)val3 != (Object)null)
			{
				ImperialDockPositioner component7 = ((Component)val3).GetComponent<ImperialDockPositioner>();
				if ((Object)(object)component7 != (Object)null)
				{
					component7.MarkDirty();
				}
			}
			return component4;
		}

		public static void ClearChildren(Transform parent)
		{
			if (!((Object)(object)parent == (Object)null))
			{
				for (int num = parent.childCount - 1; num >= 0; num--)
				{
					Transform child = parent.GetChild(num);
					GameObject gameObject = ((Component)child).gameObject;
					gameObject.SetActive(false);
					child.SetParent((Transform)null, false);
					Object.Destroy((Object)(object)gameObject);
				}
			}
		}
	}
	internal sealed class ImperialDockPositioner : MonoBehaviour
	{
		private static readonly Vector3[] WorldCorners = (Vector3[])(object)new Vector3[4];

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

		private RectTransform _contentRect;

		private RectTransform _dockRect;

		private RectTransform _mainPanelRect;

		private RectTransform _canvasRect;

		private Action _liveRebuildCallback;

		private int _lastStockSignature;

		private int _lastActiveChildMask = -1;

		private Vector2 _lastContentSize;

		private Vector3 _lastContentWorldPos;

		private int _dirtyFrames = 5;

		private float _settleUntilTime;

		private bool _needsSettledClamp;

		private float _nextPeriodicCheckTime;

		private bool _isRebuilding;

		public void Initialize(RectTransform contentRect, RectTransform dockRect)
		{
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			_contentRect = contentRect;
			_dockRect = dockRect;
			_mainPanelRect = (RectTransform)(((Object)(object)contentRect != (Object)null) ? /*isinst with value type is only supported in some contexts*/: null);
			_lastContentWorldPos = (((Object)(object)contentRect != (Object)null) ? ((Transform)contentRect).position : Vector3.zero);
			_dirtyFrames = 5;
			_settleUntilTime = Time.unscaledTime + 0.45f;
			_needsSettledClamp = true;
		}

		public void SetRefreshCallback(Action liveRebuildCallback)
		{
			_liveRebuildCallback = liveRebuildCallback;
			_lastStockSignature = EconomyHelper.GetUpgradeGoodsSignature();
		}

		private void OnEnable()
		{
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			_dirtyFrames = 5;
			_lastActiveChildMask = -1;
			_lastContentWorldPos = (((Object)(object)_contentRect != (Object)null) ? ((Transform)_contentRect).position : Vector3.zero);
			_lastStockSignature = EconomyHelper.GetUpgradeGoodsSignature();
			_settleUntilTime = Time.unscaledTime + 0.45f;
			_needsSettledClamp = true;
			_nextPeriodicCheckTime = Time.unscaledTime + 0.25f;
		}

		public void MarkDirty()
		{
			_dirtyFrames = 3;
			_settleUntilTime = Mathf.Max(_settleUntilTime, Time.unscaledTime + 0.35f);
			_needsSettledClamp = true;
		}

		private void LateUpdate()
		{
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0183: Unknown result type (might be due to invalid IL or missing references)
			//IL_0188: Unknown result type (might be due to invalid IL or missing references)
			//IL_018c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0191: 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_01a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a6: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)_dockRect == (Object)null || (Object)(object)_contentRect == (Object)null || !((Component)_contentRect).gameObject.activeInHierarchy)
			{
				return;
			}
			Vector3 position = ((Transform)_contentRect).position;
			Vector3 val = position - _lastContentWorldPos;
			bool num = ((Vector3)(ref val)).sqrMagnitude > 0.01f;
			if (num)
			{
				_lastContentWorldPos = position;
				_dirtyFrames = Math.Max(_dirtyFrames, 2);
				_settleUntilTime = Mathf.Max(_settleUntilTime, Time.unscaledTime + 0.15f);
				_needsSettledClamp = true;
			}
			bool flag = num || Time.unscaledTime < _settleUntilTime;
			if (_dirtyFrames > 0)
			{
				_dirtyFrames--;
				RepositionNow(flag);
				if (!flag)
				{
					_needsSettledClamp = false;
				}
			}
			else
			{
				if (flag)
				{
					return;
				}
				if (_needsSettledClamp)
				{
					_needsSettledClamp = false;
					RepositionNow();
				}
				else
				{
					if (Time.unscaledTime < _nextPeriodicCheckTime)
					{
						return;
					}
					_nextPeriodicCheckTime = Time.unscaledTime + 0.45f;
					if (_liveRebuildCallback != null && !_isRebuilding && Svc.Active)
					{
						int upgradeGoodsSignature = EconomyHelper.GetUpgradeGoodsSignature();
						if (upgradeGoodsSignature != _lastStockSignature)
						{
							_lastStockSignature = upgradeGoodsSignature;
							_isRebuilding = true;
							try
							{
								_liveRebuildCallback();
								return;
							}
							catch (Exception ex)
							{
								Plugin.Log.LogWarning((object)("Error refreshing dock affordability: " + ex.Message));
								return;
							}
							finally
							{
								_isRebuilding = false;
							}
						}
					}
					int num2 = ComputeActiveChildMask();
					Rect rect = _contentRect.rect;
					Vector2 size = ((Rect)(ref rect)).size;
					if (num2 == _lastActiveChildMask)
					{
						Vector2 val2 = size - _lastContentSize;
						if (!(((Vector2)(ref val2)).sqrMagnitude > 0.5f))
						{
							return;
						}
					}
					RepositionNow();
				}
			}
		}

		private int ComputeActiveChildMask()
		{
			if ((Object)(object)_contentRect == (Object)null)
			{
				return 0;
			}
			int num = 17;
			int childCount = ((Transform)_contentRect).childCount;
			for (int i = 0; i < childCount; i++)
			{
				Transform child = ((Transform)_contentRect).GetChild(i);
				if (!((Object)(object)child == (Object)(object)_dockRect))
				{
					num = num * 31 + (((Component)child).gameObject.activeSelf ? 1 : 0);
				}
			}
			return num;
		}

		public void RepositionNow(bool skipHorizontalScreenClamp = false)
		{
			//IL_0030: 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)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: 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_020d: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_030d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0327: Unknown result type (might be due to invalid IL or missing references)
			//IL_0340: Unknown result type (might be due to invalid IL or missing references)
			//IL_0257: Unknown result type (might be due to invalid IL or missing references)
			//IL_025c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0261: Unknown result type (might be due to invalid IL or missing references)
			//IL_026f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0274: Unknown result type (might be due to invalid IL or missing references)
			//IL_0279: Unknown result type (might be due to invalid IL or missing references)
			//IL_0299: Unknown result type (might be due to invalid IL or missing references)
			//IL_0280: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_02bb: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)_contentRect == (Object)null || (Object)(object)_dockRect == (Object)null)
			{
				return;
			}
			_lastActiveChildMask = ComputeActiveChildMask();
			Rect rect = _contentRect.rect;
			_lastContentSize = ((Rect)(ref rect)).size;
			_lastContentWorldPos = ((Transform)_contentRect).position;
			if ((Object)(object)_mainPanelRect == (Object)null)
			{
				ref RectTransform mainPanelRect = ref _mainPanelRect;
				Transform obj = ((Transform)_contentRect).Find("MainPanel");
				mainPanelRect = (RectTransform)(object)((obj is RectTransform) ? obj : null);
			}
			if ((Object)(object)_canvasRect == (Object)null)
			{
				Canvas componentInParent = ((Component)_contentRect).GetComponentInParent<Canvas>();
				Canvas val = ((componentInParent != null) ? componentInParent.rootCanvas : null);
				if ((Object)(object)val != (Object)null)
				{
					ref RectTransform canvasRect = ref _canvasRect;
					Transform transform = ((Component)val).transform;
					canvasRect = (RectTransform)(object)((transform is RectTransform) ? transform : null);
				}
			}
			bool hasAny = false;
			float minX = float.MaxValue;
			float maxX = float.MinValue;
			float minY = float.MaxValue;
			float maxY = float.MinValue;
			bool hasAny2 = false;
			float minX2 = float.MaxValue;
			float maxX2 = float.MinValue;
			float minY2 = float.MaxValue;
			float maxY2 = float.MinValue;
			int childCount = ((Transform)_contentRect).childCount;
			for (int i = 0; i < childCount; i++)
			{
				Transform child = ((Transform)_contentRect).GetChild(i);
				if ((Object)(object)child == (Object)(object)_dockRect || !((Component)child).gameObject.activeSelf)
				{
					continue;
				}
				if ((Object)(object)child == (Object)(object)_mainPanelRect)
				{
					AccumulateVisibleBounds(child, ref hasAny2, ref minX2, ref maxX2, ref minY2, ref maxY2);
					if (hasAny2)
					{
						IncludeMinMax(minX2, maxX2, minY2, maxY2, ref hasAny, ref minX, ref maxX, ref minY, ref maxY);
					}
				}
				else
				{
					AccumulateVisibleBounds(child, ref hasAny, ref minX, ref maxX, ref minY, ref maxY);
				}
			}
			if (!hasAny)
			{
				return;
			}
			float num = (hasAny2 ? minX2 : minX);
			float num2 = (hasAny2 ? maxX2 : maxX);
			float num3 = Mathf.Max(260f, num2 - num);
			LayoutRebuilder.ForceRebuildLayoutImmediate(_dockRect);
			float preferredWidth = LayoutUtility.GetPreferredWidth(_dockRect);
			float num4 = Mathf.Max(num3, preferredWidth);
			_dockRect.SetSizeWithCurrentAnchors((Axis)0, num4);
			LayoutRebuilder.ForceRebuildLayoutImmediate(_dockRect);
			rect = _dockRect.rect;
			float num5 = Mathf.Max(32f, ((Rect)(ref rect)).height);
			float num6 = num2;
			float num7 = minY - 8f;
			if ((Object)(object)_canvasRect != (Object)null)
			{
				_canvasRect.GetWorldCorners(CanvasCorners);
				Vector3 val2 = ((Transform)_contentRect).InverseTransformPoint(CanvasCorners[0]);
				Vector3 val3 = ((Transform)_contentRect).InverseTransformPoint(CanvasCorners[2]);
				if (!skipHorizontalScreenClamp)
				{
					num6 = Mathf.Min(num6, val3.x - 10f);
				}
				if (num7 - num5 < val2.y + 18f)
				{
					num6 = minX - 8f;
					num7 = Mathf.Min(hasAny2 ? maxY2 : maxY, val3.y - 75f);
				}
				if (!skipHorizontalScreenClamp)
				{
					num6 = Mathf.Max(num6, val2.x + num4 + 10f);
				}
			}
			_dockRect.anchorMin = _contentRect.pivot;
			_dockRect.anchorMax = _contentRect.pivot;
			_dockRect.pivot = new Vector2(1f, 1f);
			((Transform)_dockRect).localPosition = new Vector3(num6, num7, 0f);
			((Transform)_dockRect).SetAsLastSibling();
		}

		private static void IncludeMinMax(float srcMinX, float srcMaxX, float srcMinY, float srcMaxY, ref bool dstHas, ref float dstMinX, ref float dstMaxX, ref float dstMinY, ref float dstMaxY)
		{
			if (!dstHas)
			{
				dstMinX = srcMinX;
				dstMaxX = srcMaxX;
				dstMinY = srcMinY;
				dstMaxY = srcMaxY;
				dstHas = true;
				return;
			}
			if (srcMinX < dstMinX)
			{
				dstMinX = srcMinX;
			}
			if (srcMaxX > dstMaxX)
			{
				dstMaxX = srcMaxX;
			}
			if (srcMinY < dstMinY)
			{
				dstMinY = srcMinY;
			}
			if (srcMaxY > dstMaxY)
			{
				dstMaxY = srcMaxY;
			}
		}

		private void AccumulateVisibleBounds(Transform node, ref bool hasAny, ref float minX, ref float maxX, ref float minY, ref float maxY)
		{
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)node == (Object)null || (Object)(object)node == (Object)(object)_dockRect || !((Component)node).gameObject.activeSelf)
			{
				return;
			}
			RectTransform val = (RectTransform)(object)((node is RectTransform) ? node : null);
			if ((Object)(object)val != (Object)null)
			{
				if ((Object)(object)((Component)node).GetComponent<ScrollRect>() != (Object)null || (Object)(object)((Component)node).GetComponent<Mask>() != (Object)null || (Object)(object)((Component)node).GetComponent<RectMask2D>() != (Object)null)
				{
					IncludeRect(val, ref hasAny, ref minX, ref maxX, ref minY, ref maxY);
					return;
				}
				Graphic component = ((Component)node).GetComponent<Graphic>();
				if ((Object)(object)component != (Object)null && ((Behaviour)component).enabled && component.color.a > 0.02f)
				{
					IncludeRect(val, ref hasAny, ref minX, ref maxX, ref minY, ref maxY);
				}
			}
			int childCount = node.childCount;
			for (int i = 0; i < childCount; i++)
			{
				AccumulateVisibleBounds(node.GetChild(i), ref hasAny, ref minX, ref maxX, ref minY, ref maxY);
			}
		}

		private void IncludeRect(RectTransform rt, ref bool hasAny, ref float minX, ref float maxX, ref float minY, ref float maxY)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: 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_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			Rect rect = rt.rect;
			if (((Rect)(ref rect)).width <= 1f)
			{
				return;
			}
			rect = rt.rect;
			if (((Rect)(ref rect)).height <= 1f)
			{
				return;
			}
			rt.GetWorldCorners(WorldCorners);
			for (int i = 0; i < 4; i++)
			{
				Vector3 val = ((Transform)_contentRect).InverseTransformPoint(WorldCorners[i]);
				if (!hasAny)
				{
					minX = (maxX = val.x);
					minY = (maxY = val.y);
					hasAny = true;
					continue;
				}
				if (val.x < minX)
				{
					minX = val.x;
				}
				if (val.x > maxX)
				{
					maxX = val.x;
				}
				if (val.y < minY)
				{
					minY = val.y;
				}
				if (val.y > maxY)
				{
					maxY = val.y;
				}
			}
		}
	}
	[HarmonyPatch]
	internal static class ImperialUiPatches
	{
		[HarmonyPatch(typeof(PreviewPanel), "Hide")]
		[HarmonyPostfix]
		private static void PreviewPanel_Hide_Postfix(PreviewPanel __instance)
		{
			try
			{
				if ((Object)(object)__instance != (Object)null)
				{
					ImperialUiHelper.HideDock(((Component)__instance).transform);
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Error hiding Imperial UI dock: " + ex.Message));
			}
		}
	}
}
namespace ATS_ImperialLogistics.SupplyChain
{
	public static class SmartSupplyChainManager
	{
		private static bool _isAutoUpdatingLimit;

		private static bool _isLoadingSavedLimits;

		private static HashSet<string> _intermediateGoods;

		private static HashSet<string> _rawEdibleFoods;

		private static HashSet<string> _burnableFuels;

		private static readonly List<(IngredientState ing, float score)> ScratchRanked = new List<(IngredientState, float)>(12);

		private static readonly HashSet<string> ScratchCountedInSlot = new HashSet<string>(StringComparer.Ordinal);

		private static readonly Dictionary<string, int> ScratchConsumerCounts = new Dictionary<string, int>(StringComparer.Ordinal);

		public static void EnsureInitialized(bool forceRefreshGoods = false)
		{
			if ((Object)(object)Svc.Cfg == (Object)null)
			{
				return;
			}
			if (_intermediateGoods == null)
			{
				_intermediateGoods = new HashSet<string>(StringComparer.Ordinal)
				{
					GoodsTypesExtensions.ToName((GoodsTypes)33),
					GoodsTypesExtensions.ToName((GoodsTypes)29),
					GoodsTypesExtensions.ToName((GoodsTypes)30),
					GoodsTypesExtensions.ToName((GoodsTypes)32),
					GoodsTypesExtensions.ToName((GoodsTypes)7),
					GoodsTypesExtensions.ToName((GoodsTypes)6),
					GoodsTypesExtensions.ToName((GoodsTypes)67),
					GoodsTypesExtensions.ToName((GoodsTypes)68),
					GoodsTypesExtensions.ToName((GoodsTypes)69),
					GoodsTypesExtensions.ToName((GoodsTypes)44),
					GoodsTypesExtensions.ToName((GoodsTypes)46)
				};
			}
			if (!(_rawEdibleFoods == null || _burnableFuels == null || forceRefreshGoods))
			{
				return;
			}
			_rawEdibleFoods = new HashSet<string>(StringComparer.Ordinal);
			_burnableFuels = new HashSet<string>(StringComparer.Ordinal);
			if (Svc.Cfg.Goods == null)
			{
				return;
			}
			GoodModel[] goods = Svc.Cfg.Goods;
			foreach (GoodModel val in goods)
			{
				if (!((Object)(object)val == (Object)null) && !string.IsNullOrEmpty(((SO)val).Name))
				{
					bool flag = (Object)(object)val.category != (Object)null && ((SO)val.category).Name != null && ((SO)val.category).Name.IndexOf("Complex", StringComparison.OrdinalIgnoreCase) >= 0;
					if (val.eatable && !flag && ((SO)val).Name.IndexOf("Processed", StringComparison.OrdinalIgnoreCase) < 0)
					{
						_rawEdibleFoods.Add(((SO)val).Name);
					}
					if (val.canBeBurned)
					{
						_burnableFuels.Add(((SO)val).Name);
					}
				}
			}
		}

		public static void OnSettlementStarted()
		{
			EnsureInitialized(forceRefreshGoods: true);
		}

		public static void Tick()
		{
			IBuildingsService buildings = Svc.Buildings;
			if (((buildings != null) ? buildings.Workshops : null) == null || Svc.Buildings.Storages == null || Svc.Buildings.Storages.Count == 0 || Svc.Storage == null || (Object)(object)Svc.Cfg == (Object)null)
			{
				return;
			}
			SettlementModData current = SettlementModState.Current;
			if (!ModConfig.EnableSmartSupplyChains.Value)
			{
				if (current.FloorPausedIngredients.Count > 0 || current.PlayerManualFloorOverrides.Count > 0)
				{
					RestoreAllFloorPausedIngredients(Svc.Buildings.Workshops.Values, current);
				}
				return;
			}
			EnsureInitialized();
			Dictionary<int, Workshop>.ValueCollection values = Svc.Buildings.Workshops.Values;
			int num = CalculateTotalStock(_rawEdibleFoods);
			int num2 = CalculateTotalStock(_burnableFuels);
			bool flag = ModConfig.EnableReserveFloors.Value && num <= ModConfig.RawFoodSafetyFloor.Value;
			bool flag2 = !ModConfig.EnableReserveFloors.Value || num >= ModConfig.RawFoodSafetyFloor.Value + 5;
			bool flag3 = ModConfig.EnableReserveFloors.Value && num2 <= ModConfig.FuelSafetyFloor.Value;
			bool flag4 = !ModConfig.EnableReserveFloors.Value || num2 >= ModConfig.FuelSafetyFloor.Value + 5;
			Dictionary<string, int> dictionary = null;
			if (ModConfig.EnableSmartIntermediateCaps.Value)
			{
				dictionary = CountDownstreamConsumers(values);
			}
			bool flag5 = false;
			bool flag6 = current.FloorPausedIngredients.Count > 0 || current.PlayerManualFloorOverrides.Count > 0;
			foreach (Workshop item in values)
			{
				if ((Object)(object)item == (Object)null || item.state?.recipes == null || !((Building)item).IsFinished())
				{
					continue;
				}
				foreach (WorkshopRecipeState recipe in item.state.recipes)
				{
					if (recipe == null || string.IsNullOrEmpty(recipe.productName))
					{
						continue;
					}
					if (dictionary != null && _intermediateGoods.Contains(recipe.productName))
					{
						bool num3 = current.PlayerLockedGlobalProductLimits.Contains(recipe.productName) || (Svc.Workshops != null && Svc.Workshops.GetGlobalLimitFor(recipe.productName) > 0);
						string limitLockKey = GetLimitLockKey(((Building)item).Id, recipe.productName);
						if (!num3 && !current.PlayerLockedRecipeLimits.Contains(limitLockKey))
						{
							dictionary.TryGetValue(recipe.productName, out var value);
							int num4 = ModConfig.IntermediateBaseCap.Value + value * ModConfig.IntermediateCapPerConsumer.Value;
							if (recipe.limit != num4 || recipe.isLimitLocal)
							{
								_isAutoUpdatingLimit = true;
								try
								{
									item.ChangeLimitFor(recipe, num4, false);
								}
								finally
								{
									_isAutoUpdatingLimit = false;
								}
							}
						}
					}
					if (!((RecipeState)recipe).active || recipe.ingredients == null)
					{
						continue;
					}
					GoodModel val = (Svc.Cfg.ContainsGood(recipe.productName) ? Svc.Cfg.GetGood(recipe.productName) : null);
					bool flag7 = (Object)(object)val != (Object)null && val.eatable;
					bool flag8 = (Object)(object)val != (Object)null && val.canBeBurned;
					for (int i = 0; i < recipe.ingredients.Length; i++)
					{
						IngredientState[] array = recipe.ingredients[i];
						if (array == null || array.Length == 0)
						{
							continue;
						}
						if (flag6)
						{
							foreach (IngredientState val2 in array)
							{
								if (val2 == null)
								{
									continue;
								}
								bool num5 = _rawEdibleFoods.Contains(val2.good.name);
								bool flag9 = _burnableFuels.Contains(val2.good.name);
								if ((!num5 || flag7 || flag2) && (!flag9 || flag8 || flag4))
								{
									string floorPauseKey = GetFloorPauseKey(((Building)item).Id, recipe.productName, i, val2.good.name);
									string legacyFloorPauseKey = GetLegacyFloorPauseKey(((Building)item).Id, ((RecipeState)recipe).model, i, val2.good.name);
									if (current.FloorPausedIngredients.Remove(floorPauseKey) | current.FloorPausedIngredients.Remove(legacyFloorPauseKey))
									{
										val2.allowed = true;
										flag5 = true;
									}
									if (current.PlayerManualFloorOverrides.Remove(floorPauseKey))
									{
										flag5 = true;
									}
								}
							}
						}
						bool flag10 = false;
						foreach (IngredientState val3 in array)
						{
							if (val3 != null && val3.allowed && (!(!flag7 && flag) || !_rawEdibleFoods.Contains(val3.good.name)) && (!(!flag8 && flag3) || !_burnableFuels.Contains(val3.good.name)) && Svc.Storage.Main.GetAmount(val3.good.name) >= val3.good.amount)
							{
								flag10 = true;
								break;
							}
						}
						if (!flag10 && ModConfig.EnableReserveFloors.Value && (flag || flag3))
						{
							foreach (IngredientState val4 in array)
							{
								if (val4 != null && val4.allowed && ((!flag7 && flag && _rawEdibleFoods.Contains(val4.good.name)) || (!flag8 && flag3 && _burnableFuels.Contains(val4.good.name))))
								{
									string floorPauseKey2 = GetFloorPauseKey(((Building)item).Id, recipe.productName, i, val4.good.name);
									if (!current.PlayerManualFloorOverrides.Contains(floorPauseKey2))
									{
										val4.allowed = false;
										current.FloorPausedIngredients.Add(floorPauseKey2);
										flag6 = true;
										flag5 = true;
										ReturnUnusedBufferedIngredientToWarehouse(item, val4.good.name);
									}
								}
							}
						}
						if (ModConfig.EnableSurplusIngredientPriority.Value && array.Length > 1)
						{
							AssignSurplusPriorities(array, flag7, flag, flag8, flag3);
						}
					}
				}
			}
			if (flag5)
			{
				SettlementModState.Save();
			}
		}

		private static void RestoreAllFloorPausedIngredients(IEnumerable<Workshop> workshops, SettlementModData modState)
		{
			foreach (Workshop workshop in workshops)
			{
				if (workshop?.state?.recipes == null)
				{
					continue;
				}
				foreach (WorkshopRecipeState recipe in workshop.state.recipes)
				{
					if (recipe?.ingredients == null)
					{
						continue;
					}
					for (int i = 0; i < recipe.ingredients.Length; i++)
					{
						IngredientState[] array = recipe.ingredients[i];
						if (array == null)
						{
							continue;
						}
						foreach (IngredientState val in array)
						{
							if (val != null)
							{
								string floorPauseKey = GetFloorPauseKey(((Building)workshop).Id, recipe.productName, i, val.good.name);
								string legacyFloorPauseKey = GetLegacyFloorPauseKey(((Building)workshop).Id, ((RecipeState)recipe).model, i, val.good.name);
								if (modState.FloorPausedIngredients.Contains(floorPauseKey) || modState.FloorPausedIngredients.Contains(legacyFloorPauseKey))
								{
									val.allowed = true;
								}
							}
						}
					}
				}
			}
			modState.FloorPausedIngredients.Clear();
			modState.PlayerManualFloorOverrides.Clear();
			SettlementModState.Save();
		}

		private static void ReturnUnusedBufferedIngredientToWarehouse(Workshop ws, string goodName)
		{
			//IL_0114: Unknown result type (might be due to invalid IL or missing references)
			//IL_0132: Unknown result type (might be due to invalid IL or missing references)
			if (((ws == null) ? null : ws.IngredientsStorage?.goods) == null || Svc.Storage == null || string.IsNullOrEmpty(goodName))
			{
				return;
			}
			int amount = ws.IngredientsStorage.goods.GetAmount(goodName);
			if (amount <= 0)
			{
				return;
			}
			if (ws.state?.recipes != null)
			{
				foreach (WorkshopRecipeState recipe in ws.state.recipes)
				{
					if (recipe == null || !((RecipeState)recipe).active || recipe.ingredients == null)
					{
						continue;
					}
					for (int i = 0; i < recipe.ingredients.Length; i++)
					{
						IngredientState[] array = recipe.ingredients[i];
						if (array == null)
						{
							continue;
						}
						foreach (IngredientState val in array)
						{
							if (val != null && val.allowed && string.Equals(val.good.name, goodName, StringComparison.Ordinal))
							{
								return;
							}
						}
					}
				}
			}
			Good val2 = default(Good);
			((Good)(ref val2))..ctor(goodName, amount);
			Svc.Storage.Store(val2, ((Building)ws).ModelName, ((Building)ws).Id, (StorageOperationType)3);
			ws.IngredientsStorage.goods.Remove(val2);
		}

		private static void AssignSurplusPriorities(IngredientState[] set, bool producesFood, bool protectFood, bool producesFuel, bool protectFuel)
		{
			ScratchRanked.Clear();
			foreach (IngredientState val in set)
			{
				if (val != null && val.allowed)