PumpsHavePropaneMenu = {}

PumpsHavePropaneMenu.OnContextMenu = function(player, context, worldobjects)
    local playerObj = getSpecificPlayer(player)
    if not playerObj then return end

    -- 1. Шукаємо колонку, на яку клікнули (або поруч)
    local pump = nil
    for _, obj in ipairs(worldobjects) do
        if obj:getPipedFuelAmount() > 0 then
            pump = obj
            break
        end
    end

    if not pump then return end
    
    -- 2. Перевіряємо дистанцію
    if pump:getSquare():DistToProper(playerObj) > 3.5 then return end

    local playerInv = playerObj:getInventory()
    local items = playerInv:getItems()
    
    -- Прапори, щоб не дублювати пункти меню
    local addedTankOption = false
    local addedTorchOption = false

    for i = 0, items:size() - 1 do
        local item = items:get(i)
        local typeLower = string.lower(item:getFullType())

        -- Логіка для БАЛОНА
        if not addedTankOption and string.find(typeLower, "propanetank") then
            -- Перевіряємо, чи не повний він (візуально)
            local isFull = false
            if item.getUsedDelta and item:getUsedDelta() >= 0.99 then isFull = true end
            
            if not isFull then
                context:addOptionOnTop(getText("ContextMenu_TakePropaneFromPump"), item, PumpsHavePropaneMenu.OnFillAction, playerObj, pump, false)
                addedTankOption = true
            end
        
        -- Логіка для ПАЯЛЬНОЇ ЛАМПИ
        elseif not addedTorchOption and string.find(typeLower, "blowtorch") then
            local isFull = false
            if item.getUsedDelta and item:getUsedDelta() >= 0.99 then isFull = true end
            
            if not isFull then
                context:addOptionOnTop(getText("ContextMenu_FillTorchFromPump"), item, PumpsHavePropaneMenu.OnFillAction, playerObj, pump, true)
                addedTorchOption = true
            end
        end
        
        if addedTankOption and addedTorchOption then break end
    end
end

PumpsHavePropaneMenu.OnFillAction = function(item, playerObj, pump, isTorch)
    local duration = 100
    if isTorch then duration = 50 end
    
    if luautils.walkToObject(playerObj, pump, false) then
        ISTimedActionQueue.add(PumpsHavePropane_Action:new(pump, item, playerObj, duration, isTorch))
    end
end

Events.OnFillWorldObjectContextMenu.Add(PumpsHavePropaneMenu.OnContextMenu)