extends Node
# Additional Godot 2.1 autoload. Exact display routes; no save/actor/ID mutation.
var options = {}
var overrides_path = "res://localization/display-overrides.json"
var pickup_effect_path = "res://localization/pickup_effect_localization.gd"
var dialogue_text_box_path = "res://localization/dialogue_text_box_localization.gd"
var native_ui_index = {}
var native_ui_repairs = 0
var native_supplement = null
var rules = []
var maps = {}
var tracked = []
var fonts = {}
var elapsed = 0.0
var tree_dirty = false
var prepared_scenes = []

func _ready():
	var file = File.new()
	if file.open(overrides_path, File.READ) != OK:
		print("KOTD_DISPLAY_OVERRIDES_MISSING")
		return
	var parsed = options.parse_json(file.get_as_text())
	file.close()
	if parsed != OK or not options.has("rules") or not options.has("maps"):
		print("KOTD_DISPLAY_OVERRIDES_INVALID")
		return
	rules = options["rules"]
	maps = options["maps"]
	_repair_native_markup(options)
	_install_native_supplement(options)
	_index_native_ui(options)
	_prepare_dialogue_scene()

func _repair_native_markup(data):
	# The compiled dictionary stays immutable. Repair this exact known malformed
	# value in our own Translation resource before original UI scripts parse it.
	if not data.has("native_markup_repairs") or not get_tree().get_root().has_node("ZhTWLocalization"):
		return
	var base = get_tree().get_root().get_node("ZhTWLocalization")
	if base.get_script() == null:
		return
	var language = base.get("language")
	if language == null or not language.is_type("Translation"):
		return
	for repair in data["native_markup_repairs"]:
		if language.get_message(repair["key"]) == repair["expected_old"]:
			language.add_message(repair["key"], repair["replacement"])

func _install_native_supplement(data):
	if not data.has("native_supplement"):
		return
	native_supplement = Translation.new()
	native_supplement.set_locale("zh_TW")
	for key in data["native_supplement"]:
		native_supplement.add_message(key, data["native_supplement"][key])
	TranslationServer.add_translation(native_supplement)

func _repair_rendered_bbcode(node, field):
	# parse_bbcode does not update get_bbcode in Godot 2.1. Match the complete
	# rendered text at this verified description route, then restore source markup.
	if not node.is_type("RichTextLabel"):
		return
	var current = node.get_text()
	if not field["values"].has(current):
		return
	var replacement = field["values"][current]
	if node.has_meta("zhtw_detail_rendered") and node.get_meta("zhtw_detail_rendered") == current:
		return
	var visible = node.get_visible_characters()
	var percent = node.get_percent_visible()
	var scroll = node.get_v_scroll()
	var scroll_value = scroll.get_val()
	_fallback_display(node)
	node.parse_bbcode(replacement)
	node.set_percent_visible(percent)
	node.set_visible_characters(visible)
	scroll.set_val(scroll_value)
	node.set_meta("zhtw_detail_rendered", node.get_text())
	native_ui_repairs += 1

func _index_native_ui(data):
	native_ui_index = {}
	if not data.has("native_ui_rules"):
		return
	for rule in data["native_ui_rules"]:
		var scene = _canonical(rule["scene"])
		var path = _relative(rule["node_path"])
		if not native_ui_index.has(scene):
			native_ui_index[scene] = {}
		native_ui_index[scene][path] = rule

func _native_routes_for(node):
	var found = []
	var ancestor = node
	while ancestor != null:
		var scene = _canonical(ancestor.get_filename())
		if native_ui_index.has(scene):
			var path = _relative(str(ancestor.get_path_to(node)))
			if native_ui_index[scene].has(path):
				found.append(native_ui_index[scene][path])
		ancestor = ancestor.get_parent()
	return found

func _repair_native_ui(node):
	if not node.has_meta("zhtw_native_ui_routes"):
		return
	var selected = {}
	# Outer scene overrides take precedence over an instanced component's defaults.
	for route in node.get_meta("zhtw_native_ui_routes"):
		if not _matches(node, route) or not node.is_type(route["node_type"]):
			continue
		for field in route["fields"]:
			selected[field["property"]] = field
	for property in selected:
		var field = selected[property]
		if property == "rendered_bbcode":
			_repair_rendered_bbcode(node, field)
			continue
		var current = ""
		var button = -1
		if property == "text" and node.has_method("get_text") and node.has_method("set_text"):
			current = node.get_text()
		elif property.begins_with("button/") and node.has_method("get_button_text") and node.has_method("set_button_text") and node.has_method("get_button_count"):
			button = int(property.split("/")[1])
			if button < 0 or button >= node.get_button_count():
				continue
			current = node.get_button_text(button)
		else:
			continue
		# Exact values take priority. Prefix rules exist only on explicitly
		# configured display fields; the suffix remains untouched.
		var replacement = current
		if field["values"].has(current):
			replacement = field["values"][current]
		elif field.has("prefix_rewrites") and property == "text":
			for prefix in field["prefix_rewrites"]:
				var source = prefix["source"]
				if current.begins_with(source):
					replacement = prefix["replacement"] + current.substr(source.length(), current.length() - source.length())
					break
		else:
			continue
		if replacement != current:
			if button >= 0:
				node.set_button_text(button, replacement)
			else:
				node.set_text(replacement)
			native_ui_repairs += 1
			if native_ui_repairs <= 3:
				print("KOTD_UI_CACHE_REPAIR ", native_ui_repairs)
		if button >= 0 and _has_cjk(replacement):
			_fallback_slot(node, "font")
			_fallback_slot(node, "font_selected")

