extends UIPage # 继承自我们之前创建的 UIPage

#-- 配置变量 (可在 Inspector 中调整) --
@export var min_value_per_category: int = 0 # 每个类别的最小值
@export var max_value_per_category: int = 10 # 每个类别的最大值 (对应10个格子)
@export var active_color: Color = Color("05b700")   # 激活格子的颜色
@export var inactive_color: Color = Color("acacac") # 非激活格子的颜色

#-- 内部变量 --
var total_points_from_state: int = 0 # 从get_main_data获取的总点数
var remaining_points: int = 0
# 存储每个类别 (info_1 到 info_6) 当前分配的点数
var category_points: Array[int] = []
# 存储每个类别在 get_main_data 中的键名 ("视觉表现", "游戏深度", ...)
var category_keys: Array[String] = []

# 存储每个类别 UI 元素的引用
var category_controls: Array[Dictionary] = []

#-- 节点引用 --
@onready var points_label: Label = $BG/Part_2/HBoxContainer/Points
@onready var grid_container: GridContainer = $BG/Part_3/GridContainer
@onready var gameplay_info_label: Label = $BG/Part_4/gameplay/info
@onready var theme_info_label: Label = $BG/Part_4/theme/info
@onready var confirm_button: Button = $BG/Confirm

func _ready():
	super._ready() # 调用父类的 _ready() (如果 UIPage 中有 _ready() 逻辑)
	add_to_group(str(name)) # 方便父节点查找

	# --- 初始化控件引用和类别键名 ---
	category_keys.clear()
	category_controls.clear()
	category_points.clear() # 确保清空

	var category_index = 0
	for info_node in grid_container.get_children():
		if not info_node is VBoxContainer:
			continue

		# 获取类别键名 (从 Title Label)
		var title_label = info_node.get_node_or_null("Title")
		if title_label:
			category_keys.append(title_label.text)
		else:
			printerr("Product Focus: Category node '%s' is missing a Title Label!" % info_node.name)
			category_keys.append("未知类别_%d" % category_index) # 占位符

		# 获取并存储控件引用
		var hbox = info_node.get_node("HBoxContainer")
		var prev_button = hbox.get_node("Previous/Button")
		var next_button = hbox.get_node("Next/Button")
		var segments_container = hbox.get_node("Segments")

		var segments_array: Array[ColorRect] = []
		for segment_node in segments_container.get_children():
			if segment_node is ColorRect:
				segments_array.append(segment_node)

		if segments_array.size() != max_value_per_category:
			push_warning("Product Focus: Category '%s' has %d segments, expected %d." % [info_node.name, segments_array.size(), max_value_per_category])

		var controls = {
			"prev_button": prev_button,
			"next_button": next_button,
			"segments": segments_array
		}
		category_controls.append(controls)

		# 连接按钮信号 (确保只连接一次)
		if not prev_button.is_connected("pressed", _on_adjust_points):
			prev_button.pressed.connect(_on_adjust_points.bind(-1, category_index))
		if not next_button.is_connected("pressed", _on_adjust_points):
			next_button.pressed.connect(_on_adjust_points.bind(1, category_index))

		category_index += 1

	# 连接 visibility_changed 信号 (用于界面显示时重置)
	if not is_connected("visibility_changed", _on_visibility_changed):
		visibility_changed.connect(_on_visibility_changed)

	# 连接确认按钮信号
	if confirm_button and not confirm_button.is_connected("pressed", _on_confirm_pressed):
		confirm_button.pressed.connect(_on_confirm_pressed)
	elif not confirm_button:
		printerr("Product Focus: Confirm button node not found!")

	# 初始数据加载和 UI 更新将在 _on_visibility_changed 中处理

# --- 可见性改变处理 ---
func _on_visibility_changed():
	if is_visible_in_tree():
		print("Product Focus: Becoming visible, resetting display.")
		reset_display()
	# else: # 可选：隐藏时清理
	#	 print("Product Focus: Becoming hidden.")

