# World.gd
# Initialisiert die Spielwelt: weist dem Gegner den Spieler als Ziel zu
extends Node3D

const ENEMY_SCENE = preload("res://enemy.tscn")
const MAIN_MENU = preload("res://main_menu.tscn")
const CLASS_SELECTION_MENU = preload("res://class_selection_menu.tscn")
const RESPAWN_TIME = 5.0

# Startausrüstung
const STARTER_SWORD = preload("res://equipment/iron_sword.tres")
const STARTER_STAFF = preload("res://equipment/wooden_staff.tres")
const STARTER_CHEST = preload("res://equipment/leather_chest.tres")

# Loot Tables
const GOBLIN_LOOT = preload("res://loot_tables/goblin_loot.tres")

@onready var player = $Player

func _ready():
	# Hauptmenü anzeigen
	var main_menu = MAIN_MENU.instantiate()
	add_child(main_menu)
	main_menu.start_game.connect(_on_start_game)

# Nach Hauptmenü: Klassenauswahl anzeigen
func _on_start_game():
	var menu = CLASS_SELECTION_MENU.instantiate()
	add_child(menu)
	menu.class_selected.connect(_on_class_selected)
	# Spiel wieder pausieren für Klassenauswahl
	get_tree().paused = true

# Klasse ausgewählt: Spieler initialisieren
func _on_class_selected(character_class: CharacterClass):
	player.character_class = character_class

	# Skills klassenabhängig aufbauen
	player._init_class_skills()
	for i in range(9):
		player._refresh_action_slot(i)

	# Startausrüstung klassenabhängig
	if character_class.resource_type == CharacterClass.ResourceType.MANA:
		player.equip_item(STARTER_STAFF)
	else:
		player.equip_item(STARTER_SWORD)
	player.equip_item(STARTER_CHEST)

	player._calculate_stats()
	player.current_hp = player.max_hp
	player.current_resource = player.max_resource
	player.hud.update_health(player.current_hp, player.max_hp)
	player.hud.update_resource(player.current_resource, player.max_resource, player.get_resource_name())
	print("Klasse gewählt: ", character_class.class_name_de)

	# Jetzt Gegner initialisieren
	var enemy = get_node("Enemy")
	_setup_enemy(enemy)

# Gegner initialisieren und Signal verbinden
func _setup_enemy(enemy):
	if enemy and player:
		enemy.target = player
		if enemy.loot_table == null:
			enemy.loot_table = GOBLIN_LOOT
		enemy.enemy_died.connect(_on_enemy_died)
		enemy.enemy_dropped_loot.connect(_on_enemy_dropped_loot)
	else:
		print("Fehler: Player oder Enemy nicht gefunden!")

# Loot-Drop an Spieler weiterleiten
func _on_enemy_dropped_loot(loot: Dictionary, world_pos: Vector3):
	if player:
		player.receive_loot(loot, world_pos)

# Gegner gestorben: Nach 5 Sekunden respawnen
func _on_enemy_died(spawn_position: Vector3, _xp_reward: int):
	print("Respawn in ", RESPAWN_TIME, " Sekunden...")
	await get_tree().create_timer(RESPAWN_TIME).timeout
	_spawn_enemy(spawn_position)

# Neuen Gegner an Position spawnen
func _spawn_enemy(position: Vector3):
	var new_enemy = ENEMY_SCENE.instantiate()
	add_child(new_enemy)
	new_enemy.global_position = position
	_setup_enemy(new_enemy)
	print("Gegner respawned!")
