extends Control

@export var world_size: float = 200.0
@export var label_text: String = ""
@export var draw_labels: bool = false

func _ready() -> void:
  set_process(false)

func _draw() -> void:
  var view_size: Vector2 = get_size()
  draw_rect(Rect2(Vector2.ZERO, view_size), Color(0.05, 0.05, 0.08, 0.85))
  draw_rect(Rect2(Vector2.ZERO, view_size), Color(0.6, 0.6, 0.6, 0.5), false, 2.0)
  var local: Node = _local_player()
  var center_offset: Vector2 = Vector2.ZERO
  if local:
    center_offset = Vector2((local as Node3D).global_position.x, (local as Node3D).global_position.z)
  var map_sys: Node = get_tree().root.get_node_or_null("World/Systems/MapSystem")
  if map_sys == null:
    return
  for entry in map_sys.get_marker_data():
    var pos: Vector3 = entry.pos
    var px: Vector2 = _to_pixel(Vector2(pos.x, pos.z), view_size, center_offset)
    if px.x < 0 or px.x > view_size.x or px.y < 0 or px.y > view_size.y:
      continue
    draw_circle(px, 3.0, entry.color)
    if draw_labels and entry.label != "":
      var f: Font = ThemeDB.fallback_font
      draw_string(f, px + Vector2(5, -5), entry.label, HORIZONTAL_ALIGNMENT_LEFT, -1, 12, Color.WHITE)

func _to_pixel(world: Vector2, view_size: Vector2, center: Vector2) -> Vector2:
  var rel: Vector2 = world - center
  var s: float = view_size.x / world_size
  return view_size * 0.5 + rel * s

func _local_player() -> Node:
  for p in get_tree().get_nodes_in_group("player"):
    if p.is_multiplayer_authority():
      return p
  return null
