local mainPanel
local buttons = {}

local function toggleWidget(widget)
  if not widget then return end
  if widget:isVisible() then
    widget:hide()
  else
    widget:show()
    widget:raise()
  end
end

local function findFirst(names)
  for _, name in ipairs(names) do
    local w = rootWidget:recursiveGetChildById(name)
    if w then return w end
  end
  return nil
end

function init()
  connect(g_game, {
    onGameStart = refresh,
    onGameEnd = refresh
  })

  mainPanel = g_ui.loadUI('game_interface_upgrade.otui', modules.game_interface.getRootPanel())
  if mainPanel then
    mainPanel:hide()
  end

  refresh()
end

function terminate()
  disconnect(g_game, {
    onGameStart = refresh,
    onGameEnd = refresh
  })

  buttons = {}

  if mainPanel then
    mainPanel:destroy()
    mainPanel = nil
  end
end

function refresh()
  if not mainPanel then return end
  if g_game.isOnline() then
    mainPanel:show()
  else
    mainPanel:hide()
  end
end

function toggleInventory()
  toggleWidget(findFirst({'inventoryWindow', 'inventory'}))
end

function toggleSkills()
  toggleWidget(findFirst({'skillsWindow', 'skills'}))
end

function toggleBattle()
  toggleWidget(findFirst({'battleWindow', 'battleList'}))
end

function toggleVip()
  toggleWidget(findFirst({'vipWindow', 'vipList'}))
end

function toggleOptions()
  toggleWidget(findFirst({'optionsWindow', 'options'}))
end

function toggleHotkeys()
  toggleWidget(findFirst({'hotkeysWindow', 'hotkeys'}))
end
