extends Node3D

@export var player_spawn_position := Vector3(0.0, 0.0, 0.0)
@export var day_length := 120.0
@export var start_light_angle := -90.0

@onready var _player: RigidBody3D = get_node_or_null("Player") as RigidBody3D
@onready var _sun: DirectionalLight3D = $DirectionalLight3D

var _time := 0.0


func _ready() -> void:
	_move_player_to_spawn()


func _process(delta: float) -> void:
	_update_day_night(delta)


func _move_player_to_spawn() -> void:
	if _player == null:
		return
	_player.global_position = player_spawn_position
	_player.linear_velocity = Vector3.ZERO
	_player.angular_velocity = Vector3.ZERO


func _update_day_night(delta: float) -> void:
	if _sun == null or day_length <= 0.0:
		return
	_time = fmod(_time + delta, day_length)
	var t: float = _time / day_length
	var angle: float = lerp(start_light_angle, start_light_angle + 360.0, t)
	_sun.rotation_degrees.x = angle
	var energy_curve: float = -sin((t * TAU) + (start_light_angle * PI / 180.0))
	_sun.light_energy = clamp((energy_curve * 1.0) + 0.2, 0.0, 1.2)
