extends Sprite2D

signal bomb_sliced(bomb: Node2D)

# Bomb textures
var bomb_texture = preload("res://assets/images/bomb_small.png")
var explosion_texture = preload("res://assets/images/explosion_small.png")

# Bomb sounds
var fuse_sound = preload("res://assets/sounds/bomb-fuse.wav")
var explode_sound = preload("res://assets/sounds/bomb-explode.wav")

# Movement properties
var velocity = Vector2.ZERO
var gravity = 800.0
var rotation_speed = 0.0
var is_sliced = false

# Fuse audio player reference
var fuse_audio: AudioStreamPlayer

func _ready():
	# Add to BOMB group
	add_to_group("BOMB")
	
	# Set initial texture
	texture = bomb_texture
	
	# Play fuse sound on spawn
	play_fuse_sound()
	
	# Add random rotation
	rotation = randf_range(-PI/4, PI/4)
	rotation_speed = randf_range(-2, 2)
	
	# Set initial velocity (random x, upward y)
	velocity = Vector2(randf_range(-100, 100), -400)

func _process(delta):
	if not is_sliced:
		# Update position based on velocity
		position += velocity * delta
		
		# Apply gravity to velocity
		velocity.y += gravity * delta
		
		# Update rotation
		rotation += rotation_speed * delta
		
		# Remove if off screen
		if position.y > 800:
			queue_free()

func play_fuse_sound():
	fuse_audio = AudioStreamPlayer.new()
	fuse_audio.stream = fuse_sound
	fuse_audio.volume_db = -10
	add_child(fuse_audio)
	fuse_audio.play()

func slice(slash_pos: Vector2):
	if is_sliced:
		return
	
	is_sliced = true
	
	# Stop fuse sound
	if fuse_audio:
		fuse_audio.stop()
	
	# Stop movement
	velocity = Vector2.ZERO
	
	# Emit signal for game over, passing the bomb node
	emit_signal("bomb_sliced", self)

func detonate():
	# Swap texture to explosion
	texture = explosion_texture
	
	# Play explosion sound
	play_explosion_sound()
	
	# Create particle burst at bomb position
	var ParticleBurst = preload("res://scripts/particle_burst.gd")
	ParticleBurst.create_bomb_burst(get_parent(), global_position)

func play_explosion_sound():
	var audio = AudioStreamPlayer.new()
	audio.stream = explode_sound
	audio.volume_db = 0
	add_child(audio)
	audio.play()
	
	# Remove the audio player after sound finishes
	await audio.finished
	audio.queue_free()
