extends Node

# Simple chat: F2 opens input, send to all peers, printed to console.

var _input_open: bool = false
var _input_line: LineEdit = null


func _ready() -> void:
	# Build minimal LineEdit for chat input
	_input_line = LineEdit.new()
	_input_line.placeholder_text = "Message... (Entrée pour envoyer, Echap pour annuler)"
	_input_line.custom_minimum_size = Vector2(500, 40)
	_input_line.visible = false
	_input_line.text_submitted.connect(_on_text_submitted)
	add_child(_input_line)

	if not InputMap.has_action("open_chat"):
		InputMap.add_action("open_chat")
		var ev := InputEventKey.new()
		ev.physical_keycode = KEY_F2
		InputMap.action_add_event("open_chat", ev)


func _unhandled_input(event: InputEvent) -> void:
	if event.is_action_pressed("open_chat") and not _input_open:
		_open_chat()
		get_viewport().set_input_as_handled()
	elif _input_open and event.is_action_pressed("escape"):
		_close_chat()
		get_viewport().set_input_as_handled()


func _open_chat() -> void:
	_input_open = true
	_input_line.visible = true
	_input_line.text = ""
	_input_line.grab_focus()
	Input.set_mouse_mode(Input.MOUSE_MODE_VISIBLE)


func _close_chat() -> void:
	_input_open = false
	_input_line.visible = false
	Input.set_mouse_mode(Input.MOUSE_MODE_CAPTURED)


func _on_text_submitted(text: String) -> void:
	if text.strip_edges().length() == 0:
		_close_chat()
		return
	send_chat.rpc(text.strip_edges())
	_close_chat()


@rpc("any_peer", "call_local", "reliable")
func send_chat(msg: String) -> void:
	var sender_id: int = multiplayer.get_remote_sender_id()
	if sender_id == 0:
		sender_id = multiplayer.get_unique_id()
	print("[CHAT][peer %d] %s" % [sender_id, msg])