func _prepare_dialogue_scene():
	# 2.1 tree_changed occurs after _ready. Prepare this cached scene's private
	# theme and font variants so its original effect script gets CJK before ready.
	var packed = load("res://lib/core/dialogue/text_box_entry.tscn")
	var body = _localized_font("res://lib/ui/fonts/DUMPIUS_Basic_Dense.tres", true)
	if packed == null or body == null:
		print("KOTD_DIALOGUE_FONT_PREPARE_FAILED")
		return
	var bundle = packed.get("_bundled")
	var variants = bundle["variants"]
	var replacement_variants = []
	var theme_count = 0
	var font_count = 0
	var script_count = 0
	var effect = load(pickup_effect_path)
	if effect == null:
		print("KOTD_PICKUP_EFFECT_LOAD_FAILED")
		return
	for i in range(variants.size()):
		var resource = variants[i]
		replacement_variants.append(resource)
		if typeof(resource) != TYPE_OBJECT or resource == null:
			continue
		if resource.is_type("Theme") and resource.get_path() == "res://lib/ui/common_theme.thm":
			var theme = resource.duplicate()
			theme.set_font("font", "Range", body)
			replacement_variants[i] = theme
			theme_count += 1
		elif resource.is_type("BitmapFont") and resource.get_path() == "res://lib/ui/fonts/DUMPIUS_Basic_Dense.tres":
			replacement_variants[i] = body
			font_count += 1
		elif resource.is_type("GDScript") and (resource.get_path() == "res://lib/core/dialogue/SpecialEffectLabel.gd" or resource.get_path() == "res://lib/core/dialogue/SpecialEffectLabel.gde"):
			replacement_variants[i] = effect
			script_count += 1
	if theme_count != 1 or font_count != 2 or script_count != 1:
		print("KOTD_DIALOGUE_FONT_SOURCE_MISMATCH ", theme_count, " ", font_count, " ", script_count)
		return
	bundle["variants"] = replacement_variants
	packed.set("_bundled", bundle)
	# Keep the prepared resource cached for every future instance. No disk write.
	prepared_scenes.append(packed)
	_prepare_dialogue_text_box(body)

func _prepare_dialogue_text_box(body):
	# Only the framed dialogue component. Other native text_box.gd users retain
	# their own geometry and pagination. Prepare before the original child _ready.
	var packed = load("res://lib/core/dialogue/dialogue_box.tscn")
	var wrapper = load(dialogue_text_box_path)
	var header_font = _localized_font("res://lib/ui/fonts/BATTLEFONT.tres")
	if packed == null or wrapper == null or header_font == null:
		print("KOTD_DIALOGUE_BOX_PREPARE_FAILED")
		return
	var bundle = packed.get("_bundled")
	var variants = bundle["variants"]
	var replacements = []
	var fonts_replaced = 0
	var scripts_replaced = 0
	for i in range(variants.size()):
		var value = variants[i]
		replacements.append(value)
		if typeof(value) != TYPE_OBJECT or value == null:
			continue
		if value.is_type("BitmapFont") and value.get_path() == "res://lib/ui/fonts/DUMPIUS_Basic_Dense.tres":
			replacements[i] = body
			fonts_replaced += 1
		elif value.is_type("BitmapFont") and value.get_path() == "res://lib/ui/fonts/BATTLEFONT.tres":
			replacements[i] = header_font
			fonts_replaced += 1
		elif value.is_type("GDScript") and value.get_path() in ["res://lib/core/dialogue/text_box.gd", "res://lib/core/dialogue/text_box.gde"]:
			replacements[i] = wrapper
			scripts_replaced += 1
	if fonts_replaced != 2 or scripts_replaced != 1:
		print("KOTD_DIALOGUE_BOX_SOURCE_MISMATCH ", fonts_replaced, " ", scripts_replaced)
		return
	bundle["variants"] = replacements
	packed.set("_bundled", bundle)
	prepared_scenes.append(packed)

func _canonical(path):
	return path.replace(".tscn.converted.scn", ".tscn")

func _relative(path):
	if path.begins_with("./"):
		return path.substr(2, path.length() - 2)
	return path

func _matches(node, rule):
	var ancestor = node
	while ancestor != null:
		if _canonical(ancestor.get_filename()) == _canonical(rule["scene"]):
			if _relative(str(ancestor.get_path_to(node))) == _relative(rule["node_path"]):
				return true
		ancestor = ancestor.get_parent()
	return false

