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

local ZomboRutScene = require "ZomboRut/ZomboRutScene"
local ZR_MenuUtil   = require "ZomboRut/ContextMenu/ZR_MenuUtil"

local banditsAvailable        = ZR_MenuUtil.banditsAvailable
local findOnTilesAndNeighbors = ZR_MenuUtil.findOnTilesAndNeighbors
local setIcon                 = ZR_MenuUtil.icon
local sceneLabel              = ZR_MenuUtil.sceneLabel

local FRIENDLY_SCENES = {
	{ base = "Holding_Holding_Holding",                   label = "Holding" },
	{ base = "StandingDoggy_StandingDoggy_StandingDoggy", label = "Standing Doggy" },
}

local function isFriendlyBandit(obj)
	if not banditsAvailable() then return false end
	if not instanceof(obj, "IsoZombie") then return false end
	if not obj:getVariableBoolean("Bandit") then return false end
	if obj:isDead() then return false end
	if Bandit.IsHostile and Bandit.IsHostile(obj) then return false end
	return true
end

local function findFriendlyBandit(worldobjects)
	return findOnTilesAndNeighbors(worldobjects, "moving", isFriendlyBandit)
end

local function maleMaleBlocked(playerObj, target)
	local bothMale = not playerObj:isFemale() and not target:isFemale()
	if not bothMale then return false end
	return not (SandboxVars and SandboxVars.ZomboRut
		and SandboxVars.ZomboRut.allowMaleMale == true)
end

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

	if playerObj:isDraggingCorpse() then return end
	if not banditsAvailable() then return end

	local target = findFriendlyBandit(worldobjects)
	if not target then return end

	if maleMaleBlocked(playerObj, target) then return end

	local entries = {}
	for _, fs in ipairs(FRIENDLY_SCENES) do
		local resolvedId = ZomboRutScene._resolveGender(playerObj, target, fs.base)
		if resolvedId then
			entries[#entries + 1] = { id = resolvedId, label = fs.label }
		end
	end
	if #entries == 0 then return end

	local function makeCb(sceneId)
		return function()
			ZomboRutScene.playSceneFromLive(playerObj, target, sceneId)
		end
	end

	local zrMenu = getRoot()
	local root = zrMenu:addOption(getText("ContextMenu_ZR_AskForSexMenu"), playerObj, nil)
	setIcon(root, "AskForSex")
	local sub = ISContextMenu:getNew(context)
	zrMenu:addSubMenu(root, sub)
	for _, e in ipairs(entries) do
		sub:addOption(sceneLabel(e.label), playerObj, makeCb(e.id))
	end
end
