# Respawn safety handler
#
# Intended behavior:
# - If the player has a valid bed / respawn anchor spawn and actually respawns there, leave them alone.
# - If the player has no personal spawnpoint, or their personal spawnpoint was broken/obstructed and
#   Minecraft fell back to the world-spawn area near the Bordercraft anchor, move them to the anchor in the sky.
# - Always give Resistance on respawn so anchor fallback is safe.

# Always give fall protection first. The normal grounded-clear logic in loop.mcfunction removes it.
effect give @s resistance infinite 255 true

# Record current position.
execute store result score #bc_pos_x bc_tmp run data get entity @s Pos[0] 1
execute store result score #bc_pos_y bc_tmp run data get entity @s Pos[1] 1
execute store result score #bc_pos_z bc_tmp run data get entity @s Pos[2] 1

# Case 1: the player has no personal spawnpoint at all.
# If they are on the ground near the Bordercraft origin, treat that as the normal world-spawn fallback.
execute at @e[tag=bc_anchor,limit=1] unless data entity @s SpawnX if entity @s[distance=..64] if score #bc_pos_y bc_tmp matches ..200 run function bordercraft:respawn_fallback

# Case 2: the player does have a stored personal spawnpoint.
# Compare current respawn position to the stored SpawnX / SpawnZ.
execute if data entity @s SpawnX store result score #bc_spawn_x bc_tmp run data get entity @s SpawnX 1
execute if data entity @s SpawnZ store result score #bc_spawn_z bc_tmp run data get entity @s SpawnZ 1

scoreboard players operation #bc_dx bc_tmp = #bc_spawn_x bc_tmp
scoreboard players operation #bc_dx bc_tmp -= #bc_pos_x bc_tmp
scoreboard players operation #bc_dz bc_tmp = #bc_spawn_z bc_tmp
scoreboard players operation #bc_dz bc_tmp -= #bc_pos_z bc_tmp

# Only fallback if the player is near the Bordercraft origin on the ground AND clearly far away from
# their stored personal spawnpoint. That means Minecraft did not actually place them at their bed/anchor.
execute at @e[tag=bc_anchor,limit=1] if data entity @s SpawnX if entity @s[distance=..64] if score #bc_pos_y bc_tmp matches ..200 if score #bc_dx bc_tmp matches 9.. run function bordercraft:respawn_fallback
execute at @e[tag=bc_anchor,limit=1] if data entity @s SpawnX if entity @s[distance=..64] if score #bc_pos_y bc_tmp matches ..200 if score #bc_dx bc_tmp matches ..-9 run function bordercraft:respawn_fallback
execute at @e[tag=bc_anchor,limit=1] if data entity @s SpawnX if entity @s[distance=..64] if score #bc_pos_y bc_tmp matches ..200 if score #bc_dz bc_tmp matches 9.. run function bordercraft:respawn_fallback
execute at @e[tag=bc_anchor,limit=1] if data entity @s SpawnX if entity @s[distance=..64] if score #bc_pos_y bc_tmp matches ..200 if score #bc_dz bc_tmp matches ..-9 run function bordercraft:respawn_fallback
