-- lx-bundle:true

--- Provide a reusable Lua-owned Checkbox Control
-- @module qui.checkbox

local qui = require("qui")
local Accelerator = require("qui.accelerator")
local colors = require("qui.colors")
local glyphs = require("qui.glyph")
local metrics = require("qui.metrics")
local theme = require("qui.theme")
local Font = require("qui.font")

local Checkbox = {}
local color_flags = setmetatable({}, { __mode = "k" })	-- One reusable flag set follows each live Checkbox table

--- Return a checked non-negative whole DIP value
-- @param value number|nil requested value
-- @param fallback number default value
-- @param name string readable option name
-- @return integer value
local function dip_value(value, fallback, name)
	value = value == nil and fallback or value
	assert(type(value) == "number" and value >= 0 and value < math.huge, name .. " must be a non-negative number")

	return math.floor(value + 0.5)
end

--- Report whether one local point remains inside the arranged Checkbox
-- @param self table Checkbox control
-- @param x number local horizontal position
-- @param y number local vertical position
-- @return boolean inside
local function contains_point(self, x, y)
	return x >= 0 and y >= 0 and x < self.arranged_width and y < self.arranged_height
end

--- Tell application code about one completed value change
-- @param self table Checkbox control
local function notify_change(self)
	if self.on_change then
		self:on_change(self.checked)
	end
end

--- Change checked state, schedule its redraw, and notify only for a real change
-- @param self table Checkbox control
-- @param checked boolean requested state
-- @return boolean|nil changed
-- @return string|nil error_text
local function set_checked(self, checked)
	assert(type(checked) == "boolean", "Checkbox checked state must be a boolean")
	if self.checked == checked then
		return true
	end

	local previous = self.checked
	self.checked = checked
	local invalidated, invalidate_error = self:invalidate()
	if not invalidated then
		self.checked = previous
		return nil, invalidate_error
	end

	notify_change(self)

	return true
end

--- Select one central color identifier for every Checkbox instance
-- @param self table Checkbox control
-- @param type string requested visual type
-- @param flags table current Checkbox conditions
-- @return string color_identifier
function Checkbox.default_color(self, type, flags)
	if type == "background" then
		if flags.grayed then
			return colors.checkbox_disabled_bg
		elseif flags.pressing then
			return colors.checkbox_pressing_bg
		elseif flags.down then
			return colors.checkbox_down_bg
		elseif flags.hovering then
			return colors.checkbox_hover_bg
		end

		return colors.checkbox_bg
	elseif type == "indicator" then
		if flags.grayed then
			return colors.checkbox_disabled_indicator
		end

		return colors.checkbox_indicator
	elseif type == "frame" then
		-- Focus is the stronger state, so moving the pointer over it must not hide the active frame
		if flags.focused then
			return colors.checkbox_focused_frame
		elseif flags.hovering then
			return colors.checkbox_hover_frame
		end

		return colors.checkbox_frame
	elseif type == "checkmark" then
		return flags.grayed and colors.checkbox_disabled_checkmark or colors.checkbox_checkmark
	elseif type == "text" then
		return flags.grayed and colors.checkbox_disabled_text or colors.checkbox_text
	end

	return nil
end

