Professionally optimize code, improve code, reduce the number of lines, structure code, format code, remove unnecessary calculations or condition checks.
```lua
local ev = require("lib.samp.events")
local imgui = require('mimgui')
local encoding = require('encoding')

encoding.default = 'CP1251'
local u8 = encoding.UTF8
local new = imgui.new

local startTime = os.time();
local statusBar = ''

local status = {
    ['len'] = 0,
    ['cotton'] = 0,
    ['total'] = 0,
    ['circle'] = 0
}

local sc = {
    menu = new.bool(),
    status = new.bool(),
    active_bot = new.bool(),
    pause_bot = new.bool(),
    collection = new.int(3),
    circle_status = new.int(1),
    circle_len = new.int(0),
    circle_cotton = new.int(0),
    circle_route = new.int(10)
}

local menu = imgui.OnFrame(
    function() return sc.menu[0] end,
    function(player)

        if sc.circle_route[0] < 1 or sc.circle_len[0] < 1 or sc.circle_cotton[0] < 1 then
            sc.circle_route[0] = 1; sc.circle_len[0] = 1; sc.circle_cotton[0] = 1;
        end

        local sizeX, sizeY = getScreenResolution()
		imgui.SetNextWindowPos(imgui.ImVec2(sizeX / 2, sizeY / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
        imgui.SetNextWindowSize(imgui.ImVec2(300, 318), imgui.Cond.FirstUseEver)

		imgui.Begin(u8"Linen & Cotton", sc.menu, imgui.WindowFlags.NoResize + imgui.WindowFlags.NoCollapse)
            imgui.PushFont(font16)

            imgui.CenterTextColoredRGB('Что собирать боту?')
            if sc.collection[0] == 1 then
                if imgui.AnimButton(u8'Лён', imgui.ImVec2(-1, 24)) then
                    sc.collection[0] = 2
                end
            elseif sc.collection[0] == 2 then
                if imgui.AnimButton(u8'Хлопок', imgui.ImVec2(-1, 24)) then
                    sc.collection[0] = 3
                end
            elseif sc.collection[0] == 3 then
                if imgui.AnimButton(u8'Лён и Хлопок', imgui.ImVec2(-1, 24)) then
                    sc.collection[0] = 1
                end
            end

            imgui.CenterTextColoredRGB('Тип кругов и количество кругов')
            imgui.PushItemWidth(-1)
            if sc.circle_status[0] == 1 then
                if imgui.AnimButton(u8'Количество кругов', imgui.ImVec2(-1, 24)) then
                    sc.circle_status[0] = 2
                end
                imgui.InputInt(u8'##circle1', sc.circle_route, 1, 1)
            elseif sc.circle_status[0] == 2 then
                if imgui.AnimButton(u8'Количество льна', imgui.ImVec2(-1, 24)) then
                    sc.circle_status[0] = 3
                end
                imgui.InputInt(u8'##circle2', sc.circle_len, 1, 1)
            elseif sc.circle_status[0] == 3 then
                if imgui.AnimButton(u8'Количество хлопка', imgui.ImVec2(-1, 24)) then
                    sc.circle_status[0] = 1
                end
                imgui.InputInt(u8'##circle3', sc.circle_cotton, 1, 1)
            end
            imgui.PopItemWidth()

            imgui.NewLine()

            if not sc.active_bot[0] then
                if imgui.AnimButton(u8'Запустить бота', imgui.ImVec2(-1, 24)) then
                    sc.active_bot[0] = true; sc.status[0] = true;
                    startTime = os.time()
                    msg('Бот начал роботу.')
                end
            else
                if imgui.AnimButton(u8'Остановить бота', imgui.ImVec2(-1, 24)) then
                    sc.active_bot[0] = false; sc.status[0] = false
                    msg('Бот остановлен.')
                end
            end

            imgui.BeginChild(u8'##authours', imgui.ImVec2(-1, 70), true)
                imgui.CenterTextColoredRGB('Автор бота: Scar')
                imgui.CenterTextColoredRGB('Fix bot by Lirik')
            imgui.EndChild()

            imgui.PopFont()
        imgui.End()
    end
)

local statusMenu = imgui.OnFrame(
    function() return sc.status[0] end,
    function(player)

        local sizeX, sizeY = getScreenResolution()
		imgui.SetNextWindowPos(imgui.ImVec2((sizeX / 2) + 300, sizeY / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
        imgui.SetNextWindowSize(imgui.ImVec2(200, 200), imgui.Cond.FirstUseEver)

        player.HideCursor = true

		imgui.Begin(u8"##status", sc.menu, imgui.WindowFlags.NoResize + imgui.WindowFlags.NoCollapse + imgui.WindowFlags.NoTitleBar)
            imgui.PushFont(font16)

                imgui.CenterTextColoredRGB('Статистика')

                imgui.Separator()
                
                if sc.circle_status[0] == 1 then
                    imgui.CenterTextColoredRGB('Пройдено кругов: '..status['circle']..' из '..sc.circle_route[0])
                    imgui.CenterTextColoredRGB('Количество льна: '..status['len'])
                    imgui.CenterTextColoredRGB('Количество хлопка: '..status['cotton'])
                    imgui.CenterTextColoredRGB('Общее количество: '..status['total'])
                elseif sc.circle_status[0] == 2 then
                    imgui.CenterTextColoredRGB('Собрано льна: '..status['len']..' из '..sc.circle_len[0])
                    imgui.CenterTextColoredRGB('Количество льна: '..status['len'])
                    imgui.CenterTextColoredRGB('Количество хлопка: '..status['cotton'])
                    imgui.CenterTextColoredRGB('Общее количество: '..status['total'])
                elseif sc.circle_status[0] == 3 then
                    imgui.CenterTextColoredRGB('Собрано хлопка: '..status['cotton']..' из '..sc.circle_cotton[0])
                    imgui.CenterTextColoredRGB('Количество льна: '..status['len'])
                    imgui.CenterTextColoredRGB('Количество хлопка: '..status['cotton'])
                    imgui.CenterTextColoredRGB('Общее количество: '..status['total'])
                end
            imgui.Separator()
            imgui.CenterTextColoredRGB('Статус бота: '..statusBar)
            imgui.Separator()
            imgui.CenterTextColoredRGB('Прошло время: '..TimeWork(os.time() - startTime))

            imgui.PopFont()
        imgui.End()
    end
)

local function getNearGardenBed()
    local near = {distance = 999, id, position = {}};

    for text3D = 1, 2048 do
        if sampIs3dTextDefined(text3D) then
            local text, color, posX, posY, posZ, distance, ignoreWalls, playerId, vehicleId = sampGet3dTextInfoById(text3D)
            local pos = {getCharCoordinates(PLAYER_PED)}
            local dist = getDistanceBetweenCoords3d(pos[1], pos[2], pos[3], posX, posY, posZ)
            if (string.find(text, "Для сбора урожая")) then
                if (string.find(text, 'Лён') and sc.collection[0] == 1) then
                    if (near.distance > dist) then
                        near.id = text3D;
                        near.distance = dist;
                        near.position = {x = posX, y = posY, z = posZ};
                    end
                elseif (string.find(text, 'Хлопок') and sc.collection[0] == 2) then
                    if (near.distance > dist) then
                        near.id = text3D;
                        near.distance = dist;
                        near.position = {x = posX, y = posY, z = posZ};
                    end
                elseif (string.find(text, 'Для сбора урожая') and sc.collection[0] == 3) then
                    if (near.distance > dist) then
                        near.id = text3D;
                        near.distance = dist;
                        near.position = {x = posX, y = posY, z = posZ};
                    end
                end
            end
        end
    end

    return near;
end

function main()
    repeat wait(0) until isSampAvailable()

    sampRegisterChatCommand('ferma', function() sc.menu[0] = not sc.menu[0] end)

    while true do wait(0)

        if not sc.active_bot[0] then
            status['len'] = 0; status['cotton'] = 0; status['total'] = 0; status['circle'] = 0; sc.status[0] = false;
        end

        if sc.active_bot[0] then

            if sc.circle_status[0] == 1 and status['circle'] == sc.circle_route[0] then
                sc.active_bot[0] = false
                msg('Бот выключен, пройдено '..status['circle']..' из '..sc.circle_route[0]..' кругов.')
            elseif sc.circle_status[0] == 2 and status['len'] == sc.circle_len[0] then
                sc.active_bot[0] = false
                msg('Бот выключен, собрано льна '..status['len']..' из '..sc.circle_len[0]..' кругов.')
            elseif sc.circle_status[0] == 3 and status['cotton'] == sc.circle_cotton[0] then
                sc.active_bot[0] = false
                msg('Бот выключен, собрано хлопка '..status['cotton']..' из '..sc.circle_cotton[0]..' кругов.')
            end

            local garden_bed = getNearGardenBed();

            if (garden_bed.distance ~= 999) then
                runToPoint(garden_bed.position.x, garden_bed.position.y, garden_bed.position.z, {sprint = true, jump = true});
                setGameKeyState(21, 255);
                wait(100);
                sampForceOnfootSync();
            else
                statusBar = 'Ожидание куста'
            end
        end
    end
end

function runToPoint(x, y, z, config)
    config = config or {};
    while (sc.active_bot[0] and not locateCharAnyMeans2d(PLAYER_PED, x, y, config["radius"] or 2, config["radius"] or 2)) do
        setAngle(x, y); wait(0);
        setGameKeyState(1, -255)
        
        statusBar = 'Бегу к кусту'

        lua_thread.create(function()
            drawRoute(x, y, z)
            Draw3DCircle(x, y, z, 4, 0xFF37ff57)
        end)

        local pX, pY, pZ = getCharCoordinates(PLAYER_PED)
        local distance = getDistanceBetweenCoords3d(x, y, z, pX, pY, pZ);
        if (config["sprint"] and distance > 2) then 
            setGameKeyState(16, 255)
        end

        if (config["jump"]) then 
            local rand = math.random(0, 9999999);
            if rand >= 9909999 then
                setGameKeyState(16, 0);
                setGameKeyState(14, 255);
            end
        end

        if distance < (config['radius'] or 3) then
            status['circle'] = status['circle'] + 1
            statusBar = 'Собираю куст'
            break
        end
    end
end

function setAngle(X, Y)
    local cX, cY, cZ = getActiveCameraCoordinates()
    setCameraPositionUnfixed(0.0, (getHeadingFromVector2d(X - cX, Y - cY) - 90.0) / 57.2957795)
end

function drawRoute(coordX, coordY, coorZ)
    if isPointOnScreen(coordX, coordY, coorZ, 9999) then
        local x1, y1 = convert3DCoordsToScreen(getCharCoordinates(1))
        local x2, y2 = convert3DCoordsToScreen(coordX, coordY, coorZ)
        renderDrawPolygon(x1, y1, 8, 8, 16, 0.0, 0xFFe80074)
        renderDrawLine(x1, y1, x2, y2, 3, 0xFF00c9c6)
        renderDrawPolygon(x2, y2, 8, 8, 16, 0.0, 0xFFe80074)
    end
end

function Draw3DCircle(x, y, z, radius, color) -- by MrCreepTon
    local screen_x_line_old, screen_y_line_old;

    for rot=0, 360 do
        local rot_temp = math.rad(rot)
        local lineX, lineY, lineZ = radius * math.cos(rot_temp) + x, radius * math.sin(rot_temp) + y, z
        local screen_x_line, screen_y_line = convert3DCoordsToScreen(lineX, lineY, lineZ)
        if screen_x_line ~=nil and screen_x_line_old ~= nil and isPointOnScreen(lineX, lineY, lineZ, 1) then renderDrawLine(screen_x_line, screen_y_line, screen_x_line_old, screen_y_line_old, 3, color) end
        screen_x_line_old, screen_y_line_old = screen_x_line, screen_y_line
    end
end

function ev.onDisplayGameText(style, time, text)
    if sc.active_bot[0] then
        if text:find('linen %+ %d+') then
            status['len'] = status['len'] + text:match('linen %+ (%d+)')
            status['total'] = status['total'] + 1
        elseif text:find('cotton %+ %d+') then
            status['cotton'] = status['cotton'] + text:match('cotton %+ (%d+)')
            status['total'] = status['total'] + 1
        end
    end
end

function themeOne() -- theme by Chapo
    imgui.SwitchContext()
    local style = imgui.GetStyle()
    local colors = style.Colors
    local clr = imgui.Col
    local ImVec4 = imgui.ImVec4
    local ImVec2 = imgui.ImVec2

    colors[clr.Text]                   = ImVec4(1.00, 1.00, 1.00, 1.00)
    colors[clr.TextDisabled]           = ImVec4(0.28, 0.30, 0.35, 1.00)
    colors[clr.WindowBg]               = ImVec4(0.16, 0.18, 0.22, 1.00)
    colors[clr.ChildBg]                = ImVec4(0.19, 0.22, 0.26, 1.00)
    colors[clr.PopupBg]                = ImVec4(0.05, 0.05, 0.10, 1.00)
    colors[clr.Border]                 = ImVec4(0.41, 0.55, 0.78, 1.00)
    colors[clr.BorderShadow]           = ImVec4(0.00, 0.00, 0.00, 0.00)
    colors[clr.FrameBg]                = ImVec4(0.19, 0.22, 0.26, 1.00)
    colors[clr.FrameBgHovered]         = ImVec4(0.22, 0.25, 0.30, 1.00)
    colors[clr.FrameBgActive]          = ImVec4(0.22, 0.25, 0.29, 1.00)
    colors[clr.TitleBg]                = ImVec4(0.19, 0.22, 0.26, 1.00)
    colors[clr.TitleBgActive]          = ImVec4(0.19, 0.22, 0.26, 1.00)
    colors[clr.TitleBgCollapsed]       = ImVec4(0.19, 0.22, 0.26, 0.59)
    colors[clr.MenuBarBg]              = ImVec4(0.19, 0.22, 0.26, 1.00)
    colors[clr.ScrollbarBg]            = ImVec4(0.20, 0.25, 0.30, 0.60)
    colors[clr.ScrollbarGrab]          = ImVec4(0.41, 0.55, 0.78, 1.00)
    colors[clr.ScrollbarGrabHovered]   = ImVec4(0.49, 0.63, 0.86, 1.00)
    colors[clr.ScrollbarGrabActive]    = ImVec4(0.49, 0.63, 0.86, 1.00)
    colors[clr.CheckMark]              = ImVec4(0.90, 0.90, 0.90, 0.50)
    colors[clr.SliderGrab]             = ImVec4(1.00, 1.00, 1.00, 0.30)
    colors[clr.SliderGrabActive]       = ImVec4(0.80, 0.50, 0.50, 1.00)
    colors[clr.Button]                 = ImVec4(0.41, 0.55, 0.78, 1.00)
    colors[clr.ButtonHovered]          = ImVec4(0.49, 0.62, 0.85, 1.00)
    colors[clr.ButtonActive]           = ImVec4(0.49, 0.62, 0.85, 1.00)
    colors[clr.Header]                 = ImVec4(0.19, 0.22, 0.26, 1.00)
    colors[clr.HeaderHovered]          = ImVec4(0.22, 0.24, 0.28, 1.00)
    colors[clr.HeaderActive]           = ImVec4(0.22, 0.24, 0.28, 1.00)
    colors[clr.Separator]              = ImVec4(0.41, 0.55, 0.78, 1.00)
    colors[clr.SeparatorHovered]       = ImVec4(0.41, 0.55, 0.78, 1.00)
    colors[clr.SeparatorActive]        = ImVec4(0.41, 0.55, 0.78, 1.00)
    colors[clr.ResizeGrip]             = ImVec4(0.05, 0.05, 0.10, 0.90)
    colors[clr.ResizeGripHovered]      = ImVec4(0.05, 0.05, 0.10, 0.90)
    colors[clr.ResizeGripActive]       = ImVec4(0.05, 0.05, 0.10, 0.90)
    colors[clr.PlotLines]              = ImVec4(1.00, 1.00, 1.00, 1.00)
    colors[clr.PlotLinesHovered]       = ImVec4(0.90, 0.70, 0.00, 1.00)
    colors[clr.PlotHistogram]          = ImVec4(0.90, 0.70, 0.00, 1.00)
    colors[clr.PlotHistogramHovered]   = ImVec4(1.00, 0.60, 0.00, 1.00)
    colors[clr.TextSelectedBg]         = ImVec4(0.41, 0.55, 0.78, 1.00)
end

function msg(text)
    sampAddChatMessage("{2FEE00}[Len]: {EAEAEA}"..text)
end

function TimeWork(seconds)
	local seconds = tonumber(seconds)
	if seconds <= 0 then
		return "00:00:00";
	else
		hours = string.format("%02.f", math.floor(seconds/3600));
		mins = string.format("%02.f", math.floor(seconds/60 - (hours*60)));
		secs = string.format("%02.f", math.floor(seconds - hours*3600 - mins *60));
		return hours..":"..mins..":"..secs
	end
end

function imgui.CenterTextColoredRGB(text)
    local width = imgui.GetWindowWidth()
    local style = imgui.GetStyle()
    local colors = style.Colors
    local ImVec4 = imgui.ImVec4

    local explode_argb = function(argb)
        local a = bit.band(bit.rshift(argb, 24), 0xFF)
        local r = bit.band(bit.rshift(argb, 16), 0xFF)
        local g = bit.band(bit.rshift(argb, 8), 0xFF)
        local b = bit.band(argb, 0xFF)
        return a, r, g, b
    end

    local getcolor = function(color)
        if color:sub(1, 6):upper() == 'SSSSSS' then
            local r, g, b = colors[1].x, colors[1].y, colors[1].z
            local a = tonumber(color:sub(7, 8), 16) or colors[1].w * 255
            return ImVec4(r, g, b, a / 255)
        end
        local color = type(color) == 'string' and tonumber(color, 16) or color
        if type(color) ~= 'number' then return end
        local r, g, b, a = explode_argb(color)
        return imgui.ImColor(r, g, b, a):GetVec4()
    end

    local render_text = function(text_)
        for w in text_:gmatch('[^\r\n]+') do
            local textsize = w:gsub('{.-}', '')
            local text_width = imgui.CalcTextSize(u8(textsize))
            imgui.SetCursorPosX( width / 2 - text_width .x / 2 )
            local text, colors_, m = {}, {}, 1
            w = w:gsub('{(......)}', '{%1FF}')
            while w:find('{........}') do
                local n, k = w:find('{........}')
                local color = getcolor(w:sub(n + 1, k - 1))
                if color then
                    text[#text], text[#text + 1] = w:sub(m, n - 1), w:sub(k + 1, #w)
                    colors_[#colors_ + 1] = color
                    m = n
                end
                w = w:sub(1, n - 1) .. w:sub(k + 1, #w)
            end
            if text[0] then
                for i = 0, #text do
                    imgui.TextColored(colors_[i] or colors[1], u8(text[i]))
                    imgui.SameLine(nil, 0)
                end
                imgui.NewLine()
            else
                imgui.Text(u8(w))
            end
        end
    end
    render_text(text)
end

function imgui.AnimButton(label, size) -- by Cosmo
    local duration = {
        1.0, -- Длительность переходов между hovered / idle
        0.3  -- Длительность анимации после нажатия
    }

    local cols = {
        default = imgui.ImVec4(imgui.GetStyle().Colors[imgui.Col.Button]),
        hovered = imgui.ImVec4(imgui.GetStyle().Colors[imgui.Col.ButtonHovered]),
        active  = imgui.ImVec4(imgui.GetStyle().Colors[imgui.Col.ButtonActive])
    }

    if not FBUTPOOL then FBUTPOOL = {} end
    if not FBUTPOOL[label] then
        FBUTPOOL[label] = {
            color = cols.default,
            clicked = { nil, nil },
            hovered = {
                cur = false,
                old = false,
                clock = nil,
            }
        }
    end

    local degrade = function(before, after, start_time, duration)
        local result_vec4 = before
        local timer = os.clock() - start_time
        if timer >= 0.00 then
            local offs = {
                x = after.x - before.x,
                y = after.y - before.y,
                z = after.z - before.z,
                w = after.w - before.w
            }

            result_vec4.x = result_vec4.x + ( (offs.x / duration) * timer )
            result_vec4.y = result_vec4.y + ( (offs.y / duration) * timer )
            result_vec4.z = result_vec4.z + ( (offs.z / duration) * timer )
            result_vec4.w = result_vec4.w + ( (offs.w / duration) * timer )
        end
        return result_vec4
    end

    if FBUTPOOL[label]['clicked'][1] and FBUTPOOL[label]['clicked'][2] then
        if os.clock() - FBUTPOOL[label]['clicked'][1] <= duration[2] then
            FBUTPOOL[label]['color'] = degrade(
                FBUTPOOL[label]['color'],
                cols.active,
                FBUTPOOL[label]['clicked'][1],
                duration[2]
            )
            goto no_hovered
        end

        if os.clock() - FBUTPOOL[label]['clicked'][2] <= duration[2] then
            FBUTPOOL[label]['color'] = degrade(
                FBUTPOOL[label]['color'],
                FBUTPOOL[label]['hovered']['cur'] and cols.hovered or cols.default,
                FBUTPOOL[label]['clicked'][2],
                duration[2]
            )
            goto no_hovered
        end
    end

    if FBUTPOOL[label]['hovered']['clock'] ~= nil then
        if os.clock() - FBUTPOOL[label]['hovered']['clock'] <= duration[1] then
            FBUTPOOL[label]['color'] = degrade(
                FBUTPOOL[label]['color'],
                FBUTPOOL[label]['hovered']['cur'] and cols.hovered or cols.default,
                FBUTPOOL[label]['hovered']['clock'],
                duration[1]
            )
        else
            FBUTPOOL[label]['color'] = FBUTPOOL[label]['hovered']['cur'] and cols.hovered or cols.default
        end
    end

    ::no_hovered::

    imgui.PushStyleColor(imgui.Col.Button, imgui.ImVec4(FBUTPOOL[label]['color']))
    imgui.PushStyleColor(imgui.Col.ButtonHovered, imgui.ImVec4(FBUTPOOL[label]['color']))
    imgui.PushStyleColor(imgui.Col.ButtonActive, imgui.ImVec4(FBUTPOOL[label]['color']))
    local result = imgui.Button(label, size or imgui.ImVec2(0, 0))
    imgui.PopStyleColor(3)

    if result then
        FBUTPOOL[label]['clicked'] = {
            os.clock(),
            os.clock() + duration[2]
        }
    end

    FBUTPOOL[label]['hovered']['cur'] = imgui.IsItemHovered()
    if FBUTPOOL[label]['hovered']['old'] ~= FBUTPOOL[label]['hovered']['cur'] then
        FBUTPOOL[label]['hovered']['old'] = FBUTPOOL[label]['hovered']['cur']
        FBUTPOOL[label]['hovered']['clock'] = os.clock()
    end

    return result
end

imgui.OnInitialize(function()
    imgui.GetIO().IniFilename = nil
    local style = imgui.GetStyle()
    local colors = style.Colors
    local clr = imgui.Col
    local ImVec4 = imgui.ImVec4
    local ImVec2 = imgui.ImVec2
 
    if font24 == nil then
        font24 = imgui.GetIO().Fonts:AddFontFromFileTTF(getFolderPath(0x14) .. '\\trebucbd.ttf', 24.0, nil, imgui.GetIO().Fonts:GetGlyphRangesCyrillic())
    end
    if font20 == nil then
        font20 = imgui.GetIO().Fonts:AddFontFromFileTTF(getFolderPath(0x14) .. '\\trebucbd.ttf', 20.0, nil, imgui.GetIO().Fonts:GetGlyphRangesCyrillic())
    end
    if font18 == nil then
        font18 = imgui.GetIO().Fonts:AddFontFromFileTTF(getFolderPath(0x14) .. '\\trebucbd.ttf', 18.0, nil, imgui.GetIO().Fonts:GetGlyphRangesCyrillic())
    end

    style.WindowPadding = ImVec2(15, 15)
    style.WindowRounding = 8.0
    style.FramePadding = ImVec2(5, 5)
    style.ItemSpacing = ImVec2(12, 8)
    style.ItemInnerSpacing = ImVec2(8, 6)
    style.IndentSpacing = 25.0
    style.ScrollbarSize = 15.0
    style.ScrollbarRounding = 15.0
    style.GrabMinSize = 15.0
    style.GrabRounding = 8.0
    style.ChildRounding = 8.0
    style.FrameRounding = 6.0
    style.WindowTitleAlign = ImVec2(0.5, 0.5)
	style.ButtonTextAlign = ImVec2(0.5, 0.5)

    themeOne()
end)
```