-- Unreal Realms OT - client_terminal (Nekiro)
-- Fix: terminal input focus (can type), close with X and ESC.
-- No accents.

local terminalWindow
local terminalButton
local closeButton
local escBinded = false

local function getInput()
  if not terminalWindow then return nil end
  return terminalWindow:recursiveGetChildById("commandTextEdit")
end

local function hideTerminal()
  if terminalWindow and terminalWindow:isVisible() then
    terminalWindow:hide()
  end
end

local function focusInput()
  local input = getInput()
  if input then
    input:focus()
    input:setCursorPos(-1)
  end
end

local function toggle()
  if not terminalWindow then return end

  if terminalWindow:isVisible() then
    hideTerminal()
    return
  end

  terminalWindow:show()
  terminalWindow:raise()
  terminalWindow:focus()

  -- Critical: focus the text edit, otherwise Nekiro keeps keyboard on game.
  focusInput()
end

local function ensureCloseButton()
  if not terminalWindow then return end

  closeButton = terminalWindow:recursiveGetChildById("closeButton")
  if closeButton then
    closeButton.onClick = hideTerminal
    return
  end

  closeButton = g_ui.createWidget("Button", terminalWindow)
  closeButton:setId("closeButton")
  closeButton:setText("X")
  closeButton:setWidth(24)
  closeButton:setHeight(24)
  closeButton:addAnchor(AnchorTop, "parent", AnchorTop)
  closeButton:addAnchor(AnchorRight, "parent", AnchorRight)
  closeButton:setMarginTop(4)
  closeButton:setMarginRight(4)
  closeButton.onClick = hideTerminal
end

local function bindEsc()
  if escBinded then return end
  if not g_keyboard or not g_keyboard.bindKeyDown then return end
  escBinded = true

  pcall(function()
    g_keyboard.bindKeyDown("Escape", function()
      hideTerminal()
    end, terminalWindow)
  end)
end

function init()
  terminalWindow = g_ui.displayUI("terminal")
  if not terminalWindow then
    if g_logger and g_logger.warning then
      g_logger.warning("client_terminal: terminal.otui not found, disabling terminal module.")
    end
    return
  end

  terminalWindow:hide()
  ensureCloseButton()
  bindEsc()

  -- When the terminal is clicked, force focus back to the input.
  terminalWindow.onMousePress = function()
    focusInput()
    return false
  end

  if modules and modules.client_topmenu and modules.client_topmenu.addLeftGameButton then
    terminalButton = modules.client_topmenu.addLeftGameButton(
      "terminalButton",
      tr("Terminal"),
      "/images/topbuttons/terminal",
      toggle
    )
  end
end

function terminate()
  if closeButton then closeButton:destroy(); closeButton = nil end
  if terminalWindow then terminalWindow:destroy(); terminalWindow = nil end
  if terminalButton then terminalButton:destroy(); terminalButton = nil end
end
