--[[
	Implementation
]]


local localPlayer = Players.LocalPlayer

local ActionPrompts = {
	targetChanged = Signal.new(),
	actionActivated = Signal.new(),
	targetInstance = nil,
	isRunning = false,
}

local function contextActivate(actionName, userInputState, inputObject)
	if not ActionPrompts.targetInstance then
		return Enum.ContextActionResult.Pass
	end

	if userInputState == Enum.UserInputState.Begin then
		ActionPrompts.actionActivated:fire(ActionPrompts.targetInstance)
	end
end

local function getTarget()
	local humanoidRootPart = localPlayer.Character and localPlayer.Character:FindFirstChild("HumanoidRootPart")

	if not humanoidRootPart then
		return
	end

	local closestAction = getNearestTagged(humanoidRootPart.Position, "Action", MAX_CUTTOFF_DISTANCE)

	if closestAction then
		if closestAction ~= ActionPrompts.targetInstance then
			ActionPrompts.targetChanged:fire({
				enabled = true,
				newTargetInstance = closestAction,
				oldTargetInstance = ActionPrompts.targetInstance,
				sizeOffset = ACTION_BUTTON_OFFSET,
			})
		end
	else
		ActionPrompts.targetChanged:fire({
			enabled = false,
			newTargetInstance = closestAction,
			oldTargetInstance = ActionPrompts.targetInstance,
		})
	end

	ActionPrompts.targetInstance = closestAction
end

function ActionPrompts.start()
	RunService:BindToRenderStep("GetActionTarget", Enum.RenderPriority.Camera.Value - 1, function()
		getTarget()
	end)

	ContextActionService:BindActionAtPriority(
		"ActionActivate",
		contextActivate,
		false,
		ACTION_PRIORITY,
		ACTIVATE_KEYBOARD,
		ACTIVATE_CONSOLE
	)

	ActionPrompts.isRunning = true
end

function ActionPrompts.stop()
	RunService:UnbindFromRenderStep("GetActionTarget")

	ActionPrompts.isRunning = false
end

function ActionPrompts.activate()
	if not ActionPrompts.targetInstance then
		return
	end

	ActionPrompts.actionActivated:fire(ActionPrompts.targetInstance)
end
