-- Auto Hunt: auto-heal, auto-potion (mana) and auto-loot
-- Settings are configured per-character in-game (Ctrl+Alt+A to open).

AutoHunt = {}

local settings = {
    healEnabled = false,
    healPercent = 60,
    healSpell = '',

    manaEnabled = false,
    manaPercent = 30,
    manaPotionId = 0,

    lootEnabled = false,
    lootRadius = 1,
    lootBackpackSlot = 3, -- CONST_SLOT_BACKPACK
}

local healEvent, manaEvent, lootEvent
local lootedPositions = {}
local hutWindow

local function setButtonState(button, enabled)
    if not button then return end
    button:setText(enabled and 'ON' or 'OFF')
    if enabled then
        button:setColor('#3ddc57')
    else
        button:setColor('#dc3d3d')
    end
end

local function settingsKey(field)
    local player = g_game.getLocalPlayer()
    local charName = player and player:getName() or 'default'
    return 'autohunt_' .. charName .. '_' .. field
end

local function loadSettings()
    settings.healEnabled = g_settings.getBoolean(settingsKey('healEnabled')) or false
    settings.healPercent = g_settings.getInteger(settingsKey('healPercent'))
    if settings.healPercent == 0 then settings.healPercent = 60 end
    settings.healSpell = g_settings.getString(settingsKey('healSpell')) or ''

    settings.manaEnabled = g_settings.getBoolean(settingsKey('manaEnabled')) or false
    settings.manaPercent = g_settings.getInteger(settingsKey('manaPercent'))
    if settings.manaPercent == 0 then settings.manaPercent = 30 end
    settings.manaPotionId = g_settings.getInteger(settingsKey('manaPotionId')) or 0

    settings.lootEnabled = g_settings.getBoolean(settingsKey('lootEnabled')) or false
end

local function saveSettings()
    g_settings.set(settingsKey('healEnabled'), settings.healEnabled)
    g_settings.set(settingsKey('healPercent'), settings.healPercent)
    g_settings.set(settingsKey('healSpell'), settings.healSpell)

    g_settings.set(settingsKey('manaEnabled'), settings.manaEnabled)
    g_settings.set(settingsKey('manaPercent'), settings.manaPercent)
    g_settings.set(settingsKey('manaPotionId'), settings.manaPotionId)

    g_settings.set(settingsKey('lootEnabled'), settings.lootEnabled)
    g_settings.save()
end

local function isSafeToAct()
    local player = g_game.getLocalPlayer()
    return g_game.isOnline() and player and not player:isDead()
end

-- Auto-heal
local function checkHeal()
    if settings.healEnabled and settings.healSpell ~= '' and isSafeToAct() then
        local player = g_game.getLocalPlayer()
        if player:getHealthPercent() <= settings.healPercent then
            g_game.talk(settings.healSpell)
        end
    end
    healEvent = scheduleEvent(checkHeal, 500)
end

-- Auto mana potion
local function checkMana()
    if settings.manaEnabled and settings.manaPotionId > 0 and isSafeToAct() then
        local player = g_game.getLocalPlayer()
        if player:getManaPercent() <= settings.manaPercent then
            g_game.useInventoryItem(settings.manaPotionId)
        end
    end
    manaEvent = scheduleEvent(checkMana, 1000)
end

-- Auto-loot: scans nearby ground tiles for container items (corpses) and
-- moves their contents into the player's backpack.
local function lootContainer(item)
    g_game.open(item, nil)
    scheduleEvent(function()
        local container = g_game.getContainer(0)
        if not container then
            return
        end
        for slot, containerItem in pairs(container:getItems()) do
            g_game.move(containerItem, {x = 65535, y = settings.lootBackpackSlot, z = 0}, containerItem:getCount())
        end
        scheduleEvent(function()
            g_game.close(container)
        end, 300)
    end, 200)
end

local function checkLoot()
    if settings.lootEnabled and isSafeToAct() then
        local player = g_game.getLocalPlayer()
        local playerPos = player:getPosition()

        for dx = -settings.lootRadius, settings.lootRadius do
            for dy = -settings.lootRadius, settings.lootRadius do
                local pos = {x = playerPos.x + dx, y = playerPos.y + dy, z = playerPos.z}
                local tile = g_map.getTile(pos)
                if tile then
                    for _, item in ipairs(tile:getItems()) do
                        if item:isContainer() then
                            local key = string.format('%d,%d,%d,%d', pos.x, pos.y, pos.z, item:getId())
                            if not lootedPositions[key] then
                                lootedPositions[key] = true
                                lootContainer(item)
                            end
                        end
                    end
                end
            end
        end
    end
    lootEvent = scheduleEvent(checkLoot, 700)
