extends Node2D

# Constants for game configuration
const SPAWN_INTERVAL = 2.0
const MIN_SPAWN_X = 50
const MAX_SPAWN_X = 350
const SPAWN_Y = 700

# Initial velocity ranges
const INITIAL_Y_VELOCITY = -900
const INITIAL_X_VELOCITY_RANGE = Vector2(-10, 10)

# Preload scenes
var Fruit = preload("res://scenes/fruit.tscn")
var Bomb = preload("res://scenes/bomb.tscn")

# Game state
var score = 0
var is_game_active = true
var time = 0.0

# Bomb spawn chance (15%)
const BOMB_SPAWN_CHANCE = 0.15

# Camera shake state
var is_shaking = false
var shake_intensity = 0.0
var camera_original_pos = Vector2.ZERO

func _ready():
	# Start spawning fruits
	spawn_fruit()
	$SpawnTimer.wait_time = SPAWN_INTERVAL
	$SpawnTimer.start()
	
	# Store original camera position
	camera_original_pos = $Camera2D.global_position
	
	# Fade in score label to full opacity
	var tween = create_tween()
	tween.tween_property($ScoreLabel, "modulate:a", 1.0, 0.5)\
		.set_trans(Tween.TRANS_SINE)\
		.set_ease(Tween.EASE_IN_OUT)
	
	# Setup background
	#$Background.texture = preload("res://assets/images/background.png")

func _process(delta):
	if is_game_active:
		time += delta
		#$TimeLabel.text = "Time: %.1f" % time
	
	# Apply camera shake if active
	if is_shaking:
		var shake_offset = Vector2(
			randf_range(-shake_intensity, shake_intensity),
			randf_range(-shake_intensity, shake_intensity)
		)
		$Camera2D.global_position = camera_original_pos + shake_offset

func spawn_fruit():
	if not is_game_active:
		return
	
	# 15% chance to spawn a bomb instead of a fruit
	if randf() < BOMB_SPAWN_CHANCE:
		spawn_bomb()
		return
		
	var fruit = Fruit.instantiate()
	add_child(fruit)
	
	# Connect to the fruit_sliced signal
	fruit.fruit_sliced.connect(_on_fruit_sliced)
	
	# Random spawn position
	var spawn_x = randf_range(MIN_SPAWN_X, MAX_SPAWN_X)
	fruit.position = Vector2(spawn_x, SPAWN_Y)
	
	# Random rotation
	fruit.rotation = randf_range(-PI/4, PI/4)
	fruit.rotation_speed = randf_range(-10, 10)
	
	# Set initial velocity
	fruit.velocity = Vector2(
		randf_range(INITIAL_X_VELOCITY_RANGE.x, INITIAL_X_VELOCITY_RANGE.y),
		INITIAL_Y_VELOCITY
	)
	
	# Scale up animation (keep this tween for visual effect)
	var tween = create_tween()
	tween.tween_property(fruit, "scale", Vector2(1, 1), 0.3)\
		.from(Vector2(0.1, 0.1))\
		.set_trans(Tween.TRANS_BOUNCE)\
		.set_ease(Tween.EASE_OUT)

func spawn_bomb():
	var bomb = Bomb.instantiate()
	add_child(bomb)
	
	# Connect to the bomb_sliced signal
	bomb.bomb_sliced.connect(_on_bomb_sliced)
	
	# Random spawn position
	var spawn_x = randf_range(MIN_SPAWN_X, MAX_SPAWN_X)
	bomb.position = Vector2(spawn_x, SPAWN_Y)
	
	# Random rotation
	bomb.rotation = randf_range(-PI/4, PI/4)
	bomb.rotation_speed = randf_range(-10, 10)
	
	# Set initial velocity
	bomb.velocity = Vector2(
		randf_range(INITIAL_X_VELOCITY_RANGE.x, INITIAL_X_VELOCITY_RANGE.y),
		INITIAL_Y_VELOCITY
	)
	
	# Scale up animation
	var tween = create_tween()
	tween.tween_property(bomb, "scale", Vector2(1, 1), 0.3)\
		.from(Vector2(0.1, 0.1))\
		.set_trans(Tween.TRANS_BOUNCE)\
		.set_ease(Tween.EASE_OUT)

