Why next/previous page system errors by not going to the correct pages

so im creating a system where you can navigate to the previous displayed page and back but it or jumps to much index or infinite create index how could i fix

local layout = script.Parent.Parent.main.UIPageLayout

local main = script.Parent.Parent.main
local index = 0

local previousPageCursors = {}

local page1b = main.home.page1
local page2b = main.home.page2

local function clear()
	print("🟠 clearing table but...")
	
	
	for i = #previousPageCursors, index + 1, -1 do
		warn(i)
		table.remove(previousPageCursors, i)
	end
end

page1b.MouseButton1Click:Connect(function() 
	table.insert(previousPageCursors, layout.CurrentPage)
	index = #previousPageCursors
	layout:JumpTo(main.page1)
	print(previousPageCursors)
	--clear()
end)

page2b.MouseButton1Click:Connect(function()
	table.insert(previousPageCursors, layout.CurrentPage)
	index = #previousPageCursors
	layout:JumpTo(main.page2)
	print(previousPageCursors)
	--clear()
end)

script.Parent.MouseButton1Click:Connect(function() 
	warn("🤔"..index)
	if index >= 1 then
		
		local success, err = pcall(function()
			table.insert(previousPageCursors, layout.CurrentPage)
			layout:JumpTo(previousPageCursors[index])
			print(previousPageCursors)
		end)

		if success then
			index = index - 1	
		end
		
	end
end)

script.Parent.Parent.next.MouseButton1Click:Connect(function() 
	warn("🤔"..index)
	if index >= 0 then
		local success, err = pcall(function()
			table.insert(previousPageCursors, layout.CurrentPage)
			layout:JumpTo(previousPageCursors[index])
			print(previousPageCursors)
		end)

		if success then
			index = index + 1	
		end
	end
end)