extends Node
# Original texture resources and animation players are retained. Only the matched
# CanvasItem's own drawing is hidden; its child label inherits transform/opacity.
# Victory, yayy (stars), and boil_blast (explosion) are never mapped.
# Candidate remaining-signs-v0.4: source-partitioned room signs and cutout thanks.
# Original credits, Victory and all node visibility/animation triggers are retained.
var mapping = {}
var owner_bindings = {}
var tracked = []
var font = null
var tree_dirty = false
var candidates = []
var candidate_elapsed = 0.0

func _ready():
	var file = File.new()
	if file.open("res://localization/image-text.json", File.READ) != OK:
		return
	var data = {}
	var error = data.parse_json(file.get_as_text())
	file.close()
	if error != OK or not data.has("textures"):
		return
	mapping = data["textures"]
	font = load("res://localization/zh-TW/fonts/cjk-ui-pixel-v0.1/font.tres")
	if font == null:
		return
	if file.open("res://localization/event-owner-bindings.json", File.READ) == OK:
		owner_bindings.parse_json(file.get_as_text())
		file.close()

func _protected(path):
	return path.to_lower().find("victory") != -1 or path == "res://lib/battle/universal/yayy.png" or path == "res://lib/battle/universal/boil_blast.png"

func _route_owner(node, scene, path):
	var ancestor = node
	while ancestor != null:
		if ancestor.get_filename().replace(".tscn.converted.scn", ".tscn") == scene:
			if str(ancestor.get_path_to(node)) == path:
				return ancestor
		ancestor = ancestor.get_parent()
	return null

func _reserve_height(node, height):
	var minimum = node.get_custom_minimum_size()
	node.set_custom_minimum_size(Vector2(minimum.x, max(minimum.y, height)))

func _reserve_stat_text(node, text):
	# Exact stat TextureFrames sit inside source Containers. Reserve the actual
	# CJK width so their original numeric siblings reflow without overlap.
	var minimum = node.get_custom_minimum_size()
	node.set_custom_minimum_size(Vector2(max(minimum.x, ceil(font.get_string_size(text).x)), max(minimum.y, 13)))

func _refresh_hud_geometry(reference):
	var root = reference.get_ref()
	if root == null:
		return
	var parent = root.get_parent()
	# The original Main HUD script sizes and positions this panel from its
	# minimum size, then refreshes its own slide tween. No numeric setter changes.
	if parent != null and parent.has_method("reset_info_box_pos"):
		parent.call("reset_info_box_pos")

func _stat_number_height(node):
	_reserve_height(node, 13)
	if node.is_type("Label"):
		node.set_valign(1)

func _prepare_party_card(card):
	if card.has_meta("zhtw_stats_rows_v02"):
		return
	if not card.has_node("HP Info/Labels/Label") or not card.has_node("BP Info/MarginContainer/Label") or not card.has_node("Lvl Info/Labels/Label"):
		return
	card.set_meta("zhtw_stats_rows_v02", true)
	# Formation has two 128x56 cards with name, HP and level stacked.
	# Its original level y27 must not inherit the main menu's level y0.
	var formation = false
	for i in range(1, 3):
		if _route_owner(card, "res://lib/ui/game_menu/game_menu.tscn", "Position Page/Character Panel/HBoxContainer/Party Member " + str(i)) != null:
			formation = true
			break
	if formation:
		var hp = card.get_node("HP Info")
		hp.set_pos(Vector2(hp.get_pos().x, 17))
		var level = card.get_node("Lvl Info")
		level.set_pos(Vector2(level.get_pos().x, 36))
	elif _route_owner(card, "res://lib/battle/system/leveling_up.tscn", "Center Panel/Party Member") != null:
		# Level-up has no boil row. Keep HP above its Stats List at y41.
		var hp = card.get_node("HP Info")
		hp.set_pos(Vector2(hp.get_pos().x, 13))
		var level = card.get_node("Lvl Info")
		level.set_pos(Vector2(level.get_pos().x, 0))
	else:
		# Existing 48px card: top name/level+EXP; lower HP/boil at y22.
		for path in ["HP Info", "BP Info"]:
			var row = card.get_node(path)
			row.set_pos(Vector2(row.get_pos().x, 22))
		var level = card.get_node("Lvl Info")
		level.set_pos(Vector2(level.get_pos().x, 0))
	# No card size, numeric value, name, slot or progress value is changed.
	var stat_labels = {"HP Info/Labels/Label": "生命", "BP Info/MarginContainer/Label": "沸騰", "Lvl Info/Labels/Label": "等級"}
	for path in stat_labels:
		_reserve_stat_text(card.get_node(path), stat_labels[path])
	for path in ["HP Info/Labels/HP", "HP Info/Labels/Slash", "HP Info/Labels/Max HP", "Lvl Info/Labels/Lvl"]:
		if card.has_node(path):
			_stat_number_height(card.get_node(path))
	# These two source cards use Control/Label for Slash, not a container.
	# Resizing only the Control leaves the child at its old top baseline.
	if card.has_node("HP Info/Labels/Slash/Label"):
		var slash_label = card.get_node("HP Info/Labels/Slash/Label")
		_put_size(slash_label, Vector2(slash_label.get_size().x, 13))
		slash_label.set_valign(1)

