local monitor = peripheral.find("monitor")
local me = peripheral.find("meBridge")

if not monitor then error("Monitor not found") end
if not me then error("ME Bridge not found") end

monitor.setTextScale(1)

local page = 1
local items = {}
local pageSize = 10
local pageDelay = 5

local function refreshItems()
    local all = me.listItems()
    local grouped = {}

    for _, item in ipairs(all) do
        local name = item.displayName or item.name
        if grouped[name] then
            grouped[name] = grouped[name] + item.amount
        else
            grouped[name] = item.amount
        end
    end

    items = {}
    for name, amount in pairs(grouped) do
        table.insert(items, {
            name = name,
            amount = amount
        })
    end

    table.sort(items, function(a, b)
        return a.name < b.name
    end)
end

local function draw()
    local w, h = monitor.getSize()
    pageSize = h - 5

    local pages = math.max(1, math.ceil(#items / pageSize))
    page = math.min(page, pages)

    monitor.setBackgroundColor(colors.black)
    monitor.clear()

    -- Header
    monitor.setCursorPos(1, 1)
    monitor.setTextColor(colors.cyan)
    monitor.write("  AE2 NETWORK STORAGE")

    monitor.setCursorPos(1, 2)
    monitor.setTextColor(colors.gray)
    monitor.write(string.rep("-", w))

    -- Items
    local first = (page - 1) * pageSize + 1

    for i = 1, pageSize do
        local index = first + i - 1
        local item = items[index]
        local y = i + 2

        if item then
            monitor.setCursorPos(2, y)
            monitor.setTextColor(colors.white)

            local text = item.name
            local maxName = math.max(1, w - 13)

            if #text > maxName then
                text = text:sub(1, maxName - 2) .. ".."
            end

            monitor.write(text)

            monitor.setCursorPos(w - 9, y)
            monitor.setTextColor(colors.lime)
            monitor.write(tostring(item.amount))
        end
    end

    -- Footer
    monitor.setCursorPos(1, h - 1)
    monitor.setTextColor(colors.gray)
    monitor.write(string.rep("-", w))

    monitor.setCursorPos(1, h)
    monitor.setTextColor(colors.yellow)
    monitor.write(" PAGE " .. page .. "/" .. pages)

    monitor.setCursorPos(math.max(1, w - 13), h)
    monitor.setTextColor(colors.lightBlue)
    monitor.write("AUTO SCROLL")
end

while true do
    refreshItems()
    draw()

    sleep(pageDelay)

    local pages = math.max(1, math.ceil(#items / pageSize))
    page = page + 1
    if page > pages then page = 1 end
end
