-- Basic settings

local ROTATION_SPEED = 0.025

local tweenService = game:GetService("TweenService")
local debounce = false
local breakLoop = false

script.Parent.Touched:connect(function(hit)
	
	-- Check if player
	if hit.Parent:FindFirstChild("Humanoid") and not debounce then
		debounce = true
		
		-- Give if player isn't null and hasn't reached maximum coins
		local plr = game.Players:GetPlayerFromCharacter(hit.Parent)
		if plr ~= nil then
			local maxCoins = 10
			if plr.Stats.IsHunter.Value then
				maxCoins = maxCoins + 100
			end
			if plr.Stats.CoinsPickedUpInRound.Value < maxCoins then
				
				-- Set the loop to break
				breakLoop = true
				
				-- Give coin
				plr.Stats.CoinsPickedUpInRound.Value = plr.Stats.CoinsPickedUpInRound.Value + 1
				plr.Stats.Coins.Value = plr.Stats.Coins.Value + 1000
				
				-- Play effect
				game.ReplicatedStorage.Interactions.Client.GotCoinEffect:FireClient(plr, script.Parent.Position)
				
				-- Continously spin and make less visible
				local originalCFrame = script.Parent.CFrame
				for i=1, 20 do
					script.Parent.CFrame = originalCFrame * CFrame.new(-5 * math.sin(i * math.pi / 20), 0, 0) * CFrame.fromEulerAnglesXYZ(0.75 * i, 0, 0)
					script.Parent.Transparency = math.sin(i * math.pi / 40)
					wait()
				end
				
				-- Destroy
				script.Parent:destroy()
				
			end
		end
			
		debounce = false
	end
	
end)

while true do
	
	-- Wait
	local waitTime = wait()
	
	-- See if should break loop
	if breakLoop then
		break
	end
	
	-- Tween to rotate
	local goal
	if script.Parent.Transparency > 0 then
		goal = {
			CFrame = script.Parent.CFrame * CFrame.fromEulerAnglesXYZ(ROTATION_SPEED, 0, 0),
			Transparency = script.Parent.Transparency - 0.033
		}
	else
		goal = {
			CFrame = script.Parent.CFrame * CFrame.fromEulerAnglesXYZ(ROTATION_SPEED, 0, 0)
		}
	end
	tweenService:Create(script.Parent, TweenInfo.new(waitTime, Enum.EasingStyle.Linear, Enum.EasingDirection.Out), goal):Play()
	
end
