-- PRIVATE METHODS
function IconController:_updateSelectionGroup(clearAll)
	if IconController._navigationEnabled then
		guiService:RemoveSelectionGroup("TopbarPlusIcons")
	end
	if clearAll then
		guiService.CoreGuiNavigationEnabled = IconController._originalCoreGuiNavigationEnabled
		guiService.GuiNavigationEnabled = IconController._originalGuiNavigationEnabled
		IconController._navigationEnabled = nil
	elseif IconController.controllerModeEnabled then
		local icons = IconController.getIcons()
		local iconContainers = {}
		for i, otherIcon in pairs(icons) do
			local featureName = otherIcon.joinedFeatureName
			if not featureName or otherIcon._parentIcon[otherIcon.joinedFeatureName.."Open"] == true then
				table.insert(iconContainers, otherIcon.instances.iconButton)
			end
		end
		guiService:AddSelectionTuple("TopbarPlusIcons", table.unpack(iconContainers))
		if not IconController._navigationEnabled then
			IconController._originalCoreGuiNavigationEnabled = guiService.CoreGuiNavigationEnabled
			IconController._originalGuiNavigationEnabled = guiService.GuiNavigationEnabled
			guiService.CoreGuiNavigationEnabled = false
			guiService.GuiNavigationEnabled = true
			IconController._navigationEnabled = true
		end
	end
end

local function getScaleMultiplier()
	if guiService:IsTenFootInterface() then
		return 3
	else
		return 1.3
	end
end

function IconController._setControllerSelectedObject(object)
	local startId = (IconController._controllerSetCount and IconController._controllerSetCount + 1) or 0
	IconController._controllerSetCount = startId
	guiService.SelectedObject = object
	task.delay(0.1, function()
		local finalId = IconController._controllerSetCountS
		if startId == finalId then
			guiService.SelectedObject = object
		end
	end)
end

function IconController._enableControllerMode(bool)
	local indicator = TopbarPlusGui.Indicator
	local controllerOptionIcon = IconController.getIcon("_TopbarControllerOption")
	if IconController.controllerModeEnabled == bool then
		return
	end
	IconController.controllerModeEnabled = bool
	if bool then
		TopbarPlusGui.TopbarContainer.Position = UDim2.new(0,0,0,5)
		TopbarPlusGui.TopbarContainer.Visible = false
		local scaleMultiplier = getScaleMultiplier()
		indicator.Position = UDim2.new(0.5,0,0,5)
		indicator.Size = UDim2.new(0, 18*scaleMultiplier, 0, 18*scaleMultiplier)
		indicator.Image = "rbxassetid://5278151556"
		indicator.Visible = checkTopbarEnabledAccountingForMimic()
		indicator.Position = UDim2.new(0.5,0,0,5)
		indicator.Active = true
		controllerMenuOverride = indicator.InputBegan:Connect(function(input)
			if input.UserInputType == Enum.UserInputType.MouseButton1 then
				IconController.setTopbarEnabled(true,false)
			end
		end)
	else
		TopbarPlusGui.TopbarContainer.Position = UDim2.new(0,0,0,0)
		TopbarPlusGui.TopbarContainer.Visible = checkTopbarEnabledAccountingForMimic()
		indicator.Visible = false
		IconController._setControllerSelectedObject(nil)
	end
	for icon, _ in pairs(topbarIcons) do
		IconController._enableControllerModeForIcon(icon, bool)
	end
end

