extends Control

@export var tuto_got_sword_packed : PackedScene
@export var focused_viewport : Viewport
var already_shown_weapon_tuto : bool = false
var active_tutorial: Control

@onready var tutorial_master_panel: PanelContainer = $PanelContainer
@onready var wait_to_show_blocking_tuto: Timer = $WaitToShowBlockingTuto

@onready var tuto_move_and_look: VBoxContainer = %TutoMoveAndLook
@onready var tuto_mantle_up: HBoxContainer = %TutoMantleUp
@onready var tuto_wall_jump: HBoxContainer = %TutoWallJump
@onready var tuto_dash_weapon: HBoxContainer = %TutoDashWeapon
@onready var tuto_weapon_throw: HBoxContainer = %TutoWeaponThrow
@onready var tuto_enjoy: HBoxContainer = %TutoEnjoy


func _ready() -> void:
	active_tutorial = tuto_move_and_look
func hide_tutorials(body: Node3D) -> void:
	active_tutorial.visible = false
	master_invisible()
func master_invisible() -> void:
	tutorial_master_panel.visible = false
func master_visible() -> void:
	tutorial_master_panel.visible = true
func handle_new_tutorial(tuto: Control) -> void:
	tuto.visible = true
	active_tutorial = tuto
	master_visible()


func _on_tuto_mantle_body_entered(body: Node3D) -> void:
	handle_new_tutorial(tuto_mantle_up)

func _on_tuto_wall_jump_body_entered(body: Node3D) -> void:
	handle_new_tutorial(tuto_wall_jump)

func _on_tuto_done_area_body_entered(body: Node3D) -> void:
	handle_new_tutorial(tuto_dash_weapon)

func _on_weapon_retrieved_body_entered(body: Node3D) -> void:
	wait_to_show_blocking_tuto.start()

func _on_tuto_weapon_throw_body_entered(body: Node3D) -> void:
	handle_new_tutorial(tuto_weapon_throw)

func _on_tuto_enjoy_body_entered(body: Node3D) -> void:
	handle_new_tutorial(tuto_enjoy)

func _show_weapon_tutorial() -> void:
	if already_shown_weapon_tuto:
		return
	
	already_shown_weapon_tuto = true
	if not focused_viewport:
		focused_viewport = get_viewport()
	var _initial_focus_control = focused_viewport.gui_get_focus_owner()
	var current_menu = tuto_got_sword_packed.instantiate()
	get_tree().current_scene.call_deferred("add_child", current_menu)
	await current_menu.tree_exited
	if is_inside_tree() and _initial_focus_control:
		_initial_focus_control.grab_focus()
