extends CharacterBody3D


@export var SPEED = 5.0
const MOUSE_SENSITIVITY_X = 0.3
const MOUSE_SENSITIVITY_Y = 0.15

const MAX_ROTATION = 85.0
var rotation_x = 0.0

var in_dialogue = false

@export var raycast: RayCast3D

@export var eyes: Node2D

@export var photo_preview: Control

# Get the gravity from the project settings to be synced with RigidBody nodes.
var gravity = ProjectSettings.get_setting("physics/3d/default_gravity")

var enabled = false

func enable():
	Input.set_mouse_mode(Input.MOUSE_MODE_CAPTURED)
	enabled = true

func _input(event):
	if !enabled || DialogueManager.is_dialog_active:
		return
	
	if in_dialogue:
		photo_preview.hide_picture()
		eyes.timer_going = true
		in_dialogue = false
	
	if event is InputEventMouseMotion:
		rotation_degrees.y -= MOUSE_SENSITIVITY_X * event.relative.x
		rotation_x -= MOUSE_SENSITIVITY_Y * event.relative.y
		rotation_x = clamp(rotation_x, -MAX_ROTATION, MAX_ROTATION)
		$Camera3D.rotation_degrees.x = rotation_x

var npc: CharacterBody3D
func _process(delta):
	if !enabled:
		return
	if raycast.is_colliding():
		npc = raycast.get_collider()
		npc.pointing(true)
		if Input.is_action_just_pressed("interact"):
			DialogueManager.start_dialog(raycast.get_collider().get_text())
			
			if raycast.get_collider().is_photo():
				photo_preview.show_picture(raycast.get_collider().get_photo_index())
			
			raycast.get_collider().destroy()
			in_dialogue = true
			eyes.timer_going = false
	elif npc != null:
		npc.pointing(false)
		npc = null

func _physics_process(delta):
	if !enabled:
		return
	# Add the gravity.
	if not is_on_floor():
		velocity.y -= gravity * delta
	
	# Get the input direction and handle the movement/deceleration.
	# As good practice, you should replace UI actions with custom gameplay actions.
	var input_dir = Input.get_vector("move_left", "move_right", "move_forwards", "move_backwards")
	var direction = (transform.basis * Vector3(input_dir.x, 0, input_dir.y)).normalized()
	if direction:
		velocity.x = direction.x * SPEED
		velocity.z = direction.z * SPEED
	else:
		velocity.x = move_toward(velocity.x, 0, SPEED)
		velocity.z = move_toward(velocity.z, 0, SPEED)
	
	if DialogueManager.is_dialog_active:
		velocity = Vector3(0, velocity.y, 0)
	
	move_and_slide()
