extends Node3D

@onready var player: FPVController = $PlayerFPV
@onready var fridge_note: Interactable = $Fridge/WiFiNote
@onready var door_back: Interactable = $WallS/DoorBack


func _ready() -> void:
	_apply_textures()
	player.interactable_focused.connect(_on_player_focused)
	player.interactable_unfocused.connect(_on_player_unfocused)

	if GameState.wifi_password_found:
		fridge_note.set_interactable(false)
	else:
		fridge_note.set_interactable(true)
	door_back.set_interactable(true)

	DialogManager.set_date_time(GameState.game_date, GameState.game_time)
	DialogManager.set_crosshair_visible(true)
	DialogManager.set_controls_hint("WASD ходить · мышь смотреть · ЛКМ взаимодействие · ESC мышь · Q выход")
	if GameState.wifi_password_found:
		DialogManager.set_objective("Вернись в комнату — флешка ждёт")
	else:
		DialogManager.set_objective("Найди пароль Wi-Fi на холодильнике")


func _apply_textures() -> void:
	var floor_mat: BaseMaterial3D = ($Floor/Mesh as MeshInstance3D).material_override
	TextureGen.apply_to_material(floor_mat, TextureGen.linoleum(), Vector3(6, 6, 6))

	var ceiling_mat: BaseMaterial3D = ($Ceiling/Mesh as MeshInstance3D).material_override
	TextureGen.apply_to_material(ceiling_mat, TextureGen.ceiling(), Vector3(4, 4, 4))

	for wall_path in ["WallN", "WallS", "WallE", "WallW"]:
		var wall_node: Node = get_node(wall_path)
		var wall_mat: BaseMaterial3D = (wall_node.get_node("Mesh") as MeshInstance3D).material_override
		TextureGen.apply_to_material(wall_mat, TextureGen.wallpaper(), Vector3(6, 5, 6))

	var door_panel_mat: BaseMaterial3D = ($WallS/DoorPanel as MeshInstance3D).material_override
	TextureGen.apply_to_material(door_panel_mat, TextureGen.door(), Vector3(1, 1, 1))


func _on_player_focused(obj: Node) -> void:
	if obj.has_method("get_prompt"):
		DialogManager.set_prompt(obj.get_prompt())


func _on_player_unfocused() -> void:
	DialogManager.clear_prompt()


func _on_note_interacted(_p: Node) -> void:
	DialogManager.clear_prompt()
	await DialogManager.show_note("«Wi-Fi: qwerty. Не парься.»\n— Бать")
	fridge_note.set_interactable(false)
	GameState.wifi_password_found = true
	GameState.unlock_achievement("Wi-Fi разведчик")
	DialogManager.set_objective("Вернись в комнату — флешка ждёт")


func _on_door_back_interacted(_p: Node) -> void:
	SceneManager.go_room()
