-- @author DoomTero 2026

local ZomboRutScene = require "ZomboRut/ZomboRutScene"

ZR_CrowdControl = ZR_CrowdControl or {}

local DEBUG = true
local function log(fmt, ...)
	if DEBUG then print(string.format("[ZR Crowd] " .. fmt, ...)) end
end

local function modEnabled()
	if not SandboxVars or not SandboxVars.ZomboRut then return true end
	return SandboxVars.ZomboRut.enableMod ~= false
end

local DECOY_OFFSET  = 3
local DECOY_RADIUS  = 15
local DECOY_VOLUME  = 50
local TICK_INTERVAL = 30

ZR_CrowdControl.active = ZR_CrowdControl.active or {}

local function emitDecoys(player)
	local x, y, z = player:getX(), player:getY(), player:getZ()
	addSound(player, x - DECOY_OFFSET, y - DECOY_OFFSET, z, DECOY_RADIUS, DECOY_VOLUME)
	addSound(player, x + DECOY_OFFSET, y - DECOY_OFFSET, z, DECOY_RADIUS, DECOY_VOLUME)
	addSound(player, x - DECOY_OFFSET, y + DECOY_OFFSET, z, DECOY_RADIUS, DECOY_VOLUME)
	addSound(player, x + DECOY_OFFSET, y + DECOY_OFFSET, z, DECOY_RADIUS, DECOY_VOLUME)
end

local function onPlayerUpdate(player)
	local state = ZR_CrowdControl.active[player]
	if not state then return end
	state.ticks = state.ticks + 1
	if state.ticks % TICK_INTERVAL == 0 then
		emitDecoys(player)
	end
end

if ZR_CrowdControl.onPlayerUpdate then
	Events.OnPlayerUpdate.Remove(ZR_CrowdControl.onPlayerUpdate)
end
ZR_CrowdControl.onPlayerUpdate = onPlayerUpdate
Events.OnPlayerUpdate.Add(onPlayerUpdate)

if not ZR_CrowdControl._sceneCallbacksRegistered then
	ZomboRutScene.registerSceneStartCallback(function(player, _sceneActive)
		if not modEnabled() then return end
		if not player then return end
		ZR_CrowdControl.active[player] = { ticks = 0 }
		emitDecoys(player)
		log("decoys active around player")
	end)
	ZomboRutScene.registerSceneEndCallback(function(player, _active, _result)
		if ZR_CrowdControl.active[player] then
			ZR_CrowdControl.active[player] = nil
			log("scene end, decoys stopped")
		end
	end)
	ZR_CrowdControl._sceneCallbacksRegistered = true
end
