extends CharacterBody2D

var speed = 80.0

@onready var player = get_tree().get_first_node_in_group("Player")

@export var damage: int = 1
@export var health: int = 10

var hurt_sprite_time: float = 0.0

@onready var sprite: AnimatedSprite2D = $AnimatedSprite2D

@onready var hitbox_collision: CollisionShape2D = %hitboxCollision

@onready var tileMap = get_tree().get_first_node_in_group("Ground")

@onready var despawn_timer: Timer = $despawnTimer

#Tilespeed
@export_group("Speeds")
@export var grass_speed = 80
@export var high_grass_speed = 60
@export var shallow_water_speed = 60
@export var water_speed = 30
@export var sand_speed = 75
@export var snow_speed = 75

func _physics_process(delta: float) -> void:
	
	_handle_current_tile()

	
	if hurt_sprite_time > 0:
		hurt_sprite_time -= delta
	
	var current_pos: Vector2 = global_position
	
	if current_pos.distance_to(player.global_position) > 400:
		if despawn_timer.is_stopped():
			despawn_timer.start()
	else:
		despawn_timer.stop()
	
	velocity = current_pos.direction_to(player.global_position) * speed
	
	
	if velocity > Vector2(0,0) and hurt_sprite_time <= 0 or velocity < Vector2(0,0) and hurt_sprite_time <= 0:
		sprite.play("move")
	elif hurt_sprite_time <= 0:
		sprite.play("default")
	else:
		sprite.play("hurt")
	
	move_and_slide()

func _handle_current_tile():
	var tile_pos = tileMap.local_to_map(global_position)
	var tile_data = tileMap.get_cell_atlas_coords(tile_pos)
	
	match tile_data:
		Vector2i(0,0): # grass
			speed = grass_speed
		Vector2i(1,0): # high grasss
			speed = high_grass_speed
		Vector2i(2,0): # shallow water
			speed = shallow_water_speed
		Vector2i(3,0): # water
			speed = water_speed
		Vector2i(4,0): # sand
			speed = sand_speed
		Vector2i(5,0): # mountain
			speed = 0
			position.y += 32 # ga met 1 tile omlaag
		Vector2i(6,0): # snow
			speed = snow_speed
			position.y += 32


func _on_hurtbox_area_entered(area: Area2D) -> void:
	if area.is_in_group("Hitbox") and !area.get_parent().is_in_group("enemy"):
		var new_damage = area.get_parent().get_parent().damage
		if new_damage <= 0:
			return
		sprite.play("hurt")
		hurt_sprite_time = 0.2
		health -= new_damage
		if health <= 0:
			hitbox_collision.set_deferred("disabled", true)
			await get_tree().process_frame
			call_deferred("queue_free")


func _on_despawn_timer_timeout() -> void:
	hitbox_collision.set_deferred("disabled", true)
	await get_tree().process_frame
	call_deferred("queue_free")
