-- Basic settings

local COOLDOWN_TIME = 25
local RUNTIME = 10

local plr = game.Players.LocalPlayer
local inputService = game:GetService("UserInputService")

game.ReplicatedStorage.Interactions.Client.Perks.UseInvisibility.OnClientEvent:connect(function()
	
	-- Make sure character is alive
	if plr.Character ~= nil and plr.Character:FindFirstChild("Humanoid") then
		
		-- Show tip
		plr.PlayerGui.MainGui.Tip.Text = "Press Q to turn invisible"
		
		-- Set map object
		local map = workspace:FindFirstChild("Map")
	
		-- Listen for keypress
		local debounce = false
		local event
		local done = false
		event = inputService.InputBegan:connect(function(inputObj)
			
			-- Check if states are correct
			if inputObj.KeyCode == Enum.KeyCode.Q and not debounce and not done and workspace:FindFirstChild("Map") == map then
				debounce = true
				
				-- Tell server to make invisible
				game.ReplicatedStorage.Interactions.Server.Perks.MakeInvisible:FireServer()
				
				-- Update text to match state
				for i=1, RUNTIME do
					if done or workspace:FindFirstChild("Map") == nil then
						break
					end
					plr.PlayerGui.MainGui.Tip.Text = "Invisible for " .. (RUNTIME - i + 1) .. " seconds"
					wait(1)
				end
				if not done and workspace:FindFirstChild("Map") then
					for i=1, COOLDOWN_TIME do
						if done or workspace:FindFirstChild("Map") == nil then
							break
						end
						plr.PlayerGui.MainGui.Tip.Text = "Can use again in " .. (COOLDOWN_TIME - i + 1) .. " seconds"
						wait(1)
					end
					if not done and workspace:FindFirstChild("Map") then
						plr.PlayerGui.MainGui.Tip.Text = "Press Q to turn invisible"
					end
				end
				if done or workspace:FindFirstChild("Map") == nil then
					if event ~= nil then
						event:disconnect()
						event = nil
					end
					done = true
					plr.PlayerGui.MainGui.Tip.Text = ""
				end
				
				debounce = false
			elseif workspace:FindFirstChild("Map") ~= map then
				if event ~= nil then
					event:disconnect()
					event = nil
				end
				done = true
				plr.PlayerGui.MainGui.Tip.Text = ""
			end
			
		end)
		
		-- Connect character death
		plr.Character.Humanoid.Died:connect(function()
			if not done then
				event:disconnect()
				event = nil
				done = true
				plr.PlayerGui.MainGui.Tip.Text = ""
			end
		end)
		
	end
	
end)