func _party_card_for_stat(node, texture_path):
	var relative = ""
	if texture_path == "res://lib/battle/system/hp.png":
		relative = "HP Info/Labels/Label"
	elif texture_path == "res://lib/battle/system/boil.png":
		relative = "BP Info/MarginContainer/Label"
	elif texture_path == "res://lib/ui/game_menu/lvl.png":
		relative = "Lvl Info/Labels/Label"
	else:
		return null
	var owner = _route_owner(node, "res://lib/ui/game_menu/party_member_info.tscn", relative)
	if owner != null:
		return owner
	owner = _route_owner(node, "res://lib/ui/file_menu/Save Slot.tscn", "Button/Save Info/Party Member/" + relative)
	if owner != null:
		return owner.get_node("Button/Save Info/Party Member")
	return null

func _prepare_save_slot_rows(card):
	# The Save Slot has opaque Location/Time panels starting at Save Info y33.
	# Its Party Member extends behind them: the 48px card is NOT free space.
	var slot = _route_owner(card, "res://lib/ui/file_menu/Save Slot.tscn", "Button/Save Info/Party Member")
	if slot == null or card.has_meta("zhtw_save_slot_rows_v04"):
		return
	var info = slot.get_node("Button/Save Info")
	for path in ["Location/PanelContainer", "Time n Money Panel", "Metals Info", "OtherCharacters"]:
		if not info.has_node(path):
			return
	if not card.has_node("Name"):
		return
	card.set_meta("zhtw_save_slot_rows_v04", true)
	var card_pos = card.get_pos()
	var name = card.get_node("Name")
	name.set_pos(Vector2(name.get_pos().x, 2 - card_pos.y))
	for path in ["HP Info", "Lvl Info"]:
		var row = card.get_node(path)
		row.set_pos(Vector2(row.get_pos().x, 14 - card_pos.y))
	card.get_node("BP Info").set_pos(Vector2(224 - card_pos.x, 14 - card_pos.y))
	# Fits even six 16px companions and five 4px gaps before the x312 metals panel.
	info.get_node("OtherCharacters").set_pos(Vector2(190, 0))

func _set_row_pos(node, pos):
	if node.get_pos() != pos:
		node.set_pos(pos)

func _page_is_settled(page):
	# The authored Main Page remains visible while translated to x=-374.
	# Visibility alone incorrectly reapplies Main coordinates on Equip/Skills.
	return page.is_visible() and abs(page.get_pos().x) < 0.1 and abs(page.get_pos().y) < 0.1

