extends Area3D

@export var target_group: StringName = &"player"
@export var prompt_text := "Press E to talk"
@export_multiline var dialog_text := ""
@export var auto_popup := false
@export_enum("Every Entry", "Once") var auto_popup_mode := 0
@export var auto_popup_close_on_exit := false

var _has_triggered := false

func _ready() -> void:
	collision_layer = 2
	collision_mask = 1
	body_entered.connect(_on_body_entered)
	body_exited.connect(_on_body_exited)


func _exit_tree() -> void:
	if not auto_popup and DialogSystem:
		DialogSystem.unregister_interactable(self)


func _on_body_entered(body: Node) -> void:
	if not (target_group == StringName() or body.is_in_group(target_group)):
		return
	if auto_popup:
		if DialogSystem and DialogSystem.has_method("is_dialog_open") and DialogSystem.is_dialog_open():
			if not (DialogSystem.has_method("is_dialog_open_from") and DialogSystem.is_dialog_open_from(self)):
				return
		if auto_popup_mode == 1 and _has_triggered:
			return
		_has_triggered = true
		if DialogSystem and auto_popup_close_on_exit and DialogSystem.has_method("show_text_from"):
			DialogSystem.show_text_from(self, dialog_text)
			return
		if DialogSystem and DialogSystem.has_method("show_text"):
			DialogSystem.show_text(dialog_text)
		return
	if DialogSystem:
		DialogSystem.register_interactable(self)


func _on_body_exited(body: Node) -> void:
	if not (target_group == StringName() or body.is_in_group(target_group)):
		return
	if auto_popup:
		if auto_popup_close_on_exit and DialogSystem:
			if DialogSystem.has_method("close_if_source"):
				DialogSystem.close_if_source(self)
			elif DialogSystem.has_method("close_if_text"):
				DialogSystem.close_if_text(dialog_text)
			return
		return
	if target_group == StringName() or body.is_in_group(target_group):
		DialogSystem.unregister_interactable(self)


func get_dialog_prompt() -> String:
	return prompt_text


func get_dialog_text() -> String:
	return dialog_text
