extends Node2D

var last_position = Vector2.ZERO
var min_slash_distance = 10.0
var slash_points = []
var trail_points = []
const MAX_TRAIL_POINTS = 20
const TRAIL_COLOR = Color(0.2, 0.2, 0.2, 0.8)  # Dark gray with high opacity
const TRAIL_WIDTH = 8.0

# Trail effect properties
const TRAIL_COLORS = [
	Color(0.2, 0.2, 0.2, 0.8),  # Dark gray
	Color(0.3, 0.3, 0.3, 0.6),  # Lighter gray
	Color(0.4, 0.4, 0.4, 0.4)   # Even lighter gray
]

# Sound effects
var swipe_sounds = [
	preload("res://assets/sounds/swipe1.wav"),
	preload("res://assets/sounds/swipe2.wav")
]
var is_swiping = false

# Splash textures
var splash_textures = {
	"red": preload("res://assets/images/splash_red_small.png"),
	"yellow": preload("res://assets/images/splash_yellow_small.png"),
	"orange": preload("res://assets/images/splash_orange_small.png")
}

func _ready():
	# Make sure we're on top of everything
	z_index = 100

func _input(event):
	if event is InputEventMouseButton:
		if event.button_index == MOUSE_BUTTON_LEFT:
			if event.pressed:
				# Start new swipe
				is_swiping = true
				play_swipe_sound()
			else:
				# End swipe
				is_swiping = false
				trail_points.clear()
				queue_redraw()
	elif event is InputEventMouseMotion:
		if event.button_mask == MOUSE_BUTTON_MASK_LEFT and is_swiping:
			# Record slash point
			slash_points.append(event.position)
			
			# Add to trail points
			trail_points.append(event.position)
			# Limit the number of points to prevent memory issues
			if trail_points.size() > MAX_TRAIL_POINTS:
				trail_points.pop_front()
			
			# Check for collisions with fruits
			check_slice(event.position)
			
			# Create slash trail effect
			create_slash_trail(event.position)
			
			last_position = event.position
			
			# Request redraw to show the trail
			queue_redraw()

func play_swipe_sound():
	var audio = AudioStreamPlayer.new()
	audio.stream = swipe_sounds[randi() % swipe_sounds.size()]
	audio.volume_db = -10  # Slightly quieter
	add_child(audio)
	audio.play()
	
	# Remove the audio player after sound finishes
	await audio.finished
	audio.queue_free()

func _draw():
	if trail_points.size() > 1:
		# Calculate velocities for each point
		var velocities = []
		for i in range(trail_points.size()):
			if i == 0:
				velocities.append((trail_points[1] - trail_points[0]).length())
			elif i == trail_points.size() - 1:
				velocities.append((trail_points[i] - trail_points[i-1]).length())
			else:
				# Average velocity between previous and next point
				var prev_vel = (trail_points[i] - trail_points[i-1]).length()
				var next_vel = (trail_points[i+1] - trail_points[i]).length()
				velocities.append((prev_vel + next_vel) / 2)
		
		# Find max velocity for normalization
		var max_velocity = velocities.max()
		
		# Draw multiple layers of the trail for a more dynamic effect
		for layer in range(3):
			for i in range(trail_points.size() - 1):
				var start = trail_points[i]
				var end = trail_points[i + 1]
				
				# Calculate alpha based on position in trail
				var alpha = float(i) / trail_points.size()
				var color = TRAIL_COLORS[layer]
				color.a = alpha * (1.0 - float(layer) * 0.2)  # Each layer is slightly more transparent
				
				# Calculate width based on velocity and layer
				var normalized_velocity = velocities[i] / max_velocity
				var base_width = TRAIL_WIDTH * (1.0 + float(layer) * 0.5)
				var velocity_factor = 0.5 + normalized_velocity * 0.5  # Scale between 0.5 and 1.0
				var width = base_width * velocity_factor
				
				# Add taper effect at the start and end
				var taper_factor = 1.0
				if i < 3:  # Start taper
					taper_factor = float(i) / 3.0
				elif i > trail_points.size() - 4:  # End taper
					taper_factor = float(trail_points.size() - i) / 3.0
				
				width *= taper_factor
				
				# Draw line with gradient
				draw_line(start, end, color, width)
				
				# Add a subtle glow effect for the outer layer
				if layer == 2:
					var glow_color = Color(0.5, 0.5, 0.5, alpha * 0.2)
					draw_line(start, end, glow_color, width * 1.5)

