extends CanvasLayer

# Last MAX_LINES deaths, server-relayed via KillFeedManager. Stacked directly
# above ChatBox's history panel (same left column, off-center rather than
# top-dead-center) so both overlays read as one HUD block.

const MAX_LINES := 4
const WIDTH := 460.0  # matches chat/chat_box.gd's HISTORY_W for column alignment
const HEIGHT := 100.0
const MARGIN_X := 16.0
const GAP := 4.0

# chat/chat_box.gd's history panel spans y -210 to -50 off the window's
# bottom edge (anchor_bottom 1.0) -- see that script's _build_ui() for the
# margin/gap math behind those numbers. Stack this panel on top of it using
# the same GAP chat uses internally between its own history and input line.
const CHAT_HISTORY_TOP := -210.0

var _list: RichTextLabel
var _lines: Array[String] = []


func _ready() -> void:
	layer = 5
	_build_ui()
	KillFeedManager.kill_reported.connect(_on_kill_reported)


func _build_ui() -> void:
	var panel := PanelContainer.new()
	var ps := StyleBoxFlat.new()
	ps.bg_color = Color(0.02, 0.03, 0.06, 0.55)
	ps.set_corner_radius_all(6)
	panel.add_theme_stylebox_override("panel", ps)
	panel.mouse_filter = Control.MOUSE_FILTER_IGNORE
	# Same anchor pattern as chat_box.gd/player_list.gd: set every
	# anchor_* as a plain property assignment (not sequential
	# set_anchor_and_offset() calls) to avoid the push_opposite_anchor
	# footgun described in team_select.gd's _place().
	panel.anchor_left = 0.0
	panel.anchor_right = 0.0
	panel.anchor_top = 1.0
	panel.anchor_bottom = 1.0
	panel.offset_left = MARGIN_X
	panel.offset_right = MARGIN_X + WIDTH
	panel.offset_bottom = CHAT_HISTORY_TOP - GAP
	panel.offset_top = panel.offset_bottom - HEIGHT
	add_child(panel)

	_list = RichTextLabel.new()
	_list.bbcode_enabled = true
	_list.scroll_active = false
	_list.mouse_filter = Control.MOUSE_FILTER_IGNORE
	_list.add_theme_font_size_override("normal_font_size", 15)
	_list.set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT)
	_list.offset_left = 8
	_list.offset_top = 4
	_list.offset_right = -8
	_list.offset_bottom = -4
	panel.add_child(_list)


func _on_kill_reported(victim_name: String, victim_race: int, killer_name: String, killer_race: int, is_environment_kill: bool) -> void:
	var victim_text := "[color=#%s]%s[/color]" % [_race_color(victim_race).to_html(false), _escape_bbcode(victim_name)]
	var line: String
	if is_environment_kill:
		line = "%s killed by the environment" % victim_text
	else:
		var killer_text := "[color=#%s]%s[/color]" % [_race_color(killer_race).to_html(false), _escape_bbcode(killer_name)]
		line = "%s killed by %s" % [victim_text, killer_text]

	_lines.append(line)
	if _lines.size() > MAX_LINES:
		_lines.pop_front()
	_list.text = "\n".join(_lines)


func _race_color(race_id: int) -> Color:
	for race in TeamSelect.RACES:
		if race.id == race_id:
			return race.color
	return Color(0.85, 0.87, 0.92)


func _escape_bbcode(s: String) -> String:
	return s.replace("[", "[lb]")