func _align_mixed_baseline(font, body):
	# Only private localized copies. Preserve atlas, advances, kerning, line
	# metrics and lowercase descenders. The primary/original resource is untouched.
	var marker = "zhtw_body_baseline_v16" if body else "zhtw_location_baseline_v16"
	if font.has_meta(marker):
		return
	var source_chars = font.get("chars")
	if source_chars.size() % 9 != 0:
		return
	var chars = IntArray()
	for value in source_chars:
		chars.append(value)
	for i in range(0, chars.size(), 9):
		var code = chars[i]
		var shift = 0
		if code >= 48 and code <= 57:
			shift = 3 if body else 2
		elif body and code == 43:
			shift = 2
		elif not body and code in [73, 86, 88, 76, 67, 68, 77]:
			shift = 2
		elif not body and code == 45:
			shift = 1
		if shift == 0:
			continue
		var offset = chars[i + 7] + shift
		if offset < 0 or offset + chars[i + 5] > font.get_height():
			print("KOTD_BASELINE_GLYPH_BOUNDS_FAILED ", code)
			return
		chars[i + 7] = offset
	font.set("chars", chars)
	font.set_meta(marker, true)

func _align_capitals_baseline(font, body):
	# DUMPIUS capitals only, on private CJK font copies. Tiny/battle fonts keep
	# their own metrics. Do not move lowercase descenders or any line/width metric.
	if font.has_meta("zhtw_capitals_baseline_v19"):
		return
	var source_chars = font.get("chars")
	if source_chars.size() % 9 != 0:
		return
	var profile = 0
	for i in range(0, source_chars.size(), 9):
		if source_chars[i] in [77, 80] and source_chars[i + 5] == 10 and source_chars[i + 7] == 0:
			profile += 1
	if profile != 2:
		return
	var shift = 3 if body else 2
	var chars = IntArray()
	for value in source_chars:
		chars.append(value)
	var count = 0
	for i in range(0, chars.size(), 9):
		if chars[i] < 65 or chars[i] > 90:
			continue
		var offset = chars[i + 7] + shift
		if offset < 0 or offset + chars[i + 5] > font.get_height():
			return
		chars[i + 7] = offset
		count += 1
	if count != 26:
		return
	font.set("chars", chars)
	font.set_meta("zhtw_capitals_baseline_v19", true)

func _localized_font(path, body=false, location=false):
	var key = path + ("#body" if body else "#ui") + ("#location-baseline" if location else "")
	if fonts.has(key):
		return fonts[key]
	var original = load(path)
	var fallback_path = "res://localization/zh-TW/fonts/cjk-ui-pixel-v0.1/font.tres"
	if body:
		fallback_path = "res://localization/zh-TW/fonts/cjk-body-pixel-v0.1/font.tres"
	var fallback = load(fallback_path)
	if original == null or fallback == null:
		return null
	var font = original.duplicate()
	font.set("fallback", fallback)
	font.set("height", 14 if body else 13)
	font.set("ascent", 11 if body else 10)
	if body or location:
		_align_mixed_baseline(font, body)
	if body:
		_align_capitals_baseline(font, true)
	font.set_meta("zhtw_metrics_ready", true)
	fonts[key] = font
	return font

func _special(node):
	if not node.is_type("Range"):
		return false
	var script = node.get_script()
	if script == null:
		return false
	var path = script.get_path()
	return path == "res://lib/core/dialogue/SpecialEffectLabel.gd" or path == "res://lib/core/dialogue/SpecialEffectLabel.gde" or path == pickup_effect_path

func _body_font(node):
	if node.has_meta("zhtw_effect_font_ready"):
		return
	node.set_meta("zhtw_effect_font_ready", true)
	var parent = node.get_parent()
	var original = null
	if parent != null and parent.is_type("Label"):
		original = parent.get_font("font")
	if original == null:
		original = load("res://lib/ui/fonts/DUMPIUS_Basic_Dense.tres")
	var fallback = load("res://localization/zh-TW/fonts/cjk-body-pixel-v0.1/font.tres")
	if original == null or fallback == null:
		return
	var key = "effect#" + str(original.get_instance_ID())
	if not fonts.has(key):
		var duplicate = original.duplicate()
		duplicate.set("fallback", fallback)
		duplicate.set("height", 14)
		duplicate.set("ascent", 11)
		if original.has_meta("zhtw_body_baseline_v16"):
			duplicate.set_meta("zhtw_body_baseline_v16", true)
		else:
			_align_mixed_baseline(duplicate, true)
		if original.has_meta("zhtw_capitals_baseline_v19"):
			duplicate.set_meta("zhtw_capitals_baseline_v19", true)
		else:
			_align_capitals_baseline(duplicate, true)
		duplicate.set_meta("zhtw_metrics_ready", true)
		fonts[key] = duplicate
	var font = fonts[key]
	# Canonical dialogue entries already received this font before instancing.
	# This covers existing/noncanonical debug nodes without changing their script.
	node.add_font_override("font", font)
	if parent != null and parent.is_type("Label"):
		parent.add_font_override("font", font)
	node.update()