func _refresh_levelup_hp_group(card):
	var screen = _route_owner(card, "res://lib/battle/system/leveling_up.tscn", "Center Panel/Party Member")
	if screen == null or not screen.has_node("Center Panel/Stats List/Max Hp/Value"):
		return
	var source = card.get_node("HP Info/Labels/Max HP")
	var group = screen.get_node("Center Panel/Stats List/Max Hp")
	for path in ["Value", "Plus", "Added Value", "Arrow", "New Value"]:
		if not group.has_node(path):
			return
	# The native _hp_hack copies the source label's rectangle top before
	# deferred CJK/GridContainer layout. Keep its five-node group on the
	# source numeral's actual centered ink after every container reflow.
	var padding = floor((source.get_size().y - source.get_font("font").get_height()) / 2)
	var shift = source.get_global_pos() + Vector2(0, padding) - group.get_node("Value").get_global_pos()
	if shift == Vector2(0, 0):
		return
	for path in ["Value", "Plus", "Added Value", "Arrow", "New Value"]:
		var node = group.get_node(path)
		node.set_global_pos(node.get_global_pos() + shift)

func _refresh_shared_card_rows(card):
	# Original Move Party/Return All animations reset these same shared nodes.
	# Re-apply only after those transitions stop, only on Main/Item pages.
	var menu = null
	for i in range(1, 4):
		menu = _route_owner(card, "res://lib/ui/game_menu/game_menu.tscn", "ScrollContainer/Characters/Party Slot" + str(i) + "/Party Member")
		if menu != null:
			break
	if menu == null or not menu.has_node("CharactersAnimation") or not menu.has_node("Main Page") or not menu.has_node("Item Page"):
		return
	var animation = menu.get_node("CharactersAnimation")
	if not animation.is_type("AnimationPlayer") or animation.is_playing():
		return
	if _page_is_settled(menu.get_node("Item Page")):
		_set_row_pos(card.get_node("HP Info"), Vector2(57, 12))
		_set_row_pos(card.get_node("BP Info"), Vector2(56, 29))
	elif menu.has_node("Party Page") and _page_is_settled(menu.get_node("Party Page")):
		# Its native compact layout hides boil and the EXP bar, preserving
		# only name, HP and level inside each original 48px party slot.
		_set_row_pos(card.get_node("HP Info"), Vector2(57, 12))
		_set_row_pos(card.get_node("Lvl Info"), Vector2(62, 29))
	elif _page_is_settled(menu.get_node("Main Page")):
		_set_row_pos(card.get_node("HP Info"), Vector2(57, 22))
		_set_row_pos(card.get_node("BP Info"), Vector2(147, 22))
		_set_row_pos(card.get_node("Lvl Info"), Vector2(148, 0))

