-- @module plugins.window_test

-- This file is part of Lx, created by Liqube <www.liqube.com>
-- Copyright Liqube Audio. All rights reserved.
-- Lx Interim License. See LICENSE for details.

--- Native window utilities and manual test commands

local core = require("core")
local qui = require("qui")
local colors = require("qui.colors")
local palette = require("qui.palette")
local theme = require("qui.theme")
local Button = require("qui.button")
local Checkbox = require("qui.checkbox")
local Combobox = require("qui.combobox")
local Listbox = require("qui.listbox")
local Menu = require("qui.menu")
local Panel = require("qui.panel")
local Radio = require("qui.radio")
local Scrollbar = require("qui.scrollbar")
local Separator = require("qui.separator")
local Textbox = require("qui.textbox")
local Tree = require("qui.tree")
local VirtualTree = require("qui.vtree")
local Label = require("qui.label")
require("themes.liqube_light")	-- Registers the standard stock light theme used by the switch Button
local utf8 = require("utf8")

local window_test = {}

-- Keep each live Form object until its one completion callback removes the utility bookkeeping
local opened_window_ids = {}	-- Opening order used by 'win:close-last'
local opened_forms = {}		-- Live Form object retained for each utility window ID
local opened_right_panes = {}	-- Optional right Pane retained for runtime collapse tests
local opened_right_toggles = {}	-- Shared toggle action used by the Button and command
local next_window_number = 1	-- Human-friendly number used only in test titles
local light_theme_active = false	-- Shared by every test Window because the active Theme is application-wide

--- Find the copied native information for one stable Window ID
-- @param window_id number stable Lx Window ID
-- @return table|nil info
local function get_window_info(window_id)
	for _, info in ipairs(window.list()) do
		if info.id == window_id then
			return info
		end
	end

	return nil
end

--- Open one Lua-authored owner-modal confirmation Form above a test window
-- @param owner_window_id number stable owner Window ID
-- @return boolean opened
local function open_confirmation(owner_window_id)
	local message = Label {
		name = "message",
		text = "This entire confirmation window is drawn and controlled by Lua.",
		placement = {
			horizontal = "center",
			vertical = "center",
		},
	}
	local accept_button = Button {
		name = "accept",
		caption = "&Accept",
		dialog_action = "default",
		placement = {
			horizontal = "right",
			vertical = "center",
		},
	}
	local cancel_button = Button {
		name = "cancel",
		caption = "&Cancel",
		dialog_action = "cancel",
		placement = {
			horizontal = "right",
			vertical = "center",
		},
	}
	local confirmation_form
	local build_error
	confirmation_form, build_error = qui.form {
		name = "Lua Confirmation",
		type = "dialog",
		initial_focus = accept_button,
		on_complete = function(_, result)
			core.log("Lua confirmation completed with result '%s'", tostring(result))
		end,
		layout = qui.rows {
			gap = 12,
			padding_left = 18,
			padding_top = 18,
			padding_right = 18,
			padding_bottom = 18,

			qui.pane {
				name = "content",
				length = "weighted",
				weight = 1,
				controls = { message },
			},

			qui.pane {
				name = "actions",
				length = "content",
				layout = qui.cols {
					gap = 8,

					qui.pane {
						name = "action_filler",
						length = "weighted",
						weight = 1,
					},

					qui.pane {
						name = "accept_action",
						length = "content",
						controls = { accept_button },
					},

					qui.pane {
						name = "cancel_action",
						length = "content",
						controls = { cancel_button },
					},
				},
			},
		},
	}

	if not confirmation_form then
		core.error("Confirmation Form failed: %s", tostring(build_error))
		return false
	end

	--- Close through the same checked Form path for either visible Button
	local function finish(result)
		local closed, close_error = confirmation_form:close(result)
		if not closed then
			core.error("Confirmation close failed: %s", tostring(close_error))
			return false
		end

		return true
	end

	accept_button.on_click = function()
		return finish("accept")
	end
	cancel_button.on_click = function()
		return finish("cancel")
	end

	local window_id, window_error = confirmation_form:open_window {
		title = "Lua Confirmation",
		-- These old pixel-era dimensions retain the same footprint after Window sizes became DIPs
		width = 448,
		height = 160,
		owner_id = owner_window_id,
		modality = "owner_modal",
	}
	if not window_id then
		if confirmation_form:is_valid() then
			confirmation_form:destroy()
		end
		core.error("Confirmation window failed: %s", tostring(window_error))
		return false
	end

	return true
end