func _added(node):
	if _special(node):
		_body_font(node)
		return
	var button_array = node.is_type("HButtonArray") or node.is_type("VButtonArray")
	if not node.is_type("Label") and not node.is_type("Button") and not node.is_type("RichTextLabel") and not button_array:
		return
	var native_routes = _native_routes_for(node)
	# Refresh exact route metadata after tree changes, including reparenting.
	node.set_meta("zhtw_native_ui_routes", native_routes)
	if button_array and native_routes.empty():
		return
	if node.has_meta("zhtw_exact_display_tracked"):
		return
	for rule in rules:
		if _matches(node, rule):
			node.set_meta("zhtw_exact_display_tracked", true)
			tracked.append({"node": weakref(node), "rule": rule})
			# Deferred call covers scripts that set initial text in their _ready.
			_watch_display(node, rule)
			return
	# Internal/theme fonts have no external resource path for the base cache.
	# They get a glyph fallback only when their actual translated text is CJK.
	node.set_meta("zhtw_exact_display_tracked", true)
	tracked.append({"node": weakref(node), "rule": null})
	_watch_display(node, null)

func _has_cjk(text):
	for i in range(text.length()):
		var code = text.ord_at(i)
		if (code >= 0x2E80 and code <= 0x9FFF) or (code >= 0xFF00 and code <= 0xFFEF) or code == 0x2026 or code == 0x2014:
			return true
	return false

func _fallback_slot(node, slot):
	var original = node.get_font(slot)
	if original == null or original.has_meta("zhtw_metrics_ready"):
		return
	if original.get_path().begins_with("res://localization/zh-TW/fonts/"):
		return
	if not original.is_type("BitmapFont"):
		return
	var key = "display#" + str(original.get_instance_ID())
	if not fonts.has(key):
		var body = original.get_height() >= 14
		var fallback_path = "res://localization/zh-TW/fonts/cjk-ui-pixel-v0.1/font.tres"
		if body:
			fallback_path = "res://localization/zh-TW/fonts/cjk-body-pixel-v0.1/font.tres"
		var fallback = load(fallback_path)
		if fallback == null:
			return
		var duplicate = original.duplicate()
		duplicate.set("fallback", fallback)
		duplicate.set("height", max(original.get_height(), 14 if body else 13))
		duplicate.set("ascent", max(original.get_ascent(), 11 if body else 10))
		_align_capitals_baseline(duplicate, body)
		duplicate.set_meta("zhtw_metrics_ready", true)
		fonts[key] = duplicate
	node.add_font_override(slot, fonts[key])

func _fallback_display(node):
	if node.is_type("RichTextLabel"):
		for slot in ["normal_font", "bold_font", "italics_font", "bold_italics_font", "mono_font"]:
			_fallback_slot(node, slot)
	else:
		_fallback_slot(node, "font")

func _quest_inline_fonts(node):
	if not node.is_type("RichTextLabel") or not node.is_using_bbcode():
		return
	var route = {"scene": "res://lib/ui/game_menu/Quest Page.tscn", "node_path": "Quest Details/RichTextLabel"}
	if not _matches(node, route):
		return
	var original = node.get_bbcode()
	if not _has_cjk(original):
		return
	_repair_quest_author_header(node)
	# BBCode font items bypass the five theme slots. Only this journal renderer
	# receives these local wrappers; original resources and the text corpus stay intact.
	var paths = {
		"res://lib/ui//fonts/TINYTRASH.tres": "res://localization/zh-TW/fonts/inline/TINYTRASH.zh-TW.tres",
		"res://lib/ui//fonts/DUMPIUS_Basic.tres": "res://localization/zh-TW/fonts/inline/DUMPIUS_Basic.zh-TW.tres",
		"res://lib/ui//fonts/DUMPIUS_Basic_Dense.tres": "res://localization/zh-TW/fonts/inline/DUMPIUS_Basic_Dense.zh-TW.tres",
		# Original Basic_ does not exist: Godot2 originally falls back to normal_font.
		"res://lib/ui//fonts/DUMPIUS_Basic_.tres": "res://localization/zh-TW/fonts/inline/DUMPIUS_Basic.zh-TW.tres"
	}
	var replacement = original
	for source in paths:
		var tag = "[font=" + source + "]"
		if replacement.find(tag) == -1:
			continue
		var target = paths[source]
		var key = "inline#" + target
		if not fonts.has(key):
			fonts[key] = load(target)
		if fonts[key] != null:
			replacement = replacement.replace(tag, "[font=" + target + "]")
	if replacement == original:
		return
	var visible = node.get_visible_characters()
	var percent = node.get_percent_visible()
	var scroll = node.get_v_scroll()
	var scroll_value = scroll.get_val()
	node.set_bbcode(replacement)
	node.set_percent_visible(percent)
	node.set_visible_characters(visible)
	scroll.set_val(scroll_value)

