-- ╔════════════════════════════════════════════════════════════════════════════════════════╗
-- ║                                    VIOL.LUA CHEAT MENU                                 ║
-- ║                                   Advanced Cheat System                                ║
-- ╚════════════════════════════════════════════════════════════════════════════════════════╝

-- ┌──────────────────────────────────────────────────────────────────────────────────────┐
-- │                                  CORE REFERENCES                                     │
-- └──────────────────────────────────────────────────────────────────────────────────────┘

local _R = {
    me = function() return LocalPlayer() end,
    sw = function() return ScrW() end,
    sh = function() return ScrH() end,
    mdl = function() return LocalPlayer():GetModel() end,
    eyePos = function() return LocalPlayer():EyePos() end,
    eyeAng = function() return LocalPlayer():EyeAngles() end,
    weapon = function() return LocalPlayer():GetActiveWeapon() end,
    wClass = function() local wep = LocalPlayer():GetActiveWeapon() return IsValid(wep) and wep:GetClass() or "" end,
    spread = {}, comps = {}, cones = {}, impacts = {},
    CT = CurTime, RFT = RealFrameTime, latency = function() return LocalPlayer():Ping() / 1000 end,
    zeroVec = Vector(), Vec = Vector,
    hTabl = function() return hook.GetTable() end, hAdd = function(...) return hook.Add(...) end, hRem = function(...) return hook.Remove(...) end,
    toStr = tostring, valid = IsValid, tSimple = timer.Simple,
    deg = math.deg, cos = math.cos, abs = math.abs, sin = math.sin, tan = math.tan,
    acos = math.acos, sqrt = math.sqrt, pi = math.pi, floor = math.floor,
    rad = math.rad, round = math.Round, normAng = math.NormalizeAngle,
    rand = math.random, rRand = math.Rand, rSeed = math.randomseed,
    atan = math.atan, clamp = math.Clamp,
    dText = draw.SimpleText, dTextOut = draw.SimpleTextOutlined, dBox = draw.RoundedBox, dDrawText = draw.DrawText,
    sPlay = surface.PlaySound, sSetCol = surface.SetDrawColor, sRect = surface.DrawRect,
    sLine = surface.DrawLine, sText = surface.DrawText, sCircle = surface.DrawCircle,
    sSetFont = surface.SetFont, sSetTxtCol = surface.SetTextColor, sSetTxtPos = surface.SetTextPos,
    sOutline = surface.DrawOutlinedRect, sTxtSize = surface.GetTextSize,
    rSupLight = render.SuppressEngineLighting, rMatOver = render.MaterialOverride, rModelLit = render.SetModelLighting,
    rColMod = render.SetColorModulation, rDepth = render.DepthRange, rBlend = render.SetBlend,
    rColMat = render.SetColorMaterial, rDrawBox = render.DrawBox,
    _C = MsgC, _P = print, _PT = PrintTable, _CLR = Color,
    CustomSpread = {},
}

require("vrmod")
if not KEY_INSERT then
    KEY_INSERT = 45
end
 
-- ┌──────────────────────────────────────────────────────────────────────────────────────┐
-- │                                  Hook UHQFREEISREAL                                  │
-- └──────────────────────────────────────────────────────────────────────────────────────┘
 require("vrmod")
