-- lx-bundle:true

-- Fast document scrolling commands (10% jumps by default)

local core = require("core")
local command = require("core.command")
local keymap = require("core.keymap")
local config = require("core.config")

-- Fraction of full scroll range per fast-scroll step
config.fastscroll_step_fraction = config.fastscroll_step_fraction or 0.05

-- Return the currently active document-backed view
local function get_active_document_view()
	local active_view = core.active_view
	if not active_view or not active_view.doc then
		return nil
	end
	return active_view
end

local function fastscroll(delta_sign)
	local active_view = get_active_document_view()
	if not active_view then
		return
	end

	local max_scroll = math.max(0, active_view:get_scrollable_size() - active_view.size.y)
	if max_scroll <= 0 then
		return
	end

	local current = active_view.scroll.to.y or active_view.scroll.y or 0
	local line_height = (active_view.get_line_height and math.max(1, active_view:get_line_height())) or 1
	-- Scroll by % of full range, with at least one-line movement
	local step_fraction = config.fastscroll_step_fraction or 0.05
	local step_px = math.max(line_height, max_scroll * step_fraction)
	-- Fastscroll must never be slower than regular wheel scrolling
	local wheel_px = config.mouse_wheel_scroll or 0
	if config.mouse_wheel_scroll_lines and active_view.get_line_height then
		wheel_px = line_height * config.mouse_wheel_scroll_lines
	end
	step_px = math.max(step_px, wheel_px)
	local target = current + delta_sign * step_px
	local clamped = math.max(0, math.min(max_scroll, target))

	-- Instant movement for fastscroll semantics
	active_view.scroll.to.y = clamped
	active_view.scroll.y = clamped
end

command.add({
	["doc:fastscroll-up"] = {
		requires = { "doc", "scroll" },
		perform = function()
			fastscroll(-1)
		end,
	},
	["doc:fastscroll-down"] = {
		requires = { "doc", "scroll" },
		perform = function()
			fastscroll(1)
		end,
	},
})

-- Default wheel bindings (can be overridden in user/settings.lua)
keymap.add({
	["ctrl+alt+wheelup"] = "doc:fastscroll-up",
	["ctrl+alt+wheeldown"] = "doc:fastscroll-down",
})
