@tool
extends Area2D

@export var memory_texture: Texture2D:
	set(value):
		memory_texture = value
		if has_node("Sprite2D"):
			$Sprite2D.texture = memory_texture

@export var return_spawn: Marker2D
@export var wardrobe: Node2D

@onready var sprite: Sprite2D = $Sprite2D

var player_inside := false
var player: Player = null

func _ready() -> void:
	if memory_texture:
		sprite.texture = memory_texture

	if not Engine.is_editor_hint():
		body_entered.connect(_on_body_entered)
		body_exited.connect(_on_body_exited)

func _process(_delta: float) -> void:
	if Engine.is_editor_hint():
		return

	if player_inside and Input.is_action_just_pressed("interact"):
		collect_memory()

func _on_body_entered(body: Node) -> void:
	if body is Player:
		player_inside = true
		player = body
		print("Press ENTER to collect memory piece")

func _on_body_exited(body: Node) -> void:
	if body is Player:
		player_inside = false
		player = null

func collect_memory() -> void:
	if player == null:
		return

	print("Memory piece collected")

	if wardrobe and wardrobe.has_method("complete_wardrobe"):
		wardrobe.complete_wardrobe()

	if return_spawn:
		player.global_position = return_spawn.global_position
	else:
		print("No return_spawn assigned to memory piece")

	queue_free()
