extends Camera3D
@export var player: Node3D

func _ready():
	player = %Player

func _process(delta):
	if player:
		check_line_of_sight_to_player()

func check_line_of_sight_to_player():
	var start_pos = global_position
	var end_pos = player.global_position
	var direction = (end_pos - start_pos).normalized()
	var max_distance = start_pos.distance_to(end_pos)
	
	var space_state = get_world_3d().direct_space_state
	var current_distance = 0.0
	var hit_trees: Array[Node] = []
	
	# Keep casting rays until we reach the player
	while current_distance < max_distance - 0.1:
		var current_start = start_pos + direction * current_distance
		var current_end = end_pos
		
		# Create ray query
		var query = PhysicsRayQueryParameters3D.create(current_start, current_end)
		var result = space_state.intersect_ray(query)
		
		if result.is_empty():
			# No obstacles, clear line of sight
			break
		
		var hit_object = result.collider
		var hit_point = result.position
		var distance_to_hit = current_start.distance_to(hit_point)
		
		# If we hit a tree, add it to the list
		if hit_object.is_in_group("tree_visibility"):
			if hit_object not in hit_trees:
				hit_trees.append(hit_object)
				# Only fade if player is behind the tree
				if is_player_behind_tree(hit_object):
					tree_is_blocking_player(hit_object)
		
		# Move past the hit point for next iteration
		current_distance += distance_to_hit + 0.1
		
		# Safety check to prevent infinite loops
		if distance_to_hit < 0.01:
			current_distance += 0.5

func is_player_behind_tree(tree_object: Node) -> bool:
	var camera_pos = global_position
	var player_pos = player.global_position
	var tree_pos = tree_object.global_position
	
	# Calculate distances from camera
	var camera_to_tree_distance = camera_pos.distance_to(tree_pos)
	var camera_to_player_distance = camera_pos.distance_to(player_pos)
	
	# Tree should be faded if it's closer to camera than player
	# (tree is between camera and player)
	var buffer = 0.2 # Small buffer to avoid flickering
	return camera_to_tree_distance < (camera_to_player_distance - buffer)

func tree_is_blocking_player(tree_object):
	# Fade out the blocking tree
	tree_object.get_parent().fade_out_tree_simple()
