-- Unreal Realms - Module Manager (safe, minimal)
-- Opens a simple window listing modules and allowing reload.
-- No accents.

local window
local textBox

local function buildList()
  if not textBox then return end
  local mods = g_modules.getModules() or {}
  local names = {}
  for _, m in pairs(mods) do
    table.insert(names, m:getName())
  end
  table.sort(names)

  local lines = {}
  for _, name in ipairs(names) do
    local m = g_modules.getModule(name)
    local state = (m and m:isLoaded()) and 'loaded' or 'not loaded'
    table.insert(lines, string.format('%s  -  %s', name, state))
  end
  textBox:setText(table.concat(lines, '\n'))
end

function init()
  g_ui.importStyle('modulemanager.otui')
  window = g_ui.displayUI('modulemanager')
  window:hide()

  textBox = window:getChildById('modulesText')

  window:getChildById('btnRefresh').onClick = function()
    buildList()
  end

  window:getChildById('btnReloadAll').onClick = function()
    local mods = g_modules.getModules() or {}
    local names = {}
    for _, m in pairs(mods) do
      table.insert(names, m:getName())
    end
    table.sort(names)
    for _, name in ipairs(names) do
      local m = g_modules.getModule(name)
      if m and m:isLoaded() then
        pcall(function() m:reload() end)
      end
    end
    buildList()
  end

  window:getChildById('btnClose').onClick = function()
    toggle(false)
  end

  buildList()
end

function terminate()
  if window then
    window:destroy()
    window = nil
  end
  textBox = nil
end

function toggle(force)
  if not window then return end
  local show = force
  if show == nil then
    show = not window:isVisible()
  end
  if show then
    buildList()
    window:show()
    window:raise()
    window:focus()
  else
    window:hide()
  end
end