local _hok = {}
local _xor = {}
local f_xor = {}
local function XORString(text)
    if not isstring(text) then return end

    if _xor[text] then
        return _xor[text]
    end

    local key = "allahuhqniggerfuckyoupalestine"
    local out = {}

    for i = 1, #text do
        out[i] = bit.bxor(string.byte(text[i]), string.byte(key[i % #key]))
    end

    local strOut = string.char(unpack(out))

    _xor[text] = strOut
    _xor[strOut] = text
    f_xor[strOut] = text

    return strOut
end

local function AddHook(strType, pFunction)
    local strName = XORString(tostring({}))

        _hok[#_hok + 1] = {
        m_strType = strType,
        m_strName = strName
    }

    local ppFunction = function()
        local ok, err = pcall(pFunction)
        if not ok then
            error(err)
        end
    end

    _R.hAdd(strType, strName, ppFunction)
    
    _R._C(
                _R._CLR(224, 110, 250), 
                "[VIOL.LUA] ", 
                color_white, 
                "-> _R." .. strType .. "." .. strName .."\n"
            )
end

local function shouldFire(b)
    local wep = _R.wClass()
    local wepactive = _R.weapon()
    local weps = {
        'weapon_physgun',
        "weapon_physcannon",
        "gmod_tool",
        'hands',
        'none',
        'pocket',
        'inventory',
        'weapon_physcannon',
        'weapon_vape*',
    }
    if _R.me():Alive() and wep then
        for k, v in ipairs( weps ) do
            if wep == v then return false end
        end
    end
    return true
end
-- ┌──────────────────────────────────────────────────────────────────────────────────────┐
-- │                                   COLOR SCHEME                                       │
-- └──────────────────────────────────────────────────────────────────────────────────────┘

local COLORS = {
    bg = _R._CLR(13, 13, 13, 255),
    panel = _R._CLR(26, 26, 26, 255),
    accent = _R._CLR(198, 84, 185, 255),
    text = _R._CLR(224, 224, 224, 255),
    white = _R._CLR(255, 255, 255, 255),
    border = _R._CLR(198, 84, 185, 100),
    success = _R._CLR(46, 204, 113, 255),
    warning = _R._CLR(241, 196, 15, 255),
    error = _R._CLR(231, 76, 60, 255)
}

-- ┌──────────────────────────────────────────────────────────────────────────────────────┐
-- │                                   MENU STRUCTURE                                     │
-- └──────────────────────────────────────────────────────────────────────────────────────┘

local TABS = {
    {"Aimbot", "aimbot"}, {"Visual", "visual"}, {"Misc", "misc"}, {"Hook", "hook"}, {"Debug", "debug"}
}

local OPTIONS = {
    -- ═══════════════════════════════════════════════════════════════════════════════════════
    --                                    AIMBOT TAB
    -- ═══════════════════════════════════════════════════════════════════════════════════════
    aimbot = {
        panel1 = {
            title = "Aimbot Core",
            options = {
                {type = "checkbox", name = "Aimbot", var = "aimbot_enabled"},
                {type = "keybind", name = "Bind", var = "aimbot_key", default = "MOUSE5"},
                {type = "checkbox", name = "SilentAim", var = "silent_aim"},
                {type = "checkbox", name = "No-Spread", var = "no_spread"},
                {type = "checkbox", name = "No-Recoil", var = "no_recoil"},
                {type = "checkbox", name = "Multi-point", var = "multi_point"},
                {type = "checkbox", name = "Target Backtrack", var = "target_backtrack"}
            }
        },
        panel2 = {
            title = "Aimbot Settings",
            options = {
                {type = "slider", name = "FOV Circle", var = "fov_circle", min = 0, max = 360, default = 90},
                {type = "slider", name = "Smoothness", var = "smoothness", min = 0, max = 100, default = 0},
                {type = "dropdown", name = "Hitbox", var = "hitbox", options = {"Head", "Chest", "Pelvis", "Arms", "Legs"}},
                {type = "checkbox", name = "Auto-Fire", var = "auto_fire"}
            }
        }
    },
    -- ═══════════════════════════════════════════════════════════════════════════════════════
    --                                    VISUAL TAB
    -- ═══════════════════════════════════════════════════════════════════════════════════════
    visual = {
        panel1 = {
            title = "ESP Features",
            options = {
                {type = "checkbox", name = "Box ESP", var = "box_esp"},
                {type = "color", parent = "Box ESP", var = "box_color", default = _R._CLR(255, 255, 255, 255)},
                {type = "checkbox", name = "Skeleton", var = "skeleton"},
                {type = "color", parent = "Skeleton", var = "skeleton_color", default = _R._CLR(255, 255, 255, 255)},
                {type = "checkbox", name = "Health ESP", var = "health_esp"},
                {type = "color", parent = "Health ESP", var = "health_color", default = _R._CLR(0, 255, 0, 255)},
                {type = "checkbox", name = "Name ESP", var = "name_esp"},
                {type = "color", parent = "Name ESP", var = "name_color", default = _R._CLR(255, 255, 255, 255)},
                {type = "checkbox", name = "Distance ESP", var = "distance_esp"},
                {type = "checkbox", name = "Weapon ESP", var = "weapon_esp"}
            }
        },
        panel2 = {
            title = "Visual Settings",
            options = {
                {type = "dropdown", name = "Chams Material", var = "chams_material", options = {"Flat", "Lit", "Custom"}},
                {type = "checkbox", name = "Chams", var = "chams_enabled"},
                {type = "color", parent = "Chams", var = "chams_color", default = _R._CLR(255, 0, 0, 255)},
                {type = "checkbox", name = "Wireframe", var = "wireframe"},
                {type = "slider", name = "ESP Distance", var = "esp_distance", min = 100, max = 5000, default = 1500}
            }
        }
    },
    -- ═══════════════════════════════════════════════════════════════════════════════════════
    --                                    MISC TAB
    -- ═══════════════════════════════════════════════════════════════════════════════════════
    misc = {
        panel1 = {
            title = "Movement",
            options = {
                {type = "checkbox", name = "BunnyHop", var = "bhop"},
                {type = "checkbox", name = "AutoStrafe", var = "autostrafe"},
                {type = "checkbox", name = "FakeLag", var = "fakelag"},
                {type = "checkbox", name = "Third Person", var = "third_person"}
            }
        },
        panel2 = {
            title = "Misc Settings",
            options = {
                {type = "slider", name = "FakeLag Amount", var = "fakelag_amount", min = 1, max = 16, default = 8},
                {type = "checkbox", name = "Anti-AFK", var = "anti_afk"},
                {type = "checkbox", name = "Auto-Reload", var = "auto_reload"}
            }
        }
    },
    -- ═══════════════════════════════════════════════════════════════════════════════════════
    --                                    HOOK TAB
    -- ═══════════════════════════════════════════════════════════════════════════════════════
    hook = {
        panel1 = {
            title = "Hook System",
            options = {
                {type = "checkbox", name = "Enable Hooks", var = "hooks_enabled"},
                {type = "checkbox", name = "Paint Hook", var = "paint_hook"},
                {type = "checkbox", name = "CreateMove Hook", var = "createmove_hook"}
            }
        },
        panel2 = {
            title = "Hook Settings",
            options = {
                {type = "checkbox", name = "Debug Mode", var = "debug_hooks"},
                {type = "button", name = "Reload Hooks", var = "reload_hooks", action = "reload_hooks"}
            }
        }
    },
    -- ═══════════════════════════════════════════════════════════════════════════════════════
    --                                    DEBUG TAB
    -- ═══════════════════════════════════════════════════════════════════════════════════════
    debug = {
        panel1 = {
            title = "Debug Info",
            options = {
                {type = "checkbox", name = "Show FPS", var = "show_fps"},
                {type = "checkbox", name = "Show Ping", var = "show_ping"},
                {type = "checkbox", name = "Console Output", var = "console_output"}
            }
        },
        panel2 = {
            title = "Debug Tools",
            options = {
                {type = "button", name = "Clear Console", var = "clear_console", action = "clear_console"},
                {type = "button", name = "Dump Variables", var = "dump_vars", action = "dump_variables"}
            }
        }
    }
}

-- ┌──────────────────────────────────────────────────────────────────────────────────────┐
-- │                                 GLOBAL VARIABLES                                     │
-- └──────────────────────────────────────────────────────────────────────────────────────┘

local VARS = {}
local frame, current_tab, visible = nil, "aimbot", false

-- ╔════════════════════════════════════════════════════════════════════════════════════════╗
-- ║                                     FUNCTIONS                                          ║
-- ╚════════════════════════════════════════════════════════════════════════════════════════╝

-- ┌──────────────────────────────────────────────────────────────────────────────────────┐
-- │                               VARIABLE INITIALIZATION                                │
-- └──────────────────────────────────────────────────────────────────────────────────────┘

local function InitVars()
    for tab, data in pairs(OPTIONS) do
        for panel, pdata in pairs(data) do
            for _, opt in ipairs(pdata.options) do
                if opt.default then
                    VARS[opt.var] = opt.default
                elseif opt.type == "checkbox" then
                    VARS[opt.var] = false
                elseif opt.type == "slider" then
                    VARS[opt.var] = opt.min or 0
                elseif opt.type == "dropdown" then
                    VARS[opt.var] = opt.options[1]
                elseif opt.type == "color" then
                    VARS[opt.var] = opt.default or _R._CLR(255, 255, 255, 255)
                end
            end
        end
    end
end

-- ┌──────────────────────────────────────────────────────────────────────────────────────┐
-- │                                CHEAT FEATURES                                        │
-- └──────────────────────────────────────────────────────────────────────────────────────┘

local function BoxESPExample()
    if VARS["box_esp"] then
        -- Box ESP logic here
    end
end

local function AimbotExample()
    if VARS["aimbot_enabled"] then
        -- Aimbot logic here
    end
end

local function BhopExample()
    if VARS["bhop"] then
        -- Bunny hop logic here
    end
end

local function RunCheatFeatures()
    -- Execute all cheat features
    BoxESPExample()
    AimbotExample()
    BhopExample()
    
    -- Debug info display
    if VARS["show_fps"] then
        _R.dText("FPS: " .. _R.round(1 / _R.RFT()), "DermaDefault", 10, 10, COLORS.success, TEXT_ALIGN_LEFT, TEXT_ALIGN_TOP)
    end
    
    if VARS["show_ping"] then
        _R.dText("Ping: " .. _R.round(_R.latency * 1000) .. "ms", "DermaDefault", 10, 30, COLORS.warning, TEXT_ALIGN_LEFT, TEXT_ALIGN_TOP)
    end
    
    -- Console output for debugging
    if VARS["console_output"] then
        local active_features = {}
        for var, value in pairs(VARS) do
            if value == true then
                table.insert(active_features, var)
            end
        end
        
        if #active_features > 0 then
            _R._P("Active Features: " .. table.concat(active_features, ", "))
        end
    end
end

-- ┌──────────────────────────────────────────────────────────────────────────────────────┐
-- │                                  UI ELEMENTS                                         │
-- └──────────────────────────────────────────────────────────────────────────────────────┘

local function CreateColorButton(parent, x, y, var, parent_name)
    local btn = vgui.Create("DButton", parent)
    btn:SetPos(x, y)
    btn:SetSize(16, 16)
    btn:SetText("")
    
    btn.Paint = function(self, w, h)
        _R.sSetCol(VARS[var] or _R._CLR(255, 255, 255, 255))
        _R.sRect(0, 0, w, h)
        _R.sSetCol(COLORS.accent)
        _R.sOutline(0, 0, w, h)
    end
    
    btn.DoClick = function()
        local mixer = vgui.Create("DFrame")
        mixer:SetSize(300, 200)
        mixer:Center()
        mixer:SetTitle("Color - " .. parent_name)
        mixer:MakePopup()
        
        local colorMixer = vgui.Create("DColorMixer", mixer)
        colorMixer:SetPos(10, 30)
        colorMixer:SetSize(280, 160)
        colorMixer:SetColor(VARS[var])
        colorMixer.ValueChanged = function(self, col) VARS[var] = col end
    end
    
    return btn
end

local function CreateElement(parent, opt, x, y, w, h)
    if opt.type == "checkbox" then
        local cb = vgui.Create("DButton", parent)
        cb:SetPos(x, y)
        cb:SetSize(w, h)
        cb:SetText("")
        
        cb.Paint = function(self, w, h)
            _R.sSetCol(COLORS.panel)
            _R.sRect(0, 0, 18, 18)
            _R.sSetCol(COLORS.accent)
            _R.sOutline(0, 0, 18, 18)
            
            if VARS[opt.var] then
                _R.sSetCol(COLORS.accent)
                _R.sRect(3, 3, 12, 12)
            end
            
            _R.dText(opt.name, "DermaDefault", 25, 9, COLORS.text, TEXT_ALIGN_LEFT, TEXT_ALIGN_CENTER)
        end
        
        cb.DoClick = function()
            VARS[opt.var] = not VARS[opt.var]
        end
        
        return cb
        
    elseif opt.type == "color" then
        return CreateColorButton(parent, x + 150, y, opt.var, opt.parent)
        
    elseif opt.type == "slider" then
        local slider = vgui.Create("DNumSlider", parent)
        slider:SetPos(x, y)
        slider:SetSize(w, h)
        slider:SetText(opt.name)
        slider:SetMin(opt.min)
        slider:SetMax(opt.max)
        slider:SetValue(VARS[opt.var])
        slider:SetDecimals(0)
        
        slider.OnValueChanged = function(self, val)
            VARS[opt.var] = _R.floor(val)
        end
        
        return slider
        
    elseif opt.type == "dropdown" then
        local dd = vgui.Create("DComboBox", parent)
        dd:SetPos(x, y + 15)
        dd:SetSize(w, 20)
        dd:SetValue(VARS[opt.var])
        
        for _, option in ipairs(opt.options) do
            dd:AddChoice(option)
        end
        
        dd.OnSelect = function(self, index, value)
            VARS[opt.var] = value
        end
        
        return dd
        
    elseif opt.type == "button" then
        local btn = vgui.Create("DButton", parent)
        btn:SetPos(x, y)
        btn:SetSize(w, h)
        btn:SetText("")
        
        btn.Paint = function(self, w, h)
            local col = self:IsHovered() and COLORS.accent or COLORS.panel
            _R.sSetCol(col)
            _R.sRect(0, 0, w, h)
            _R.sSetCol(COLORS.accent)
            _R.sOutline(0, 0, w, h)
            local tcol = self:IsHovered() and COLORS.white or COLORS.text
            _R.dText(opt.name, "DermaDefault", w/2, h/2, tcol, TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
        end
        
        btn.DoClick = function()
            if opt.action == "reload_hooks" then
                _R._P("Reloading hooks...")
                
            elseif opt.action == "clear_console" then
                RunConsoleCommand("clear")
                _R._P("Console cleared!")
                
            elseif opt.action == "dump_variables" then
                _R._P("═══════════════════════════════════════════════════════════")
                _R._P("                   VARIABLE DUMP")
                _R._P("═══════════════════════════════════════════════════════════")
                _R._PT(VARS)
                _R._P("═══════════════════════════════════════════════════════════")
            end
        end
        
        return btn
        
    elseif opt.type == "keybind" then
        local kb = vgui.Create("DButton", parent)
        kb:SetPos(x, y)
        kb:SetSize(w, h)
        kb:SetText("")
        kb.binding = false
        
        kb.Paint = function(self, w, h)
            _R.sSetCol(COLORS.panel)
            _R.sRect(0, 0, w, h)
            _R.sSetCol(COLORS.accent)
            _R.sOutline(0, 0, w, h)
            
            local text = self.binding and "Press key..." or (opt.name .. ": [" .. (VARS[opt.var] or "NONE") .. "]")
            _R.dText(text, "DermaDefault", 5, h/2, COLORS.text, TEXT_ALIGN_LEFT, TEXT_ALIGN_CENTER)
        end
        
        kb.DoClick = function(self)
            self.binding = true
        end
        
        kb.OnKeyCodePressed = function(self, key)
            if self.binding then
                VARS[opt.var] = input.GetKeyName(key)
                self.binding = false
            end
        end
        
        return kb
    end
end

-- ┌──────────────────────────────────────────────────────────────────────────────────────┐
-- │                                 MENU TOGGLE                                          │
-- └──────────────────────────────────────────────────────────────────────────────────────┘

local function Toggle()
    if frame and frame:IsValid() then
        frame:Remove()
        visible = false
    else
        CreateMenu()
    end
end

-- ╔════════════════════════════════════════════════════════════════════════════════════════╗
-- ║                                   UI SYSTEM                                            ║
-- ╚════════════════════════════════════════════════════════════════════════════════════════╝

-- ┌──────────────────────────────────────────────────────────────────────────────────────┐
-- │                                CREATE PANEL                                          │
-- └──────────────────────────────────────────────────────────────────────────────────────┘

local function CreatePanel(parent, data, x, y, w, h)
    local panel = vgui.Create("DPanel", parent)
    panel:SetPos(x, y)
    panel:SetSize(w, h)
    
    panel.Paint = function(self, w, h)
        _R.sSetCol(COLORS.panel)
        _R.sRect(0, 0, w, h)
        _R.sSetCol(COLORS.border)
        _R.sOutline(0, 0, w, h)
        _R.dText(data.title, "DermaDefaultBold", 10, 10, COLORS.accent, TEXT_ALIGN_LEFT, TEXT_ALIGN_TOP)
    end
    
    local y_offset = 35
    for _, opt in ipairs(data.options) do
        if opt.type ~= "color" then
            CreateElement(panel, opt, 10, y_offset, w - 20, 20)
            y_offset = y_offset + 30
            if opt.type == "dropdown" then y_offset = y_offset + 15 end
        else
            CreateElement(panel, opt, 10, y_offset - 30, 16, 16)
        end
    end
    
    return panel
end

-- ┌──────────────────────────────────────────────────────────────────────────────────────┐
-- │                                UPDATE CONTENT                                        │
-- └──────────────────────────────────────────────────────────────────────────────────────┘

local function UpdateContent()
    if not frame or not frame.content then return end
    
    frame.content:Clear()
    local data = OPTIONS[current_tab]
    if not data then return end
    
    if data.panel1 then CreatePanel(frame.content, data.panel1, 0, 0, 285, 320) end
    if data.panel2 then CreatePanel(frame.content, data.panel2, 295, 0, 285, 320) end
end

-- ┌──────────────────────────────────────────────────────────────────────────────────────┐
-- │                                CREATE MENU                                           │
-- └──────────────────────────────────────────────────────────────────────────────────────┘

function CreateMenu()
    if frame then frame:Remove() end
    
    frame = vgui.Create("DFrame")
    frame:SetSize(600, 400)
    frame:Center()
    frame:SetTitle("")
    frame:SetDraggable(true)
    frame:ShowCloseButton(false)
    frame:MakePopup()
    
    frame.Paint = function(self, w, h)
        _R.sSetCol(COLORS.bg)
        _R.sRect(0, 0, w, h)
        _R.sSetCol(COLORS.accent)
        _R.sOutline(0, 0, w, h)
        _R.dText("VIOL.LUA", "DermaDefaultBold", w/2, 15, COLORS.accent, TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
    end
    
    local close = vgui.Create("DButton", frame)
    close:SetPos(560, 5)
    close:SetSize(30, 20)
    close:SetText("")
    close.Paint = function(self, w, h)
        local col = self:IsHovered() and _R._CLR(255, 50, 50) or COLORS.panel
        _R.sSetCol(col)
        _R.sRect(0, 0, w, h)
        _R.sSetCol(COLORS.accent)
        _R.sOutline(0, 0, w, h)
        _R.dText("X", "DermaDefault", w/2, h/2, COLORS.white, TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
    end
    close.DoClick = function() frame:Remove() visible = false end
    
    local tab_width = 600 / #TABS
    for i, tab in ipairs(TABS) do
        local btn = vgui.Create("DButton", frame)
        btn:SetPos((i-1) * tab_width, 30)
        btn:SetSize(tab_width, 30)
        btn:SetText("")
        btn.tab = tab[2]
        btn.Paint = function(self, w, h)
            local active = current_tab == self.tab
            local col = active and COLORS.accent or COLORS.panel
            _R.sSetCol(col)
            _R.sRect(0, 0, w, h)
            _R.sSetCol(COLORS.accent)
            _R.sOutline(0, 0, w, h)
            local tcol = active and COLORS.white or COLORS.text
            _R.dText(tab[1], "DermaDefault", w/2, h/2, tcol, TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
        end
        btn.DoClick = function(self)
            current_tab = self.tab
            UpdateContent()
        end
    end
    
    frame.content = vgui.Create("DPanel", frame)
    frame.content:SetPos(10, 70)
    frame.content:SetSize(580, 320)
    frame.content.Paint = function() end
    
    visible = true
    UpdateContent()
end

-- ┌──────────────────────────────────────────────────────────────────────────────────────┐
-- │                              INITIALIZATION                                          │
-- └──────────────────────────────────────────────────────────────────────────────────────┘

local function Initialize()
    InitVars()
end

-- ┌──────────────────────────────────────────────────────────────────────────────────────┐
-- │                              MENU KEYBIND                                            │
-- └──────────────────────────────────────────────────────────────────────────────────────┘

local last_menu_state = false
local function MenuKeybind()
    local pressed = input.IsKeyDown(KEY_INSERT)
    if pressed and not last_menu_state then
        Toggle()
    end
    last_menu_state = pressed
end

-- ┌──────────────────────────────────────────────────────────────────────────────────────┐
-- │                              AIMBOT   FEATURES                                       │
-- └──────────────────────────────────────────────────────────────────────────────────────┘

local function MovementFix(cmd, wish_yaw)
    local pitch = _R.math_NormAngle(cmd:GetViewAngles().x)
    local inverted = -1

    if (pitch > 89 or pitch < -89) then
        inverted = 1
    end

    local ang_diff = _R.math_rad(_R.math_NormAngle((cmd:GetViewAngles().y - wish_yaw) * inverted))
    local forwardmove = cmd:GetForwardMove()
    local sidemove = cmd:GetSideMove()

    local new_forwardmove = forwardmove * -_R.math_cos(ang_diff) * inverted + sidemove * _R.math_sin(ang_diff)
    local new_sidemove = forwardmove * _R.math_sin(ang_diff) * inverted + sidemove * _R.math_cos(ang_diff)

    cmd:SetForwardMove(new_forwardmove)
    cmd:SetSideMove(new_sidemove)
end

local function Silent(cmd)
    if !_R.fa then _R.fa = cmd:GetViewAngles() end
    _R.fa = _R.fa + Angle(cmd:GetMouseY() * GetConVarNumber("m_yaw"), cmd:GetMouseX() * -GetConVarNumber("m_yaw"), 0)
    _R.fa.p = _R.math_clamp(_R.fa.p, -89, 89)
    _R.fa.r = 0
    _R.fa:Normalize()
end

function _R.CustomSpread.swb( cmd, ang ) -- WORK

    local cone = _R.activeWeapon.CurCone
    if !cone then return ang end
    if _R.me:Crouching() then
        cone = cone * 0.85
    end

    _R.math_randomseed( cmd:CommandNumber() )
    return ang  - _R.me:GetViewPunchAngles() - Angle( _R.math_rand(-cone, cone), _R.math_rand(-cone, cone), 0 ) * 25
end

function _R.CustomSpread.cw(cmd, ang) -- WORK
    if not (cmd and ang) then return ang end
    if not _R.isValid(_R.me) or not _R.isValid(_R.activeWeapon) then return ang end
    if not isnumber(_R.activeWeapon.CurCone) then return ang end

    local cone = _R.activeWeapon.CurCone
    if not cone then return ang end
    _R.math_randomseed(cmd:CommandNumber())

    if _R.me:Crouching() then
        cone = cone * 0.85
    end

    if not isnumber(cone) then return ang end
    Dir = Angle(_R.math_rand(cone, -cone), _R.math_rand(cone, -cone), 0) * 25

    clumpSpread = clumpSpread or _R.activeWeapon.ClumpSpread
    if not isnumber(clumpSpread) then clumpSpread = 0 end

    Dir2 = Dir
    if clumpSpread > 0 then
        Dir2 = Dir + _R.Vec(_R.math_rand(-1, 1), _R.math_rand(-1, 1), _R.math_rand(-1, 1)) * clumpSpread
    end

    if not isangle(ang) or not isangle(Dir2) then return ang end

    return ang - _R.me:GetViewPunchAngles() + Dir2
end

function _R.CustomSpread.arccw( cmd, ang )
    return ang - _R.me:GetViewPunchAngles()
end

function _R.CustomSpread.fas2( cmd, ang )
    local cone = _R.activeWeapon.CurCone
    if !cone then return ang end
    _R.math_randomseed(_R.C())

    Dir2 = Angle(_R.math_rand(cone, -cone), _R.math_rand(cone, -cone), 0) * 25

    return ang - _R.me:GetViewPunchAngles() + Dir2
end

function _R.CustomSpread.tfa(cmd, ang) -- WORK
    if not vars or not _R.activeWeapon or not _R.isValid(_R.activeWeapon) then return ang end
    local wep = _R.activeWeapon
    if not isfunction(wep.CalculateConeRecoil) or not isfunction(wep.ComputeBulletDeviation) then return ang end

    local con, _ = wep:CalculateConeRecoil()
    if not con or not wep:CanPrimaryAttack() then return ang end

    local dYaw, dPitch = wep:ComputeBulletDeviation(1, 1, con)
    if not dYaw or not dPitch then return ang end

    local aimAng = Angle(ang)
    local right, up = aimAng:Right(), aimAng:Up()

    aimAng:RotateAroundAxis(up, -dYaw)
    aimAng:RotateAroundAxis(right, -dPitch)

    return aimAng
end

_R.comps["swb"]     = _R.CustomSpread.swb
_R.comps["cw"]      = _R.CustomSpread.cw
_R.comps["arccw"]   = _R.CustomSpread.arccw
_R.comps["fas2"]    = _R.CustomSpread.fas2
_R.comps["tfa"]     = _R.CustomSpread.tfa

GAMEMODE["EntityFireBullets"] = function( self, p, data )

    local spread = data.Spread * -1

    if _R.cones[ _R.activeWeaponClass ] == spread or spread == _R.nulVec then return end

    _R.cones[ _R.activeWeaponClass ] = spread;
end

local function Spread(cmd, ang, spread)
    if !_R.cones[ _R.activeWeaponClass ] then return ang end
    local spread = _R.cones[ _R.activeWeaponClass ]
    local dir = ded.PredictSpread( cmd, ang, spread )
    local spreadangle = ang + dir:Angle()
    spreadangle:Normalize()
    return spreadangle
end

local function NoSpread(cmd, ang)
    if not _R.activeWeaponClass or not _R.activeWeapon then return ang end

    local wep = _R.activeWeapon
    local base = string.Split(_R.activeWeaponClass, "_")[1]
    if _R.isValid(wep) and wep.IsTFAWeapon then
        base = "tfa"
    end
    if _R.comps[base] then
        ang = _R.comps[base](cmd, ang)
    elseif _R.cones[_R.activeWeaponClass] then
        local spread = _R.cones[_R.activeWeaponClass]
        return Spread(cmd, ang, spread)
    end
    return ang
end

local tr = {
    mask = MASK_SHOT,
    filter = _R.me
}

local function VisibleCheck( who, where, wall)
    local start = _R.me:EyePos()
    tr.start = start
    tr.endpos = where
    tr.mask = MASK_SHOT
    local trace = util.TraceLine( tr )
    local canhit = trace.Entity == who or trace.Fraction == 1

    return canhit

end

local function GetAngleDifference(from, to)
    return _R.math_deg(_R.math_acos(to:Forward():Dot(from:Forward())))
end

local function GetBestTarget()
    local bestTarget = nil
    local bestFov = VARS["fov_circle"] or 90
    for _, ply in ipairs(player.GetAll()) do
        if ply ~= _R.me() and ply:Alive() and not ply:IsDormant() then
            local boneIndex = ply:LookupBone("ValveBiped.Bip01_Head1")
            if boneIndex then
                local bonePos = ply:GetBonePosition(boneIndex)
                if bonePos and VisibleCheck(ply, bonePos) and (not IsFriend or not IsFriend(ply:SteamID())) and not ply:IsFlagSet(FL_GODMODE) and not ply:InVehicle() then
                    local targetDirection = (bonePos - _R.me():GetShootPos()):Angle()
                    targetDirection:Normalize()
                    local angDiff = math.abs(math.NormalizeAngle(GetAngleDifference(_R.fa or Angle(0,0,0), targetDirection)))
                    if angDiff < bestFov then
                        bestFov = angDiff
                        bestTarget = ply
                    end
                end
            end
        end
    end
    return bestTarget
end

local function NoRecoil(ang)
    local wep = _R.weapon
    if _R.wClass == "weapon_pistol" or string.StartsWith(_R.wClass, "m9k_") or 
       string.StartsWith(_R.wClass, "fas2") or string.StartsWith(_R.wClass, "cw") or 
       string.StartsWith(_R.wClass, "arccw") or string.StartsWith(_R.wClass, "swb") then
        return ang
    elseif wep and wep.IsTFAWeapon then
        ang.p = ang.p - wep:GetViewPunchP()
        ang.y = ang.y - wep:GetViewPunchY()
    else
        ang = ang - _R.me:GetViewPunchAngles()
    end

    return ang
end

local function getCenterBone(ply)
    if not ply then return end
    local Bone = ply:LookupBone("ValveBiped.Bip01_Head1 ")
    if not Bone then return end
    local matrix = ply:GetBoneMatrix(Bone)
    if not matrix then return end
    local pos, ang = matrix:GetTranslation(), matrix:GetAngles()
    
    local min, max = ply:GetHitBoxBounds(0, 0)
    min:Rotate(ang)
    max:Rotate(ang)
    
    pos = pos + ((min + max) * 0.5)
    return pos
end

local function AUTOPISTOL_C( cmd )
    if _R.me:KeyDown( IN_ATTACK ) and _R.me:Alive() and shouldFire() then
        cmd:RemoveKey( IN_ATTACK )
    end
end

local function predictTarget(pos,trg)
    if not pos or not trg then return _R.zeroVec end
    local lvel,tvel,frm,eng = _R.me():GetAbsVelocity(), trg:GetAbsVelocity(), RealFrameTime(), engine.TickInterval()
    if _R.predtype == 'velocity' then return pos+((lvel-tvel)*(frm/(1/eng))) end
    if _R.predtype == 'engine'  then return tvel == _R.zeroVec and pos or pos+tvel*eng*frm-lvel*eng end
end

local function _CAIM(cmd)
    if not (VARS["aimbot_enabled"] and shouldFire()) then return end
    _R.target = GetBestTarget()
    local direction = cmd:GetViewAngles()
    if _R.target and cmd:KeyDown(IN_ATTACK) then
        if _R.wClass() and string.StartWith(_R.wClass(), "m9k_") then
            cmd:RemoveKey(IN_SPEED)
        end
        local pos = getCenterBone(_R.target)
        local bonePos = predictTarget(pos, _R.target)
        direction = (bonePos - _R.me():GetShootPos()):Angle()
        direction:Normalize()
    end
    if VARS["no_spread"] and cmd:KeyDown(IN_ATTACK) then
        direction = NoSpread(cmd, direction)
    end
    direction = NoRecoil(direction)
    cmd:SetViewAngles(direction)
end

local function AdvancedESP()
    if not VARS["box_esp"] then return end
    
    for _, ply in ipairs(player.GetAll()) do
        if ply ~= _R.me and ply:Alive() then
            local pos = ply:GetPos()
            local screen = pos:ToScreen()
            
            if screen.visible then
                -- Box ESP logic would go here
            end
        end
    end
end

local function AdvancedMovement()
    if VARS["bhop"] then
        -- Bunny hop logic
        if _R.me:OnGround() and input.IsKeyDown(KEY_SPACE) then
            -- Jump logic
        end
    end
    
    if VARS["autostrafe"] then
        -- Auto strafe logic
        if not _R.me:OnGround() then
            -- Strafe logic
        end
    end
end


-- ┌──────────────────────────────────────────────────────────────────────────────────────┐
-- │                             ENHANCED PAINT HOOK                                      │
-- └──────────────────────────────────────────────────────────────────────────────────────┘

local function EnhancedPaintHook()

end

-- ┌──────────────────────────────────────────────────────────────────────────────────────┐
-- │                              CONSOLE COMMANDS                                        │
-- └──────────────────────────────────────────────────────────────────────────────────────┘

for _variable, _meth in pairs(_R) do
    if istable(_meth) then
        for _NickFunc, func in pairs(_meth) do
            _R._C(
                _R._CLR(224, 110, 250), 
                "[VIOL.LUA] ", 
                color_white, 
                "-> _R." .. _variable .. "." .. _NickFunc .. "()\n"
            )
        end
    end
end


-- ╔════════════════════════════════════════════════════════════════════════════════════════╗
-- ║                                 HOOK REGISTRATION                                      ║
-- ╚════════════════════════════════════════════════════════════════════════════════════════╝
_R._C( _R._CLR(224, 110, 250), "[VIOL.LUA] ",  color_white, "--------" .. "-------" .. "--------" .. "CREATED HOOK BY YOU." .. "--------" .. "-------" .. "--------" .. "\n")
AddHook("Think", MenuKeybind)
_R._C( _R._CLR(224, 110, 250), "[VIOL.LUA] ",  color_white, "--------" .. "-------" .. "--------" .. "CREATED HOOK BY YOU." .. "--------" .. "-------" .. "--------" .. "\n")
AddHook("HUDPaint", EnhancedPaintHook)
AddHook("PostCreateMove", _CAIM)

-- Initialize everything
Initialize()
Toggle()

-- ╔════════════════════════════════════════════════════════════════════════════════════════╗
-- ║                                  END OF SCRIPT                                         ║
-- ╚════════════════════════════════════════════════════════════════════════════════════════╝
