@tool
@icon("uid://2e0o5lq5u7qj")
class_name PlayerRespawnPoint
extends Node2D

var _can_respawn: bool = false
const avatar_scene := preload("res://_player/Avatar.tscn")

func _ready() -> void:
	if not Engine.is_editor_hint():
		
		GlobalEvent.player_dead.connect(_on_player_dead)

func _on_player_dead(player: Player) -> void:
	call_deferred(&"respawn_avatar")

func _process(delta: float) -> void:
	queue_redraw()

func _draw() -> void:
	# 只在编辑器绘制
	if not Engine.is_editor_hint():
		return
	
	var color := Color(0.2, 0.9, 0.4, 0.8)
	var line_width := 2.0
	
	# 尺寸参数（都可以微调）
	var outer_radius := 16.0
	var inner_gap := 6.0
	var line_length := 10.0
	var center_radius := 3.0
	
	var center := Vector2.ZERO
	
	# —— 外圈圆环 ——
	draw_arc(
		center,
		outer_radius,
		0.0,
		TAU,
		48,          # 分段数，越大越圆
		color,
		line_width
	)
	
	# —— 准星十字 ——
	# 上
	draw_line(
		center + Vector2(0, -inner_gap),
		center + Vector2(0, -inner_gap - line_length),
		color,
		line_width
	)
	# 下
	draw_line(
		center + Vector2(0, inner_gap),
		center + Vector2(0, inner_gap + line_length),
		color,
		line_width
	)
	# 左
	draw_line(
		center + Vector2(-inner_gap, 0),
		center + Vector2(-inner_gap - line_length, 0),
		color,
		line_width
	)
	# 右
	draw_line(
		center + Vector2(inner_gap, 0),
		center + Vector2(inner_gap + line_length, 0),
		color,
		line_width
	)
	
	# —— 中心圆点 ——
	draw_circle(center, center_radius, color)


func push_respawner() -> void:
	_can_respawn = true

func pop_respawner() -> void:
	_can_respawn = false

func respawn_avatar() -> CharacterBody2D:
	if not _can_respawn: return null
	
	if not avatar_scene:
		return null
	
	var new_avatar : Player = avatar_scene.instantiate()
	var pc : PlayerController = GlobalEvent.get_player_controller()
	if not pc or not new_avatar:
		return null
	
	pc.unbind_avatar()
	pc.bind_avatar(new_avatar)
	
	new_avatar.position = self.global_position
	get_tree().current_scene.add_child(new_avatar)
	
	return new_avatar
