extends CharacterBody2D

@onready var bullet = preload("res://assets/scenes/enemyBullet.tscn")
#@onready var bullet = preload("res://assets/scenes/enemyBullet.tscn")
@onready var explosionSFX = preload("res://assets/scenes/explosionsfx.tscn")
@onready var explosion = preload("res://assets/scenes/explosion.tscn")

@onready var player = $"../../Player"
@onready var poly = $"Polygon2D"
@onready var animations = $AnimationPlayer
@onready var healthBar = $health
@onready var healthBg = $ColorRect
@onready var nav_agent: NavigationAgent2D = $NavigationAgent2D
@onready var ray:= $RayCast2D
@onready var hitsfx = $hitsfx
@onready var shootsfx = $shootsfx
const RANGE = 400.0

var curShootVal := 1.0
var lock := true
@export var shootDelay := 1.0

var health := 100.0
var maxHealth := 100.0

var wave := 1

var flash := 0.0

var knockback := Vector2.ZERO

var frameData = {}

var transitioning := false
var transitionState = [false, false, false]
var targetState = []

var ticks = 0
var tickToDel = 0

var boomTimer := 0.0

func moveback(seconds):
	if ticks < 5: return
	
	print("lets go")
	targetState = frameData[max(tickToDel, ticks - (int(floor(seconds)) * 20))]
	transitioning = true

func _ready():
	animations.play("spawn")
	
	await get_tree().create_timer(0.7).timeout
	lock = false
	
	call_deferred("actor_setup")

func actor_setup() -> void:
	await get_tree().physics_frame
	if player:
		nav_agent.target_position = player.global_position

func _process(delta: float) -> void:
	healthBar.size.x += ((health / maxHealth) * healthBg.size.x - healthBar.size.x) * 5 * delta

	if health < 0:
		if player:
			
			if Globals.unlockedUpgrades.get("firstAidKit", 0) > 0:
				player.heal(randf_range(3,5))
			else:
				player.heal(randf_range(2,3))
			
		get_node("explode").emitting = true
		get_node("explode").unlock = true
		get_node("explode").reparent(get_parent().get_parent())
		 
		var exlopsion = explosionSFX.instantiate()
		get_parent().get_parent().add_child(exlopsion)
		
		queue_free()

func _physics_process(delta: float) -> void:
	if lock:
		return
		
		
	if transitioning:
		
		position += (targetState[0] - position) * 5 * delta / Engine.time_scale
		rotation += (targetState[1] - rotation) * 5 * delta / Engine.time_scale
		velocity += (targetState[2] - velocity) * 5 * delta / Engine.time_scale
		
		#
		#position = position.round()
		#rotation = round(rotation)
		#velocity = velocity.round()
		
		#print((position - targetState[0]).length(), " ", abs(rotation - targetState[1]), " ", (velocity - targetState[2]).length())
		
		if (position - targetState[0]).length() < 2:
			position = targetState[0]
			transitionState[0] = true
		if abs(rotation - targetState[1]) < 0.05:
			rotation = targetState[1]
			transitionState[1] = true
		if (velocity - targetState[2]).length() < 2:
			velocity = targetState[2]
			transitionState[2] = true
		
		if transitionState.count(true) == len(transitionState):
			transitioning = false
			transitionState = [false, false, false]
			targetState = []
		
		return
	
	var nextpos := nav_agent.get_next_path_position()
	
	ray.rotation += ray.get_angle_to(player.global_position)
	
	var distance = global_position.distance_to(player.global_position)
	ray.target_position.x = min(distance, 400)
	if not ray.is_colliding():
		poly.rotation += poly.get_angle_to(player.global_position) * 5 * delta
		
		velocity.x += (cos(poly.rotation) * 200 - velocity.x) * 5 * delta
		velocity.y += (sin(poly.rotation) * 200 - velocity.y) * 5 * delta
	else:
		var newvel := (nextpos - global_position).normalized() * 200
		poly.rotation += poly.get_angle_to(nextpos) * 5 * delta
		velocity = newvel
			
			#velocity += (newvel - velocity) * 5 * delta
		
		#velocity.x += (cos(rotation) * 200 - velocity.x) * 5 * delta
		#velocity.y += (sin(rotation) * 200 - velocity.y) * 5 * delta

	knockback += -knockback * 5 * delta

	boomTimer += delta
	
	$Polygon2D.modulate.v = boomTimer / 5.0
	
	if boomTimer > 5:
		var instantiated = explosion.instantiate()
		shootsfx.play()
		instantiated.global_position = global_position
		get_parent().get_parent().add_child(instantiated)
		queue_free()

	move_and_collide((velocity + knockback) * delta)
	
	


func _on_new_path() -> void:
	if player:
		nav_agent.target_position = player.global_position - Vector2(16, 16)


func _on_snappie_timeout() -> void:
	frameData[ticks] = [position, rotation, velocity]
	ticks += 1
	
	if ticks > 240:
		frameData.erase(tickToDel)
		tickToDel += 1
