extends Area3D

@onready var mesh: MeshInstance3D = $Mesh
@onready var label: Label3D = $Label

@export var item_id: StringName = &""
@export var amount: int = 1

var rotation_speed: float = 1.5
var bob: float = 0.0

func _enter_tree() -> void:
  set_multiplayer_authority(1)

func _ready() -> void:
  add_to_group("loot")
  body_entered.connect(_on_body_entered)
  if item_id != &"":
    label.text = "%s x%d" % [str(item_id), amount]
  else:
    label.text = "Loot"

func _process(delta: float) -> void:
  bob += delta
  mesh.rotation.y += rotation_speed * delta
  mesh.position.y = 0.5 + sin(bob * 2.0) * 0.1

func _on_body_entered(body: Node) -> void:
  if not multiplayer.is_server() and multiplayer.multiplayer_peer != null:
    return
  if not body.is_in_group("player"):
    return
  var inv: Node = get_node_or_null("/root/World/Systems/InventorySystem")
  if inv == null:
    inv = get_node_or_null("/root/Dungeon/Systems/InventorySystem")
  if inv and inv.has_method("add_item"):
    inv.add_item(body, item_id, amount)
  EventBus.item_picked_up.emit(body, item_id)
  queue_free()
