extends Node3D
## Tower Defense — Lecture 27 (Starter)
##
## Homing projectile; self-destructs on hit or if target freed.

# ============================================================
# CONSTANTS
# ============================================================

const SPEED := 15.0
const MAX_LIFETIME := 5.0

# ============================================================
# STATE
# ============================================================

var target: Node3D = null
var damage: int = 10
var lifetime: float = 0.0

@onready var mesh_instance: MeshInstance3D = $MeshInstance3D

# ============================================================
# LIFECYCLE
# ============================================================

func _ready() -> void:
	# Set projectile color
	var material := StandardMaterial3D.new()
	material.albedo_color = Color.ORANGE
	material.emission_enabled = true
	material.emission = Color.ORANGE
	mesh_instance.set_surface_override_material(0, material)


func _process(delta: float) -> void:
	# === TODO 1: Implement projectile movement and hit detection ===
	# Increment lifetime by delta
	# If lifetime > MAX_LIFETIME: queue_free() and return
	#
	# Check if target is still valid:
	#   If not target or not is_instance_valid(target): queue_free() and return
	#
	# Move toward target:
	#   Calculate direction from global_position to target.global_position
	#   Move: global_position += direction * SPEED * delta
	#
	# Rotate to face target:
	#   look_at(target.global_position, Vector3.UP)
	#
	# Check if close enough to hit:
	#   Calculate distance to target
	#   If distance < 0.5: call _hit_target()
	pass


# ============================================================
# COLLISION
# ============================================================

func _hit_target() -> void:
	if target and target.has_method("take_damage"):
		target.take_damage(damage)
	queue_free()
