extends ColorRect

signal tile_hovered(coords: Vector2i)

@export var tile_size: float = 48.0

var _time: float = 0.0
var _previous_coords := Vector2i(INF, INF)


func _ready() -> void:
	size = Vector2(tile_size, tile_size)
	color = Color(1.0, 1.0, 1.0, 0.25)
	mouse_filter = Control.MOUSE_FILTER_IGNORE


func _process(delta: float) -> void:
	_time += delta
	color.a = 0.25 + 0.1 * sin(_time * 4.0)
	var mouse_pos := get_global_mouse_position()
	var snapped_pos := _snap_to_grid(mouse_pos)
	global_position = snapped_pos
	var coords := Vector2i(snapped_pos / tile_size)
	if coords != _previous_coords:
		_previous_coords = coords
		tile_hovered.emit(coords)


func _notification(what: int) -> void:
	if what == NOTIFICATION_WM_MOUSE_EXIT:
		hide()
	elif what == NOTIFICATION_WM_MOUSE_ENTER:
		show()


func _snap_to_grid(pos: Vector2) -> Vector2:
	return Vector2(floorf(pos.x / tile_size), floorf(pos.y / tile_size)) * tile_size
