extends Node3D

const ROOM_COUNT := 8

var _modifier: int = 0
var _roll_log: RichTextLabel


func _ready() -> void:
	var args := OS.get_cmdline_args() + OS.get_cmdline_user_args()
	if OS.has_feature("dedicated_server") or "--server" in args:
		return
	var role: String = NetworkManager.players.get(NetworkManager.my_id, {}).get("role", "player")
	if role == "dm":
		return  # DM lädt tavern.tscn nur für Top-Down-Ansicht, kein PlayerController
	var room_index := SceneManager.pending_room_index
	_spawn_player(room_index)
	# Kamera-Transform-Broadcast alle 0.1s an DM-Peer
	var timer := Timer.new()
	timer.wait_time = 0.1
	timer.autostart = true
	timer.timeout.connect(_broadcast_camera_transform)
	add_child(timer)
	_setup_dice_ui()


func _get_dm_peer_id() -> int:
	for peer_id in NetworkManager.players.keys():
		if NetworkManager.players[peer_id].get("role", "") == "dm":
			return peer_id
	return 0


func _broadcast_camera_transform() -> void:
	var dm_id := _get_dm_peer_id()
	if dm_id == 0:
		return
	var controller := get_node_or_null("PlayerController") as Node3D
	if controller == null:
		return
	var cam := controller.get_node_or_null("Camera3D") as Camera3D
	var pos: Vector3 = cam.global_position if cam != null else controller.global_position
	var rot: Vector3 = cam.global_rotation if cam != null else controller.global_rotation
	NetworkManager.sync_player_position.rpc_id(dm_id, NetworkManager.my_id, pos, rot)


func _spawn_player(room_index: int) -> void:
	var room_num := (room_index % ROOM_COUNT) + 1  # Zimmer heißen Room1..Room8
	var spawn_path := "UpperFloor/Room%d/SpawnPoint" % room_num
	var spawn := get_node_or_null(spawn_path) as Marker3D
	if spawn == null:
		push_error("[Tavern] SpawnPoint nicht gefunden: %s" % spawn_path)
		return
	var controller := Node3D.new()
	controller.name = "PlayerController"
	var camera := Camera3D.new()
	camera.name = "Camera3D"
	camera.current = true
	controller.add_child(camera)
	add_child(controller)
	controller.global_transform = spawn.global_transform
	print("[Tavern] Spieler gespawnt in %s" % spawn_path)


func _setup_dice_ui() -> void:
	var canvas := CanvasLayer.new()
	canvas.name = "DiceUI"
	add_child(canvas)

	var panel := PanelContainer.new()
	panel.set_anchors_and_offsets_preset(Control.PRESET_BOTTOM_LEFT)
	panel.offset_top = -120
	panel.offset_right = 400
	canvas.add_child(panel)

	var vbox := VBoxContainer.new()
	panel.add_child(vbox)

	_roll_log = RichTextLabel.new()
	_roll_log.custom_minimum_size = Vector2(380, 60)
	_roll_log.bbcode_enabled = true
	vbox.add_child(_roll_log)

	var hbox := HBoxContainer.new()
	vbox.add_child(hbox)

	var roll_btn := Button.new()
	roll_btn.text = "d20 Würfeln"
	roll_btn.pressed.connect(_on_roll_pressed)
	hbox.add_child(roll_btn)

	var mod_label := Label.new()
	mod_label.text = "  Mod:"
	hbox.add_child(mod_label)

	var mod_display := Label.new()
	mod_display.text = "0"
	mod_display.custom_minimum_size = Vector2(30, 0)
	mod_display.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER

	var mod_minus := Button.new()
	mod_minus.text = "-"
	mod_minus.pressed.connect(func() -> void: _modifier -= 1; _update_mod_display(mod_display))
	hbox.add_child(mod_minus)

	hbox.add_child(mod_display)

	var mod_plus := Button.new()
	mod_plus.text = "+"
	mod_plus.pressed.connect(func() -> void: _modifier += 1; _update_mod_display(mod_display))
	hbox.add_child(mod_plus)

	NetworkManager.roll_received.connect(_on_roll_received)


func _update_mod_display(label: Label) -> void:
	label.text = "%+d" % _modifier if _modifier != 0 else "0"


func _on_roll_pressed() -> void:
	var d20 := randi() % 20 + 1
	NetworkManager.broadcast_roll.rpc_id(1, NetworkManager.my_id, d20, _modifier)


func _on_roll_received(roller_peer_id: int, player_name: String, d20_result: int, modifier: int, total: int) -> void:
	var mod_str := " %+d" % modifier if modifier != 0 else ""
	var line := "[b]%s[/b] würfelt %d%s = [b]%d[/b]" % [player_name, d20_result, mod_str, total]
	if d20_result == 20:
		line = "[color=gold]" + line + " ★ NAT 20![/color]"
	elif d20_result == 1:
		line = "[color=red]" + line + " ☠ NAT 1[/color]"
	_roll_log.append_text(line + "\n")
