class_name LoadMenu extends CanvasLayer
## Phase 16 — Slot-picker shown when the player taps Load.
##
## Layer 25 — above StorytellerModal (20) and any banner (15).
## Shows Manual save + Autosave slots with timestamps.  If a slot's version
## differs from SAVE_VERSION, the player sees a warning dialog before the load
## proceeds.
##
## Open via LoadMenu.open(); close via the Cancel button or _close().

## Emitted when the player confirms a load (after any version-mismatch dialog).
signal load_confirmed(slot: StringName)


const TILE_SIZE_PX: int = 16

# ── node refs ─────────────────────────────────────────────────────────────────
var _dim: ColorRect = null
var _panel: PanelContainer = null
var _slot_list: VBoxContainer = null
var _no_saves_label: Label = null
var _cancel_btn: Button = null

# Version-mismatch confirmation dialog refs.
var _warn_dim: ColorRect = null
var _warn_panel: PanelContainer = null
var _warn_label: Label = null
var _warn_continue_btn: Button = null
var _warn_cancel_btn: Button = null

## The slot waiting for confirmation (set while the warning dialog is open).
var _pending_slot: StringName = &""


func _ready() -> void:
	layer = 25
	_build_ui()
	_set_visible(false)
	Audit.log("load_menu", "LoadMenu ready")


func _exit_tree() -> void:
	pass


func _unhandled_input(event: InputEvent) -> void:
	# _set_visible drives _panel.visible, not CanvasLayer.visible — use _panel as the gate.
	if _panel == null or not _panel.visible:
		return
	if event.is_action_pressed("cancel"):
		# If the version-mismatch sub-dialog is open, dismiss it first.
		if _warn_panel != null and _warn_panel.visible:
			_on_warn_cancel()
		else:
			_close()
		get_viewport().set_input_as_handled()


# ── public API ────────────────────────────────────────────────────────────────

func open() -> void:
	_refresh_slots()
	_set_visible(true)
	Audit.log("load_menu", "opened")


# ── UI construction ───────────────────────────────────────────────────────────

func _build_ui() -> void:
	# Full-screen dim.
	_dim = ColorRect.new()
	_dim.name = "Dim"
	_dim.set_anchors_preset(Control.PRESET_FULL_RECT)
	_dim.color = Color(0.0, 0.0, 0.0, 0.55)
	_dim.mouse_filter = Control.MOUSE_FILTER_STOP
	add_child(_dim)

	# Centre panel.
	_panel = PanelContainer.new()
	_panel.name = "Dialog"
	_panel.set_anchors_preset(Control.PRESET_CENTER)
	_panel.custom_minimum_size = Vector2(360, 220)
	_panel.offset_left  = -180
	_panel.offset_right = 180
	_panel.offset_top   = -110
	_panel.offset_bottom = 110
	add_child(_panel)

	var vbox := VBoxContainer.new()
	vbox.add_theme_constant_override("separation", 12)
	_panel.add_child(vbox)

	# Title.
	var title := Label.new()
	title.name = "Title"
	title.text = Strings.t(&"ui.load")
	title.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER
	vbox.add_child(title)

	# Slot list (populated by _refresh_slots).
	_slot_list = VBoxContainer.new()
	_slot_list.name = "SlotList"
	_slot_list.add_theme_constant_override("separation", 8)
	vbox.add_child(_slot_list)

	# "No saves yet" label — hidden when slots exist.
	_no_saves_label = Label.new()
	_no_saves_label.name = "NoSaves"
	_no_saves_label.text = Strings.t(&"ui.no_saves")
	_no_saves_label.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER
	_no_saves_label.visible = false
	vbox.add_child(_no_saves_label)

	# Cancel row.
	var cancel_row := HBoxContainer.new()
	cancel_row.alignment = BoxContainer.ALIGNMENT_CENTER
	vbox.add_child(cancel_row)

	_cancel_btn = Button.new()
	_cancel_btn.name = "CancelBtn"
	_cancel_btn.text = Strings.t(&"ui.cancel")
	_cancel_btn.custom_minimum_size = Vector2(120, 48)
	_cancel_btn.focus_mode = Control.FOCUS_NONE
	_cancel_btn.pressed.connect(_close)
	cancel_row.add_child(_cancel_btn)

	# Version-mismatch warning dialog (built once, shown when needed).
	_build_warn_dialog()


