## Tests for SnapReceiver — snap detection when Character is released near a SnapPoint.
extends GutTest

var _char: Character
var _snap: SnapPoint


func before_each() -> void:
	_char = preload("res://scenes/characters/Character.tscn").instantiate() as Character
	add_child_autofree(_char)
	_snap = SnapPoint.new()
	_snap.pose = "sitting"
	add_child_autofree(_snap)


func _get_receiver() -> SnapReceiver:
	return _char.get_node("SnapReceiver") as SnapReceiver


func test_snap_receiver_exists_on_character() -> void:
	assert_not_null(_get_receiver())


func test_no_current_snap_initially() -> void:
	assert_null(_get_receiver().get_current_snap())


func test_snap_detected_when_character_released_within_radius() -> void:
	_snap.global_position = Vector2(0.0, 0.0)
	_char.global_position = Vector2(50.0, 0.0)
	_get_receiver()._on_drag_released(Vector2(50.0, 0.0))
	assert_eq(_get_receiver().get_current_snap(), _snap)


func test_no_snap_when_released_outside_radius() -> void:
	_snap.global_position = Vector2(0.0, 0.0)
	_char.global_position = Vector2(200.0, 0.0)
	_get_receiver()._on_drag_released(Vector2(200.0, 0.0))
	assert_null(_get_receiver().get_current_snap())


func test_character_position_set_to_snap_point_on_snap() -> void:
	_snap.global_position = Vector2(100.0, 100.0)
	_char.global_position = Vector2(120.0, 100.0)
	_get_receiver()._on_drag_released(Vector2(120.0, 100.0))
	assert_eq(_char.global_position, Vector2(100.0, 100.0))


func test_character_animation_set_to_snap_pose_on_snap() -> void:
	_snap.global_position = Vector2(0.0, 0.0)
	_snap.pose = "lying"
	_char.global_position = Vector2(50.0, 0.0)
	_get_receiver()._on_drag_released(Vector2(50.0, 0.0))
	assert_eq(_char.get_animation_state(), "lying")


func test_pickup_clears_current_snap() -> void:
	_snap.global_position = Vector2(0.0, 0.0)
	_char.global_position = Vector2(50.0, 0.0)
	_get_receiver()._on_drag_released(Vector2(50.0, 0.0))
	_get_receiver()._on_drag_picked_up(Vector2(50.0, 0.0))
	assert_null(_get_receiver().get_current_snap())


func test_pickup_frees_snap_point() -> void:
	_snap.global_position = Vector2(0.0, 0.0)
	_char.global_position = Vector2(50.0, 0.0)
	_get_receiver()._on_drag_released(Vector2(50.0, 0.0))
	_get_receiver()._on_drag_picked_up(Vector2(50.0, 0.0))
	assert_true(_snap.is_free())


func test_second_character_cannot_snap_to_occupied_point() -> void:
	_snap.global_position = Vector2(0.0, 0.0)
	_char.global_position = Vector2(50.0, 0.0)
	_get_receiver()._on_drag_released(Vector2(50.0, 0.0))
	var char2: Character = preload("res://scenes/characters/Character.tscn").instantiate() as Character
	add_child_autofree(char2)
	char2.global_position = Vector2(60.0, 0.0)
	var recv2: SnapReceiver = char2.get_node("SnapReceiver") as SnapReceiver
	recv2._on_drag_released(Vector2(60.0, 0.0))
	assert_null(recv2.get_current_snap())
