class_name Checkpoint
extends Area2D

@onready var _sprite: AnimatedSprite2D = $AnimatedSprite2D

var is_activated: bool = false

func _ready() -> void:
	add_to_group("checkpoints")
	body_entered.connect(_on_body_entered)

func _on_body_entered(body: Node2D) -> void:
	if is_activated or not body.is_in_group("player"):
		return
	_activate()

func _activate() -> void:
	get_tree().call_group("checkpoints", "_deactivate")
	is_activated = true
	_sprite.play("activated")
	EventBus.has_checkpoint = true
	EventBus.last_checkpoint_position = global_position
	EventBus.checkpoint_activated.emit(global_position)

func _deactivate() -> void:
	if not is_activated:
		return
	is_activated = false
	_sprite.play("deactivated")
