extends Node2D

@onready var health_bar: HealthBar = $HealthBar
@onready var transition: Transition = $Overlay/Transition
@onready var spawn_timer: Timer = $Timer
@onready var base_hit_sound: AudioStreamPlayer = $BaseHitSound

@onready var main_menu: PackedScene = load("res://screens/main_menu.tscn")
@onready var bot_scene: PackedScene = load("res://assets/scenes/bot.tscn")

@onready var spawn_points: Array[Marker2D] = [
	$EnemySpawn_1,
	$EnemySpawn_2,
	$EnemySpawn_3,
]

func _ready() -> void:
	transition.slide_out()
	await transition.game_fully_visible
	spawn_bot()

func _process(_delta: float) -> void:
	if Input.is_action_pressed("ui_cancel"):
		var tree = get_tree()
		transition.text = ""
		transition.slide_in()
		await transition.game_fully_hidden
		tree.change_scene_to_packed(main_menu)
		
func spawn_bot() -> void:
	var spawn = spawn_points.pick_random()
	var bot = bot_scene.instantiate()
	bot.global_position = spawn.global_position
	add_child(bot)

func _on_timer_timeout() -> void:
	spawn_bot()

func base_hit() -> void:
	base_hit_sound.play()
	health_bar.health -= 1
	if health_bar.health == 0:
		spawn_timer.stop()
		var foes = get_tree().get_nodes_in_group("foe")
		for foe in foes:
			foe.queue_free()

func _on_base_area_entered(area: Area2D) -> void:
	if area.is_in_group("foe") || area.is_in_group("foe_weapons"):
		area.queue_free()
		base_hit()