--- Build the declarative Form used to inspect drawing, focus, and pointer capture
-- @param title string native Window and Form name
-- @return table|nil built_form durable handles on success
-- @return string|nil error_text construction failure on error
local function create_test_form(title)
	-- All mutable appearance and interaction state deliberately lives in this Lua table
	local definition = qui.control {
		name = "lua_surface",
		width = 480,
		height = 240,
		focusable = true,
		accepts_pointer = true,
		background = colors.input_bg,
		hover_background = colors.input_hover_bg,
		accent = palette.blue.strong.color,
		focus_accent = palette.green.strong.color,
		pressed_accent = palette.orange.strong.color,
		marker_x = 64,
		marker_y = 64,
		hovered = false,
		focused = false,
		pressed = false,
	}

	--- Report a natural size while allowing the weighted root layout to assign the final size
	function definition:measure(_, minimum_width, minimum_height, maximum_width, maximum_height)
		local width = math.max(minimum_width, math.min(self.width, maximum_width))
		local height = math.max(minimum_height, math.min(self.height, maximum_height))

		return width, height
	end

	--- Draw the complete control through the short-lived control canvas supplied by C++
	function definition:draw(control_canvas)
		local width, height = control_canvas:size()
		local background_token = self.hovered and self.hover_background or self.background
		local accent_token = self.focused and self.focus_accent or self.accent

		if self.pressed then
			accent_token = self.pressed_accent
		end
		local background = theme.resolve(background_token)
		local accent = theme.resolve(accent_token)

		control_canvas:fill_rect(0, 0, width, height, background)
		control_canvas:fill_rect(12, 12, math.max(0, width - 24), 4, accent)
		control_canvas:fill_rect(12, math.max(12, height - 16), math.max(0, width - 24), 4, accent)
		control_canvas:fill_rect(self.marker_x - 10, self.marker_y - 10, 20, 20, accent)
	end

	--- Keep hover, drag, focus, and keyboard behavior entirely in Lua
	function definition:event(event)
		if event.kind == "pointer_enter" then
			self.hovered = true
			return { handled = true, redraw = true }
		elseif event.kind == "pointer_leave" then
			self.hovered = false
			return { handled = true, redraw = true }
		elseif event.kind == "pointer_down" and event.button == "left" then
			self.pressed = true
			self.marker_x = event.x
			self.marker_y = event.y
			return { handled = true, redraw = true, focus = "acquire", capture = "acquire" }
		elseif event.kind == "pointer_move" and self.pressed then
			self.marker_x = event.x
			self.marker_y = event.y
			return { handled = true, redraw = true }
		elseif event.kind == "pointer_up" and event.button == "left" then
			self.pressed = false
			self.marker_x = event.x
			self.marker_y = event.y
			return { handled = true, redraw = true, capture = "release" }
		elseif event.kind == "focus_gained" then
			self.focused = true
			return { redraw = true }
		elseif event.kind == "focus_lost" then
			self.focused = false
			self.pressed = false
			return { redraw = true, capture = "release" }
		elseif event.kind == "key_down" then
			local step = event.shift and 24 or 8

			if event.key == "left" then
				self.marker_x = self.marker_x - step
			elseif event.key == "right" then
				self.marker_x = self.marker_x + step
			elseif event.key == "up" then
				self.marker_y = self.marker_y - step
			elseif event.key == "down" then
				self.marker_y = self.marker_y + step
			else
				return nil
			end

			return { handled = true, redraw = true }
		end

		return nil
	end

	definition.placement = {
		horizontal = "stretch",
		vertical = "stretch",
	}

	-- A second initially collapsed Pane proves runtime structure changes without rebuilding controls
	local side_definition = qui.control {
		name = "right_surface",
		width = 220,
		height = 240,
		accepts_pointer = false,
	}
	local embedded_label = Label {
		name = "embedded_label",
		text = "Pane-hosted Form",
		placement = {
			horizontal = "center",
			vertical = "center",
		},
	}
	-- A focusable child Control proves that embedded Forms join normal Window input routing
	local embedded_button = Button {
		name = "embedded_button",
		caption = "Embedded Form Button",
		placement = {
			horizontal = "center",
			vertical = "center",
		},
		on_click = function()
			core.log("Clicked the Button owned by the embedded Form")
			return true
		end,
	}

	--- Draw a deliberately simple side surface so its structural boundary remains obvious
	function side_definition:draw(control_canvas)
		local width, height = control_canvas:size()

		control_canvas:fill_rect(0, 0, width, height, { 38, 43, 52, 255 })
		control_canvas:fill_rect(0, 0, 3, height, { 86, 156, 214, 255 })
	end

	-- The first reusable Lua Button remains an ordinary unrestricted Control definition
	local toggle_button = Button {
		name = "toggle_right",
		caption = "Toggle side Pane",
		placement = {
			horizontal = "right",
			vertical = "center",
		},
	}
	local side_button_enabled = true
	-- The shared Command gives one Button, one Menu item, and one shortcut the same action
	local toggle_button_command = qui.command {
		name = "test.toggle-side-button",
		text = "Enable/disable side Pane Button",
		shortcut = qui.shortcut("ctrl+shift+b"),
		execute = function()
			side_button_enabled = not side_button_enabled
			local changed, change_error = toggle_button:set_enabled(side_button_enabled)
			if not changed then
				core.error("Shared Command target change failed: %s", tostring(change_error))
				return
			end
			core.log("Test window side Pane Button enabled=%s", tostring(side_button_enabled))
		end,
	}
	local button_state_button = Button {
		name = "toggle_button_enabled",
		command = toggle_button_command,
		placement = {
			horizontal = "right",
			vertical = "center",
		},
	}
	local theme_button = Button {
		name = "switch_theme",
		caption = "Switch UI theme",
		placement = {
			horizontal = "right",
			vertical = "center",
		},
		on_click = function()
			local next_theme = light_theme_active and "Liqube Dark" or "Liqube Light"
			local applied, apply_error = theme.apply(next_theme)
			if not applied then
				core.error("Window theme switch failed: %s", tostring(apply_error))
				return false
			end
			light_theme_active = not light_theme_active
			core.log("Test window theme changed to %s", next_theme)

			return true
		end,
	}
	local close_button = Button {
		name = "close_form",
		caption = "Close Form",
		placement = {
			horizontal = "right",
			vertical = "center",
		},
	}
	local confirmation_button = Button {
		name = "open_confirmation",
		caption = "Open confirmation",
		placement = {
			horizontal = "right",
			vertical = "center",
		},
	}
	local toggle_embedded_button = Button {
		name = "toggle_embedded",
		caption = "Detach/attach Form",
		placement = {
			horizontal = "right",
			vertical = "center",
		},
	}
	local toggle_overlay_button = Button {
		name = "toggle_overlay",
		caption = "Show/hide overlay",
		placement = {
			horizontal = "right",
			vertical = "center",
		},
	}
	-- A transparent Label proves that text changes can resize a live content Pane
	local side_status = Label {
		name = "side_status",
		text = "Side Pane: hidden",
		placement = {
			horizontal = "right",
			vertical = "center",
		},
	}
	local input_status = Label {
		name = "input_status",
		text = "Typed: nothing yet",
		placement = {
			horizontal = "left",
			vertical = "center",
		},
	}
	local listbox_status = Label {
		name = "listbox_status",
		text = "Selected mode: Markdown",
		placement = {
			horizontal = "left",
			vertical = "center",
		},
	}
	local combobox_status = Label {
		name = "combobox_status",
		text = "Dropdown data ID: 202",
		placement = {
			horizontal = "left",
			vertical = "center",
		},
	}
	local tree_status = Label {
		name = "tree_status",
		text = "Tree selection: Workspace",
		placement = {
			horizontal = "left",
			vertical = "center",
		},
	}
	local metrics_status = Label {
		name = "metrics_status",
		text = "Window metrics become available after opening",
		placement = {
			horizontal = "left",
			vertical = "center",
		},
	}
	local menu_status = Label {
		name = "menu_status",
		text = "Menu result: nothing yet",
		placement = {
			horizontal = "left",
			vertical = "center",
		},
	}
	--- Report one choice made anywhere in the test Menu tree
	-- @param _ table Menu that owns the selected item
	-- @param item table selected item and its application-owned data
	local function report_menu_choice(_, item)
		local changed, change_error = menu_status:set_text(
			"Menu result: " .. tostring(item.id) .. " | Data: " .. tostring(item.data.command)
		)
		if not changed then
			core.error("Test Menu status change failed: %s", tostring(change_error))
		end
		core.log("Test Menu selected '%s' with data '%s'", tostring(item.id), tostring(item.data.command))
	end

	-- These child Menus deliberately prove that a popup can branch more than once
	local density_menu = Menu {
		name = "test_density_menu",
		items = {
			{
				id = "density_compact",
				text = "&Compact",
				data = { command = "view.density.compact" },
			},
			{
				id = "density_normal",
				text = "&Normal",
				detail = "Default",
				checked = true,
				indicator = "radio",
				data = { command = "view.density.normal" },
			},
			{
				id = "density_comfortable",
				text = "C&omfortable",
				data = { command = "view.density.comfortable" },
			},
		},
		on_click = report_menu_choice,
	}
	local view_menu = Menu {
		name = "test_view_menu",
		items = {
			{
				id = "show_icons",
				text = "Show &icons",
				checked = true,
				indicator = "check",
				data = { command = "view.show_icons" },
			},
			{
				id = "density",
				text = "&Display density",
				glyph = "font_size",
				menu = density_menu,
			},
		},
		on_click = report_menu_choice,
	}
	local popup_menu
	local menu_button = Button {
		name = "open_popup_menu",
		caption = "Open popup Menu",
		placement = {
			horizontal = "left",
			vertical = "center",
		},
		on_click = function(self)
			local opened, open_error = popup_menu:toggle {
				anchor = self,
				position = "bottom_left",
				gap = 2,
			}
			if not opened then
				core.error("Test Menu open failed: %s", tostring(open_error))
			end
		end,
	}
	-- This sample keeps Menu-specific visuals together without turning the wider Control lab into another list
	popup_menu = Menu {
		name = "test_popup_menu",
		items = {
			{
				id = "open",
				text = "&Open file",
				shortcut = qui.shortcut("ctrl+shift+o"),
				data = { command = "file.open" },
			},
			{
				id = "toggle_side_button",
				command = toggle_button_command,
			},
			{
				id = "delete",
				text = "&Delete",
				style = "critical",
				data = { command = "test.delete" },
			},
			{
				id = "view",
				text = "&View",
				menu = view_menu,
			},
			Menu.separator(),
			{
				id = "disabled",
				text = "&Unavailable item",
				detail = "D",
				enabled = false,
				data = { command = "test.disabled" },
			},
			{
				id = "close",
				text = "&Close Menu",
				data = { command = "test.close" },
			},
		},
		on_click = report_menu_choice,
	}
	local text_input = Textbox {
		name = "text_input",
		placeholder = "Type, select, copy, paste, undo, or use an IME",
		width = 520,
		placement = {
			horizontal = "stretch",
			vertical = "center",
		},
		on_change = function(_, text)
			local preview = utf8.sub(text, 1, 36)
			if utf8.len(text) > 36 then
				preview = preview .. "…"
			end
			local changed, change_error = input_status:set_text(
				preview == "" and "Typed: nothing yet" or "Typed: " .. preview
			)
			if not changed then
				core.error("Window input status change failed: %s", tostring(change_error))
			end
		end,
		on_submit = function(_, text)
			core.log("Test window Textbox submitted '%s'", text)
			return false	-- Leave Return available to the containing Form
		end,
	}
	-- The normal Checkbox proves that shared enabled state reaches both Command presenters
	local enable_test_button = Checkbox {
		name = "enable_test_button",
		text = "Enable shared Command",
		checked = true,
		placement = {
			horizontal = "stretch",
			vertical = "center",
		},
		on_change = function(_, checked)
			toggle_button_command:set_enabled(checked)
			core.log("Test window shared Command enabled=%s", tostring(checked))
		end,
	}
	-- A second instance keeps compact sizing and caption alignment available for direct comparison
	local compact_checkbox = Checkbox {
		name = "compact_checkbox",
		text = "Compact Checkbox",
		compact = true,
		placement = {
			horizontal = "stretch",
			vertical = "center",
		},
		on_change = function(_, checked)
			core.log("Test window compact Checkbox checked=%s", tostring(checked))
		end,
	}
	-- A textual group identifier binds these choices without a separate group object
	local radio_group = title .. ".sample_mode"
	local first_radio = Radio {
		name = "first_radio",
		group = radio_group,
		text = "First Radio choice",
		checked = true,
		placement = {
			horizontal = "stretch",
			vertical = "center",
		},
		on_change = function(_, checked)
			if checked then
				core.log("Test window selected the first Radio choice")
			end
		end,
	}
	local second_radio = Radio {
		name = "second_radio",
		group = radio_group,
		text = "Second Radio choice",
		placement = {
			horizontal = "stretch",
			vertical = "center",
		},
		on_change = function(_, checked)
			if checked then
				core.log("Test window selected the second Radio choice")
			end
		end,
	}
	-- Enough entries make pointer, wheel, and every navigation key directly testable
	local mode_listbox = Listbox {
		name = "mode_listbox",
		width = 300,
		height = 148,
		items = {
			{ text = "Plain text", value = "text", data = { id = 101 } },
			{ text = "Markdown", value = "markdown", data = { id = 102 } },
			{ text = "Read-only text", value = "view", data = { id = 103 } },
			{ text = "Unavailable preview", value = "preview", enabled = false, data = { id = 104 } },
			{ text = "Raw bytes", value = "bytes", data = { id = 105 } },
			{ text = "Hexadecimal", value = "hex", data = { id = 106 } },
			{ text = "Extracted document text", value = "extract", data = { id = 107 } },
			{ text = "Image preview", value = "image", data = { id = 108 } },
		},
		selected = "markdown",
		placement = {
			horizontal = "stretch",
			vertical = "stretch",
		},
		on_change = function(_, value, item)
			local changed, change_error = listbox_status:set_text(
				"Selected mode: " .. tostring(value) .. " | Data ID: " .. tostring(item.data.id))
			if not changed then
				core.error("Window Listbox status change failed: %s", tostring(change_error))
			end
		end,
	}
	-- This compact field exercises an anchored Listbox that can cross every Form and Pane above it
	local mode_combobox = Combobox {
		name = "mode_combobox",
		width = 300,
		items = {
			{ text = "Plain text", value = "text", data = { id = 201 } },
			{ text = "Markdown", value = "markdown", data = { id = 202 } },
			{ text = "Read-only text", value = "view", data = { id = 203 } },
			{ text = "Unavailable preview", value = "preview", enabled = false, data = { id = 204 } },
			{ text = "Raw bytes", value = "bytes", data = { id = 205 } },
			{ text = "Hexadecimal", value = "hex", data = { id = 206 } },
			{ text = "Extracted document text", value = "extract", data = { id = 207 } },
			{ text = "Image preview", value = "image", data = { id = 208 } },
			{ text = "Font preview", value = "font", data = { id = 209 } },
		},
		selected = "markdown",
		placement = {
			horizontal = "stretch",
			vertical = "center",
		},
		on_change = function(_, value, item)
			local changed, change_error = combobox_status:set_text(
				"Dropdown mode: " .. tostring(value) .. " | Data ID: " .. tostring(item.data.id))
			if not changed then
				core.error("Window Combobox status change failed: %s", tostring(change_error))
			end
		end,
	}
	-- Branches and leaves each retain their own application data while Tree handles only presentation state
	local sample_tree = Tree {
		name = "sample_tree",
		height = 138,
		items = {
			{
				text = "Workspace",
				value = "workspace",
				expanded = true,
				data = { id = 301, kind = "root" },
				children = {
					{
						text = "Documents",
						value = "documents",
						expanded = true,
						data = { id = 302, kind = "folder" },
						children = {
							{ text = "Notes.txt", value = "notes", data = { id = 303, kind = "file" } },
							{ text = "Plan.md", value = "plan", data = { id = 304, kind = "file" } },
						},
					},
					{
						text = "Images",
						value = "images",
						data = { id = 305, kind = "folder" },
						children = {
							{ text = "Cover.png", value = "cover", data = { id = 306, kind = "file" } },
							{ text = "Icon.svg", value = "icon", data = { id = 307, kind = "file" } },
						},
					},
					{ text = "Unavailable item", enabled = false, data = { id = 308, kind = "file" } },
				},
			},
		},
		selected = "workspace",
		placement = {
			horizontal = "stretch",
			vertical = "stretch",
		},
		on_change = function(_, _, node)
			local changed, change_error = tree_status:set_text(
				"Tree selection: " .. node.text .. " | Data ID: " .. tostring(node.data.id))
			if not changed then
				core.error("Window Tree status change failed: %s", tostring(change_error))
			end
		end,
	}
	-- This generated source represents millions of possible descendants without building them in advance
	local virtual_nodes = {}
	local virtual_node_count = 0
	local function virtual_node(parent, index)
		local id = (parent and parent.id .. "." or "") .. tostring(index)
		local node = virtual_nodes[id]
		if not node then
			node = {
				id = id,
				depth = parent and parent.depth + 1 or 0,
				parent = parent,
			}
			virtual_nodes[id] = node
			virtual_node_count = virtual_node_count + 1
		end

		return node
	end
	local sample_vtree = VirtualTree {
		name = "sample_vtree",
		height = 138,
		root_count = function()
			return 100000
		end,
		child_count = function(node)
			return node.depth < 3 and 100000 or 0
		end,
		child = virtual_node,
		text = function(node)
			return node.depth == 0 and "Virtual root " .. node.id or "Generated node " .. node.id
		end,
		has_children = function(node)
			return node.depth < 3
		end,
		placement = {
			horizontal = "stretch",
			vertical = "stretch",
		},
		on_change = function(_, node)
			local changed, change_error = tree_status:set_text(
				"Virtual selection: " .. node.id .. " | Materialized: " .. tostring(virtual_node_count))
			if not changed then
				core.error("Window VirtualTree status change failed: %s", tostring(change_error))
			end
		end,
	}
	local controls_heading = Label {
		name = "controls_heading",
		text = "Reusable Control laboratory",
		placement = {
			horizontal = "left",
			vertical = "center",
		},
	}
	-- Reusable surfaces divide the laboratory without becoming layout containers themselves
	local heading_panel = Panel {
		name = "heading_panel",
		frame_width = 1,
		placement = {
			horizontal = "stretch",
			vertical = "stretch",
		},
	}
	-- A direct vertical Separator keeps both orientations visible outside the Section helper
	local body_separator = Separator {
		name = "body_separator",
		orientation = "vertical",
	}
	-- Sections group related Controls like modern fieldsets without becoming live Controls themselves
	local input_section = qui.section {
		name = "input_section",
		title = "Input",
		length = "content",
		layout = qui.rows {
			name = "input_section_content",
			gap = 6,

			qui.pane {
				name = "input_edit",
				length = "content",
				controls = { text_input },
			},

			qui.pane {
				name = "input_status_pane",
				length = "content",
				controls = { input_status },
			},
		},
	}
	local choice_section = qui.section {
		name = "choice_section",
		title = "Choices",
		length = "content",
		layout = qui.rows {
			name = "choice_section_content",
			gap = 6,

			qui.pane {
				name = "enable_test_button_pane",
				length = "content",
				controls = { enable_test_button },
			},

			qui.pane {
				name = "compact_checkbox_pane",
				length = "content",
				controls = { compact_checkbox },
			},

			qui.pane {
				name = "first_radio_pane",
				length = "content",
				controls = { first_radio },
			},

			qui.pane {
				name = "second_radio_pane",
				length = "content",
				controls = { second_radio },
			},
		},
	}
	local action_section = qui.section {
		name = "action_section",
		title = "Actions and popup Menu",
		length = "content",
		layout = qui.rows {
			name = "action_section_content",
			gap = 6,

			qui.pane {
				name = "button_state_pane",
				length = "content",
				controls = { button_state_button },
			},

			qui.pane {
				name = "popup_menu_button_pane",
				length = "content",
				controls = { menu_button },
			},

			qui.pane {
				name = "popup_menu_status_pane",
				length = "content",
				controls = { menu_status },
			},
		},
	}
	local listbox_section = qui.section {
		name = "listbox_section",
		title = "Single selection",
		length = "content",
		layout = qui.rows {
			name = "listbox_section_content",
			gap = 6,

			qui.pane {
				name = "mode_listbox_pane",
				height = 148,
				controls = { mode_listbox },
			},

			qui.pane {
				name = "listbox_status_pane",
				length = "content",
				controls = { listbox_status },
			},
		},
	}
	local combobox_section = qui.section {
		name = "combobox_section",
		title = "Dropdown selection",
		length = "content",
		layout = qui.rows {
			name = "combobox_section_content",
			gap = 6,

			qui.pane {
				name = "mode_combobox_pane",
				length = "content",
				controls = { mode_combobox },
			},

			qui.pane {
				name = "combobox_status_pane",
				length = "content",
				controls = { combobox_status },
			},
		},
	}
	local tree_section = qui.section {
		name = "tree_section",
		title = "Nested and virtual data",
		length = "content",
		layout = qui.rows {
			name = "tree_section_content",
			gap = 6,

			qui.pane {
				name = "tree_controls_pane",
				height = 138,
				layout = qui.cols {
					name = "tree_control_columns",
					gap = 8,

					qui.pane {
						name = "sample_tree_pane",
						length = "weighted",
						weight = 1,
						controls = { sample_tree },
					},

					qui.pane {
						name = "sample_vtree_pane",
						length = "weighted",
						weight = 1,
						controls = { sample_vtree },
					},
				},
			},

			qui.pane {
				name = "tree_status_pane",
				length = "content",
				controls = { tree_status },
			},
		},
	}
	-- Both directions share one compact range API while vertical remains the natural default
	local scrollbar_status = Label {
		name = "scrollbar_status",
		text = "Vertical: 30 | Horizontal: 40",
		placement = {
			horizontal = "left",
			vertical = "center",
		},
	}
	local vertical_scrollbar
	local horizontal_scrollbar
	local function update_scrollbar_status()
		local changed, change_error = scrollbar_status:set_text(string.format(
			"Vertical: %.0f | Horizontal: %.0f",
			vertical_scrollbar.value,
			horizontal_scrollbar.value
		))
		if not changed then
			core.error("Window Scrollbar status change failed: %s", tostring(change_error))
		end
	end
	vertical_scrollbar = Scrollbar {
		name = "vertical_scrollbar",
		min = 0,
		max = 100,
		value = 30,
		line = 2,
		page = 20,
		height = 76,
		placement = {
			horizontal = "center",
			vertical = "stretch",
		},
		on_change = update_scrollbar_status,
	}
	horizontal_scrollbar = Scrollbar {
		name = "horizontal_scrollbar",
		horizontal = true,
		min = 0,
		max = 100,
		value = 40,
		line = 2,
		page = 25,
		placement = {
			horizontal = "stretch",
			vertical = "center",
		},
		on_change = update_scrollbar_status,
	}
	local scrollbar_section = qui.section {
		name = "scrollbar_section",
		title = "Scrolling",
		length = "content",
		layout = qui.cols {
			name = "scrollbar_section_columns",
			gap = 10,

			qui.pane {
				name = "vertical_scrollbar_pane",
				width = 16,
				controls = { vertical_scrollbar },
			},

			qui.pane {
				name = "horizontal_scrollbar_area",
				length = "weighted",
				weight = 1,
				layout = qui.rows {
					name = "horizontal_scrollbar_rows",
					gap = 6,

					qui.pane {
						name = "scrollbar_status_pane",
						length = "content",
						controls = { scrollbar_status },
					},

					qui.pane {
						name = "horizontal_scrollbar_pane",
						length = "content",
						controls = { horizontal_scrollbar },
					},
				},
			},
		},
	}

	-- The embedded Form owns this Control while its native Window presents it above both Forms
	local embedded_form
	local overlay_visible = false
	local overlay_definition
	overlay_definition = qui.control {
		name = "window_overlay",
		accepts_pointer = true,
		draw = function(_, control_canvas)
			local width, height = control_canvas:size()

			control_canvas:fill_rect(0, 0, width, height, { 48, 39, 30, 248 })
			control_canvas:fill_rect(0, 0, width, 4, { 231, 166, 75, 255 })
			control_canvas:fill_rect(0, math.max(0, height - 4), width, 4, { 231, 166, 75, 255 })
			control_canvas:fill_rect(0, 0, 4, height, { 231, 166, 75, 255 })
			control_canvas:fill_rect(math.max(0, width - 4), 0, 4, height, { 231, 166, 75, 255 })
		end,
		event = function(_, event)
			if event.kind ~= "pointer_down" or event.button ~= "left" then
				return nil
			end

			local hidden, hide_error = embedded_form:hide_overlay(overlay_definition)
			if not hidden then
				core.error("Window overlay close failed: %s", tostring(hide_error))
				return { handled = true }
			end
			overlay_visible = false

			return { handled = true, redraw = true }
		end,
	}

	-- Construct the child first so the parent can declare the complete Form tree in one operation
	local embedded_error
	embedded_form, embedded_error = qui.form {
		name = title .. " embedded",
		overlays = { overlay_definition },
		layout = qui.rows {
			gap = 8,
			padding_left = 8,
			padding_top = 8,
			padding_right = 8,
			padding_bottom = 8,

			qui.pane {
				name = "embedded_heading",
				length = "content",
				controls = { embedded_label },
			},

			qui.pane {
				name = "embedded_surface",
				length = "weighted",
				weight = 1,
				controls = { side_definition },
			},

			qui.pane {
				name = "embedded_action",
				length = "content",
				controls = { embedded_button },
			},
		},
	}

	if not embedded_form then
		return nil, embedded_error
	end

	-- Rows and Cols remain Layouts, while every ordered child is visibly a Pane declaration
	local built_form, build_error = qui.form {
		name = title,
		commands = { toggle_button_command },
		initial_focus = text_input,
		overlays = { popup_menu },
		on_close_request = function()
			core.log("Test Form accepted its native close request")
			return true
		end,
		layout = qui.rows {
			gap = 12,
			padding_left = 12,
			padding_top = 12,
			padding_right = 12,
			padding_bottom = 12,

			qui.pane {
				name = "metrics",
				length = "content",
				controls = { metrics_status },
			},

			qui.pane {
				name = "body",
				length = "weighted",
				weight = 1,
				layout = qui.cols {
					name = "body_columns",
					gap = 12,

					qui.pane {
						name = "surface",
						width = 480,
						layout = qui.rows {
							name = "surface_rows",
							gap = 8,

							qui.pane {
								name = "surface_canvas",
								length = "weighted",
								weight = 1,
								controls = { definition },
							},

							-- Window structure tests use the empty space below the drawing surface
							qui.pane {
								name = "structure_utilities",
								length = "content",
								layout = qui.cols {
									name = "structure_utility_columns",
									gap = 8,

									qui.pane {
										name = "toggle_right_action",
										length = "content",
										controls = { toggle_button },
									},

									qui.pane {
										name = "toggle_embedded_action",
										length = "content",
										controls = { toggle_embedded_button },
									},

									qui.pane {
										name = "toggle_overlay_action",
										length = "content",
										controls = { toggle_overlay_button },
									},
								},
							},

							-- General window tests form a second compact row at the far left
							qui.pane {
								name = "window_utilities",
								length = "content",
								layout = qui.cols {
									name = "window_utility_columns",
									gap = 8,

									qui.pane {
										name = "switch_theme_action",
										length = "content",
										controls = { theme_button },
									},

									qui.pane {
										name = "confirmation_action",
										length = "content",
										controls = { confirmation_button },
									},

									qui.pane {
										name = "close_form_action",
										length = "content",
										controls = { close_button },
									},
								},
							},
						},
					},

					qui.pane {
						name = "body_separator_pane",
						length = "content",
						controls = { body_separator },
					},

					qui.pane {
						name = "control_laboratory",
						length = "weighted",
						weight = 1,
						layout = qui.rows {
							name = "control_laboratory_rows",
							gap = 10,
							padding_left = 12,
							padding_top = 12,
							padding_right = 12,
							padding_bottom = 12,

							qui.pane {
								name = "controls_heading_pane",
								length = "content",
								controls = { heading_panel, controls_heading },
							},

							qui.pane {
								name = "control_laboratory_columns",
								length = "weighted",
								weight = 2,
								layout = qui.cols {
									name = "control_laboratory_column_layout",
									gap = 12,

									-- Established controls remain in reading order down the first column
									qui.pane {
										name = "control_laboratory_left",
										length = "weighted",
										weight = 1,
										layout = qui.rows {
											name = "control_laboratory_left_rows",
											gap = 10,

											input_section,
											choice_section,
											combobox_section,
											listbox_section,

											qui.pane {
												name = "control_laboratory_left_filler",
												length = "weighted",
												weight = 1,
											},
										},
									},

									-- Newer and taller controls continue at the top of the second column
									qui.pane {
										name = "control_laboratory_right",
										length = "weighted",
										weight = 1,
										layout = qui.rows {
											name = "control_laboratory_right_rows",
											gap = 10,

											tree_section,
											scrollbar_section,
											action_section,

											qui.pane {
												name = "control_laboratory_right_filler",
												length = "weighted",
												weight = 1,
											},
										},
									},
								},
							},
						},
					},

					qui.pane {
						name = "right",
						width = 360,
						collapsed = true,
						form = embedded_form,
					},
				},
			},

			qui.pane {
				name = "utilities",
				length = "content",
				controls = { side_status },
			},
		},
	}

	if not built_form then
		local destroyed, destroy_error = embedded_form:destroy()
		if not destroyed then
			build_error = tostring(build_error) .. "; child cleanup failed: " .. tostring(destroy_error)
		end

		return nil, build_error
	end
	built_form.embedded_form = embedded_form
	built_form.metrics_status = metrics_status
	built_form.metric_button = toggle_button
	built_form.metric_textbox = text_input
	built_form.metric_checkbox = enable_test_button
	built_form.metric_compact_checkbox = compact_checkbox

	-- This Button visibly exercises both live operations after construction-time attachment
	local embedded_form_attached = true
	local function toggle_embedded_form()
		local changed, change_error
		if embedded_form_attached then
			if overlay_visible then
				local hidden, hide_error = embedded_form:hide_overlay(overlay_definition)
				if not hidden then
					core.error("Window overlay close failed: %s", tostring(hide_error))
					return false
				end
				overlay_visible = false
			end
			changed, change_error = embedded_form:detach()
		else
			changed, change_error = embedded_form:attach(built_form.panes.right)
		end

		if not changed then
			core.error("Embedded Form attachment change failed: %s", tostring(change_error))
			return false
		end

		embedded_form_attached = not embedded_form_attached
		core.log("Test window embedded Form attached=%s", tostring(embedded_form_attached))
		return true
	end
	toggle_embedded_button.on_click = toggle_embedded_form

	-- Both the visible Button and 'win:toggle-right' use exactly the same state change
	local right_pane_visible = false
	local function toggle_right()
		if right_pane_visible and overlay_visible then
			local hidden, hide_error = embedded_form:hide_overlay(overlay_definition)
			if not hidden then
				core.error("Window overlay close failed: %s", tostring(hide_error))
				return false
			end
			overlay_visible = false
		end
		right_pane_visible = not right_pane_visible
		local changed, change_error = pane.set_collapsed(
			built_form.handle,
			built_form.panes.right,
			not right_pane_visible
		)

		if not changed then
			right_pane_visible = not right_pane_visible
			core.error("Window right Pane toggle failed: %s", tostring(change_error))
			return false
		end

		local status_changed, status_error = side_status:set_text(
			right_pane_visible and "Side Pane: visible" or "Side Pane: hidden"
		)
		if not status_changed then
			core.error("Window side status change failed: %s", tostring(status_error))
			return false
		end

		core.log("Test window right Pane visible=%s", tostring(right_pane_visible))
		return true
	end

	toggle_button.on_click = toggle_right
	--- Show an embedded Form's Control across both Form boundaries, or close it for reuse
	local function toggle_overlay()
		if overlay_visible then
			local hidden, hide_error = embedded_form:hide_overlay(overlay_definition)
			if not hidden then
				core.error("Window overlay close failed: %s", tostring(hide_error))
				return false
			end
			overlay_visible = false

			return true
		end

		if not embedded_form_attached then
			core.error("Attach the embedded Form before opening its overlay")
			return false
		end
		if not right_pane_visible and not toggle_right() then
			return false
		end

		local shown, show_error = embedded_form:show_overlay(overlay_definition, {
			x = -260,
			y = 52,
			width = 420,
			height = 180,
		})
		if not shown then
			core.error("Window overlay open failed: %s", tostring(show_error))
			return false
		end
		overlay_visible = true

		return true
	end

	toggle_overlay_button.on_click = toggle_overlay
	--- Exercise programmatic Form completion from inside the Button callback
	close_button.on_click = function()
		local closed, close_error = built_form:close("button")

		if not closed then
			core.error("Window Form close failed: %s", tostring(close_error))
			return false
		end

		return true
	end
	built_form.toggle_right = toggle_right
	built_form.confirmation_button = confirmation_button

	return built_form
