extends Node2D

@onready var label : Label = $"label"

func _ready():
	ActionState.hover_changed.connect(_on_hover_changed)

func _on_transitioned(_s):
	$label.hide()
		
# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta):
	#var ideal:Vector2 = $"..".to_local(get_global_mouse_position())
	#var bg = $"..".find_child("bg")
	#var far_point = self.to_global(Vector2(bg.texture.get_width(), bg.texture.get_height() ) * bg.get_global_transform())
	##self.position.x = clamp(ideal.x, 0,  far_point.x - 200)
	#var camera = $"..".find_child("Camera2D")
	#var cam = get_viewport()
	#var z = cam.get_visible_rect()
	#var cam2 = cam.get_camera_2d()
	#cam2.get_screen_transform()
	#self.position.x = clamp(ideal.x, z.position.x, z.end.x - 500)
	#self.position.y = clamp(ideal.y, z.position.y, z.end.y - 50)
	#
	#var viewport = get_viewport()
	#var viewport_size = viewport.get_visible_rect().size
	#
	#var camera_position = cam2.global_position
	#
	#var margin = 10
	## Example positioning: Top-left corner of the viewport
	#var start = Vector2(camera_position.x - viewport_size.x / 2 + margin,  camera_position.y - viewport_size.y / 2 + margin)
	#var end =  start +  viewport_size
	## Here 'margin' is the distance you want to keep from the viewport edge
	#
	#
	##print("ideal", ideal, "start", start, "end", end)
	#print(cam2.get_screen_center_position())
	## Adjust this to keep the label within the viewport bounds
	#global_position = Vector2(clamp(ideal.x, start.x, end.x - 400), clamp(ideal.y, start.y, end.y))
	var viewport = get_viewport_rect()
	var mouse_pos = get_viewport().get_mouse_position()

	# Obtain camera information if camera is used
	var camera = get_viewport().get_camera_2d()
	mouse_pos = camera.get_global_mouse_position()
	if camera:
		# Calculate the screen boundaries considering the camera's position and zoom
		var cam_top_left = camera.get_screen_center_position() - (viewport.size * 0.5 / camera.zoom)
		var cam_bottom_right = camera.get_screen_center_position() + (viewport.size * 0.5 / camera.zoom)

		# Clamp mouse position to camera's visible area
		var margin = 100
		var s = label.size
		mouse_pos.x = clamp(mouse_pos.x, cam_top_left.x + margin, cam_bottom_right.x - label.size.x - margin)
		mouse_pos.y = clamp(mouse_pos.y, cam_top_left.y, cam_bottom_right.y)

 
   # Update label position
	global_position = mouse_pos


func _on_hover_changed(piece: SetPiece) -> void:
	if piece == null:
		$label.hide()
	else:
		$label.show()
		$label.text = piece.label
		var size = label.label_settings.font.get_string_size(piece.label, HORIZONTAL_ALIGNMENT_LEFT, 200, 32)
		label.size = size
