extends UIPage

# References to UI elements
@onready var title_label = $BG/Title/Title
@onready var name_label = $BG/Option/Name
@onready var icon_rect = $BG/Option/Info/Icon
@onready var info1_label = $BG/Option/Info/Info_List_1/Info_1/info # 制造商 (Maker)
@onready var info2_label = $BG/Option/Info/Info_List_1/Info_2/info # 发售 (Sales)
@onready var info3_label = $BG/Option/Info/Info_List_1/Info_3/info # 市场占比 (Market_share)
@onready var info4_label = $BG/Option/Info/Info_List_2/info_4/info # 开发费用 (Cost)
# @onready var info5_label = $BG/Option/Info/Info_List_2/info_5/info # 开发次数 - 暂不处理，数据源未知

@onready var prev_button = $BG/Title/previous/Button
@onready var next_button = $BG/Title/next/Button
@onready var confirm_button = $BG/Confirm

# Internal state
var enabled_platform_keys: Array[String] = [] # Store keys (names) of enabled platforms
var current_platform_index: int = -1       # Index in the enabled_platform_keys array

const PLATFORM_ICON_PATH = "res://UI/popup/task_development/main_plan/platform/"
# --- 新增：用于存储从 GameState 获取的平台数据 ---
var _platforms_data: Dictionary = {}

func _ready():
	super._ready() # 调用父类的 _ready() (如果 UIPage 中有 _ready() 逻辑)
	add_to_group(str(name)) # 保持不变

	# Connect button signals (保持不变)
	if prev_button:
		if not prev_button.pressed.is_connected(_on_previous_pressed):
			prev_button.pressed.connect(_on_previous_pressed)
	if next_button:
		if not next_button.pressed.is_connected(_on_next_pressed):
			next_button.pressed.connect(_on_next_pressed)
	if confirm_button:
		if not confirm_button.pressed.is_connected(_on_confirm_pressed):
			confirm_button.pressed.connect(_on_confirm_pressed)

	# Connect visibility changed signal (保持不变)
	if not is_connected("visibility_changed", _on_visibility_changed):
		visibility_changed.connect(_on_visibility_changed)

	# Initial call if already visible on ready (保持不变)
	if is_visible_in_tree():
		reset_display()


# Visibility Change Handler (保持不变)
func _on_visibility_changed():
	if is_visible_in_tree():
		reset_display()

# 重置显示状态，在窗口可见时调用
func reset_display():
	print("Platform: Resetting display state.")
	# 1. 加载并过滤平台数据
	_load_and_filter_platforms() # 这会更新 _platforms_data 和 enabled_platform_keys

	# 2. 检查是否有可用的平台
	if enabled_platform_keys.is_empty():
		print("Platform: No enabled platforms found during reset.")
		current_platform_index = -1
		_display_current_platform() # 显示 "无可用平台" 状态
		return

	# 3. 获取主任务数据中当前已选择的平台 Key
	#    假设 get_main_data("键名", "默认值") 是 UIPage 基类或全局提供的方法，
	#    用于获取与 task_development.gd 中 task_info["平台"] 对应的值。
	var current_main_task_platform = ""
	if has_method("get_main_data"): # 检查方法是否存在以避免错误
		current_main_task_platform = get_main_data("平台", "")
	else:
		push_error("Platform: 'get_main_data' method not found. Cannot retrieve current platform from main task data.")
		# 作为后备，可以尝试默认第一个，或者保持之前的 GameState 逻辑（如果还需要）
		# 这里我们假设如果 get_main_data 不可用，则无法确定上次选择，行为类似首次打开
		current_main_task_platform = "" # 明确设置为空，将导致默认选中第一个

	# 4. 查找主任务数据中的平台 Key 在当前可用列表中的索引
	if not current_main_task_platform.is_empty():
		var found_index = enabled_platform_keys.find(current_main_task_platform)
		if found_index != -1:
			# 5. 如果找到，并且该平台仍然可用，则更新当前索引
			current_platform_index = found_index
			print("Platform: Defaulting to platform '%s' from main task data (found at index %d)." % [current_main_task_platform, found_index])
		else:
			# 6. 如果在主任务数据中记录的平台 Key 在当前启用的平台列表中找不到
			#    (例如，该平台可能已被禁用或数据不一致)，则默认使用第一个可用的平台。
			print("Platform: Platform '%s' (from main task data) not found in current enabled list. Defaulting to index 0." % current_main_task_platform)
			current_platform_index = 0 # 确保至少有一个有效索引，如果 enabled_platform_keys 不为空
	else:
		# 7. 如果主任务数据中没有记录平台选择 (例如首次配置)，则默认使用第一个可用的平台。
		print("Platform: No platform selection found in main task data for key '平台'. Defaulting to index 0.")
		current_platform_index = 0 # 确保至少有一个有效索引，如果 enabled_platform_keys 不为空

	# 8. 更新显示
	#    (在步骤 2 中，如果 enabled_platform_keys 为空，current_platform_index 会是 -1，_display_current_platform 会处理这种情况)
	_display_current_platform()

