class_name EnemyCar
extends Car

@export_file("*.tscn") var clone_path: String = ""
@export var start_y_range: Vector2i = Vector2i(0, 50)
@export var distance_range: Vector2i = Vector2(100, 300)
@export var avalible_cars: Array[int] = []

var _is_clone_spawned: bool = false


func _ready() -> void:
	super()
	global_position.y = randi_range(start_y_range.x, start_y_range.y)
	set_sprite(avalible_cars.pick_random())
	RideManager.get_instance().level_finished.connect(_on_level_finished)


func _physics_process(delta: float) -> void:
	global_position.y += (PlayerManager.get_instance().current_speed - speed) * delta

	if global_position.y > 0 and not _is_clone_spawned:
		var clone: EnemyCar = load(clone_path).instantiate()
		var dist: int = randi_range(distance_range.x, distance_range.y)
		clone.distance_range = distance_range
		clone.speed = speed
		clone.oncoming = oncoming
		clone.avalible_cars = avalible_cars
		clone._start_x = global_position.x
		clone.global_position = global_position
		add_sibling(clone)
		clone.global_position.y = global_position.y - dist
		_is_clone_spawned = true

	if global_position.y > 500.0:
		queue_free()


func _on_skidding() -> void:
	Globals.raw_score += 25.0


func _on_level_finished() -> void:
	if not oncoming:
		speed = Player.FINISH_SPEED


func kick() -> void:
	global_position.y -= 2.0


func return_to_road() -> void:
	_return_tween = get_tree().create_tween()
	set_car_rotation(1 if global_position.x < _start_x else -1)
	_return_tween.tween_property(self, ^"global_position:x", _start_x, 1.0)
	_return_tween.tween_callback(set_car_rotation.bind(0))