func _layout_profile(node, texture_path):
	var card = _party_card_for_stat(node, texture_path)
	if card != null:
		_prepare_party_card(card)
		_prepare_save_slot_rows(card)
		return "stats_card_v02"
	if texture_path == "res://lib/ui/game_menu/lvl_cropped.png":
		var tier = _route_owner(node, "res://lib/ui/game_menu/skills_page/TierLevel.tscn", "Lvl")
		if tier != null and tier.has_node("Number"):
			# Compact number + 級 stays in the original 15px header above Skill1.
			# Keep original numeric font/content and all tree/button geometry.
			var number = tier.get_node("Number")
			number.set_pos(Vector2(number.get_pos().x, 3))
			return "skill_lvl_v04"
	if texture_path == "res://lib/ui/game_menu/lvl.png":
		var results = _route_owner(node, "res://lib/battle/system/results_party_member_info_small.tscn", "Lvl Info/Labels/Label")
		if results != null:
			var number = results.get_node("Lvl Info/Labels/Lvl")
			if not number.has_meta("zhtw_result_level_v02"):
				number.set_meta("zhtw_result_level_v02", true)
				number.set_pos(Vector2(number.get_pos().x, 13))
			_reserve_height(node, 13)
			return "result_lvl_v02"
		_reserve_stat_text(node, "等級")
		if node.get_parent().has_node("Lvl"):
			_stat_number_height(node.get_parent().get_node("Lvl"))
		return "container_lvl_v02"
	if texture_path == "res://lib/battle/system/hp.png":
		var hud = _route_owner(node, "res://lib/ui/hud/main_info_box.tscn", "VBox/HP Info/Icon")
		if hud != null:
			var row = hud.get_node("VBox/HP Info")
			if not row.has_meta("zhtw_hp_spacing"):
				row.set_meta("zhtw_hp_spacing", true)
				for name in ["HP", "Slash", "Max HP"]:
					var field = row.get_node(name)
					field.set_pos(field.get_pos() + Vector2(8, 0))
				var minimum = row.get_custom_minimum_size()
				row.set_custom_minimum_size(Vector2(max(minimum.x, 68), minimum.y))
				call_deferred("_refresh_hud_geometry", weakref(hud))
			return "hud_hp"
		if _route_owner(node, "res://lib/ui/game_menu/party_member_info.tscn", "HP Info/Labels/Label") != null or _route_owner(node, "res://lib/ui/file_menu/Save Slot.tscn", "Button/Save Info/Party Member/HP Info/Labels/Label") != null:
			return "compact_hp"
		if _route_owner(node, "res://lib/battle/system/pc_info_fields.tscn", "HP Info/Labels/Label") != null:
			_reserve_stat_text(node, "生命")
			return "container_hp"
	if texture_path == "res://lib/battle/system/boil.png":
		if _route_owner(node, "res://lib/ui/game_menu/party_member_info.tscn", "BP Info/MarginContainer/Label") != null or _route_owner(node, "res://lib/ui/file_menu/Save Slot.tscn", "Button/Save Info/Party Member/BP Info/MarginContainer/Label") != null:
			return "compact_boil"
		if _route_owner(node, "res://lib/battle/system/pc_info_fields.tscn", "BP Info/MarginContainer/Label") != null or _route_owner(node, "res://lib/ui/game_menu/BoilpointMenu.tscn", "CharacterStats/HBoxContainer/BP Info/MarginContainer/Label") != null:
			_reserve_stat_text(node, "沸騰")
			return "container_boil"
	return "center"

func _surface_route_matches(node, texture, profile):
	if not node.is_type("Sprite") or texture.get_width() != profile["source_size"][0] or texture.get_height() != profile["source_size"][1]:
		return false
	var columns = 1
	var rows = 1
	if profile.has("frame_grid"):
		columns = int(profile["frame_grid"][0])
		rows = int(profile["frame_grid"][1])
	if node.get_frame() < 0 or node.get_frame() >= columns * rows or node.get_hframes() != columns or node.get_vframes() != rows or node.is_flipped_h() or node.is_flipped_v():
		return false
	if node.get_item_rect().size != Vector2(texture.get_width() / columns, texture.get_height() / rows):
		return false
	if profile.has("unbound_scene_prefix") and profile["routes"].empty():
		var ancestor = node
		while ancestor != null:
			if ancestor.get_filename().begins_with(profile["unbound_scene_prefix"]):
				return true
			ancestor = ancestor.get_parent()
	for route in profile["routes"]:
		if _route_owner(node, route["scene"], route["node_path"]) != null:
			return true
	return false

