--- Zombie and bandits nondefeat options
-- подключение api самого мода, чтобы видеть всякое типо связывания
local ZomboLewd = require("ZomboLewd/ZomboLewd")
-- Теги позиций для обработки в менюшнки
local ListedPositions = { 
    "Oral",
    "Intercourse",
    "Consent",
}

local function onAskForSex(worldObjects, contextMenu, position, requester, target)
  DebugLog.log("[ZomboLewd] /onAskForSex/")
  local opts = PZAPI.ModOptions:getOptions("ZomboLewdFramework")
  local requesterFemale = requester:isFemale()
  local targetFemale    = target:isFemale()
  local sPosition = ListedPositions[position]
  print("Requester isFemale =", requesterFemale, "Target isFemale =", targetFemale)
  print("Requester isFemale =", requester:isZombie(), "Target isFemale =", target:isZombie())
  -- Determine number of male/female actors
  local maleCount, femaleCount
  if requesterFemale and targetFemale then
    maleCount, femaleCount = 0, 2    -- Lesbian
  elseif not requesterFemale and not targetFemale then
    maleCount, femaleCount = 2, 0    -- Gay
  else
    maleCount, femaleCount = 1, 1    -- Straight
  end

  -- Fetch random sex animation
  local availableAnimations = contextMenu.Client.AnimationUtils:getAnimations(2, maleCount, femaleCount, {sPosition})
  local randomIndex         = ZombRand(1, #availableAnimations + 1)
  local selectedAnimation   = availableAnimations[randomIndex]
  local WornedItems = {}

  contextMenu.Client.AnimationHandler.Play(
    worldObjects,
    { requester, target },
    selectedAnimation,
    false,
    true,
    {                    
        Start = function(action)                        
            if opts:getOption("box_SUndress"):getValue() then
                DebugLog.log("[Zombolewd] /ZLHandleZombie.lua/ Try to undress...")                
                WornedItems = ZomboLewd.ClothHandler.Undress(requester)
                DebugLog.log(string.format("WornedItems count: %d", #WornedItems))
            end
        end,
        Perform = function(action)
          if opts:getOption("box_SUndress"):getValue() then
                DebugLog.log("[Zombolewd] /ZLHandleZombie.lua/ Try to dressup...")     
                ZomboLewd.ClothHandler.DressUp(requester,WornedItems) 
            end    
        end
    }
  )
end

--- Callback: Subdue a prone zombie
local function onSubdue(worldObjects, contextMenu, player, zombie)
  DebugLog.log("[ZomboLewd] /onSubdue/")
  local weapon_primary = player:getPrimaryHandItem()
  local weapon_secondary = player:getSecondaryHandItem()  
  local inventory = player:getInventory()
  local items = inventory:getItems()
  if weapon_primary and weapon_primary:hasTag(ItemTag.ROPE) then
    DebugLog.log("[ZomboLewd] Rope in main hand. Removing...")
    weapon_primary:Use()
  elseif weapon_secondary and weapon_secondary:hasTag(ItemTag.ROPE) then
    DebugLog.log("[ZomboLewd] Rope in secondary hand. Removing...")
    weapon_secondary:Use()
  else
    for i = 0, items:size() - 1 do
      local item = items:get(i)   
      if item:hasTag(ItemTag.ROPE) then
        DebugLog.log("[ZomboLewd] Rope in inventory. using...")
        item:Use()
        break
      end
    end
  end
  player:Say(getText("IGUI_Phrase_subdued"))
  ZomboLewd.ZombieHandler.Subdue(zombie)
end
  
--- Helper: Check if player carries rope
local function hasRope(player)
  DebugLog.log("[ZomboLewd] /hasRope/")
  local function isRope(item) return item and item:hasTag(ItemTag.ROPE) end
  if isRope(player:getPrimaryHandItem()) or isRope(player:getSecondaryHandItem()) then
    return true
  end

  local invItems = player:getInventory():getItems()
  for i = 0, invItems:size() - 1 do
    if isRope(invItems:get(i)) then
      return true
    end
  end
  return false
end

  --- Main export: build context menu
return function(ContextMenuClass, character, clickedZombie, context, worldObjects)
  DebugLog.log("[ZomboLewd] ZLHandleZombie function")

  local opts = PZAPI.ModOptions:getOptions("ZomboLewdFramework")
  if not opts:getOption("box_Survivor_Sex"):getValue() then
    return
  end
  if character:isFemale() == clickedZombie:isFemale() then
      return
  end

  if clickedZombie:isUseless() then
    local sOption = context:addOption(getText("ContextMenu_AskForSex"), worldobjects)	
    local sSexSubMenu = ISContextMenu:getNew(context)	
    context:addSubMenu(sOption, sSexSubMenu)
    for iPosition = 1, #ListedPositions do	
      local text = getText(string.format("ContextMenu_AskForSex_%s", ListedPositions[iPosition]))
      if text then
        local animationOption = sSexSubMenu:addOption(text, worldobjects, onAskForSex, ContextMenuClass, iPosition, character, clickedZombie)
      else
        DebugLog.log(string.format("Missing Text: %s", anim))
      end
    end
  elseif clickedZombie:isProne() or clickedZombie:isKnockedDown() or clickedZombie:isCrawling() then
    if not character:hasTrait(ZombolewdRegistries.Peaceful) then
      if hasRope(character) then
          context:addOption(
          getText("ContextMenu_Subdue"),
          worldObjects,
          onSubdue,
          ContextMenuClass,
          character,
          clickedZombie
          )
      else
          context:addOption(getText("ContextMenu_Subdue_noRope"), worldObjects)
      end
    end
  else
      context:addOption(getText("ContextMenu_noSubdue"), worldObjects)
  end
end