end

--- Remove one ID from the local test-window history
-- @param window_id number stable Lx window ID
local function forget_window(window_id)
	-- Search backwards so removal does not disturb entries still left to inspect
	for index = #opened_window_ids, 1, -1 do
		if opened_window_ids[index] == window_id then
			table.remove(opened_window_ids, index)
		end
	end

	opened_forms[window_id] = nil
	opened_right_panes[window_id] = nil
	opened_right_toggles[window_id] = nil
end

--- Destroy the utility form retained for one window
-- @param window_id number stable Lx window ID
local function destroy_window_form(window_id)
	local attached_form = opened_forms[window_id]
	local embedded_form = attached_form and attached_form.embedded_form

	if attached_form and attached_form:is_valid() then
		attached_form:destroy()
	end
	-- Direct parent destruction detaches a child, while normal Window completion already destroys it
	if embedded_form and embedded_form:is_valid() then
		embedded_form:destroy()
	end

	opened_forms[window_id] = nil
end

--- Redraw one utility window with a size-responsive test canvas
-- @param window_id number stable Lx window ID
function window_test.redraw(window_id)
	local attached_form = opened_forms[window_id]
	local info = get_window_info(window_id)
	if attached_form and attached_form.metrics_status and info then
		local changed, change_error = attached_form.metrics_status:set_text(string.format(
			"%d x %d DIP | %d x %d px | Scale %.2f | Density %.2f | Font 14 DIP | Padding T %dx%d, B %dx%d | Checkbox %d/%d +%d DIP",
			info.width,
			info.height,
			info.pixel_width,
			info.pixel_height,
			info.display_scale,
			info.pixel_density,
			attached_form.metric_textbox.padding_x,
			attached_form.metric_textbox.padding_y,
			attached_form.metric_button.padding_x,
			attached_form.metric_button.padding_y,
			attached_form.metric_checkbox.indicator_size,
			attached_form.metric_compact_checkbox.indicator_size,
			attached_form.metric_checkbox.indicator_gap
		))
		if not changed then
			core.error("Window metrics display failed for %s: %s", tostring(window_id), tostring(change_error))
			return false
		end
	end

	local rendered, err = window.invalidate(window_id)

	if not rendered then
		core.error("Window redraw failed for %s: %s", tostring(window_id), tostring(err))
		return false
	end

	return true