func _repair_quest_author_header(node):
	# Called only after the existing exact Quest Page/RichTextLabel/CJK guards.
	if node.has_meta("zhtw_v38_quest_author_busy") and node.get_meta("zhtw_v38_quest_author_busy"):
		return
	var page = node.get_parent().get_parent()
	if _canonical(page.get_filename()) != "res://lib/ui/game_menu/Quest Page.tscn":
		return
	if not page.has_node("Page Label Panel/Label") or not page.has_node("Panel/Quest List/VBoxContainer"):
		return
	var header = page.get_node("Page Label Panel/Label")
	if not node.has_meta("zhtw_v38_quest_header"):
		node.set_meta("zhtw_v38_quest_header", weakref(header))
	var selected = node.get_focus_owner()
	if selected == node:
		selected = page.get("focused_button")
	if selected == null or selected.get_parent() != page.get_node("Panel/Quest List/VBoxContainer"):
		return
	if _canonical(selected.get_filename()) != "res://lib/ui/game_menu/QuestButton.tscn":
		return
	var info = selected.get("current_quest_info")
	if typeof(info) != TYPE_ARRAY or info.size() < 3 or typeof(info[0]) != TYPE_INT:
		return
	# These IDs originally select an author by an English marker inside the body.
	# ID 43 is separately confirmed by native BY: MUSK and the existing title key.
	var authors = {14: "Walker Jacket's Journal", 30: "Ratavia's Journal", 31: "Ratavia's Journal", 32: "Ratavia's Journal", 33: "Ratavia's Journal", 43: "Musk's Journal", 47: "Ratavia's Journal", 48: "Ratavia's Journal", 49: "Ratavia's Journal", 50: "Ratavia's Journal", 51: "Ratavia's Journal", 54: "Ratavia's Journal"}
	if not authors.has(info[0]):
		return
	var key = authors[info[0]]
	var replacement = tr(key)
	var current = header.get_text()
	if current == replacement or not current in ["Dustin's Journal", tr("Dustin's Journal"), key]:
		return
	node.set_meta("zhtw_v38_quest_author_busy", true)
	header.set_text(replacement)
	node.set_meta("zhtw_v38_quest_author_busy", false)


func _repair_levelup_header(node):
	# Native _char_init builds this sentence without tr(). Only its exact
	# display label is parsed; actor IDs, names and level values remain intact.
	if not node.is_type("Label"):
		return
	var current = node.get_text()
	var delimiter = " reached level "
	var split_at = current.find(delimiter)
	if split_at <= 0:
		return
	if not _matches(node, {"scene": "res://lib/battle/system/leveling_up.tscn", "node_path": "Top Panel/Label"}):
		return
	var level = current.substr(split_at + delimiter.length(), current.length())
	if level.length() == 0:
		return
	for i in range(level.length()):
		if level.ord_at(i) < 48 or level.ord_at(i) > 57:
			return
	var name = current.substr(0, split_at)
	if maps.has("names") and maps["names"].has(name):
		name = maps["names"][name]
	node.set_text(name + "升到了 " + level + " 級！")

func _is_equipment_inventory_name(node):
	if not node.is_type("Button") or _canonical(node.get_filename()) != "res://lib/ui/game_menu/equipment_entry.tscn":
		return false
	var inventory = node.get_parent()
	if inventory == null or inventory.get_script() == null or not inventory.get_script().get_path() in ["res://lib/ui/game_menu/equipment_inventory.gd", "res://lib/ui/game_menu/equipment_inventory.gde"]:
		return false
	var owner = inventory
	for depth in range(4):
		if owner == null:
			return false
		owner = owner.get_parent()
	if owner == null or _canonical(owner.get_filename()) != "res://lib/ui/game_menu/game_menu.tscn":
		return false
	var path = "Equip Page/Inventory/ScrollContainer/Inventory List"
	return owner.has_node(path) and owner.get_node(path) == inventory

func _repair_equipment_roman_baseline(node):
	if not _is_equipment_inventory_name(node):
		return
	# This single observed display value needs two native pixels below Latin I.
	# Other equipment names return to the original font, including reused entries.
	if node.has_meta("zhtw_v39_equipment_font_busy") and node.get_meta("zhtw_v39_equipment_font_busy"):
		return
	var original = node.get_font("font")
	if original == null or not original.is_type("BitmapFont"):
		return
	if node.get_text() != "斬翼劍 II":
		if original.has_meta("zhtw_v39_roman_source"):
			var source = original.get_meta("zhtw_v39_roman_source").get_ref()
			if source != null and node.get_font("font") != source:
				node.set_meta("zhtw_v39_equipment_font_busy", true)
				node.add_font_override("font", source)
				node.set_meta("zhtw_v39_equipment_font_busy", false)
		return
	if original.has_meta("zhtw_v39_roman_source"):
		return
	if original.get_path() != "res://lib/ui/fonts/DUMPIUS_Basic_Dense_noheight.fnt" or original.get_height() != 9 or original.get_ascent() != 9 or node.get_size().y < 14:
		return
	var key = "equipment_roman_v39#" + str(original.get_instance_ID())
	if not fonts.has(key):
		var source_chars = original.get("chars")
		if source_chars.size() % 9 != 0:
			return
		var chars = IntArray()
		var count = 0
		for value in source_chars:
			chars.append(value)
		for index in range(0, chars.size(), 9):
			if chars[index] != 73:
				continue
			if chars[index + 5] != 10 or chars[index + 7] != 0:
				return
			chars[index + 7] = 2
			count += 1
		if count != 1:
			return
		var local = original.duplicate()
		local.set("chars", chars)
		local.set_meta("zhtw_metrics_ready", true)
		local.set_meta("zhtw_v39_roman_source", weakref(original))
		fonts[key] = local
	if node.get_font("font") != fonts[key]:
		node.set_meta("zhtw_v39_equipment_font_busy", true)
		node.add_font_override("font", fonts[key])
		node.set_meta("zhtw_v39_equipment_font_busy", false)