func _draw_localized_surface(node_reference, drawing_reference):
	var node = node_reference.get_ref()
	var drawing = drawing_reference.get_ref()
	if node == null or drawing == null:
		return
	var texture = node.get_texture()
	if texture == null or _protected(texture.get_path()) or not mapping.has(texture.get_path()):
		return
	var entry = mapping[texture.get_path()]
	if not entry.has("surface") or not _surface_route_matches(node, texture, entry["surface"]):
		return
	# Canvas draw commands retain a RID, not a Resource reference. Keep this
	# texture alive on the geometry even if the source Sprite drops it between
	# process and render. A redraw clears old commands before this callback;
	# freeing this CanvasItem clears its commands before its metadata is released.
	# Hidden geometry may retain one texture until redraw or node destruction.
	drawing.set_meta("zhtw_surface_texture", texture)
	var profile = entry["surface"]
	var source_offset = Vector2(0, 0)
	if profile.has("frames"):
		var frame = node.get_frame()
		var columns = int(profile["frame_grid"][0])
		var rows = int(profile["frame_grid"][1])
		source_offset = Vector2((frame % columns) * texture.get_width() / columns, int(frame / columns) * texture.get_height() / rows)
		if not profile["frames"].has(str(frame)):
			return
		profile = profile["frames"][str(frame)]
	var rect = node.get_item_rect()
	var tint = node.get_modulate()
	# Original texture areas and replacement colored rectangles are disjoint.
	# Do not draw the complete original texture underneath this partition.
	for region in profile["source_regions"]:
		drawing.draw_texture_rect_region(texture, Rect2(rect.pos + Vector2(region[0], region[1]), Vector2(region[2], region[3])), Rect2(source_offset + Vector2(region[0], region[1]), Vector2(region[2], region[3])), tint)
	for piece in profile["geometry"]:
		var c = profile["palette"][piece[4]]
		drawing.draw_rect(Rect2(rect.pos + Vector2(piece[0], piece[1]), Vector2(piece[2], piece[3])), Color(c[0] * tint.r, c[1] * tint.g, c[2] * tint.b, tint.a))

func _titlecard_route_matches(node, texture, entry):
	if entry.has("exact_routes"):
		var matched = false
		for route in entry["exact_routes"]:
			if _route_owner(node, route["scene"], route["node_path"]) != null:
				matched = true
		if not matched:
			return false
	if entry.has("surface"):
		return _surface_route_matches(node, texture, entry["surface"])
	if not entry.has("titlecard"):
		return true
	var profile = entry["titlecard"]
	if not profile.has("background_mode"):
		return false
	if profile["background_mode"] != "opaque_black" and profile["background_mode"] != "transparent" and profile["background_mode"] != "cutout_black":
		return false
	if (profile["background_mode"] == "opaque_black" or profile["background_mode"] == "cutout_black") and not profile.has("geometry"):
		return false
	if not node.is_type("Sprite") or texture.get_width() != profile["source_size"][0] or texture.get_height() != profile["source_size"][1]:
		return false
	return _route_owner(node, profile["scene"], profile["node_path"]) != null

func _draw_titlecard(node_reference, drawing_reference):
	var node = node_reference.get_ref()
	var drawing = drawing_reference.get_ref()
	if node == null or drawing == null:
		return
	var texture = node.get_texture()
	if texture == null:
		return
	var path = texture.get_path()
	if _protected(path) or not mapping.has(path):
		return
	var entry = mapping[path]
	if not entry.has("titlecard") or not _titlecard_route_matches(node, texture, entry):
		return
	var profile = entry["titlecard"]
	var rect = node.get_item_rect()
	# These opaque-source profiles partition the complete source canvas into
	# disjoint black/white rectangles. Glyphs and underline are already in that
	# partition: no full black underlay or second Label draw may overlap them.
	# Thus each source pixel receives the inherited Sprite alpha exactly once.
	if profile["background_mode"] == "opaque_black" or profile["background_mode"] == "cutout_black":
		for piece in profile["geometry"]:
			var color = Color(0, 0, 0, 1) if piece[4] == 0 else Color(1, 1, 1, 1)
			drawing.draw_rect(Rect2(rect.pos + Vector2(piece[0], piece[1]), Vector2(piece[2], piece[3])), color)

func _hide_item(item):
	var node = item["node"].get_ref()
	var label = item["label"].get_ref()
	if label != null:
		label.hide()
	if item.has("geometry"):
		var geometry = item["geometry"].get_ref()
		if geometry != null:
			geometry.hide()
	if node != null:
		_put_self_opacity(node, item["self_opacity"])

