class_name InteractIndicator extends PanelContainer

var _entity:Entity = null

func _enter_tree() -> void:
  UI.interactIndicator = self

func _exit_tree() -> void:
  if UI.interactIndicator == self:
    UI.interactIndicator = null

func _ready() -> void:
  visible = false
  DialogueManager.dialogue_started.connect(_onDialogueStarted)
  DialogueManager.dialogue_ended.connect(_onDialogueEnded)

func setEntity(entity:Entity) -> void:
  if is_instance_valid(_entity):
    _entity.tree_exiting.disconnect(_onEntityExiting)
  _entity = entity
  _entity.tree_exiting.connect(_onEntityExiting)
  visible = _canShow()
  if visible:
    updateWorldPosition()

func clear() -> void:
  if is_instance_valid(_entity):
    _entity.tree_exiting.disconnect(_onEntityExiting)
  _entity = null
  visible = false

func _canShow() -> bool:
  return _entity != null and not UI.dialogueActive

func _onEntityExiting() -> void:
  _entity = null
  visible = false

func _onDialogueStarted(_resource:DialogueResource) -> void:
  visible = false

func _onDialogueEnded(_resource:DialogueResource) -> void:
  visible = _canShow()
  if visible:
    updateWorldPosition()

func updateWorldPosition() -> void:
  var camera:Camera3D = get_viewport().get_camera_3d()
  if camera == null:
    return
  var worldPos:Vector3 = _entity.global_position + Vector3(0, 2.5, 0)
  var screenPos:Vector2 = camera.unproject_position(worldPos)
  var viewportSize:Vector2 = get_viewport().get_visible_rect().size
  position = screenPos - size * 0.5
  position.x = clamp(position.x, 0.0, viewportSize.x - size.x)
  position.y = clamp(position.y, 0.0, viewportSize.y - size.y)
