-- lx-bundle:true

--- ANSI viewer commands
-- Keep ANSI navigation and bindings owned by the ANSI surface
-- @module core.ansi.commands

local core = require("core")
local command = require("core.command")
local keymap = require("core.keymap")
local AnsiViewer = require("core.ansi.viewer")

--- Return the active ANSI viewer for explicit viewer-owned commands
-- @return table active_view current ANSI viewer
local function active_ansi_view()
	return core.active_view
end

-- Keep ANSI navigation explicit and surface-owned during the context migration
command.add({
	-- Scroll one ANSI row upward
	["ansi-viewer:line-up"] = {
		requires = { "ansi_viewer" },
		perform = function()
			AnsiViewer.scroll_by(active_ansi_view(), -AnsiViewer.get_line_height())
			return true
		end,
	},

	-- Scroll one ANSI row downward
	["ansi-viewer:line-down"] = {
		requires = { "ansi_viewer" },
		perform = function()
			AnsiViewer.scroll_by(active_ansi_view(), AnsiViewer.get_line_height())
			return true
		end,
	},

	-- Scroll one ANSI page upward
	["ansi-viewer:page-up"] = {
		requires = { "ansi_viewer" },
		perform = function()
			local active_view = active_ansi_view()
			AnsiViewer.scroll_page_by(active_view, -AnsiViewer.get_page_scroll_delta(active_view))
			return true
		end,
	},

	-- Scroll one ANSI page downward
	["ansi-viewer:page-down"] = {
		requires = { "ansi_viewer" },
		perform = function()
			local active_view = active_ansi_view()
			AnsiViewer.scroll_page_by(active_view, AnsiViewer.get_page_scroll_delta(active_view))
			return true
		end,
	},

	-- Jump to the top of the ANSI view
	["ansi-viewer:home"] = {
		requires = { "ansi_viewer" },
		perform = function()
			AnsiViewer.scroll_to_ratio(active_ansi_view(), 0)
			return true
		end,
	},

	-- Jump to the bottom of the ANSI view
	["ansi-viewer:end"] = {
		requires = { "ansi_viewer" },
		perform = function()
			AnsiViewer.scroll_to_ratio(active_ansi_view(), 1)
			return true
		end,
	},
})

-- Keep ANSI navigation keys local to the ANSI surface context
keymap.add({
	["up"] = "ansi-viewer:line-up",
	["down"] = "ansi-viewer:line-down",
	["pageup"] = "ansi-viewer:page-up",
	["pagedown"] = "ansi-viewer:page-down",
	["home"] = "ansi-viewer:home",
	["end"] = "ansi-viewer:end",
	["ctrl+home"] = "ansi-viewer:home",
	["ctrl+end"] = "ansi-viewer:end",
}, {
	context = "ansi_viewer"
})