func _consider(reference):
	var node = reference.get_ref()
	if node == null or node.has_meta("zhtw_image_text"):
		return
	var texture = node.get_texture()
	if texture == null:
		return
	var path = texture.get_path()
	if _protected(path) or not mapping.has(path):
		return
	var entry = mapping[path]
	if not _titlecard_route_matches(node, texture, entry):
		return
	node.set_meta("zhtw_image_text", true)
	var geometry = null
	if entry.has("titlecard") or entry.has("surface"):
		geometry = Node2D.new()
		geometry.set_name("ZhTWTitlecardGeometry")
		var draw_method = "_draw_localized_surface" if entry.has("surface") else "_draw_titlecard"
		geometry.connect("draw", self, draw_method, [weakref(node), weakref(geometry)])
		node.add_child(geometry)
		if entry.has("surface"):
			# The source room originally drew before its stool/cardgame children.
			# Keep the replacement in that same draw order.
			node.move_child(geometry, 0)
	var label = Label.new()
	label.set_name("ZhTWImageText")
	label.set_ignore_mouse(true)
	label.set_stop_mouse(false)
	label.set_focus_mode(0)
	label.set_align(1)
	label.set_valign(1)
	label.set_autowrap(false)
	label.set_clip_text(false)
	label.add_font_override("font", font)
	_put_color(label, "font_color_shadow", Color(0.08, 0.06, 0.1, 1.0))
	_put_constant(label, "shadow_offset_x", 1)
	_put_constant(label, "shadow_offset_y", 1)
	node.add_child(label)
	var item = {"node": weakref(node), "label": weakref(label), "self_opacity": node.get_self_opacity(), "texture_path": path, "layout": _layout_profile(node, path)}
	if geometry != null:
		item["geometry"] = weakref(geometry)
	node.set_meta("zhtw_v35_image_item", item)

