term.setBackgroundColor(colors.green)

-- Maze size for each difficulty
local difficulties = {
    EASY = {width = 15, height = 15},
    MEDIUM = {width = 26, height = 15},  -- Adjusted width
    HARD = {width = 51, height = 15}     -- Full screen width
}

-- High scores
local highScores = {
    EASY = "--:--:--",
    MEDIUM = "--:--:--",
    HARD = "--:--:--"
}

-- Load high scores from file
local function loadHighScores()
    if fs.exists("savedata/maze_game.txt") then
        local file = fs.open("savedata/maze_game.txt", "r")
        for difficulty, _ in pairs(highScores) do
            highScores[difficulty] = file.readLine() or "--:--:--"
        end
        file.close()
    end
end

-- Save high scores to file
local function saveHighScores()
    local file = fs.open("savedata/maze_game.txt", "w")
    for difficulty, score in pairs(highScores) do
        file.writeLine(score)
    end
    file.close()
end

-- Function to center text
local function centerText(text, y)
    local w, h = term.getSize()
    local x = math.floor((w - #text) / 2)
    term.setCursorPos(x, y)
    term.write(text)
end

-- Function to draw the menu
local function drawMenu()
    term.clear()
    term.setCursorPos(1, 1)
    term.write("High Scores:")
    term.setCursorPos(1, 2)
    term.write("EASY:   " .. highScores.EASY)
    term.setCursorPos(1, 3)
    term.write("MEDIUM: " .. highScores.MEDIUM)
    term.setCursorPos(1, 4)
    term.write("HARD:   " .. highScores.HARD)

    centerText("MAZE GAME", 5)
    centerText("Select Difficulty:", 7)
    centerText("[ EASY ]", 9)
    centerText("[ MEDIUM ]", 11)
    centerText("[ HARD ]", 13)
    centerText("Use arrow keys to select, Enter to start", 15)
end

-- Function to handle menu selection
local function handleMenu()
    local selection = 1
    local options = {"EASY", "MEDIUM", "HARD"}
    
    while true do
        drawMenu()
        term.setCursorPos(1, 9 + (selection - 1) * 2)
        term.write(">")
        
        local event, key = os.pullEvent("key")
        if key == keys.up and selection > 1 then
            selection = selection - 1
        elseif key == keys.down and selection < 3 then
            selection = selection + 1
        elseif key == keys.enter then
            return options[selection]
        end
    end
end

-- Create empty maze
local maze = {}
local width, height, playerX, playerY

-- Recursive backtracker algorithm for maze generation
local function generateMaze(x, y)
    maze[y][x] = 0  -- 0 represents a path
    
    local directions = {{0, -2}, {2, 0}, {0, 2}, {-2, 0}}
    for i = 1, #directions do
        local j = math.random(i, #directions)
        directions[i], directions[j] = directions[j], directions[i]
    end
    
    for _, dir in ipairs(directions) do
        local nextX, nextY = x + dir[1], y + dir[2]
        if nextX > 0 and nextX <= width and nextY > 0 and nextY <= height and maze[nextY][nextX] == 1 then
            maze[y + dir[2]/2][x + dir[1]/2] = 0
            generateMaze(nextX, nextY)
        end
    end
end

-- Function to display the maze
local function displayMaze(difficulty, startTime)
    term.clear()
    for y = 1, height + 2 do  -- Added 2 to height
        for x = 1, width do
            term.setCursorPos(x, y)
            if y > height or maze[y][x] == 1 then
                term.setBackgroundColor(colors.green)
                term.write(string.char(160))
            elseif maze[y][x] == 3 then
                term.setBackgroundColor(colors.yellow)
                term.write(string.char(160))
            elseif x == playerX and y == playerY then
                term.setBackgroundColor(colors.red)
                term.write(string.char(160))
            else
                term.setBackgroundColor(colors.black)
                term.write(" ")
            end
        end
    end

    
    -- Reset text color
    term.setTextColor(colors.white)
    
    -- Display help in bottom-right corner
    local w, h = term.getSize()
    term.setCursorPos(w - 29, 18)
    term.write("ARROW KEYS - control the player")
    term.setCursorPos(w - 29, 17)
    term.write("Q - exit the game")
    
    -- Display difficulty, time, and high score
    local currentTime = os.clock() - startTime
    local timeString = string.format("%02d:%02d:%02d", 
        math.floor(currentTime / 3600),
        math.floor(currentTime % 3600 / 60),
        math.floor(currentTime % 60))
    
    term.setCursorPos(1, 17)
    term.write("Difficulty: " .. difficulty)
    term.setCursorPos(1, 18)
    term.write("Time: " .. timeString)
    term.setCursorPos(1, 19)
    term.write("High Score: " .. highScores[difficulty])
end

-- Function to find a random empty cell
local function findRandomEmptyCell()
    local emptyCells = {}
    for y = 1, height do
        for x = 1, width do
            if maze[y][x] == 0 then
                table.insert(emptyCells, {x = x, y = y})
            end
        end
    end
    return emptyCells[math.random(#emptyCells)]
end

-- Main game loop
local function playMaze(difficulty)
    local startCell = findRandomEmptyCell()
    playerX, playerY = startCell.x, startCell.y
    local startTime = os.clock()
    
    while true do
        displayMaze(difficulty, startTime)
        local event, key = os.pullEvent("key")
        local newX, newY = playerX, playerY
        
        if key == keys.up then
            newY = playerY - 1
        elseif key == keys.down then
            newY = playerY + 1
        elseif key == keys.left then
            newX = playerX - 1
        elseif key == keys.right then
            newX = playerX + 1
        elseif key == keys.q then
            break
        end
        
        if maze[newY][newX] ~= 1 then
            playerX, playerY = newX, newY
        end
        
        if maze[playerY][playerX] == 3 then
            local endTime = os.clock()
            local timeTaken = string.format("%02d:%02d:%02d", 
                math.floor(endTime - startTime) / 3600,
                math.floor((endTime - startTime) % 3600) / 60,
                math.floor(endTime - startTime) % 60)
            
            term.clear()
            centerText("Congratulations! You reached the end!", math.floor(height/2))
            centerText("Time: " .. timeTaken, math.floor(height/2) + 2)
            
            -- Update high score if better
            if timeTaken < highScores[difficulty] or highScores[difficulty] == "--:--:--" then
                highScores[difficulty] = timeTaken
                saveHighScores()
                centerText("New high score!", math.floor(height/2) + 4)
            end
            
            os.sleep(3)
            break
        end
    end
end

-- Main program loop
while true do
    loadHighScores()
    local difficulty = handleMenu()
    width, height = difficulties[difficulty].width, difficulties[difficulty].height
    
    -- Generate the maze
    maze = {}
    for y = 1, height do
        maze[y] = {}
        for x = 1, width do
            maze[y][x] = 1  -- 1 represents a wall
        end
    end
    math.randomseed(os.time())
    generateMaze(2, 2)
    
    -- Set end point
    maze[height-1][width-1] = 3  -- 3 represents the end
    
    playMaze(difficulty)
end
