-- Local Functions

local function makePurchase()
	local newLevel = upgrades.Value + 1

	BuyUpgradeEvent:FireServer()
	showLevelUpBanner()
end

local function updateUpgrades()
	local cost = GameSettings.upgradeCost(upgrades.Value)
	local upgradeProgress = points.Value/cost
	local starProgress = (points.Value % (cost / 3)) / (cost / 3)
	
	prevStarProgress = currStarProgress
	currStarProgress = starProgress

	local tweenTime = 1 * math.abs(starProgress - prevStarProgress)
	if starProgress <= prevStarProgress then
		local tweenTimeToFull = 1 * (1-prevStarProgress)
		tweenTime = 1 * (starProgress)

		ProgressBarContainer:TweenPosition(UDim2.fromScale(0, 0), 
			Enum.EasingDirection.Out, Enum.EasingStyle.Quad, tweenTimeToFull, true)
		ProgressBarFill:TweenPosition(UDim2.fromScale(0, 0), 
			Enum.EasingDirection.Out, Enum.EasingStyle.Quad, tweenTimeToFull, true)
			
		wait(tweenTime)
		if starProgress == currStarProgress then
			ProgressBarContainer.Position = UDim2.fromScale(-0.56, 0)
			ProgressBarFill.Position = UDim2.fromScale(0.56, 0)

			ProgressBarContainer:TweenPosition(UDim2.fromScale(-0.56 + math.min(1, starProgress) * 0.56, 0), 
				Enum.EasingDirection.Out, Enum.EasingStyle.Quad, tweenTime, true)
			ProgressBarFill:TweenPosition(UDim2.fromScale(0.56 - math.min(1, starProgress) * 0.56, 0), 
				Enum.EasingDirection.Out, Enum.EasingStyle.Quad, tweenTime, true)
		end	
	else
		ProgressBarContainer:TweenPosition(UDim2.fromScale(-0.5 + math.min(1, starProgress) * 0.5, 0), 
			Enum.EasingDirection.Out, Enum.EasingStyle.Quad, tweenTime, true)
		ProgressBarFill:TweenPosition(UDim2.fromScale(0.5 - math.min(1, starProgress) * 0.5, 0), 
			Enum.EasingDirection.Out, Enum.EasingStyle.Quad, tweenTime, true)
	end
	
	if points.Value >= cost then
		-- 3 Stars, slight pause, upgrade
		Star1.Visible = true
		Star2.Visible = true
		Star3.Visible = true
		wait()
		makePurchase()
	elseif points.Value >= 2*cost / 3 then
		-- 2 Stars
		Star1.Visible = true
		Star2.Visible = true
	elseif points.Value >= cost / 3 then
		-- 1 Star
		Star1.Visible = true
	else
		-- 0 Stars
		Star1.Visible = false
		Star2.Visible = false
		Star3.Visible = false
	end
end

local function toggleEnabled()	
	if GameplayUi.Enabled then
		ChangeController:FireServer(false)
	else
		ChangeController:FireServer(true)
	end
end

local function toggleLobby()
	if GameplayUi.Enabled then
		-- Enter lobby and exit game
		humanoidRoot.CFrame = SpawnLocation.CFrame + Vector3.new(0, 3, 0)
		humanoid.WalkSpeed = 16
		
		GameplayUi.Enabled = false
		Tutorial.Enabled = false
		Controller.Disabled = true
		InteractionBillboard.Enabled = true
		
		LobbyButton.Visible = false
	end
end