# --- 重置和加载数据 ---
func reset_display():
	if not GameState:
		printerr("Product Focus: GameState not available during reset_display.")
		# 可以考虑禁用界面或显示错误信息
		return

	# 1. 从 GameState 获取 task_development 数据
	#var task_dev_data: Dictionary = GameState.get_value("task_development", {})
	var focus_data: Dictionary = get_main_data("产品侧重点",{})
	if focus_data.is_empty():
		push_warning("Product Focus: 'product_focus_points' not found in task_development data. Using defaults.")
		total_points_from_state = 20 # 使用默认总点数
	else:
		# 从 focus_data 获取总数，如果不存在则使用默认值
		total_points_from_state = focus_data.get("总数", 20)

	# 2. 初始化本地 category_points (从 focus_data 加载)
	category_points.clear()
	var current_total_allocated = 0
	for key in category_keys:
		# 从 focus_data 获取该类别的值，进行类型检查和范围限制
		var value_loaded = focus_data.get(key, min_value_per_category)
		var value: int = min_value_per_category # 默认值

		if typeof(value_loaded) == TYPE_INT:
			value = value_loaded
		elif typeof(value_loaded) == TYPE_FLOAT:
			value = int(value_loaded) # 浮点数转整数
			# push_warning("Product Focus: Loaded float value for key '%s', converting to int." % key)
		# else: # 非数字类型已在上面用默认值处理

		# 确保值在合法范围内
		value = clamp(value, min_value_per_category, max_value_per_category)
		category_points.append(value)
		current_total_allocated += value

	# 3. 计算剩余点数 (修正逻辑)
	# 如果加载的总分配点数超过了总点数（可能由于存档数据或配置问题）
	if current_total_allocated > total_points_from_state:
		push_warning("Product Focus: Loaded allocated points (%d) exceed total points (%d). Resetting points to minimums." % [current_total_allocated, total_points_from_state])
		# 重置所有点数为最小值，并重新计算
		category_points.clear()
		current_total_allocated = 0
		for _i in range(category_keys.size()):
			category_points.append(min_value_per_category)
			current_total_allocated += min_value_per_category
		remaining_points = total_points_from_state - current_total_allocated
	else:
		# 正常计算剩余点数
		remaining_points = total_points_from_state - current_total_allocated

	# 4. 更新 UI
	_update_remaining_points_label()
	_update_all_category_visuals() # 更新所有格子颜色
	_update_all_button_states()    # 更新所有按钮状态
	_load_part4_info()             # 加载玩法和题材信息

# 处理点数调整按钮点击的函数
func _on_adjust_points(delta: int, category_index: int):
	# 检查索引是否有效
	if category_index < 0 or category_index >= category_points.size():
		printerr("Product Focus: Invalid category_index %d in _on_adjust_points" % category_index)
		return

	var current_cat_value = category_points[category_index]
	var new_cat_value = current_cat_value + delta

	# 合法性检查: 是否在单项范围内，是否有足够剩余点数来增加
	if new_cat_value < min_value_per_category or new_cat_value > max_value_per_category:
		return # 超出单项范围
	if delta > 0 and remaining_points <= 0:
		return # 没点数了不能加

	# 更新数据
	category_points[category_index] = new_cat_value
	remaining_points -= delta

	# 更新 UI
	_update_remaining_points_label()
	_update_category_visuals(category_index) # 只更新当前类别的视觉
	_update_all_button_states()          # 更新所有按钮状态（因为剩余点数或单项值变了）

# 更新指定类别的格子颜色
func _update_category_visuals(category_index: int):
	if category_index < 0 or category_index >= category_controls.size():
		printerr("Product Focus: Invalid category_index %d in _update_category_visuals" % category_index)
		return
	if category_index >= category_points.size():
		printerr("Product Focus: category_points array out of bounds for index %d" % category_index)
		return

	var value = category_points[category_index]
	var segments = category_controls[category_index]["segments"]

	for i in range(segments.size()):
		if i < value:
			segments[i].color = active_color
		else:
			segments[i].color = inactive_color

# 更新所有类别的格子颜色
func _update_all_category_visuals():
	for i in range(category_controls.size()):
		_update_category_visuals(i)

# 更新剩余点数标签的文本
func _update_remaining_points_label():
	points_label.text = str(remaining_points)

# 更新所有类别按钮的启用/禁用状态
func _update_all_button_states():
	for i in range(category_controls.size()):
		if i >= category_controls.size() or i >= category_points.size():
			printerr("Product Focus: Index mismatch in _update_all_button_states at index %d" % i)
			continue # 安全检查

		var controls = category_controls[i]
		var value = category_points[i]

		# 更新 "-" 按钮状态: 当前值 > 最小值时启用
		controls["prev_button"].disabled = (value <= min_value_per_category)

		# 更新 "+" 按钮状态: 当前值 < 最大值 且 剩余点数 > 0 时启用
		var can_increment = (value < max_value_per_category) and (remaining_points > 0)
		controls["next_button"].disabled = not can_increment

# 从父节点加载 Part_4 的信息 (玩法和题材)
func _load_part4_info():
	gameplay_info_label.text = get_main_data("玩法", "未知")
	theme_info_label.text = get_main_data("题材", "未知")

# --- 处理确定按钮的逻辑 ---
func _on_confirm_pressed():
	# 1. 构建包含当前侧重点分配的字典
	var confirmed_focus_points: Dictionary = {}
	if category_keys.size() != category_points.size():
		printerr("Product Focus: Mismatch between category_keys and category_points on confirm!")
		# 可以考虑显示错误提示给用户
		return # 阻止继续执行

	for i in range(category_keys.size()):
		confirmed_focus_points[category_keys[i]] = category_points[i]
	confirmed_focus_points['总数'] = total_points_from_state
	set_main_data("产品侧重点", confirmed_focus_points)
	go_next()
