-- Etapa 18: gerenciador leve de notificações.
-- Não substitui mensagens do servidor. É uma camada visual opcional.
local NotificationManager = {
  active = {},
  maxActive = 5,
  defaultDuration = 3000
}

local function removeEntry(entry)
  for i, item in ipairs(NotificationManager.active) do
    if item == entry then
      table.remove(NotificationManager.active, i)
      break
    end
  end
  if entry.widget and entry.widget.destroy then
    entry.widget:destroy()
  end
end

function NotificationManager.clear()
  for _, entry in ipairs(NotificationManager.active) do
    if entry.event then
      removeEvent(entry.event)
    end
    if entry.widget and entry.widget.destroy then
      entry.widget:destroy()
    end
  end
  NotificationManager.active = {}
end

function NotificationManager.push(widget, duration)
  if not widget then return end

  while #NotificationManager.active >= NotificationManager.maxActive do
    local first = table.remove(NotificationManager.active, 1)
    if first.event then
      removeEvent(first.event)
    end
    if first.widget and first.widget.destroy then
      first.widget:destroy()
    end
  end

  local entry = { widget = widget }
  table.insert(NotificationManager.active, entry)

  entry.event = scheduleEvent(function()
    removeEntry(entry)
  end, duration or NotificationManager.defaultDuration)
end

return NotificationManager
