---@diagnostic disable: duplicate-set-field
-- lx-bundle:true

local common = require("core.common")
local DocView = require("core.text.editor")

local _original_on_mouse_down = DocView.on_mouse_down
local _original_on_mouse_move = DocView.on_mouse_move
local _original_on_mouse_up = DocView.on_mouse_up

function DocView:on_mouse_down(button, x, y, clicks)
	-- Let the shared doc-view zoom reset win before middle-drag panning starts
	if self:try_middle_click_zoom_reset(button) then
		return true
	end

	if button == "middle" then
		self._mclickpan = {
			x = x,
			y = y,
		}
		self.mouse_selecting = nil
		self.blink_timer = 0
		return true
	end
	return _original_on_mouse_down(self, button, x, y, clicks)
end

function DocView:on_mouse_move(x, y, dx, dy)
	local pan = self._mclickpan
	if pan then
		local dx = x - pan.x
		local dy = y - pan.y
		pan.x = x
		pan.y = y

		local max_x = self:get_scroll_max_x()
		local cur_x = self.scroll.to.x or self.scroll.x or 0
		local cur_y = self.scroll.to.y or self.scroll.y or 0
		local target_x = common.clamp(cur_x - dx, 0, max_x)
		local target_y = math.max(0, cur_y - dy)
		local max_y = self:get_scroll_max_y()
		target_y = common.clamp(target_y, 0, max_y)

		self.scroll.to.x = target_x
		self.scroll.to.y = target_y
		self.scroll.x = target_x
		self.scroll.y = target_y
		self.mouse_cursor = "arrow"
		return
	end
	return _original_on_mouse_move(self, x, y, dx, dy)
end

function DocView:on_mouse_up(button, x, y)
	if button == "middle" then
		self._mclickpan = nil
	end
	return _original_on_mouse_up(self, button, x, y)
end
