extends Node

@export var pickup_scene : PackedScene
@export var powerup_scene : PackedScene

@export var playtime = 5

var level = 1
var score = 0
var timeLeft = 0
var screenSize = Vector2.ZERO
var playState = false
# Called when the node enters the scene tree for the first time.
func _ready():
	screenSize = get_viewport().get_visible_rect().size
	$Player.screenSize = screenSize
	$Player.hide()
	
	#new_game()
	
func new_game():
	playState = true
	level = 1
	score = 0
	timeLeft = playtime
	$Player.start()
	$Player.show()
	$GameTimer.start()
	spawnFruits()
	$HUD.updateScore(score)
	$HUD.updateTime(timeLeft)
	
func spawnFruits():
	var po = powerup_scene.instantiate()
	add_child(po)
	po.screenSize = screenSize
	po.position = Vector2(randi_range(0, screenSize.x), randi_range(0, screenSize.y))
	for i in level * 2 + 3:
		var fr = pickup_scene.instantiate()
		add_child(fr)
		fr.screenSize = screenSize
		fr.position = Vector2(randi_range(0, screenSize.x), randi_range(0, screenSize.y))
	


# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta):
	if playState and get_tree().get_node_count_in_group("fruits") == 0:
		level += 1
		timeLeft += 10
		$LevelSound.play()
		spawnFruits()

func _on_game_timer_timeout():
	timeLeft -= 1
	$HUD.updateTime(timeLeft)
	if timeLeft < 0:
		gameOver()
		
func _on_player_hit():
	gameOver()

func _on_player_pickup():
	$FruitSound.play()
	score += 1
	$HUD.updateScore(score)

func gameOver():
	$EndSound.play()
	playState = false
	$GameTimer.stop()
	get_tree().call_group("fruits", "queue_free")
	$HUD.showGameOver()
	$Player.die()
	#$Player.hide()
	

func _on_hud_start_game():
	new_game()
