-- @author DoomTero 2026
-- @copyright 2026 DoomTero - ZomboRut original work. ref:6463bff8
-- @license Proprietary. Not licensed for reuse, redistribution or derivative works without written permission from DoomTero. Ask - permission is obtainable. See ZomboRut/LICENSE.txt

require "TimedActions/ISUnsubdueZombieAction"

local findOnTilesAndNeighbors = require("ZomboRut/ContextMenu/ZR_MenuUtil").findOnTilesAndNeighbors
local setIcon = require("ZomboRut/ContextMenu/ZR_MenuUtil").icon

local function isSubduedZombie(obj)
	if not instanceof(obj, "IsoZombie") then return false end
	if obj:isDead() then return false end
	local md = obj.getModData and obj:getModData() or nil
	return md ~= nil and md.zrSubdued == true
end

local function onUnsubdue(playerObj, target)
	local sq = target:getSquare()
	if not sq then return end
	if not luautils.walkAdj(playerObj, sq) then return end

	ISTimedActionQueue.add(ISUnsubdueZombieAction:new(playerObj, target))
end

return function(ContextMenu, playerObj, context, worldobjects, getRoot)
	if not playerObj then return end

	if playerObj:isDraggingCorpse() then return end

	local target = findOnTilesAndNeighbors(worldobjects, "moving", isSubduedZombie)
	if not target then return end

	local option = getRoot():addOption(
		getText("ContextMenu_ZR_Unsubdue") or "Untie",
		worldobjects,
		function() onUnsubdue(playerObj, target) end)
	setIcon(option, "Untie")

	local tooltip = ISToolTip:new()
	tooltip:initialise()
	tooltip:setVisible(false)
	tooltip.description = " <RED>" .. (getText("ContextMenu_ZR_Unsubdue_Warning")
		or "Returns the binding and tape. The zombie will get up and attack.")
	option.toolTip = tooltip
end