func _build_warn_dialog() -> void:
	_warn_dim = ColorRect.new()
	_warn_dim.name = "WarnDim"
	_warn_dim.set_anchors_preset(Control.PRESET_FULL_RECT)
	_warn_dim.color = Color(0.0, 0.0, 0.0, 0.45)
	_warn_dim.mouse_filter = Control.MOUSE_FILTER_STOP
	_warn_dim.visible = false
	add_child(_warn_dim)

	_warn_panel = PanelContainer.new()
	_warn_panel.name = "WarnDialog"
	_warn_panel.set_anchors_preset(Control.PRESET_CENTER)
	_warn_panel.custom_minimum_size = Vector2(340, 160)
	_warn_panel.offset_left  = -170
	_warn_panel.offset_right = 170
	_warn_panel.offset_top   = -80
	_warn_panel.offset_bottom = 80
	_warn_panel.visible = false
	add_child(_warn_panel)

	var vbox := VBoxContainer.new()
	vbox.add_theme_constant_override("separation", 12)
	_warn_panel.add_child(vbox)

	_warn_label = Label.new()
	_warn_label.name = "WarnLabel"
	_warn_label.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER
	_warn_label.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
	vbox.add_child(_warn_label)

	var btn_row := HBoxContainer.new()
	btn_row.alignment = BoxContainer.ALIGNMENT_CENTER
	btn_row.add_theme_constant_override("separation", 12)
	vbox.add_child(btn_row)

	_warn_continue_btn = Button.new()
	_warn_continue_btn.text = Strings.t(&"ui.continue")
	_warn_continue_btn.custom_minimum_size = Vector2(120, 48)
	_warn_continue_btn.focus_mode = Control.FOCUS_NONE
	_warn_continue_btn.pressed.connect(_on_warn_continue)
	btn_row.add_child(_warn_continue_btn)

	_warn_cancel_btn = Button.new()
	_warn_cancel_btn.text = Strings.t(&"ui.cancel")
	_warn_cancel_btn.custom_minimum_size = Vector2(120, 48)
	_warn_cancel_btn.focus_mode = Control.FOCUS_NONE
	_warn_cancel_btn.pressed.connect(_on_warn_cancel)
	btn_row.add_child(_warn_cancel_btn)


# ── slot population ───────────────────────────────────────────────────────────

func _refresh_slots() -> void:
	# Clear previous slot buttons.
	for child in _slot_list.get_children():
		child.queue_free()

	var slots: Array[StringName] = [&"manual", &"autosave"]
	var any_exist: bool = false

	for slot in slots:
		var meta: Dictionary = SaveSystem.peek_save_metadata(slot)
		if not meta.get("exists", false):
			continue
		any_exist = true

		var label_key: StringName = &"ui.manual_save" if slot == &"manual" else &"ui.autosave"
		var saved_at: int = int(meta.get("saved_at_unix", 0))
		var date_str: String = _unix_to_date(saved_at)
		var btn_text: String = "%s  (%s)" % [Strings.t(label_key), date_str]

		var btn := Button.new()
		btn.text = btn_text
		btn.custom_minimum_size = Vector2(320, 48)
		btn.focus_mode = Control.FOCUS_NONE
		# Capture slot by value in the lambda.
		btn.pressed.connect(_on_slot_pressed.bind(slot, int(meta.get("version", 1))))
		_slot_list.add_child(btn)

	_no_saves_label.visible = not any_exist


func _unix_to_date(unix: int) -> String:
	if unix <= 0:
		return "—"
	var dt: Dictionary = Time.get_datetime_dict_from_unix_time(unix)
	return "%04d-%02d-%02d %02d:%02d" % [dt.year, dt.month, dt.day, dt.hour, dt.minute]


# ── interaction ───────────────────────────────────────────────────────────────

func _on_slot_pressed(slot: StringName, file_version: int) -> void:
	if file_version != SaveSystem.SAVE_VERSION:
		# Show version-mismatch warning dialog before proceeding.
		_pending_slot = slot
		_warn_label.text = Strings.t(&"ui.version_mismatch").format({"v": file_version})
		_warn_dim.visible = true
		_warn_panel.visible = true
		Audit.log("load_menu", "version mismatch warning shown for slot '%s' (v%d)" % [slot, file_version])
	else:
		_do_load(slot)


func _on_warn_continue() -> void:
	_warn_dim.visible = false
	_warn_panel.visible = false
	if _pending_slot != &"":
		_do_load(_pending_slot)
	_pending_slot = &""


func _on_warn_cancel() -> void:
	_warn_dim.visible = false
	_warn_panel.visible = false
	_pending_slot = &""
	Audit.log("load_menu", "version mismatch — player cancelled load")


func _do_load(slot: StringName) -> void:
	Audit.log("load_menu", "loading slot '%s'" % slot)
	load_confirmed.emit(slot)
	_close()
	SaveSystem.load_from_slot(slot)


func _close() -> void:
	_set_visible(false)
	Audit.log("load_menu", "closed")


func _set_visible(v: bool) -> void:
	# Toggle CanvasLayer.visible so the dim Control (MOUSE_FILTER_STOP) does not
	# eat _unhandled_input mouse events for the world below when modal is hidden.
	# (The warning sub-dialog visibility is managed separately and lives inside.)
	visible = v or (_warn_panel != null and _warn_panel.visible)
	if _dim != null:
		_dim.visible = v
	if _panel != null:
		_panel.visible = v