end

--- Toggle the optional right Pane without rebuilding either Control
-- @param window_id number stable Lx window ID
function window_test.toggle_right(window_id)
	local attached_form = opened_forms[window_id]
	local side_pane = opened_right_panes[window_id]
	local toggle_right = opened_right_toggles[window_id]

	if not attached_form or not side_pane or not toggle_right
		or not attached_form:is_valid() or not pane.is_valid(attached_form.handle, side_pane)
	then
		core.error("No live right Pane belongs to test window %s", tostring(window_id))
		return false
	end

	return toggle_right()
end

--- Open one visible modeless utility window
function window_test.open()
	-- Create the complete form first so the window never observes a half-built design
	local title = string.format("Lx Window Test %d", next_window_number)
	local built_form, build_error = create_test_form(title)

	if not built_form then
		core.error("Window test Form failed: %s", tostring(build_error))
		return false
	end

	local window_id
	-- Remove native-close and programmatic-close state after the Form has finalized
	built_form.on_complete = function(_, result)
		local embedded_form = built_form.embedded_form
		-- An attached child is already completed child-first; a manually detached child still needs cleanup
		if embedded_form and embedded_form:is_valid() then
			local destroyed, destroy_error = embedded_form:destroy()
			if not destroyed then
				core.error("Detached embedded Form cleanup failed: %s", tostring(destroy_error))
			end
		end

		if window_id then
			forget_window(window_id)
			core.log("Closed test window %d with result '%s'", window_id, tostring(result))
		else
			core.log("Test Form completed with result '%s' while Window opening was rolled back", tostring(result))
		end
	end

	local err
	window_id, err = built_form:open_window {
		title = title,
		width = 1400,
		height = 920,
		resizable = true,
	}

	if not window_id then
		local embedded_form = built_form.embedded_form
		if built_form:is_valid() then
			built_form:destroy()
		end
		if embedded_form and embedded_form:is_valid() then
			embedded_form:destroy()
		end
		core.error("Window test open failed: %s", tostring(err))
		return false
	end

	next_window_number = next_window_number + 1
	opened_window_ids[#opened_window_ids + 1] = window_id
	opened_forms[window_id] = built_form
	opened_right_panes[window_id] = built_form.panes.right
	opened_right_toggles[window_id] = built_form.toggle_right
	built_form.confirmation_button.on_click = function()
		-- A complete Form changes structure, so build it after this Button traversal returns
		local accepted, defer_error = qui.defer(function()
			open_confirmation(window_id)
		end)
		if not accepted then
			core.error("Confirmation request failed: %s", tostring(defer_error))
			return false
		end

		return true
	end

	core.log("Opened test window %d", window_id)

	if window_test.redraw(window_id) then
		return true
	end

	-- False open result must not retain successfully created window
	local closed, close_error = built_form:close("redraw_failed")
	if closed then
		return false
	end

	core.error("Window %d remains open after redraw cleanup failed: %s", window_id, tostring(close_error))
	return true
end

--- Close one test window by stable ID
-- @param window_id number stable Lx window ID
function window_test.close(window_id)
	local attached_form = opened_forms[window_id]
	local closed, err
	if attached_form and attached_form:is_valid() then
		closed, err = attached_form:close("command")
	else
		closed, err = window.close(window_id)
	end

	if not closed then
		core.error("Window test close failed for %s: %s", tostring(window_id), tostring(err))
		return false
	end

	return true
end

--- Close the newest test window that still exists
function window_test.close_last()
	-- Skip IDs for windows already closed through another command or the native close button
	while #opened_window_ids > 0 do
		local window_id = opened_window_ids[#opened_window_ids]
		local attached_form = opened_forms[window_id]
		local closed, err
		if attached_form and attached_form:is_valid() then
			closed, err = attached_form:close("command")
		else
			closed, err = window.close(window_id)
		end

		if closed then
			forget_window(window_id)
			return true
		end

		if err ~= "window does not exist" then
			core.error("Window test close failed for %s: %s", tostring(window_id), tostring(err))
			return false
		end

		destroy_window_form(window_id)
		forget_window(window_id)
	end

	core.warning("No test window remains open")
	return true
end

--- Log all windows currently owned by the native manager
function window_test.list()
	local windows = window.list()

	if #windows == 0 then
		core.log("No managed windows")
		return true
	end

	core.log("Managed windows:")
	for _, info in ipairs(windows) do
		core.log(
			"  id=%d native=%d main=%s visible=%s size=%dx%d DIP pixels=%dx%d scale=%.2f density=%.2f title=%q",
			info.id,
			info.native_id,
			tostring(info.is_main),
			tostring(info.visible),
			info.width,
			info.height,
			info.pixel_width,
			info.pixel_height,
			info.display_scale,
			info.pixel_density,
			info.title
		)
	end

	return true
end

return window_test
