Error with GUI page handler

Hello, could someone please help me with this script?
This script is intended to manage the page of an “index” of badges a player is on.
It works regularly, except when on the third page and the back button is pressed, it jumps back to the first page even though pagenumber, the variable that is used to find the page the player is on should have still been 2 (It needs to have been 3 for the third frame to be visible)

Thank you for reading this, any help is very appreciated!

local player = game.Players.LocalPlayer

local screengui = player.PlayerGui.ScreenGui

local backbutton = screengui.BackButton

local forwardbutton = screengui.ForwardButton

local pagenumber = 1

local page1 = screengui.Index

local page2 = screengui.Index2

local page3 = screengui.Index3

forwardbutton.MouseButton1Click:Connect(function()

if pagenumber < 3 then

pagenumber = pagenumber + 1

if pagenumber == 1 then

page1.Visible = true

page2.Visible = false

page3.Visible = false

elseif pagenumber == 2 then

page1.Visible = false

page2.Visible = true

page3.Visible = false

elseif pagenumber == 3 then

page1.Visible = false

page2.Visible = false

page3.Visible = true

end

end

backbutton.MouseButton1Click:Connect(function()

if pagenumber > 1 then

pagenumber = pagenumber - 1

if pagenumber == 1 then

page1.Visible = true

page2.Visible = false

page3.Visible = false

elseif pagenumber == 2 then

page1.Visible = false

page2.Visible = true

page3.Visible = false

elseif pagenumber == 3 then

page1.Visible = false

page2.Visible = false

page3.Visible = true

end

end

end)

end)

It seems like the issue is that the pagenumber variable is not being updated correctly when the BackButton is pressed on the third page. One potential solution is to set the pagenumber variable to the correct value whenever a page is made visible.

local player = game.Players.LocalPlayer
local screengui = player.PlayerGui.ScreenGui
local backbutton = screengui.BackButton
local forwardbutton = screengui.ForwardButton
local pagenumber = 1
local page1 = screengui.Index
local page2 = screengui.Index2
local page3 = screengui.Index3


local function goToPage(pageNum)
    pagenumber = pageNum
    page1.Visible = pageNum == 1
    page2.Visible = pageNum == 2
    page3.Visible = pageNum == 3
end

forwardbutton.MouseButton1Click:Connect(function()
    if pagenumber < 3 then
        goToPage(pagenumber + 1)
    end
end)

backbutton.MouseButton1Click:Connect(function()
    if pagenumber > 1 then
        goToPage(pagenumber - 1)
    end
end)


goToPage(1)

The pagenumber would not update because you somehow “?” forgot to set the pagenumber, this is what I meant :

-- For the forwardbutton, it should be
pagenumber += 1
goToPage(pagenumber)

-- For the backbutton, it should be
pagenumber -= 1
goToPage(pagenumber)