extends Control

@export_group("Labels")
@export var score_label: Label = null
@export var time_label: Label = null
@export var lives_label: Label = null
@export var start_label: Label = null

@export_group("Audio")
@export var completed_sound: AudioStream = null
@export var pip_sound: AudioStream = null
@export var tick_sound: AudioStream = null

@export_group("Scenes")
@export_file("*.tscn") var track_info_path: String = ""
@export_file("*.tscn") var win_path: String = ""

var _showed: bool = false
var _score_calculated: bool = false
var _lives: int = 0
var _prev_score: int = 0


func _ready() -> void:
	hide()


func _physics_process(_delta: float) -> void:
	if not _showed:
		return

	if Input.is_action_just_pressed("start") and _score_calculated:
		get_tree().paused = false
		if Globals.current_track < Globals.tracks.size():
			Globals.current_track += 1
			get_tree().change_scene_to_file(track_info_path)
		else:
			get_tree().change_scene_to_file(win_path)

	score_label.text = "%05d" % Globals.total_score
	time_label.text = Globals.get_time_string(RideManager.get_instance().current_time)
	lives_label.text = str(_lives)

	if _prev_score != Globals.total_score:
		PulseSound0.load_and_play(tick_sound)
		_prev_score = Globals.total_score


func animation() -> void:
	_lives = Globals.player_lives
	_prev_score = Globals.total_score
	score_label.hide()
	time_label.hide()
	lives_label.hide()
	start_label.hide()
	await get_tree().create_timer(0.5).timeout
	score_label.show()
	PulseSound0.load_and_play(pip_sound)
	await get_tree().create_timer(0.5).timeout
	time_label.show()
	PulseSound0.load_and_play(pip_sound)
	await get_tree().create_timer(0.5).timeout
	time_to_score()
	await get_tree().create_timer(RideManager.get_instance().current_time * 0.03 + 0.5).timeout
	PulseSound0.load_and_play(pip_sound)
	lives_label.show()
	await get_tree().create_timer(0.5).timeout
	if Globals.player_lives > 0:
		lives_to_score()
		await get_tree().create_timer(0.5).timeout
	PulseSound0.load_and_play(pip_sound)
	start_label.show()
	_score_calculated = true


func lives_to_score() -> void:
	var lives: int = Globals.player_lives
	for i in range(lives):
		Globals.raw_score += 100.0
		await get_tree().create_timer(0.1).timeout


func show_menu() -> void:
	Music.stop()
	PulseSound1.load_and_play(completed_sound, 0.0, true)
	await PulseSound1.finished
	show()
	_showed = true
	get_tree().paused = true
	animation()


func time_to_score() -> void:
	var time: float = RideManager.get_instance().current_time
	var new_score: float = Globals.raw_score + time * 10
	var tween: Tween = get_tree().create_tween()
	tween.set_pause_mode(Tween.TWEEN_PAUSE_PROCESS)
	tween.parallel().tween_property(Globals, ^"raw_score", new_score, time * 0.03)
	tween.parallel().tween_property(RideManager.get_instance(), ^"current_time", 0, time * 0.03)