function IconController._enableControllerModeForIcon(icon, bool)
	local parentIcon = icon._parentIcon
	local featureName = icon.joinedFeatureName
	if parentIcon then
		icon:leave()
	end
	if bool then
		local scaleMultiplier = getScaleMultiplier()
		local currentSizeDeselected = icon:get("iconSize", "deselected")
		local currentSizeSelected = icon:get("iconSize", "selected")
		local currentSizeHovering = icon:getHovering("iconSize")
		icon:set("iconSize", UDim2.new(0, currentSizeDeselected.X.Offset*scaleMultiplier, 0, currentSizeDeselected.Y.Offset*scaleMultiplier), "deselected", "controllerMode")
		icon:set("iconSize", UDim2.new(0, currentSizeSelected.X.Offset*scaleMultiplier, 0, currentSizeSelected.Y.Offset*scaleMultiplier), "selected", "controllerMode")
		if currentSizeHovering then
			icon:set("iconSize", UDim2.new(0, currentSizeSelected.X.Offset*scaleMultiplier, 0, currentSizeSelected.Y.Offset*scaleMultiplier), "hovering", "controllerMode")
		end
		icon:set("alignment", "mid", "deselected", "controllerMode")
		icon:set("alignment", "mid", "selected", "controllerMode")
	else
		local states = {"deselected", "selected", "hovering"}
		for _, iconState in pairs(states) do
			local _, previousAlignment = icon:get("alignment", iconState, "controllerMode")
			if previousAlignment then
				icon:set("alignment", previousAlignment, iconState)
			end
			local currentSize, previousSize = icon:get("iconSize", iconState, "controllerMode")
			if previousSize then
				icon:set("iconSize", previousSize, iconState)
			end
		end
	end
	if parentIcon then
		icon:join(parentIcon, featureName)
	end
end

