# ============================================================
# Cross-Timeline Interactions Gym — Controller
# ============================================================
# This script demonstrates GDScript-driven cross-timeline
# interactions: signal handling, timeline chaining, and
# dynamic timeline starting.
# ============================================================
extends Node2D

@export var start_timeline: DialogicTimeline


func _ready() -> void:
	# Connect to Dialogic's signal_event to react to [signal arg=...]
	Dialogic.signal_event.connect(_on_dialogic_signal)

	# Connect to timeline_ended for chaining patterns
	Dialogic.timeline_ended.connect(_on_timeline_ended)

	# Connect to variable changes to watch for demo variables
	Dialogic.VAR.variable_changed.connect(_on_variable_changed)

	# Check if we're returning from the gym09 minigame
	if Dialogic.VAR.Gym.minigame_done:
		print("[Gym Controller] Returning from minigame — starting congrats timeline.")
		Dialogic.VAR.Gym.minigame_done = false
		Dialogic.start("gym09_congrats")
		return

	# Start the hub timeline
	Dialogic.start(start_timeline)

	print("[Gym Controller] Ready. Listening for signals and timeline events.")


#region SIGNAL HANDLING (Pattern 4)

# Called whenever a [signal arg=...] event fires in any timeline
func _on_dialogic_signal(argument: Variant) -> void:
	print("[Gym Controller] Signal received: ", argument)

	if argument is String and argument == "demo_chain":
		# Pattern 4: Signal → GDScript → New Timeline
		# The signal timeline continues running, but we start a new one here.
		# In a real game, you might call end_timeline() first:
		#   Dialogic.end_timeline()
		# For this demo, we let gym_pattern4_signal_chain finish naturally
		# and then start the target timeline when timeline_ended fires.
		print("[Gym Controller] 'demo_chain' signal detected. Will start target timeline after current one ends.")
		# We store the intent and act on timeline_ended
		_pending_signal_target = "gym_pattern4_signal_target"

	elif argument is String and argument == "start_from_code":
		# Example: start a specific timeline on demand
		print("[Gym Controller] Starting timeline from code signal.")
		Dialogic.end_timeline()
		Dialogic.start_timeline("gym_pattern4_signal_target")

	elif argument is String and argument == "start_minigame":
		# Gym 09: Scene switching demo
		# Store the return path so the minigame knows where to come back to
		Dialogic.VAR.Gym.minigame_return = "hub"
		print("[Gym Controller] Signal 'start_minigame' — switching to minigame scene.")
		await get_tree().create_timer(0.3).timeout
		get_tree().change_scene_to_file("res://docs/gyms/gym09_scene_switching/gym09_minigame.tscn")

#endregion


#region TIMELINE CHAINING (Pattern 8 extension)

var _pending_signal_target: String = ""


func _on_timeline_ended() -> void:
	print("[Gym Controller] Timeline ended.")

	# Pattern 4: If we had a pending signal target, start it now
	if not _pending_signal_target.is_empty():
		var target := _pending_signal_target
		_pending_signal_target = ""
		print("[Gym Controller] Starting pending target timeline: ", target)
		# Small delay so the player can see the transition
		await get_tree().create_timer(0.5).timeout
		Dialogic.start_timeline(target)

#endregion


#region VARIABLE WATCHING (for debugging/demo)

func _on_variable_changed(info: Dictionary) -> void:
	# Only log our demo variables to avoid noise
	var demo_vars := ["Gym.demo_flag", "Gym.sub_value", "Gym.player_name",
					  "Gym.time_of_day", "Museum.coins", "Museum.met_merchant", "Museum.player_has_key"]
	if info.variable in demo_vars:
		print("[Gym Controller] Variable changed: ", info.variable, " = ", info.new_value)

#endregion


#region UTILITY: Start a specific pattern from code

# You can call these from the Godot editor's remote scene tree
# or from other autoloads using: GymController.start_pattern_1()

func start_pattern_1() -> void:
	Dialogic.end_timeline()
	Dialogic.start_timeline("gym_pattern1_jump")

func start_pattern_2() -> void:
	Dialogic.end_timeline()
	Dialogic.start_timeline("gym_pattern2_caller", "start")

func start_pattern_5() -> void:
	Dialogic.end_timeline()
	Dialogic.start_timeline("gym_pattern5_choice_jump", "start")

func return_to_hub() -> void:
	Dialogic.end_timeline()
	Dialogic.start_timeline("gym_main", "menu")

#endregion
