extends Node

enum Action { WALK = 0, LOOK = 1, TOUCH = 2, TALK = 3, ITEM = 4 }

var current_action: int = Action.WALK:
	set(value):
		current_action = value
		action_changed.emit(value)

signal action_changed(new_action: int)

# Centralized SetPiece hover tracking
var current_scene: Node = null
var hovered_setpieces: Array[SetPiece] = []
var top_hovered_setpiece: SetPiece = null

signal hover_changed(piece: SetPiece)

func get_action_name() -> String:
	match current_action:
		Action.WALK: return "walk"
		Action.LOOK: return "look"
		Action.TOUCH: return "touch"
		Action.TALK: return "talk"
		Action.ITEM: return "item"
	return "walk"

func get_action_enum() -> int:
	return current_action

func set_current_scene(scene: Node) -> void:
	current_scene = scene
	hovered_setpieces.clear()
	top_hovered_setpiece = null

func get_top_hovered_setpiece() -> SetPiece:
	return top_hovered_setpiece

func _process(_delta: float) -> void:
	if not current_scene:
		return
	
	# Use the scene's viewport (SubViewport), not the root viewport,
	# so we get the correct Camera2D and properly account for zoom/position.
	var scene_viewport = current_scene.get_viewport()
	var camera = scene_viewport.get_camera_2d()
	var global_mouse_pos: Vector2
	if camera:
		global_mouse_pos = camera.get_global_mouse_position()
	else:
		global_mouse_pos = scene_viewport.get_mouse_position()
	
	# Find all SetPieces in current scene
	var new_hovered: Array[SetPiece] = []
	for piece in current_scene.find_children("*", "SetPiece", true, false):
		if piece is SetPiece:
			var local_pos = piece.to_local(global_mouse_pos)
			if piece.polygon.size() > 0 and Geometry2D.is_point_in_polygon(local_pos, piece.polygon):
				new_hovered.append(piece)
	
	# Sort by priority (highest first)
	new_hovered.sort_custom(func(a, b): return b.priority < a.priority)
	
	# Check if top piece changed
	var new_top = new_hovered[0] if new_hovered.size() > 0 else null
	if new_top != top_hovered_setpiece:
		top_hovered_setpiece = new_top
		hover_changed.emit(top_hovered_setpiece)
	
	hovered_setpieces = new_hovered