--- Create one Checkbox for use inside 'qui.pane.controls'
-- @param options table text, state, sizing, placement, and optional on_change handler
-- @return table control unrestricted Lua Control declaration
function Checkbox.new(options)
	assert(type(options) == "table", "Checkbox expects a table")
	assert(options.text == nil or type(options.text) == "string", "Checkbox text must be a string")
	assert(options.accelerator == nil, "Checkbox must mark its accelerator with & inside text")
	assert(options.show_accelerators == nil or type(options.show_accelerators) == "boolean",
		"Checkbox show_accelerators must be a boolean")
	assert(options.checked == nil or type(options.checked) == "boolean", "Checkbox checked must be a boolean")
	assert(options.compact == nil or type(options.compact) == "boolean", "Checkbox compact must be a boolean")
	assert(options.on_change == nil or type(options.on_change) == "function", "Checkbox on_change must be a function")
	assert(options.on_color == nil or type(options.on_color) == "function", "Checkbox on_color must be a function")
	assert(options.default_color == nil, "Checkbox default_color is fixed; use on_color for dynamic changes")

	local control = options
	control.text, control.accelerator, control.accelerator_column =
		Accelerator.parse(control.text or "", "Checkbox text")
	control.show_accelerators = control.show_accelerators ~= false
	control.checked = control.checked == true
	control.compact = control.compact == true
	control.font = control.font or (control.compact and Font.compact or Font.default)
	assert(control.font, "Checkbox requires a font")
	control.indicator_size = dip_value(
		control.indicator_size,
		theme.resolve_metric(control.compact and
			metrics.checkbox_compact_indicator_size or metrics.checkbox_indicator_size),
		"Checkbox indicator_size"
	)
	-- Every Checkbox reserves the normal indicator area so compact boxes align without manual offsets
	control.indicator_slot_size = math.max(
		control.indicator_size, theme.resolve_metric(metrics.checkbox_indicator_size))
	control.indicator_gap = dip_value(
		control.indicator_gap, theme.resolve_metric(metrics.checkbox_indicator_gap), "Checkbox indicator_gap")
	-- The Checkbox owns the space between its checkmark and frame; named glyphs remain reusable elsewhere
	control.checkmark_padding = dip_value(
		control.checkmark_padding,
		theme.resolve_metric(metrics.checkbox_checkmark_padding),
		"Checkbox checkmark_padding")
	assert(control.checkmark_padding * 2 < control.indicator_size,
		"Checkbox checkmark_padding must leave room for the checkmark")
	control.text_indent = control.text_indent and dip_value(control.text_indent, 0, "Checkbox text_indent") or nil
	control.width = control.width and dip_value(control.width, 0, "Checkbox width") or nil
	control.height = control.height and dip_value(control.height, 0, "Checkbox height") or nil
	control.enabled = control.enabled ~= false
	control.focusable = control.focusable ~= false
	control.accepts_pointer = control.accepts_pointer ~= false
	control.default_color = Checkbox.default_color
	control.hovered = false
	control.focused = false
	control.pointer_pressed = false
	control.keyboard_pressed = false
	control.arranged_width = control.width or 0
	control.arranged_height = control.height or 0
	color_flags[control] = {
		grayed = not control.enabled,
		down = control.checked,
		pressing = false,
		hovering = false,
		focused = false,
	}

	--- Measure the indicator, optional caption indent, and shaped text
	function control:measure(control_canvas, minimum_width, minimum_height, maximum_width, maximum_height)
		local text_width, text_height = control_canvas:measure_text(self.font, self.text)
		local text_x = self.text_indent or self.indicator_slot_size + (self.text == "" and 0 or self.indicator_gap)
		local natural_width = self.width or math.max(self.indicator_slot_size, text_x + text_width)
		local natural_height = self.height or math.max(self.indicator_slot_size, text_height)
		local width = math.max(minimum_width, math.min(natural_width, maximum_width))
		local height = math.max(minimum_height, math.min(natural_height, maximum_height))

		return width, height
	end

	--- Draw one direct Checkbox without allocating visual child Controls
	function control:draw(control_canvas)
		local width, height = control_canvas:size()
		self.arranged_width = width
		self.arranged_height = height
		local visibly_pressed = (self.pointer_pressed and self.hovered) or self.keyboard_pressed
		local flags = assert(color_flags[self], "Checkbox color flags are unavailable")
		flags.grayed = not self.enabled
		flags.down = self.checked
		flags.pressing = visibly_pressed
		flags.hovering = self.hovered
		flags.focused = self.focused
		-- Center the visible box inside the normal 16-DIP slot on both axes
		local slot_y = math.floor((height - self.indicator_slot_size) / 2)
		local indicator_x = math.floor((self.indicator_slot_size - self.indicator_size) / 2)
		local indicator_y = slot_y + math.floor((self.indicator_slot_size - self.indicator_size) / 2)
		local checkmark_size = self.indicator_size - self.checkmark_padding * 2
		local background = self:get_color("background", flags)
		local indicator = self:get_color("indicator", flags)

		-- Background belongs to the whole Control; the square has its own independently themed interior
		control_canvas:fill_rect(0, 0, width, height, background)
		control_canvas:fill_rect(indicator_x, indicator_y, self.indicator_size, self.indicator_size, indicator)
		if flags.hovering or flags.focused then
			local frame = self:get_color("frame", flags)

			control_canvas:draw_rect(indicator_x, indicator_y, self.indicator_size, self.indicator_size, 1, frame)
		end
		if self.checked then
			control_canvas:draw_glyph(
				glyphs.check,
				indicator_x + self.checkmark_padding,
				indicator_y + self.checkmark_padding,
				checkmark_size,
				checkmark_size,
				self:get_color("checkmark", flags))
		end
		if self.text ~= "" then
			local _, text_height = control_canvas:measure_text(self.font, self.text)
			local text_x = self.text_indent or self.indicator_slot_size + self.indicator_gap
			local text_y = math.floor((height - text_height) / 2)
			local text_color = self:get_color("text", flags)

			control_canvas:draw_text(self.font, self.text, text_x, text_y, text_color)
			if self.show_accelerators then
				Accelerator.draw(
					control_canvas,
					self.font,
					self.text,
					self.accelerator_column,
					text_x,
					text_y,
					text_height,
					text_color
				)
			end
		end
	end

	--- Handle pointer, focus, and Space without taking Return from the containing Form
	function control: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.pointer_pressed = true
			return { handled = true, redraw = true, focus = "acquire", capture = "acquire" }
		elseif event.kind == "pointer_up" and event.button == "left" and self.pointer_pressed then
			self.pointer_pressed = false
			if contains_point(self, event.x, event.y) then
				local changed, change_error = set_checked(self, not self.checked)
				assert(changed, "Checkbox pointer toggle failed: " .. tostring(change_error))
			end

			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.pointer_pressed = false
			self.keyboard_pressed = false
			return { redraw = true, capture = "release" }
		elseif event.kind == "key_down" and event.key == "space" then
			if not event["repeat"] then
				self.keyboard_pressed = true
			end

			return { handled = true, redraw = true }
		elseif event.kind == "key_up" and event.key == "space" then
			local should_toggle = self.keyboard_pressed
			self.keyboard_pressed = false
			if should_toggle then
				local changed, change_error = set_checked(self, not self.checked)
				assert(changed, "Checkbox keyboard toggle failed: " .. tostring(change_error))
			end

			return { handled = true, redraw = true }
		end

		return nil
	end

	--- Change checked state only when the requested value differs
	-- @param checked boolean requested value
	-- @return boolean|nil changed
	-- @return string|nil error_text
	function control:set_checked(checked)
		return set_checked(self, checked)
	end

	--- Reverse the current checked state through the same public change path
	-- @return boolean|nil changed
	-- @return string|nil error_text
	function control:toggle()
		return set_checked(self, not self.checked)
	end

	--- Toggle this Checkbox through the same public path used by Form accelerators
	-- @return boolean|nil activated
	-- @return string|nil error_text
	function control:activate()
		if not self.enabled then
			return false
		end

		return set_checked(self, not self.checked)
	end

	return qui.control(control)
end

-- Callable module syntax keeps declarations readable as 'Checkbox { ... }'
setmetatable(Checkbox, {
	__call = function(_, options)
		return Checkbox.new(options)
	end,
})

return Checkbox