func check_slice(pos: Vector2):
	# Get all fruits in the scene
	var fruits = get_tree().get_nodes_in_group("FRUIT")
	
	# Check each fruit for collision
	for fruit in fruits:
		if not fruit.is_sliced:
			# Check if the slash point is near the fruit
			var distance = pos.distance_to(fruit.position)
			if distance < 50:  # Adjust this value to change slice sensitivity
				fruit.slice(pos)  # Pass the slash position
	
	# Check for bomb slices
	var bombs = get_tree().get_nodes_in_group("BOMB")
	for bomb in bombs:
		if not bomb.is_sliced:
			# Check if the slash point is near the bomb
			var distance = pos.distance_to(bomb.position)
			if distance < 50:  # Adjust this value to change slice sensitivity
				bomb.slice(pos)  # Pass the slash position

func create_slash_trail(pos: Vector2):
	# Create a line to show the slash
	var line = Line2D.new()
	line.width = TRAIL_WIDTH
	line.default_color = TRAIL_COLOR
	add_child(line)
	
	# Add points to the line
	if slash_points.size() > 1:
		line.points = slash_points
	
	# Create a more dynamic animation
	var tween = create_tween()
	tween.set_parallel(true)
	
	# Scale up and fade out
	tween.tween_property(line, "scale", Vector2(1.2, 1.2), 0.2)\
		.from(Vector2(1, 1))\
		.set_trans(Tween.TRANS_BOUNCE)\
		.set_ease(Tween.EASE_OUT)
	
	tween.tween_property(line, "modulate:a", 0.0, 0.3)\
		.from(0.8)\
		.set_trans(Tween.TRANS_SINE)
	
	# Add a subtle rotation
	tween.tween_property(line, "rotation", randf_range(-0.1, 0.1), 0.2)\
		.from(0)\
		.set_trans(Tween.TRANS_SINE)
	
	# Remove the line after animation
	tween.tween_callback(line.queue_free)

func create_fruit_splash(pos: Vector2, color: String):
	var splash = Sprite2D.new()
	splash.texture = splash_textures[color]

	# Add to root node (game scene)
	add_child(splash)
	
	# Use the mouse position directly
	splash.global_position = pos
	splash.scale = Vector2(0.5, 0.5)  # Start at normal size
	splash.modulate.a = 1.0
	splash.z_index = 100 
	
	# Animate splash
	var tween = splash.create_tween()
	tween.set_parallel(true)
	
	# Scale up quickly
	tween.tween_property(splash, "scale", Vector2(1.2, 1.2), 0.2)\
		.set_trans(Tween.TRANS_BOUNCE)\
		.set_ease(Tween.EASE_OUT)
	
	# Fade out
	tween.tween_property(splash, "modulate:a", 0.0, 0.4)\
		.set_trans(Tween.TRANS_SINE)
	
	# Add rotation
	tween.tween_property(splash, "rotation", randf_range(-PI/2, PI/2), 0.3)\
		.set_trans(Tween.TRANS_SINE)
	
	# Move up and slightly outward
	var target_pos = splash.global_position + Vector2(randf_range(-10, 10), -30)
	tween.tween_property(splash, "global_position", target_pos, 0.3)\
		.set_trans(Tween.TRANS_SINE)
	
	# Connect to the finished signal to remove the splash when all tweens are done
	tween.finished.connect(func():
		splash.queue_free()
	)
