core.register_abm({
	label = "Water freezing",
	nodenames = { "group:water" },
	interval = 1.2,
	chance = 1.8,
	catch_up = true,
	action = function(pos)
		if pos.y < PyuTest.OVERWORLD_SURFACE_BOTTOM and pos.y >= PyuTest.OVERWORLD_DEEP_OCEAN_MIN then
			return
		end

		local def = PyuTest.get_biome_def(pos)
		if not def then return end

		local heat = def.heat_point or 50
		local found = core.find_node_near(pos, 2, { "group:emits_heat" }) ~= nil

		if heat <= PyuTest.WATER_FREEZING_TEMPERATURE and not found then
			core.set_node(pos, { name = "pyutest_blocks:ice_block" })
		end
	end
})

core.register_abm({
	label = "Water evaporating",
	nodenames = { "group:water" },
	interval = 0.1,
	chance = 1,
	action = function(pos)
		local def = PyuTest.get_biome_def(pos)
		if not def then return end

		local heat = def.heat_point or 50

		if heat >= PyuTest.WATER_EVAPORATING_TEMPERATURE then
			core.remove_node(pos)
		end
	end
})

core.register_abm({
	label = "Ice thawing",
	nodenames = { "group:thawable" },
	neighbors = { "group:emits_heat" },
	interval = 3,
	chance = 2.5,
	catch_up = true,
	action = function(pos, node)
		local def = core.registered_nodes[node.name]
		local thaw_into = def.__thaw_into or "pyutest_blocks:water_source"
		core.set_node(pos, { name = thaw_into })
	end
})

core.register_abm({
	nodenames = { "group:lava" },
	interval = 1,
	chance = 1,
	action = function(pos)
		local function is_water(p)
			local name = core.get_node(p).name

			return core.get_item_group(name, "water") ~= 0
		end

		local function replace(name, p)
			core.set_node(p or pos, { name = name })
		end

		local p1 = vector.new(pos.x, pos.y + 1, pos.z)
		local p2 = vector.new(pos.x, pos.y - 1, pos.z)

		if is_water(p1) then
			replace("pyutest_blocks:obsidian_block")
			return
		end

		if is_water(p2) then
			replace("pyutest_blocks:stone_block", p2)
			return
		end

		for dx = -1, 1 do
			for dz = -1, 1 do
				local p3 = vector.new(pos.x + dx, pos.y, pos.z + dz)
				if is_water(p3) then
					replace("pyutest_blocks:cobblestone_block")
					return
				end
			end
		end
	end
})
