extends Node3D
# Attach to the ROOT node (DartboardProto).
# Leave `dartboard_root` empty to auto-search, or drag the glb node in.

@export var dartboard_root: Node

var dartboard: MeshInstance3D

func _ready() -> void:
	dartboard = _find_mesh_instance(dartboard_root if dartboard_root else self)
	if dartboard == null:
		push_error("Could not find a MeshInstance3D. Check that the glb is in the scene.")
		return
	print("Found dartboard mesh node: ", dartboard.name)
	_print_surfaces()
	_ensure_collision()

func _find_mesh_instance(node: Node) -> MeshInstance3D:
	if node is MeshInstance3D and node.mesh != null:
		return node
	for child in node.get_children():
		var found := _find_mesh_instance(child)
		if found:
			return found
	return null

func _print_surfaces() -> void:
	var mesh := dartboard.mesh
	print("=== Dartboard surfaces ===")
	for i in mesh.get_surface_count():
		var mat := mesh.surface_get_material(i)
		var mat_name := mat.resource_name if mat else "(no material)"
		print("Surface ", i, "  material name: '", mat_name, "'")
	print("==========================")
	var aabb := dartboard.get_aabb()
	print("Board local size (x,y,z): ", aabb.size)

# CHEAP collision: one box that matches the board's bounding box.
# This replaces create_trimesh_collision(), which was making it run at ~3 FPS
# because it built a collision triangle for every face of the board.
func _ensure_collision() -> void:
	# Remove any existing auto-added body so we don't stack shapes on re-runs.
	for child in dartboard.get_children():
		if child is StaticBody3D and child.name == "AutoBoardBody":
			child.queue_free()

	var body := StaticBody3D.new()
	body.name = "AutoBoardBody"

	var col := CollisionShape3D.new()
	var box := BoxShape3D.new()
	# Match the mesh's bounding box. Use the AABB size directly as the box size.
	var aabb := dartboard.get_aabb()
	box.size = aabb.size
	col.shape = box
	# Center the box on the mesh's bounding-box center (not always the origin).
	col.position = aabb.position + aabb.size * 0.5

	body.add_child(col)
	dartboard.add_child(body)
	print("Created cheap box collision for the dartboard.")