end

-- Settings window
local function refreshWindow()
    if not hutWindow then return end
    hutWindow:getChildById('healSpellEdit'):setText(settings.healSpell)
    hutWindow:getChildById('healPercentEdit'):setText(tostring(settings.healPercent))
    hutWindow:getChildById('manaPotionIdEdit'):setText(settings.manaPotionId > 0 and tostring(settings.manaPotionId) or '')
    hutWindow:getChildById('manaPercentEdit'):setText(tostring(settings.manaPercent))

    setButtonState(hutWindow:getChildById('healToggleButton'), settings.healEnabled)
    setButtonState(hutWindow:getChildById('manaToggleButton'), settings.manaEnabled)
    setButtonState(hutWindow:getChildById('lootToggleButton'), settings.lootEnabled)
end

local function onSave()
    settings.healSpell = hutWindow:getChildById('healSpellEdit'):getText()
    settings.healPercent = tonumber(hutWindow:getChildById('healPercentEdit'):getText()) or 60

    settings.manaPotionId = tonumber(hutWindow:getChildById('manaPotionIdEdit'):getText()) or 0
    settings.manaPercent = tonumber(hutWindow:getChildById('manaPercentEdit'):getText()) or 30

    saveSettings()
    modules.game_textmessage.displayGameMessage('Auto Hunt: configurações salvas.')
    hutWindow:hide()
end

local function onToggleHeal()
    settings.healEnabled = not settings.healEnabled
    setButtonState(hutWindow:getChildById('healToggleButton'), settings.healEnabled)
    saveSettings()
end

local function onToggleMana()
    settings.manaEnabled = not settings.manaEnabled
    setButtonState(hutWindow:getChildById('manaToggleButton'), settings.manaEnabled)
    saveSettings()
end

local function onToggleLoot()
    settings.lootEnabled = not settings.lootEnabled
    setButtonState(hutWindow:getChildById('lootToggleButton'), settings.lootEnabled)
    saveSettings()
end

local function onSearchItem()
    if modules.game_cyclopedia and modules.game_cyclopedia.Cyclopedia then
        modules.game_cyclopedia.Cyclopedia.openTab('items')
    else
        modules.game_textmessage.displayGameMessage('Cyclopedia não disponível neste client/servidor.')
    end
end

function AutoHunt.toggleWindow()
    if not hutWindow then
        hutWindow = g_ui.displayUI('autohunt')
        hutWindow:getChildById('saveButton').onClick = onSave
        hutWindow:getChildById('closeButton').onClick = function() hutWindow:hide() end
        hutWindow:getChildById('healToggleButton').onClick = onToggleHeal
        hutWindow:getChildById('manaToggleButton').onClick = onToggleMana
        hutWindow:getChildById('lootToggleButton').onClick = onToggleLoot
        hutWindow:getChildById('itemSearchButton').onClick = onSearchItem
    end

    if hutWindow:isVisible() then
        hutWindow:hide()
    else
        refreshWindow()
        hutWindow:show()
        hutWindow:raise()
        hutWindow:focus()
    end
end

local quickButton

function AutoHunt.init()
    loadSettings()
    g_keyboard.bindKeyDown('Ctrl+Alt+A', AutoHunt.toggleWindow)

    local parent = modules.game_interface and modules.game_interface.getRootPanel()
    if parent then
        quickButton = g_ui.createWidget('CyclopediaQuickButton', parent)
        quickButton:setId('autoHuntCyclopediaButton')
        quickButton:addAnchor(AnchorTop, 'parent', AnchorTop)
        quickButton:addAnchor(AnchorRight, 'parent', AnchorRight)
        quickButton:setMarginTop(4)
        quickButton:setMarginRight(4)
        quickButton.onClick = onSearchItem
    end

    checkHeal()
    checkMana()
    checkLoot()

    connect(g_game, { onGameStart = loadSettings })
end

function AutoHunt.terminate()
    g_keyboard.unbindKeyDown('Ctrl+Alt+A')

    removeEvent(healEvent)
    removeEvent(manaEvent)
    removeEvent(lootEvent)

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

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

connect(g_game, { onGameEnd = function() lootedPositions = {} end })
