extends CharacterBody2D

const BULLET_SCENE = preload("res://bullet.tscn")

var _fire_cooldown: float = 0.0
var health: int = 0
var _dead: bool = false
var _invincible: bool = false
var _invincible_timer: float = 0.0

func _ready() -> void:
	if GameConfig.player_ship_path.is_empty():
		visible = false
		set_physics_process(false)
		GameConfig.team_selected.connect(_on_team_selected)
	else:
		_init_player()


func _on_team_selected() -> void:
	_init_player()


func _init_player() -> void:
	var sprite := get_node_or_null("Sprite2D")
	if sprite and not GameConfig.player_ship_path.is_empty():
		sprite.texture = load(GameConfig.player_ship_path)
	set_physics_process(true)
	_respawn()

func _physics_process(delta: float) -> void:
	if _dead:
		return

	# 1. INVINCIBILITY BLINK
	if _invincible:
		_invincible_timer -= delta
		modulate.a = 0.3 if int(_invincible_timer * 8) % 2 == 0 else 1.0
		if _invincible_timer <= 0.0:
			_invincible = false
			modulate.a = 1.0

	# 2. ROTATION
	if Input.is_action_pressed("move_right"):
		rotation += GameConfig.ship_rotation_speed * delta
	if Input.is_action_pressed("move_left"):
		rotation -= GameConfig.ship_rotation_speed * delta

	# 3. THRUST
	if Input.is_action_pressed("move_up"):
		velocity += Vector2.UP.rotated(rotation) * GameConfig.ship_thrust * delta
	if Input.is_action_pressed("move_down"):
		velocity += Vector2.DOWN.rotated(rotation) * GameConfig.ship_thrust * delta

	velocity = velocity.limit_length(GameConfig.ship_max_speed)

	move_and_slide()

	# 4. SHOOT
	_fire_cooldown -= delta
	if Input.is_action_pressed("shoot") and _fire_cooldown <= 0.0:
		_fire_cooldown = GameConfig.ship_fire_rate
		var bullet = BULLET_SCENE.instantiate()
		bullet.global_position = global_position + Vector2.UP.rotated(rotation) * 40.0
		bullet.velocity = Vector2.UP.rotated(rotation) * GameConfig.bullet_speed + velocity
		bullet.source = self
		get_parent().add_child(bullet)

	# 5. WALL COLLISION
	var screen = get_viewport_rect().size
	if global_position.x < 0 or global_position.x > screen.x:
		velocity.x = 0
		global_position.x = clamp(global_position.x, 0, screen.x)
		take_damage(GameConfig.ship_wall_damage)
	if global_position.y < 0 or global_position.y > screen.y:
		velocity.y = 0
		global_position.y = clamp(global_position.y, 0, screen.y)
		take_damage(GameConfig.ship_wall_damage)

func take_damage(amount: int) -> void:
	if _invincible or _dead:
		return
	health = max(0, health - amount)
	_update_hud()
	if health == 0:
		_die()

func _die() -> void:
	_dead = true
	visible = false
	velocity = Vector2.ZERO
	await get_tree().create_timer(GameConfig.ship_respawn_delay).timeout
	_respawn()

func _respawn() -> void:
	var screen = get_viewport_rect().size
	global_position = screen / 2.0
	velocity = Vector2.ZERO
	rotation = 0.0
	health = GameConfig.ship_max_health
	_dead = false
	visible = true
	_invincible = true
	_invincible_timer = GameConfig.ship_invincibility_time
	_update_hud()

func _update_hud() -> void:
	var label = get_node_or_null("/root/World/HUD/HealthLabel")
	if label:
		label.text = "HP: %d / %d" % [health, GameConfig.ship_max_health]