func _refresh_one(reference, rule):
	var node = reference.get_ref()
	if node == null:
		return
	_repair_native_ui(node)
	_repair_levelup_header(node)
	if not node.has_method("get_text"):
		return
	var text = node.get_text()
	if rule != null:
		var key = rule["map"]
		if maps.has(key) and maps[key].has(text):
			var replacement = maps[key][text]
			if replacement != text:
				node.set_text(replacement)
				text = replacement
	if not _has_cjk(tr(text)):
		return
	if rule != null:
		var location = rule.has("id") and rule["id"] in ["save_location", "game_menu_full_location", "map_page_full_location"]
		var font = _localized_font(rule["font"], false, location)
		if font != null:
			var slot = "normal_font" if node.is_type("RichTextLabel") else "font"
			if node.get_font(slot) != font:
				node.add_font_override(slot, font)
	_fallback_display(node)
	_quest_inline_fonts(node)
	# Preserve source line count, reveal percentage, clipping, alignment and box mode.
	# Name/location layout is measured separately, not globally rescaled here.

func _menu_layout_panel(panel, top, bottom):
	var original = panel.get_stylebox("panel")
	if original == null:
		return
	var local = original.duplicate()
	local.set("content_margin/top", top)
	local.set("content_margin/bottom", bottom)
	panel.add_style_override("panel", local)

func _apply_menu_layout(node):
	if node.has_meta("zhtw_menu_layout_v11"):
		return
	var scene = node.get_filename().replace(".tscn.converted.scn", ".tscn")
	if scene == "res://lib/ui/game_menu/game_menu.tscn":
		for path in ["Equip Page/Stats Box/Stats Panel/Stats List", "Equip Page/Element Box/Element Panel/Element List", "Equip Page/Status Box/Status Panel/Status List", "Equip Page/Equipped Items/Equipment List", "Equip Page/Description Panel/VBoxContainer/Label"]:
			if not node.has_node(path):
				return
		var page = node.get_node("Equip Page")
		for header_path in ["Stats Header", "Equipment Header", "Element Header", "Status Header", "Info Header"]:
			if not page.has_node(header_path):
				return
		for path in ["Stats Header", "Equipment Header", "Element Header", "Status Header", "Info Header"]:
			var header = page.get_node(path)
			header.set_custom_minimum_size(Vector2(header.get_custom_minimum_size().x, 13))
		_menu_layout_panel(page.get_node("Stats Box/Stats Panel"), 12, 2)
		page.get_node("Stats Header").set_pos(Vector2(22, 146))
		page.get_node("Stats Box/Stats Panel/Stats List").add_constant_override("separation", 0)
		_menu_layout_panel(page.get_node("Element Box/Element Panel"), 14, 4)
		page.get_node("Element Box/Element Panel/Element List").add_constant_override("separation", 0)
		_menu_layout_panel(page.get_node("Status Box/Status Panel"), 14, 4)
		page.get_node("Status Box/Status Panel/Status List").add_constant_override("separation", 0)
		_menu_layout_panel(page.get_node("Equipped Items"), 14, 5)
		var equipment = page.get_node("Equipped Items/Equipment List")
		equipment.add_constant_override("separation", 0)
		equipment.set_custom_minimum_size(Vector2(equipment.get_custom_minimum_size().x, 70))
		for button in equipment.get_children():
			if button.is_type("Button"):
				button.set_custom_minimum_size(Vector2(button.get_custom_minimum_size().x, 14))
		_menu_layout_panel(page.get_node("Description Panel"), 14, 4)
		page.get_node("Description Panel/VBoxContainer").add_constant_override("separation", 0)
		var text = page.get_node("Description Panel/VBoxContainer/Label")
		text.set_custom_minimum_size(Vector2(text.get_custom_minimum_size().x, 0))
		call_deferred("_settle_menu_layout", weakref(node))
	elif scene == "res://lib/ui/game_menu/BoilpointMenu.tscn":
		if not node.has_node("BoilpointInfoPanel/Description") or not node.has_node("BoilpointInfoPanel/Header"):
			return
		var text = node.get_node("BoilpointInfoPanel/Description")
		var header = node.get_node("BoilpointInfoPanel/Header")
		header.set_custom_minimum_size(Vector2(header.get_custom_minimum_size().x, 13))
		text.set_pos(Vector2(text.get_pos().x, 14))
		text.set_size(Vector2(text.get_size().x, 37))
	elif scene == "res://lib/ui/game_menu/Quest Page.tscn":
		if not node.has_node("Quest Details/RichTextLabel"):
			return
		var text = node.get_node("Quest Details/RichTextLabel")
		text.set_size(Vector2(text.get_parent().get_size().x - text.get_pos().x - 8, text.get_size().y))
	else:
		return
	node.set_meta("zhtw_menu_layout_v11", true)

