extends Area3D

@export var billboard = true
@onready var sprite: Sprite3D = $UiSprite
@onready var viewport: SubViewport = $UiSprite/SubViewport

func _process(_delta):
	if billboard:
		var camera = get_viewport().get_camera_3d()
		
		var up = (camera.global_position - global_position)
		up = up.cross(Vector3.UP).cross(up)
		
		look_at(global_position - (camera.global_position - global_position), up)

func _unhandled_input(event):
	viewport.push_input(event)

func _on_input_event(_camera: Camera3D, event: InputEvent, pos: Vector3, _normal: Vector3, _shape_idx: int):
	if not State.focus_locked:
		# Position of the event in Sprite3D local coordinates.
		var texture_3d_position = sprite.get_global_transform().affine_inverse() * pos
		#if !is_zero_approx(texture_3d_position.z):
		#    # Discard event because event didn't happen on the side of the Sprite3D.
		#    return
		# Position of the event relative to the texture.
		var texture_position: Vector2 = Vector2(texture_3d_position.x, -texture_3d_position.y) / sprite.pixel_size - sprite.get_item_rect().position
		# Send mouse event.
		var e: InputEvent = event.duplicate()
		if e is InputEventMouse:
			e.set_position(texture_position)
			e.set_global_position(texture_position)
			viewport.push_input(e)

func _on_button_pressed():
	print("Button pressed")

func _on_line_edit_text_submitted(new_text):
	print("Text submitted: ", new_text)
