extends Node2D

@onready var witch = get_node("/root/Game/Witch")
@onready var player = get_node("/root/Game/Player")
var fireball = preload("res://scenes/fireball.tscn")
var throwing_knife = preload("res://scenes/throwing_knive.tscn")
var cauldron
var available_perks: Array[Perk] = []
var fireball_aoe_enabled = false
var throwing_knife_enabled = false
var throwing_knife_cooldown: float = 2.0
var _knife_timer: float = 0.0

func _ready() -> void:
	cauldron = witch.get_node("CauldronBar")
	var dsh = Perk.new()
	dsh.name = "Double Shuriken"
	dsh.description = "Throw two shurikens instead of one"
	dsh.effect = double_shuriken
	available_perks.append(dsh)
	var faoe = Perk.new()
	faoe.name = "AOE Fireball"
	faoe.description = "Fireballs spawn an explosion on contact"
	faoe.effect = fireball_aoe
	available_perks.append(faoe)
	var bexp = Perk.new()
	bexp.name = "Brew Explosion"
	bexp.description = "The Witch casts an explosion on finishing a brew"
	bexp.effect = brew_explosion
	available_perks.append(bexp)
	var tk = Perk.new()
	tk.name = "Throwing Knife"
	tk.description = "Automatically throw a knife at the nearest enemy every second"
	tk.effect = enable_throwing_knife
	available_perks.append(tk)

func _process(delta: float) -> void:
	if throwing_knife_enabled:
		_knife_timer += delta
		if _knife_timer >= throwing_knife_cooldown:
			_knife_timer = 0.0
			_shoot_throwing_knife()

func double_shuriken():
	witch.shuriken_count = 2

func fireball_aoe():
	fireball_aoe_enabled = true

func brew_explosion():
	cauldron.brew_explosion = true

func enable_throwing_knife():
	throwing_knife_enabled = true
	var upg = Perk.new()
	upg.name = "Knife Cooldown"
	upg.description = "Reduce throwing knife cooldown by 0.2s (min 1s)"
	upg.effect = knife_cooldown_upgrade
	available_perks.append(upg)

func knife_cooldown_upgrade():
	throwing_knife_cooldown = maxf(1.0, throwing_knife_cooldown - 0.2)
	if throwing_knife_cooldown > 1.0:
		var upg = Perk.new()
		upg.name = "Knife Cooldown"
		upg.description = "Reduce throwing knife cooldown by 0.2s (min 1s)"
		upg.effect = knife_cooldown_upgrade
		available_perks.append(upg)

func _shoot_throwing_knife() -> void:
	var knife = throwing_knife.instantiate()
	knife.global_position = witch.global_position
	witch.get_parent().add_child(knife)
	
