dofile_once("mods/lewd_noita/files/text/ln_text.lua")

local entity = GetUpdatedEntityID()
local kobold_id = EntityGetParent(entity)
if kobold_id == nil or kobold_id == 0 then return end

local no_cooldown = true

for _, ch in ipairs(EntityGetAllChildren(kobold_id) or {}) do
	if EntityGetName(ch) == "ln_sex_cooldown" then
		no_cooldown = false
		break
	end
end

-- Also block if compulsion is active (would conflict with controls)
if GlobalsGetValue("LN_COMPULSION_ACTIVE", "0") == "1" then
	no_cooldown = false
end

SetRandomSeed(GameGetFrameNum(), entity)

if no_cooldown == true then
	local dmg = EntityGetFirstComponent(kobold_id, "DamageModelComponent")
	if dmg == nil then return end
	if ComponentGetValue2(dmg, "is_on_fire") == true then return end

	local preg_vsc = EntityGetFirstComponent(entity, "VariableStorageComponent")
	if preg_vsc == nil then return end
	local spawn_file = ComponentGetValue2(preg_vsc, "value_string")
	if spawn_file == nil or spawn_file == "" then return end

	local birth_scene = EntityCreateNew("birth")

	EntityAddComponent2(birth_scene, "VariableStorageComponent", {
		value_string = spawn_file,
	})

	local kobold_x, kobold_y = EntityGetTransform(kobold_id)

	if Random(0, 1) == 1 then
		EntitySetTransform(birth_scene, kobold_x, kobold_y, 0, 1, 1)
	else
		EntitySetTransform(birth_scene, kobold_x, kobold_y, 0, -1, 1)
	end

	EntityAddChild(birth_scene, kobold_id)

	EntityAddComponent2(birth_scene, "LuaComponent", {
		script_source_file="mods/lewd_noita/files/sex_logic/sex_scene.lua"
	})

	EntityKill(entity)

	if IsPlayer(kobold_id) == true then
		ln_print_birth_start("mods/lewd_noita/files/sex_logic/ui_msg.png")
		GamePlaySound("data/audio/Desktop/event_cues.bank", "event_cues/heartbeat/create", kobold_x, kobold_y)
	end
else
	-- delay birth if it triggers during another scene or compulsion
	EntityAddComponent2(entity, "LuaComponent", {
		script_source_file="mods/lewd_noita/files/sex_logic/start_birth.lua",
		execute_every_n_frame=Random(10, 15) * 60,
		remove_after_executed=true,
	})
end
