extends Area2D

const DIALOGO := preload("res://dialogues/dialogo1.dialogue")

@export var start_key: String = "start"
@export var tiempo: float = 1.5  # frame random interval (if you want)

@onready var npc_sprite: AnimatedSprite2D = $"../../AnimatedSprite2D"

var _loop_running := false

func _ready() -> void:
	randomize()
	DialogueManager.dialogue_started.connect(_on_dialogue_started)
	DialogueManager.dialogue_ended.connect(_on_dialogue_ended)
	_start_random_idle_loop()

# This is what the Player raycast calls
func interact(_player: Node = null) -> void:
	if Game.is_dialogue_active:
		return
	Game.is_dialogue_active = true
	DialogueManager.show_dialogue_balloon(DIALOGO, start_key)

func _start_random_idle_loop() -> void:
	if _loop_running:
		return
	_loop_running = true
	_random_idle_loop()

func _stop_random_idle_loop() -> void:
	_loop_running = false

func _random_idle_loop() -> void:
	while _loop_running:
		# Randomize frame inside "default" animation
		var anim := "default"
		if npc_sprite.animation != anim:
			npc_sprite.play(anim)

		var count := npc_sprite.sprite_frames.get_frame_count(anim)
		if count > 0:
			npc_sprite.frame = randi_range(0, count - 1)

		await get_tree().create_timer(tiempo).timeout

func _on_dialogue_started(_dialogue) -> void:
	Game.is_dialogue_active = true
	_stop_random_idle_loop()
	npc_sprite.pause()

func _on_dialogue_ended(_dialogue) -> void:
	await get_tree().create_timer(0.2).timeout
	Game.is_dialogue_active = false
	npc_sprite.play()
	_start_random_idle_loop()