local createdFakeHealthbarIcon = false
function IconController.setupHealthbar()

	if createdFakeHealthbarIcon then
		return
	end
	createdFakeHealthbarIcon = true

	-- Create a fake healthbar icon to mimic the core health gui
	task.defer(function()
		runService.Heartbeat:Wait()
		local Icon = require(iconModule)

		Icon.new()
			:setProperty("internalIcon", true)
			:setName("_FakeHealthbar")
			:setRight()
			:setOrder(-420)
			:setSize(80, 32)
			:lock()
			:set("iconBackgroundTransparency", 1)
			:give(function(icon)

				local healthContainer = Instance.new("Frame")
				healthContainer.Name = "HealthContainer"
				healthContainer.BackgroundColor3 = Color3.fromRGB(0, 0, 0)
				healthContainer.BorderSizePixel = 0
				healthContainer.AnchorPoint = Vector2.new(0, 0.5)
				healthContainer.Position = UDim2.new(0, 0, 0.5, 0)
				healthContainer.Size = UDim2.new(1, 0, 0.2, 0)
				healthContainer.Visible = true
				healthContainer.ZIndex = 11
				healthContainer.Parent = icon.instances.iconButton

				local corner = Instance.new("UICorner")
				corner.CornerRadius = UDim.new(1, 0)
				corner.Parent = healthContainer

				local healthFrame = healthContainer:Clone()
				healthFrame.Name = "HealthFrame"
				healthFrame.BackgroundColor3 = Color3.fromRGB(167, 167, 167)
				healthFrame.BorderSizePixel = 0
				healthFrame.AnchorPoint = Vector2.new(0.5, 0.5)
				healthFrame.Position = UDim2.new(0.5, 0, 0.5, 0)
				healthFrame.Size = UDim2.new(1, -2, 1, -2)
				healthFrame.Visible = true
				healthFrame.ZIndex = 12
				healthFrame.Parent = healthContainer

				local healthBar = healthFrame:Clone()
				healthBar.Name = "HealthBar"
				healthBar.BackgroundColor3 = Color3.fromRGB(255, 255, 255)
				healthBar.BorderSizePixel = 0
				healthBar.AnchorPoint = Vector2.new(0, 0.5)
				healthBar.Position = UDim2.new(0, 0, 0.5, 0)
				healthBar.Size = UDim2.new(0.5, 0, 1, 0)
				healthBar.Visible = true
				healthBar.ZIndex = 13
				healthBar.Parent = healthFrame

				local START_HEALTHBAR_COLOR = Color3.fromRGB(27, 252, 107)
				local MID_HEALTHBAR_COLOR = Color3.fromRGB(250, 235, 0)
				local END_HEALTHBAR_COLOR = Color3.fromRGB(255, 28, 0)

				local function powColor3(color, pow)
					return Color3.new(
						math.pow(color.R, pow),
						math.pow(color.G, pow),
						math.pow(color.B, pow)
					)
				end

				local function lerpColor(colorA, colorB, frac, gamma)
					gamma = gamma or 2.0
					local CA = powColor3(colorA, gamma)
					local CB = powColor3(colorB, gamma)
					return powColor3(CA:Lerp(CB, frac), 1/gamma)
				end

				local firstTimeEnabling = true
				local function listenToHealth(character)
					if not character then
						return
					end
					local humanoid = character:WaitForChild("Humanoid", 10)
					if not humanoid then
						return
					end

					local function updateHealthBar()
						local realHealthbarEnabled = starterGui:GetCoreGuiEnabled(Enum.CoreGuiType.Health)
						local healthInterval = humanoid.Health / humanoid.MaxHealth
						if healthInterval == 1 or IconController.healthbarDisabled or (firstTimeEnabling and realHealthbarEnabled == false) then
							if icon.enabled then
								icon:setEnabled(false)
							end
							return
						elseif healthInterval < 1 then
							if not icon.enabled then
								icon:setEnabled(true)
							end
							firstTimeEnabling = false
							if realHealthbarEnabled then
								starterGui:SetCoreGuiEnabled(Enum.CoreGuiType.Health, false)
							end
						end
						local startInterval = 0.9
						local endInterval = 0.1
						local m = 1/(startInterval - endInterval)
						local c = -m*endInterval
						local colorIntervalAbsolute = (m*healthInterval) + c
						local colorInterval = (colorIntervalAbsolute > 1 and 1) or (colorIntervalAbsolute < 0 and 0) or colorIntervalAbsolute
						local firstColor = (healthInterval > 0.5 and START_HEALTHBAR_COLOR) or MID_HEALTHBAR_COLOR
						local lastColor = (healthInterval > 0.5 and MID_HEALTHBAR_COLOR) or END_HEALTHBAR_COLOR
						local doubleSubtractor = (1-colorInterval)*2
						local modifiedColorInterval = (healthInterval > 0.5 and (1-doubleSubtractor)) or (2-doubleSubtractor)
						local newHealthFillColor = lerpColor(lastColor, firstColor, modifiedColorInterval)
						local newHealthFillSize = UDim2.new(healthInterval, 0, 1, 0)
						healthBar.BackgroundColor3 = newHealthFillColor
						healthBar.Size = newHealthFillSize
					end

					humanoid.HealthChanged:Connect(updateHealthBar)
					IconController.healthbarDisabledSignal:Connect(updateHealthBar)
					updateHealthBar()
				end
				localPlayer.CharacterAdded:Connect(function(character)
					listenToHealth(character)
				end)
				task.spawn(listenToHealth, localPlayer.Character)
			end)
	end)
end

function IconController._determineControllerDisplay()
	local mouseEnabled = userInputService.MouseEnabled
	local controllerEnabled = userInputService.GamepadEnabled
	local controllerOptionIcon = IconController.getIcon("_TopbarControllerOption")
	if mouseEnabled and controllerEnabled then
		-- Show icon (if option not disabled else hide)
		if not disableControllerOption then
			controllerOptionIcon:setEnabled(true)
		else
			controllerOptionIcon:setEnabled(false)
		end
	elseif mouseEnabled and not controllerEnabled then
		-- Hide icon, disableControllerMode
		controllerOptionIcon:setEnabled(false)
		IconController._enableControllerMode(false)
		controllerOptionIcon:deselect()
	elseif not mouseEnabled and controllerEnabled then
		-- Hide icon, _enableControllerMode
		controllerOptionIcon:setEnabled(false)
		IconController._enableControllerMode(true)
	end
end