func _settle_menu_layout(reference):
	var node = reference.get_ref()
	if node == null:
		return
	# Containers may already have expanded before tree_changed; restore their
	# authored bounds after the new child minimum sizes have propagated.
	var page = node.get_node("Equip Page")
	# A child keeps its previous expanded size when its minimum decreases.
	# Restore this exact inner panel before the enclosing HBoxContainer.
	page.get_node("Stats Box/Stats Panel").set_size(Vector2(108, 92))
	for item in [["Stats Box", Vector2(123, 92)], ["Element Box", Vector2(71, 120)], ["Status Box", Vector2(71, 114)], ["Equipped Items", Vector2(187, 89)], ["Description Panel", Vector2(187, 56)]]:
		page.get_node(item[0]).set_size(item[1])

# v13: only source-bound fields demonstrated in native v12 screenshots.
func _location_layout_v13(location):
	if not location.has_node("Header") or not location.has_node("PanelContainer/Label"):
		return
	var header = location.get_node("Header")
	header.set_custom_minimum_size(Vector2(header.get_custom_minimum_size().x, 13))
	_menu_layout_panel(location.get_node("PanelContainer"), 14, 4)
	location.get_node("PanelContainer/Label").set_valign(1)

func _apply_native_layout_v13(node):
	if node.has_meta("zhtw_native_layout_v13"):
		return
	var scene = node.get_filename().replace(".tscn.converted.scn", ".tscn")
	if scene == "res://lib/ui/game_menu/game_menu.tscn":
		if not node.has_node("Main Page/Location/PanelContainer/Label") or not node.has_node("Main Page/Metals/Metals Info"):
			return
		_location_layout_v13(node.get_node("Main Page/Location"))
		var metals = node.get_node("Main Page/Metals/Metals Info")
		for path in ["Header", "Copper", "Colon", "MP", "Slash", "Max MP"]:
			if not metals.has_node(path):
				return
		# Original 74x25 panel, unchanged numeric values and widths. The 12px
		# CJK header gets a separate row from its 11px icon and 6px numbers.
		metals.get_node("Header").set_custom_minimum_size(Vector2(24, 13))
		var copper = metals.get_node("Copper")
		copper.set_pos(Vector2(copper.get_pos().x, 12))
		for path in ["Colon", "MP", "Slash", "Max MP"]:
			var number = metals.get_node(path)
			number.set_pos(Vector2(number.get_pos().x, 15))
	elif scene == "res://lib/battle/battle_scene_ui.tscn":
		var path = "Victory Screens/Results/Bottom Panel"
		if not node.has_node(path + "/Clips Header") or not node.has_node(path + "/HBox Money"):
			return
		var bottom = node.get_node(path)
		var header = bottom.get_node("Clips Header")
		var money = bottom.get_node("HBox Money")
		# The original 4px heading starts at y=-2 on the divider. Put its
		# 13px Chinese label fully inside the unchanged 35px bottom panel.
		header.set_custom_minimum_size(Vector2(header.get_custom_minimum_size().x, 13))
		header.set_pos(Vector2(header.get_pos().x, 2))
		# The original 30px centered money row would intersect the new heading.
		# Its income box needs 17px; keep every icon/value width and right anchor.
		money.set_pos(Vector2(money.get_pos().x, 15))
		money.set_size(Vector2(money.get_size().x, 17))
	elif scene == "res://lib/ui/shop_menu/shop_menu.tscn":
		if not node.has_node("Money Panel/Header") or not node.has_node("Money Panel/HBoxContainer"):
			return
		var panel = node.get_node("Money Panel")
		var header = panel.get_node("Header")
		var row = panel.get_node("HBoxContainer")
		# Keep the original 79x28 shop panel and every value/icon width.
		# The Chinese heading occupies the first row; money fits below it.
		header.set_custom_minimum_size(Vector2(header.get_custom_minimum_size().x, 13))
		row.set_pos(Vector2(row.get_pos().x, 15))
		row.set_size(Vector2(row.get_size().x, 9))
	elif scene == "res://lib/battle/system/leveling_up.tscn":
		# CJK stat captions make these six rows 13px high. Original numeric
		# labels center automatically; operators inside plain Controls do not.
		for stat in ["Attack", "Agility", "Defense", "Luck", "Magic", "Honor"]:
			for token in ["Colon", "Plus", "Arrow"]:
				var path = "Center Panel/Stats List/" + stat + "/" + token + "/Label"
				if node.has_node(path):
					var label = node.get_node(path)
					label.set_size(Vector2(label.get_size().x, 13))
					label.set_valign(1)
	elif scene == "res://lib/ui/file_menu/Save Slot.tscn":
		if not node.has_node("Button/Save Info/Location/PanelContainer/Label"):
			return
		_location_layout_v13(node.get_node("Button/Save Info/Location"))
		# Save Slot uses its own 56x34 metals panel. Put the 10x11 icon,
		# original colon and 12px Chinese heading beside one another.
		# The existing 13/20 number row and main-menu layout stay untouched.
		if node.has_node("Button/Save Info/Metals Info"):
			var saved_metals = node.get_node("Button/Save Info/Metals Info")
			if saved_metals.has_node("Header") and saved_metals.has_node("Copper") and saved_metals.has_node("Colon"):
				var saved_header = saved_metals.get_node("Header")
				saved_header.set_custom_minimum_size(Vector2(24, 13))
				saved_header.set_pos(Vector2(22, 1))
				saved_metals.get_node("Copper").set_pos(Vector2(6, 2))
				saved_metals.get_node("Colon").set_pos(Vector2(17, 5))
	elif scene == "res://lib/ui/game_menu/equipment_entry.tscn":
		if not node.has_node("Label/E") or not node.has_node("Label/Colon"):
			return
		# Keep the right-aligned count and colon unchanged. The 12px 裝 glyph
		# needs more left clearance than the original single Latin E.
		var marker = node.get_node("Label/E")
		marker.set_pos(Vector2(-16, marker.get_pos().y))
	else:
		return
	node.set_meta("zhtw_native_layout_v13", 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_font_only(node):
	# Called only for exact prior static-CJK fields, including inherited fonts.
	# Retain the old Latin baseline adjustment as well as CJK font metrics.
	if node == null or not node.has_meta("zhtw_v35_font_events") or not _has_cjk(tr(node.get_text())):
		return
	_fallback_display(node)

func register_owner(owner, expected_scene):
	if owner == null or _canonical(owner.get_filename()) != expected_scene:
		return
	_apply_native_layout_v13(owner)
	_apply_menu_layout(owner)
	var paths = {}
	for rule in rules:
		if _canonical(rule["scene"]) == expected_scene:
			paths[_relative(rule["node_path"])] = true
	if native_ui_index.has(expected_scene):
		for path in native_ui_index[expected_scene]:
			paths[path] = true
	# These two exact existing repairs live in code rather than mapping JSON.
	if expected_scene == "res://lib/battle/system/leveling_up.tscn":
		paths["Top Panel/Label"] = true
	elif expected_scene == "res://lib/ui/game_menu/Quest Page.tscn":
		paths["Quest Details/RichTextLabel"] = true
	# Native inventory names were not registered by the static-CJK field list.
	# Keep this new, finite name watcher separate from the generic font pipeline.
	if expected_scene == "res://lib/ui/game_menu/equipment_entry.tscn" and _is_equipment_inventory_name(owner):
		if not owner.has_meta("zhtw_exact_display_tracked") and not owner.has_meta("zhtw_v35_font_events"):
			owner.set_meta("zhtw_v39_equipment_roman_only", true)
			_watch_display(owner, null)
	for path in paths:
		if path == "." or owner.has_node(path):
			var node = owner if path == "." else owner.get_node(path)
			_added(node)

func _watch_display(node, rule):
	node.set_meta("zhtw_v35_rule", {} if rule == null else rule)
	if not node.has_meta("zhtw_v35_display_events"):
		node.set_meta("zhtw_v35_display_events", true)
		for signal_name in ["draw", "visibility_changed", "item_rect_changed", "focus_enter", "focus_exit"]:
			_connect_event(node, signal_name, "_display_event", "_display_event_arg", weakref(node))
	_display_event(weakref(node))

func _display_event_arg(value, reference):
	_display_event(reference)

func _display_event(reference):
	var node = reference.get_ref()
	if node == null or node.has_meta("zhtw_v35_display_queued"):
		return
	node.set_meta("zhtw_v35_display_queued", true)
	call_deferred("_display_apply", reference)

func _display_signature(node):
	var state = []
	# Only this registered journal body needs author/focus state in its cache key.
	# Reopening the same entry can reset its header without changing body text.
	if node.has_meta("zhtw_v38_quest_header"):
		var header = node.get_meta("zhtw_v38_quest_header").get_ref()
		var focus = node.get_focus_owner()
		state.append("" if header == null else header.get_text())
		state.append(0 if focus == null else focus.get_instance_ID())
	if node.has_method("get_text"):
		state.append(node.get_text())
	if node.has_method("get_button_count"):
		for i in range(node.get_button_count()):
			state.append(node.get_button_text(i))
	for slot in ["font", "font_selected", "normal_font"]:
		var current_font = node.get_font(slot)
		state.append(0 if current_font == null else current_font.get_instance_ID())
	return str(state)

func _display_apply(reference):
	var node = reference.get_ref()
	if node == null:
		return
	node.set_meta("zhtw_v35_display_queued", null)
	var signature = _display_signature(node)
	if node.has_meta("zhtw_v35_display_result") and node.get_meta("zhtw_v35_display_result") == signature:
		return
	# Only newly registered native inventory name fields use this private repair.
	# Non-target and reused rows retain their original native font and metrics.
	if node.has_meta("zhtw_v39_equipment_roman_only"):
		_repair_equipment_roman_baseline(node)
		node.set_meta("zhtw_v35_display_result", _display_signature(node))
		return
	if has_node("/root/ZhTWLocalization"):
		get_node("/root/ZhTWLocalization").register_display(node)
	var selected_rule = node.get_meta("zhtw_v35_rule")
	_refresh_one(reference, null if selected_rule.empty() else selected_rule)
	node.set_meta("zhtw_v35_display_result", _display_signature(node))