# 从 GameState 获取平台数据并筛选出启用的平台
func _load_and_filter_platforms():
	enabled_platform_keys.clear()
	_platforms_data = {} # 清空旧数据

	if not GameState:
		push_error("GameState not available in _load_and_filter_platforms.")
		return

	# --- 修改：从 GameState 获取 task_development 数据 ---
	var task_dev_data = GameState.get_value("task_development", {})
	if task_dev_data.is_empty():
		printerr("Platform: Failed to get 'task_development' data from GameState.")
		return

	# --- 修改：获取 platforms 字典 ---
	var all_platforms = task_dev_data.get("platforms", {})
	if all_platforms.is_empty():
		print("Platform: 'platforms' data in GameState is empty.")
		return

	# --- 修改：将获取到的平台数据存储到内部变量 ---
	_platforms_data = all_platforms

	# 遍历平台数据，筛选出启用的平台 Key
	for platform_key in _platforms_data:
		var platform_info = _platforms_data[platform_key]
		# 确保 platform_info 是字典并且 'enabled' 键存在且为 true
		if typeof(platform_info) == TYPE_DICTIONARY and platform_info.get("enabled", false) == true:
			enabled_platform_keys.append(platform_key)

	# 可选：按键名排序，保持一致性
	#if not enabled_platform_keys.is_empty():
		#enabled_platform_keys.sort() # 简单字符串排序
		## current_platform_index 会在 reset_display 中设置
	#else:
		#print("Platform: No enabled platforms found.")
		#current_platform_index = -1 # 明确设置无可用平台

# 根据 current_platform_index 更新 UI 显示
func _display_current_platform():
	# 处理无可用平台或索引无效的情况
	if current_platform_index < 0 or current_platform_index >= enabled_platform_keys.size():
		title_label.text = "游戏平台"
		name_label.text = "无可用平台"
		if icon_rect: icon_rect.texture = null
		if info1_label: info1_label.text = "-" # Maker
		if info2_label: info2_label.text = "-" # Sales
		if info3_label: info3_label.text = "-" # Market_share
		if info4_label: info4_label.text = "-" # Cost
		if prev_button: prev_button.disabled = true
		if next_button: next_button.disabled = true
		if confirm_button: confirm_button.disabled = true
		return

	# --- 如果有有效平台 ---
	if confirm_button: confirm_button.disabled = false # 启用确认按钮

	# 更新标题
	var display_index = current_platform_index + 1
	var total_count = enabled_platform_keys.size()
	title_label.text = "游戏平台 %d/%d" % [display_index, total_count]

	# 获取当前平台的 Key 和数据
	var platform_key = enabled_platform_keys[current_platform_index]

	# --- 从内部缓存 _platforms_data 获取平台信息 ---
	if not _platforms_data.has(platform_key):
		push_error("Current platform key '%s' not found in cached _platforms_data!" % platform_key)
		name_label.text = "错误：数据丢失"
		# ... 清空其他信息 ...
		return

	var platform_info = _platforms_data[platform_key]

	# 更新平台名称
	name_label.text = platform_key

	# --- 修改：从 platform_info 读取所有需要的信息，数值转为整数显示 ---
	# 使用 .get(key, default) 确保安全访问

	# 制造商 (Maker) - 通常是字符串，保持不变
	info1_label.text = platform_info.get("Maker", "-")

	# 发售 (Sales) - 转换为整数显示
	var sales_value = platform_info.get("Sales", null)
	if typeof(sales_value) == TYPE_INT or typeof(sales_value) == TYPE_FLOAT:
		info2_label.text = str(int(sales_value)) # 转换为整数再转字符串
	else:
		info2_label.text = "-" # 如果不是数字或不存在，显示 "-"

	# 市场占比 (Market_share) - 转换为整数显示
	var market_share_value = platform_info.get("Market_share", null)
	if typeof(market_share_value) == TYPE_INT or typeof(market_share_value) == TYPE_FLOAT:
		info3_label.text = str(int(market_share_value)) # 转换为整数再转字符串
	else:
		info3_label.text = "-"

	# 开发费用 (Cost) - 转换为整数显示
	var cost_value = platform_info.get("Cost", null)
	if typeof(cost_value) == TYPE_INT or typeof(cost_value) == TYPE_FLOAT:
		info4_label.text = str(int(cost_value)) # 转换为整数再转字符串
	else:
		info4_label.text = "-"

	# info5 (开发次数) 暂不处理

	# 更新图标 (逻辑不变)
	var icon_name = platform_info.get("Icon", "")
	if not icon_name.is_empty():
		var icon_path = PLATFORM_ICON_PATH + icon_name + ".png"
		if ResourceLoader.exists(icon_path):
			icon_rect.texture = ResourceLoader.load(icon_path)
		else:
			push_error("Failed to load platform icon: " + icon_path)
			icon_rect.texture = null
	else:
		print("Platform icon name is empty for key: ", platform_key)
		icon_rect.texture = null

	# 更新导航按钮状态 (逻辑不变)
	var can_navigate = enabled_platform_keys.size() > 1
	if prev_button: prev_button.disabled = not can_navigate
	if next_button: next_button.disabled = not can_navigate


# --- _on_previous_pressed (逻辑不变) ---
func _on_previous_pressed():
	if enabled_platform_keys.size() > 1:
		current_platform_index -= 1
		if current_platform_index < 0:
			current_platform_index = enabled_platform_keys.size() - 1
		_display_current_platform()


# --- _on_next_pressed (逻辑不变) ---
func _on_next_pressed():
	if enabled_platform_keys.size() > 1:
		current_platform_index += 1
		if current_platform_index >= enabled_platform_keys.size():
			current_platform_index = 0
		_display_current_platform()


# --- _on_confirm_pressed ---
# 处理确认选择
func _on_confirm_pressed():
	if current_platform_index != -1 and current_platform_index < enabled_platform_keys.size():
		# 1. 获取选中的平台 Key
		var selected_platform_key = enabled_platform_keys[current_platform_index]

		# 2. 获取父节点 (task_development)
		set_main_data("平台", selected_platform_key)
		go_next()
	else:
		# 处理没有有效平台被选中的情况
		print("Platform: No valid platform selected to confirm.")
