-- Create ParticleEffect for specified part (being destroyed)	

local function createParticles(parentPart)
	local particles = Instance.new("ParticleEmitter")
	particles.Name = "Particles"
	particles.Parent = parentPart
	particles.Texture = "rbxassetid://3127279684" -- Points icon
	particles.Size = NumberSequence.new(.75)
	particles.Acceleration = Vector3.new(0, -15, 0)
	particles.Lifetime = NumberRange.new(0.5, 1.5)
	particles.Speed = NumberRange.new(15)
	particles.SpreadAngle = Vector2.new(30, 30)
	particles.Rate = 20
	
	local particleThread = coroutine.create(function()
		wait(0.75)
		particles.Enabled = false
		DebrisService:AddItem(particles, 0.75)
	end)
	coroutine.resume(particleThread)
	
	return particles
end

local function getHittableWhitelist()
	local map = mapManager.getMap()
	if not map then 
		return false
	end
	
	local highPoints = map:FindFirstChild("HighPoints")
	local mediumPoints = map:FindFirstChild("MediumPoints")
	local lowPoints = map:FindFirstChild("LowPoints")
	
	return {highPoints, mediumPoints, lowPoints}
end

local function getHit(player)
	-- Destroy parts touching the player's right hand if they are in the map and not a prop (and award points)
	local humanoidRootPart = player.Character:FindFirstChild("HumanoidRootPart")
	if not humanoidRootPart then return end
	
	local origin = humanoidRootPart.Position + PUNCH_HEIGHT_OFFSET -- Lower the origin
	local aimDirection = humanoidRootPart.CFrame.lookVector
	
	-- create a ray aiming the same way as player
	local ray = Ray.new(origin, aimDirection * PUNCH_RANGE)

	-- Create a whitelist for the map folders
	local hittableWhitelist = getHittableWhitelist()
	if not hittableWhitelist then return end
	
	-- raycast		
	local hit, position = workspace:FindPartOnRayWithWhitelist(ray, hittableWhitelist, true)
	
	return hit
end

local function handleHit(hit, player)
	local model = getModel(hit)
	if model and isModelDestroyed(hit, destroyedModels) then
		return
	end
		
	-- Get topmost ancestor (for cases where touched part is part of a model)
	local topAncestor = getTopAncestor(hit)

	-- Points type matching name of ancestor folder
	local pointsType = topAncestor.Parent.Name
	
	-- Add member to debris
	DebrisService:AddItem(topAncestor, 0.01)
			
	-- Add model to destroy model table to track before Debris does garbage
	-- collection and removes it
	table.insert(destroyedModels, topAncestor)
			
	-- Make part/model non-collidable
	if topAncestor:IsA("Model") then
		breakModel(topAncestor)
	else
		topAncestor.CanCollide = false
	end
	
	createSmoke(topAncestor)
	local debris = createDebris(topAncestor)
	createParticles(debris)

	-- Award points
	leaderboardManager:incrementStat(player, "Points", gameSettings.pointValues[pointsType])
end
