# main_controller.gd
extends Control

# --- Signals ---
signal workflow_confirmed(final_data: Dictionary)
signal workflow_cancelled()

# --- Exported Variables ---
@export var initial_page_path: NodePath
@export var gamestate_data_key: String

# --- Internal Variables ---
var current_active_page: UIPage = null
var shared_workflow_data: Dictionary = {}

# --- Godot Lifecycle Methods ---
func _ready():
	shared_workflow_data = GameState.get_value(gamestate_data_key)
	for child in get_children():
		if child is UIPage:
			child.hide_page()
			_connect_page_signals(child)
			for sub_child in child.get_children():
				if sub_child is UIPage:
					sub_child.hide_page()
					_connect_page_signals(sub_child)

# --- Public Methods ---
func show_up():
	GameState.pause_game()
	shared_workflow_data = GameState.get_value(gamestate_data_key)
	var original_money = GameState.get_value("money") # 记录初始Money
	shared_workflow_data["original_money"] = int(original_money)
	if not initial_page_path.is_empty():
		var initial_page_node = get_node_or_null(initial_page_path)
		if initial_page_node and initial_page_node is UIPage:
			start_new_workflow(initial_page_node, shared_workflow_data)
		else:
			printerr("Main: Initial page not found or not a UIPage: ", initial_page_path)
	else:
		self.show()

func start_new_workflow(start_page: UIPage, initial_data: Dictionary = {}):
	print("Main: Starting new workflow with page: ", start_page.name, " and data: ", initial_data)
	shared_workflow_data = initial_data.duplicate()

	for child in get_children():
		if child is UIPage and child != start_page:
			child.hide_page()
			for sub_child in child.get_children():
				if sub_child is UIPage:
					sub_child.hide_page()

	_switch_to_page(start_page)
	self.visible = true

func get_shared_data(key: String, default = null):
	return shared_workflow_data.get(key, default)

func set_shared_data(key: String, value):
	shared_workflow_data[key] = value
	print("Main: Shared data updated: ", shared_workflow_data)

# --- Private Helper Methods ---
func _connect_page_signals(page: UIPage):
	if not page.is_connected("navigate_requested", Callable(self, "_on_page_navigate_requested")):
		page.navigate_requested.connect(self._on_page_navigate_requested)
	if not page.is_connected("workflow_end_requested", Callable(self, "_on_page_workflow_end_requested")):
		page.workflow_end_requested.connect(self._on_page_workflow_end_requested)

func _switch_to_page(target_page: UIPage):
	var previous_page = current_active_page

	if previous_page:
		# ... (处理前一页面的隐藏逻辑，包括 hide_on_next 和父页面清理) ...
		# (这部分逻辑不变)
		var should_hide_previous_page = true 
		if previous_page.has_meta("hide_on_next"):
			should_hide_previous_page = previous_page.get_meta("hide_on_next")
		elif previous_page.has_signal("about_to_show"):
			if "hide_on_next" in previous_page:
				should_hide_previous_page = previous_page.hide_on_next
			else:
				printerr("MainController: 'hide_on_next' property not found on previous_page '", previous_page.name, "'. Defaulting to hide.")
		
		if should_hide_previous_page:
			previous_page.hide_page()

		var old_page_parent_path = previous_page.parent_page_node_path
		if not old_page_parent_path.is_empty():
			var old_page_parent_node = previous_page.get_node_or_null(old_page_parent_path) as UIPage
			if old_page_parent_node:
				var target_is_old_parent_itself = (target_page == old_page_parent_node)
				var target_is_sibling_of_previous = false
				var target_parent = target_page.get_parent()
				if target_parent and target_parent == old_page_parent_node:
					target_is_sibling_of_previous = true
				
				if not target_is_old_parent_itself and not target_is_sibling_of_previous:
					old_page_parent_node.hide_page()

	current_active_page = target_page
	current_active_page.show_page() # 调用 UIPage.show_page()，现在它只负责设置 visible = true
	
	# 确保新页面的 _on_page_activated() 被调用，无论它之前是否可见
	current_active_page._on_page_activated() # <--- 关键：MainController 负责调用

	# 确保新当前页面的父页面 (如果它是子页面) 也可见并已激活 (如果需要)
	var new_page_parent_path = current_active_page.parent_page_node_path
	if not new_page_parent_path.is_empty():
		var new_page_parent_node = current_active_page.get_node_or_null(new_page_parent_path) as UIPage
		if new_page_parent_node:
			# 如果父页面之前不可见，则显示并激活它
			if not new_page_parent_node.visible:
				new_page_parent_node.show_page() # 使其可见
				new_page_parent_node._on_page_activated() # 激活它
			else:
				# 如果父页面已经可见 (例如，它从未被隐藏)，
				# 确保其 show_page 至少被调用一次以符合逻辑 (尽管它可能什么都不做)
				new_page_parent_node.show_page() 
	
	print("Main: Switched to page: ", current_active_page.name)

# --- Signal Handlers ---
func _on_page_navigate_requested(target_page_node: Control): # Changed to Control to match signal
	if target_page_node is UIPage:
		_switch_to_page(target_page_node)
	else:
		printerr("Main: Navigation requested to a node that is not a UIPage: ", target_page_node)

func _on_page_workflow_end_requested(is_confirm_and_trigger_action: bool):
	print("Main: Workflow end requested. Confirm and trigger: ", is_confirm_and_trigger_action)
	if is_confirm_and_trigger_action:
		print("Main: Workflow CONFIRMED. Final data: ", shared_workflow_data)
		emit_signal("workflow_confirmed", shared_workflow_data)
	else:
		print("Main: Workflow CANCELLED/BACKED OUT.")
		emit_signal("workflow_cancelled")

	if current_active_page:
		current_active_page.hide_page()
		var parent = current_active_page.get_node_or_null(current_active_page.parent_page_node_path) as UIPage
		if parent:
			parent.hide_page()

	current_active_page = null
	GameState.set_value(gamestate_data_key,shared_workflow_data)
	GameState.set_value("is_on_task",true)
	GameState.resume_game()
	self.hide()
	print("Main: UI Workflow finished and Main hidden.")
