extends Area2D

@onready var bullet = $Bullet

@export var speed = -250
var shader_active = false
var pause = false
var target = null
var stuck: bool = false

@onready var head_splat = preload("res://sprites/head_splat.png")

func start(pos):
    position = pos
    
#func _ready():
  #var target_node = get_parent().get_node("root/$EnemyShard")
  #var target = target_node.is_in_group("shards")
  

func _process(delta):
    if pause == true: return
    position.y += speed * delta
    
    #if target:
      #var direction = (target.position - position).normalized()
      #position += direction * speed * delta
      #
      #if position.distance_to(target.position) < 10:
        #stick_to_target(target)
        
#func stick_to_target(target):
  #target.add_child(bullet)
  #print("Sticking to target!")
  #position = Vector2.ZERO
    #

# Signal checks to see if the bullet leaves the viewport then removes bullet.
func _on_visible_on_screen_notifier_2d_screen_exited() -> void:
  queue_free()

func _on_area_entered(area: Area2D) -> void:
  
  if area.is_in_group("enemies"):
    match area.enemy_type:
          "crt":
            if area.is_in_group("enemies"):
              print("CRT hit!")
              area.hit_detection()
              queue_free()
      
          "shards":
            if stuck == true: return
            if area.is_in_group("shards"):                
              #print("Shards hit!")
              area.hit_detection() 
              # stick_to_target(target)
              reparent(area)
              stuck = true
              $Splat.play()
              $Sprite2D.texture = head_splat
              $Sprite2D.hframes = 1
              position = Vector2.ZERO
              pause = true
              $Sprite2D/GPUParticles2D.hide()
             
              
                    
          "mirror":
            if stuck == true: return
            if area.is_in_group("enemies"):
              print("Mirror hit!")
              area.hit_detection()
              queue_free()
                  
          "chicken":
            if area.is_in_group("enemies"):
                print("Chicken hit!")
                area.hit_detection()
                queue_free()
                
          _:
            if area.is_in_group("enemies"):
              area.hit_detection()
              
              
  if area.is_in_group("heart"):
    print("Heart hit!")
    EventBus.ending.emit(2)
    queue_free()
    #area.hit_detection()
      

#func bullet_fx():
    #shader_active = true
    #bullet.material.set_shader_parameter("toggle", 1.0)
    #pause = true
    #await get_tree().create_timer(1).timeout
    #pause = false
    #shader_active = false
    #bullet.material.set_shader_parameter("toggle", 0.0)
