extends CanvasLayer

@onready var anim:AnimationPlayer = $AnimationPlayer
@onready var text_box:TextBox = $RichTextLabel
@onready var timer:Timer = $Timer

@export var cam_main:Camera2D

@export var spawn_point:Vector2
var respawn_point:Vector2
@export var player:Player
var respawning = false

var text_to_show = ''
signal cutscene
var trophies_sprites
var trophies = [false, false, false, false]
var ref = 0
var node_textures

func _ready():
	if player:
		respawn_point = player.position
	trophies_sprites = get_tree().get_first_node_in_group("trophies").get_children()
	node_textures = $Node.get_children()


func _on_player_trigger_object(text:String, reference:int) -> void:
	anim.play("fade out")
	trophies[reference] = true
	trophies_sprites[reference].visible = true
	text_to_show = text
	ref = reference
	
func _on_animation_player_animation_finished(anim_name: StringName) -> void:
	if anim_name == "fade out":
		if not respawning: 
			anim.play('item')
			node_textures[ref].visible = true
			
			var completed = true
			for t in trophies:
				if not t:
					completed = false
					break
			if completed: cutscene.emit()

		else:
			if player:
				player.position = respawn_point
				
				
				
			respawning = false
			anim.play("fade in")
			anim.speed_scale = 1
	
	if anim_name  == "item":
		text_box.set_new_text(text_to_show)

func _on_rich_text_label_done_text() -> void:
	timer.start()
	if player:
		player.position = spawn_point
		cam_main.make_current()
	
	
func _on_timer_timeout() -> void:
	text_box.reset_text()
	for txt in node_textures:
			txt.visible = false
	$Sprite2D.visible = false
	anim.play("fade in")
	

func respawn(_body:Node2D):
	respawning = true
	anim.speed_scale = 3
	anim.play("fade out")
	


func _on_cameras_change_respawn(player_pos:Vector2) -> void:
	respawn_point = player_pos