func _update_item(item):
	var node = item["node"].get_ref()
	var label = item["label"].get_ref()
	if node == null or label == null:
		_hide_item(item)
		return false
	var texture = node.get_texture()
	if texture == null:
		_hide_item(item)
		return true
	var path = texture.get_path()
	if _protected(path) or not mapping.has(path):
		_hide_item(item)
		return true
	var entry = mapping[path]
	if not _titlecard_route_matches(node, texture, entry):
		_hide_item(item)
		return true
	var geometry = null
	if item.has("geometry"):
		geometry = item["geometry"].get_ref()
		if geometry != null and not entry.has("titlecard") and not entry.has("surface"):
			geometry.hide()
	if (entry.has("titlecard") or entry.has("surface")) and geometry == null:
		_hide_item(item)
		return true
	if entry.has("surface"):
		var tint = node.get_modulate()
		var surface_frame = node.get_frame()
		if not item.has("surface_texture") or item["surface_texture"] != texture or not item.has("surface_tint") or item["surface_tint"] != tint or not item.has("surface_frame") or item["surface_frame"] != surface_frame:
			# Dynamic map Sprite can receive a new Texture with the same frame/tint.
			item["surface_texture"] = texture
			item["surface_tint"] = tint
			item["surface_frame"] = surface_frame
			geometry.update()
		_put_opacity(geometry, item["self_opacity"])
		geometry.show()
		label.hide()
		_put_self_opacity(node, 0.0)
		return true
	if item["layout"] == "stats_card_v02":
		var card = _party_card_for_stat(node, path)
		if card != null:
			_refresh_shared_card_rows(card)
			_refresh_levelup_hp_group(card)
	var text = entry["text"]
	var frame = 0
	if node.is_type("Sprite"):
		frame = node.get_frame()
	if entry.has("frames") and entry["frames"].has(str(frame)):
		text = entry["frames"][str(frame)]
	_put_text(label, text)
	var rect = node.get_item_rect()
	if node.is_type("TextureFrame"):
		rect = Rect2(Vector2(0, 0), node.get_size())
	var height = 26 if text.find("\n") != -1 else 13
	var width = max(rect.size.x, font.get_string_size(text.replace("\n", "")).x if height == 13 else 22)
	_put_size(label, Vector2(width, height))
	var pos = Vector2(floor(rect.pos.x + (rect.size.x - width) / 2), floor(rect.pos.y + (rect.size.y - height) / 2))
	if path == item["texture_path"]:
		if item["layout"] == "compact_hp":
			# Actual glyph ink is y=1..9. This fits between the original Name
			# row and HP bar without changing names, numbers or bar geometry.
			pos.y = -3
			_put_constant(label, "shadow_offset_y", 0)
		elif item["layout"] == "compact_boil":
			# Thirteen pixels between the LVL row and the existing bar top.
			pos.y = rect.size.y - height
	if item["layout"] == "stats_card_v02" or item["layout"] == "result_lvl_v02" or item["layout"] == "container_lvl_v02":
		pos = Vector2(0, 0)
		label.set_align(0)
		_put_constant(label, "shadow_offset_x", 0)
		_put_constant(label, "shadow_offset_y", 0)
		_put_color(label, "font_color_shadow", Color(0, 0, 0, 0))
	if item["layout"] == "skill_lvl_v04":
		var tier_number = node.get_parent().get_node("Number")
		_set_row_pos(tier_number, Vector2(tier_number.get_pos().x, 3))
		pos = Vector2(18, 0)
		label.set_align(0)
		_put_size(label, Vector2(12, 13))
		_put_constant(label, "shadow_offset_x", 0)
		_put_constant(label, "shadow_offset_y", 0)
		_put_color(label, "font_color_shadow", Color(0, 0, 0, 0))
	if entry.has("titlecard"):
		var text_rect = entry["titlecard"]["text_rect"]
		pos = rect.pos + Vector2(text_rect[0], text_rect[1])
		_put_size(label, Vector2(text_rect[2], text_rect[3]))
		_put_constant(label, "shadow_offset_x", 0)
		_put_constant(label, "shadow_offset_y", 0)
		# Offset zero still draws a shadow in Godot2. Disable its alpha explicitly.
		_put_color(label, "font_color_shadow", Color(0, 0, 0, 0))
		_put_opacity(geometry, item["self_opacity"])
		geometry.show()
	_put_pos(label, pos)
	if entry.has("color"):
		var c = entry["color"]
		_put_color(label, "font_color", Color(c[0], c[1], c[2], 1.0))
	if entry.has("frame_colors") and entry["frame_colors"].has(str(frame)):
		var frame_color = entry["frame_colors"][str(frame)]
		_put_color(label, "font_color", Color(frame_color[0], frame_color[1], frame_color[2], 1.0))
	if (path == "res://lib/battle/system/boil.png" or path == "res://lib/ui/game_menu/lvl_cropped.png") and node.is_type("TextureFrame"):
		# BP Info's original ProgressBar script controls cyan/white and the
		# warm strobe material. Keep that live state on the replacement glyphs.
		_put_color(label, "font_color", node.get_modulate())
		label.set_use_parent_material(true)
	_put_opacity(label, item["self_opacity"])
	_put_self_opacity(node, 0.0)
	if entry.has("titlecard") and entry["titlecard"]["background_mode"] != "transparent":
		# Keep the owned Label only for metadata/cleanup. The geometry owns its ink.
		label.hide()
	else:
		label.show()
	return true


func _connect_event(node, signal_name, method0, method1, reference):
	for info in node.get_signal_list():
		if info["name"] != signal_name:
			continue
		var argc = info["args"].size()
		var method = method0 if argc == 0 else method1
		if argc > 1:
			return
		if not node.is_connected(signal_name, self, method):
			node.connect(signal_name, self, method, [reference])
		return

