local taskChartWindow = nil
local taskChartEvent  = nil
local sessionKills    = 0
local sessionStart    = 0
local npcTasks        = {}  -- { {taskName, count, max}, ... }
local prevCounts      = {}

local TICK = 10000

-- Intercepta mensagens do formato:
--   "Suas tasks ativas (2/2):"
--   " - Dwarfs: 0/500 (0%)"
local function onNpcTaskMessage(mode, text)
  if not text then return end

  if text:lower():find("tasks ativas") or text:lower():find("active task") then
    npcTasks = {}
    prevCounts = {}
    return
  end

  local name, count, max = text:match("%-%s*([%a%s]+):%s*(%d+)/(%d+)")
  if name and count and max then
    local trimName = name:match("^%s*(.-)%s*$")
    table.insert(npcTasks, {
      taskName = trimName,
      count    = tonumber(count),
      max      = tonumber(max),
    })
    if taskChartWindow and not taskChartWindow:isDestroyed() then
      removeEvent(taskChartEvent)
      buildTaskPanels()
      updateChart()
    end
  end
end

connect(g_game, { onTextMessage = onNpcTaskMessage })

local function getTasksData()
  -- Prioridade 1: bot storage
  local tasker = botStorage and botStorage.caveBotTasker
  if tasker and (tasker.max or 0) > 0 then
    return {{ taskName = tasker.taskName or "?", count = tasker.count or 0, max = tasker.max or 0 }}
  end
  -- Prioridade 2: capturado do NPC
  if #npcTasks > 0 then return npcTasks end
  return {}
end

function buildTaskPanels()
  if not taskChartWindow or taskChartWindow:isDestroyed() then return end
  local container = taskChartWindow.tasksContainer
  container:destroyChildren()

  local tasks = getTasksData()
  if #tasks == 0 then
    taskChartWindow.headerLabel:setText("Nenhuma task ativa")
    return
  end

  taskChartWindow.headerLabel:setText("Tasks ativas: " .. #tasks)

  for i, task in ipairs(tasks) do
    local pct = task.max > 0 and math.min(100, math.floor(task.count / task.max * 100)) or 0

    -- painel de cada task
    local panel = g_ui.createWidget("Panel", container)
    panel:setHeight(46)
    panel:setMarginTop(i == 1 and 0 or 6)

    local nameLabel = g_ui.createWidget("Label", panel)
    nameLabel:setText(task.taskName .. ":  " .. task.count .. " / " .. task.max .. "  (" .. pct .. "%)")
    nameLabel:setHeight(16)
    nameLabel:setTextAlign(AlignCenter)
    nameLabel:setFont("verdana-11px-rounded")
    nameLabel:setColor("#FFFFFF")
    nameLabel:addAnchor(AnchorTop, "parent", AnchorTop)
    nameLabel:addAnchor(AnchorLeft, "parent", AnchorLeft)
    nameLabel:addAnchor(AnchorRight, "parent", AnchorRight)

    local bar = g_ui.createWidget("TaskChartBar", panel)
    bar:setPercent(pct)
    bar:setHeight(18)
    bar:setMarginTop(2)
    bar:setMarginLeft(6)
    bar:setMarginRight(6)
    bar:addAnchor(AnchorTop, "prev", AnchorBottom)
    bar:addAnchor(AnchorLeft, "parent", AnchorLeft)
    bar:addAnchor(AnchorRight, "parent", AnchorRight)

    -- cor da barra: verde se andamento, cinza se zerado
    if pct >= 100 then
      bar:setBackgroundColor("#00AA00")
    elseif pct > 0 then
      bar:setBackgroundColor("#DDAA00")
    else
      bar:setBackgroundColor("#AA0000")
    end
  end
end

local function formatETA(killsPerHour, remaining)
  if killsPerHour <= 0 or remaining <= 0 then return "--" end
  local hours = remaining / killsPerHour
  local h = math.floor(hours)
  local m = math.floor((hours - h) * 60)
  if h > 0 then return h .. "h " .. m .. "m" end
  return m .. "m"
end

function updateChart()
  if not taskChartWindow or taskChartWindow:isDestroyed() then return end

  local tasks = getTasksData()

  -- contabiliza kills da sessao (soma delta de todas as tasks)
  for i, task in ipairs(tasks) do
    local prev = prevCounts[i] or task.count
    local delta = math.max(0, task.count - prev)
    sessionKills = sessionKills + delta
    prevCounts[i] = task.count
  end

  taskChartEvent = scheduleEvent(updateChart, TICK)
end

function toggleTaskChart()
  if taskChartWindow and not taskChartWindow:isDestroyed() then
    closeTaskChart()
    return
  end

  local ok, err = pcall(function()
    npcTasks = {}
    prevCounts = {}
    sessionKills = 0
    sessionStart = g_clock.millis()

    taskChartWindow = g_ui.createWidget("TaskChartWindow", g_ui.getRootWidget())
    taskChartWindow:show()
    taskChartWindow:raise()
    taskChartWindow:focus()

    buildTaskPanels()
    updateChart()

    if g_game.isOnline() then
      g_game.talk("!task")
    end
  end)

  if not ok then
    g_logger.error("[game_bot] toggleTaskChart falhou: " .. tostring(err))
  end
end

function closeTaskChart()
  removeEvent(taskChartEvent)
  taskChartEvent = nil
  if taskChartWindow and not taskChartWindow:isDestroyed() then
    taskChartWindow:destroy()
  end
  taskChartWindow = nil
end