func _on_spawn_timer_timeout():
	spawn_fruit()

func _on_fruit_sliced():
	score += 10
	$ScoreLabel.text = "Score: %d" % score
	
	# Score popup animation with time
	score_popup(get_global_mouse_position())

func _on_bomb_sliced(bomb: Node2D):
	# Game over sequence
	is_game_active = false
	$SpawnTimer.stop()
	
	# Execute the full explosion sequence
	await execute_bomb_sequence(bomb)
	
	# Save final score to global state
	Global.set_score(score)
	
	# Transition to score screen
	get_tree().change_scene_to_file("res://scenes/score_screen.tscn")

func execute_bomb_sequence(bomb: Node2D):
	# T = 0s: Start initial shake and stop bomb movement
	is_shaking = true
	shake_intensity = 8.0
	bomb.is_sliced = true
	
	# T = 0s to 2s: Shoot 5 rays, one every 0.4 seconds
	var ray_count = 5
	var ray_interval = 2.0 / ray_count  # 0.4 seconds
	
	for i in range(ray_count):
		shoot_ray(bomb.global_position)
		await get_tree().create_timer(ray_interval).timeout
	
	# T = 2s: Full detonation
	bomb.detonate()
	shake_intensity = 12.0  # Increase shake for impact
	
	# Wait for explosion to finish playing
	await get_tree().create_timer(0.5).timeout
	
	# T = 2.5s: Stop the camera shake
	is_shaking = false
	$Camera2D.global_position = camera_original_pos
	
	# T = 2.5s to 4.5s: Wait in stillness before transition
	await get_tree().create_timer(2.0).timeout

func shoot_ray(from_pos: Vector2):
	# Create a ray that shoots outward from the bomb center
	var ray = Line2D.new()
	add_child(ray)
	
	# Random direction
	var angle = randf() * TAU  # Full rotation 0 to 2π
	var direction = Vector2(cos(angle), sin(angle))
	
	# Ray properties
	ray.width = 20.0
	ray.default_color = Color.WHITE
	
	# Start with both points at the bomb center
	var start_point = from_pos
	var end_point = from_pos
	
	ray.add_point(start_point)
	ray.add_point(end_point)
	
	# Shoot out animation (0.15 seconds)
	var tween = create_tween()
	var ray_distance = 600.0
	var target_point = from_pos + direction * ray_distance
	
	tween.tween_property(ray, "points", PackedVector2Array([start_point, target_point]), 0.15)\
		.set_trans(Tween.TRANS_LINEAR)
	
	# Fade out animation (runs in parallel)
	var tween2 = create_tween()
	tween2.tween_property(ray, "modulate:a", 0.0, 0.2)\
		.set_trans(Tween.TRANS_SINE)
	
	# Clean up after animation
	tween.finished.connect(func():
		ray.queue_free()
	)

func score_popup(pos: Vector2):
	var popup = Label.new()
	popup.text = "+10"
	popup.add_theme_font_size_override("font_size", 32)
	#popup.add_theme_color_override("font_color", Color(0.2, 0.2, 0.2))
	popup.z_index = 1000
	
	add_child(popup)
		
	popup.global_position = pos
	popup.scale = Vector2(0.1, 0.1)
	popup.modulate.a = 1.0
	
	var tween = popup.create_tween()
	
	tween.tween_property(popup, "scale", Vector2(1.0, 1.0), 1)\
		.set_trans(Tween.TRANS_BOUNCE)\
		.set_ease(Tween.EASE_OUT)
	
	var target_pos = popup.global_position + Vector2(0, -30)
	tween.parallel().tween_property(popup, "global_position", target_pos, 0.5)\
		.set_trans(Tween.TRANS_SINE)
	
	tween.tween_property(popup, "modulate:a", 0.0, 0.4)\
		.set_trans(Tween.TRANS_SINE)
	
	tween.finished.connect(func():
		popup.queue_free()
	) 