func register_owner(owner, expected_scene):
	if owner == null or owner.get_filename().replace(".tscn.converted.scn", ".tscn") != expected_scene:
		return
	if not owner_bindings.has(expected_scene):
		return
	for path in owner_bindings[expected_scene]["images"]:
		if path == "." or owner.has_node(path):
			var node = owner if path == "." else owner.get_node(path)
			_watch_image(node)
	# Native BP ProgressBar handler sets this exact TextureFrame tint/material.
	# Deferred localization observes the original handler's completed result.
	if expected_scene == "res://lib/ui/game_menu/components/BP Info.tscn" and owner.has_node("ProgressBar") and owner.has_node("MarginContainer/Label"):
		_connect_event(owner.get_node("ProgressBar"), "value_changed", "_image_event", "_image_event_arg", weakref(owner.get_node("MarginContainer/Label")))
	# These exact native transitions run in different process modes. Observe both
	# completed results so the Item card receives its existing CJK row positions.
	if expected_scene == "res://lib/ui/game_menu/game_menu.tscn":
		for path in ["CharactersAnimation", "SubPageAnimation"]:
			if owner.has_node(path):
				_connect_event(owner.get_node(path), "finished", "_layout_event", "_layout_event_arg", weakref(owner))
				_connect_event(owner.get_node(path), "animation_finished", "_layout_event", "_layout_event_arg", weakref(owner))

func _watch_image(node):
	if not node.is_type("Sprite") and not node.is_type("TextureFrame"):
		return
	if not node.has_meta("zhtw_v35_image_events"):
		node.set_meta("zhtw_v35_image_events", true)
		for signal_name in ["draw", "texture_changed", "frame_changed", "item_rect_changed", "visibility_changed"]:
			_connect_event(node, signal_name, "_image_event", "_image_event_arg", weakref(node))
	_image_event(weakref(node))

func _image_event_arg(value, reference):
	_image_event(reference)

func _image_event(reference):
	var node = reference.get_ref()
	if node == null or node.has_meta("zhtw_v35_image_queued"):
		return
	node.set_meta("zhtw_v35_image_queued", true)
	call_deferred("_image_apply", reference)

func _image_signature(node):
	var texture = node.get_texture()
	var state = [0 if texture == null else texture.get_instance_ID(), node.get_item_rect(), node.get_self_opacity(), node.is_visible()]
	if node.is_type("Sprite"):
		state.append(node.get_frame())
	else:
		state.append(node.get_size())
	if node.has_method("get_modulate"):
		state.append(node.get_modulate())
	return str(state)

func _image_apply(reference):
	var node = reference.get_ref()
	if node == null:
		return
	node.set_meta("zhtw_v35_image_queued", null)
	var signature = _image_signature(node)
	if node.has_meta("zhtw_v35_image_result") and node.get_meta("zhtw_v35_image_result") == signature:
		return
	_consider(reference)
	if node.has_meta("zhtw_v35_image_item"):
		_update_item(node.get_meta("zhtw_v35_image_item"))
	node.set_meta("zhtw_v35_image_result", _image_signature(node))

func _layout_event_arg(value, reference):
	_layout_event(reference)

func _layout_event(reference):
	var menu = reference.get_ref()
	if menu == null or menu.has_meta("zhtw_v37_layout_queued"):
		return
	menu.set_meta("zhtw_v37_layout_queued", true)
	call_deferred("_layout_apply", reference)

func _layout_apply(reference):
	var menu = reference.get_ref()
	if menu == null:
		return
	menu.set_meta("zhtw_v37_layout_queued", null)
	for i in range(1, 4):
		var path = "ScrollContainer/Characters/Party Slot" + str(i) + "/Party Member"
		if menu.has_node(path):
			_refresh_shared_card_rows(menu.get_node(path))

func _put_text(node, value):
	if node.get_text() != value:
		node.set_text(value)

func _put_pos(node, value):
	if node.get_pos() != value:
		node.set_pos(value)

func _put_size(node, value):
	if node.get_size() != value:
		node.set_size(value)

func _put_color(node, key, value):
	if node.get_color(key) != value:
		node.add_color_override(key, value)

func _put_constant(node, key, value):
	if node.get_constant(key) != value:
		node.add_constant_override(key, value)

func _put_opacity(node, value):
	if node.get_opacity() != value:
		node.set_opacity(value)

func _put_self_opacity(node, value):
	if node.get_self_opacity() != value:
		node.set_self_opacity(value)
