opensource silent aim, skin changer, wallbang NOT WORKING!!!
Key Required Patched

opensource silent aim, skin changer, wallbang NOT WORKING!!!

Murder Duelssmertni*qqsmertni*qq 1.5K views 6.4K executesUpdated Sep 3, 2026
5.0/ 5(1 votes)
10100% Positive
Lua Script•8782 lines (320177 chars)
--[[
    Murder Duels - Skeet / Linoria Edition (CS-Style UI)
    Features:
      - Multi-Language Support (RU / EN) with instant language switcher
      - Full Config Manager & Themes (SaveManager & ThemeManager):
          * Create, Save, Load, Overwrite, Delete configs
          * Set as default / Autoload on start
          * Custom theme picker & presets (Skeet, BBot, Tokyo Night, Ubuntu, Synthwave)
      - Working Silent Aim (Bullets & knives hit targets without camera snapping)
      - Silent Auto-Fire (Triggerbot) with Muzzle Clearance:
          * Automatically shoots when aim target is locked inside FOV
          * Zero camera movement / snapping
          * Muzzle Clearance Check (Raycasts directly from the revolver barrel/tip to target)
            Prevents shooting into walls, corners, boxes, or firing prematurely before peeking
          * Hooks ViewportPointToRay and Mouse.Hit natively so Triggerbot shots always hit via Silent Aim
      - Glowing Bullet Tracers / Hit Tracers:
          * Glowing Neon laser beam from muzzle to impact point on every shot (Revolver & Knife)
          * Neon impact hit dot with smooth Quad fadeout
          * Supports ricochets and custom colors / thickness / duration
      - Strict Target & Health Validation:
          * Alive & Health Check (HP > 0, state ~= Dead, no dead attributes)
          * Existence Check (Part and Character exist in workspace, not destroyed)
          * Immunity / ForceField Check
          * Strict Wall Check (Raycast Line-of-Sight, pierces destructible glass, blocks solid walls)
          * Team Check (Respects teammates and lobby teams)
      - High-Speed Bhop (Speed up to 150 studs/s, instant air strafes without CD)
      - Native Centered 3rd Person (Zero crookedness, shoulder offset 0)
      - Advanced ESP (Chams, Names, Distance, Health Bar, Weapon indicator)
      - Rich 2D Visuals:
          * 2D Box ESP (Bounding box around enemies)
          * Snaplines / Tracers (From Bottom or Center)
          * Head Dots (Precise head circles)
          * Silent Aim Target Line (Line directly to locked aim target)
          * Custom CS Crosshair (Size, Gap, Thickness, Dot)
      - Custom World Ambience:
          * Atmosphere Presets (Purple Night, Sunset, Blood Moon, Cyberpunk, Midnight, Toxic Green)
          * Time of Day (ClockTime 0 - 24 hours)
          * Custom Ambient & OutdoorAmbient colors
          * Fog Distance & Color with Atmosphere Tint
          * Saturation & Tint Color Correction
      - Bulletproof Menu Keybind (Quick-Select Dropdown + Press-Any-Key listener via UIS)
      - Working Sliders (Auto mouse unlock while menu is open)
      - Client-Side Weapon Skin Changer:
          * Equips any revolver and knife skin in the game (82+ Knives, 62+ Revolvers)
          * Full 3D meshes, PBR SurfaceAppearance, particles, beams, glow and neon
          * Custom weapon animations (Equip, Shoot, Slash, Inspect) & sounds (Firing, Reload, Equip)
          * Auto-persists on round change and respawns
]]

local Players = game:GetService("Players")
local RunService = game:GetService("RunService")
local UserInputService = game:GetService("UserInputService")
local Lighting = game:GetService("Lighting")
local TweenService = game:GetService("TweenService")

local LocalPlayer = Players.LocalPlayer

-- ==================== 0. MASTER PURGE PREVIOUS INSTANCES ====================
pcall(function()
    if _G.MD_GlobalConnections then
        for _, c in ipairs(_G.MD_GlobalConnections) do
            pcall(function() c:Disconnect() end)
        end
    end
end)
_G.MD_GlobalConnections = {}

if _G.MurderDuelsCleanup then
    pcall(_G.MurderDuelsCleanup)
    _G.MurderDuelsCleanup = nil
end
if _G.MD_Unload then
    pcall(_G.MD_Unload)
    _G.MD_Unload = nil
end

pcall(function()
    if cleardrawcache then cleardrawcache() end
end)

pcall(function()
    local CoreGui = game:GetService("CoreGui")
    for _, child in ipairs(CoreGui:GetChildren()) do
        if child.Name:find("ESP") or child.Name:find("Linoria") or child.Name == "ScreenGui" or child.Name:find("MD_") then
            pcall(function() child:Destroy() end)
        end
    end
end)

pcall(function()
    for _, obj in ipairs(workspace:GetDescendants()) do
        if obj:IsA("Highlight") and (obj.Name:find("ESP") or obj.Name:find("MD_")) then
            pcall(function() obj:Destroy() end)
        end
    end
end)

local isAlive = true
_G.MD_Running = true

-- Weapon timings & instant knife charging
pcall(function()
    local rs = game:GetService("ReplicatedStorage")
    local revTiming = require(rs.Shared.RevolverTiming)
    local knifeTiming = require(rs.Shared.KnifeTiming)
    revTiming.SHOT_COOLDOWN = 2
    revTiming.RELOAD_SOUND_FALLBACK = 0.8
    knifeTiming.THROW_COOLDOWN = 0.3
    knifeTiming.HOLD_TO_THROW_SEC = 0.2
    knifeTiming.CHARGE_DUR = 0.01
end)

-- Game native modules
local PlayerState = nil
local NativeTP = nil
pcall(function()
    PlayerState = require(game:GetService("ReplicatedStorage"):WaitForChild("Shared"):WaitForChild("PlayerState"))
    NativeTP = require(game:GetService("ReplicatedStorage"):WaitForChild("Shared"):WaitForChild("ThirdPerson"))
end)

-- ==================== LOCALIZATION (RU / EN) ====================
local currentLang = _G.MD_SelectedLanguage or "RU"

local Loc = {
    RU = {
        Title = "Murder Duels | Skeet Edition",
        Rage = "Рейдж",
        Legit = "Легит",
        Combat = "Бой",
        AntiAim = "Анти-Аим",
        Movement = "Движение",
        Visuals = "Визуалы",
        Settings = "Настройки",
        -- Combat / Rage
        SilentAimbot = "Сайлент Аим и Триггер",
        EnableSilentAim = "Включить Silent Aim",
        SilentAimDesc = "Пули и ножи летят во врага БЕЗ поворота камеры",
        ActivationMode = "Режим работы аима",
        AlwaysOn = "Всегда включен",
        HoldKey = "При удержании клавиши",
        SilentAutoFire = "Сайлент Авто-выстрел (Triggerbot)",
        SilentAutoFireDesc = "Автоматически стреляет при наведении на врага с Сайлент Аимом (БЕЗ рывков камеры)",
        AutoFireDelay = "Задержка выстрела (сек)",
        KnifeHoldDuration = "Зажатие ножа (сек)",
        KnifeHoldDurationDesc = "Сколько удерживать ЛКМ для броска ножа в триггерботе (сек)",
        MuzzleCheck = "Проверка дула револьвера (Muzzle Check)",
        MuzzleCheckDesc = "Стрелять только когда конец револьвера чисто видит цель (не стреляет в углы и стены)",
        WallCheck = "Строгая проверка стен (Wall Check)",
        WallCheckDesc = "Не стрелять если враг за стеной или препятствием",
        TeamCheck = "Проверка команды (Team Check)",
        TeamCheckDesc = "Не целиться в союзников",
        Prediction = "Упреждение движения (Prediction)",
        PredictionDesc = "Упреждение полета ножа/пули по скорости цели",
        ProjSpeed = "Скорость снаряда",
        MaxKnifePower = "Всегда макс. сила ножа (Always Max Power)",
        MaxKnifePowerDesc = "Нож всегда летит с максимальной скоростью и дальностью, даже при слабом броске",
        InstantKnifeCharge = "Мгновенный заряд ножа (Instant Charge)",
        InstantKnifeChargeDesc = "Прицел мгновенно сужается за 0.01 сек при замахе ножа",
        TargetFilters = "Фильтры целей и хитбоксы",
        TargetPlayers = "Игроки (Players)",
        TargetNoobs = "Манекены / Нубы (Dummies)",
        TargetBullseyes = "Мишени в тире (Targets)",
        HitboxPriority = "Приоритет хитбокса",
        DrawFOV = "Отображать круг FOV",
        FOVRadius = "Радиус FOV",
        -- Auto-Peek
        AutoPeek = "Авто-Пик (Auto-Peek)",
        EnableAutoPeek = "Включить Auto-Peek",
        AutoPeekDesc = "Запоминает точку, при выстреле моментально оттягивает обратно в укрытие",
        AutoPeekKey = "Клавиша Auto-Peek",
        AutoPeekMarker = "Светящийся маркер",
        AutoPeekMarkerDesc = "Показывать круг возврата на полу за укрытием",
        AutoPeekColor = "Цвет маркера",
        AutoPeekSpeed = "Скорость возврата (Speed)",
        -- Auto-Win / Kill Aura
        AutoWinGroup = "Авто-Вин / Килл Аура",
        EnableAutoWin = "Включить Auto-Win",
        AutoWinDesc = "Моментальное убийство противника в раунде (авто-победа)",
        AutoWinMode = "Режим автовина",
        AutoWinKey = "Клавиша Auto-Win",
        AutoWinReturn = "Возврат на место после ТП",
        AutoWinReturnDesc = "После удара со спины мгновенно возвращает на исходную точку",
        AutoWinEquip = "Авто-доставать нож",
        AutoWinEquipDesc = "Автоматически берет нож в руку перед атакой",
        AutoWinDelay = "Задержка повтора (сек)",
        -- Legit Tab
        LegitAimbot = "Легит Аимбот (Smooth Aim)",
        EnableLegitAim = "Включить Legit Aim",
        LegitAimDesc = "Плавная человеческая доводка камеры к противнику",
        LegitAimKey = "Клавиша Legit Aim",
        LegitSmoothness = "Плавность доводки (Smooth)",
        LegitFOV = "Радиус легит FOV",
        DrawLegitFOV = "Отображать легит FOV",
        LegitHitbox = "Приоритет хитбокса",
        LegitWallCheck = "Проверка видимости (Wall Check)",
        LegitTriggerbot = "Легит Триггербот (Triggerbot)",
        EnableLegitTrigger = "Включить Legit Triggerbot",
        LegitTriggerDesc = "Авто-выстрел только когда реальный прицел мыши наведён на врага",
        ReactionDelay = "Человеческая задержка (мс)",
        -- Anti-Aim
        AnglesDesync = "Углы и Дезсинк",
        SpeedConfig = "Скорость и Настройки",
        EnableAA = "Включить Anti-Aim",
        AADesc = "Ломает траектории ножей и аимботы противников",
        YawMode = "Режим Yaw",
        PitchMode = "Режим Pitch",
        SpinSpeed = "Скорость вращения",
        PitchAngle = "Угол Pitch",
        JitterAngle = "Угол Jitter",
        SwayFreq = "Частота Sway",
        -- Movement
        BhopStrafes = "Баннихоп и Стрейфы",
        MovementBoost = "Ускорители движения",
        Bhop = "Bunny Hop (Bhop)",
        BhopDesc = "Автоматические прыжки при удержании Пробела",
        AirStrafes = "Instant Air Strafes",
        AirStrafesDesc = "Мгновенное изменение вектора скорости без задержки и КД (W/A/S/D)",
        BhopSpeed = "Bhop Speed (Разгон)",
        InfJump = "Бесконечный прыжок (Infinite Jump)",
        InfJumpDesc = "Прыгать в воздухе сколько угодно раз",
        WalkSpeed = "WalkSpeed Booster",
        -- Visuals
        ThirdPersonCam = "Камера 3-го лица",
        CrosshairVisuals = "Кастомный прицел (Crosshair)",
        ESPWorld = "ESP игроков и Chams",
        DrawingVisuals = "2D Боксы и Трейсеры",
        AmbienceWorld = "Кастомный Эмбиенс и Освещение",
        BulletTracers = "Хиттрейсеры пуль (Bullet Tracers)",
        EnableTP = "Включить 3-е лицо",
        TPDesc = "Нативный вид от 3-го лица (ровно по центру, без кривых углов)",
        CamDist = "Дистанция камеры",
        ShoulderX = "Смещение плеча (0 = Центр)",
        HeightY = "Высота камеры",
        FOV = "Поле зрения (FOV)",
        EnableESP = "Включить Chams ESP",
        ESPDesc = "Подсветка игроков и ботов через стены",
        ESPNames = "Имена и Дистанция",
        ESPNamesDesc = "Отображать ник и дистанцию над головой",
        ESPHealth = "Полоска здоровья",
        ESPHealthDesc = "Отображать динамическую полоску здоровья",
        ESPWeapon = "Отображать оружие",
        ESPWeaponDesc = "Показывать что враг держит в руках (Revolver / Knife)",
        ESPBots = "Подсвечивать ботов / нубов",
        ChamsTransp = "Прозрачность Chams",
        Fullbright = "Fullbright (Без темноты)",
        FullbrightDesc = "Удалить тени, темноту и туман на арене",
        -- 2D Visuals
        BoxESP = "2D Рамки (Box ESP)",
        BoxESPDesc = "Отображать 2D прямоугольники вокруг игроков",
        Snaplines = "Трейсеры (Snaplines)",
        SnaplinesDesc = "Отображать линии к игрокам",
        TracerOrigin = "Откуда рисовать линии",
        TracerBottom = "Снизу экрана",
        TracerCenter = "От прицела",
        HeadDots = "Точки на голове (Head Dots)",
        HeadDotsDesc = "Отображать кружки на голове противников",
        TargetLine = "Линия захвата аима (Target Line)",
        TargetLineDesc = "Показывает линию к текущей цели сайлент аима",
        EnableCrosshair = "Включить кастомный прицел",
        CrosshairSize = "Размер линий прицела",
        CrosshairGap = "Зазор прицела (Gap)",
        CrosshairThickness = "Толщина линий",
        CrosshairDot = "Центральная точка",
        -- Bullet Tracers
        EnableTracers = "Включить хиттрейсеры",
        TracersDesc = "Светящийся неоновый луч от дула револьвера до точки попадания",
        ShowImpact = "Точка попадания (Impact Dot)",
        ShowImpactDesc = "Светящаяся сфера в месте попадания пули",
        TracerDuration = "Длительность луча (сек)",
        TracerThickness = "Толщина луча",
        -- Custom Ambience
        EnableAmbience = "Включить кастомный эмбиенс",
        AmbienceDesc = "Кастомное освещение, время суток и атмосфера карты",
        AmbiencePreset = "Пресеты атмосферы",
        ClockTime = "Время суток (Часы)",
        FogDist = "Дистанция тумана (Fog)",
        Saturation = "Насыщенность цветов",
        AmbientColor = "Цвет Ambient",
        OutdoorColor = "Цвет OutdoorAmbient",
        FogColor = "Цвет тумана",
        -- Settings
        MenuSettings = "Настройки интерфейса",
        LanguageSettings = "Язык меню и Бинд",
        UnloadGroup = "Управление скриптом",
        Language = "Выбор языка",
        Unload = "Выгрузить меню (Unload)",
        MenuKey = "Клавиша меню",
        QuickKeySelect = "Быстрый выбор клавиши меню",
        ChangeMenuKey = "Нажмите для смены клавиши (Любая)",
        PressAnyKey = "Нажмите любую клавишу...",
        KeybindUpdated = "Клавиша меню изменена на",
        -- Skins Tab
        Skins = "Скины",
        SkinChanger = "Скинченджер оружия (Client-Side)",
        EnableSkinChanger = "Включить Скинченджер",
        SkinChangerDesc = "Визуально надевает любой скин на револьвер и нож (3D модели, PBR-текстуры, звуки и анимации)",
        RevolverSkinsGroup = "Скины на Револьвер",
        KnifeSkinsGroup = "Скины на Нож",
        RevolverSkinSelect = "Выбор скина револьвера",
        KnifeSkinSelect = "Выбор скина ножа",
        ApplySkins = "Применить скины",
        SaveAsAutoload = "Сохранить как автозагрузку",
        AutoloadSaved = "Скины сохранены в автозагрузку!",
        AutoSaveSkins = "Авто-сохранение скинов",
        AutoSaveSkinsDesc = "Автоматически сохранять выбранные скины в автозагрузку",
        AutoloadStatus = "Автозагрузка",
        -- Viewmodel & Weapon Scale
        ViewmodelGroup = "Кастомный Viewmodel (Положение оружия)",
        EnableViewmodel = "Включить Viewmodel",
        ViewmodelDesc = "Смещение и наклон оружия в руках от 1-го и 3-го лица",
        HideArms = "Скрыть руки (Hide Arms)",
        HideArmsDesc = "Делает руки полностью невидимыми (парящее оружие)",
        VMMode = "Режим смещения",
        VMArmAndWeapon = "Рука и оружие (Вместе)",
        VMWeaponOnly = "Только оружие",
        VMPreset = "Пресеты Viewmodel",
        VMOffsetX = "Смещение X (Влево / Вправо)",
        VMOffsetY = "Смещение Y (Вверх / Вниз)",
        VMOffsetZ = "Смещение Z (Вперед / Назад)",
        VMPitch = "Наклон Pitch (Вверх / Вниз)",
        VMYaw = "Поворот Yaw (Влево / Вправо)",
        VMRoll = "Крен Roll (Gangster Tilt)",
        WeaponScaleGroup = "Размер оружия (Weapon Scale)",
        EnableWeaponScale = "Включить изменение размера",
        WeaponScaleDesc = "Увеличивает или уменьшает 3D модель ножа и револьвера",
        WeaponScale = "Масштаб размера (Scale)",
        ScalePreset = "Пресеты размера",
        ResetViewmodel = "Сбросить по умолчанию",
    },
    EN = {
        Title = "Murder Duels | Skeet Edition",
        Rage = "Rage",
        Legit = "Legit",
        Combat = "Combat",
        AntiAim = "Anti-Aim",
        Movement = "Movement",
        Visuals = "Visuals",
        Settings = "Settings",
        -- Combat / Rage
        SilentAimbot = "Silent Aim & Trigger",
        EnableSilentAim = "Enable Silent Aim",
        SilentAimDesc = "Bullets & knives hit target WITHOUT moving camera",
        ActivationMode = "Aim Activation Mode",
        AlwaysOn = "Always On",
        HoldKey = "Hold Keybind",
        SilentAutoFire = "Silent Auto-Fire (Triggerbot)",
        SilentAutoFireDesc = "Automatically fires when aiming at enemy with Silent Aim (no camera snap)",
        AutoFireDelay = "Auto-Fire Delay (sec)",
        KnifeHoldDuration = "Knife Hold Time (sec)",
        KnifeHoldDurationDesc = "Duration triggerbot holds attack to throw knife (sec)",
        MuzzleCheck = "Muzzle Clearance Check",
        MuzzleCheckDesc = "Only fire when the revolver barrel has a direct line of sight (avoids walls/corners)",
        WallCheck = "Strict Wall Check",
        WallCheckDesc = "Do not shoot if target is behind solid walls or obstacles",
        TeamCheck = "Team Check",
        TeamCheckDesc = "Do not target teammates",
        Prediction = "Movement Prediction",
        PredictionDesc = "Lead knife/bullet based on target velocity",
        ProjSpeed = "Projectile Speed",
        MaxKnifePower = "Always Max Knife Power",
        MaxKnifePowerDesc = "Knife throws always have maximum velocity (420) and range even on weak taps",
        InstantKnifeCharge = "Instant Knife Charge",
        InstantKnifeChargeDesc = "Charges knife instantly in 0.01s with zero crosshair bloom",
        TargetFilters = "Target Filters & Hitbox",
        TargetPlayers = "Target Players",
        TargetNoobs = "Target Dummies (Noobs)",
        TargetBullseyes = "Target Shooting Bullseyes",
        HitboxPriority = "Hitbox Priority",
        DrawFOV = "Draw FOV Circle",
        FOVRadius = "FOV Radius",
        -- Auto-Peek
        AutoPeek = "Auto-Peek (Peek Assist)",
        EnableAutoPeek = "Enable Auto-Peek",
        AutoPeekDesc = "Records safe position, peeks, and pulls back behind cover after shot",
        AutoPeekKey = "Auto-Peek Keybind",
        AutoPeekMarker = "Show Return Marker",
        AutoPeekMarkerDesc = "Displays glowing circle marker on the ground at return point",
        AutoPeekColor = "Marker Color",
        AutoPeekSpeed = "Return Speed",
        -- Auto-Win / Kill Aura
        AutoWinGroup = "Auto-Win / Kill Aura",
        EnableAutoWin = "Enable Auto-Win",
        AutoWinDesc = "Instantly eliminates the opponent to win the round automatically",
        AutoWinMode = "Auto-Win Mode",
        AutoWinKey = "Auto-Win Keybind",
        AutoWinReturn = "Return to Origin After TP",
        AutoWinReturnDesc = "Instantly snaps character back to original position after backstab",
        AutoWinEquip = "Auto-Equip Knife",
        AutoWinEquipDesc = "Automatically pulls out the knife before attacking",
        AutoWinDelay = "Repeat Delay (sec)",
        -- Legit Tab
        LegitAimbot = "Legit Aimbot (Smooth Aim)",
        EnableLegitAim = "Enable Legit Aim",
        LegitAimDesc = "Smooth humanized camera aim assistance towards target",
        LegitAimKey = "Legit Aim Keybind",
        LegitSmoothness = "Aim Smoothness",
        LegitFOV = "Legit FOV Radius",
        DrawLegitFOV = "Draw Legit FOV Circle",
        LegitHitbox = "Hitbox Priority",
        LegitWallCheck = "Visibility Check (Wall Check)",
        LegitTriggerbot = "Legit Triggerbot",
        EnableLegitTrigger = "Enable Legit Triggerbot",
        LegitTriggerDesc = "Fires only when your crosshair is directly aimed at an enemy",
        ReactionDelay = "Reaction Delay (ms)",
        -- Anti-Aim
        AnglesDesync = "Angles & Desync",
        SpeedConfig = "Speed & Configuration",
        EnableAA = "Enable Anti-Aim",
        AADesc = "Breaks knife trajectories and opponent aimbots",
        YawMode = "Yaw Mode",
        PitchMode = "Pitch Mode",
        SpinSpeed = "Spinbot Speed",
        PitchAngle = "Pitch Angle",
        JitterAngle = "Jitter Angle",
        SwayFreq = "Sway Frequency",
        -- Movement
        BhopStrafes = "Bunny Hop & Air Strafes",
        MovementBoost = "Movement Boosters",
        Bhop = "Bunny Hop (Bhop)",
        BhopDesc = "Automatic jumps when holding Space without landing lag",
        AirStrafes = "Instant Air Strafes",
        AirStrafesDesc = "Instant velocity redirection without cooldown (W/A/S/D)",
        BhopSpeed = "Bhop Speed (Acceleration)",
        InfJump = "Infinite Jump",
        InfJumpDesc = "Jump in mid-air unlimited times",
        WalkSpeed = "WalkSpeed Booster",
        -- Visuals
        ThirdPersonCam = "3rd Person Camera",
        CrosshairVisuals = "Custom Crosshair",
        ESPWorld = "Player ESP & Chams",
        DrawingVisuals = "2D Boxes & Tracers",
        AmbienceWorld = "Custom Ambience & Lighting",
        BulletTracers = "Bullet Tracers",
        EnableTP = "Enable 3rd Person",
        TPDesc = "Native 3rd person perspective (centered, no crooked angles)",
        CamDist = "Camera Distance",
        ShoulderX = "Shoulder Offset (0 = Centered)",
        HeightY = "Height Offset",
        FOV = "Field Of View",
        EnableESP = "Enable Chams ESP",
        ESPDesc = "Highlight opponents and bots through walls",
        ESPNames = "Show Names & Distance",
        ESPNamesDesc = "Display username and distance above head",
        ESPHealth = "Show Health Bar",
        ESPHealthDesc = "Display dynamic health bar with current HP",
        ESPWeapon = "Show Equipped Weapon",
        ESPWeaponDesc = "Show held weapon (Revolver / Knife)",
        ESPBots = "Highlight Bots / Dummies",
        ChamsTransp = "Chams Transparency",
        Fullbright = "Fullbright (No Darkness)",
        FullbrightDesc = "Remove shadows, darkness, and fog",
        -- 2D Visuals
        BoxESP = "2D Box ESP",
        BoxESPDesc = "Draw 2D bounding boxes around players",
        Snaplines = "Snaplines / Tracers",
        SnaplinesDesc = "Draw lines pointing to enemies",
        TracerOrigin = "Tracer Origin",
        TracerBottom = "Bottom of Screen",
        TracerCenter = "Center / Crosshair",
        HeadDots = "Head Dots",
        HeadDotsDesc = "Draw clean dots on enemy heads",
        TargetLine = "Silent Aim Target Line",
        TargetLineDesc = "Shows a tracer to current silent aim target",
        EnableCrosshair = "Enable Custom Crosshair",
        CrosshairSize = "Crosshair Line Size",
        CrosshairGap = "Crosshair Gap",
        CrosshairThickness = "Line Thickness",
        CrosshairDot = "Center Dot",
        -- Bullet Tracers
        EnableTracers = "Enable Bullet Tracers",
        TracersDesc = "Glowing neon beam from weapon muzzle to impact point",
        ShowImpact = "Impact Dot",
        ShowImpactDesc = "Glowing neon sphere at bullet impact point",
        TracerDuration = "Tracer Duration (sec)",
        TracerThickness = "Tracer Thickness",
        -- Custom Ambience
        EnableAmbience = "Enable Custom Ambience",
        AmbienceDesc = "Custom world lighting, time of day and map atmosphere",
        AmbiencePreset = "Atmosphere Presets",
        ClockTime = "Time of Day (Hours)",
        FogDist = "Fog Distance",
        Saturation = "Color Saturation",
        AmbientColor = "Ambient Color",
        OutdoorColor = "OutdoorAmbient Color",
        FogColor = "Fog Color",
        -- Settings
        MenuSettings = "UI Settings",
        LanguageSettings = "Menu Language & Keybind",
        UnloadGroup = "Script Control",
        Language = "Select Language",
        Unload = "Unload Hub",
        MenuKey = "Menu Keybind",
        QuickKeySelect = "Quick Menu Key Select",
        ChangeMenuKey = "Click to Change Key (Any Key)",
        PressAnyKey = "Press any key...",
        KeybindUpdated = "Menu keybind updated to",
        -- Skins Tab
        Skins = "Skins",
        SkinChanger = "Weapon Skin Changer (Client-Side)",
        EnableSkinChanger = "Enable Skin Changer",
        SkinChangerDesc = "Visually equips any revolver & knife skin (3D models, PBR textures, sounds & animations)",
        RevolverSkinsGroup = "Revolver Skins",
        KnifeSkinsGroup = "Knife Skins",
        RevolverSkinSelect = "Select Revolver Skin",
        KnifeSkinSelect = "Select Knife Skin",
        ApplySkins = "Apply Skins",
        SaveAsAutoload = "Set as Autoload",
        AutoloadSaved = "Skins saved to autoload!",
        AutoSaveSkins = "Auto-Save Skins",
        AutoSaveSkinsDesc = "Automatically save selected skins to autoload",
        AutoloadStatus = "Autoload",
        -- Viewmodel & Weapon Scale
        ViewmodelGroup = "Custom Viewmodel (Weapon Position)",
        EnableViewmodel = "Enable Viewmodel Offset",
        ViewmodelDesc = "Offset and angle of weapon in hands (1st & 3rd person)",
        HideArms = "Hide Arms / Hands",
        HideArmsDesc = "Makes arms fully invisible (floating weapon view)",
        VMMode = "Offset Mode",
        VMArmAndWeapon = "Arm & Weapon (Together)",
        VMWeaponOnly = "Weapon Only",
        VMPreset = "Viewmodel Presets",
        VMOffsetX = "Offset X (Left / Right)",
        VMOffsetY = "Offset Y (Up / Down)",
        VMOffsetZ = "Offset Z (Forward / Back)",
        VMPitch = "Pitch Tilt (Up / Down)",
        VMYaw = "Yaw Angle (Left / Right)",
        VMRoll = "Roll Angle (Gangster Tilt)",
        WeaponScaleGroup = "Weapon Scale (Size)",
        EnableWeaponScale = "Enable Weapon Scale",
        WeaponScaleDesc = "Scales the 3D model size of knife and revolver",
        WeaponScale = "Scale Multiplier",
        ScalePreset = "Scale Presets",
        ResetViewmodel = "Reset to Default",
    }
}

local function T(k)
    local dict = Loc[currentLang] or Loc.RU
    return dict[k] or k
end

-- Load LinoriaLib & Addons
local Library = loadstring(game:HttpGet("https://raw.githubusercontent.com/GhostDuckyy/UI-Libraries/3b0bcba89893baa65d36b12b33e70e93ebc8b122/LinoriaLib/source.lua"))()
local ThemeManager = loadstring(game:HttpGet("https://raw.githubusercontent.com/GhostDuckyy/UI-Libraries/3b0bcba89893baa65d36b12b33e70e93ebc8b122/LinoriaLib/addons/ThemeManager.lua"))()
local SaveManager = loadstring(game:HttpGet("https://raw.githubusercontent.com/GhostDuckyy/UI-Libraries/3b0bcba89893baa65d36b12b33e70e93ebc8b122/LinoriaLib/addons/SaveManager.lua"))()

local Connections = _G.MD_GlobalConnections
local cachedTargets = {}
local silentAimTargetPart = nil
local silentAimTargetChar = nil

-- Combat variables (Silent Aim)
local silentAimEnabled = false
local teamCheckEnabled = true
local wallCheckEnabled = true
local wallbangEnabled = false
local targetPlayers = true
local targetNoobs = true
local targetTargets = true
local targetPartMode = "Head"
local fovRadius = 160
local showFovCircle = true
local silentAimMode = "AlwaysOn"
local alwaysMaxKnifePower = true
local instantKnifeCharge = true
local knifeSpeed = 6.5
_G.MD_AlwaysMaxKnifePower = true
_G.MD_KnifeSpeed = 6.5
_G.MD_WallbangEnabled = wallbangEnabled

-- Silent Auto-Fire (Triggerbot without camera snapping)
local silentAutoFire = false
local silentAutoFireDelay = 0.25
local knifeHoldDuration = 0.24
local lastSilentFireTime = 0
local muzzleCheckEnabled = false -- Muzzle Clearance Check (off by default so triggerbot is 100% reliable)

-- Auto-Peek (Peek Assist) State
local autoPeekEnabled = false
local autoPeekAnchor = nil
local autoPeekVisual = nil
local autoPeekColor = Color3.fromRGB(0, 255, 180)
local autoPeekShowMarker = true
local autoPeekReturnSpeed = 4.0
local autoPeekState = "IDLE" -- "IDLE", "RECORDED", "PEEKING", "RETURNING"

-- Auto-Win / Kill Aura State
local autoWinEnabled = false
local autoWinMode = "TP Backstab"
local autoWinDelay = 0.15
local autoWinReturn = true
local autoWinEquip = true
local lastAutoWinTime = 0
local isAutoWinExecuting = false

local function updateAutoPeekVisual()
    if autoPeekEnabled and autoPeekShowMarker and autoPeekAnchor then
        local container = workspace:FindFirstChild("Bin") or workspace.CurrentCamera
        if not autoPeekVisual or not autoPeekVisual.Parent then
            local marker = Instance.new("Part")
            marker.Name = "MD_AutoPeekMarker"
            marker.Anchored = true
            marker.CanCollide = false
            marker.CanTouch = false
            marker.CanQuery = false
            marker.CastShadow = false
            marker.Material = Enum.Material.Neon
            marker.Shape = Enum.PartType.Cylinder
            marker.Color = autoPeekColor
            marker.Transparency = 0.35
            marker.Size = Vector3.new(0.25, 4.5, 4.5)
            marker.Parent = container
            autoPeekVisual = marker
        end
        autoPeekVisual.Color = autoPeekColor
        autoPeekVisual.CFrame = CFrame.new(autoPeekAnchor.X, autoPeekAnchor.Y - 2.8, autoPeekAnchor.Z) * CFrame.Angles(0, 0, math.rad(90))
    else
        if autoPeekVisual then
            pcall(function() autoPeekVisual:Destroy() end)
            autoPeekVisual = nil
        end
    end
end

local function triggerAutoPeekReturn()
    if autoPeekEnabled and autoPeekAnchor and (autoPeekState == "PEEKING" or autoPeekState == "RECORDED") then
        task.delay(0.06, function()
            if autoPeekEnabled and autoPeekAnchor then
                autoPeekState = "RETURNING"
            end
        end)
    end
end

-- Legit Aimbot (Smooth Aim) State
local legitAimEnabled = false
local legitAimMode = "HoldKey"
local legitSmoothness = 6
local legitFovRadius = 85
local legitHitbox = "Head"
local legitShowFov = false
local legitWallCheck = true
local legitFovCircle = nil

-- Legit Triggerbot State
local legitTriggerEnabled = false
local legitTriggerDelay = 0.16
local legitTriggerTeamCheck = true
local legitTriggerStartTime = 0
local lastLegitTriggerFireTime = 0

-- Bullet Tracers / Hit Tracers State
local bulletTracersEnabled = true
local tracerColor = Color3.fromRGB(0, 255, 220) -- Neon Cyan
local tracerImpactColor = Color3.fromRGB(255, 60, 60) -- Neon Red
local tracerDuration = 1.0
local tracerThickness = 0.12
local tracerShowImpact = true

local function spawnBulletTracer(from, to)
    if not bulletTracersEnabled then return end
    if not from or not to then return end
    local dist = (to - from).Magnitude
    if dist < 0.5 or dist > 1500 then return end

    local container = workspace:FindFirstChild("Bin") or workspace.CurrentCamera
    if not container then return end

    task.spawn(function()
        pcall(function()
            -- Glowing Neon Cylinder Beam
            local tracer = Instance.new("Part")
            tracer.Name = "MD_BulletTracer"
            tracer.Anchored = true
            tracer.CanCollide = false
            tracer.CanTouch = false
            tracer.CanQuery = false
            tracer.CastShadow = false
            tracer.Material = Enum.Material.Neon
            tracer.Color = tracerColor
            tracer.Shape = Enum.PartType.Cylinder
            tracer.Size = Vector3.new(dist, tracerThickness, tracerThickness)
            tracer.CFrame = CFrame.lookAt((from + to) / 2, to) * CFrame.Angles(0, math.rad(90), 0)
            tracer.Parent = container

            local tracerTween = TweenService:Create(tracer, TweenInfo.new(tracerDuration, Enum.EasingStyle.Quad, Enum.EasingDirection.Out), {
                Transparency = 1
            })
            tracerTween.Completed:Connect(function()
                pcall(function() tracer:Destroy() end)
            end)
            tracerTween:Play()

            -- Glowing Neon Impact Dot at hit position
            if tracerShowImpact then
                local hitDot = Instance.new("Part")
                hitDot.Name = "MD_ImpactDot"
                hitDot.Anchored = true
                hitDot.CanCollide = false
                hitDot.CanTouch = false
                hitDot.CanQuery = false
                hitDot.CastShadow = false
                hitDot.Material = Enum.Material.Neon
                hitDot.Color = tracerImpactColor
                hitDot.Shape = Enum.PartType.Ball
                hitDot.Size = Vector3.new(tracerThickness * 2.5, tracerThickness * 2.5, tracerThickness * 2.5)
                hitDot.CFrame = CFrame.new(to)
                hitDot.Parent = container

                local dotTween = TweenService:Create(hitDot, TweenInfo.new(tracerDuration, Enum.EasingStyle.Quad, Enum.EasingDirection.Out), {
                    Transparency = 1,
                    Size = Vector3.new(0.01, 0.01, 0.01)
                })
                dotTween.Completed:Connect(function()
                    pcall(function() hitDot:Destroy() end)
                end)
                dotTween:Play()
            end
        end)
    end)
end

_G.MD_OnShotFired = function(from, to)
    if bulletTracersEnabled and from and to then
        spawnBulletTracer(from, to)
    end
    triggerAutoPeekReturn()
end

local isKnifeThrowing = false

local function fireWeapon()
    local myChar = LocalPlayer.Character
    local tool = myChar and myChar:FindFirstChildOfClass("Tool")
    local isKnife = tool and (tool.Name:lower():find("knife") ~= nil)

    local im = nil
    pcall(function()
        im = require(game:GetService("ReplicatedStorage"):WaitForChild("Extensions"):WaitForChild("InputMap"))
    end)

    if isKnife then
        if isKnifeThrowing then return end
        isKnifeThrowing = true
        if im and im.fire then im.fire("Attack", true) end
        pcall(mouse1press)
        task.delay(knifeHoldDuration, function()
            if im and im.fire then im.fire("Attack", false) end
            pcall(mouse1release)
            task.delay(0.20, function()
                isKnifeThrowing = false
            end)
        end)
    else
        if im and im.tap then
            im.tap("Attack")
        else
            pcall(function() mouse1click() end)
        end
    end
end

-- Anti-Aim variables
local aaEnabled = false
local aaYawMode = "Spinbot"
local aaPitchMode = "Down (Head Roll)"
local spinSpeed = 25
local jitterAngle = 90
local swayFreq = 8
local swayAngle = 75
local pitchAngle = 35
local currentYaw = 0
local defaultRjC0 = CFrame.new(0, 0, 0, -1, 0, 0, 0, 0, 1, 0, 1, -0)

-- Movement variables
local bhopEnabled = false
local bhopSpeed = 55
local instantStrafes = true
local infiniteJump = false

-- 3rd Person variables (Native Centered)
local thirdPersonEnabled = false
local cameraDistance = 10
local shoulderOffset = 0
local heightOffset = 1.3
local customFOV = 85

-- Visuals: Advanced ESP
local espEnabled = false
local espShowNames = true
local espShowDistance = true
local espShowHealth = true
local espShowWeapon = true
local espTargetBots = true
local espFillColor = Color3.fromRGB(255, 65, 65)
local espOutlineColor = Color3.fromRGB(255, 255, 255)
local espFillTransparency = 0.5
local espOutlineTransparency = 0
local espCache = {}

local fullbrightEnabled = false

-- Original Lighting State
local colorCorrection = Lighting:FindFirstChildOfClass("ColorCorrectionEffect")
local atmosphere = Lighting:FindFirstChildOfClass("Atmosphere")
local origLighting = {
    Ambient = Lighting.Ambient,
    OutdoorAmbient = Lighting.OutdoorAmbient,
    Brightness = Lighting.Brightness,
    ClockTime = Lighting.ClockTime,
    FogColor = Lighting.FogColor,
    FogEnd = Lighting.FogEnd,
    GlobalShadows = Lighting.GlobalShadows,
    TintColor = colorCorrection and colorCorrection.TintColor or Color3.fromRGB(255, 255, 255),
    Saturation = colorCorrection and colorCorrection.Saturation or 0,
    AtmoColor = atmosphere and atmosphere.Color or Color3.fromRGB(200, 200, 200),
    AtmoDecay = atmosphere and atmosphere.Decay or Color3.fromRGB(100, 100, 100),
}

-- Custom Ambience State
local customAmbienceEnabled = false
local customLighting = {
    ClockTime = 0,
    Ambient = Color3.fromRGB(90, 20, 140),
    OutdoorAmbient = Color3.fromRGB(45, 10, 80),
    FogColor = Color3.fromRGB(35, 5, 55),
    FogDistance = 450,
    TintColor = Color3.fromRGB(230, 200, 255),
    Saturation = 0.35,
}

local ambiencePresets = {
    ["Purple Night"] = { ClockTime = 0, Ambient = Color3.fromRGB(90, 20, 140), OutdoorAmbient = Color3.fromRGB(45, 10, 80), FogColor = Color3.fromRGB(35, 5, 55), FogEnd = 450, Tint = Color3.fromRGB(230, 200, 255), Saturation = 0.35 },
    ["Sunset"] = { ClockTime = 17.8, Ambient = Color3.fromRGB(180, 90, 60), OutdoorAmbient = Color3.fromRGB(130, 60, 40), FogColor = Color3.fromRGB(160, 80, 50), FogEnd = 550, Tint = Color3.fromRGB(255, 220, 180), Saturation = 0.25 },
    ["Blood Moon"] = { ClockTime = 0, Ambient = Color3.fromRGB(160, 20, 20), OutdoorAmbient = Color3.fromRGB(90, 10, 10), FogColor = Color3.fromRGB(70, 5, 5), FogEnd = 400, Tint = Color3.fromRGB(255, 180, 180), Saturation = 0.4 },
    ["Cyberpunk"] = { ClockTime = 21, Ambient = Color3.fromRGB(140, 30, 140), OutdoorAmbient = Color3.fromRGB(30, 140, 180), FogColor = Color3.fromRGB(30, 25, 60), FogEnd = 500, Tint = Color3.fromRGB(230, 180, 255), Saturation = 0.5 },
    ["Midnight"] = { ClockTime = 0, Ambient = Color3.fromRGB(25, 35, 70), OutdoorAmbient = Color3.fromRGB(15, 20, 45), FogColor = Color3.fromRGB(10, 15, 35), FogEnd = 600, Tint = Color3.fromRGB(200, 220, 255), Saturation = 0.15 },
    ["Toxic Green"] = { ClockTime = 0, Ambient = Color3.fromRGB(20, 120, 50), OutdoorAmbient = Color3.fromRGB(10, 70, 30), FogColor = Color3.fromRGB(15, 50, 20), FogEnd = 450, Tint = Color3.fromRGB(180, 255, 200), Saturation = 0.4 }
}

local function applyAmbience()
    if not customAmbienceEnabled then
        Lighting.ClockTime = origLighting.ClockTime
        Lighting.Ambient = origLighting.Ambient
        Lighting.OutdoorAmbient = origLighting.OutdoorAmbient
        Lighting.FogColor = origLighting.FogColor
        Lighting.FogEnd = origLighting.FogEnd
        if colorCorrection then
            colorCorrection.TintColor = origLighting.TintColor
            colorCorrection.Saturation = origLighting.Saturation
        end
        if atmosphere then
            atmosphere.Color = origLighting.AtmoColor
            atmosphere.Decay = origLighting.AtmoDecay
        end
        return
    end

    Lighting.ClockTime = customLighting.ClockTime
    Lighting.Ambient = customLighting.Ambient
    Lighting.OutdoorAmbient = customLighting.OutdoorAmbient
    Lighting.FogColor = customLighting.FogColor
    Lighting.FogEnd = customLighting.FogDistance

    if not colorCorrection then
        colorCorrection = Instance.new("ColorCorrectionEffect", Lighting)
    end
    colorCorrection.TintColor = customLighting.TintColor
    colorCorrection.Saturation = customLighting.Saturation

    if atmosphere then
        atmosphere.Color = customLighting.FogColor
        atmosphere.Decay = customLighting.OutdoorAmbient
    end
end

-- Rich 2D Visuals State
local boxEspEnabled = false
local boxColor = Color3.fromRGB(255, 65, 65)

local snaplinesEnabled = false
local snaplinesColor = Color3.fromRGB(255, 200, 50)
local snaplinesOrigin = "Bottom"

local headDotsEnabled = false
local headDotsColor = Color3.fromRGB(0, 255, 200)

local targetLineEnabled = false
local targetLineColor = Color3.fromRGB(50, 255, 50)
local targetLine = nil

local customCrosshairEnabled = false
local crosshairColor = Color3.fromRGB(0, 255, 120)
local crosshairSize = 6
local crosshairGap = 4
local crosshairThickness = 1.5
local crosshairDotEnabled = false
local crosshairLines = {}

local drawingCache = {}

-- Menu Keybind State
_G.MD_MenuToggleKey = _G.MD_MenuToggleKey or Enum.KeyCode.RightControl
local isListeningForMenuKey = false
local menuKeyLabelRef = nil

-- ==================== CLIENT-SIDE SKIN CHANGER STATE & LOGIC ====================
local skinChangerEnabled = false
local selectedRevolverSkin = "ChromaSniper"
local selectedKnifeSkin = "ChromaKatana"

-- Viewmodel & Weapon Scale State
local viewmodelEnabled = false
local hideArmsEnabled = false
local vmTargetMode = "ArmAndWeapon" -- "ArmAndWeapon" or "WeaponOnly"
local defaultRSC1 = CFrame.new(-0.5, 0.5, 0, 0, 0, 1, 0, 1, 0, -1, 0, 0)
local vm = {
    x = 0, y = 0, z = 0,
    pitch = 0, yaw = 0, roll = 0
}

local weaponScaleEnabled = false
local weaponScale = 1.0

local skinsConfigFile = "MurderDuelsSkeet/skins_autoload.json"

local function saveSkinsAutoload()
    pcall(function()
        if not isfolder("MurderDuelsSkeet") then
            pcall(makefolder, "MurderDuelsSkeet")
        end
        local data = {
            enabled = (skinChangerEnabled == true),
            revolver = selectedRevolverSkin or "ChromaSniper",
            knife = selectedKnifeSkin or "ChromaKatana",
        }
        writefile(skinsConfigFile, game:GetService("HttpService"):JSONEncode(data))
    end)
end

local function loadSkinsAutoload()
    local loaded = false
    pcall(function()
        if isfile(skinsConfigFile) then
            local content = readfile(skinsConfigFile)
            local data = game:GetService("HttpService"):JSONDecode(content)
            if typeof(data) == "table" then
                if data.enabled ~= nil then
                    skinChangerEnabled = (data.enabled == true)
                end
                if data.revolver and data.revolver ~= "" then
                    selectedRevolverSkin = data.revolver
                end
                if data.knife and data.knife ~= "" then
                    selectedKnifeSkin = data.knife
                end
                loaded = true
            end
        end
    end)
    return loaded
end

loadSkinsAutoload()

local originalRevolverSkin = LocalPlayer:GetAttribute("RevolverSkin") or "Default"
local originalKnifeSkin = LocalPlayer:GetAttribute("KnifeSkin") or "Default"

local availableKnives, availableRevolvers
do
    local topKnives = { "ChromaKatana", "CorruptedChromaKatana", "Voidreaver", "Balisong", "GalaxyKarambit", "Karambit", "GoldenStiletto", "RedStiletto", "Kunai", "Saber", "Solaris", "Seraphim", "Default" }
    local topRevolvers = { "ChromaSniper", "MurderNote", "GoldenLuger", "RedLuger", "PurpleLuger", "ChampionSniper", "Deagle", "InfinityRay", "RayGun", "Voidcaster", "Default" }

    local function buildSkinList(folderName, topPriority)
        local list = {}
        local seen = {}
        local folder = game:GetService("ReplicatedStorage"):FindFirstChild(folderName)
        if folder then
            for _, name in ipairs(topPriority) do
                if folder:FindFirstChild(name) then
                    table.insert(list, name)
                    seen[name] = true
                end
            end
            local rest = {}
            for _, child in ipairs(folder:GetChildren()) do
                if child:IsA("Model") and not seen[child.Name] and not child.Name:find("Root") and not child.Name:find("Test") then
                    table.insert(rest, child.Name)
                end
            end
            table.sort(rest)
            for _, name in ipairs(rest) do
                table.insert(list, name)
            end
        end
        if #list == 0 then
            list = topPriority
        end
        return list
    end

    availableKnives = buildSkinList("Knives", topKnives)
    availableRevolvers = buildSkinList("Revolvers", topRevolvers)
end

local function updateSlotPreview(slotName, folderName, skinName, isKnife)
    local playerGui = LocalPlayer:FindFirstChild("PlayerGui")
    if not playerGui then return end
    local inMatchUI = playerGui:FindFirstChild("InMatchUI")
    if not inMatchUI then return end
    local abilities = inMatchUI:FindFirstChild("Abilities")
    if not abilities then return end
    local slot = abilities:FindFirstChild(slotName)
    if not slot then return end
    local icon = slot:FindFirstChild("WeaponIcon")

    local existingVp = slot:FindFirstChild("MD_SkinViewport")

    if not skinChangerEnabled or not skinName or skinName == "Default" or skinName == "" then
        if existingVp then
            pcall(function() existingVp:Destroy() end)
        end
        if icon then
            icon.ImageTransparency = 0
        end
        return
    end

    local folder = game:GetService("ReplicatedStorage"):FindFirstChild(folderName)
    if not folder then return end
    local skinModel = folder:FindFirstChild(skinName)
    if not skinModel then return end

    if icon then
        icon.ImageTransparency = 1
    end

    local vp = existingVp
    if not vp then
        vp = Instance.new("ViewportFrame")
        vp.Name = "MD_SkinViewport"
        vp.Size = UDim2.fromScale(0.88, 0.88)
        vp.Position = UDim2.fromScale(0.5, 0.5)
        vp.AnchorPoint = Vector2.new(0.5, 0.5)
        vp.BackgroundTransparency = 1
        vp.BorderSizePixel = 0
        vp.ZIndex = (icon and icon.ZIndex or 5) + 1
        vp.Parent = slot
    end

    vp.Visible = true
    vp:ClearAllChildren()

    local clone = skinModel:Clone()
    for _, d in ipairs(clone:GetDescendants()) do
        if d:IsA("Sound") or d:IsA("ParticleEmitter") or d:IsA("Light") or d:IsA("Script") or d:IsA("LocalScript") or d:IsA("Trail") then
            pcall(function() d:Destroy() end)
        elseif d:IsA("BasePart") then
            d.CanCollide = false
            d.Anchored = true
        end
    end

    local rootName = isKnife and "KnifeRoot" or "RevolverRoot"
    local root = clone:FindFirstChild(rootName, true)

    local minB = Vector3.new(math.huge, math.huge, math.huge)
    local maxB = Vector3.new(-math.huge, -math.huge, -math.huge)
    local rootPos = root and root.Position
    local tipPos = rootPos
    local maxDistFromRoot = 0

    for _, p in ipairs(clone:GetDescendants()) do
        if p:IsA("BasePart") and p.Transparency < 0.9 and p.Name ~= "BoundingBox" and not p.Name:lower():find("hitbox") then
            local cf = p.CFrame
            local h = p.Size * 0.5
            for x = -1, 1, 2 do
                for y = -1, 1, 2 do
                    for z = -1, 1, 2 do
                        local pt = cf:PointToWorldSpace(Vector3.new(x*h.X, y*h.Y, z*h.Z))
                        minB = Vector3.new(math.min(minB.X, pt.X), math.min(minB.Y, pt.Y), math.min(minB.Z, pt.Z))
                        maxB = Vector3.new(math.max(maxB.X, pt.X), math.max(maxB.Y, pt.Y), math.max(maxB.Z, pt.Z))
                    end
                end
            end
            if rootPos then
                local d = (p.Position - rootPos).Magnitude
                if d > maxDistFromRoot then
                    maxDistFromRoot = d
                    tipPos = p.Position
                end
            end
        end
    end

    local center = (minB + maxB) * 0.5
    local size = maxB - minB

    for _, p in ipairs(clone:GetDescendants()) do
        if p:IsA("BasePart") then
            p.CFrame = p.CFrame - center
        end
    end
    clone.Parent = vp

    local forwardDir
    if rootPos and tipPos and (tipPos - rootPos).Magnitude > 0.1 then
        forwardDir = (tipPos - rootPos).Unit
    else
        if size.X >= size.Y and size.X >= size.Z then forwardDir = Vector3.new(1,0,0)
        elseif size.Y >= size.X and size.Y >= size.Z then forwardDir = Vector3.new(0,1,0)
        else forwardDir = Vector3.new(0,0,1) end
    end

    local axes = {
        { axis = Vector3.new(1, 0, 0), len = size.X },
        { axis = Vector3.new(0, 1, 0), len = size.Y },
        { axis = Vector3.new(0, 0, 1), len = size.Z }
    }
    table.sort(axes, function(a, b) return a.len < b.len end)
    local thinAxis = axes[1].axis

    local normal = (thinAxis - forwardDir * thinAxis:Dot(forwardDir))
    if normal.Magnitude < 0.01 then
        normal = (axes[2].axis - forwardDir * axes[2].axis:Dot(forwardDir))
    end
    normal = normal.Unit

    local S = normal:Cross(forwardDir).Unit

    if not isKnife then
        local trueUp = (root and root.CFrame.UpVector) or Vector3.new(0, 1, 0)
        if S:Dot(trueUp) < 0 then
            S = -S
            normal = -normal
        end
    end
    local F = forwardDir
    local camRight, camUp
    if isKnife then
        camRight = (-F * 0.707 + S * 0.707).Unit
        camUp    = ( F * 0.707 + S * 0.707).Unit
    else
        camRight = (-F * 0.92 + S * 0.38).Unit
        camUp    = ( F * 0.38 + S * 0.92).Unit
    end

    local camLook = camRight:Cross(camUp).Unit

    local maxSpan = math.sqrt(size.X*size.X + size.Y*size.Y + size.Z*size.Z) * 0.65
    if maxSpan < 0.1 then maxSpan = 1 end

    local cam = Instance.new("Camera")
    cam.FieldOfView = 25
    local dist = (maxSpan * 0.5) / math.tan(math.rad(12.5)) * 1.25

    cam.CFrame = CFrame.fromMatrix(-camLook * dist, camRight, camUp, -camLook)
    cam.Parent = vp
    vp.CurrentCamera = cam

    vp.LightColor = Color3.fromRGB(255, 255, 255)
    vp.LightDirection = (-camLook + Vector3.new(0.4, 0.4, 0.4)).Unit
    vp.Ambient = Color3.fromRGB(200, 200, 200)
end

local function applySkins()
    if skinChangerEnabled then
        if selectedRevolverSkin and selectedRevolverSkin ~= "" then
            LocalPlayer:SetAttribute("RevolverSkin", selectedRevolverSkin)
            LocalPlayer:SetAttribute("RevolverName", selectedRevolverSkin)
        end
        if selectedKnifeSkin and selectedKnifeSkin ~= "" then
            LocalPlayer:SetAttribute("KnifeSkin", selectedKnifeSkin)
            LocalPlayer:SetAttribute("KnifeName", selectedKnifeSkin)
        end
    else
        LocalPlayer:SetAttribute("RevolverSkin", originalRevolverSkin)
        LocalPlayer:SetAttribute("KnifeSkin", originalKnifeSkin)
    end

    pcall(function()
        updateSlotPreview("Gun", "Revolvers", selectedRevolverSkin, false)
        updateSlotPreview("Knife", "Knives", selectedKnifeSkin, true)
    end)
end

_G.MD_SetSkin = function(gun, knife)
    skinChangerEnabled = true
    if gun then selectedRevolverSkin = gun end
    if knife then selectedKnifeSkin = knife end
    saveSkinsAutoload()
    applySkins()
end

if skinChangerEnabled then
    task.spawn(function()
        task.wait(0.15)
        applySkins()
    end)
end

table.insert(Connections, LocalPlayer:GetAttributeChangedSignal("RevolverSkin"):Connect(function()
    if skinChangerEnabled and selectedRevolverSkin and selectedRevolverSkin ~= "" and LocalPlayer:GetAttribute("RevolverSkin") ~= selectedRevolverSkin then
        LocalPlayer:SetAttribute("RevolverSkin", selectedRevolverSkin)
        LocalPlayer:SetAttribute("RevolverName", selectedRevolverSkin)
    end
end))

table.insert(Connections, LocalPlayer:GetAttributeChangedSignal("KnifeSkin"):Connect(function()
    if skinChangerEnabled and selectedKnifeSkin and selectedKnifeSkin ~= "" and LocalPlayer:GetAttribute("KnifeSkin") ~= selectedKnifeSkin then
        LocalPlayer:SetAttribute("KnifeSkin", selectedKnifeSkin)
        LocalPlayer:SetAttribute("KnifeName", selectedKnifeSkin)
    end
end))

table.insert(Connections, LocalPlayer.CharacterAdded:Connect(function()
    task.wait(0.25)
    if skinChangerEnabled then
        applySkins()
    end
end))

do
    local inMatchUIObj = LocalPlayer:FindFirstChild("PlayerGui") and LocalPlayer.PlayerGui:FindFirstChild("InMatchUI")
    if inMatchUIObj then
        table.insert(Connections, inMatchUIObj:GetPropertyChangedSignal("Enabled"):Connect(function()
            if inMatchUIObj.Enabled and skinChangerEnabled then
                task.wait(0.1)
                applySkins()
            end
        end))
        local abilitiesObj = inMatchUIObj:FindFirstChild("Abilities")
        if abilitiesObj then
            table.insert(Connections, abilitiesObj:GetPropertyChangedSignal("Visible"):Connect(function()
                if abilitiesObj.Visible and skinChangerEnabled then
                    task.wait(0.1)
                    applySkins()
                end
            end))
        end
    end

    if LocalPlayer:FindFirstChild("PlayerGui") then
        table.insert(Connections, LocalPlayer.PlayerGui.ChildAdded:Connect(function(child)
            if child.Name == "InMatchUI" and skinChangerEnabled then
                task.wait(0.2)
                applySkins()
            end
        end))
    end
end

-- FOV Circle & Drawing Initialization
local fovCircle = nil
if typeof(Drawing) == "table" and Drawing.new then
    pcall(function()
        fovCircle = Drawing.new("Circle")
        fovCircle.Thickness = 1.5
        fovCircle.NumSides = 64
        fovCircle.Radius = fovRadius
        fovCircle.Filled = false
        fovCircle.Color = Color3.fromRGB(255, 75, 75)
        fovCircle.Visible = false
        fovCircle.Transparency = 0.8

        legitFovCircle = Drawing.new("Circle")
        legitFovCircle.Thickness = 1.5
        legitFovCircle.NumSides = 64
        legitFovCircle.Radius = legitFovRadius
        legitFovCircle.Filled = false
        legitFovCircle.Color = Color3.fromRGB(60, 180, 255)
        legitFovCircle.Visible = false
        legitFovCircle.Transparency = 0.8

        targetLine = Drawing.new("Line")
        targetLine.Thickness = 1.5
        targetLine.Color = targetLineColor
        targetLine.Visible = false

        crosshairLines.h1 = Drawing.new("Line")
        crosshairLines.h2 = Drawing.new("Line")
        crosshairLines.v1 = Drawing.new("Line")
        crosshairLines.v2 = Drawing.new("Line")
        crosshairLines.dot = Drawing.new("Circle")
        crosshairLines.dot.Radius = 1.5
        crosshairLines.dot.Filled = true
        for _, l in pairs(crosshairLines) do
            l.Visible = false
        end
    end)
end

-- ==================== 0. MOUSE UNLOCK FOR SLIDERS ====================
local function maintainMouseAndOrder()
    local isMenuOpen = (Library and Library.IsOpen) or false
    if isMenuOpen then
        if LocalPlayer:GetAttribute("MouseUnlocked") ~= 1 then
            LocalPlayer:SetAttribute("MouseUnlocked", 1)
        end
        if UserInputService.MouseBehavior ~= Enum.MouseBehavior.Default then
            UserInputService.MouseBehavior = Enum.MouseBehavior.Default
        end
        UserInputService.MouseIconEnabled = true
    else
        if LocalPlayer:GetAttribute("MouseUnlocked") == 1 then
            LocalPlayer:SetAttribute("MouseUnlocked", nil)
        end
    end
end

table.insert(Connections, RunService.RenderStepped:Connect(maintainMouseAndOrder))

-- ==================== 1. HOOKS: TRUE SILENT AIM & BULLET TRACERS ====================
_G.MD_SilentAimEnabled = false
_G.MD_SilentAimTarget = nil
_G.MD_PredictionEnabled = false
_G.MD_CurrentWeaponIsKnife = false
local getAnyEnemyTarget = nil

_G.MD_NIL = _G.MD_NIL or newproxy()

-- Dynamic Metamethod Dispatchers (Ultra-optimized, zero allocations on non-target calls)
_G.MD_OnNamecall = function(self, method, ...)
    if method ~= "FireServer" and method ~= "Fire" and method ~= "ViewportPointToRay" and method ~= "Raycast" then
        return nil
    end

    if method == "Raycast" then
        if _G.MD_WallbangEnabled then
            local origin, direction, rayParams = ...
            if typeof(rayParams) == "RaycastParams" and rayParams.FilterType == Enum.RaycastFilterType.Exclude then
                -- Bypasses obstacle/wall collision for knife and bullet in ProjectilesController
                return _G.MD_NIL
            end
        end
        return nil
    end

    if method == "ViewportPointToRay" then
        if _G.MD_SilentAimEnabled and _G.MD_SilentAimTarget then
            local target = _G.MD_SilentAimTarget
            if target and target.Parent and self:IsA("Camera") then
                local camPos = self.CFrame.Position
                local targetPos = target.Position
                return Ray.new(camPos, (targetPos - camPos).Unit)
            end
        end
        return nil
    end

    if method == "Fire" then
        if self.Name == "SpawnKnife" then
            local shotData = ...
            if typeof(shotData) == "table" then
                shotData.power = _G.MD_KnifeSpeed or 6.5
                if _G.MD_SilentAimEnabled and _G.MD_SilentAimTarget then
                    local tgt = _G.MD_SilentAimTarget
                    local targetPos = tgt.Position
                    local origin = shotData.origin or workspace.CurrentCamera.CFrame.Position
                    shotData.target = origin + (targetPos - origin).Unit * 1000
                end
            end
            return nil
        end
        if self.Name == "SpawnBullet" then
            local shotData = ...
            if typeof(shotData) == "table" and _G.MD_SilentAimEnabled and _G.MD_SilentAimTarget then
                local tgt = _G.MD_SilentAimTarget
                shotData.hitInstance = tgt
                shotData.hitPos = tgt.Position
                shotData.to = tgt.Position
                shotData.isCharacterHit = true
                if typeof(shotData.segments) == "table" then
                    for _, seg in ipairs(shotData.segments) do
                        seg.hitInstance = tgt
                        seg.hitPos = tgt.Position
                        seg.isCharacterHit = true
                    end
                end
            end
            return nil
        end
        return nil
    end

    if method == "FireServer" then
        if self.Name == "ThrowReplicate" then
            local shotData = ...
            if typeof(shotData) == "table" then
                shotData.power = 1.0
                if _G.MD_SilentAimEnabled and _G.MD_SilentAimTarget then
                    local tgt = _G.MD_SilentAimTarget
                    local targetPos = tgt.Position
                    local origin = shotData.origin or workspace.CurrentCamera.CFrame.Position
                    shotData.target = origin + (targetPos - origin).Unit * 1000
                end
            end
        end

        if self.Name == "ShootReplicate" then
            local shotData = ...
            if typeof(shotData) == "table" and _G.MD_SilentAimEnabled and _G.MD_SilentAimTarget then
                local tgt = _G.MD_SilentAimTarget
                shotData.hitInstance = tgt
                shotData.hitPos = tgt.Position
                shotData.to = tgt.Position
                shotData.isCharacterHit = true
                if typeof(shotData.segments) == "table" then
                    for _, seg in ipairs(shotData.segments) do
                        seg.hitInstance = tgt
                        seg.hitPos = tgt.Position
                        seg.isCharacterHit = true
                    end
                end
            end
        end

        if self.Name == "ShootReplicate" or self.Name == "ThrowReplicate" then
            local shotData = ...
            if _G.MD_OnShotFired and typeof(shotData) == "table" then
                task.spawn(function()
                    pcall(function()
                        if shotData.segments and #shotData.segments > 0 then
                            for _, seg in ipairs(shotData.segments) do
                                if seg.from and seg.hitPos then
                                    _G.MD_OnShotFired(seg.from, seg.hitPos)
                                end
                            end
                        elseif shotData.origin and (shotData.hitPos or shotData.to or shotData.target) then
                            _G.MD_OnShotFired(shotData.origin, shotData.hitPos or shotData.to or shotData.target)
                        end
                    end)
                end)
            end
        end
        return nil
    end

    return nil
end

_G.MD_OnIndex = function(self, key)
    -- Fast exit: NEVER touch anything unless the key is specifically "Hit" or "Target"
    if key ~= "Hit" and key ~= "Target" then
        return nil
    end

    if not _G.MD_SilentAimEnabled or not _G.MD_SilentAimTarget then
        return nil
    end

    -- Verify caller is mouse without triggering recursive metamethod calls
    if typeof(self) == "Instance" and self.ClassName == "PlayerMouse" then
        local target = _G.MD_SilentAimTarget
        if target and target.Parent then
            local targetPos = target.Position

            if key == "Hit" then
                return CFrame.new(targetPos)
            elseif key == "Target" then
                return target
            end
        end
    end

    return nil
end

if not _G.MD_HooksInstalled then
    local oldNamecall
    oldNamecall = hookmetamethod(game, "__namecall", function(self, ...)
        local method = getnamecallmethod()
        if _G.MD_OnNamecall then
            local override = _G.MD_OnNamecall(self, method, ...)
            if override == _G.MD_NIL then
                return nil
            elseif override ~= nil then
                return override
            end
        end
        return oldNamecall(self, ...)
    end)

    local oldIndex
    oldIndex = hookmetamethod(game, "__index", function(self, key)
        if _G.MD_OnIndex then
            local override = _G.MD_OnIndex(self, key)
            if override ~= nil then
                return override
            end
        end
        return oldIndex(self, key)
    end)

    _G.MD_HooksInstalled = true
end

-- ==================== 2. STRICT TARGET & HP VALIDATION ====================
local function isEnemy(plr)
    if plr == LocalPlayer then return false end
    if not teamCheckEnabled then return true end
    if LocalPlayer.Team and plr.Team then
        if LocalPlayer.Team.Name == "Lobby" and plr.Team.Name == "Lobby" then
            return true
        end
        return LocalPlayer.Team ~= plr.Team
    end
    if LocalPlayer.TeamColor and plr.TeamColor then
        return LocalPlayer.TeamColor ~= plr.TeamColor
    end
    return true
end

local function getTargetAimPart(char)
    if not char then return nil end
    if targetPartMode == "Head" then
        return char:FindFirstChild("Head") or char:FindFirstChild("HumanoidRootPart")
    elseif targetPartMode == "Torso" then
        return char:FindFirstChild("Torso") or char:FindFirstChild("UpperTorso") or char:FindFirstChild("HumanoidRootPart")
    else
        return char:FindFirstChild("HumanoidRootPart") or char:FindFirstChild("Torso")
    end
end

local function isTargetAliveAndValid(target)
    if not target then return false end
    local part = target.part
    local char = target.char
    if not part or not part.Parent or not part:IsDescendantOf(workspace) then
        return false
    end
    if part.Transparency > 0.8 then
        return false
    end

    if char then
        if not char:IsDescendantOf(workspace) then return false end
        if char:FindFirstChildOfClass("ForceField") then return false end

        local hum = char:FindFirstChildOfClass("Humanoid")
        if hum then
            if hum.Health <= 0 then return false end
            local state = hum:GetState()
            if state == Enum.HumanoidStateType.Dead then return false end
        end

        if char:GetAttribute("Dead") == true or char:GetAttribute("Invulnerable") == true then
            return false
        end

        local plr = Players:GetPlayerFromCharacter(char)
        if plr then
            if plr.Parent ~= Players then return false end
            if not isEnemy(plr) then return false end
        end
    end

    return true
end

local function isTargetVisible(origin, part, char)
    if wallbangEnabled then return true end
    if not wallCheckEnabled then return true end
    local dir = part.Position - origin
    local dist = dir.Magnitude
    if dist <= 0.5 then return true end

    local rayParams = RaycastParams.new()
    rayParams.FilterType = Enum.RaycastFilterType.Exclude
    rayParams.FilterDescendantsInstances = { workspace.CurrentCamera, LocalPlayer.Character, workspace:FindFirstChild("Bin") }
    rayParams.IgnoreWater = true

    local hit = workspace:Raycast(origin, dir.Unit * dist, rayParams)
    if not hit then
        return true
    end

    local hitInst = hit.Instance
    if hitInst == part or (char and hitInst:IsDescendantOf(char)) then
        return true
    end

    -- Pierce thin transparent glass, destructibles glass, or non-collidable cosmetic parts
    local hitName = hitInst.Name:lower()
    if (hitInst.Material == Enum.Material.Glass and hitInst.Transparency > 0.3) or hitName:find("glass") or (not hitInst.CanCollide and hitInst.Transparency > 0.6) then
        local secondaryOrigin = hit.Position + (dir.Unit * 0.15)
        local remainingDist = (part.Position - secondaryOrigin).Magnitude
        if remainingDist <= 0.5 then return true end

        local hit2 = workspace:Raycast(secondaryOrigin, dir.Unit * remainingDist, rayParams)
        if not hit2 then return true end
        if hit2.Instance == part or (char and hit2.Instance:IsDescendantOf(char)) then
            return true
        end
    end

    return false
end

local sharedRayParams = RaycastParams.new()
sharedRayParams.FilterType = Enum.RaycastFilterType.Exclude
sharedRayParams.IgnoreWater = true

-- Exact Weapon Muzzle / Barrel Position (Where bullets and thrown knives spawn)
local function getWeaponMuzzlePosition()
    local char = LocalPlayer.Character
    if not char then return nil end

    local tool = char:FindFirstChildOfClass("Tool")
    if not tool then
        tool = char:FindFirstChild("Revolver") or char:FindFirstChild("Knife")
    end

    if tool then
        local handle = tool:FindFirstChild("Handle")
        if handle and handle:IsA("BasePart") then
            return (handle.CFrame * CFrame.new(0, 0.2, -1.6)).Position
        end
        local p = tool:FindFirstChildWhichIsA("BasePart")
        if p then
            return (p.CFrame * CFrame.new(0, 0.2, -1.6)).Position
        end
    end

    local rightArm = char:FindFirstChild("Right Arm") or char:FindFirstChild("RightHand")
    if rightArm and rightArm:IsA("BasePart") then
        return (rightArm.CFrame * CFrame.new(0, 0, -1.5)).Position
    end

    local head = char:FindFirstChild("Head")
    return head and head.Position or nil
end

-- Muzzle Clearance Check: Guarantees the revolver barrel/tip has an open line of fire
local function canMuzzleHitTarget(targetPart, targetChar)
    if not targetPart or not targetPart:IsDescendantOf(workspace) then
        return false
    end

    local muzzlePos = getWeaponMuzzlePosition()
    if not muzzlePos then
        return true -- If muzzle position cannot be determined, do not block firing
    end

    local dir = targetPart.Position - muzzlePos
    local dist = dir.Magnitude
    if dist <= 1.0 then
        return true
    end

    sharedRayParams.FilterDescendantsInstances = {
        workspace.CurrentCamera,
        LocalPlayer.Character,
        workspace:FindFirstChild("Bin"),
        workspace:FindFirstChild("RaycastIgnore")
    }

    local hit = workspace:Raycast(muzzlePos, dir.Unit * dist, sharedRayParams)
    if not hit then
        return true
    end

    local hitInst = hit.Instance
    if not hitInst then return true end

    -- Hit target player or part
    if hitInst == targetPart or (targetChar and hitInst:IsDescendantOf(targetChar)) then
        return true
    end

    -- Ignore non-collidable parts (cosmetics, invisible barriers, triggers, hitboxes)
    if not hitInst.CanCollide or hitInst.Transparency > 0.6 then
        return true
    end

    -- Transparent destructibles / glass piercing
    local hitName = hitInst.Name:lower()
    if (hitInst.Material == Enum.Material.Glass and hitInst.Transparency > 0.3) or hitName:find("glass") then
        local secondaryOrigin = hit.Position + (dir.Unit * 0.25)
        local remainingDist = (targetPart.Position - secondaryOrigin).Magnitude
        if remainingDist <= 0.5 then return true end

        local hit2 = workspace:Raycast(secondaryOrigin, dir.Unit * remainingDist, sharedRayParams)
        if not hit2 then return true end
        if hit2.Instance == targetPart or (targetChar and hit2.Instance:IsDescendantOf(targetChar)) or not hit2.Instance.CanCollide then
            return true
        end
    end

    return false
end

local staticLobbyTargets = {}
local function cacheStaticLobbyTargets()
    table.clear(staticLobbyTargets)
    pcall(function()
        local lobby = workspace:FindFirstChild("Lobby")
        if lobby then
            for _, obj in ipairs(lobby:GetDescendants()) do
                if obj:IsA("BasePart") and (obj.Name:lower():find("target") or obj.Name:lower():find("bullseye")) and obj.Transparency < 0.8 then
                    table.insert(staticLobbyTargets, obj)
                end
            end
        end
    end)
end
task.spawn(cacheStaticLobbyTargets)

local function refreshTargetCache()
    local list = {}
    local seenModels = {}
    local myCam = workspace.CurrentCamera
    local myPos = myCam.CFrame.Position

    -- 1. Real Players
    if targetPlayers then
        for _, plr in ipairs(Players:GetPlayers()) do
            if isEnemy(plr) and plr.Character then
                local hum = plr.Character:FindFirstChildOfClass("Humanoid")
                local part = getTargetAimPart(plr.Character)
                if hum and hum.Health > 0 and part and hum:GetState() ~= Enum.HumanoidStateType.Dead then
                    local dist = (part.Position - myPos).Magnitude
                    if dist <= 350 and math.abs(part.Position.Y - myPos.Y) < 150 then
                        seenModels[plr.Character] = true
                        table.insert(list, { part = part, char = plr.Character, name = plr.Name })
                    end
                end
            end
        end
    end

    -- 2. Models in workspace.Characters (Opponents, bots, dummies)
    if workspace:FindFirstChild("Characters") then
        for _, m in ipairs(workspace.Characters:GetChildren()) do
            if m:IsA("Model") and m ~= LocalPlayer.Character and not seenModels[m] then
                local plr = Players:GetPlayerFromCharacter(m)
                local isTarget = false
                if plr then
                    if isEnemy(plr) and targetPlayers then isTarget = true end
                else
                    if targetNoobs then isTarget = true end
                end

                if isTarget then
                    local hum = m:FindFirstChildOfClass("Humanoid")
                    local part = getTargetAimPart(m)
                    if hum and hum.Health > 0 and part and hum:GetState() ~= Enum.HumanoidStateType.Dead then
                        local dist = (part.Position - myPos).Magnitude
                        if dist <= 350 and math.abs(part.Position.Y - myPos.Y) < 150 then
                            seenModels[m] = true
                            table.insert(list, { part = part, char = m, name = plr and plr.Name or m.Name })
                        end
                    end
                end
            end
        end
    end

    -- 3. Targets in Lobby (Pre-cached static targets, zero lag!)
    if targetTargets and #staticLobbyTargets > 0 then
        for _, obj in ipairs(staticLobbyTargets) do
            if obj and obj.Parent and obj:IsDescendantOf(workspace) then
                local dist = (obj.Position - myPos).Magnitude
                if dist <= 250 and math.abs(obj.Position.Y - myPos.Y) < 100 then
                    table.insert(list, { part = obj, char = obj.Parent, name = "Target" })
                end
            end
        end
    end

    cachedTargets = list
    _G.MD_CachedTargets = list
end

pcall(refreshTargetCache)

task.spawn(function()
    while isAlive do
        task.wait(0.3)
        pcall(refreshTargetCache)
    end
end)

local function getBestSilentTarget()
    local best = nil
    local bestScore = math.huge
    local myCam = workspace.CurrentCamera
    local screenCenter = Vector2.new(myCam.ViewportSize.X / 2, myCam.ViewportSize.Y / 2)
    local camPos = myCam.CFrame.Position

    for _, t in ipairs(cachedTargets) do
        if isTargetAliveAndValid(t) then
            local part = t.part
            local screenPos, onScreen = myCam:WorldToViewportPoint(part.Position)
            local dist2D = (Vector2.new(screenPos.X, screenPos.Y) - screenCenter).Magnitude
            local dist3D = (part.Position - camPos).Magnitude

            if onScreen and dist2D <= fovRadius and dist3D <= 350 then
                if isTargetVisible(camPos, part, t.char) then
                    if dist2D < bestScore then
                        bestScore = dist2D
                        best = { part = part, char = t.char, dist3D = dist3D, name = t.name }
                    end
                end
            end
        end
    end
    return best
end

local function getBestLegitTarget()
    local best = nil
    local bestDist2D = math.huge
    local myCam = workspace.CurrentCamera
    local screenCenter = Vector2.new(myCam.ViewportSize.X / 2, myCam.ViewportSize.Y / 2)
    local camPos = myCam.CFrame.Position

    for _, t in ipairs(cachedTargets) do
        if isTargetAliveAndValid(t) then
            local part = t.part
            if legitHitbox == "Head" and t.char then
                part = t.char:FindFirstChild("Head") or t.part
            elseif legitHitbox == "Torso" and t.char then
                part = t.char:FindFirstChild("Torso") or t.char:FindFirstChild("UpperTorso") or t.part
            end
            local screenPos, onScreen = myCam:WorldToViewportPoint(part.Position)
            if onScreen then
                local dist2D = (Vector2.new(screenPos.X, screenPos.Y) - screenCenter).Magnitude
                local dist3D = (part.Position - camPos).Magnitude
                if dist2D <= legitFovRadius and dist3D <= 350 then
                    if not legitWallCheck or isTargetVisible(camPos, part, t.char) then
                        if dist2D < bestDist2D then
                            bestDist2D = dist2D
                            best = { part = part, char = t.char, screenPos = screenPos }
                        end
                    end
                end
            end
        end
    end
    return best
end

getAnyEnemyTarget = function()
    local myChar = LocalPlayer.Character
    local myHRP = myChar and (myChar:FindFirstChild("HumanoidRootPart") or myChar:FindFirstChild("Torso"))
    if not myHRP then return nil end
    local myPos = myHRP.Position
    local mySide = LocalPlayer:GetAttribute("MatchSide")

    local best = nil
    local bestDist = math.huge

    local function checkModel(m)
        if not m or not m:IsA("Model") or m == myChar then return end
        if m:FindFirstChildOfClass("ForceField") then return end
        local hum = m:FindFirstChildOfClass("Humanoid")
        if not hum or hum.Health <= 0 or hum:GetState() == Enum.HumanoidStateType.Dead then return end
        local hrp = m:FindFirstChild("HumanoidRootPart") or m:FindFirstChild("Torso") or m:FindFirstChild("UpperTorso")
        if not hrp then return end

        local plr = Players:GetPlayerFromCharacter(m)
        if plr then
            if not isEnemy(plr) then return end
        else
            if mySide and m:GetAttribute("MatchSide") == mySide then return end
            if not targetNoobs and m.Name == "Noob" then return end
        end

        local aimPart = getTargetAimPart(m) or hrp
        local dist = (hrp.Position - myPos).Magnitude
        if dist < bestDist then
            bestDist = dist
            best = {
                char = m,
                hrp = hrp,
                part = aimPart,
                player = plr,
                dist = dist
            }
        end
    end

    for _, plr in ipairs(Players:GetPlayers()) do
        if plr ~= LocalPlayer and isEnemy(plr) and plr.Character then
            checkModel(plr.Character)
        end
    end

    if workspace:FindFirstChild("Characters") then
        for _, m in ipairs(workspace.Characters:GetChildren()) do
            checkModel(m)
        end
    end

    return best
end

local function executeAutoWin()
    if isAutoWinExecuting then return end
    local myChar = LocalPlayer.Character
    if not myChar then return end
    local myHRP = myChar:FindFirstChild("HumanoidRootPart") or myChar:FindFirstChild("Torso")
    local myHum = myChar:FindFirstChildOfClass("Humanoid")
    if not myHRP or not myHum or myHum.Health <= 0 then return end

    local target = getAnyEnemyTarget()
    if not target or not target.hrp or not target.char then return end

    isAutoWinExecuting = true

    local bp = LocalPlayer:FindFirstChild("Backpack")
    local currentTool = myChar:FindFirstChildOfClass("Tool")
    local currentToolName = currentTool and currentTool.Name:lower() or ""
    local knifeInBp = bp and bp:FindFirstChild("Knife")
    local revInBp = bp and bp:FindFirstChild("Revolver")
    local hasKnife = currentToolName:find("knife") ~= nil or knifeInBp ~= nil

    if autoWinEquip then
        if autoWinMode == "TP Backstab" and knifeInBp and currentToolName:find("knife") == nil then
            myHum:EquipTool(knifeInBp)
            task.wait(0.04)
        elseif autoWinMode == "360° Auto-Throw" then
            if not currentTool then
                local tToEquip = knifeInBp or revInBp
                if tToEquip then
                    myHum:EquipTool(tToEquip)
                    task.wait(0.04)
                end
            end
        end
    end

    currentTool = myChar:FindFirstChildOfClass("Tool")
    currentToolName = currentTool and currentTool.Name:lower() or ""

    if autoWinMode == "TP Backstab" and hasKnife then
        local originalCFrame = myHRP.CFrame
        local targetHRP = target.hrp
        local targetChar = target.char
        local targetPlr = target.player

        local targetLook = targetHRP.CFrame.LookVector
        local behindPos = targetHRP.Position - (targetLook * 1.5)
        myHRP.CFrame = CFrame.lookAt(behindPos, targetHRP.Position)
        myHRP.AssemblyLinearVelocity = Vector3.zero

        local im = nil
        pcall(function()
            im = require(game:GetService("ReplicatedStorage"):WaitForChild("Extensions"):WaitForChild("InputMap"))
        end)
        if im and im.tap then
            im.tap("Attack")
        else
            pcall(mouse1click)
        end

        pcall(function()
            local Remotes = game:GetService("ReplicatedStorage"):FindFirstChild("Remotes")
            local ReportHit = Remotes and Remotes:FindFirstChild("ReportHit")
            if ReportHit then
                ReportHit:FireServer({
                    kind = "melee",
                    targetUserId = targetPlr and targetPlr.UserId or 0,
                    targetModel = targetChar,
                    direction = myHRP.CFrame.LookVector,
                    at = workspace:GetServerTimeNow(),
                    backstab = true
                })
            end
        end)

        if autoWinReturn then
            task.delay(0.06, function()
                if myHRP and myHRP.Parent and originalCFrame then
                    myHRP.CFrame = originalCFrame
                    myHRP.AssemblyLinearVelocity = Vector3.zero
                end
                task.delay(0.1, function()
                    isAutoWinExecuting = false
                end)
            end)
        else
            task.delay(0.15, function()
                isAutoWinExecuting = false
            end)
        end

    else
        _G.MD_SilentAimTarget = target.part or target.hrp
        _G.MD_SilentAimEnabled = true
        _G.MD_WallbangEnabled = true

        fireWeapon()
        task.delay(0.25, function()
            isAutoWinExecuting = false
        end)
    end
end

-- ==================== 3. RENDERSTEPPED LOOP ====================
table.insert(Connections, RunService.RenderStepped:Connect(function()
    local myCam = workspace.CurrentCamera
    local screenCenter = Vector2.new(myCam.ViewportSize.X / 2, myCam.ViewportSize.Y / 2)
    if fovCircle then
        fovCircle.Position = screenCenter
        fovCircle.Radius = fovRadius
        fovCircle.Visible = silentAimEnabled and showFovCircle
    end

    local isAimActive = silentAimEnabled
    if isAimActive and silentAimMode == "HoldKey" then
        if Options.SilentAimKey and not Options.SilentAimKey:GetState() then
            isAimActive = false
        end
    end

    if isAimActive then
        local best = getBestSilentTarget()
        silentAimTargetPart = best and best.part or nil
        silentAimTargetChar = best and best.char or nil
    else
        silentAimTargetPart = nil
        silentAimTargetChar = nil
    end

    _G.MD_SilentAimEnabled = isAimActive and (silentAimTargetPart ~= nil)
    _G.MD_SilentAimTarget = silentAimTargetPart
    _G.MD_WallbangEnabled = wallbangEnabled
    _G.MD_KnifeSpeed = knifeSpeed

    local myChar = LocalPlayer.Character
    local activeTool = myChar and myChar:FindFirstChildOfClass("Tool")
    local tName = activeTool and activeTool.Name:lower() or ""
    local isKnife = (tName:find("knife") ~= nil)
    _G.MD_CurrentWeaponIsKnife = isKnife

    -- Viewmodel & Weapon Scale Execution
    if myChar then
        local torso = myChar:FindFirstChild("Torso")
        local rightArm = myChar:FindFirstChild("Right Arm") or myChar:FindFirstChild("RightHand")
        local leftArm = myChar:FindFirstChild("Left Arm") or myChar:FindFirstChild("LeftHand")
        local rs = torso and torso:FindFirstChild("Right Shoulder")
        local attach = rightArm and (rightArm:FindFirstChild("Knife_HandAttach") or rightArm:FindFirstChild("Revolver_HandAttach"))

        -- 1. Hide Arms
        if hideArmsEnabled then
            if rightArm then rightArm.LocalTransparencyModifier = 1 end
            if leftArm then leftArm.LocalTransparencyModifier = 1 end
        else
            if rightArm and rightArm.LocalTransparencyModifier == 1 then rightArm.LocalTransparencyModifier = 0 end
            if leftArm and leftArm.LocalTransparencyModifier == 1 then leftArm.LocalTransparencyModifier = 0 end
        end

        -- 2. Viewmodel Offset
        if viewmodelEnabled then
            local offsetCF = CFrame.new(vm.x, vm.y, vm.z) * CFrame.Angles(math.rad(vm.pitch), math.rad(vm.yaw), math.rad(vm.roll))
            if vmTargetMode == "ArmAndWeapon" then
                if rs and rs:IsA("Motor6D") then
                    local targetRSC1 = offsetCF:Inverse() * defaultRSC1
                    if rs.C1 ~= targetRSC1 then
                        rs.C1 = targetRSC1
                    end
                end
                if attach and attach:IsA("Motor6D") and attach.C1 ~= CFrame.identity then
                    attach.C1 = CFrame.identity
                end
            else
                if rs and rs:IsA("Motor6D") and rs.C1 ~= defaultRSC1 then
                    rs.C1 = defaultRSC1
                end
                if attach and attach:IsA("Motor6D") and attach.C1 ~= offsetCF then
                    attach.C1 = offsetCF
                end
            end
        else
            if rs and rs:IsA("Motor6D") and rs.C1 ~= defaultRSC1 then
                rs.C1 = defaultRSC1
            end
            if attach and attach:IsA("Motor6D") and attach.C1 ~= CFrame.identity then
                attach.C1 = CFrame.identity
            end
        end

        -- 3. Weapon Scale
        local targetScale = (weaponScaleEnabled and weaponScale) or 1.0
        local knifeRig = myChar:FindFirstChild("KnifeRig")
        if knifeRig and knifeRig:IsA("Model") then
            if math.abs(knifeRig:GetScale() - targetScale) > 0.01 then
                pcall(function() knifeRig:ScaleTo(targetScale) end)
            end
        end
        local revRig = myChar:FindFirstChild("RevolverRig")
        if revRig and revRig:IsA("Model") then
            if math.abs(revRig:GetScale() - targetScale) > 0.01 then
                pcall(function() revRig:ScaleTo(targetScale) end)
            end
        end
    end

    -- Silent Auto-Fire (Triggerbot: Fires automatically WITHOUT camera snapping)
    if silentAutoFire and isAimActive and silentAimTargetPart then
        local now = tick()
        local fireDelay = isKnife and math.max(silentAutoFireDelay, knifeHoldDuration + 0.12) or silentAutoFireDelay
        if (now - lastSilentFireTime >= fireDelay) then
            -- Muzzle clearance check: skip when wallbang is on (we spoof origin anyway)
            if wallbangEnabled or isKnife or not muzzleCheckEnabled or canMuzzleHitTarget(silentAimTargetPart, silentAimTargetChar) then
                local char = LocalPlayer.Character
                local tool = char and char:FindFirstChildOfClass("Tool")
                if not tool then
                    local bp = LocalPlayer:FindFirstChild("Backpack")
                    local rev = bp and (bp:FindFirstChild("Revolver") or bp:FindFirstChild("Knife"))
                    local hum = char and char:FindFirstChildOfClass("Humanoid")
                    if rev and hum then
                        hum:EquipTool(rev)
                    end
                end

                lastSilentFireTime = now
                fireWeapon()
            end
        end
    end

    -- Auto-Win / Kill Aura Execution
    local isAutoWinKeyActive = Options.AutoWinKey and Options.AutoWinKey:GetState()
    if (autoWinEnabled or isAutoWinKeyActive) and not isAutoWinExecuting then
        local now = tick()
        if (now - lastAutoWinTime >= autoWinDelay) then
            lastAutoWinTime = now
            task.spawn(executeAutoWin)
        end
    end

    -- Legit FOV Circle
    if legitFovCircle then
        legitFovCircle.Position = screenCenter
        legitFovCircle.Radius = legitFovRadius
        legitFovCircle.Visible = legitAimEnabled and legitShowFov and (not isMenuOpen)
    end

    -- Legit Aimbot Execution (Smooth Camera Aim)
    local isLegitActive = legitAimEnabled
    if isLegitActive and legitAimMode == "HoldKey" then
        if Options.LegitAimKey and not Options.LegitAimKey:GetState() then
            isLegitActive = false
        end
    end

    if isLegitActive then
        local legitTarget = getBestLegitTarget()
        if legitTarget and legitTarget.part then
            local targetPos = legitTarget.part.Position
            local currentCF = myCam.CFrame
            local targetCF = CFrame.lookAt(currentCF.Position, targetPos)
            local factor = math.clamp(1 / math.max(legitSmoothness, 1), 0.04, 0.45)
            myCam.CFrame = currentCF:Lerp(targetCF, factor)
        end
    end

    -- Legit Triggerbot Execution (Humanized Reaction Time on Direct Crosshair Aim)
    local isLegitTriggerActive = legitTriggerEnabled
    if isLegitTriggerActive and Options.LegitTriggerKey then
        if not Options.LegitTriggerKey:GetState() then
            isLegitTriggerActive = false
        end
    end

    if isLegitTriggerActive then
        local ray = myCam:ViewportPointToRay(screenCenter.X, screenCenter.Y)
        local rayParams = RaycastParams.new()
        rayParams.FilterType = Enum.RaycastFilterType.Exclude
        rayParams.FilterDescendantsInstances = { myCam, LocalPlayer.Character, workspace:FindFirstChild("Bin") }
        local hit = workspace:Raycast(ray.Origin, ray.Direction * 350, rayParams)
        local isEnemyAimed = false

        if hit and hit.Instance then
            local hitChar = hit.Instance.Parent
            if hitChar and hitChar:IsA("Accessory") then
                hitChar = hitChar.Parent
            end
            if hitChar and hitChar:FindFirstChildOfClass("Humanoid") then
                local plr = Players:GetPlayerFromCharacter(hitChar)
                if plr then
                    if not legitTriggerTeamCheck or isEnemy(plr) then
                        isEnemyAimed = true
                    end
                elseif targetNoobs then
                    isEnemyAimed = true
                end
            end
        end

        if isEnemyAimed then
            if legitTriggerStartTime == 0 then
                legitTriggerStartTime = tick()
            elseif (tick() - legitTriggerStartTime) >= (legitTriggerDelay or 0.16) then
                local now = tick()
                if (now - lastLegitTriggerFireTime >= 0.25) then
                    lastLegitTriggerFireTime = now
                    fireWeapon()
                end
            end
        else
            legitTriggerStartTime = 0
        end
    else
        legitTriggerStartTime = 0
    end

    -- Auto-Peek Execution (Peek Assist)
    if autoPeekEnabled and Options.AutoPeekKey then
        local isKeyHeld = Options.AutoPeekKey:GetState()
        local char = LocalPlayer.Character
        local hrp = char and char:FindFirstChild("HumanoidRootPart")

        if isKeyHeld and hrp then
            if not autoPeekAnchor then
                autoPeekAnchor = hrp.Position
                autoPeekState = "RECORDED"
                updateAutoPeekVisual()
            else
                local dist = (hrp.Position - autoPeekAnchor).Magnitude
                if autoPeekState == "RECORDED" and dist > 2 then
                    autoPeekState = "PEEKING"
                end

                if autoPeekState == "RETURNING" then
                    local cur = hrp.Position
                    local target = Vector3.new(autoPeekAnchor.X, cur.Y, autoPeekAnchor.Z)
                    local diff = target - cur
                    if diff.Magnitude > 1.2 then
                        local step = math.min(diff.Magnitude, autoPeekReturnSpeed)
                        hrp.CFrame = CFrame.new(cur + diff.Unit * step) * (hrp.CFrame - hrp.CFrame.Position)
                        hrp.AssemblyLinearVelocity = Vector3.zero
                    else
                        hrp.CFrame = CFrame.new(target) * (hrp.CFrame - hrp.CFrame.Position)
                        hrp.AssemblyLinearVelocity = Vector3.zero
                        autoPeekState = "RECORDED"
                    end
                end
            end
        else
            if autoPeekAnchor then
                autoPeekAnchor = nil
                autoPeekState = "IDLE"
                updateAutoPeekVisual()
            end
        end
    elseif autoPeekAnchor then
        autoPeekAnchor = nil
        autoPeekState = "IDLE"
        updateAutoPeekVisual()
    end

    -- 1. Silent Aim Target Line
    if targetLine then
        if targetLineEnabled and _G.MD_SilentAimEnabled and _G.MD_SilentAimTarget then
            local tPos, onScreen = myCam:WorldToViewportPoint(_G.MD_SilentAimTarget.Position)
            if onScreen then
                targetLine.From = screenCenter
                targetLine.To = Vector2.new(tPos.X, tPos.Y)
                targetLine.Color = targetLineColor
                targetLine.Visible = true
            else
                targetLine.Visible = false
            end
        else
            targetLine.Visible = false
        end
    end

    -- 2. Custom CS Crosshair
    if crosshairLines.h1 then
        if customCrosshairEnabled then
            local cx, cy = screenCenter.X, screenCenter.Y
            local g, s = crosshairGap, crosshairSize
            local col = crosshairColor
            local th = crosshairThickness

            crosshairLines.h1.From = Vector2.new(cx - g - s, cy)
            crosshairLines.h1.To = Vector2.new(cx - g, cy)
            crosshairLines.h1.Color = col
            crosshairLines.h1.Thickness = th
            crosshairLines.h1.Visible = true

            crosshairLines.h2.From = Vector2.new(cx + g, cy)
            crosshairLines.h2.To = Vector2.new(cx + g + s, cy)
            crosshairLines.h2.Color = col
            crosshairLines.h2.Thickness = th
            crosshairLines.h2.Visible = true

            crosshairLines.v1.From = Vector2.new(cx, cy - g - s)
            crosshairLines.v1.To = Vector2.new(cx, cy - g)
            crosshairLines.v1.Color = col
            crosshairLines.v1.Thickness = th
            crosshairLines.v1.Visible = true

            crosshairLines.v2.From = Vector2.new(cx, cy + g)
            crosshairLines.v2.To = Vector2.new(cx, cy + g + s)
            crosshairLines.v2.Color = col
            crosshairLines.v2.Thickness = th
            crosshairLines.v2.Visible = true

            crosshairLines.dot.Position = screenCenter
            crosshairLines.dot.Color = col
            crosshairLines.dot.Radius = th
            crosshairLines.dot.Visible = crosshairDotEnabled
        else
            for _, l in pairs(crosshairLines) do
                l.Visible = false
            end
        end
    end

    -- 3. 2D Visuals: Box ESP, Snaplines, Head Dots
    local activeDrawModels = {}
    if boxEspEnabled or snaplinesEnabled or headDotsEnabled then
        for _, t in ipairs(cachedTargets) do
            if isTargetAliveAndValid(t) then
                local char = t.char
                local head = char and (char:FindFirstChild("Head") or t.part)
                local root = char and (char:FindFirstChild("HumanoidRootPart") or char:FindFirstChild("Torso") or t.part)
                if head and root and head:IsDescendantOf(workspace) then
                    activeDrawModels[char] = true
                    if not drawingCache[char] then
                        local box = Drawing.new("Square")
                        box.Thickness = 1.5
                        box.Filled = false
                        box.Visible = false

                        local line = Drawing.new("Line")
                        line.Thickness = 1
                        line.Visible = false

                        local dot = Drawing.new("Circle")
                        dot.Radius = 3.5
                        dot.Filled = true
                        dot.Visible = false

                        drawingCache[char] = { box = box, line = line, dot = dot }
                    end

                    local d = drawingCache[char]
                    local headPos, onHead = myCam:WorldToViewportPoint(head.Position + Vector3.new(0, 0.6, 0))
                    local rootPos, onRoot = myCam:WorldToViewportPoint(root.Position - Vector3.new(0, 2.8, 0))

                    if onHead or onRoot then
                        local topY = headPos.Y
                        local botY = rootPos.Y
                        local h = math.abs(botY - topY)
                        local w = math.max(h * 0.65, 12)

                        -- 2D Box
                        if boxEspEnabled then
                            d.box.Size = Vector2.new(w, h)
                            d.box.Position = Vector2.new(rootPos.X - w / 2, math.min(topY, botY))
                            d.box.Color = boxColor
                            d.box.Visible = true
                        else
                            d.box.Visible = false
                        end

                        -- Snaplines / Tracers
                        if snaplinesEnabled then
                            local startPos = (snaplinesOrigin == "Bottom") and Vector2.new(myCam.ViewportSize.X / 2, myCam.ViewportSize.Y) or screenCenter
                            d.line.From = startPos
                            d.line.To = Vector2.new(rootPos.X, math.max(topY, botY))
                            d.line.Color = snaplinesColor
                            d.line.Visible = true
                        else
                            d.line.Visible = false
                        end

                        -- Head Dot
                        if headDotsEnabled and onHead then
                            d.dot.Position = Vector2.new(headPos.X, headPos.Y + 0.6 * (h / 30))
                            d.dot.Color = headDotsColor
                            d.dot.Visible = true
                        else
                            d.dot.Visible = false
                        end
                    else
                        d.box.Visible = false
                        d.line.Visible = false
                        d.dot.Visible = false
                    end
                end
            end
        end
    end

    -- Hide or cleanup Drawing objects (Reuses instances, zero allocation overhead)
    for m, d in pairs(drawingCache) do
        if not activeDrawModels[m] then
            d.box.Visible = false
            d.line.Visible = false
            d.dot.Visible = false
            if not m.Parent or not m:IsDescendantOf(workspace) then
                pcall(function() d.box:Remove() end)
                pcall(function() d.line:Remove() end)
                pcall(function() d.dot:Remove() end)
                drawingCache[m] = nil
            end
        end
    end
end))

-- ==================== 4. ANTI-AIM LOGIC ====================
local function getCharParts()
    local char = LocalPlayer.Character
    if not char then return nil end
    local root = char:FindFirstChild("HumanoidRootPart")
    local hum = char:FindFirstChildOfClass("Humanoid")
    local rj = root and root:FindFirstChild("RootJoint")
    return char, root, hum, rj
end

local function resetAntiAim()
    local _, root, hum, rj = getCharParts()
    if hum then hum.AutoRotate = true end
    if rj then rj.C0 = defaultRjC0 end
end

table.insert(Connections, RunService.Heartbeat:Connect(function(dt)
    if not aaEnabled then return end
    local _, root, hum, rj = getCharParts()
    if not root or not hum or hum.Health <= 0 then return end

    hum.AutoRotate = false
    local camLook = workspace.CurrentCamera.CFrame.LookVector
    local baseAngle = math.atan2(-camLook.X, -camLook.Z)

    if aaYawMode == "Spinbot" then
        currentYaw = (currentYaw + spinSpeed * dt) % (math.pi * 2)
    elseif aaYawMode == "Jitter (180 Flip)" then
        local flip = (tick() % 0.1 > 0.05)
        currentYaw = baseAngle + (flip and 0 or math.pi)
    elseif aaYawMode == "Jitter (Custom Angle)" then
        local flip = (tick() % 0.12 > 0.06)
        currentYaw = baseAngle + math.rad(flip and jitterAngle or -jitterAngle)
    elseif aaYawMode == "Random Jitter" then
        currentYaw = math.rad(math.random(-180, 180))
    elseif aaYawMode == "Backward (180)" then
        currentYaw = baseAngle + math.pi
    elseif aaYawMode == "Sideways (90)" then
        currentYaw = baseAngle + math.rad(90)
    elseif aaYawMode == "Sway (Sinusoid)" then
        currentYaw = baseAngle + math.sin(tick() * swayFreq) * math.rad(swayAngle)
    end

    local preservedVelocity = root.AssemblyLinearVelocity
    root.CFrame = CFrame.new(root.Position) * CFrame.Angles(0, currentYaw, 0)
    root.AssemblyLinearVelocity = preservedVelocity

    if rj then
        if aaPitchMode == "Down (Head Roll)" then
            rj.C0 = defaultRjC0 * CFrame.Angles(math.rad(pitchAngle), 0, 0)
        elseif aaPitchMode == "Up (Sky)" then
            rj.C0 = defaultRjC0 * CFrame.Angles(math.rad(-pitchAngle), 0, 0)
        elseif aaPitchMode == "Jitter Pitch" then
            local flipP = (tick() % 0.1 > 0.05)
            rj.C0 = defaultRjC0 * CFrame.Angles(math.rad(flipP and pitchAngle or -pitchAngle), 0, 0)
        elseif aaPitchMode == "Zero" then
            rj.C0 = defaultRjC0
        end
    end
end))

-- ==================== 5. MOVEMENT: BHOP & STRAFES ====================
table.insert(Connections, RunService.Heartbeat:Connect(function()
    local char = LocalPlayer.Character
    local hum = char and char:FindFirstChildOfClass("Humanoid")
    local root = char and char:FindFirstChild("HumanoidRootPart")
    if not hum or not root or hum.Health <= 0 then return end

    local isSpaceDown = UserInputService:IsKeyDown(Enum.KeyCode.Space)
    local onGround = (hum.FloorMaterial ~= Enum.Material.Air)
    local moveDir = hum.MoveDirection

    -- 1. Auto-Bhop без задержки приземления
    if bhopEnabled and isSpaceDown and onGround then
        hum:ChangeState(Enum.HumanoidStateType.Jumping)
    end

    -- 2. Air Strafes: Мгновенная смена направления без КД и задержки (W/A/S/D)
    if bhopEnabled and instantStrafes and moveDir.Magnitude > 0 then
        local currentVel = root.AssemblyLinearVelocity
        local speed = math.max(hum.WalkSpeed, bhopSpeed)
        root.AssemblyLinearVelocity = Vector3.new(moveDir.X * speed, currentVel.Y, moveDir.Z * speed)
    end
end))

table.insert(Connections, UserInputService.JumpRequest:Connect(function()
    if infiniteJump then
        local hum = LocalPlayer.Character and LocalPlayer.Character:FindFirstChildOfClass("Humanoid")
        if hum and hum.Health > 0 then
            hum:ChangeState(Enum.HumanoidStateType.Jumping)
        end
    end
end))

-- ==================== 6. PERFECT NATIVE 3RD PERSON ====================
local function applyNativeCamera()
    if NativeTP then
        NativeTP.Distance = cameraDistance
        NativeTP.Shoulder = shoulderOffset
        NativeTP.Height = heightOffset
        NativeTP.SetEnabled(thirdPersonEnabled)
    end
    if PlayerState then
        PlayerState.CameraFirstPerson = not thirdPersonEnabled
    end
    workspace.CurrentCamera.FieldOfView = customFOV

    local char = LocalPlayer.Character
    if char and thirdPersonEnabled then
        for _, p in ipairs(char:GetDescendants()) do
            if p:IsA("BasePart") and p.Name ~= "HumanoidRootPart" and p.Name ~= "BoundingBox" then
                p.LocalTransparencyModifier = 0
            end
        end
    end
end

table.insert(Connections, RunService.RenderStepped:Connect(function()
    if thirdPersonEnabled then
        if NativeTP and not NativeTP.IsEnabled() then
            NativeTP.SetEnabled(true)
        end
        if PlayerState and PlayerState.CameraFirstPerson ~= false then
            PlayerState.CameraFirstPerson = false
        end
        local char = LocalPlayer.Character
        if char then
            for _, p in ipairs(char:GetChildren()) do
                if p:IsA("BasePart") and p.Name ~= "HumanoidRootPart" and p.LocalTransparencyModifier > 0.1 then
                    p.LocalTransparencyModifier = 0
                end
            end
        end
    end
end))

-- ==================== 7. VISUALS: ADVANCED ESP ====================
local function removeEspForModel(model)
    local data = espCache[model]
    if data then
        if data.highlight then pcall(function() data.highlight:Destroy() end) end
        if data.billboard then pcall(function() data.billboard:Destroy() end) end
        espCache[model] = nil
    end
end

local function clearAllEsp()
    for model, _ in pairs(espCache) do
        removeEspForModel(model)
    end
    for _, d in pairs(drawingCache) do
        pcall(function() d.box:Remove() end)
        pcall(function() d.line:Remove() end)
        pcall(function() d.dot:Remove() end)
    end
    drawingCache = {}
end

local function getWeaponName(char)
    local tool = char:FindFirstChildOfClass("Tool")
    if tool then
        return tool.Name
    end
    return nil
end

local function createEspForModel(model, isBot, displayName)
    if espCache[model] then return end
    local head = model:FindFirstChild("Head") or model:FindFirstChild("HumanoidRootPart")
    if not head then return end

    -- 1. Highlight (Chams)
    local hl = Instance.new("Highlight")
    hl.Name = "ESP_Highlight"
    hl.Adornee = model
    hl.FillColor = espFillColor
    hl.FillTransparency = espFillTransparency
    hl.OutlineColor = espOutlineColor
    hl.OutlineTransparency = espOutlineTransparency
    hl.DepthMode = Enum.HighlightDepthMode.AlwaysOnTop
    hl.Enabled = espEnabled
    pcall(function() hl.Parent = model end)
    if not hl.Parent then
        hl.Parent = game:GetService("CoreGui")
    end

    -- 2. BillboardGui (Name, Distance, Health, Weapon)
    local bb = Instance.new("BillboardGui")
    bb.Name = "ESP_Billboard"
    bb.Adornee = head
    bb.AlwaysOnTop = true
    bb.Size = UDim2.new(0, 160, 0, 52)
    bb.StudsOffset = Vector3.new(0, 3.2, 0)
    bb.Enabled = espEnabled
    bb.Parent = game:GetService("CoreGui")

    local container = Instance.new("Frame", bb)
    container.Size = UDim2.new(1, 0, 1, 0)
    container.BackgroundTransparency = 1

    local nameLabel = Instance.new("TextLabel", container)
    nameLabel.Name = "NameLabel"
    nameLabel.Size = UDim2.new(1, 0, 0, 16)
    nameLabel.Position = UDim2.new(0, 0, 0, 0)
    nameLabel.BackgroundTransparency = 1
    nameLabel.TextColor3 = Color3.fromRGB(255, 255, 255)
    nameLabel.TextStrokeColor3 = Color3.fromRGB(0, 0, 0)
    nameLabel.TextStrokeTransparency = 0.2
    nameLabel.TextSize = 13
    nameLabel.Font = Enum.Font.GothamBold
    nameLabel.Text = displayName or model.Name

    local healthBg = Instance.new("Frame", container)
    healthBg.Name = "HealthBg"
    healthBg.Size = UDim2.new(0, 90, 0, 4)
    healthBg.Position = UDim2.new(0.5, -45, 0, 18)
    healthBg.BackgroundColor3 = Color3.fromRGB(30, 30, 30)
    healthBg.BorderSizePixel = 0
    healthBg.Visible = espShowHealth

    local healthFill = Instance.new("Frame", healthBg)
    healthFill.Name = "HealthFill"
    healthFill.Size = UDim2.new(1, 0, 1, 0)
    healthFill.BackgroundColor3 = Color3.fromRGB(46, 204, 113)
    healthFill.BorderSizePixel = 0

    local weaponLabel = Instance.new("TextLabel", container)
    weaponLabel.Name = "WeaponLabel"
    weaponLabel.Size = UDim2.new(1, 0, 0, 14)
    weaponLabel.Position = UDim2.new(0, 0, 0, 24)
    weaponLabel.BackgroundTransparency = 1
    weaponLabel.TextColor3 = Color3.fromRGB(241, 196, 15)
    weaponLabel.TextStrokeColor3 = Color3.fromRGB(0, 0, 0)
    weaponLabel.TextStrokeTransparency = 0.3
    weaponLabel.TextSize = 11
    weaponLabel.Font = Enum.Font.GothamMedium
    weaponLabel.Text = ""
    weaponLabel.Visible = espShowWeapon

    espCache[model] = {
        highlight = hl,
        billboard = bb,
        nameLabel = nameLabel,
        healthBg = healthBg,
        healthFill = healthFill,
        weaponLabel = weaponLabel,
        isBot = isBot,
        displayName = displayName or model.Name
    }
end

local function updateEsp()
    if not espEnabled then
        for _, data in pairs(espCache) do
            if data.highlight then data.highlight.Enabled = false end
            if data.billboard then data.billboard.Enabled = false end
        end
        return
    end

    local camPos = workspace.CurrentCamera.CFrame.Position
    local activeModels = {}

    -- 1. Scan Players
    for _, plr in ipairs(Players:GetPlayers()) do
        if plr ~= LocalPlayer and plr.Character then
            local char = plr.Character
            local hum = char:FindFirstChildOfClass("Humanoid")
            local head = char:FindFirstChild("Head") or char:FindFirstChild("HumanoidRootPart")
            if hum and hum.Health > 0 and head and head:IsDescendantOf(workspace) and hum:GetState() ~= Enum.HumanoidStateType.Dead then
                activeModels[char] = true
                if not espCache[char] then
                    createEspForModel(char, false, plr.DisplayName or plr.Name)
                end
                local data = espCache[char]
                if data then
                    data.highlight.Enabled = true
                    data.billboard.Enabled = true
                    data.highlight.FillColor = espFillColor
                    data.highlight.FillTransparency = espFillTransparency
                    data.highlight.OutlineColor = espOutlineColor
                    data.highlight.OutlineTransparency = espOutlineTransparency

                    local dist = math.floor((head.Position - camPos).Magnitude)
                    if espShowDistance then
                        data.nameLabel.Text = string.format("%s [%dm]", data.displayName, dist)
                    else
                        data.nameLabel.Text = data.displayName
                    end
                    data.nameLabel.Visible = espShowNames

                    local hpPercent = math.clamp(hum.Health / math.max(hum.MaxHealth, 1), 0, 1)
                    data.healthFill.Size = UDim2.new(hpPercent, 0, 1, 0)
                    if hpPercent > 0.5 then
                        data.healthFill.BackgroundColor3 = Color3.fromRGB(46, 204, 113)
                    elseif hpPercent > 0.25 then
                        data.healthFill.BackgroundColor3 = Color3.fromRGB(241, 196, 15)
                    else
                        data.healthFill.BackgroundColor3 = Color3.fromRGB(231, 76, 60)
                    end
                    data.healthBg.Visible = espShowHealth

                    local weapon = getWeaponName(char)
                    if weapon then
                        data.weaponLabel.Text = "[" .. weapon .. "]"
                        if weapon:find("Revolver") or weapon:find("Gun") then
                            data.weaponLabel.TextColor3 = Color3.fromRGB(230, 126, 34)
                        else
                            data.weaponLabel.TextColor3 = Color3.fromRGB(52, 152, 219)
                        end
                        data.weaponLabel.Visible = espShowWeapon
                    else
                        data.weaponLabel.Visible = false
                    end
                end
            end
        end
    end

    -- 2. Scan Bots / Dummies in workspace.Characters
    if espTargetBots and workspace:FindFirstChild("Characters") then
        for _, m in ipairs(workspace.Characters:GetChildren()) do
            if m:IsA("Model") and m ~= LocalPlayer.Character then
                local hum = m:FindFirstChildOfClass("Humanoid")
                local head = m:FindFirstChild("Head") or m:FindFirstChild("HumanoidRootPart")
                if hum and hum.Health > 0 and head and head:IsDescendantOf(workspace) and hum:GetState() ~= Enum.HumanoidStateType.Dead then
                    activeModels[m] = true
                    if not espCache[m] then
                        createEspForModel(m, true, m.Name)
                    end
                    local data = espCache[m]
                    if data then
                        data.highlight.Enabled = true
                        data.billboard.Enabled = true
                        data.highlight.FillColor = espFillColor
                        data.highlight.FillTransparency = espFillTransparency
                        data.highlight.OutlineColor = espOutlineColor
                        data.highlight.OutlineTransparency = espOutlineTransparency

                        local dist = math.floor((head.Position - camPos).Magnitude)
                        if espShowDistance then
                            data.nameLabel.Text = string.format("%s [%dm]", m.Name, dist)
                        else
                            data.nameLabel.Text = m.Name
                        end
                        data.nameLabel.Visible = espShowNames

                        local hpPercent = math.clamp(hum.Health / math.max(hum.MaxHealth, 1), 0, 1)
                        data.healthFill.Size = UDim2.new(hpPercent, 0, 1, 0)
                        data.healthBg.Visible = espShowHealth

                        local weapon = getWeaponName(m)
                        if weapon then
                            data.weaponLabel.Text = "[" .. weapon .. "]"
                            data.weaponLabel.Visible = espShowWeapon
                        else
                            data.weaponLabel.Visible = false
                        end
                    end
                end
            end
        end
    end

    -- 3. Cleanup dead or despawned models
    for m, _ in pairs(espCache) do
        if not activeModels[m] then
            removeEspForModel(m)
        end
    end
end

task.spawn(function()
    while isAlive do
        task.wait(0.12)
        pcall(updateEsp)
    end
end)

-- ==================== 8. UI BUILDER WITH LOCALIZATION ====================
local buildMenu

buildMenu = function()
    local Window = Library:CreateWindow({
        Title = T("Title"),
        Center = true,
        AutoShow = true,
        TabPadding = 8,
        MenuFadeTime = 0.2
    })

    local Tabs = {
        Rage = Window:AddTab(T("Rage")),
        Legit = Window:AddTab(T("Legit")),
        Visuals = Window:AddTab(T("Visuals")),
        Skins = Window:AddTab(T("Skins")),
        Movement = Window:AddTab(T("Movement")),
        ["UI Settings"] = Window:AddTab(T("Settings")),
    }

    -- 1. RAGE TAB
    local LeftRage = Tabs.Rage:AddLeftGroupbox(T("SilentAimbot"))
    local AutoWinBox = Tabs.Rage:AddLeftGroupbox(T("AutoWinGroup"))
    local AutoPeekBox = Tabs.Rage:AddLeftGroupbox(T("AutoPeek"))
    local RightAA = Tabs.Rage:AddRightGroupbox(T("AnglesDesync"))
    local TargetBox = Tabs.Rage:AddRightGroupbox(T("TargetFilters"))

    -- Left Column: Silent Aim + Silent Auto-Shot (Triggerbot)
    LeftRage:AddToggle("SilentAim", {
        Text = T("EnableSilentAim"),
        Default = silentAimEnabled,
        Tooltip = T("SilentAimDesc"),
        Callback = function(Value)
            silentAimEnabled = Value
        end
    }):AddKeyPicker("SilentAimKey", {
        Default = "MB2",
        SyncToggleState = true,
        Mode = "Toggle",
        Text = "Silent Aim Keybind",
        NoUI = false,
    })

    LeftRage:AddDropdown("SilentActivation", {
        Values = { "Always On", "Hold Keybind" },
        Default = silentAimMode == "HoldKey" and 2 or 1,
        Multi = false,
        Text = T("ActivationMode"),
        Callback = function(Value)
            silentAimMode = (Value == "Hold Keybind" or Value:find("Hold")) and "HoldKey" or "AlwaysOn"
        end
    })

    LeftRage:AddDivider()

    -- Silent Auto-Fire (Triggerbot)
    LeftRage:AddToggle("SilentAutoFire", {
        Text = T("SilentAutoFire"),
        Default = silentAutoFire,
        Tooltip = T("SilentAutoFireDesc"),
        Callback = function(Value)
            silentAutoFire = Value
        end
    })

    LeftRage:AddSlider("AutoFireDelay", {
        Text = T("AutoFireDelay"),
        Default = math.floor(silentAutoFireDelay * 100),
        Min = 10,
        Max = 100,
        Rounding = 0,
        Compact = false,
        Callback = function(Value)
            silentAutoFireDelay = Value / 100
        end
    })

    LeftRage:AddSlider("KnifeHoldDuration", {
        Text = T("KnifeHoldDuration"),
        Default = math.floor(knifeHoldDuration * 100),
        Min = 10,
        Max = 60,
        Rounding = 0,
        Compact = false,
        Tooltip = T("KnifeHoldDurationDesc"),
        Callback = function(Value)
            knifeHoldDuration = Value / 100
        end
    })

    LeftRage:AddToggle("MuzzleCheck", {
        Text = T("MuzzleCheck"),
        Default = muzzleCheckEnabled,
        Tooltip = T("MuzzleCheckDesc"),
        Callback = function(Value)
            muzzleCheckEnabled = Value
        end
    })

    LeftRage:AddDivider()

    LeftRage:AddToggle("WallCheck", {
        Text = T("WallCheck"),
        Default = wallCheckEnabled,
        Tooltip = T("WallCheckDesc"),
        Callback = function(Value)
            wallCheckEnabled = Value
        end
    })

    LeftRage:AddToggle("TeamCheck", {
        Text = T("TeamCheck"),
        Default = teamCheckEnabled,
        Tooltip = T("TeamCheckDesc"),
        Callback = function(Value)
            teamCheckEnabled = Value
        end
    })

    LeftRage:AddToggle("Wallbang", {
        Text = "Wallbang",
        Default = wallbangEnabled,
        Tooltip = "Shoot through walls / bypass line of sight raycasts",
        Callback = function(Value)
            wallbangEnabled = Value
        end
    })

    LeftRage:AddToggle("MaxKnifePower", {
        Text = T("MaxKnifePower"),
        Default = alwaysMaxKnifePower,
        Tooltip = T("MaxKnifePowerDesc"),
        Callback = function(Value)
            alwaysMaxKnifePower = Value
            _G.MD_AlwaysMaxKnifePower = Value
        end
    })

    LeftRage:AddToggle("InstantKnifeCharge", {
        Text = T("InstantKnifeCharge"),
        Default = instantKnifeCharge,
        Tooltip = T("InstantKnifeChargeDesc"),
        Callback = function(Value)
            instantKnifeCharge = Value
            pcall(function()
                local rs = game:GetService("ReplicatedStorage")
                local kt = require(rs.Shared.KnifeTiming)
                kt.CHARGE_DUR = Value and 0.01 or 0.5
                kt.HOLD_TO_THROW_SEC = 0.2
            end)
        end
    })

    LeftRage:AddSlider("KnifeSpeed", {
        Text = currentLang == "RU" and "Скорость ножа (как у ревика)" or "Knife Speed (Revolver Speed)",
        Default = 65,
        Min = 10,
        Max = 100,
        Rounding = 0,
        Compact = false,
        Callback = function(Value)
            knifeSpeed = Value / 10
            _G.MD_KnifeSpeed = knifeSpeed
        end
    })

    -- Auto-Win / Kill Aura Groupbox
    AutoWinBox:AddToggle("EnableAutoWin", {
        Text = T("EnableAutoWin"),
        Default = autoWinEnabled,
        Tooltip = T("AutoWinDesc"),
        Callback = function(Value)
            autoWinEnabled = Value
        end
    }):AddKeyPicker("AutoWinKey", {
        Default = "None",
        SyncToggleState = false,
        Mode = "Hold",
        Text = T("AutoWinKey"),
        NoUI = false,
    })

    AutoWinBox:AddDropdown("AutoWinMode", {
        Values = { "TP Backstab", "360° Auto-Throw" },
        Default = 1,
        Multi = false,
        Text = T("AutoWinMode"),
        Callback = function(Value)
            autoWinMode = Value
        end
    })

    AutoWinBox:AddSlider("AutoWinDelay", {
        Text = T("AutoWinDelay"),
        Default = math.floor(autoWinDelay * 100),
        Min = 5,
        Max = 100,
        Rounding = 0,
        Compact = false,
        Callback = function(Value)
            autoWinDelay = Value / 100
        end
    })

    AutoWinBox:AddToggle("AutoWinReturn", {
        Text = T("AutoWinReturn"),
        Default = autoWinReturn,
        Tooltip = T("AutoWinReturnDesc"),
        Callback = function(Value)
            autoWinReturn = Value
        end
    })

    AutoWinBox:AddToggle("AutoWinEquip", {
        Text = T("AutoWinEquip"),
        Default = autoWinEquip,
        Tooltip = T("AutoWinEquipDesc"),
        Callback = function(Value)
            autoWinEquip = Value
        end
    })

    -- Auto-Peek Groupbox (Peek Assist)
    AutoPeekBox:AddToggle("AutoPeek", {
        Text = T("EnableAutoPeek"),
        Default = autoPeekEnabled,
        Tooltip = T("AutoPeekDesc"),
        Callback = function(Value)
            autoPeekEnabled = Value
            if not Value and autoPeekAnchor then
                autoPeekAnchor = nil
                autoPeekState = "IDLE"
                updateAutoPeekVisual()
            end
        end
    }):AddKeyPicker("AutoPeekKey", {
        Default = "C",
        SyncToggleState = false,
        Mode = "Hold",
        Text = "Auto-Peek Key",
        NoUI = false,
    })

    AutoPeekBox:AddToggle("AutoPeekMarker", {
        Text = T("AutoPeekMarker"),
        Default = autoPeekShowMarker,
        Tooltip = T("AutoPeekMarkerDesc"),
        Callback = function(Value)
            autoPeekShowMarker = Value
            updateAutoPeekVisual()
        end
    }):AddColorPicker("AutoPeekColor", {
        Default = autoPeekColor,
        Title = "Marker Color",
        Callback = function(Value)
            autoPeekColor = Value
            if autoPeekVisual then autoPeekVisual.Color = Value end
        end
    })

    AutoPeekBox:AddSlider("AutoPeekSpeed", {
        Text = T("AutoPeekSpeed"),
        Default = math.floor(autoPeekReturnSpeed),
        Min = 2,
        Max = 8,
        Rounding = 0,
        Compact = false,
        Callback = function(Value)
            autoPeekReturnSpeed = Value
        end
    })

    -- Right Column: Anti-Aim
    RightAA:AddToggle("EnableAA", {
        Text = T("EnableAA"),
        Default = aaEnabled,
        Tooltip = T("AADesc"),
        Callback = function(Value)
            aaEnabled = Value
            if not Value then resetAntiAim() end
        end
    }):AddKeyPicker("AAKey", {
        Default = "X",
        SyncToggleState = true,
        Mode = "Toggle",
        Text = "Toggle Anti-Aim",
        NoUI = false,
    })

    RightAA:AddDropdown("YawMode", {
        Values = { "Spinbot", "Jitter (180 Flip)", "Jitter (Custom Angle)", "Random Jitter", "Backward (180)", "Sideways (90)", "Sway (Sinusoid)" },
        Default = 1,
        Multi = false,
        Text = T("YawMode"),
        Callback = function(Value)
            aaYawMode = Value
        end
    })

    RightAA:AddDropdown("PitchMode", {
        Values = { "Down (Head Roll)", "Up (Sky)", "Jitter Pitch", "Zero" },
        Default = 1,
        Multi = false,
        Text = T("PitchMode"),
        Callback = function(Value)
            aaPitchMode = Value
            if Value == "Zero" then
                local _, _, _, rj = getCharParts()
                if rj then rj.C0 = defaultRjC0 end
            end
        end
    })

    RightAA:AddSlider("SpinSpeed", {
        Text = T("SpinSpeed"),
        Default = spinSpeed,
        Min = 5,
        Max = 75,
        Rounding = 0,
        Compact = false,
        Callback = function(Value)
            spinSpeed = Value
        end
    })

    RightAA:AddSlider("PitchAngle", {
        Text = T("PitchAngle"),
        Default = pitchAngle,
        Min = -85,
        Max = 85,
        Rounding = 0,
        Compact = false,
        Callback = function(Value)
            pitchAngle = Value
        end
    })

    RightAA:AddSlider("JitterAngle", {
        Text = T("JitterAngle"),
        Default = jitterAngle,
        Min = 30,
        Max = 180,
        Rounding = 0,
        Compact = false,
        Callback = function(Value)
            jitterAngle = Value
        end
    })

    RightAA:AddSlider("SwayFreq", {
        Text = T("SwayFreq"),
        Default = swayFreq,
        Min = 2,
        Max = 20,
        Rounding = 0,
        Compact = false,
        Callback = function(Value)
            swayFreq = Value
        end
    })

    -- Right Column: Target Filters & FOV
    TargetBox:AddToggle("TargetPlayers", {
        Text = T("TargetPlayers"),
        Default = targetPlayers,
        Callback = function(Value)
            targetPlayers = Value
            refreshTargetCache()
        end
    })

    TargetBox:AddToggle("TargetNoobs", {
        Text = T("TargetNoobs"),
        Default = targetNoobs,
        Callback = function(Value)
            targetNoobs = Value
            refreshTargetCache()
        end
    })

    TargetBox:AddToggle("TargetBullseyes", {
        Text = T("TargetBullseyes"),
        Default = targetTargets,
        Callback = function(Value)
            targetTargets = Value
            refreshTargetCache()
        end
    })

    TargetBox:AddDropdown("TargetPart", {
        Values = { "Head", "Torso", "HumanoidRootPart" },
        Default = targetPartMode == "Head" and 1 or (targetPartMode == "Torso" and 2 or 3),
        Multi = false,
        Text = T("HitboxPriority"),
        Callback = function(Value)
            targetPartMode = Value
        end
    })

    TargetBox:AddDivider()

    TargetBox:AddToggle("ShowFOV", {
        Text = T("DrawFOV"),
        Default = showFovCircle,
        Callback = function(Value)
            showFovCircle = Value
            if fovCircle and not Value then
                fovCircle.Visible = false
            end
        end
    }):AddColorPicker("FOVColor", {
        Default = Color3.fromRGB(255, 75, 75),
        Title = "FOV Color",
        Callback = function(Value)
            if fovCircle then fovCircle.Color = Value end
        end
    })

    TargetBox:AddSlider("FOVRadius", {
        Text = T("FOVRadius"),
        Default = fovRadius,
        Min = 30,
        Max = 450,
        Rounding = 0,
        Compact = false,
        Callback = function(Value)
            fovRadius = Value
        end
    })

    -- 2. LEGIT TAB
    local LeftLegit = Tabs.Legit:AddLeftGroupbox(T("LegitAimbot"))
    local RightLegit = Tabs.Legit:AddRightGroupbox(T("LegitTriggerbot"))

    LeftLegit:AddToggle("LegitAim", {
        Text = T("EnableLegitAim"),
        Default = legitAimEnabled,
        Tooltip = T("LegitAimDesc"),
        Callback = function(Value)
            legitAimEnabled = Value
        end
    }):AddKeyPicker("LegitAimKey", {
        Default = "MB2",
        SyncToggleState = true,
        Mode = "Hold",
        Text = "Legit Aim Key",
        NoUI = false,
    })

    LeftLegit:AddDropdown("LegitAimMode", {
        Values = { "Hold Keybind", "Always On" },
        Default = legitAimMode == "AlwaysOn" and 2 or 1,
        Multi = false,
        Text = T("ActivationMode"),
        Callback = function(Value)
            legitAimMode = (Value:find("Always") or Value == "Always On") and "AlwaysOn" or "HoldKey"
        end
    })

    LeftLegit:AddSlider("LegitSmoothness", {
        Text = T("LegitSmoothness"),
        Default = legitSmoothness,
        Min = 1,
        Max = 25,
        Rounding = 0,
        Compact = false,
        Callback = function(Value)
            legitSmoothness = Value
        end
    })

    LeftLegit:AddSlider("LegitFOV", {
        Text = T("LegitFOV"),
        Default = legitFovRadius,
        Min = 20,
        Max = 250,
        Rounding = 0,
        Compact = false,
        Callback = function(Value)
            legitFovRadius = Value
            if legitFovCircle then legitFovCircle.Radius = Value end
        end
    })

    LeftLegit:AddToggle("DrawLegitFOV", {
        Text = T("DrawLegitFOV"),
        Default = legitShowFov,
        Callback = function(Value)
            legitShowFov = Value
        end
    }):AddColorPicker("LegitFOVColor", {
        Default = Color3.fromRGB(60, 180, 255),
        Title = "Legit FOV Color",
        Callback = function(Value)
            if legitFovCircle then legitFovCircle.Color = Value end
        end
    })

    LeftLegit:AddDropdown("LegitHitbox", {
        Values = { "Head", "Torso", "HumanoidRootPart" },
        Default = legitHitbox == "Head" and 1 or (legitHitbox == "Torso" and 2 or 3),
        Multi = false,
        Text = T("LegitHitbox"),
        Callback = function(Value)
            legitHitbox = Value
        end
    })

    LeftLegit:AddToggle("LegitWallCheck", {
        Text = T("LegitWallCheck"),
        Default = legitWallCheck,
        Callback = function(Value)
            legitWallCheck = Value
        end
    })

    -- Right Legit: Legit Triggerbot
    RightLegit:AddToggle("LegitTrigger", {
        Text = T("EnableLegitTrigger"),
        Default = legitTriggerEnabled,
        Tooltip = T("LegitTriggerDesc"),
        Callback = function(Value)
            legitTriggerEnabled = Value
        end
    }):AddKeyPicker("LegitTriggerKey", {
        Default = "None",
        SyncToggleState = true,
        Mode = "Toggle",
        Text = "Trigger Key",
        NoUI = false,
    })

    RightLegit:AddSlider("ReactionDelay", {
        Text = T("ReactionDelay"),
        Default = math.floor(legitTriggerDelay * 1000),
        Min = 50,
        Max = 400,
        Rounding = 0,
        Compact = false,
        Callback = function(Value)
            legitTriggerDelay = Value / 1000
        end
    })

    RightLegit:AddToggle("LegitTriggerTeamCheck", {
        Text = T("TeamCheck"),
        Default = legitTriggerTeamCheck,
        Callback = function(Value)
            legitTriggerTeamCheck = Value
        end
    })

    -- 3. MOVEMENT TAB
    local LeftMove = Tabs.Movement:AddLeftGroupbox(T("BhopStrafes"))
    local RightMove = Tabs.Movement:AddRightGroupbox(T("MovementBoost"))

    LeftMove:AddToggle("Bhop", {
        Text = T("Bhop"),
        Default = bhopEnabled,
        Tooltip = T("BhopDesc"),
        Callback = function(Value)
            bhopEnabled = Value
        end
    })

    LeftMove:AddToggle("AirStrafes", {
        Text = T("AirStrafes"),
        Default = instantStrafes,
        Tooltip = T("AirStrafesDesc"),
        Callback = function(Value)
            instantStrafes = Value
        end
    })

    LeftMove:AddSlider("BhopSpeed", {
        Text = T("BhopSpeed"),
        Default = bhopSpeed,
        Min = 23,
        Max = 150,
        Rounding = 0,
        Compact = false,
        Callback = function(Value)
            bhopSpeed = Value
        end
    })

    RightMove:AddToggle("InfJump", {
        Text = T("InfJump"),
        Default = infiniteJump,
        Tooltip = T("InfJumpDesc"),
        Callback = function(Value)
            infiniteJump = Value
        end
    })

    RightMove:AddSlider("WalkSpeed", {
        Text = T("WalkSpeed"),
        Default = 23,
        Min = 23,
        Max = 150,
        Rounding = 0,
        Compact = false,
        Callback = function(Value)
            local hum = LocalPlayer.Character and LocalPlayer.Character:FindFirstChildOfClass("Humanoid")
            if hum then hum.WalkSpeed = Value end
        end
    })

    -- 4. VISUALS TAB
    local LeftVis = Tabs.Visuals:AddLeftGroupbox(T("ThirdPersonCam"))
    local AmbienceBox = Tabs.Visuals:AddLeftGroupbox(T("AmbienceWorld"))
    local CrosshairBox = Tabs.Visuals:AddLeftGroupbox(T("CrosshairVisuals"))

    local RightVis = Tabs.Visuals:AddRightGroupbox(T("ESPWorld"))
    local DrawingBox = Tabs.Visuals:AddRightGroupbox(T("DrawingVisuals"))
    local TracerBox = Tabs.Visuals:AddRightGroupbox(T("BulletTracers"))

    -- Left Visuals: Third Person
    LeftVis:AddToggle("ThirdPerson", {
        Text = T("EnableTP"),
        Default = thirdPersonEnabled,
        Tooltip = T("TPDesc"),
        Callback = function(Value)
            thirdPersonEnabled = Value
            applyNativeCamera()
        end
    }):AddKeyPicker("TPKey", {
        Default = "V",
        SyncToggleState = true,
        Mode = "Toggle",
        Text = "Toggle 3rd Person",
        NoUI = false,
    })

    LeftVis:AddSlider("CamDist", {
        Text = T("CamDist"),
        Default = cameraDistance,
        Min = 5,
        Max = 30,
        Rounding = 0,
        Compact = false,
        Callback = function(Value)
            cameraDistance = Value
            applyNativeCamera()
        end
    })

    LeftVis:AddSlider("ShoulderX", {
        Text = T("ShoulderX"),
        Default = shoulderOffset,
        Min = -3,
        Max = 3,
        Rounding = 1,
        Compact = false,
        Callback = function(Value)
            shoulderOffset = Value
            applyNativeCamera()
        end
    })

    LeftVis:AddSlider("HeightY", {
        Text = T("HeightY"),
        Default = heightOffset,
        Min = -1,
        Max = 4,
        Rounding = 1,
        Compact = false,
        Callback = function(Value)
            heightOffset = Value
            applyNativeCamera()
        end
    })

    LeftVis:AddSlider("FOV", {
        Text = T("FOV"),
        Default = customFOV,
        Min = 70,
        Max = 120,
        Rounding = 0,
        Compact = false,
        Callback = function(Value)
            customFOV = Value
            workspace.CurrentCamera.FieldOfView = Value
        end
    })

    -- Left Visuals: Custom Ambience & Lighting
    AmbienceBox:AddToggle("CustomAmbience", {
        Text = T("EnableAmbience"),
        Default = customAmbienceEnabled,
        Tooltip = T("AmbienceDesc"),
        Callback = function(Value)
            customAmbienceEnabled = Value
            applyAmbience()
        end
    })

    AmbienceBox:AddDropdown("AmbiencePreset", {
        Values = { "Purple Night", "Sunset", "Blood Moon", "Cyberpunk", "Midnight", "Toxic Green" },
        Default = 1,
        Multi = false,
        Text = T("AmbiencePreset"),
        Callback = function(Value)
            local p = ambiencePresets[Value]
            if p then
                customLighting.ClockTime = p.ClockTime
                customLighting.Ambient = p.Ambient
                customLighting.OutdoorAmbient = p.OutdoorAmbient
                customLighting.FogColor = p.FogColor
                customLighting.FogDistance = p.FogEnd
                customLighting.TintColor = p.Tint
                customLighting.Saturation = p.Saturation
                applyAmbience()
            end
        end
    })

    AmbienceBox:AddSlider("AmbienceClockTime", {
        Text = T("ClockTime"),
        Default = customLighting.ClockTime,
        Min = 0,
        Max = 24,
        Rounding = 1,
        Compact = false,
        Callback = function(Value)
            customLighting.ClockTime = Value
            if customAmbienceEnabled then Lighting.ClockTime = Value end
        end
    })

    AmbienceBox:AddSlider("AmbienceFogDist", {
        Text = T("FogDist"),
        Default = customLighting.FogDistance,
        Min = 100,
        Max = 3000,
        Rounding = 0,
        Compact = false,
        Callback = function(Value)
            customLighting.FogDistance = Value
            if customAmbienceEnabled then Lighting.FogEnd = Value end
        end
    })

    AmbienceBox:AddSlider("AmbienceSaturation", {
        Text = T("Saturation"),
        Default = math.floor(customLighting.Saturation * 10),
        Min = -10,
        Max = 15,
        Rounding = 0,
        Compact = false,
        Callback = function(Value)
            customLighting.Saturation = Value / 10
            if customAmbienceEnabled and colorCorrection then
                colorCorrection.Saturation = Value / 10
            end
        end
    })

    AmbienceBox:AddLabel(T("AmbientColor")):AddColorPicker("AmbientCol", {
        Default = customLighting.Ambient,
        Title = "Ambient Color",
        Callback = function(Value)
            customLighting.Ambient = Value
            if customAmbienceEnabled then Lighting.Ambient = Value end
        end
    })

    AmbienceBox:AddLabel(T("OutdoorColor")):AddColorPicker("OutdoorCol", {
        Default = customLighting.OutdoorAmbient,
        Title = "Outdoor Ambient",
        Callback = function(Value)
            customLighting.OutdoorAmbient = Value
            if customAmbienceEnabled then Lighting.OutdoorAmbient = Value end
        end
    })

    AmbienceBox:AddLabel(T("FogColor")):AddColorPicker("FogCol", {
        Default = customLighting.FogColor,
        Title = "Fog Color",
        Callback = function(Value)
            customLighting.FogColor = Value
            if customAmbienceEnabled then
                Lighting.FogColor = Value
                if atmosphere then atmosphere.Color = Value end
            end
        end
    })

    -- Left Visuals: Custom CS Crosshair
    CrosshairBox:AddToggle("EnableCrosshair", {
        Text = T("EnableCrosshair"),
        Default = customCrosshairEnabled,
        Callback = function(Value)
            customCrosshairEnabled = Value
        end
    }):AddColorPicker("CrosshairColor", {
        Default = crosshairColor,
        Title = "Crosshair Color",
        Callback = function(Value)
            crosshairColor = Value
        end
    })

    CrosshairBox:AddSlider("CrosshairSize", {
        Text = T("CrosshairSize"),
        Default = crosshairSize,
        Min = 2,
        Max = 25,
        Rounding = 0,
        Compact = false,
        Callback = function(Value)
            crosshairSize = Value
        end
    })

    CrosshairBox:AddSlider("CrosshairGap", {
        Text = T("CrosshairGap"),
        Default = crosshairGap,
        Min = 0,
        Max = 15,
        Rounding = 0,
        Compact = false,
        Callback = function(Value)
            crosshairGap = Value
        end
    })

    CrosshairBox:AddSlider("CrosshairThickness", {
        Text = T("CrosshairThickness"),
        Default = math.floor(crosshairThickness * 10),
        Min = 10,
        Max = 40,
        Rounding = 0,
        Compact = false,
        Callback = function(Value)
            crosshairThickness = Value / 10
        end
    })

    CrosshairBox:AddToggle("CrosshairDot", {
        Text = T("CrosshairDot"),
        Default = crosshairDotEnabled,
        Callback = function(Value)
            crosshairDotEnabled = Value
        end
    })

    -- Right Visuals: Advanced ESP / Chams
    RightVis:AddToggle("ESP", {
        Text = T("EnableESP"),
        Default = espEnabled,
        Tooltip = T("ESPDesc"),
        Callback = function(Value)
            espEnabled = Value
            pcall(updateEsp)
        end
    }):AddColorPicker("ESPColor", {
        Default = espFillColor,
        Title = "ESP Color",
        Callback = function(Value)
            espFillColor = Value
            for _, d in pairs(espCache) do
                if d.highlight then d.highlight.FillColor = Value end
            end
        end
    })

    RightVis:AddToggle("ESPNames", {
        Text = T("ESPNames"),
        Default = espShowNames,
        Tooltip = T("ESPNamesDesc"),
        Callback = function(Value)
            espShowNames = Value
            espShowDistance = Value
            for _, d in pairs(espCache) do
                if d.nameLabel then d.nameLabel.Visible = Value end
            end
        end
    })

    RightVis:AddToggle("ESPHealth", {
        Text = T("ESPHealth"),
        Default = espShowHealth,
        Tooltip = T("ESPHealthDesc"),
        Callback = function(Value)
            espShowHealth = Value
            for _, d in pairs(espCache) do
                if d.healthBg then d.healthBg.Visible = Value end
            end
        end
    })

    RightVis:AddToggle("ESPWeapon", {
        Text = T("ESPWeapon"),
        Default = espShowWeapon,
        Tooltip = T("ESPWeaponDesc"),
        Callback = function(Value)
            espShowWeapon = Value
        end
    })

    RightVis:AddToggle("ESPBots", {
        Text = T("ESPBots"),
        Default = espTargetBots,
        Callback = function(Value)
            espTargetBots = Value
        end
    })

    RightVis:AddSlider("ESPTransp", {
        Text = T("ChamsTransp"),
        Default = math.floor(espFillTransparency * 10),
        Min = 0,
        Max = 10,
        Rounding = 0,
        Compact = false,
        Callback = function(Value)
            espFillTransparency = Value / 10
            for _, d in pairs(espCache) do
                if d.highlight then d.highlight.FillTransparency = Value / 10 end
            end
        end
    })

    RightVis:AddDivider()

    RightVis:AddToggle("Fullbright", {
        Text = T("Fullbright"),
        Default = fullbrightEnabled,
        Tooltip = T("FullbrightDesc"),
        Callback = function(Value)
            fullbrightEnabled = Value
            if Value then
                Lighting.Brightness = 2
                Lighting.ClockTime = 14
                Lighting.FogEnd = 100000
                Lighting.GlobalShadows = false
            else
                Lighting.Brightness = origLighting.Brightness
                Lighting.ClockTime = origLighting.ClockTime
                Lighting.FogEnd = origLighting.FogEnd
                Lighting.GlobalShadows = origLighting.GlobalShadows
            end
        end
    })

    -- Right Visuals: 2D Box ESP, Snaplines, Head Dots, Target Tracer
    DrawingBox:AddToggle("BoxESP", {
        Text = T("BoxESP"),
        Default = boxEspEnabled,
        Tooltip = T("BoxESPDesc"),
        Callback = function(Value)
            boxEspEnabled = Value
            if not Value then
                for _, d in pairs(drawingCache) do
                    if d.box then d.box.Visible = false end
                end
            end
        end
    }):AddColorPicker("BoxColor", {
        Default = boxColor,
        Title = "Box Color",
        Callback = function(Value)
            boxColor = Value
        end
    })

    DrawingBox:AddToggle("Snaplines", {
        Text = T("Snaplines"),
        Default = snaplinesEnabled,
        Tooltip = T("SnaplinesDesc"),
        Callback = function(Value)
            snaplinesEnabled = Value
            if not Value then
                for _, d in pairs(drawingCache) do
                    if d.line then d.line.Visible = false end
                end
            end
        end
    }):AddColorPicker("SnaplinesColor", {
        Default = snaplinesColor,
        Title = "Snaplines Color",
        Callback = function(Value)
            snaplinesColor = Value
        end
    })

    DrawingBox:AddDropdown("TracerOrigin", {
        Values = { "Bottom", "Center" },
        Default = 1,
        Multi = false,
        Text = T("TracerOrigin"),
        Callback = function(Value)
            snaplinesOrigin = Value
        end
    })

    DrawingBox:AddToggle("HeadDots", {
        Text = T("HeadDots"),
        Default = headDotsEnabled,
        Tooltip = T("HeadDotsDesc"),
        Callback = function(Value)
            headDotsEnabled = Value
            if not Value then
                for _, d in pairs(drawingCache) do
                    if d.dot then d.dot.Visible = false end
                end
            end
        end
    }):AddColorPicker("HeadDotsColor", {
        Default = headDotsColor,
        Title = "Head Dots Color",
        Callback = function(Value)
            headDotsColor = Value
        end
    })

    DrawingBox:AddToggle("TargetLine", {
        Text = T("TargetLine"),
        Default = targetLineEnabled,
        Tooltip = T("TargetLineDesc"),
        Callback = function(Value)
            targetLineEnabled = Value
            if not Value and targetLine then
                targetLine.Visible = false
            end
        end
    }):AddColorPicker("TargetLineColor", {
        Default = targetLineColor,
        Title = "Target Line Color",
        Callback = function(Value)
            targetLineColor = Value
        end
    })

    -- Right Visuals: Bullet Tracers (Hit Tracers)
    TracerBox:AddToggle("BulletTracers", {
        Text = T("EnableTracers"),
        Default = bulletTracersEnabled,
        Tooltip = T("TracersDesc"),
        Callback = function(Value)
            bulletTracersEnabled = Value
        end
    }):AddColorPicker("TracerCol", {
        Default = tracerColor,
        Title = "Tracer Color",
        Callback = function(Value)
            tracerColor = Value
        end
    })

    TracerBox:AddToggle("TracerImpact", {
        Text = T("ShowImpact"),
        Default = tracerShowImpact,
        Tooltip = T("ShowImpactDesc"),
        Callback = function(Value)
            tracerShowImpact = Value
        end
    }):AddColorPicker("ImpactCol", {
        Default = tracerImpactColor,
        Title = "Impact Color",
        Callback = function(Value)
            tracerImpactColor = Value
        end
    })

    TracerBox:AddSlider("TracerDur", {
        Text = T("TracerDuration"),
        Default = math.floor(tracerDuration * 10),
        Min = 2,
        Max = 30,
        Rounding = 0,
        Compact = false,
        Callback = function(Value)
            tracerDuration = Value / 10
        end
    })

    TracerBox:AddSlider("TracerThick", {
        Text = T("TracerThickness"),
        Default = math.floor(tracerThickness * 100),
        Min = 5,
        Max = 40,
        Rounding = 0,
        Compact = false,
        Callback = function(Value)
            tracerThickness = Value / 100
        end
    })

    -- 5. SKINS TAB
    local LeftSkins = Tabs.Skins:AddLeftGroupbox(T("RevolverSkinsGroup"))
    local RightSkins = Tabs.Skins:AddRightGroupbox(T("KnifeSkinsGroup"))

    local function findSkinIdx(list, targetName)
        for i, v in ipairs(list) do
            if v == targetName then return i end
        end
        return 1
    end

    LeftSkins:AddToggle("EnableSkinChanger", {
        Text = T("EnableSkinChanger"),
        Default = skinChangerEnabled,
        Tooltip = T("SkinChangerDesc"),
        Callback = function(Value)
            skinChangerEnabled = Value
            saveSkinsAutoload()
            applySkins()
        end
    })

    LeftSkins:AddDropdown("RevolverSkinSelect", {
        Values = availableRevolvers,
        Default = findSkinIdx(availableRevolvers, selectedRevolverSkin),
        Multi = false,
        Text = T("RevolverSkinSelect"),
        Callback = function(Value)
            selectedRevolverSkin = Value
            saveSkinsAutoload()
            if skinChangerEnabled then
                applySkins()
            end
        end
    })

    LeftSkins:AddButton(T("ApplySkins"), function()
        applySkins()
    end)

    LeftSkins:AddButton(T("SaveAsAutoload"), function()
        saveSkinsAutoload()
        Library:Notify(T("AutoloadSaved") .. string.format("\n[%s | %s]", selectedRevolverSkin, selectedKnifeSkin), 3)
    end)

    RightSkins:AddDropdown("KnifeSkinSelect", {
        Values = availableKnives,
        Default = findSkinIdx(availableKnives, selectedKnifeSkin),
        Multi = false,
        Text = T("KnifeSkinSelect"),
        Callback = function(Value)
            selectedKnifeSkin = Value
            saveSkinsAutoload()
            if skinChangerEnabled then
                applySkins()
            end
        end
    })

    RightSkins:AddButton(T("ApplySkins"), function()
        applySkins()
    end)

    RightSkins:AddButton(T("SaveAsAutoload"), function()
        saveSkinsAutoload()
        Library:Notify(T("AutoloadSaved") .. string.format("\n[%s | %s]", selectedRevolverSkin, selectedKnifeSkin), 3)
    end)

    -- Viewmodel Settings (Left Column)
    local ViewmodelBox = Tabs.Skins:AddLeftGroupbox(T("ViewmodelGroup"))
    ViewmodelBox:AddToggle("EnableViewmodel", {
        Text = T("EnableViewmodel"),
        Default = viewmodelEnabled,
        Tooltip = T("ViewmodelDesc"),
        Callback = function(Value)
            viewmodelEnabled = Value
        end
    })

    ViewmodelBox:AddToggle("HideArms", {
        Text = T("HideArms"),
        Default = hideArmsEnabled,
        Tooltip = T("HideArmsDesc"),
        Callback = function(Value)
            hideArmsEnabled = Value
        end
    })

    ViewmodelBox:AddDropdown("VMMode", {
        Values = { T("VMArmAndWeapon"), T("VMWeaponOnly") },
        Default = (vmTargetMode == "ArmAndWeapon") and 1 or 2,
        Multi = false,
        Text = T("VMMode"),
        Callback = function(Value)
            if Value == T("VMWeaponOnly") or Value:find("Weapon") or Value:find("Только") then
                vmTargetMode = "WeaponOnly"
            else
                vmTargetMode = "ArmAndWeapon"
            end
        end
    })

    ViewmodelBox:AddDropdown("VMPreset", {
        Values = { "Default", "Left Hand", "Centered / Doom", "Gangster Tilt", "Extended" },
        Default = 1,
        Multi = false,
        Text = T("VMPreset"),
        Callback = function(Value)
            if Value == "Default" then
                vm.x, vm.y, vm.z = 0, 0, 0
                vm.pitch, vm.yaw, vm.roll = 0, 0, 0
            elseif Value == "Left Hand" then
                vm.x, vm.y, vm.z = -1.3, -0.1, 0.2
                vm.pitch, vm.yaw, vm.roll = 0, 0, -15
            elseif Value == "Centered / Doom" then
                vm.x, vm.y, vm.z = -0.85, -0.2, 0.4
                vm.pitch, vm.yaw, vm.roll = 5, 0, 0
            elseif Value == "Gangster Tilt" then
                vm.x, vm.y, vm.z = 0.1, 0.1, 0.2
                vm.pitch, vm.yaw, vm.roll = 0, 10, 40
            elseif Value == "Extended" then
                vm.x, vm.y, vm.z = 0, -0.1, -1.2
                vm.pitch, vm.yaw, vm.roll = 0, 0, 0
            end
            pcall(function()
                if Options.VMOffsetX then Options.VMOffsetX:SetValue(math.floor(vm.x * 10)) end
                if Options.VMOffsetY then Options.VMOffsetY:SetValue(math.floor(vm.y * 10)) end
                if Options.VMOffsetZ then Options.VMOffsetZ:SetValue(math.floor(vm.z * 10)) end
                if Options.VMPitch then Options.VMPitch:SetValue(vm.pitch) end
                if Options.VMYaw then Options.VMYaw:SetValue(vm.yaw) end
                if Options.VMRoll then Options.VMRoll:SetValue(vm.roll) end
            end)
        end
    })

    ViewmodelBox:AddSlider("VMOffsetX", {
        Text = T("VMOffsetX"),
        Default = math.floor(vm.x * 10),
        Min = -25,
        Max = 25,
        Rounding = 0,
        Compact = false,
        Callback = function(Value)
            vm.x = Value / 10
        end
    })

    ViewmodelBox:AddSlider("VMOffsetY", {
        Text = T("VMOffsetY"),
        Default = math.floor(vm.y * 10),
        Min = -25,
        Max = 25,
        Rounding = 0,
        Compact = false,
        Callback = function(Value)
            vm.y = Value / 10
        end
    })

    ViewmodelBox:AddSlider("VMOffsetZ", {
        Text = T("VMOffsetZ"),
        Default = math.floor(vm.z * 10),
        Min = -25,
        Max = 25,
        Rounding = 0,
        Compact = false,
        Callback = function(Value)
            vm.z = Value / 10
        end
    })

    ViewmodelBox:AddSlider("VMPitch", {
        Text = T("VMPitch"),
        Default = vm.pitch,
        Min = -45,
        Max = 45,
        Rounding = 0,
        Compact = false,
        Callback = function(Value)
            vm.pitch = Value
        end
    })

    ViewmodelBox:AddSlider("VMYaw", {
        Text = T("VMYaw"),
        Default = vm.yaw,
        Min = -45,
        Max = 45,
        Rounding = 0,
        Compact = false,
        Callback = function(Value)
            vm.yaw = Value
        end
    })

    ViewmodelBox:AddSlider("VMRoll", {
        Text = T("VMRoll"),
        Default = vm.roll,
        Min = -45,
        Max = 45,
        Rounding = 0,
        Compact = false,
        Callback = function(Value)
            vm.roll = Value
        end
    })

    ViewmodelBox:AddButton(T("ResetViewmodel"), function()
        vm.x, vm.y, vm.z = 0, 0, 0
        vm.pitch, vm.yaw, vm.roll = 0, 0, 0
        pcall(function()
            if Options.VMOffsetX then Options.VMOffsetX:SetValue(0) end
            if Options.VMOffsetY then Options.VMOffsetY:SetValue(0) end
            if Options.VMOffsetZ then Options.VMOffsetZ:SetValue(0) end
            if Options.VMPitch then Options.VMPitch:SetValue(0) end
            if Options.VMYaw then Options.VMYaw:SetValue(0) end
            if Options.VMRoll then Options.VMRoll:SetValue(0) end
        end)
    end)

    -- Weapon Scale (Right Column)
    local ScaleBox = Tabs.Skins:AddRightGroupbox(T("WeaponScaleGroup"))
    ScaleBox:AddToggle("EnableWeaponScale", {
        Text = T("EnableWeaponScale"),
        Default = weaponScaleEnabled,
        Tooltip = T("WeaponScaleDesc"),
        Callback = function(Value)
            weaponScaleEnabled = Value
        end
    })

    ScaleBox:AddDropdown("ScalePreset", {
        Values = { "Default (1.0x)", "Compact / Mini (0.5x)", "Medium (1.5x)", "Giant Buster (2.5x)", "Colossal (3.5x)" },
        Default = 1,
        Multi = false,
        Text = T("ScalePreset"),
        Callback = function(Value)
            if Value:find("Default") then
                weaponScale = 1.0
            elseif Value:find("Mini") or Value:find("Compact") then
                weaponScale = 0.5
            elseif Value:find("Medium") then
                weaponScale = 1.5
            elseif Value:find("Giant") then
                weaponScale = 2.5
            elseif Value:find("Colossal") then
                weaponScale = 3.5
            end
            pcall(function()
                if Options.WeaponScaleSlider then
                    Options.WeaponScaleSlider:SetValue(math.floor(weaponScale * 100))
                end
            end)
        end
    })

    ScaleBox:AddSlider("WeaponScaleSlider", {
        Text = T("WeaponScale"),
        Default = math.floor(weaponScale * 100),
        Min = 20,
        Max = 350,
        Rounding = 0,
        Compact = false,
        Callback = function(Value)
            weaponScale = Value / 100
        end
    })

    ScaleBox:AddButton(T("ResetViewmodel"), function()
        weaponScale = 1.0
        pcall(function()
            if Options.WeaponScaleSlider then Options.WeaponScaleSlider:SetValue(100) end
        end)
    end)

    -- 6. SETTINGS TAB (Separated into Left and Right columns + Config & Theme Manager)
    local LeftSettings = Tabs["UI Settings"]:AddLeftGroupbox(T("LanguageSettings"))
    local RightSettings = Tabs["UI Settings"]:AddRightGroupbox(T("UnloadGroup"))

    LeftSettings:AddDropdown("Language", {
        Values = { "Русский (RU)", "English (EN)" },
        Default = currentLang == "RU" and 1 or 2,
        Multi = false,
        Text = T("Language"),
        Callback = function(Value)
            local newLang = Value:find("RU") and "RU" or "EN"
            if newLang ~= currentLang then
                currentLang = newLang
                _G.MD_SelectedLanguage = newLang
                task.defer(function()
                    Library:Unload()
                    buildMenu()
                end)
            end
        end
    })

    LeftSettings:AddDivider()

    -- Menu Keybind controls
    local currentKeyName = (_G.MD_MenuToggleKey and _G.MD_MenuToggleKey.Name) or "RightControl"
    menuKeyLabelRef = LeftSettings:AddLabel(T("MenuKey") .. ": [" .. currentKeyName .. "]")

    LeftSettings:AddDropdown("QuickMenuKey", {
        Values = { "RightControl", "Insert", "RightShift", "LeftAlt", "F1", "F4", "Delete", "P", "L" },
        Default = (function()
            local cur = (_G.MD_MenuToggleKey and _G.MD_MenuToggleKey.Name) or "RightControl"
            local vals = { "RightControl", "Insert", "RightShift", "LeftAlt", "F1", "F4", "Delete", "P", "L" }
            for i, v in ipairs(vals) do
                if v == cur then return i end
            end
            return 1
        end)(),
        Multi = false,
        Text = T("QuickKeySelect"),
        Callback = function(Value)
            local kc = Enum.KeyCode[Value]
            if kc then
                _G.MD_MenuToggleKey = kc
                if menuKeyLabelRef then
                    menuKeyLabelRef:SetText(T("MenuKey") .. ": [" .. Value .. "]")
                end
                Library:Notify(T("KeybindUpdated") .. ": " .. Value, 3)
            end
        end
    })

    LeftSettings:AddButton(T("ChangeMenuKey"), function()
        isListeningForMenuKey = true
        if menuKeyLabelRef then
            menuKeyLabelRef:SetText(T("MenuKey") .. ": [" .. T("PressAnyKey") .. "]")
        end
        Library:Notify(T("PressAnyKey"), 3)
    end)

    RightSettings:AddButton(T("Unload"), function()
        if _G.MurderDuelsCleanup then
            _G.MurderDuelsCleanup()
        end
    end)

    -- Integrate ThemeManager and SaveManager on UI Settings Tab
    pcall(function()
        ThemeManager:SetLibrary(Library)
        SaveManager:SetLibrary(Library)

        SaveManager:IgnoreThemeSettings()
        SaveManager:SetIgnoreIndexes({ "MenuKey", "QuickMenuKey", "Language" })

        ThemeManager:SetFolder("MurderDuelsSkeet")
        SaveManager:SetFolder("MurderDuelsSkeet")

        SaveManager:BuildConfigSection(Tabs["UI Settings"])
        ThemeManager:ApplyToTab(Tabs["UI Settings"])

        pcall(function()
            SaveManager:LoadAutoloadConfig()
        end)
    end)

    Library:SetWatermark(string.format("Murder Duels | Skeet Edition | %s | [%s]", currentLang, (_G.MD_MenuToggleKey and _G.MD_MenuToggleKey.Name) or "RightControl"))
    Library:SetWatermarkVisibility(true)
end

-- ==================== 9. GLOBAL KEYBIND LISTENER ====================
table.insert(Connections, UserInputService.InputBegan:Connect(function(input, gpe)
    if isListeningForMenuKey then
        if input.UserInputType == Enum.UserInputType.Keyboard then
            _G.MD_MenuToggleKey = input.KeyCode
            isListeningForMenuKey = false
            if menuKeyLabelRef then
                menuKeyLabelRef:SetText(T("MenuKey") .. ": [" .. input.KeyCode.Name .. "]")
            end
            Library:SetWatermark(string.format("Murder Duels | Skeet Edition | %s | [%s]", currentLang, input.KeyCode.Name))
            Library:Notify(T("KeybindUpdated") .. ": " .. input.KeyCode.Name, 3)
        end
        return
    end

    if input.UserInputType == Enum.UserInputType.Keyboard then
        local targetKey = _G.MD_MenuToggleKey or Enum.KeyCode.RightControl
        if input.KeyCode == targetKey then
            Library:Toggle()
        end
    end
end))

-- Initialize Menu
buildMenu()

-- Cleanup Handler
_G.MD_Running = true
_G.MurderDuelsCleanup = function()
    isAlive = false
    _G.MD_Running = false
    LocalPlayer:SetAttribute("MouseUnlocked", nil)
    resetAntiAim()
    thirdPersonEnabled = false
    applyNativeCamera()

    customAmbienceEnabled = false
    applyAmbience()

    pcall(function()
        if originalRevolverSkin then
            LocalPlayer:SetAttribute("RevolverSkin", originalRevolverSkin)
            LocalPlayer:SetAttribute("RevolverName", originalRevolverSkin)
        end
        if originalKnifeSkin then
            LocalPlayer:SetAttribute("KnifeSkin", originalKnifeSkin)
            LocalPlayer:SetAttribute("KnifeName", originalKnifeSkin)
        end
    end)

    pcall(function()
        local rs = game:GetService("ReplicatedStorage")
        local revTiming = require(rs.Shared.RevolverTiming)
        local knifeTiming = require(rs.Shared.KnifeTiming)
        revTiming.SHOT_COOLDOWN = 2
        revTiming.RELOAD_SOUND_FALLBACK = 0.8
        knifeTiming.THROW_COOLDOWN = 0.3
        knifeTiming.HOLD_TO_THROW_SEC = 0.2
        knifeTiming.CHARGE_DUR = 0.5
    end)

    if fovCircle then
        pcall(function() fovCircle:Remove() end)
        fovCircle = nil
    end

    if legitFovCircle then
        pcall(function() legitFovCircle:Remove() end)
        legitFovCircle = nil
    end

    if autoPeekVisual then
        pcall(function() autoPeekVisual:Destroy() end)
        autoPeekVisual = nil
    end
    autoPeekAnchor = nil
    autoPeekState = "IDLE"

    if targetLine then
        pcall(function() targetLine:Remove() end)
        targetLine = nil
    end

    for _, l in pairs(crosshairLines) do
        pcall(function() l:Remove() end)
    end
    crosshairLines = {}

    for _, d in pairs(drawingCache) do
        pcall(function() d.box:Remove() end)
        pcall(function() d.line:Remove() end)
        pcall(function() d.dot:Remove() end)
    end
    drawingCache = {}

    -- Cleanup active bullet tracers and markers from Camera and Bin
    for _, container in ipairs({ workspace.CurrentCamera, workspace:FindFirstChild("Bin") }) do
        if container then
            for _, child in ipairs(container:GetChildren()) do
                if child.Name == "MD_BulletTracer" or child.Name == "MD_ImpactDot" or child.Name == "MD_AutoPeekMarker" then
                    pcall(function() child:Destroy() end)
                end
            end
        end
    end

    for _, conn in ipairs(Connections) do
        if conn and conn.Disconnect then conn:Disconnect() end
    end
    clearAllEsp()

    if fullbrightEnabled then
        Lighting.Brightness = origLighting.Brightness
        Lighting.ClockTime = origLighting.ClockTime
        Lighting.FogEnd = origLighting.FogEnd
        Lighting.GlobalShadows = origLighting.GlobalShadows
    end

    -- Cleanup Skin Changer Viewports & restore hotbar icons & attributes
    pcall(function()
        local playerGui = LocalPlayer:FindFirstChild("PlayerGui")
        local inMatchUI = playerGui and playerGui:FindFirstChild("InMatchUI")
        local abilities = inMatchUI and inMatchUI:FindFirstChild("Abilities")
        if abilities then
            for _, slotName in ipairs({ "Knife", "Gun" }) do
                local slot = abilities:FindFirstChild(slotName)
                if slot then
                    local vp = slot:FindFirstChild("MD_SkinViewport")
                    if vp then pcall(function() vp:Destroy() end) end
                    local icon = slot:FindFirstChild("WeaponIcon")
                    if icon then icon.ImageTransparency = 0 end
                end
            end
        end
    end)
    if originalRevolverSkin then
        LocalPlayer:SetAttribute("RevolverSkin", originalRevolverSkin)
    end
    if originalKnifeSkin then
        LocalPlayer:SetAttribute("KnifeSkin", originalKnifeSkin)
    end

    pcall(function() Library:Unload() end)
    _G.MurderDuelsCleanup = nil
    _G.MD_Unload = nil
end
_G.MD_Unload = _G.MurderDuelsCleanup

Library:Notify(currentLang == "RU" and ("Murder Duels Skeet Hub загружен! [" .. ((_G.MD_MenuToggleKey and _G.MD_MenuToggleKey.Name) or "RightControl") .. "]") or ("Murder Duels Skeet Hub loaded! [" .. ((_G.MD_MenuToggleKey and _G.MD_MenuToggleKey.Name) or "RightControl") .. "]"), 5)
--[[
    Murder Duels - Skeet / Linoria Edition (CS-Style UI)
    Features:
      - Multi-Language Support (RU / EN) with instant language switcher
      - Full Config Manager & Themes (SaveManager & ThemeManager):
          * Create, Save, Load, Overwrite, Delete configs
          * Set as default / Autoload on start
          * Custom theme picker & presets (Skeet, BBot, Tokyo Night, Ubuntu, Synthwave)
      - Working Silent Aim (Bullets & knives hit targets without camera snapping)
      - Silent Auto-Fire (Triggerbot) with Muzzle Clearance:
          * Automatically shoots when aim target is locked inside FOV
          * Zero camera movement / snapping
          * Muzzle Clearance Check (Raycasts directly from the revolver barrel/tip to target)
            Prevents shooting into walls, corners, boxes, or firing prematurely before peeking
          * Hooks ViewportPointToRay and Mouse.Hit natively so Triggerbot shots always hit via Silent Aim
      - Glowing Bullet Tracers / Hit Tracers:
          * Glowing Neon laser beam from muzzle to impact point on every shot (Revolver & Knife)
          * Neon impact hit dot with smooth Quad fadeout
          * Supports ricochets and custom colors / thickness / duration
      - Strict Target & Health Validation:
          * Alive & Health Check (HP > 0, state ~= Dead, no dead attributes)
          * Existence Check (Part and Character exist in workspace, not destroyed)
          * Immunity / ForceField Check
          * Strict Wall Check (Raycast Line-of-Sight, pierces destructible glass, blocks solid walls)
          * Team Check (Respects teammates and lobby teams)
      - High-Speed Bhop (Speed up to 150 studs/s, instant air strafes without CD)
      - Native Centered 3rd Person (Zero crookedness, shoulder offset 0)
      - Advanced ESP (Chams, Names, Distance, Health Bar, Weapon indicator)
      - Rich 2D Visuals:
          * 2D Box ESP (Bounding box around enemies)
          * Snaplines / Tracers (From Bottom or Center)
          * Head Dots (Precise head circles)
          * Silent Aim Target Line (Line directly to locked aim target)
          * Custom CS Crosshair (Size, Gap, Thickness, Dot)
      - Custom World Ambience:
          * Atmosphere Presets (Purple Night, Sunset, Blood Moon, Cyberpunk, Midnight, Toxic Green)
          * Time of Day (ClockTime 0 - 24 hours)
          * Custom Ambient & OutdoorAmbient colors
          * Fog Distance & Color with Atmosphere Tint
          * Saturation & Tint Color Correction
      - Bulletproof Menu Keybind (Quick-Select Dropdown + Press-Any-Key listener via UIS)
      - Working Sliders (Auto mouse unlock while menu is open)
      - Client-Side Weapon Skin Changer:
          * Equips any revolver and knife skin in the game (82+ Knives, 62+ Revolvers)
          * Full 3D meshes, PBR SurfaceAppearance, particles, beams, glow and neon
          * Custom weapon animations (Equip, Shoot, Slash, Inspect) & sounds (Firing, Reload, Equip)
          * Auto-persists on round change and respawns
]]

local Players = game:GetService("Players")
local RunService = game:GetService("RunService")
local UserInputService = game:GetService("UserInputService")
local Lighting = game:GetService("Lighting")
local TweenService = game:GetService("TweenService")

local LocalPlayer = Players.LocalPlayer

-- ==================== 0. MASTER PURGE PREVIOUS INSTANCES ====================
pcall(function()
    if _G.MD_GlobalConnections then
        for _, c in ipairs(_G.MD_GlobalConnections) do
            pcall(function() c:Disconnect() end)
        end
    end
end)
_G.MD_GlobalConnections = {}

if _G.MurderDuelsCleanup then
    pcall(_G.MurderDuelsCleanup)
    _G.MurderDuelsCleanup = nil
end
if _G.MD_Unload then
    pcall(_G.MD_Unload)
    _G.MD_Unload = nil
end

pcall(function()
    if cleardrawcache then cleardrawcache() end
end)

pcall(function()
    local CoreGui = game:GetService("CoreGui")
    for _, child in ipairs(CoreGui:GetChildren()) do
        if child.Name:find("ESP") or child.Name:find("Linoria") or child.Name == "ScreenGui" or child.Name:find("MD_") then
            pcall(function() child:Destroy() end)
        end
    end
end)

pcall(function()
    for _, obj in ipairs(workspace:GetDescendants()) do
        if obj:IsA("Highlight") and (obj.Name:find("ESP") or obj.Name:find("MD_")) then
            pcall(function() obj:Destroy() end)
        end
    end
end)

local isAlive = true
_G.MD_Running = true

-- Weapon timings & instant knife charging
pcall(function()
    local rs = game:GetService("ReplicatedStorage")
    local revTiming = require(rs.Shared.RevolverTiming)
    local knifeTiming = require(rs.Shared.KnifeTiming)
    revTiming.SHOT_COOLDOWN = 2
    revTiming.RELOAD_SOUND_FALLBACK = 0.8
    knifeTiming.THROW_COOLDOWN = 0.3
    knifeTiming.HOLD_TO_THROW_SEC = 0.2
    knifeTiming.CHARGE_DUR = 0.01
end)

-- Game native modules
local PlayerState = nil
local NativeTP = nil
pcall(function()
    PlayerState = require(game:GetService("ReplicatedStorage"):WaitForChild("Shared"):WaitForChild("PlayerState"))
    NativeTP = require(game:GetService("ReplicatedStorage"):WaitForChild("Shared"):WaitForChild("ThirdPerson"))
end)

-- ==================== LOCALIZATION (RU / EN) ====================
local currentLang = _G.MD_SelectedLanguage or "RU"

local Loc = {
    RU = {
        Title = "Murder Duels | Skeet Edition",
        Rage = "Рейдж",
        Legit = "Легит",
        Combat = "Бой",
        AntiAim = "Анти-Аим",
        Movement = "Движение",
        Visuals = "Визуалы",
        Settings = "Настройки",
        -- Combat / Rage
        SilentAimbot = "Сайлент Аим и Триггер",
        EnableSilentAim = "Включить Silent Aim",
        SilentAimDesc = "Пули и ножи летят во врага БЕЗ поворота камеры",
        ActivationMode = "Режим работы аима",
        AlwaysOn = "Всегда включен",
        HoldKey = "При удержании клавиши",
        SilentAutoFire = "Сайлент Авто-выстрел (Triggerbot)",
        SilentAutoFireDesc = "Автоматически стреляет при наведении на врага с Сайлент Аимом (БЕЗ рывков камеры)",
        AutoFireDelay = "Задержка выстрела (сек)",
        KnifeHoldDuration = "Зажатие ножа (сек)",
        KnifeHoldDurationDesc = "Сколько удерживать ЛКМ для броска ножа в триггерботе (сек)",
        MuzzleCheck = "Проверка дула револьвера (Muzzle Check)",
        MuzzleCheckDesc = "Стрелять только когда конец револьвера чисто видит цель (не стреляет в углы и стены)",
        WallCheck = "Строгая проверка стен (Wall Check)",
        WallCheckDesc = "Не стрелять если враг за стеной или препятствием",
        TeamCheck = "Проверка команды (Team Check)",
        TeamCheckDesc = "Не целиться в союзников",
        Prediction = "Упреждение движения (Prediction)",
        PredictionDesc = "Упреждение полета ножа/пули по скорости цели",
        ProjSpeed = "Скорость снаряда",
        MaxKnifePower = "Всегда макс. сила ножа (Always Max Power)",
        MaxKnifePowerDesc = "Нож всегда летит с максимальной скоростью и дальностью, даже при слабом броске",
        InstantKnifeCharge = "Мгновенный заряд ножа (Instant Charge)",
        InstantKnifeChargeDesc = "Прицел мгновенно сужается за 0.01 сек при замахе ножа",
        TargetFilters = "Фильтры целей и хитбоксы",
        TargetPlayers = "Игроки (Players)",
        TargetNoobs = "Манекены / Нубы (Dummies)",
        TargetBullseyes = "Мишени в тире (Targets)",
        HitboxPriority = "Приоритет хитбокса",
        DrawFOV = "Отображать круг FOV",
        FOVRadius = "Радиус FOV",
        -- Auto-Peek
        AutoPeek = "Авто-Пик (Auto-Peek)",
        EnableAutoPeek = "Включить Auto-Peek",
        AutoPeekDesc = "Запоминает точку, при выстреле моментально оттягивает обратно в укрытие",
        AutoPeekKey = "Клавиша Auto-Peek",
        AutoPeekMarker = "Светящийся маркер",
        AutoPeekMarkerDesc = "Показывать круг возврата на полу за укрытием",
        AutoPeekColor = "Цвет маркера",
        AutoPeekSpeed = "Скорость возврата (Speed)",
        -- Auto-Win / Kill Aura
        AutoWinGroup = "Авто-Вин / Килл Аура",
        EnableAutoWin = "Включить Auto-Win",
        AutoWinDesc = "Моментальное убийство противника в раунде (авто-победа)",
        AutoWinMode = "Режим автовина",
        AutoWinKey = "Клавиша Auto-Win",
        AutoWinReturn = "Возврат на место после ТП",
        AutoWinReturnDesc = "После удара со спины мгновенно возвращает на исходную точку",
        AutoWinEquip = "Авто-доставать нож",
        AutoWinEquipDesc = "Автоматически берет нож в руку перед атакой",
        AutoWinDelay = "Задержка повтора (сек)",
        -- Legit Tab
        LegitAimbot = "Легит Аимбот (Smooth Aim)",
        EnableLegitAim = "Включить Legit Aim",
        LegitAimDesc = "Плавная человеческая доводка камеры к противнику",
        LegitAimKey = "Клавиша Legit Aim",
        LegitSmoothness = "Плавность доводки (Smooth)",
        LegitFOV = "Радиус легит FOV",
        DrawLegitFOV = "Отображать легит FOV",
        LegitHitbox = "Приоритет хитбокса",
        LegitWallCheck = "Проверка видимости (Wall Check)",
        LegitTriggerbot = "Легит Триггербот (Triggerbot)",
        EnableLegitTrigger = "Включить Legit Triggerbot",
        LegitTriggerDesc = "Авто-выстрел только когда реальный прицел мыши наведён на врага",
        ReactionDelay = "Человеческая задержка (мс)",
        -- Anti-Aim
        AnglesDesync = "Углы и Дезсинк",
        SpeedConfig = "Скорость и Настройки",
        EnableAA = "Включить Anti-Aim",
        AADesc = "Ломает траектории ножей и аимботы противников",
        YawMode = "Режим Yaw",
        PitchMode = "Режим Pitch",
        SpinSpeed = "Скорость вращения",
        PitchAngle = "Угол Pitch",
        JitterAngle = "Угол Jitter",
        SwayFreq = "Частота Sway",
        -- Movement
        BhopStrafes = "Баннихоп и Стрейфы",
        MovementBoost = "Ускорители движения",
        Bhop = "Bunny Hop (Bhop)",
        BhopDesc = "Автоматические прыжки при удержании Пробела",
        AirStrafes = "Instant Air Strafes",
        AirStrafesDesc = "Мгновенное изменение вектора скорости без задержки и КД (W/A/S/D)",
        BhopSpeed = "Bhop Speed (Разгон)",
        InfJump = "Бесконечный прыжок (Infinite Jump)",
        InfJumpDesc = "Прыгать в воздухе сколько угодно раз",
        WalkSpeed = "WalkSpeed Booster",
        -- Visuals
        ThirdPersonCam = "Камера 3-го лица",
        CrosshairVisuals = "Кастомный прицел (Crosshair)",
        ESPWorld = "ESP игроков и Chams",
        DrawingVisuals = "2D Боксы и Трейсеры",
        AmbienceWorld = "Кастомный Эмбиенс и Освещение",
        BulletTracers = "Хиттрейсеры пуль (Bullet Tracers)",
        EnableTP = "Включить 3-е лицо",
        TPDesc = "Нативный вид от 3-го лица (ровно по центру, без кривых углов)",
        CamDist = "Дистанция камеры",
        ShoulderX = "Смещение плеча (0 = Центр)",
        HeightY = "Высота камеры",
        FOV = "Поле зрения (FOV)",
        EnableESP = "Включить Chams ESP",
        ESPDesc = "Подсветка игроков и ботов через стены",
        ESPNames = "Имена и Дистанция",
        ESPNamesDesc = "Отображать ник и дистанцию над головой",
        ESPHealth = "Полоска здоровья",
        ESPHealthDesc = "Отображать динамическую полоску здоровья",
        ESPWeapon = "Отображать оружие",
        ESPWeaponDesc = "Показывать что враг держит в руках (Revolver / Knife)",
        ESPBots = "Подсвечивать ботов / нубов",
        ChamsTransp = "Прозрачность Chams",
        Fullbright = "Fullbright (Без темноты)",
        FullbrightDesc = "Удалить тени, темноту и туман на арене",
        -- 2D Visuals
        BoxESP = "2D Рамки (Box ESP)",
        BoxESPDesc = "Отображать 2D прямоугольники вокруг игроков",
        Snaplines = "Трейсеры (Snaplines)",
        SnaplinesDesc = "Отображать линии к игрокам",
        TracerOrigin = "Откуда рисовать линии",
        TracerBottom = "Снизу экрана",
        TracerCenter = "От прицела",
        HeadDots = "Точки на голове (Head Dots)",
        HeadDotsDesc = "Отображать кружки на голове противников",
        TargetLine = "Линия захвата аима (Target Line)",
        TargetLineDesc = "Показывает линию к текущей цели сайлент аима",
        EnableCrosshair = "Включить кастомный прицел",
        CrosshairSize = "Размер линий прицела",
        CrosshairGap = "Зазор прицела (Gap)",
        CrosshairThickness = "Толщина линий",
        CrosshairDot = "Центральная точка",
        -- Bullet Tracers
        EnableTracers = "Включить хиттрейсеры",
        TracersDesc = "Светящийся неоновый луч от дула револьвера до точки попадания",
        ShowImpact = "Точка попадания (Impact Dot)",
        ShowImpactDesc = "Светящаяся сфера в месте попадания пули",
        TracerDuration = "Длительность луча (сек)",
        TracerThickness = "Толщина луча",
        -- Custom Ambience
        EnableAmbience = "Включить кастомный эмбиенс",
        AmbienceDesc = "Кастомное освещение, время суток и атмосфера карты",
        AmbiencePreset = "Пресеты атмосферы",
        ClockTime = "Время суток (Часы)",
        FogDist = "Дистанция тумана (Fog)",
        Saturation = "Насыщенность цветов",
        AmbientColor = "Цвет Ambient",
        OutdoorColor = "Цвет OutdoorAmbient",
        FogColor = "Цвет тумана",
        -- Settings
        MenuSettings = "Настройки интерфейса",
        LanguageSettings = "Язык меню и Бинд",
        UnloadGroup = "Управление скриптом",
        Language = "Выбор языка",
        Unload = "Выгрузить меню (Unload)",
        MenuKey = "Клавиша меню",
        QuickKeySelect = "Быстрый выбор клавиши меню",
        ChangeMenuKey = "Нажмите для смены клавиши (Любая)",
        PressAnyKey = "Нажмите любую клавишу...",
        KeybindUpdated = "Клавиша меню изменена на",
        -- Skins Tab
        Skins = "Скины",
        SkinChanger = "Скинченджер оружия (Client-Side)",
        EnableSkinChanger = "Включить Скинченджер",
        SkinChangerDesc = "Визуально надевает любой скин на револьвер и нож (3D модели, PBR-текстуры, звуки и анимации)",
        RevolverSkinsGroup = "Скины на Револьвер",
        KnifeSkinsGroup = "Скины на Нож",
        RevolverSkinSelect = "Выбор скина револьвера",
        KnifeSkinSelect = "Выбор скина ножа",
        ApplySkins = "Применить скины",
        SaveAsAutoload = "Сохранить как автозагрузку",
        AutoloadSaved = "Скины сохранены в автозагрузку!",
        AutoSaveSkins = "Авто-сохранение скинов",
        AutoSaveSkinsDesc = "Автоматически сохранять выбранные скины в автозагрузку",
        AutoloadStatus = "Автозагрузка",
        -- Viewmodel & Weapon Scale
        ViewmodelGroup = "Кастомный Viewmodel (Положение оружия)",
        EnableViewmodel = "Включить Viewmodel",
        ViewmodelDesc = "Смещение и наклон оружия в руках от 1-го и 3-го лица",
        HideArms = "Скрыть руки (Hide Arms)",
        HideArmsDesc = "Делает руки полностью невидимыми (парящее оружие)",
        VMMode = "Режим смещения",
        VMArmAndWeapon = "Рука и оружие (Вместе)",
        VMWeaponOnly = "Только оружие",
        VMPreset = "Пресеты Viewmodel",
        VMOffsetX = "Смещение X (Влево / Вправо)",
        VMOffsetY = "Смещение Y (Вверх / Вниз)",
        VMOffsetZ = "Смещение Z (Вперед / Назад)",
        VMPitch = "Наклон Pitch (Вверх / Вниз)",
        VMYaw = "Поворот Yaw (Влево / Вправо)",
        VMRoll = "Крен Roll (Gangster Tilt)",
        WeaponScaleGroup = "Размер оружия (Weapon Scale)",
        EnableWeaponScale = "Включить изменение размера",
        WeaponScaleDesc = "Увеличивает или уменьшает 3D модель ножа и револьвера",
        WeaponScale = "Масштаб размера (Scale)",
        ScalePreset = "Пресеты размера",
        ResetViewmodel = "Сбросить по умолчанию",
    },
    EN = {
        Title = "Murder Duels | Skeet Edition",
        Rage = "Rage",
        Legit = "Legit",
        Combat = "Combat",
        AntiAim = "Anti-Aim",
        Movement = "Movement",
        Visuals = "Visuals",
        Settings = "Settings",
        -- Combat / Rage
        SilentAimbot = "Silent Aim & Trigger",
        EnableSilentAim = "Enable Silent Aim",
        SilentAimDesc = "Bullets & knives hit target WITHOUT moving camera",
        ActivationMode = "Aim Activation Mode",
        AlwaysOn = "Always On",
        HoldKey = "Hold Keybind",
        SilentAutoFire = "Silent Auto-Fire (Triggerbot)",
        SilentAutoFireDesc = "Automatically fires when aiming at enemy with Silent Aim (no camera snap)",
        AutoFireDelay = "Auto-Fire Delay (sec)",
        KnifeHoldDuration = "Knife Hold Time (sec)",
        KnifeHoldDurationDesc = "Duration triggerbot holds attack to throw knife (sec)",
        MuzzleCheck = "Muzzle Clearance Check",
        MuzzleCheckDesc = "Only fire when the revolver barrel has a direct line of sight (avoids walls/corners)",
        WallCheck = "Strict Wall Check",
        WallCheckDesc = "Do not shoot if target is behind solid walls or obstacles",
        TeamCheck = "Team Check",
        TeamCheckDesc = "Do not target teammates",
        Prediction = "Movement Prediction",
        PredictionDesc = "Lead knife/bullet based on target velocity",
        ProjSpeed = "Projectile Speed",
        MaxKnifePower = "Always Max Knife Power",
        MaxKnifePowerDesc = "Knife throws always have maximum velocity (420) and range even on weak taps",
        InstantKnifeCharge = "Instant Knife Charge",
        InstantKnifeChargeDesc = "Charges knife instantly in 0.01s with zero crosshair bloom",
        TargetFilters = "Target Filters & Hitbox",
        TargetPlayers = "Target Players",
        TargetNoobs = "Target Dummies (Noobs)",
        TargetBullseyes = "Target Shooting Bullseyes",
        HitboxPriority = "Hitbox Priority",
        DrawFOV = "Draw FOV Circle",
        FOVRadius = "FOV Radius",
        -- Auto-Peek
        AutoPeek = "Auto-Peek (Peek Assist)",
        EnableAutoPeek = "Enable Auto-Peek",
        AutoPeekDesc = "Records safe position, peeks, and pulls back behind cover after shot",
        AutoPeekKey = "Auto-Peek Keybind",
        AutoPeekMarker = "Show Return Marker",
        AutoPeekMarkerDesc = "Displays glowing circle marker on the ground at return point",
        AutoPeekColor = "Marker Color",
        AutoPeekSpeed = "Return Speed",
        -- Auto-Win / Kill Aura
        AutoWinGroup = "Auto-Win / Kill Aura",
        EnableAutoWin = "Enable Auto-Win",
        AutoWinDesc = "Instantly eliminates the opponent to win the round automatically",
        AutoWinMode = "Auto-Win Mode",
        AutoWinKey = "Auto-Win Keybind",
        AutoWinReturn = "Return to Origin After TP",
        AutoWinReturnDesc = "Instantly snaps character back to original position after backstab",
        AutoWinEquip = "Auto-Equip Knife",
        AutoWinEquipDesc = "Automatically pulls out the knife before attacking",
        AutoWinDelay = "Repeat Delay (sec)",
        -- Legit Tab
        LegitAimbot = "Legit Aimbot (Smooth Aim)",
        EnableLegitAim = "Enable Legit Aim",
        LegitAimDesc = "Smooth humanized camera aim assistance towards target",
        LegitAimKey = "Legit Aim Keybind",
        LegitSmoothness = "Aim Smoothness",
        LegitFOV = "Legit FOV Radius",
        DrawLegitFOV = "Draw Legit FOV Circle",
        LegitHitbox = "Hitbox Priority",
        LegitWallCheck = "Visibility Check (Wall Check)",
        LegitTriggerbot = "Legit Triggerbot",
        EnableLegitTrigger = "Enable Legit Triggerbot",
        LegitTriggerDesc = "Fires only when your crosshair is directly aimed at an enemy",
        ReactionDelay = "Reaction Delay (ms)",
        -- Anti-Aim
        AnglesDesync = "Angles & Desync",
        SpeedConfig = "Speed & Configuration",
        EnableAA = "Enable Anti-Aim",
        AADesc = "Breaks knife trajectories and opponent aimbots",
        YawMode = "Yaw Mode",
        PitchMode = "Pitch Mode",
        SpinSpeed = "Spinbot Speed",
        PitchAngle = "Pitch Angle",
        JitterAngle = "Jitter Angle",
        SwayFreq = "Sway Frequency",
        -- Movement
        BhopStrafes = "Bunny Hop & Air Strafes",
        MovementBoost = "Movement Boosters",
        Bhop = "Bunny Hop (Bhop)",
        BhopDesc = "Automatic jumps when holding Space without landing lag",
        AirStrafes = "Instant Air Strafes",
        AirStrafesDesc = "Instant velocity redirection without cooldown (W/A/S/D)",
        BhopSpeed = "Bhop Speed (Acceleration)",
        InfJump = "Infinite Jump",
        InfJumpDesc = "Jump in mid-air unlimited times",
        WalkSpeed = "WalkSpeed Booster",
        -- Visuals
        ThirdPersonCam = "3rd Person Camera",
        CrosshairVisuals = "Custom Crosshair",
        ESPWorld = "Player ESP & Chams",
        DrawingVisuals = "2D Boxes & Tracers",
        AmbienceWorld = "Custom Ambience & Lighting",
        BulletTracers = "Bullet Tracers",
        EnableTP = "Enable 3rd Person",
        TPDesc = "Native 3rd person perspective (centered, no crooked angles)",
        CamDist = "Camera Distance",
        ShoulderX = "Shoulder Offset (0 = Centered)",
        HeightY = "Height Offset",
        FOV = "Field Of View",
        EnableESP = "Enable Chams ESP",
        ESPDesc = "Highlight opponents and bots through walls",
        ESPNames = "Show Names & Distance",
        ESPNamesDesc = "Display username and distance above head",
        ESPHealth = "Show Health Bar",
        ESPHealthDesc = "Display dynamic health bar with current HP",
        ESPWeapon = "Show Equipped Weapon",
        ESPWeaponDesc = "Show held weapon (Revolver / Knife)",
        ESPBots = "Highlight Bots / Dummies",
        ChamsTransp = "Chams Transparency",
        Fullbright = "Fullbright (No Darkness)",
        FullbrightDesc = "Remove shadows, darkness, and fog",
        -- 2D Visuals
        BoxESP = "2D Box ESP",
        BoxESPDesc = "Draw 2D bounding boxes around players",
        Snaplines = "Snaplines / Tracers",
        SnaplinesDesc = "Draw lines pointing to enemies",
        TracerOrigin = "Tracer Origin",
        TracerBottom = "Bottom of Screen",
        TracerCenter = "Center / Crosshair",
        HeadDots = "Head Dots",
        HeadDotsDesc = "Draw clean dots on enemy heads",
        TargetLine = "Silent Aim Target Line",
        TargetLineDesc = "Shows a tracer to current silent aim target",
        EnableCrosshair = "Enable Custom Crosshair",
        CrosshairSize = "Crosshair Line Size",
        CrosshairGap = "Crosshair Gap",
        CrosshairThickness = "Line Thickness",
        CrosshairDot = "Center Dot",
        -- Bullet Tracers
        EnableTracers = "Enable Bullet Tracers",
        TracersDesc = "Glowing neon beam from weapon muzzle to impact point",
        ShowImpact = "Impact Dot",
        ShowImpactDesc = "Glowing neon sphere at bullet impact point",
        TracerDuration = "Tracer Duration (sec)",
        TracerThickness = "Tracer Thickness",
        -- Custom Ambience
        EnableAmbience = "Enable Custom Ambience",
        AmbienceDesc = "Custom world lighting, time of day and map atmosphere",
        AmbiencePreset = "Atmosphere Presets",
        ClockTime = "Time of Day (Hours)",
        FogDist = "Fog Distance",
        Saturation = "Color Saturation",
        AmbientColor = "Ambient Color",
        OutdoorColor = "OutdoorAmbient Color",
        FogColor = "Fog Color",
        -- Settings
        MenuSettings = "UI Settings",
        LanguageSettings = "Menu Language & Keybind",
        UnloadGroup = "Script Control",
        Language = "Select Language",
        Unload = "Unload Hub",
        MenuKey = "Menu Keybind",
        QuickKeySelect = "Quick Menu Key Select",
        ChangeMenuKey = "Click to Change Key (Any Key)",
        PressAnyKey = "Press any key...",
        KeybindUpdated = "Menu keybind updated to",
        -- Skins Tab
        Skins = "Skins",
        SkinChanger = "Weapon Skin Changer (Client-Side)",
        EnableSkinChanger = "Enable Skin Changer",
        SkinChangerDesc = "Visually equips any revolver & knife skin (3D models, PBR textures, sounds & animations)",
        RevolverSkinsGroup = "Revolver Skins",
        KnifeSkinsGroup = "Knife Skins",
        RevolverSkinSelect = "Select Revolver Skin",
        KnifeSkinSelect = "Select Knife Skin",
        ApplySkins = "Apply Skins",
        SaveAsAutoload = "Set as Autoload",
        AutoloadSaved = "Skins saved to autoload!",
        AutoSaveSkins = "Auto-Save Skins",
        AutoSaveSkinsDesc = "Automatically save selected skins to autoload",
        AutoloadStatus = "Autoload",
        -- Viewmodel & Weapon Scale
        ViewmodelGroup = "Custom Viewmodel (Weapon Position)",
        EnableViewmodel = "Enable Viewmodel Offset",
        ViewmodelDesc = "Offset and angle of weapon in hands (1st & 3rd person)",
        HideArms = "Hide Arms / Hands",
        HideArmsDesc = "Makes arms fully invisible (floating weapon view)",
        VMMode = "Offset Mode",
        VMArmAndWeapon = "Arm & Weapon (Together)",
        VMWeaponOnly = "Weapon Only",
        VMPreset = "Viewmodel Presets",
        VMOffsetX = "Offset X (Left / Right)",
        VMOffsetY = "Offset Y (Up / Down)",
        VMOffsetZ = "Offset Z (Forward / Back)",
        VMPitch = "Pitch Tilt (Up / Down)",
        VMYaw = "Yaw Angle (Left / Right)",
        VMRoll = "Roll Angle (Gangster Tilt)",
        WeaponScaleGroup = "Weapon Scale (Size)",
        EnableWeaponScale = "Enable Weapon Scale",
        WeaponScaleDesc = "Scales the 3D model size of knife and revolver",
        WeaponScale = "Scale Multiplier",
        ScalePreset = "Scale Presets",
        ResetViewmodel = "Reset to Default",
    }
}

local function T(k)
    local dict = Loc[currentLang] or Loc.RU
    return dict[k] or k
end

-- Load LinoriaLib & Addons
local Library = loadstring(game:HttpGet("https://raw.githubusercontent.com/GhostDuckyy/UI-Libraries/3b0bcba89893baa65d36b12b33e70e93ebc8b122/LinoriaLib/source.lua"))()
local ThemeManager = loadstring(game:HttpGet("https://raw.githubusercontent.com/GhostDuckyy/UI-Libraries/3b0bcba89893baa65d36b12b33e70e93ebc8b122/LinoriaLib/addons/ThemeManager.lua"))()
local SaveManager = loadstring(game:HttpGet("https://raw.githubusercontent.com/GhostDuckyy/UI-Libraries/3b0bcba89893baa65d36b12b33e70e93ebc8b122/LinoriaLib/addons/SaveManager.lua"))()

local Connections = _G.MD_GlobalConnections
local cachedTargets = {}
local silentAimTargetPart = nil
local silentAimTargetChar = nil

-- Combat variables (Silent Aim)
local silentAimEnabled = false
local teamCheckEnabled = true
local wallCheckEnabled = true
local wallbangEnabled = false
local targetPlayers = true
local targetNoobs = true
local targetTargets = true
local targetPartMode = "Head"
local fovRadius = 160
local showFovCircle = true
local silentAimMode = "AlwaysOn"
local alwaysMaxKnifePower = true
local instantKnifeCharge = true
local knifeSpeed = 6.5
_G.MD_AlwaysMaxKnifePower = true
_G.MD_KnifeSpeed = 6.5
_G.MD_WallbangEnabled = wallbangEnabled

-- Silent Auto-Fire (Triggerbot without camera snapping)
local silentAutoFire = false
local silentAutoFireDelay = 0.25
local knifeHoldDuration = 0.24
local lastSilentFireTime = 0
local muzzleCheckEnabled = false -- Muzzle Clearance Check (off by default so triggerbot is 100% reliable)

-- Auto-Peek (Peek Assist) State
local autoPeekEnabled = false
local autoPeekAnchor = nil
local autoPeekVisual = nil
local autoPeekColor = Color3.fromRGB(0, 255, 180)
local autoPeekShowMarker = true
local autoPeekReturnSpeed = 4.0
local autoPeekState = "IDLE" -- "IDLE", "RECORDED", "PEEKING", "RETURNING"

-- Auto-Win / Kill Aura State
local autoWinEnabled = false
local autoWinMode = "TP Backstab"
local autoWinDelay = 0.15
local autoWinReturn = true
local autoWinEquip = true
local lastAutoWinTime = 0
local isAutoWinExecuting = false

local function updateAutoPeekVisual()
    if autoPeekEnabled and autoPeekShowMarker and autoPeekAnchor then
        local container = workspace:FindFirstChild("Bin") or workspace.CurrentCamera
        if not autoPeekVisual or not autoPeekVisual.Parent then
            local marker = Instance.new("Part")
            marker.Name = "MD_AutoPeekMarker"
            marker.Anchored = true
            marker.CanCollide = false
            marker.CanTouch = false
            marker.CanQuery = false
            marker.CastShadow = false
            marker.Material = Enum.Material.Neon
            marker.Shape = Enum.PartType.Cylinder
            marker.Color = autoPeekColor
            marker.Transparency = 0.35
            marker.Size = Vector3.new(0.25, 4.5, 4.5)
            marker.Parent = container
            autoPeekVisual = marker
        end
        autoPeekVisual.Color = autoPeekColor
        autoPeekVisual.CFrame = CFrame.new(autoPeekAnchor.X, autoPeekAnchor.Y - 2.8, autoPeekAnchor.Z) * CFrame.Angles(0, 0, math.rad(90))
    else
        if autoPeekVisual then
            pcall(function() autoPeekVisual:Destroy() end)
            autoPeekVisual = nil
        end
    end
end

local function triggerAutoPeekReturn()
    if autoPeekEnabled and autoPeekAnchor and (autoPeekState == "PEEKING" or autoPeekState == "RECORDED") then
        task.delay(0.06, function()
            if autoPeekEnabled and autoPeekAnchor then
                autoPeekState = "RETURNING"
            end
        end)
    end
end

-- Legit Aimbot (Smooth Aim) State
local legitAimEnabled = false
local legitAimMode = "HoldKey"
local legitSmoothness = 6
local legitFovRadius = 85
local legitHitbox = "Head"
local legitShowFov = false
local legitWallCheck = true
local legitFovCircle = nil

-- Legit Triggerbot State
local legitTriggerEnabled = false
local legitTriggerDelay = 0.16
local legitTriggerTeamCheck = true
local legitTriggerStartTime = 0
local lastLegitTriggerFireTime = 0

-- Bullet Tracers / Hit Tracers State
local bulletTracersEnabled = true
local tracerColor = Color3.fromRGB(0, 255, 220) -- Neon Cyan
local tracerImpactColor = Color3.fromRGB(255, 60, 60) -- Neon Red
local tracerDuration = 1.0
local tracerThickness = 0.12
local tracerShowImpact = true

local function spawnBulletTracer(from, to)
    if not bulletTracersEnabled then return end
    if not from or not to then return end
    local dist = (to - from).Magnitude
    if dist < 0.5 or dist > 1500 then return end

    local container = workspace:FindFirstChild("Bin") or workspace.CurrentCamera
    if not container then return end

    task.spawn(function()
        pcall(function()
            -- Glowing Neon Cylinder Beam
            local tracer = Instance.new("Part")
            tracer.Name = "MD_BulletTracer"
            tracer.Anchored = true
            tracer.CanCollide = false
            tracer.CanTouch = false
            tracer.CanQuery = false
            tracer.CastShadow = false
            tracer.Material = Enum.Material.Neon
            tracer.Color = tracerColor
            tracer.Shape = Enum.PartType.Cylinder
            tracer.Size = Vector3.new(dist, tracerThickness, tracerThickness)
            tracer.CFrame = CFrame.lookAt((from + to) / 2, to) * CFrame.Angles(0, math.rad(90), 0)
            tracer.Parent = container

            local tracerTween = TweenService:Create(tracer, TweenInfo.new(tracerDuration, Enum.EasingStyle.Quad, Enum.EasingDirection.Out), {
                Transparency = 1
            })
            tracerTween.Completed:Connect(function()
                pcall(function() tracer:Destroy() end)
            end)
            tracerTween:Play()

            -- Glowing Neon Impact Dot at hit position
            if tracerShowImpact then
                local hitDot = Instance.new("Part")
                hitDot.Name = "MD_ImpactDot"
                hitDot.Anchored = true
                hitDot.CanCollide = false
                hitDot.CanTouch = false
                hitDot.CanQuery = false
                hitDot.CastShadow = false
                hitDot.Material = Enum.Material.Neon
                hitDot.Color = tracerImpactColor
                hitDot.Shape = Enum.PartType.Ball
                hitDot.Size = Vector3.new(tracerThickness * 2.5, tracerThickness * 2.5, tracerThickness * 2.5)
                hitDot.CFrame = CFrame.new(to)
                hitDot.Parent = container

                local dotTween = TweenService:Create(hitDot, TweenInfo.new(tracerDuration, Enum.EasingStyle.Quad, Enum.EasingDirection.Out), {
                    Transparency = 1,
                    Size = Vector3.new(0.01, 0.01, 0.01)
                })
                dotTween.Completed:Connect(function()
                    pcall(function() hitDot:Destroy() end)
                end)
                dotTween:Play()
            end
        end)
    end)
end

_G.MD_OnShotFired = function(from, to)
    if bulletTracersEnabled and from and to then
        spawnBulletTracer(from, to)
    end
    triggerAutoPeekReturn()
end

local isKnifeThrowing = false

local function fireWeapon()
    local myChar = LocalPlayer.Character
    local tool = myChar and myChar:FindFirstChildOfClass("Tool")
    local isKnife = tool and (tool.Name:lower():find("knife") ~= nil)

    local im = nil
    pcall(function()
        im = require(game:GetService("ReplicatedStorage"):WaitForChild("Extensions"):WaitForChild("InputMap"))
    end)

    if isKnife then
        if isKnifeThrowing then return end
        isKnifeThrowing = true
        if im and im.fire then im.fire("Attack", true) end
        pcall(mouse1press)
        task.delay(knifeHoldDuration, function()
            if im and im.fire then im.fire("Attack", false) end
            pcall(mouse1release)
            task.delay(0.20, function()
                isKnifeThrowing = false
            end)
        end)
    else
        if im and im.tap then
            im.tap("Attack")
        else
            pcall(function() mouse1click() end)
        end
    end
end

-- Anti-Aim variables
local aaEnabled = false
local aaYawMode = "Spinbot"
local aaPitchMode = "Down (Head Roll)"
local spinSpeed = 25
local jitterAngle = 90
local swayFreq = 8
local swayAngle = 75
local pitchAngle = 35
local currentYaw = 0
local defaultRjC0 = CFrame.new(0, 0, 0, -1, 0, 0, 0, 0, 1, 0, 1, -0)

-- Movement variables
local bhopEnabled = false
local bhopSpeed = 55
local instantStrafes = true
local infiniteJump = false

-- 3rd Person variables (Native Centered)
local thirdPersonEnabled = false
local cameraDistance = 10
local shoulderOffset = 0
local heightOffset = 1.3
local customFOV = 85

-- Visuals: Advanced ESP
local espEnabled = false
local espShowNames = true
local espShowDistance = true
local espShowHealth = true
local espShowWeapon = true
local espTargetBots = true
local espFillColor = Color3.fromRGB(255, 65, 65)
local espOutlineColor = Color3.fromRGB(255, 255, 255)
local espFillTransparency = 0.5
local espOutlineTransparency = 0
local espCache = {}

local fullbrightEnabled = false

-- Original Lighting State
local colorCorrection = Lighting:FindFirstChildOfClass("ColorCorrectionEffect")
local atmosphere = Lighting:FindFirstChildOfClass("Atmosphere")
local origLighting = {
    Ambient = Lighting.Ambient,
    OutdoorAmbient = Lighting.OutdoorAmbient,
    Brightness = Lighting.Brightness,
    ClockTime = Lighting.ClockTime,
    FogColor = Lighting.FogColor,
    FogEnd = Lighting.FogEnd,
    GlobalShadows = Lighting.GlobalShadows,
    TintColor = colorCorrection and colorCorrection.TintColor or Color3.fromRGB(255, 255, 255),
    Saturation = colorCorrection and colorCorrection.Saturation or 0,
    AtmoColor = atmosphere and atmosphere.Color or Color3.fromRGB(200, 200, 200),
    AtmoDecay = atmosphere and atmosphere.Decay or Color3.fromRGB(100, 100, 100),
}

-- Custom Ambience State
local customAmbienceEnabled = false
local customLighting = {
    ClockTime = 0,
    Ambient = Color3.fromRGB(90, 20, 140),
    OutdoorAmbient = Color3.fromRGB(45, 10, 80),
    FogColor = Color3.fromRGB(35, 5, 55),
    FogDistance = 450,
    TintColor = Color3.fromRGB(230, 200, 255),
    Saturation = 0.35,
}

local ambiencePresets = {
    ["Purple Night"] = { ClockTime = 0, Ambient = Color3.fromRGB(90, 20, 140), OutdoorAmbient = Color3.fromRGB(45, 10, 80), FogColor = Color3.fromRGB(35, 5, 55), FogEnd = 450, Tint = Color3.fromRGB(230, 200, 255), Saturation = 0.35 },
    ["Sunset"] = { ClockTime = 17.8, Ambient = Color3.fromRGB(180, 90, 60), OutdoorAmbient = Color3.fromRGB(130, 60, 40), FogColor = Color3.fromRGB(160, 80, 50), FogEnd = 550, Tint = Color3.fromRGB(255, 220, 180), Saturation = 0.25 },
    ["Blood Moon"] = { ClockTime = 0, Ambient = Color3.fromRGB(160, 20, 20), OutdoorAmbient = Color3.fromRGB(90, 10, 10), FogColor = Color3.fromRGB(70, 5, 5), FogEnd = 400, Tint = Color3.fromRGB(255, 180, 180), Saturation = 0.4 },
    ["Cyberpunk"] = { ClockTime = 21, Ambient = Color3.fromRGB(140, 30, 140), OutdoorAmbient = Color3.fromRGB(30, 140, 180), FogColor = Color3.fromRGB(30, 25, 60), FogEnd = 500, Tint = Color3.fromRGB(230, 180, 255), Saturation = 0.5 },
    ["Midnight"] = { ClockTime = 0, Ambient = Color3.fromRGB(25, 35, 70), OutdoorAmbient = Color3.fromRGB(15, 20, 45), FogColor = Color3.fromRGB(10, 15, 35), FogEnd = 600, Tint = Color3.fromRGB(200, 220, 255), Saturation = 0.15 },
    ["Toxic Green"] = { ClockTime = 0, Ambient = Color3.fromRGB(20, 120, 50), OutdoorAmbient = Color3.fromRGB(10, 70, 30), FogColor = Color3.fromRGB(15, 50, 20), FogEnd = 450, Tint = Color3.fromRGB(180, 255, 200), Saturation = 0.4 }
}

local function applyAmbience()
    if not customAmbienceEnabled then
        Lighting.ClockTime = origLighting.ClockTime
        Lighting.Ambient = origLighting.Ambient
        Lighting.OutdoorAmbient = origLighting.OutdoorAmbient
        Lighting.FogColor = origLighting.FogColor
        Lighting.FogEnd = origLighting.FogEnd
        if colorCorrection then
            colorCorrection.TintColor = origLighting.TintColor
            colorCorrection.Saturation = origLighting.Saturation
        end
        if atmosphere then
            atmosphere.Color = origLighting.AtmoColor
            atmosphere.Decay = origLighting.AtmoDecay
        end
        return
    end

    Lighting.ClockTime = customLighting.ClockTime
    Lighting.Ambient = customLighting.Ambient
    Lighting.OutdoorAmbient = customLighting.OutdoorAmbient
    Lighting.FogColor = customLighting.FogColor
    Lighting.FogEnd = customLighting.FogDistance

    if not colorCorrection then
        colorCorrection = Instance.new("ColorCorrectionEffect", Lighting)
    end
    colorCorrection.TintColor = customLighting.TintColor
    colorCorrection.Saturation = customLighting.Saturation

    if atmosphere then
        atmosphere.Color = customLighting.FogColor
        atmosphere.Decay = customLighting.OutdoorAmbient
    end
end

-- Rich 2D Visuals State
local boxEspEnabled = false
local boxColor = Color3.fromRGB(255, 65, 65)

local snaplinesEnabled = false
local snaplinesColor = Color3.fromRGB(255, 200, 50)
local snaplinesOrigin = "Bottom"

local headDotsEnabled = false
local headDotsColor = Color3.fromRGB(0, 255, 200)

local targetLineEnabled = false
local targetLineColor = Color3.fromRGB(50, 255, 50)
local targetLine = nil

local customCrosshairEnabled = false
local crosshairColor = Color3.fromRGB(0, 255, 120)
local crosshairSize = 6
local crosshairGap = 4
local crosshairThickness = 1.5
local crosshairDotEnabled = false
local crosshairLines = {}

local drawingCache = {}

-- Menu Keybind State
_G.MD_MenuToggleKey = _G.MD_MenuToggleKey or Enum.KeyCode.RightControl
local isListeningForMenuKey = false
local menuKeyLabelRef = nil

-- ==================== CLIENT-SIDE SKIN CHANGER STATE & LOGIC ====================
local skinChangerEnabled = false
local selectedRevolverSkin = "ChromaSniper"
local selectedKnifeSkin = "ChromaKatana"

-- Viewmodel & Weapon Scale State
local viewmodelEnabled = false
local hideArmsEnabled = false
local vmTargetMode = "ArmAndWeapon" -- "ArmAndWeapon" or "WeaponOnly"
local defaultRSC1 = CFrame.new(-0.5, 0.5, 0, 0, 0, 1, 0, 1, 0, -1, 0, 0)
local vm = {
    x = 0, y = 0, z = 0,
    pitch = 0, yaw = 0, roll = 0
}

local weaponScaleEnabled = false
local weaponScale = 1.0

local skinsConfigFile = "MurderDuelsSkeet/skins_autoload.json"

local function saveSkinsAutoload()
    pcall(function()
        if not isfolder("MurderDuelsSkeet") then
            pcall(makefolder, "MurderDuelsSkeet")
        end
        local data = {
            enabled = (skinChangerEnabled == true),
            revolver = selectedRevolverSkin or "ChromaSniper",
            knife = selectedKnifeSkin or "ChromaKatana",
        }
        writefile(skinsConfigFile, game:GetService("HttpService"):JSONEncode(data))
    end)
end

local function loadSkinsAutoload()
    local loaded = false
    pcall(function()
        if isfile(skinsConfigFile) then
            local content = readfile(skinsConfigFile)
            local data = game:GetService("HttpService"):JSONDecode(content)
            if typeof(data) == "table" then
                if data.enabled ~= nil then
                    skinChangerEnabled = (data.enabled == true)
                end
                if data.revolver and data.revolver ~= "" then
                    selectedRevolverSkin = data.revolver
                end
                if data.knife and data.knife ~= "" then
                    selectedKnifeSkin = data.knife
                end
                loaded = true
            end
        end
    end)
    return loaded
end

loadSkinsAutoload()

local originalRevolverSkin = LocalPlayer:GetAttribute("RevolverSkin") or "Default"
local originalKnifeSkin = LocalPlayer:GetAttribute("KnifeSkin") or "Default"

local availableKnives, availableRevolvers
do
    local topKnives = { "ChromaKatana", "CorruptedChromaKatana", "Voidreaver", "Balisong", "GalaxyKarambit", "Karambit", "GoldenStiletto", "RedStiletto", "Kunai", "Saber", "Solaris", "Seraphim", "Default" }
    local topRevolvers = { "ChromaSniper", "MurderNote", "GoldenLuger", "RedLuger", "PurpleLuger", "ChampionSniper", "Deagle", "InfinityRay", "RayGun", "Voidcaster", "Default" }

    local function buildSkinList(folderName, topPriority)
        local list = {}
        local seen = {}
        local folder = game:GetService("ReplicatedStorage"):FindFirstChild(folderName)
        if folder then
            for _, name in ipairs(topPriority) do
                if folder:FindFirstChild(name) then
                    table.insert(list, name)
                    seen[name] = true
                end
            end
            local rest = {}
            for _, child in ipairs(folder:GetChildren()) do
                if child:IsA("Model") and not seen[child.Name] and not child.Name:find("Root") and not child.Name:find("Test") then
                    table.insert(rest, child.Name)
                end
            end
            table.sort(rest)
            for _, name in ipairs(rest) do
                table.insert(list, name)
            end
        end
        if #list == 0 then
            list = topPriority
        end
        return list
    end

    availableKnives = buildSkinList("Knives", topKnives)
    availableRevolvers = buildSkinList("Revolvers", topRevolvers)
end

local function updateSlotPreview(slotName, folderName, skinName, isKnife)
    local playerGui = LocalPlayer:FindFirstChild("PlayerGui")
    if not playerGui then return end
    local inMatchUI = playerGui:FindFirstChild("InMatchUI")
    if not inMatchUI then return end
    local abilities = inMatchUI:FindFirstChild("Abilities")
    if not abilities then return end
    local slot = abilities:FindFirstChild(slotName)
    if not slot then return end
    local icon = slot:FindFirstChild("WeaponIcon")

    local existingVp = slot:FindFirstChild("MD_SkinViewport")

    if not skinChangerEnabled or not skinName or skinName == "Default" or skinName == "" then
        if existingVp then
            pcall(function() existingVp:Destroy() end)
        end
        if icon then
            icon.ImageTransparency = 0
        end
        return
    end

    local folder = game:GetService("ReplicatedStorage"):FindFirstChild(folderName)
    if not folder then return end
    local skinModel = folder:FindFirstChild(skinName)
    if not skinModel then return end

    if icon then
        icon.ImageTransparency = 1
    end

    local vp = existingVp
    if not vp then
        vp = Instance.new("ViewportFrame")
        vp.Name = "MD_SkinViewport"
        vp.Size = UDim2.fromScale(0.88, 0.88)
        vp.Position = UDim2.fromScale(0.5, 0.5)
        vp.AnchorPoint = Vector2.new(0.5, 0.5)
        vp.BackgroundTransparency = 1
        vp.BorderSizePixel = 0
        vp.ZIndex = (icon and icon.ZIndex or 5) + 1
        vp.Parent = slot
    end

    vp.Visible = true
    vp:ClearAllChildren()

    local clone = skinModel:Clone()
    for _, d in ipairs(clone:GetDescendants()) do
        if d:IsA("Sound") or d:IsA("ParticleEmitter") or d:IsA("Light") or d:IsA("Script") or d:IsA("LocalScript") or d:IsA("Trail") then
            pcall(function() d:Destroy() end)
        elseif d:IsA("BasePart") then
            d.CanCollide = false
            d.Anchored = true
        end
    end

    local rootName = isKnife and "KnifeRoot" or "RevolverRoot"
    local root = clone:FindFirstChild(rootName, true)

    local minB = Vector3.new(math.huge, math.huge, math.huge)
    local maxB = Vector3.new(-math.huge, -math.huge, -math.huge)
    local rootPos = root and root.Position
    local tipPos = rootPos
    local maxDistFromRoot = 0

    for _, p in ipairs(clone:GetDescendants()) do
        if p:IsA("BasePart") and p.Transparency < 0.9 and p.Name ~= "BoundingBox" and not p.Name:lower():find("hitbox") then
            local cf = p.CFrame
            local h = p.Size * 0.5
            for x = -1, 1, 2 do
                for y = -1, 1, 2 do
                    for z = -1, 1, 2 do
                        local pt = cf:PointToWorldSpace(Vector3.new(x*h.X, y*h.Y, z*h.Z))
                        minB = Vector3.new(math.min(minB.X, pt.X), math.min(minB.Y, pt.Y), math.min(minB.Z, pt.Z))
                        maxB = Vector3.new(math.max(maxB.X, pt.X), math.max(maxB.Y, pt.Y), math.max(maxB.Z, pt.Z))
                    end
                end
            end
            if rootPos then
                local d = (p.Position - rootPos).Magnitude
                if d > maxDistFromRoot then
                    maxDistFromRoot = d
                    tipPos = p.Position
                end
            end
        end
    end

    local center = (minB + maxB) * 0.5
    local size = maxB - minB

    for _, p in ipairs(clone:GetDescendants()) do
        if p:IsA("BasePart") then
            p.CFrame = p.CFrame - center
        end
    end
    clone.Parent = vp

    local forwardDir
    if rootPos and tipPos and (tipPos - rootPos).Magnitude > 0.1 then
        forwardDir = (tipPos - rootPos).Unit
    else
        if size.X >= size.Y and size.X >= size.Z then forwardDir = Vector3.new(1,0,0)
        elseif size.Y >= size.X and size.Y >= size.Z then forwardDir = Vector3.new(0,1,0)
        else forwardDir = Vector3.new(0,0,1) end
    end

    local axes = {
        { axis = Vector3.new(1, 0, 0), len = size.X },
        { axis = Vector3.new(0, 1, 0), len = size.Y },
        { axis = Vector3.new(0, 0, 1), len = size.Z }
    }
    table.sort(axes, function(a, b) return a.len < b.len end)
    local thinAxis = axes[1].axis

    local normal = (thinAxis - forwardDir * thinAxis:Dot(forwardDir))
    if normal.Magnitude < 0.01 then
        normal = (axes[2].axis - forwardDir * axes[2].axis:Dot(forwardDir))
    end
    normal = normal.Unit

    local S = normal:Cross(forwardDir).Unit

    if not isKnife then
        local trueUp = (root and root.CFrame.UpVector) or Vector3.new(0, 1, 0)
        if S:Dot(trueUp) < 0 then
            S = -S
            normal = -normal
        end
    end
    local F = forwardDir
    local camRight, camUp
    if isKnife then
        camRight = (-F * 0.707 + S * 0.707).Unit
        camUp    = ( F * 0.707 + S * 0.707).Unit
    else
        camRight = (-F * 0.92 + S * 0.38).Unit
        camUp    = ( F * 0.38 + S * 0.92).Unit
    end

    local camLook = camRight:Cross(camUp).Unit

    local maxSpan = math.sqrt(size.X*size.X + size.Y*size.Y + size.Z*size.Z) * 0.65
    if maxSpan < 0.1 then maxSpan = 1 end

    local cam = Instance.new("Camera")
    cam.FieldOfView = 25
    local dist = (maxSpan * 0.5) / math.tan(math.rad(12.5)) * 1.25

    cam.CFrame = CFrame.fromMatrix(-camLook * dist, camRight, camUp, -camLook)
    cam.Parent = vp
    vp.CurrentCamera = cam

    vp.LightColor = Color3.fromRGB(255, 255, 255)
    vp.LightDirection = (-camLook + Vector3.new(0.4, 0.4, 0.4)).Unit
    vp.Ambient = Color3.fromRGB(200, 200, 200)
end

local function applySkins()
    if skinChangerEnabled then
        if selectedRevolverSkin and selectedRevolverSkin ~= "" then
            LocalPlayer:SetAttribute("RevolverSkin", selectedRevolverSkin)
            LocalPlayer:SetAttribute("RevolverName", selectedRevolverSkin)
        end
        if selectedKnifeSkin and selectedKnifeSkin ~= "" then
            LocalPlayer:SetAttribute("KnifeSkin", selectedKnifeSkin)
            LocalPlayer:SetAttribute("KnifeName", selectedKnifeSkin)
        end
    else
        LocalPlayer:SetAttribute("RevolverSkin", originalRevolverSkin)
        LocalPlayer:SetAttribute("KnifeSkin", originalKnifeSkin)
    end

    pcall(function()
        updateSlotPreview("Gun", "Revolvers", selectedRevolverSkin, false)
        updateSlotPreview("Knife", "Knives", selectedKnifeSkin, true)
    end)
end

_G.MD_SetSkin = function(gun, knife)
    skinChangerEnabled = true
    if gun then selectedRevolverSkin = gun end
    if knife then selectedKnifeSkin = knife end
    saveSkinsAutoload()
    applySkins()
end

if skinChangerEnabled then
    task.spawn(function()
        task.wait(0.15)
        applySkins()
    end)
end

table.insert(Connections, LocalPlayer:GetAttributeChangedSignal("RevolverSkin"):Connect(function()
    if skinChangerEnabled and selectedRevolverSkin and selectedRevolverSkin ~= "" and LocalPlayer:GetAttribute("RevolverSkin") ~= selectedRevolverSkin then
        LocalPlayer:SetAttribute("RevolverSkin", selectedRevolverSkin)
        LocalPlayer:SetAttribute("RevolverName", selectedRevolverSkin)
    end
end))

table.insert(Connections, LocalPlayer:GetAttributeChangedSignal("KnifeSkin"):Connect(function()
    if skinChangerEnabled and selectedKnifeSkin and selectedKnifeSkin ~= "" and LocalPlayer:GetAttribute("KnifeSkin") ~= selectedKnifeSkin then
        LocalPlayer:SetAttribute("KnifeSkin", selectedKnifeSkin)
        LocalPlayer:SetAttribute("KnifeName", selectedKnifeSkin)
    end
end))

table.insert(Connections, LocalPlayer.CharacterAdded:Connect(function()
    task.wait(0.25)
    if skinChangerEnabled then
        applySkins()
    end
end))

do
    local inMatchUIObj = LocalPlayer:FindFirstChild("PlayerGui") and LocalPlayer.PlayerGui:FindFirstChild("InMatchUI")
    if inMatchUIObj then
        table.insert(Connections, inMatchUIObj:GetPropertyChangedSignal("Enabled"):Connect(function()
            if inMatchUIObj.Enabled and skinChangerEnabled then
                task.wait(0.1)
                applySkins()
            end
        end))
        local abilitiesObj = inMatchUIObj:FindFirstChild("Abilities")
        if abilitiesObj then
            table.insert(Connections, abilitiesObj:GetPropertyChangedSignal("Visible"):Connect(function()
                if abilitiesObj.Visible and skinChangerEnabled then
                    task.wait(0.1)
                    applySkins()
                end
            end))
        end
    end

    if LocalPlayer:FindFirstChild("PlayerGui") then
        table.insert(Connections, LocalPlayer.PlayerGui.ChildAdded:Connect(function(child)
            if child.Name == "InMatchUI" and skinChangerEnabled then
                task.wait(0.2)
                applySkins()
            end
        end))
    end
end

-- FOV Circle & Drawing Initialization
local fovCircle = nil
if typeof(Drawing) == "table" and Drawing.new then
    pcall(function()
        fovCircle = Drawing.new("Circle")
        fovCircle.Thickness = 1.5
        fovCircle.NumSides = 64
        fovCircle.Radius = fovRadius
        fovCircle.Filled = false
        fovCircle.Color = Color3.fromRGB(255, 75, 75)
        fovCircle.Visible = false
        fovCircle.Transparency = 0.8

        legitFovCircle = Drawing.new("Circle")
        legitFovCircle.Thickness = 1.5
        legitFovCircle.NumSides = 64
        legitFovCircle.Radius = legitFovRadius
        legitFovCircle.Filled = false
        legitFovCircle.Color = Color3.fromRGB(60, 180, 255)
        legitFovCircle.Visible = false
        legitFovCircle.Transparency = 0.8

        targetLine = Drawing.new("Line")
        targetLine.Thickness = 1.5
        targetLine.Color = targetLineColor
        targetLine.Visible = false

        crosshairLines.h1 = Drawing.new("Line")
        crosshairLines.h2 = Drawing.new("Line")
        crosshairLines.v1 = Drawing.new("Line")
        crosshairLines.v2 = Drawing.new("Line")
        crosshairLines.dot = Drawing.new("Circle")
        crosshairLines.dot.Radius = 1.5
        crosshairLines.dot.Filled = true
        for _, l in pairs(crosshairLines) do
            l.Visible = false
        end
    end)
end

-- ==================== 0. MOUSE UNLOCK FOR SLIDERS ====================
local function maintainMouseAndOrder()
    local isMenuOpen = (Library and Library.IsOpen) or false
    if isMenuOpen then
        if LocalPlayer:GetAttribute("MouseUnlocked") ~= 1 then
            LocalPlayer:SetAttribute("MouseUnlocked", 1)
        end
        if UserInputService.MouseBehavior ~= Enum.MouseBehavior.Default then
            UserInputService.MouseBehavior = Enum.MouseBehavior.Default
        end
        UserInputService.MouseIconEnabled = true
    else
        if LocalPlayer:GetAttribute("MouseUnlocked") == 1 then
            LocalPlayer:SetAttribute("MouseUnlocked", nil)
        end
    end
end

table.insert(Connections, RunService.RenderStepped:Connect(maintainMouseAndOrder))

-- ==================== 1. HOOKS: TRUE SILENT AIM & BULLET TRACERS ====================
_G.MD_SilentAimEnabled = false
_G.MD_SilentAimTarget = nil
_G.MD_PredictionEnabled = false
_G.MD_CurrentWeaponIsKnife = false
local getAnyEnemyTarget = nil

_G.MD_NIL = _G.MD_NIL or newproxy()

-- Dynamic Metamethod Dispatchers (Ultra-optimized, zero allocations on non-target calls)
_G.MD_OnNamecall = function(self, method, ...)
    if method ~= "FireServer" and method ~= "Fire" and method ~= "ViewportPointToRay" and method ~= "Raycast" then
        return nil
    end

    if method == "Raycast" then
        if _G.MD_WallbangEnabled then
            local origin, direction, rayParams = ...
            if typeof(rayParams) == "RaycastParams" and rayParams.FilterType == Enum.RaycastFilterType.Exclude then
                -- Bypasses obstacle/wall collision for knife and bullet in ProjectilesController
                return _G.MD_NIL
            end
        end
        return nil
    end

    if method == "ViewportPointToRay" then
        if _G.MD_SilentAimEnabled and _G.MD_SilentAimTarget then
            local target = _G.MD_SilentAimTarget
            if target and target.Parent and self:IsA("Camera") then
                local camPos = self.CFrame.Position
                local targetPos = target.Position
                return Ray.new(camPos, (targetPos - camPos).Unit)
            end
        end
        return nil
    end

    if method == "Fire" then
        if self.Name == "SpawnKnife" then
            local shotData = ...
            if typeof(shotData) == "table" then
                shotData.power = _G.MD_KnifeSpeed or 6.5
                if _G.MD_SilentAimEnabled and _G.MD_SilentAimTarget then
                    local tgt = _G.MD_SilentAimTarget
                    local targetPos = tgt.Position
                    local origin = shotData.origin or workspace.CurrentCamera.CFrame.Position
                    shotData.target = origin + (targetPos - origin).Unit * 1000
                end
            end
            return nil
        end
        if self.Name == "SpawnBullet" then
            local shotData = ...
            if typeof(shotData) == "table" and _G.MD_SilentAimEnabled and _G.MD_SilentAimTarget then
                local tgt = _G.MD_SilentAimTarget
                shotData.hitInstance = tgt
                shotData.hitPos = tgt.Position
                shotData.to = tgt.Position
                shotData.isCharacterHit = true
                if typeof(shotData.segments) == "table" then
                    for _, seg in ipairs(shotData.segments) do
                        seg.hitInstance = tgt
                        seg.hitPos = tgt.Position
                        seg.isCharacterHit = true
                    end
                end
            end
            return nil
        end
        return nil
    end

    if method == "FireServer" then
        if self.Name == "ThrowReplicate" then
            local shotData = ...
            if typeof(shotData) == "table" then
                shotData.power = 1.0
                if _G.MD_SilentAimEnabled and _G.MD_SilentAimTarget then
                    local tgt = _G.MD_SilentAimTarget
                    local targetPos = tgt.Position
                    local origin = shotData.origin or workspace.CurrentCamera.CFrame.Position
                    shotData.target = origin + (targetPos - origin).Unit * 1000
                end
            end
        end

        if self.Name == "ShootReplicate" then
            local shotData = ...
            if typeof(shotData) == "table" and _G.MD_SilentAimEnabled and _G.MD_SilentAimTarget then
                local tgt = _G.MD_SilentAimTarget
                shotData.hitInstance = tgt
                shotData.hitPos = tgt.Position
                shotData.to = tgt.Position
                shotData.isCharacterHit = true
                if typeof(shotData.segments) == "table" then
                    for _, seg in ipairs(shotData.segments) do
                        seg.hitInstance = tgt
                        seg.hitPos = tgt.Position
                        seg.isCharacterHit = true
                    end
                end
            end
        end

        if self.Name == "ShootReplicate" or self.Name == "ThrowReplicate" then
            local shotData = ...
            if _G.MD_OnShotFired and typeof(shotData) == "table" then
                task.spawn(function()
                    pcall(function()
                        if shotData.segments and #shotData.segments > 0 then
                            for _, seg in ipairs(shotData.segments) do
                                if seg.from and seg.hitPos then
                                    _G.MD_OnShotFired(seg.from, seg.hitPos)
                                end
                            end
                        elseif shotData.origin and (shotData.hitPos or shotData.to or shotData.target) then
                            _G.MD_OnShotFired(shotData.origin, shotData.hitPos or shotData.to or shotData.target)
                        end
                    end)
                end)
            end
        end
        return nil
    end

    return nil
end

_G.MD_OnIndex = function(self, key)
    -- Fast exit: NEVER touch anything unless the key is specifically "Hit" or "Target"
    if key ~= "Hit" and key ~= "Target" then
        return nil
    end

    if not _G.MD_SilentAimEnabled or not _G.MD_SilentAimTarget then
        return nil
    end

    -- Verify caller is mouse without triggering recursive metamethod calls
    if typeof(self) == "Instance" and self.ClassName == "PlayerMouse" then
        local target = _G.MD_SilentAimTarget
        if target and target.Parent then
            local targetPos = target.Position

            if key == "Hit" then
                return CFrame.new(targetPos)
            elseif key == "Target" then
                return target
            end
        end
    end

    return nil
end

if not _G.MD_HooksInstalled then
    local oldNamecall
    oldNamecall = hookmetamethod(game, "__namecall", function(self, ...)
        local method = getnamecallmethod()
        if _G.MD_OnNamecall then
            local override = _G.MD_OnNamecall(self, method, ...)
            if override == _G.MD_NIL then
                return nil
            elseif override ~= nil then
                return override
            end
        end
        return oldNamecall(self, ...)
    end)

    local oldIndex
    oldIndex = hookmetamethod(game, "__index", function(self, key)
        if _G.MD_OnIndex then
            local override = _G.MD_OnIndex(self, key)
            if override ~= nil then
                return override
            end
        end
        return oldIndex(self, key)
    end)

    _G.MD_HooksInstalled = true
end

-- ==================== 2. STRICT TARGET & HP VALIDATION ====================
local function isEnemy(plr)
    if plr == LocalPlayer then return false end
    if not teamCheckEnabled then return true end
    if LocalPlayer.Team and plr.Team then
        if LocalPlayer.Team.Name == "Lobby" and plr.Team.Name == "Lobby" then
            return true
        end
        return LocalPlayer.Team ~= plr.Team
    end
    if LocalPlayer.TeamColor and plr.TeamColor then
        return LocalPlayer.TeamColor ~= plr.TeamColor
    end
    return true
end

local function getTargetAimPart(char)
    if not char then return nil end
    if targetPartMode == "Head" then
        return char:FindFirstChild("Head") or char:FindFirstChild("HumanoidRootPart")
    elseif targetPartMode == "Torso" then
        return char:FindFirstChild("Torso") or char:FindFirstChild("UpperTorso") or char:FindFirstChild("HumanoidRootPart")
    else
        return char:FindFirstChild("HumanoidRootPart") or char:FindFirstChild("Torso")
    end
end

local function isTargetAliveAndValid(target)
    if not target then return false end
    local part = target.part
    local char = target.char
    if not part or not part.Parent or not part:IsDescendantOf(workspace) then
        return false
    end
    if part.Transparency > 0.8 then
        return false
    end

    if char then
        if not char:IsDescendantOf(workspace) then return false end
        if char:FindFirstChildOfClass("ForceField") then return false end

        local hum = char:FindFirstChildOfClass("Humanoid")
        if hum then
            if hum.Health <= 0 then return false end
            local state = hum:GetState()
            if state == Enum.HumanoidStateType.Dead then return false end
        end

        if char:GetAttribute("Dead") == true or char:GetAttribute("Invulnerable") == true then
            return false
        end

        local plr = Players:GetPlayerFromCharacter(char)
        if plr then
            if plr.Parent ~= Players then return false end
            if not isEnemy(plr) then return false end
        end
    end

    return true
end

local function isTargetVisible(origin, part, char)
    if wallbangEnabled then return true end
    if not wallCheckEnabled then return true end
    local dir = part.Position - origin
    local dist = dir.Magnitude
    if dist <= 0.5 then return true end

    local rayParams = RaycastParams.new()
    rayParams.FilterType = Enum.RaycastFilterType.Exclude
    rayParams.FilterDescendantsInstances = { workspace.CurrentCamera, LocalPlayer.Character, workspace:FindFirstChild("Bin") }
    rayParams.IgnoreWater = true

    local hit = workspace:Raycast(origin, dir.Unit * dist, rayParams)
    if not hit then
        return true
    end

    local hitInst = hit.Instance
    if hitInst == part or (char and hitInst:IsDescendantOf(char)) then
        return true
    end

    -- Pierce thin transparent glass, destructibles glass, or non-collidable cosmetic parts
    local hitName = hitInst.Name:lower()
    if (hitInst.Material == Enum.Material.Glass and hitInst.Transparency > 0.3) or hitName:find("glass") or (not hitInst.CanCollide and hitInst.Transparency > 0.6) then
        local secondaryOrigin = hit.Position + (dir.Unit * 0.15)
        local remainingDist = (part.Position - secondaryOrigin).Magnitude
        if remainingDist <= 0.5 then return true end

        local hit2 = workspace:Raycast(secondaryOrigin, dir.Unit * remainingDist, rayParams)
        if not hit2 then return true end
        if hit2.Instance == part or (char and hit2.Instance:IsDescendantOf(char)) then
            return true
        end
    end

    return false
end

local sharedRayParams = RaycastParams.new()
sharedRayParams.FilterType = Enum.RaycastFilterType.Exclude
sharedRayParams.IgnoreWater = true

-- Exact Weapon Muzzle / Barrel Position (Where bullets and thrown knives spawn)
local function getWeaponMuzzlePosition()
    local char = LocalPlayer.Character
    if not char then return nil end

    local tool = char:FindFirstChildOfClass("Tool")
    if not tool then
        tool = char:FindFirstChild("Revolver") or char:FindFirstChild("Knife")
    end

    if tool then
        local handle = tool:FindFirstChild("Handle")
        if handle and handle:IsA("BasePart") then
            return (handle.CFrame * CFrame.new(0, 0.2, -1.6)).Position
        end
        local p = tool:FindFirstChildWhichIsA("BasePart")
        if p then
            return (p.CFrame * CFrame.new(0, 0.2, -1.6)).Position
        end
    end

    local rightArm = char:FindFirstChild("Right Arm") or char:FindFirstChild("RightHand")
    if rightArm and rightArm:IsA("BasePart") then
        return (rightArm.CFrame * CFrame.new(0, 0, -1.5)).Position
    end

    local head = char:FindFirstChild("Head")
    return head and head.Position or nil
end

-- Muzzle Clearance Check: Guarantees the revolver barrel/tip has an open line of fire
local function canMuzzleHitTarget(targetPart, targetChar)
    if not targetPart or not targetPart:IsDescendantOf(workspace) then
        return false
    end

    local muzzlePos = getWeaponMuzzlePosition()
    if not muzzlePos then
        return true -- If muzzle position cannot be determined, do not block firing
    end

    local dir = targetPart.Position - muzzlePos
    local dist = dir.Magnitude
    if dist <= 1.0 then
        return true
    end

    sharedRayParams.FilterDescendantsInstances = {
        workspace.CurrentCamera,
        LocalPlayer.Character,
        workspace:FindFirstChild("Bin"),
        workspace:FindFirstChild("RaycastIgnore")
    }

    local hit = workspace:Raycast(muzzlePos, dir.Unit * dist, sharedRayParams)
    if not hit then
        return true
    end

    local hitInst = hit.Instance
    if not hitInst then return true end

    -- Hit target player or part
    if hitInst == targetPart or (targetChar and hitInst:IsDescendantOf(targetChar)) then
        return true
    end

    -- Ignore non-collidable parts (cosmetics, invisible barriers, triggers, hitboxes)
    if not hitInst.CanCollide or hitInst.Transparency > 0.6 then
        return true
    end

    -- Transparent destructibles / glass piercing
    local hitName = hitInst.Name:lower()
    if (hitInst.Material == Enum.Material.Glass and hitInst.Transparency > 0.3) or hitName:find("glass") then
        local secondaryOrigin = hit.Position + (dir.Unit * 0.25)
        local remainingDist = (targetPart.Position - secondaryOrigin).Magnitude
        if remainingDist <= 0.5 then return true end

        local hit2 = workspace:Raycast(secondaryOrigin, dir.Unit * remainingDist, sharedRayParams)
        if not hit2 then return true end
        if hit2.Instance == targetPart or (targetChar and hit2.Instance:IsDescendantOf(targetChar)) or not hit2.Instance.CanCollide then
            return true
        end
    end

    return false
end

local staticLobbyTargets = {}
local function cacheStaticLobbyTargets()
    table.clear(staticLobbyTargets)
    pcall(function()
        local lobby = workspace:FindFirstChild("Lobby")
        if lobby then
            for _, obj in ipairs(lobby:GetDescendants()) do
                if obj:IsA("BasePart") and (obj.Name:lower():find("target") or obj.Name:lower():find("bullseye")) and obj.Transparency < 0.8 then
                    table.insert(staticLobbyTargets, obj)
                end
            end
        end
    end)
end
task.spawn(cacheStaticLobbyTargets)

local function refreshTargetCache()
    local list = {}
    local seenModels = {}
    local myCam = workspace.CurrentCamera
    local myPos = myCam.CFrame.Position

    -- 1. Real Players
    if targetPlayers then
        for _, plr in ipairs(Players:GetPlayers()) do
            if isEnemy(plr) and plr.Character then
                local hum = plr.Character:FindFirstChildOfClass("Humanoid")
                local part = getTargetAimPart(plr.Character)
                if hum and hum.Health > 0 and part and hum:GetState() ~= Enum.HumanoidStateType.Dead then
                    local dist = (part.Position - myPos).Magnitude
                    if dist <= 350 and math.abs(part.Position.Y - myPos.Y) < 150 then
                        seenModels[plr.Character] = true
                        table.insert(list, { part = part, char = plr.Character, name = plr.Name })
                    end
                end
            end
        end
    end

    -- 2. Models in workspace.Characters (Opponents, bots, dummies)
    if workspace:FindFirstChild("Characters") then
        for _, m in ipairs(workspace.Characters:GetChildren()) do
            if m:IsA("Model") and m ~= LocalPlayer.Character and not seenModels[m] then
                local plr = Players:GetPlayerFromCharacter(m)
                local isTarget = false
                if plr then
                    if isEnemy(plr) and targetPlayers then isTarget = true end
                else
                    if targetNoobs then isTarget = true end
                end

                if isTarget then
                    local hum = m:FindFirstChildOfClass("Humanoid")
                    local part = getTargetAimPart(m)
                    if hum and hum.Health > 0 and part and hum:GetState() ~= Enum.HumanoidStateType.Dead then
                        local dist = (part.Position - myPos).Magnitude
                        if dist <= 350 and math.abs(part.Position.Y - myPos.Y) < 150 then
                            seenModels[m] = true
                            table.insert(list, { part = part, char = m, name = plr and plr.Name or m.Name })
                        end
                    end
                end
            end
        end
    end

    -- 3. Targets in Lobby (Pre-cached static targets, zero lag!)
    if targetTargets and #staticLobbyTargets > 0 then
        for _, obj in ipairs(staticLobbyTargets) do
            if obj and obj.Parent and obj:IsDescendantOf(workspace) then
                local dist = (obj.Position - myPos).Magnitude
                if dist <= 250 and math.abs(obj.Position.Y - myPos.Y) < 100 then
                    table.insert(list, { part = obj, char = obj.Parent, name = "Target" })
                end
            end
        end
    end

    cachedTargets = list
    _G.MD_CachedTargets = list
end

pcall(refreshTargetCache)

task.spawn(function()
    while isAlive do
        task.wait(0.3)
        pcall(refreshTargetCache)
    end
end)

local function getBestSilentTarget()
    local best = nil
    local bestScore = math.huge
    local myCam = workspace.CurrentCamera
    local screenCenter = Vector2.new(myCam.ViewportSize.X / 2, myCam.ViewportSize.Y / 2)
    local camPos = myCam.CFrame.Position

    for _, t in ipairs(cachedTargets) do
        if isTargetAliveAndValid(t) then
            local part = t.part
            local screenPos, onScreen = myCam:WorldToViewportPoint(part.Position)
            local dist2D = (Vector2.new(screenPos.X, screenPos.Y) - screenCenter).Magnitude
            local dist3D = (part.Position - camPos).Magnitude

            if onScreen and dist2D <= fovRadius and dist3D <= 350 then
                if isTargetVisible(camPos, part, t.char) then
                    if dist2D < bestScore then
                        bestScore = dist2D
                        best = { part = part, char = t.char, dist3D = dist3D, name = t.name }
                    end
                end
            end
        end
    end
    return best
end

local function getBestLegitTarget()
    local best = nil
    local bestDist2D = math.huge
    local myCam = workspace.CurrentCamera
    local screenCenter = Vector2.new(myCam.ViewportSize.X / 2, myCam.ViewportSize.Y / 2)
    local camPos = myCam.CFrame.Position

    for _, t in ipairs(cachedTargets) do
        if isTargetAliveAndValid(t) then
            local part = t.part
            if legitHitbox == "Head" and t.char then
                part = t.char:FindFirstChild("Head") or t.part
            elseif legitHitbox == "Torso" and t.char then
                part = t.char:FindFirstChild("Torso") or t.char:FindFirstChild("UpperTorso") or t.part
            end
            local screenPos, onScreen = myCam:WorldToViewportPoint(part.Position)
            if onScreen then
                local dist2D = (Vector2.new(screenPos.X, screenPos.Y) - screenCenter).Magnitude
                local dist3D = (part.Position - camPos).Magnitude
                if dist2D <= legitFovRadius and dist3D <= 350 then
                    if not legitWallCheck or isTargetVisible(camPos, part, t.char) then
                        if dist2D < bestDist2D then
                            bestDist2D = dist2D
                            best = { part = part, char = t.char, screenPos = screenPos }
                        end
                    end
                end
            end
        end
    end
    return best
end

getAnyEnemyTarget = function()
    local myChar = LocalPlayer.Character
    local myHRP = myChar and (myChar:FindFirstChild("HumanoidRootPart") or myChar:FindFirstChild("Torso"))
    if not myHRP then return nil end
    local myPos = myHRP.Position
    local mySide = LocalPlayer:GetAttribute("MatchSide")

    local best = nil
    local bestDist = math.huge

    local function checkModel(m)
        if not m or not m:IsA("Model") or m == myChar then return end
        if m:FindFirstChildOfClass("ForceField") then return end
        local hum = m:FindFirstChildOfClass("Humanoid")
        if not hum or hum.Health <= 0 or hum:GetState() == Enum.HumanoidStateType.Dead then return end
        local hrp = m:FindFirstChild("HumanoidRootPart") or m:FindFirstChild("Torso") or m:FindFirstChild("UpperTorso")
        if not hrp then return end

        local plr = Players:GetPlayerFromCharacter(m)
        if plr then
            if not isEnemy(plr) then return end
        else
            if mySide and m:GetAttribute("MatchSide") == mySide then return end
            if not targetNoobs and m.Name == "Noob" then return end
        end

        local aimPart = getTargetAimPart(m) or hrp
        local dist = (hrp.Position - myPos).Magnitude
        if dist < bestDist then
            bestDist = dist
            best = {
                char = m,
                hrp = hrp,
                part = aimPart,
                player = plr,
                dist = dist
            }
        end
    end

    for _, plr in ipairs(Players:GetPlayers()) do
        if plr ~= LocalPlayer and isEnemy(plr) and plr.Character then
            checkModel(plr.Character)
        end
    end

    if workspace:FindFirstChild("Characters") then
        for _, m in ipairs(workspace.Characters:GetChildren()) do
            checkModel(m)
        end
    end

    return best
end

local function executeAutoWin()
    if isAutoWinExecuting then return end
    local myChar = LocalPlayer.Character
    if not myChar then return end
    local myHRP = myChar:FindFirstChild("HumanoidRootPart") or myChar:FindFirstChild("Torso")
    local myHum = myChar:FindFirstChildOfClass("Humanoid")
    if not myHRP or not myHum or myHum.Health <= 0 then return end

    local target = getAnyEnemyTarget()
    if not target or not target.hrp or not target.char then return end

    isAutoWinExecuting = true

    local bp = LocalPlayer:FindFirstChild("Backpack")
    local currentTool = myChar:FindFirstChildOfClass("Tool")
    local currentToolName = currentTool and currentTool.Name:lower() or ""
    local knifeInBp = bp and bp:FindFirstChild("Knife")
    local revInBp = bp and bp:FindFirstChild("Revolver")
    local hasKnife = currentToolName:find("knife") ~= nil or knifeInBp ~= nil

    if autoWinEquip then
        if autoWinMode == "TP Backstab" and knifeInBp and currentToolName:find("knife") == nil then
            myHum:EquipTool(knifeInBp)
            task.wait(0.04)
        elseif autoWinMode == "360° Auto-Throw" then
            if not currentTool then
                local tToEquip = knifeInBp or revInBp
                if tToEquip then
                    myHum:EquipTool(tToEquip)
                    task.wait(0.04)
                end
            end
        end
    end

    currentTool = myChar:FindFirstChildOfClass("Tool")
    currentToolName = currentTool and currentTool.Name:lower() or ""

    if autoWinMode == "TP Backstab" and hasKnife then
        local originalCFrame = myHRP.CFrame
        local targetHRP = target.hrp
        local targetChar = target.char
        local targetPlr = target.player

        local targetLook = targetHRP.CFrame.LookVector
        local behindPos = targetHRP.Position - (targetLook * 1.5)
        myHRP.CFrame = CFrame.lookAt(behindPos, targetHRP.Position)
        myHRP.AssemblyLinearVelocity = Vector3.zero

        local im = nil
        pcall(function()
            im = require(game:GetService("ReplicatedStorage"):WaitForChild("Extensions"):WaitForChild("InputMap"))
        end)
        if im and im.tap then
            im.tap("Attack")
        else
            pcall(mouse1click)
        end

        pcall(function()
            local Remotes = game:GetService("ReplicatedStorage"):FindFirstChild("Remotes")
            local ReportHit = Remotes and Remotes:FindFirstChild("ReportHit")
            if ReportHit then
                ReportHit:FireServer({
                    kind = "melee",
                    targetUserId = targetPlr and targetPlr.UserId or 0,
                    targetModel = targetChar,
                    direction = myHRP.CFrame.LookVector,
                    at = workspace:GetServerTimeNow(),
                    backstab = true
                })
            end
        end)

        if autoWinReturn then
            task.delay(0.06, function()
                if myHRP and myHRP.Parent and originalCFrame then
                    myHRP.CFrame = originalCFrame
                    myHRP.AssemblyLinearVelocity = Vector3.zero
                end
                task.delay(0.1, function()
                    isAutoWinExecuting = false
                end)
            end)
        else
            task.delay(0.15, function()
                isAutoWinExecuting = false
            end)
        end

    else
        _G.MD_SilentAimTarget = target.part or target.hrp
        _G.MD_SilentAimEnabled = true
        _G.MD_WallbangEnabled = true

        fireWeapon()
        task.delay(0.25, function()
            isAutoWinExecuting = false
        end)
    end
end

-- ==================== 3. RENDERSTEPPED LOOP ====================
table.insert(Connections, RunService.RenderStepped:Connect(function()
    local myCam = workspace.CurrentCamera
    local screenCenter = Vector2.new(myCam.ViewportSize.X / 2, myCam.ViewportSize.Y / 2)
    if fovCircle then
        fovCircle.Position = screenCenter
        fovCircle.Radius = fovRadius
        fovCircle.Visible = silentAimEnabled and showFovCircle
    end

    local isAimActive = silentAimEnabled
    if isAimActive and silentAimMode == "HoldKey" then
        if Options.SilentAimKey and not Options.SilentAimKey:GetState() then
            isAimActive = false
        end
    end

    if isAimActive then
        local best = getBestSilentTarget()
        silentAimTargetPart = best and best.part or nil
        silentAimTargetChar = best and best.char or nil
    else
        silentAimTargetPart = nil
        silentAimTargetChar = nil
    end

    _G.MD_SilentAimEnabled = isAimActive and (silentAimTargetPart ~= nil)
    _G.MD_SilentAimTarget = silentAimTargetPart
    _G.MD_WallbangEnabled = wallbangEnabled
    _G.MD_KnifeSpeed = knifeSpeed

    local myChar = LocalPlayer.Character
    local activeTool = myChar and myChar:FindFirstChildOfClass("Tool")
    local tName = activeTool and activeTool.Name:lower() or ""
    local isKnife = (tName:find("knife") ~= nil)
    _G.MD_CurrentWeaponIsKnife = isKnife

    -- Viewmodel & Weapon Scale Execution
    if myChar then
        local torso = myChar:FindFirstChild("Torso")
        local rightArm = myChar:FindFirstChild("Right Arm") or myChar:FindFirstChild("RightHand")
        local leftArm = myChar:FindFirstChild("Left Arm") or myChar:FindFirstChild("LeftHand")
        local rs = torso and torso:FindFirstChild("Right Shoulder")
        local attach = rightArm and (rightArm:FindFirstChild("Knife_HandAttach") or rightArm:FindFirstChild("Revolver_HandAttach"))

        -- 1. Hide Arms
        if hideArmsEnabled then
            if rightArm then rightArm.LocalTransparencyModifier = 1 end
            if leftArm then leftArm.LocalTransparencyModifier = 1 end
        else
            if rightArm and rightArm.LocalTransparencyModifier == 1 then rightArm.LocalTransparencyModifier = 0 end
            if leftArm and leftArm.LocalTransparencyModifier == 1 then leftArm.LocalTransparencyModifier = 0 end
        end

        -- 2. Viewmodel Offset
        if viewmodelEnabled then
            local offsetCF = CFrame.new(vm.x, vm.y, vm.z) * CFrame.Angles(math.rad(vm.pitch), math.rad(vm.yaw), math.rad(vm.roll))
            if vmTargetMode == "ArmAndWeapon" then
                if rs and rs:IsA("Motor6D") then
                    local targetRSC1 = offsetCF:Inverse() * defaultRSC1
                    if rs.C1 ~= targetRSC1 then
                        rs.C1 = targetRSC1
                    end
                end
                if attach and attach:IsA("Motor6D") and attach.C1 ~= CFrame.identity then
                    attach.C1 = CFrame.identity
                end
            else
                if rs and rs:IsA("Motor6D") and rs.C1 ~= defaultRSC1 then
                    rs.C1 = defaultRSC1
                end
                if attach and attach:IsA("Motor6D") and attach.C1 ~= offsetCF then
                    attach.C1 = offsetCF
                end
            end
        else
            if rs and rs:IsA("Motor6D") and rs.C1 ~= defaultRSC1 then
                rs.C1 = defaultRSC1
            end
            if attach and attach:IsA("Motor6D") and attach.C1 ~= CFrame.identity then
                attach.C1 = CFrame.identity
            end
        end

        -- 3. Weapon Scale
        local targetScale = (weaponScaleEnabled and weaponScale) or 1.0
        local knifeRig = myChar:FindFirstChild("KnifeRig")
        if knifeRig and knifeRig:IsA("Model") then
            if math.abs(knifeRig:GetScale() - targetScale) > 0.01 then
                pcall(function() knifeRig:ScaleTo(targetScale) end)
            end
        end
        local revRig = myChar:FindFirstChild("RevolverRig")
        if revRig and revRig:IsA("Model") then
            if math.abs(revRig:GetScale() - targetScale) > 0.01 then
                pcall(function() revRig:ScaleTo(targetScale) end)
            end
        end
    end

    -- Silent Auto-Fire (Triggerbot: Fires automatically WITHOUT camera snapping)
    if silentAutoFire and isAimActive and silentAimTargetPart then
        local now = tick()
        local fireDelay = isKnife and math.max(silentAutoFireDelay, knifeHoldDuration + 0.12) or silentAutoFireDelay
        if (now - lastSilentFireTime >= fireDelay) then
            -- Muzzle clearance check: skip when wallbang is on (we spoof origin anyway)
            if wallbangEnabled or isKnife or not muzzleCheckEnabled or canMuzzleHitTarget(silentAimTargetPart, silentAimTargetChar) then
                local char = LocalPlayer.Character
                local tool = char and char:FindFirstChildOfClass("Tool")
                if not tool then
                    local bp = LocalPlayer:FindFirstChild("Backpack")
                    local rev = bp and (bp:FindFirstChild("Revolver") or bp:FindFirstChild("Knife"))
                    local hum = char and char:FindFirstChildOfClass("Humanoid")
                    if rev and hum then
                        hum:EquipTool(rev)
                    end
                end

                lastSilentFireTime = now
                fireWeapon()
            end
        end
    end

    -- Auto-Win / Kill Aura Execution
    local isAutoWinKeyActive = Options.AutoWinKey and Options.AutoWinKey:GetState()
    if (autoWinEnabled or isAutoWinKeyActive) and not isAutoWinExecuting then
        local now = tick()
        if (now - lastAutoWinTime >= autoWinDelay) then
            lastAutoWinTime = now
            task.spawn(executeAutoWin)
        end
    end

    -- Legit FOV Circle
    if legitFovCircle then
        legitFovCircle.Position = screenCenter
        legitFovCircle.Radius = legitFovRadius
        legitFovCircle.Visible = legitAimEnabled and legitShowFov and (not isMenuOpen)
    end

    -- Legit Aimbot Execution (Smooth Camera Aim)
    local isLegitActive = legitAimEnabled
    if isLegitActive and legitAimMode == "HoldKey" then
        if Options.LegitAimKey and not Options.LegitAimKey:GetState() then
            isLegitActive = false
        end
    end

    if isLegitActive then
        local legitTarget = getBestLegitTarget()
        if legitTarget and legitTarget.part then
            local targetPos = legitTarget.part.Position
            local currentCF = myCam.CFrame
            local targetCF = CFrame.lookAt(currentCF.Position, targetPos)
            local factor = math.clamp(1 / math.max(legitSmoothness, 1), 0.04, 0.45)
            myCam.CFrame = currentCF:Lerp(targetCF, factor)
        end
    end

    -- Legit Triggerbot Execution (Humanized Reaction Time on Direct Crosshair Aim)
    local isLegitTriggerActive = legitTriggerEnabled
    if isLegitTriggerActive and Options.LegitTriggerKey then
        if not Options.LegitTriggerKey:GetState() then
            isLegitTriggerActive = false
        end
    end

    if isLegitTriggerActive then
        local ray = myCam:ViewportPointToRay(screenCenter.X, screenCenter.Y)
        local rayParams = RaycastParams.new()
        rayParams.FilterType = Enum.RaycastFilterType.Exclude
        rayParams.FilterDescendantsInstances = { myCam, LocalPlayer.Character, workspace:FindFirstChild("Bin") }
        local hit = workspace:Raycast(ray.Origin, ray.Direction * 350, rayParams)
        local isEnemyAimed = false

        if hit and hit.Instance then
            local hitChar = hit.Instance.Parent
            if hitChar and hitChar:IsA("Accessory") then
                hitChar = hitChar.Parent
            end
            if hitChar and hitChar:FindFirstChildOfClass("Humanoid") then
                local plr = Players:GetPlayerFromCharacter(hitChar)
                if plr then
                    if not legitTriggerTeamCheck or isEnemy(plr) then
                        isEnemyAimed = true
                    end
                elseif targetNoobs then
                    isEnemyAimed = true
                end
            end
        end

        if isEnemyAimed then
            if legitTriggerStartTime == 0 then
                legitTriggerStartTime = tick()
            elseif (tick() - legitTriggerStartTime) >= (legitTriggerDelay or 0.16) then
                local now = tick()
                if (now - lastLegitTriggerFireTime >= 0.25) then
                    lastLegitTriggerFireTime = now
                    fireWeapon()
                end
            end
        else
            legitTriggerStartTime = 0
        end
    else
        legitTriggerStartTime = 0
    end

    -- Auto-Peek Execution (Peek Assist)
    if autoPeekEnabled and Options.AutoPeekKey then
        local isKeyHeld = Options.AutoPeekKey:GetState()
        local char = LocalPlayer.Character
        local hrp = char and char:FindFirstChild("HumanoidRootPart")

        if isKeyHeld and hrp then
            if not autoPeekAnchor then
                autoPeekAnchor = hrp.Position
                autoPeekState = "RECORDED"
                updateAutoPeekVisual()
            else
                local dist = (hrp.Position - autoPeekAnchor).Magnitude
                if autoPeekState == "RECORDED" and dist > 2 then
                    autoPeekState = "PEEKING"
                end

                if autoPeekState == "RETURNING" then
                    local cur = hrp.Position
                    local target = Vector3.new(autoPeekAnchor.X, cur.Y, autoPeekAnchor.Z)
                    local diff = target - cur
                    if diff.Magnitude > 1.2 then
                        local step = math.min(diff.Magnitude, autoPeekReturnSpeed)
                        hrp.CFrame = CFrame.new(cur + diff.Unit * step) * (hrp.CFrame - hrp.CFrame.Position)
                        hrp.AssemblyLinearVelocity = Vector3.zero
                    else
                        hrp.CFrame = CFrame.new(target) * (hrp.CFrame - hrp.CFrame.Position)
                        hrp.AssemblyLinearVelocity = Vector3.zero
                        autoPeekState = "RECORDED"
                    end
                end
            end
        else
            if autoPeekAnchor then
                autoPeekAnchor = nil
                autoPeekState = "IDLE"
                updateAutoPeekVisual()
            end
        end
    elseif autoPeekAnchor then
        autoPeekAnchor = nil
        autoPeekState = "IDLE"
        updateAutoPeekVisual()
    end

    -- 1. Silent Aim Target Line
    if targetLine then
        if targetLineEnabled and _G.MD_SilentAimEnabled and _G.MD_SilentAimTarget then
            local tPos, onScreen = myCam:WorldToViewportPoint(_G.MD_SilentAimTarget.Position)
            if onScreen then
                targetLine.From = screenCenter
                targetLine.To = Vector2.new(tPos.X, tPos.Y)
                targetLine.Color = targetLineColor
                targetLine.Visible = true
            else
                targetLine.Visible = false
            end
        else
            targetLine.Visible = false
        end
    end

    -- 2. Custom CS Crosshair
    if crosshairLines.h1 then
        if customCrosshairEnabled then
            local cx, cy = screenCenter.X, screenCenter.Y
            local g, s = crosshairGap, crosshairSize
            local col = crosshairColor
            local th = crosshairThickness

            crosshairLines.h1.From = Vector2.new(cx - g - s, cy)
            crosshairLines.h1.To = Vector2.new(cx - g, cy)
            crosshairLines.h1.Color = col
            crosshairLines.h1.Thickness = th
            crosshairLines.h1.Visible = true

            crosshairLines.h2.From = Vector2.new(cx + g, cy)
            crosshairLines.h2.To = Vector2.new(cx + g + s, cy)
            crosshairLines.h2.Color = col
            crosshairLines.h2.Thickness = th
            crosshairLines.h2.Visible = true

            crosshairLines.v1.From = Vector2.new(cx, cy - g - s)
            crosshairLines.v1.To = Vector2.new(cx, cy - g)
            crosshairLines.v1.Color = col
            crosshairLines.v1.Thickness = th
            crosshairLines.v1.Visible = true

            crosshairLines.v2.From = Vector2.new(cx, cy + g)
            crosshairLines.v2.To = Vector2.new(cx, cy + g + s)
            crosshairLines.v2.Color = col
            crosshairLines.v2.Thickness = th
            crosshairLines.v2.Visible = true

            crosshairLines.dot.Position = screenCenter
            crosshairLines.dot.Color = col
            crosshairLines.dot.Radius = th
            crosshairLines.dot.Visible = crosshairDotEnabled
        else
            for _, l in pairs(crosshairLines) do
                l.Visible = false
            end
        end
    end

    -- 3. 2D Visuals: Box ESP, Snaplines, Head Dots
    local activeDrawModels = {}
    if boxEspEnabled or snaplinesEnabled or headDotsEnabled then
        for _, t in ipairs(cachedTargets) do
            if isTargetAliveAndValid(t) then
                local char = t.char
                local head = char and (char:FindFirstChild("Head") or t.part)
                local root = char and (char:FindFirstChild("HumanoidRootPart") or char:FindFirstChild("Torso") or t.part)
                if head and root and head:IsDescendantOf(workspace) then
                    activeDrawModels[char] = true
                    if not drawingCache[char] then
                        local box = Drawing.new("Square")
                        box.Thickness = 1.5
                        box.Filled = false
                        box.Visible = false

                        local line = Drawing.new("Line")
                        line.Thickness = 1
                        line.Visible = false

                        local dot = Drawing.new("Circle")
                        dot.Radius = 3.5
                        dot.Filled = true
                        dot.Visible = false

                        drawingCache[char] = { box = box, line = line, dot = dot }
                    end

                    local d = drawingCache[char]
                    local headPos, onHead = myCam:WorldToViewportPoint(head.Position + Vector3.new(0, 0.6, 0))
                    local rootPos, onRoot = myCam:WorldToViewportPoint(root.Position - Vector3.new(0, 2.8, 0))

                    if onHead or onRoot then
                        local topY = headPos.Y
                        local botY = rootPos.Y
                        local h = math.abs(botY - topY)
                        local w = math.max(h * 0.65, 12)

                        -- 2D Box
                        if boxEspEnabled then
                            d.box.Size = Vector2.new(w, h)
                            d.box.Position = Vector2.new(rootPos.X - w / 2, math.min(topY, botY))
                            d.box.Color = boxColor
                            d.box.Visible = true
                        else
                            d.box.Visible = false
                        end

                        -- Snaplines / Tracers
                        if snaplinesEnabled then
                            local startPos = (snaplinesOrigin == "Bottom") and Vector2.new(myCam.ViewportSize.X / 2, myCam.ViewportSize.Y) or screenCenter
                            d.line.From = startPos
                            d.line.To = Vector2.new(rootPos.X, math.max(topY, botY))
                            d.line.Color = snaplinesColor
                            d.line.Visible = true
                        else
                            d.line.Visible = false
                        end

                        -- Head Dot
                        if headDotsEnabled and onHead then
                            d.dot.Position = Vector2.new(headPos.X, headPos.Y + 0.6 * (h / 30))
                            d.dot.Color = headDotsColor
                            d.dot.Visible = true
                        else
                            d.dot.Visible = false
                        end
                    else
                        d.box.Visible = false
                        d.line.Visible = false
                        d.dot.Visible = false
                    end
                end
            end
        end
    end

    -- Hide or cleanup Drawing objects (Reuses instances, zero allocation overhead)
    for m, d in pairs(drawingCache) do
        if not activeDrawModels[m] then
            d.box.Visible = false
            d.line.Visible = false
            d.dot.Visible = false
            if not m.Parent or not m:IsDescendantOf(workspace) then
                pcall(function() d.box:Remove() end)
                pcall(function() d.line:Remove() end)
                pcall(function() d.dot:Remove() end)
                drawingCache[m] = nil
            end
        end
    end
end))

-- ==================== 4. ANTI-AIM LOGIC ====================
local function getCharParts()
    local char = LocalPlayer.Character
    if not char then return nil end
    local root = char:FindFirstChild("HumanoidRootPart")
    local hum = char:FindFirstChildOfClass("Humanoid")
    local rj = root and root:FindFirstChild("RootJoint")
    return char, root, hum, rj
end

local function resetAntiAim()
    local _, root, hum, rj = getCharParts()
    if hum then hum.AutoRotate = true end
    if rj then rj.C0 = defaultRjC0 end
end

table.insert(Connections, RunService.Heartbeat:Connect(function(dt)
    if not aaEnabled then return end
    local _, root, hum, rj = getCharParts()
    if not root or not hum or hum.Health <= 0 then return end

    hum.AutoRotate = false
    local camLook = workspace.CurrentCamera.CFrame.LookVector
    local baseAngle = math.atan2(-camLook.X, -camLook.Z)

    if aaYawMode == "Spinbot" then
        currentYaw = (currentYaw + spinSpeed * dt) % (math.pi * 2)
    elseif aaYawMode == "Jitter (180 Flip)" then
        local flip = (tick() % 0.1 > 0.05)
        currentYaw = baseAngle + (flip and 0 or math.pi)
    elseif aaYawMode == "Jitter (Custom Angle)" then
        local flip = (tick() % 0.12 > 0.06)
        currentYaw = baseAngle + math.rad(flip and jitterAngle or -jitterAngle)
    elseif aaYawMode == "Random Jitter" then
        currentYaw = math.rad(math.random(-180, 180))
    elseif aaYawMode == "Backward (180)" then
        currentYaw = baseAngle + math.pi
    elseif aaYawMode == "Sideways (90)" then
        currentYaw = baseAngle + math.rad(90)
    elseif aaYawMode == "Sway (Sinusoid)" then
        currentYaw = baseAngle + math.sin(tick() * swayFreq) * math.rad(swayAngle)
    end

    local preservedVelocity = root.AssemblyLinearVelocity
    root.CFrame = CFrame.new(root.Position) * CFrame.Angles(0, currentYaw, 0)
    root.AssemblyLinearVelocity = preservedVelocity

    if rj then
        if aaPitchMode == "Down (Head Roll)" then
            rj.C0 = defaultRjC0 * CFrame.Angles(math.rad(pitchAngle), 0, 0)
        elseif aaPitchMode == "Up (Sky)" then
            rj.C0 = defaultRjC0 * CFrame.Angles(math.rad(-pitchAngle), 0, 0)
        elseif aaPitchMode == "Jitter Pitch" then
            local flipP = (tick() % 0.1 > 0.05)
            rj.C0 = defaultRjC0 * CFrame.Angles(math.rad(flipP and pitchAngle or -pitchAngle), 0, 0)
        elseif aaPitchMode == "Zero" then
            rj.C0 = defaultRjC0
        end
    end
end))

-- ==================== 5. MOVEMENT: BHOP & STRAFES ====================
table.insert(Connections, RunService.Heartbeat:Connect(function()
    local char = LocalPlayer.Character
    local hum = char and char:FindFirstChildOfClass("Humanoid")
    local root = char and char:FindFirstChild("HumanoidRootPart")
    if not hum or not root or hum.Health <= 0 then return end

    local isSpaceDown = UserInputService:IsKeyDown(Enum.KeyCode.Space)
    local onGround = (hum.FloorMaterial ~= Enum.Material.Air)
    local moveDir = hum.MoveDirection

    -- 1. Auto-Bhop без задержки приземления
    if bhopEnabled and isSpaceDown and onGround then
        hum:ChangeState(Enum.HumanoidStateType.Jumping)
    end

    -- 2. Air Strafes: Мгновенная смена направления без КД и задержки (W/A/S/D)
    if bhopEnabled and instantStrafes and moveDir.Magnitude > 0 then
        local currentVel = root.AssemblyLinearVelocity
        local speed = math.max(hum.WalkSpeed, bhopSpeed)
        root.AssemblyLinearVelocity = Vector3.new(moveDir.X * speed, currentVel.Y, moveDir.Z * speed)
    end
end))

table.insert(Connections, UserInputService.JumpRequest:Connect(function()
    if infiniteJump then
        local hum = LocalPlayer.Character and LocalPlayer.Character:FindFirstChildOfClass("Humanoid")
        if hum and hum.Health > 0 then
            hum:ChangeState(Enum.HumanoidStateType.Jumping)
        end
    end
end))

-- ==================== 6. PERFECT NATIVE 3RD PERSON ====================
local function applyNativeCamera()
    if NativeTP then
        NativeTP.Distance = cameraDistance
        NativeTP.Shoulder = shoulderOffset
        NativeTP.Height = heightOffset
        NativeTP.SetEnabled(thirdPersonEnabled)
    end
    if PlayerState then
        PlayerState.CameraFirstPerson = not thirdPersonEnabled
    end
    workspace.CurrentCamera.FieldOfView = customFOV

    local char = LocalPlayer.Character
    if char and thirdPersonEnabled then
        for _, p in ipairs(char:GetDescendants()) do
            if p:IsA("BasePart") and p.Name ~= "HumanoidRootPart" and p.Name ~= "BoundingBox" then
                p.LocalTransparencyModifier = 0
            end
        end
    end
end

table.insert(Connections, RunService.RenderStepped:Connect(function()
    if thirdPersonEnabled then
        if NativeTP and not NativeTP.IsEnabled() then
            NativeTP.SetEnabled(true)
        end
        if PlayerState and PlayerState.CameraFirstPerson ~= false then
            PlayerState.CameraFirstPerson = false
        end
        local char = LocalPlayer.Character
        if char then
            for _, p in ipairs(char:GetChildren()) do
                if p:IsA("BasePart") and p.Name ~= "HumanoidRootPart" and p.LocalTransparencyModifier > 0.1 then
                    p.LocalTransparencyModifier = 0
                end
            end
        end
    end
end))

-- ==================== 7. VISUALS: ADVANCED ESP ====================
local function removeEspForModel(model)
    local data = espCache[model]
    if data then
        if data.highlight then pcall(function() data.highlight:Destroy() end) end
        if data.billboard then pcall(function() data.billboard:Destroy() end) end
        espCache[model] = nil
    end
end

local function clearAllEsp()
    for model, _ in pairs(espCache) do
        removeEspForModel(model)
    end
    for _, d in pairs(drawingCache) do
        pcall(function() d.box:Remove() end)
        pcall(function() d.line:Remove() end)
        pcall(function() d.dot:Remove() end)
    end
    drawingCache = {}
end

local function getWeaponName(char)
    local tool = char:FindFirstChildOfClass("Tool")
    if tool then
        return tool.Name
    end
    return nil
end

local function createEspForModel(model, isBot, displayName)
    if espCache[model] then return end
    local head = model:FindFirstChild("Head") or model:FindFirstChild("HumanoidRootPart")
    if not head then return end

    -- 1. Highlight (Chams)
    local hl = Instance.new("Highlight")
    hl.Name = "ESP_Highlight"
    hl.Adornee = model
    hl.FillColor = espFillColor
    hl.FillTransparency = espFillTransparency
    hl.OutlineColor = espOutlineColor
    hl.OutlineTransparency = espOutlineTransparency
    hl.DepthMode = Enum.HighlightDepthMode.AlwaysOnTop
    hl.Enabled = espEnabled
    pcall(function() hl.Parent = model end)
    if not hl.Parent then
        hl.Parent = game:GetService("CoreGui")
    end

    -- 2. BillboardGui (Name, Distance, Health, Weapon)
    local bb = Instance.new("BillboardGui")
    bb.Name = "ESP_Billboard"
    bb.Adornee = head
    bb.AlwaysOnTop = true
    bb.Size = UDim2.new(0, 160, 0, 52)
    bb.StudsOffset = Vector3.new(0, 3.2, 0)
    bb.Enabled = espEnabled
    bb.Parent = game:GetService("CoreGui")

    local container = Instance.new("Frame", bb)
    container.Size = UDim2.new(1, 0, 1, 0)
    container.BackgroundTransparency = 1

    local nameLabel = Instance.new("TextLabel", container)
    nameLabel.Name = "NameLabel"
    nameLabel.Size = UDim2.new(1, 0, 0, 16)
    nameLabel.Position = UDim2.new(0, 0, 0, 0)
    nameLabel.BackgroundTransparency = 1
    nameLabel.TextColor3 = Color3.fromRGB(255, 255, 255)
    nameLabel.TextStrokeColor3 = Color3.fromRGB(0, 0, 0)
    nameLabel.TextStrokeTransparency = 0.2
    nameLabel.TextSize = 13
    nameLabel.Font = Enum.Font.GothamBold
    nameLabel.Text = displayName or model.Name

    local healthBg = Instance.new("Frame", container)
    healthBg.Name = "HealthBg"
    healthBg.Size = UDim2.new(0, 90, 0, 4)
    healthBg.Position = UDim2.new(0.5, -45, 0, 18)
    healthBg.BackgroundColor3 = Color3.fromRGB(30, 30, 30)
    healthBg.BorderSizePixel = 0
    healthBg.Visible = espShowHealth

    local healthFill = Instance.new("Frame", healthBg)
    healthFill.Name = "HealthFill"
    healthFill.Size = UDim2.new(1, 0, 1, 0)
    healthFill.BackgroundColor3 = Color3.fromRGB(46, 204, 113)
    healthFill.BorderSizePixel = 0

    local weaponLabel = Instance.new("TextLabel", container)
    weaponLabel.Name = "WeaponLabel"
    weaponLabel.Size = UDim2.new(1, 0, 0, 14)
    weaponLabel.Position = UDim2.new(0, 0, 0, 24)
    weaponLabel.BackgroundTransparency = 1
    weaponLabel.TextColor3 = Color3.fromRGB(241, 196, 15)
    weaponLabel.TextStrokeColor3 = Color3.fromRGB(0, 0, 0)
    weaponLabel.TextStrokeTransparency = 0.3
    weaponLabel.TextSize = 11
    weaponLabel.Font = Enum.Font.GothamMedium
    weaponLabel.Text = ""
    weaponLabel.Visible = espShowWeapon

    espCache[model] = {
        highlight = hl,
        billboard = bb,
        nameLabel = nameLabel,
        healthBg = healthBg,
        healthFill = healthFill,
        weaponLabel = weaponLabel,
        isBot = isBot,
        displayName = displayName or model.Name
    }
end

local function updateEsp()
    if not espEnabled then
        for _, data in pairs(espCache) do
            if data.highlight then data.highlight.Enabled = false end
            if data.billboard then data.billboard.Enabled = false end
        end
        return
    end

    local camPos = workspace.CurrentCamera.CFrame.Position
    local activeModels = {}

    -- 1. Scan Players
    for _, plr in ipairs(Players:GetPlayers()) do
        if plr ~= LocalPlayer and plr.Character then
            local char = plr.Character
            local hum = char:FindFirstChildOfClass("Humanoid")
            local head = char:FindFirstChild("Head") or char:FindFirstChild("HumanoidRootPart")
            if hum and hum.Health > 0 and head and head:IsDescendantOf(workspace) and hum:GetState() ~= Enum.HumanoidStateType.Dead then
                activeModels[char] = true
                if not espCache[char] then
                    createEspForModel(char, false, plr.DisplayName or plr.Name)
                end
                local data = espCache[char]
                if data then
                    data.highlight.Enabled = true
                    data.billboard.Enabled = true
                    data.highlight.FillColor = espFillColor
                    data.highlight.FillTransparency = espFillTransparency
                    data.highlight.OutlineColor = espOutlineColor
                    data.highlight.OutlineTransparency = espOutlineTransparency

                    local dist = math.floor((head.Position - camPos).Magnitude)
                    if espShowDistance then
                        data.nameLabel.Text = string.format("%s [%dm]", data.displayName, dist)
                    else
                        data.nameLabel.Text = data.displayName
                    end
                    data.nameLabel.Visible = espShowNames

                    local hpPercent = math.clamp(hum.Health / math.max(hum.MaxHealth, 1), 0, 1)
                    data.healthFill.Size = UDim2.new(hpPercent, 0, 1, 0)
                    if hpPercent > 0.5 then
                        data.healthFill.BackgroundColor3 = Color3.fromRGB(46, 204, 113)
                    elseif hpPercent > 0.25 then
                        data.healthFill.BackgroundColor3 = Color3.fromRGB(241, 196, 15)
                    else
                        data.healthFill.BackgroundColor3 = Color3.fromRGB(231, 76, 60)
                    end
                    data.healthBg.Visible = espShowHealth

                    local weapon = getWeaponName(char)
                    if weapon then
                        data.weaponLabel.Text = "[" .. weapon .. "]"
                        if weapon:find("Revolver") or weapon:find("Gun") then
                            data.weaponLabel.TextColor3 = Color3.fromRGB(230, 126, 34)
                        else
                            data.weaponLabel.TextColor3 = Color3.fromRGB(52, 152, 219)
                        end
                        data.weaponLabel.Visible = espShowWeapon
                    else
                        data.weaponLabel.Visible = false
                    end
                end
            end
        end
    end

    -- 2. Scan Bots / Dummies in workspace.Characters
    if espTargetBots and workspace:FindFirstChild("Characters") then
        for _, m in ipairs(workspace.Characters:GetChildren()) do
            if m:IsA("Model") and m ~= LocalPlayer.Character then
                local hum = m:FindFirstChildOfClass("Humanoid")
                local head = m:FindFirstChild("Head") or m:FindFirstChild("HumanoidRootPart")
                if hum and hum.Health > 0 and head and head:IsDescendantOf(workspace) and hum:GetState() ~= Enum.HumanoidStateType.Dead then
                    activeModels[m] = true
                    if not espCache[m] then
                        createEspForModel(m, true, m.Name)
                    end
                    local data = espCache[m]
                    if data then
                        data.highlight.Enabled = true
                        data.billboard.Enabled = true
                        data.highlight.FillColor = espFillColor
                        data.highlight.FillTransparency = espFillTransparency
                        data.highlight.OutlineColor = espOutlineColor
                        data.highlight.OutlineTransparency = espOutlineTransparency

                        local dist = math.floor((head.Position - camPos).Magnitude)
                        if espShowDistance then
                            data.nameLabel.Text = string.format("%s [%dm]", m.Name, dist)
                        else
                            data.nameLabel.Text = m.Name
                        end
                        data.nameLabel.Visible = espShowNames

                        local hpPercent = math.clamp(hum.Health / math.max(hum.MaxHealth, 1), 0, 1)
                        data.healthFill.Size = UDim2.new(hpPercent, 0, 1, 0)
                        data.healthBg.Visible = espShowHealth

                        local weapon = getWeaponName(m)
                        if weapon then
                            data.weaponLabel.Text = "[" .. weapon .. "]"
                            data.weaponLabel.Visible = espShowWeapon
                        else
                            data.weaponLabel.Visible = false
                        end
                    end
                end
            end
        end
    end

    -- 3. Cleanup dead or despawned models
    for m, _ in pairs(espCache) do
        if not activeModels[m] then
            removeEspForModel(m)
        end
    end
end

task.spawn(function()
    while isAlive do
        task.wait(0.12)
        pcall(updateEsp)
    end
end)

-- ==================== 8. UI BUILDER WITH LOCALIZATION ====================
local buildMenu

buildMenu = function()
    local Window = Library:CreateWindow({
        Title = T("Title"),
        Center = true,
        AutoShow = true,
        TabPadding = 8,
        MenuFadeTime = 0.2
    })

    local Tabs = {
        Rage = Window:AddTab(T("Rage")),
        Legit = Window:AddTab(T("Legit")),
        Visuals = Window:AddTab(T("Visuals")),
        Skins = Window:AddTab(T("Skins")),
        Movement = Window:AddTab(T("Movement")),
        ["UI Settings"] = Window:AddTab(T("Settings")),
    }

    -- 1. RAGE TAB
    local LeftRage = Tabs.Rage:AddLeftGroupbox(T("SilentAimbot"))
    local AutoWinBox = Tabs.Rage:AddLeftGroupbox(T("AutoWinGroup"))
    local AutoPeekBox = Tabs.Rage:AddLeftGroupbox(T("AutoPeek"))
    local RightAA = Tabs.Rage:AddRightGroupbox(T("AnglesDesync"))
    local TargetBox = Tabs.Rage:AddRightGroupbox(T("TargetFilters"))

    -- Left Column: Silent Aim + Silent Auto-Shot (Triggerbot)
    LeftRage:AddToggle("SilentAim", {
        Text = T("EnableSilentAim"),
        Default = silentAimEnabled,
        Tooltip = T("SilentAimDesc"),
        Callback = function(Value)
            silentAimEnabled = Value
        end
    }):AddKeyPicker("SilentAimKey", {
        Default = "MB2",
        SyncToggleState = true,
        Mode = "Toggle",
        Text = "Silent Aim Keybind",
        NoUI = false,
    })

    LeftRage:AddDropdown("SilentActivation", {
        Values = { "Always On", "Hold Keybind" },
        Default = silentAimMode == "HoldKey" and 2 or 1,
        Multi = false,
        Text = T("ActivationMode"),
        Callback = function(Value)
            silentAimMode = (Value == "Hold Keybind" or Value:find("Hold")) and "HoldKey" or "AlwaysOn"
        end
    })

    LeftRage:AddDivider()

    -- Silent Auto-Fire (Triggerbot)
    LeftRage:AddToggle("SilentAutoFire", {
        Text = T("SilentAutoFire"),
        Default = silentAutoFire,
        Tooltip = T("SilentAutoFireDesc"),
        Callback = function(Value)
            silentAutoFire = Value
        end
    })

    LeftRage:AddSlider("AutoFireDelay", {
        Text = T("AutoFireDelay"),
        Default = math.floor(silentAutoFireDelay * 100),
        Min = 10,
        Max = 100,
        Rounding = 0,
        Compact = false,
        Callback = function(Value)
            silentAutoFireDelay = Value / 100
        end
    })

    LeftRage:AddSlider("KnifeHoldDuration", {
        Text = T("KnifeHoldDuration"),
        Default = math.floor(knifeHoldDuration * 100),
        Min = 10,
        Max = 60,
        Rounding = 0,
        Compact = false,
        Tooltip = T("KnifeHoldDurationDesc"),
        Callback = function(Value)
            knifeHoldDuration = Value / 100
        end
    })

    LeftRage:AddToggle("MuzzleCheck", {
        Text = T("MuzzleCheck"),
        Default = muzzleCheckEnabled,
        Tooltip = T("MuzzleCheckDesc"),
        Callback = function(Value)
            muzzleCheckEnabled = Value
        end
    })

    LeftRage:AddDivider()

    LeftRage:AddToggle("WallCheck", {
        Text = T("WallCheck"),
        Default = wallCheckEnabled,
        Tooltip = T("WallCheckDesc"),
        Callback = function(Value)
            wallCheckEnabled = Value
        end
    })

    LeftRage:AddToggle("TeamCheck", {
        Text = T("TeamCheck"),
        Default = teamCheckEnabled,
        Tooltip = T("TeamCheckDesc"),
        Callback = function(Value)
            teamCheckEnabled = Value
        end
    })

    LeftRage:AddToggle("Wallbang", {
        Text = "Wallbang",
        Default = wallbangEnabled,
        Tooltip = "Shoot through walls / bypass line of sight raycasts",
        Callback = function(Value)
            wallbangEnabled = Value
        end
    })

    LeftRage:AddToggle("MaxKnifePower", {
        Text = T("MaxKnifePower"),
        Default = alwaysMaxKnifePower,
        Tooltip = T("MaxKnifePowerDesc"),
        Callback = function(Value)
            alwaysMaxKnifePower = Value
            _G.MD_AlwaysMaxKnifePower = Value
        end
    })

    LeftRage:AddToggle("InstantKnifeCharge", {
        Text = T("InstantKnifeCharge"),
        Default = instantKnifeCharge,
        Tooltip = T("InstantKnifeChargeDesc"),
        Callback = function(Value)
            instantKnifeCharge = Value
            pcall(function()
                local rs = game:GetService("ReplicatedStorage")
                local kt = require(rs.Shared.KnifeTiming)
                kt.CHARGE_DUR = Value and 0.01 or 0.5
                kt.HOLD_TO_THROW_SEC = 0.2
            end)
        end
    })

    LeftRage:AddSlider("KnifeSpeed", {
        Text = currentLang == "RU" and "Скорость ножа (как у ревика)" or "Knife Speed (Revolver Speed)",
        Default = 65,
        Min = 10,
        Max = 100,
        Rounding = 0,
        Compact = false,
        Callback = function(Value)
            knifeSpeed = Value / 10
            _G.MD_KnifeSpeed = knifeSpeed
        end
    })

    -- Auto-Win / Kill Aura Groupbox
    AutoWinBox:AddToggle("EnableAutoWin", {
        Text = T("EnableAutoWin"),
        Default = autoWinEnabled,
        Tooltip = T("AutoWinDesc"),
        Callback = function(Value)
            autoWinEnabled = Value
        end
    }):AddKeyPicker("AutoWinKey", {
        Default = "None",
        SyncToggleState = false,
        Mode = "Hold",
        Text = T("AutoWinKey"),
        NoUI = false,
    })

    AutoWinBox:AddDropdown("AutoWinMode", {
        Values = { "TP Backstab", "360° Auto-Throw" },
        Default = 1,
        Multi = false,
        Text = T("AutoWinMode"),
        Callback = function(Value)
            autoWinMode = Value
        end
    })

    AutoWinBox:AddSlider("AutoWinDelay", {
        Text = T("AutoWinDelay"),
        Default = math.floor(autoWinDelay * 100),
        Min = 5,
        Max = 100,
        Rounding = 0,
        Compact = false,
        Callback = function(Value)
            autoWinDelay = Value / 100
        end
    })

    AutoWinBox:AddToggle("AutoWinReturn", {
        Text = T("AutoWinReturn"),
        Default = autoWinReturn,
        Tooltip = T("AutoWinReturnDesc"),
        Callback = function(Value)
            autoWinReturn = Value
        end
    })

    AutoWinBox:AddToggle("AutoWinEquip", {
        Text = T("AutoWinEquip"),
        Default = autoWinEquip,
        Tooltip = T("AutoWinEquipDesc"),
        Callback = function(Value)
            autoWinEquip = Value
        end
    })

    -- Auto-Peek Groupbox (Peek Assist)
    AutoPeekBox:AddToggle("AutoPeek", {
        Text = T("EnableAutoPeek"),
        Default = autoPeekEnabled,
        Tooltip = T("AutoPeekDesc"),
        Callback = function(Value)
            autoPeekEnabled = Value
            if not Value and autoPeekAnchor then
                autoPeekAnchor = nil
                autoPeekState = "IDLE"
                updateAutoPeekVisual()
            end
        end
    }):AddKeyPicker("AutoPeekKey", {
        Default = "C",
        SyncToggleState = false,
        Mode = "Hold",
        Text = "Auto-Peek Key",
        NoUI = false,
    })

    AutoPeekBox:AddToggle("AutoPeekMarker", {
        Text = T("AutoPeekMarker"),
        Default = autoPeekShowMarker,
        Tooltip = T("AutoPeekMarkerDesc"),
        Callback = function(Value)
            autoPeekShowMarker = Value
            updateAutoPeekVisual()
        end
    }):AddColorPicker("AutoPeekColor", {
        Default = autoPeekColor,
        Title = "Marker Color",
        Callback = function(Value)
            autoPeekColor = Value
            if autoPeekVisual then autoPeekVisual.Color = Value end
        end
    })

    AutoPeekBox:AddSlider("AutoPeekSpeed", {
        Text = T("AutoPeekSpeed"),
        Default = math.floor(autoPeekReturnSpeed),
        Min = 2,
        Max = 8,
        Rounding = 0,
        Compact = false,
        Callback = function(Value)
            autoPeekReturnSpeed = Value
        end
    })

    -- Right Column: Anti-Aim
    RightAA:AddToggle("EnableAA", {
        Text = T("EnableAA"),
        Default = aaEnabled,
        Tooltip = T("AADesc"),
        Callback = function(Value)
            aaEnabled = Value
            if not Value then resetAntiAim() end
        end
    }):AddKeyPicker("AAKey", {
        Default = "X",
        SyncToggleState = true,
        Mode = "Toggle",
        Text = "Toggle Anti-Aim",
        NoUI = false,
    })

    RightAA:AddDropdown("YawMode", {
        Values = { "Spinbot", "Jitter (180 Flip)", "Jitter (Custom Angle)", "Random Jitter", "Backward (180)", "Sideways (90)", "Sway (Sinusoid)" },
        Default = 1,
        Multi = false,
        Text = T("YawMode"),
        Callback = function(Value)
            aaYawMode = Value
        end
    })

    RightAA:AddDropdown("PitchMode", {
        Values = { "Down (Head Roll)", "Up (Sky)", "Jitter Pitch", "Zero" },
        Default = 1,
        Multi = false,
        Text = T("PitchMode"),
        Callback = function(Value)
            aaPitchMode = Value
            if Value == "Zero" then
                local _, _, _, rj = getCharParts()
                if rj then rj.C0 = defaultRjC0 end
            end
        end
    })

    RightAA:AddSlider("SpinSpeed", {
        Text = T("SpinSpeed"),
        Default = spinSpeed,
        Min = 5,
        Max = 75,
        Rounding = 0,
        Compact = false,
        Callback = function(Value)
            spinSpeed = Value
        end
    })

    RightAA:AddSlider("PitchAngle", {
        Text = T("PitchAngle"),
        Default = pitchAngle,
        Min = -85,
        Max = 85,
        Rounding = 0,
        Compact = false,
        Callback = function(Value)
            pitchAngle = Value
        end
    })

    RightAA:AddSlider("JitterAngle", {
        Text = T("JitterAngle"),
        Default = jitterAngle,
        Min = 30,
        Max = 180,
        Rounding = 0,
        Compact = false,
        Callback = function(Value)
            jitterAngle = Value
        end
    })

    RightAA:AddSlider("SwayFreq", {
        Text = T("SwayFreq"),
        Default = swayFreq,
        Min = 2,
        Max = 20,
        Rounding = 0,
        Compact = false,
        Callback = function(Value)
            swayFreq = Value
        end
    })

    -- Right Column: Target Filters & FOV
    TargetBox:AddToggle("TargetPlayers", {
        Text = T("TargetPlayers"),
        Default = targetPlayers,
        Callback = function(Value)
            targetPlayers = Value
            refreshTargetCache()
        end
    })

    TargetBox:AddToggle("TargetNoobs", {
        Text = T("TargetNoobs"),
        Default = targetNoobs,
        Callback = function(Value)
            targetNoobs = Value
            refreshTargetCache()
        end
    })

    TargetBox:AddToggle("TargetBullseyes", {
        Text = T("TargetBullseyes"),
        Default = targetTargets,
        Callback = function(Value)
            targetTargets = Value
            refreshTargetCache()
        end
    })

    TargetBox:AddDropdown("TargetPart", {
        Values = { "Head", "Torso", "HumanoidRootPart" },
        Default = targetPartMode == "Head" and 1 or (targetPartMode == "Torso" and 2 or 3),
        Multi = false,
        Text = T("HitboxPriority"),
        Callback = function(Value)
            targetPartMode = Value
        end
    })

    TargetBox:AddDivider()

    TargetBox:AddToggle("ShowFOV", {
        Text = T("DrawFOV"),
        Default = showFovCircle,
        Callback = function(Value)
            showFovCircle = Value
            if fovCircle and not Value then
                fovCircle.Visible = false
            end
        end
    }):AddColorPicker("FOVColor", {
        Default = Color3.fromRGB(255, 75, 75),
        Title = "FOV Color",
        Callback = function(Value)
            if fovCircle then fovCircle.Color = Value end
        end
    })

    TargetBox:AddSlider("FOVRadius", {
        Text = T("FOVRadius"),
        Default = fovRadius,
        Min = 30,
        Max = 450,
        Rounding = 0,
        Compact = false,
        Callback = function(Value)
            fovRadius = Value
        end
    })

    -- 2. LEGIT TAB
    local LeftLegit = Tabs.Legit:AddLeftGroupbox(T("LegitAimbot"))
    local RightLegit = Tabs.Legit:AddRightGroupbox(T("LegitTriggerbot"))

    LeftLegit:AddToggle("LegitAim", {
        Text = T("EnableLegitAim"),
        Default = legitAimEnabled,
        Tooltip = T("LegitAimDesc"),
        Callback = function(Value)
            legitAimEnabled = Value
        end
    }):AddKeyPicker("LegitAimKey", {
        Default = "MB2",
        SyncToggleState = true,
        Mode = "Hold",
        Text = "Legit Aim Key",
        NoUI = false,
    })

    LeftLegit:AddDropdown("LegitAimMode", {
        Values = { "Hold Keybind", "Always On" },
        Default = legitAimMode == "AlwaysOn" and 2 or 1,
        Multi = false,
        Text = T("ActivationMode"),
        Callback = function(Value)
            legitAimMode = (Value:find("Always") or Value == "Always On") and "AlwaysOn" or "HoldKey"
        end
    })

    LeftLegit:AddSlider("LegitSmoothness", {
        Text = T("LegitSmoothness"),
        Default = legitSmoothness,
        Min = 1,
        Max = 25,
        Rounding = 0,
        Compact = false,
        Callback = function(Value)
            legitSmoothness = Value
        end
    })

    LeftLegit:AddSlider("LegitFOV", {
        Text = T("LegitFOV"),
        Default = legitFovRadius,
        Min = 20,
        Max = 250,
        Rounding = 0,
        Compact = false,
        Callback = function(Value)
            legitFovRadius = Value
            if legitFovCircle then legitFovCircle.Radius = Value end
        end
    })

    LeftLegit:AddToggle("DrawLegitFOV", {
        Text = T("DrawLegitFOV"),
        Default = legitShowFov,
        Callback = function(Value)
            legitShowFov = Value
        end
    }):AddColorPicker("LegitFOVColor", {
        Default = Color3.fromRGB(60, 180, 255),
        Title = "Legit FOV Color",
        Callback = function(Value)
            if legitFovCircle then legitFovCircle.Color = Value end
        end
    })

    LeftLegit:AddDropdown("LegitHitbox", {
        Values = { "Head", "Torso", "HumanoidRootPart" },
        Default = legitHitbox == "Head" and 1 or (legitHitbox == "Torso" and 2 or 3),
        Multi = false,
        Text = T("LegitHitbox"),
        Callback = function(Value)
            legitHitbox = Value
        end
    })

    LeftLegit:AddToggle("LegitWallCheck", {
        Text = T("LegitWallCheck"),
        Default = legitWallCheck,
        Callback = function(Value)
            legitWallCheck = Value
        end
    })

    -- Right Legit: Legit Triggerbot
    RightLegit:AddToggle("LegitTrigger", {
        Text = T("EnableLegitTrigger"),
        Default = legitTriggerEnabled,
        Tooltip = T("LegitTriggerDesc"),
        Callback = function(Value)
            legitTriggerEnabled = Value
        end
    }):AddKeyPicker("LegitTriggerKey", {
        Default = "None",
        SyncToggleState = true,
        Mode = "Toggle",
        Text = "Trigger Key",
        NoUI = false,
    })

    RightLegit:AddSlider("ReactionDelay", {
        Text = T("ReactionDelay"),
        Default = math.floor(legitTriggerDelay * 1000),
        Min = 50,
        Max = 400,
        Rounding = 0,
        Compact = false,
        Callback = function(Value)
            legitTriggerDelay = Value / 1000
        end
    })

    RightLegit:AddToggle("LegitTriggerTeamCheck", {
        Text = T("TeamCheck"),
        Default = legitTriggerTeamCheck,
        Callback = function(Value)
            legitTriggerTeamCheck = Value
        end
    })

    -- 3. MOVEMENT TAB
    local LeftMove = Tabs.Movement:AddLeftGroupbox(T("BhopStrafes"))
    local RightMove = Tabs.Movement:AddRightGroupbox(T("MovementBoost"))

    LeftMove:AddToggle("Bhop", {
        Text = T("Bhop"),
        Default = bhopEnabled,
        Tooltip = T("BhopDesc"),
        Callback = function(Value)
            bhopEnabled = Value
        end
    })

    LeftMove:AddToggle("AirStrafes", {
        Text = T("AirStrafes"),
        Default = instantStrafes,
        Tooltip = T("AirStrafesDesc"),
        Callback = function(Value)
            instantStrafes = Value
        end
    })

    LeftMove:AddSlider("BhopSpeed", {
        Text = T("BhopSpeed"),
        Default = bhopSpeed,
        Min = 23,
        Max = 150,
        Rounding = 0,
        Compact = false,
        Callback = function(Value)
            bhopSpeed = Value
        end
    })

    RightMove:AddToggle("InfJump", {
        Text = T("InfJump"),
        Default = infiniteJump,
        Tooltip = T("InfJumpDesc"),
        Callback = function(Value)
            infiniteJump = Value
        end
    })

    RightMove:AddSlider("WalkSpeed", {
        Text = T("WalkSpeed"),
        Default = 23,
        Min = 23,
        Max = 150,
        Rounding = 0,
        Compact = false,
        Callback = function(Value)
            local hum = LocalPlayer.Character and LocalPlayer.Character:FindFirstChildOfClass("Humanoid")
            if hum then hum.WalkSpeed = Value end
        end
    })

    -- 4. VISUALS TAB
    local LeftVis = Tabs.Visuals:AddLeftGroupbox(T("ThirdPersonCam"))
    local AmbienceBox = Tabs.Visuals:AddLeftGroupbox(T("AmbienceWorld"))
    local CrosshairBox = Tabs.Visuals:AddLeftGroupbox(T("CrosshairVisuals"))

    local RightVis = Tabs.Visuals:AddRightGroupbox(T("ESPWorld"))
    local DrawingBox = Tabs.Visuals:AddRightGroupbox(T("DrawingVisuals"))
    local TracerBox = Tabs.Visuals:AddRightGroupbox(T("BulletTracers"))

    -- Left Visuals: Third Person
    LeftVis:AddToggle("ThirdPerson", {
        Text = T("EnableTP"),
        Default = thirdPersonEnabled,
        Tooltip = T("TPDesc"),
        Callback = function(Value)
            thirdPersonEnabled = Value
            applyNativeCamera()
        end
    }):AddKeyPicker("TPKey", {
        Default = "V",
        SyncToggleState = true,
        Mode = "Toggle",
        Text = "Toggle 3rd Person",
        NoUI = false,
    })

    LeftVis:AddSlider("CamDist", {
        Text = T("CamDist"),
        Default = cameraDistance,
        Min = 5,
        Max = 30,
        Rounding = 0,
        Compact = false,
        Callback = function(Value)
            cameraDistance = Value
            applyNativeCamera()
        end
    })

    LeftVis:AddSlider("ShoulderX", {
        Text = T("ShoulderX"),
        Default = shoulderOffset,
        Min = -3,
        Max = 3,
        Rounding = 1,
        Compact = false,
        Callback = function(Value)
            shoulderOffset = Value
            applyNativeCamera()
        end
    })

    LeftVis:AddSlider("HeightY", {
        Text = T("HeightY"),
        Default = heightOffset,
        Min = -1,
        Max = 4,
        Rounding = 1,
        Compact = false,
        Callback = function(Value)
            heightOffset = Value
            applyNativeCamera()
        end
    })

    LeftVis:AddSlider("FOV", {
        Text = T("FOV"),
        Default = customFOV,
        Min = 70,
        Max = 120,
        Rounding = 0,
        Compact = false,
        Callback = function(Value)
            customFOV = Value
            workspace.CurrentCamera.FieldOfView = Value
        end
    })

    -- Left Visuals: Custom Ambience & Lighting
    AmbienceBox:AddToggle("CustomAmbience", {
        Text = T("EnableAmbience"),
        Default = customAmbienceEnabled,
        Tooltip = T("AmbienceDesc"),
        Callback = function(Value)
            customAmbienceEnabled = Value
            applyAmbience()
        end
    })

    AmbienceBox:AddDropdown("AmbiencePreset", {
        Values = { "Purple Night", "Sunset", "Blood Moon", "Cyberpunk", "Midnight", "Toxic Green" },
        Default = 1,
        Multi = false,
        Text = T("AmbiencePreset"),
        Callback = function(Value)
            local p = ambiencePresets[Value]
            if p then
                customLighting.ClockTime = p.ClockTime
                customLighting.Ambient = p.Ambient
                customLighting.OutdoorAmbient = p.OutdoorAmbient
                customLighting.FogColor = p.FogColor
                customLighting.FogDistance = p.FogEnd
                customLighting.TintColor = p.Tint
                customLighting.Saturation = p.Saturation
                applyAmbience()
            end
        end
    })

    AmbienceBox:AddSlider("AmbienceClockTime", {
        Text = T("ClockTime"),
        Default = customLighting.ClockTime,
        Min = 0,
        Max = 24,
        Rounding = 1,
        Compact = false,
        Callback = function(Value)
            customLighting.ClockTime = Value
            if customAmbienceEnabled then Lighting.ClockTime = Value end
        end
    })

    AmbienceBox:AddSlider("AmbienceFogDist", {
        Text = T("FogDist"),
        Default = customLighting.FogDistance,
        Min = 100,
        Max = 3000,
        Rounding = 0,
        Compact = false,
        Callback = function(Value)
            customLighting.FogDistance = Value
            if customAmbienceEnabled then Lighting.FogEnd = Value end
        end
    })

    AmbienceBox:AddSlider("AmbienceSaturation", {
        Text = T("Saturation"),
        Default = math.floor(customLighting.Saturation * 10),
        Min = -10,
        Max = 15,
        Rounding = 0,
        Compact = false,
        Callback = function(Value)
            customLighting.Saturation = Value / 10
            if customAmbienceEnabled and colorCorrection then
                colorCorrection.Saturation = Value / 10
            end
        end
    })

    AmbienceBox:AddLabel(T("AmbientColor")):AddColorPicker("AmbientCol", {
        Default = customLighting.Ambient,
        Title = "Ambient Color",
        Callback = function(Value)
            customLighting.Ambient = Value
            if customAmbienceEnabled then Lighting.Ambient = Value end
        end
    })

    AmbienceBox:AddLabel(T("OutdoorColor")):AddColorPicker("OutdoorCol", {
        Default = customLighting.OutdoorAmbient,
        Title = "Outdoor Ambient",
        Callback = function(Value)
            customLighting.OutdoorAmbient = Value
            if customAmbienceEnabled then Lighting.OutdoorAmbient = Value end
        end
    })

    AmbienceBox:AddLabel(T("FogColor")):AddColorPicker("FogCol", {
        Default = customLighting.FogColor,
        Title = "Fog Color",
        Callback = function(Value)
            customLighting.FogColor = Value
            if customAmbienceEnabled then
                Lighting.FogColor = Value
                if atmosphere then atmosphere.Color = Value end
            end
        end
    })

    -- Left Visuals: Custom CS Crosshair
    CrosshairBox:AddToggle("EnableCrosshair", {
        Text = T("EnableCrosshair"),
        Default = customCrosshairEnabled,
        Callback = function(Value)
            customCrosshairEnabled = Value
        end
    }):AddColorPicker("CrosshairColor", {
        Default = crosshairColor,
        Title = "Crosshair Color",
        Callback = function(Value)
            crosshairColor = Value
        end
    })

    CrosshairBox:AddSlider("CrosshairSize", {
        Text = T("CrosshairSize"),
        Default = crosshairSize,
        Min = 2,
        Max = 25,
        Rounding = 0,
        Compact = false,
        Callback = function(Value)
            crosshairSize = Value
        end
    })

    CrosshairBox:AddSlider("CrosshairGap", {
        Text = T("CrosshairGap"),
        Default = crosshairGap,
        Min = 0,
        Max = 15,
        Rounding = 0,
        Compact = false,
        Callback = function(Value)
            crosshairGap = Value
        end
    })

    CrosshairBox:AddSlider("CrosshairThickness", {
        Text = T("CrosshairThickness"),
        Default = math.floor(crosshairThickness * 10),
        Min = 10,
        Max = 40,
        Rounding = 0,
        Compact = false,
        Callback = function(Value)
            crosshairThickness = Value / 10
        end
    })

    CrosshairBox:AddToggle("CrosshairDot", {
        Text = T("CrosshairDot"),
        Default = crosshairDotEnabled,
        Callback = function(Value)
            crosshairDotEnabled = Value
        end
    })

    -- Right Visuals: Advanced ESP / Chams
    RightVis:AddToggle("ESP", {
        Text = T("EnableESP"),
        Default = espEnabled,
        Tooltip = T("ESPDesc"),
        Callback = function(Value)
            espEnabled = Value
            pcall(updateEsp)
        end
    }):AddColorPicker("ESPColor", {
        Default = espFillColor,
        Title = "ESP Color",
        Callback = function(Value)
            espFillColor = Value
            for _, d in pairs(espCache) do
                if d.highlight then d.highlight.FillColor = Value end
            end
        end
    })

    RightVis:AddToggle("ESPNames", {
        Text = T("ESPNames"),
        Default = espShowNames,
        Tooltip = T("ESPNamesDesc"),
        Callback = function(Value)
            espShowNames = Value
            espShowDistance = Value
            for _, d in pairs(espCache) do
                if d.nameLabel then d.nameLabel.Visible = Value end
            end
        end
    })

    RightVis:AddToggle("ESPHealth", {
        Text = T("ESPHealth"),
        Default = espShowHealth,
        Tooltip = T("ESPHealthDesc"),
        Callback = function(Value)
            espShowHealth = Value
            for _, d in pairs(espCache) do
                if d.healthBg then d.healthBg.Visible = Value end
            end
        end
    })

    RightVis:AddToggle("ESPWeapon", {
        Text = T("ESPWeapon"),
        Default = espShowWeapon,
        Tooltip = T("ESPWeaponDesc"),
        Callback = function(Value)
            espShowWeapon = Value
        end
    })

    RightVis:AddToggle("ESPBots", {
        Text = T("ESPBots"),
        Default = espTargetBots,
        Callback = function(Value)
            espTargetBots = Value
        end
    })

    RightVis:AddSlider("ESPTransp", {
        Text = T("ChamsTransp"),
        Default = math.floor(espFillTransparency * 10),
        Min = 0,
        Max = 10,
        Rounding = 0,
        Compact = false,
        Callback = function(Value)
            espFillTransparency = Value / 10
            for _, d in pairs(espCache) do
                if d.highlight then d.highlight.FillTransparency = Value / 10 end
            end
        end
    })

    RightVis:AddDivider()

    RightVis:AddToggle("Fullbright", {
        Text = T("Fullbright"),
        Default = fullbrightEnabled,
        Tooltip = T("FullbrightDesc"),
        Callback = function(Value)
            fullbrightEnabled = Value
            if Value then
                Lighting.Brightness = 2
                Lighting.ClockTime = 14
                Lighting.FogEnd = 100000
                Lighting.GlobalShadows = false
            else
                Lighting.Brightness = origLighting.Brightness
                Lighting.ClockTime = origLighting.ClockTime
                Lighting.FogEnd = origLighting.FogEnd
                Lighting.GlobalShadows = origLighting.GlobalShadows
            end
        end
    })

    -- Right Visuals: 2D Box ESP, Snaplines, Head Dots, Target Tracer
    DrawingBox:AddToggle("BoxESP", {
        Text = T("BoxESP"),
        Default = boxEspEnabled,
        Tooltip = T("BoxESPDesc"),
        Callback = function(Value)
            boxEspEnabled = Value
            if not Value then
                for _, d in pairs(drawingCache) do
                    if d.box then d.box.Visible = false end
                end
            end
        end
    }):AddColorPicker("BoxColor", {
        Default = boxColor,
        Title = "Box Color",
        Callback = function(Value)
            boxColor = Value
        end
    })

    DrawingBox:AddToggle("Snaplines", {
        Text = T("Snaplines"),
        Default = snaplinesEnabled,
        Tooltip = T("SnaplinesDesc"),
        Callback = function(Value)
            snaplinesEnabled = Value
            if not Value then
                for _, d in pairs(drawingCache) do
                    if d.line then d.line.Visible = false end
                end
            end
        end
    }):AddColorPicker("SnaplinesColor", {
        Default = snaplinesColor,
        Title = "Snaplines Color",
        Callback = function(Value)
            snaplinesColor = Value
        end
    })

    DrawingBox:AddDropdown("TracerOrigin", {
        Values = { "Bottom", "Center" },
        Default = 1,
        Multi = false,
        Text = T("TracerOrigin"),
        Callback = function(Value)
            snaplinesOrigin = Value
        end
    })

    DrawingBox:AddToggle("HeadDots", {
        Text = T("HeadDots"),
        Default = headDotsEnabled,
        Tooltip = T("HeadDotsDesc"),
        Callback = function(Value)
            headDotsEnabled = Value
            if not Value then
                for _, d in pairs(drawingCache) do
                    if d.dot then d.dot.Visible = false end
                end
            end
        end
    }):AddColorPicker("HeadDotsColor", {
        Default = headDotsColor,
        Title = "Head Dots Color",
        Callback = function(Value)
            headDotsColor = Value
        end
    })

    DrawingBox:AddToggle("TargetLine", {
        Text = T("TargetLine"),
        Default = targetLineEnabled,
        Tooltip = T("TargetLineDesc"),
        Callback = function(Value)
            targetLineEnabled = Value
            if not Value and targetLine then
                targetLine.Visible = false
            end
        end
    }):AddColorPicker("TargetLineColor", {
        Default = targetLineColor,
        Title = "Target Line Color",
        Callback = function(Value)
            targetLineColor = Value
        end
    })

    -- Right Visuals: Bullet Tracers (Hit Tracers)
    TracerBox:AddToggle("BulletTracers", {
        Text = T("EnableTracers"),
        Default = bulletTracersEnabled,
        Tooltip = T("TracersDesc"),
        Callback = function(Value)
            bulletTracersEnabled = Value
        end
    }):AddColorPicker("TracerCol", {
        Default = tracerColor,
        Title = "Tracer Color",
        Callback = function(Value)
            tracerColor = Value
        end
    })

    TracerBox:AddToggle("TracerImpact", {
        Text = T("ShowImpact"),
        Default = tracerShowImpact,
        Tooltip = T("ShowImpactDesc"),
        Callback = function(Value)
            tracerShowImpact = Value
        end
    }):AddColorPicker("ImpactCol", {
        Default = tracerImpactColor,
        Title = "Impact Color",
        Callback = function(Value)
            tracerImpactColor = Value
        end
    })

    TracerBox:AddSlider("TracerDur", {
        Text = T("TracerDuration"),
        Default = math.floor(tracerDuration * 10),
        Min = 2,
        Max = 30,
        Rounding = 0,
        Compact = false,
        Callback = function(Value)
            tracerDuration = Value / 10
        end
    })

    TracerBox:AddSlider("TracerThick", {
        Text = T("TracerThickness"),
        Default = math.floor(tracerThickness * 100),
        Min = 5,
        Max = 40,
        Rounding = 0,
        Compact = false,
        Callback = function(Value)
            tracerThickness = Value / 100
        end
    })

    -- 5. SKINS TAB
    local LeftSkins = Tabs.Skins:AddLeftGroupbox(T("RevolverSkinsGroup"))
    local RightSkins = Tabs.Skins:AddRightGroupbox(T("KnifeSkinsGroup"))

    local function findSkinIdx(list, targetName)
        for i, v in ipairs(list) do
            if v == targetName then return i end
        end
        return 1
    end

    LeftSkins:AddToggle("EnableSkinChanger", {
        Text = T("EnableSkinChanger"),
        Default = skinChangerEnabled,
        Tooltip = T("SkinChangerDesc"),
        Callback = function(Value)
            skinChangerEnabled = Value
            saveSkinsAutoload()
            applySkins()
        end
    })

    LeftSkins:AddDropdown("RevolverSkinSelect", {
        Values = availableRevolvers,
        Default = findSkinIdx(availableRevolvers, selectedRevolverSkin),
        Multi = false,
        Text = T("RevolverSkinSelect"),
        Callback = function(Value)
            selectedRevolverSkin = Value
            saveSkinsAutoload()
            if skinChangerEnabled then
                applySkins()
            end
        end
    })

    LeftSkins:AddButton(T("ApplySkins"), function()
        applySkins()
    end)

    LeftSkins:AddButton(T("SaveAsAutoload"), function()
        saveSkinsAutoload()
        Library:Notify(T("AutoloadSaved") .. string.format("\n[%s | %s]", selectedRevolverSkin, selectedKnifeSkin), 3)
    end)

    RightSkins:AddDropdown("KnifeSkinSelect", {
        Values = availableKnives,
        Default = findSkinIdx(availableKnives, selectedKnifeSkin),
        Multi = false,
        Text = T("KnifeSkinSelect"),
        Callback = function(Value)
            selectedKnifeSkin = Value
            saveSkinsAutoload()
            if skinChangerEnabled then
                applySkins()
            end
        end
    })

    RightSkins:AddButton(T("ApplySkins"), function()
        applySkins()
    end)

    RightSkins:AddButton(T("SaveAsAutoload"), function()
        saveSkinsAutoload()
        Library:Notify(T("AutoloadSaved") .. string.format("\n[%s | %s]", selectedRevolverSkin, selectedKnifeSkin), 3)
    end)

    -- Viewmodel Settings (Left Column)
    local ViewmodelBox = Tabs.Skins:AddLeftGroupbox(T("ViewmodelGroup"))
    ViewmodelBox:AddToggle("EnableViewmodel", {
        Text = T("EnableViewmodel"),
        Default = viewmodelEnabled,
        Tooltip = T("ViewmodelDesc"),
        Callback = function(Value)
            viewmodelEnabled = Value
        end
    })

    ViewmodelBox:AddToggle("HideArms", {
        Text = T("HideArms"),
        Default = hideArmsEnabled,
        Tooltip = T("HideArmsDesc"),
        Callback = function(Value)
            hideArmsEnabled = Value
        end
    })

    ViewmodelBox:AddDropdown("VMMode", {
        Values = { T("VMArmAndWeapon"), T("VMWeaponOnly") },
        Default = (vmTargetMode == "ArmAndWeapon") and 1 or 2,
        Multi = false,
        Text = T("VMMode"),
        Callback = function(Value)
            if Value == T("VMWeaponOnly") or Value:find("Weapon") or Value:find("Только") then
                vmTargetMode = "WeaponOnly"
            else
                vmTargetMode = "ArmAndWeapon"
            end
        end
    })

    ViewmodelBox:AddDropdown("VMPreset", {
        Values = { "Default", "Left Hand", "Centered / Doom", "Gangster Tilt", "Extended" },
        Default = 1,
        Multi = false,
        Text = T("VMPreset"),
        Callback = function(Value)
            if Value == "Default" then
                vm.x, vm.y, vm.z = 0, 0, 0
                vm.pitch, vm.yaw, vm.roll = 0, 0, 0
            elseif Value == "Left Hand" then
                vm.x, vm.y, vm.z = -1.3, -0.1, 0.2
                vm.pitch, vm.yaw, vm.roll = 0, 0, -15
            elseif Value == "Centered / Doom" then
                vm.x, vm.y, vm.z = -0.85, -0.2, 0.4
                vm.pitch, vm.yaw, vm.roll = 5, 0, 0
            elseif Value == "Gangster Tilt" then
                vm.x, vm.y, vm.z = 0.1, 0.1, 0.2
                vm.pitch, vm.yaw, vm.roll = 0, 10, 40
            elseif Value == "Extended" then
                vm.x, vm.y, vm.z = 0, -0.1, -1.2
                vm.pitch, vm.yaw, vm.roll = 0, 0, 0
            end
            pcall(function()
                if Options.VMOffsetX then Options.VMOffsetX:SetValue(math.floor(vm.x * 10)) end
                if Options.VMOffsetY then Options.VMOffsetY:SetValue(math.floor(vm.y * 10)) end
                if Options.VMOffsetZ then Options.VMOffsetZ:SetValue(math.floor(vm.z * 10)) end
                if Options.VMPitch then Options.VMPitch:SetValue(vm.pitch) end
                if Options.VMYaw then Options.VMYaw:SetValue(vm.yaw) end
                if Options.VMRoll then Options.VMRoll:SetValue(vm.roll) end
            end)
        end
    })

    ViewmodelBox:AddSlider("VMOffsetX", {
        Text = T("VMOffsetX"),
        Default = math.floor(vm.x * 10),
        Min = -25,
        Max = 25,
        Rounding = 0,
        Compact = false,
        Callback = function(Value)
            vm.x = Value / 10
        end
    })

    ViewmodelBox:AddSlider("VMOffsetY", {
        Text = T("VMOffsetY"),
        Default = math.floor(vm.y * 10),
        Min = -25,
        Max = 25,
        Rounding = 0,
        Compact = false,
        Callback = function(Value)
            vm.y = Value / 10
        end
    })

    ViewmodelBox:AddSlider("VMOffsetZ", {
        Text = T("VMOffsetZ"),
        Default = math.floor(vm.z * 10),
        Min = -25,
        Max = 25,
        Rounding = 0,
        Compact = false,
        Callback = function(Value)
            vm.z = Value / 10
        end
    })

    ViewmodelBox:AddSlider("VMPitch", {
        Text = T("VMPitch"),
        Default = vm.pitch,
        Min = -45,
        Max = 45,
        Rounding = 0,
        Compact = false,
        Callback = function(Value)
            vm.pitch = Value
        end
    })

    ViewmodelBox:AddSlider("VMYaw", {
        Text = T("VMYaw"),
        Default = vm.yaw,
        Min = -45,
        Max = 45,
        Rounding = 0,
        Compact = false,
        Callback = function(Value)
            vm.yaw = Value
        end
    })

    ViewmodelBox:AddSlider("VMRoll", {
        Text = T("VMRoll"),
        Default = vm.roll,
        Min = -45,
        Max = 45,
        Rounding = 0,
        Compact = false,
        Callback = function(Value)
            vm.roll = Value
        end
    })

    ViewmodelBox:AddButton(T("ResetViewmodel"), function()
        vm.x, vm.y, vm.z = 0, 0, 0
        vm.pitch, vm.yaw, vm.roll = 0, 0, 0
        pcall(function()
            if Options.VMOffsetX then Options.VMOffsetX:SetValue(0) end
            if Options.VMOffsetY then Options.VMOffsetY:SetValue(0) end
            if Options.VMOffsetZ then Options.VMOffsetZ:SetValue(0) end
            if Options.VMPitch then Options.VMPitch:SetValue(0) end
            if Options.VMYaw then Options.VMYaw:SetValue(0) end
            if Options.VMRoll then Options.VMRoll:SetValue(0) end
        end)
    end)

    -- Weapon Scale (Right Column)
    local ScaleBox = Tabs.Skins:AddRightGroupbox(T("WeaponScaleGroup"))
    ScaleBox:AddToggle("EnableWeaponScale", {
        Text = T("EnableWeaponScale"),
        Default = weaponScaleEnabled,
        Tooltip = T("WeaponScaleDesc"),
        Callback = function(Value)
            weaponScaleEnabled = Value
        end
    })

    ScaleBox:AddDropdown("ScalePreset", {
        Values = { "Default (1.0x)", "Compact / Mini (0.5x)", "Medium (1.5x)", "Giant Buster (2.5x)", "Colossal (3.5x)" },
        Default = 1,
        Multi = false,
        Text = T("ScalePreset"),
        Callback = function(Value)
            if Value:find("Default") then
                weaponScale = 1.0
            elseif Value:find("Mini") or Value:find("Compact") then
                weaponScale = 0.5
            elseif Value:find("Medium") then
                weaponScale = 1.5
            elseif Value:find("Giant") then
                weaponScale = 2.5
            elseif Value:find("Colossal") then
                weaponScale = 3.5
            end
            pcall(function()
                if Options.WeaponScaleSlider then
                    Options.WeaponScaleSlider:SetValue(math.floor(weaponScale * 100))
                end
            end)
        end
    })

    ScaleBox:AddSlider("WeaponScaleSlider", {
        Text = T("WeaponScale"),
        Default = math.floor(weaponScale * 100),
        Min = 20,
        Max = 350,
        Rounding = 0,
        Compact = false,
        Callback = function(Value)
            weaponScale = Value / 100
        end
    })

    ScaleBox:AddButton(T("ResetViewmodel"), function()
        weaponScale = 1.0
        pcall(function()
            if Options.WeaponScaleSlider then Options.WeaponScaleSlider:SetValue(100) end
        end)
    end)

    -- 6. SETTINGS TAB (Separated into Left and Right columns + Config & Theme Manager)
    local LeftSettings = Tabs["UI Settings"]:AddLeftGroupbox(T("LanguageSettings"))
    local RightSettings = Tabs["UI Settings"]:AddRightGroupbox(T("UnloadGroup"))

    LeftSettings:AddDropdown("Language", {
        Values = { "Русский (RU)", "English (EN)" },
        Default = currentLang == "RU" and 1 or 2,
        Multi = false,
        Text = T("Language"),
        Callback = function(Value)
            local newLang = Value:find("RU") and "RU" or "EN"
            if newLang ~= currentLang then
                currentLang = newLang
                _G.MD_SelectedLanguage = newLang
                task.defer(function()
                    Library:Unload()
                    buildMenu()
                end)
            end
        end
    })

    LeftSettings:AddDivider()

    -- Menu Keybind controls
    local currentKeyName = (_G.MD_MenuToggleKey and _G.MD_MenuToggleKey.Name) or "RightControl"
    menuKeyLabelRef = LeftSettings:AddLabel(T("MenuKey") .. ": [" .. currentKeyName .. "]")

    LeftSettings:AddDropdown("QuickMenuKey", {
        Values = { "RightControl", "Insert", "RightShift", "LeftAlt", "F1", "F4", "Delete", "P", "L" },
        Default = (function()
            local cur = (_G.MD_MenuToggleKey and _G.MD_MenuToggleKey.Name) or "RightControl"
            local vals = { "RightControl", "Insert", "RightShift", "LeftAlt", "F1", "F4", "Delete", "P", "L" }
            for i, v in ipairs(vals) do
                if v == cur then return i end
            end
            return 1
        end)(),
        Multi = false,
        Text = T("QuickKeySelect"),
        Callback = function(Value)
            local kc = Enum.KeyCode[Value]
            if kc then
                _G.MD_MenuToggleKey = kc
                if menuKeyLabelRef then
                    menuKeyLabelRef:SetText(T("MenuKey") .. ": [" .. Value .. "]")
                end
                Library:Notify(T("KeybindUpdated") .. ": " .. Value, 3)
            end
        end
    })

    LeftSettings:AddButton(T("ChangeMenuKey"), function()
        isListeningForMenuKey = true
        if menuKeyLabelRef then
            menuKeyLabelRef:SetText(T("MenuKey") .. ": [" .. T("PressAnyKey") .. "]")
        end
        Library:Notify(T("PressAnyKey"), 3)
    end)

    RightSettings:AddButton(T("Unload"), function()
        if _G.MurderDuelsCleanup then
            _G.MurderDuelsCleanup()
        end
    end)

    -- Integrate ThemeManager and SaveManager on UI Settings Tab
    pcall(function()
        ThemeManager:SetLibrary(Library)
        SaveManager:SetLibrary(Library)

        SaveManager:IgnoreThemeSettings()
        SaveManager:SetIgnoreIndexes({ "MenuKey", "QuickMenuKey", "Language" })

        ThemeManager:SetFolder("MurderDuelsSkeet")
        SaveManager:SetFolder("MurderDuelsSkeet")

        SaveManager:BuildConfigSection(Tabs["UI Settings"])
        ThemeManager:ApplyToTab(Tabs["UI Settings"])

        pcall(function()
            SaveManager:LoadAutoloadConfig()
        end)
    end)

    Library:SetWatermark(string.format("Murder Duels | Skeet Edition | %s | [%s]", currentLang, (_G.MD_MenuToggleKey and _G.MD_MenuToggleKey.Name) or "RightControl"))
    Library:SetWatermarkVisibility(true)
end

-- ==================== 9. GLOBAL KEYBIND LISTENER ====================
table.insert(Connections, UserInputService.InputBegan:Connect(function(input, gpe)
    if isListeningForMenuKey then
        if input.UserInputType == Enum.UserInputType.Keyboard then
            _G.MD_MenuToggleKey = input.KeyCode
            isListeningForMenuKey = false
            if menuKeyLabelRef then
                menuKeyLabelRef:SetText(T("MenuKey") .. ": [" .. input.KeyCode.Name .. "]")
            end
            Library:SetWatermark(string.format("Murder Duels | Skeet Edition | %s | [%s]", currentLang, input.KeyCode.Name))
            Library:Notify(T("KeybindUpdated") .. ": " .. input.KeyCode.Name, 3)
        end
        return
    end

    if input.UserInputType == Enum.UserInputType.Keyboard then
        local targetKey = _G.MD_MenuToggleKey or Enum.KeyCode.RightControl
        if input.KeyCode == targetKey then
            Library:Toggle()
        end
    end
end))

-- Initialize Menu
buildMenu()

-- Cleanup Handler
_G.MD_Running = true
_G.MurderDuelsCleanup = function()
    isAlive = false
    _G.MD_Running = false
    LocalPlayer:SetAttribute("MouseUnlocked", nil)
    resetAntiAim()
    thirdPersonEnabled = false
    applyNativeCamera()

    customAmbienceEnabled = false
    applyAmbience()

    pcall(function()
        if originalRevolverSkin then
            LocalPlayer:SetAttribute("RevolverSkin", originalRevolverSkin)
            LocalPlayer:SetAttribute("RevolverName", originalRevolverSkin)
        end
        if originalKnifeSkin then
            LocalPlayer:SetAttribute("KnifeSkin", originalKnifeSkin)
            LocalPlayer:SetAttribute("KnifeName", originalKnifeSkin)
        end
    end)

    pcall(function()
        local rs = game:GetService("ReplicatedStorage")
        local revTiming = require(rs.Shared.RevolverTiming)
        local knifeTiming = require(rs.Shared.KnifeTiming)
        revTiming.SHOT_COOLDOWN = 2
        revTiming.RELOAD_SOUND_FALLBACK = 0.8
        knifeTiming.THROW_COOLDOWN = 0.3
        knifeTiming.HOLD_TO_THROW_SEC = 0.2
        knifeTiming.CHARGE_DUR = 0.5
    end)

    if fovCircle then
        pcall(function() fovCircle:Remove() end)
        fovCircle = nil
    end

    if legitFovCircle then
        pcall(function() legitFovCircle:Remove() end)
        legitFovCircle = nil
    end

    if autoPeekVisual then
        pcall(function() autoPeekVisual:Destroy() end)
        autoPeekVisual = nil
    end
    autoPeekAnchor = nil
    autoPeekState = "IDLE"

    if targetLine then
        pcall(function() targetLine:Remove() end)
        targetLine = nil
    end

    for _, l in pairs(crosshairLines) do
        pcall(function() l:Remove() end)
    end
    crosshairLines = {}

    for _, d in pairs(drawingCache) do
        pcall(function() d.box:Remove() end)
        pcall(function() d.line:Remove() end)
        pcall(function() d.dot:Remove() end)
    end
    drawingCache = {}

    -- Cleanup active bullet tracers and markers from Camera and Bin
    for _, container in ipairs({ workspace.CurrentCamera, workspace:FindFirstChild("Bin") }) do
        if container then
            for _, child in ipairs(container:GetChildren()) do
                if child.Name == "MD_BulletTracer" or child.Name == "MD_ImpactDot" or child.Name == "MD_AutoPeekMarker" then
                    pcall(function() child:Destroy() end)
                end
            end
        end
    end

    for _, conn in ipairs(Connections) do
        if conn and conn.Disconnect then conn:Disconnect() end
    end
    clearAllEsp()

    if fullbrightEnabled then
        Lighting.Brightness = origLighting.Brightness
        Lighting.ClockTime = origLighting.ClockTime
        Lighting.FogEnd = origLighting.FogEnd
        Lighting.GlobalShadows = origLighting.GlobalShadows
    end

    -- Cleanup Skin Changer Viewports & restore hotbar icons & attributes
    pcall(function()
        local playerGui = LocalPlayer:FindFirstChild("PlayerGui")
        local inMatchUI = playerGui and playerGui:FindFirstChild("InMatchUI")
        local abilities = inMatchUI and inMatchUI:FindFirstChild("Abilities")
        if abilities then
            for _, slotName in ipairs({ "Knife", "Gun" }) do
                local slot = abilities:FindFirstChild(slotName)
                if slot then
                    local vp = slot:FindFirstChild("MD_SkinViewport")
                    if vp then pcall(function() vp:Destroy() end) end
                    local icon = slot:FindFirstChild("WeaponIcon")
                    if icon then icon.ImageTransparency = 0 end
                end
            end
        end
    end)
    if originalRevolverSkin then
        LocalPlayer:SetAttribute("RevolverSkin", originalRevolverSkin)
    end
    if originalKnifeSkin then
        LocalPlayer:SetAttribute("KnifeSkin", originalKnifeSkin)
    end

    pcall(function() Library:Unload() end)
    _G.MurderDuelsCleanup = nil
    _G.MD_Unload = nil
end
_G.MD_Unload = _G.MurderDuelsCleanup

Library:Notify(currentLang == "RU" and ("Murder Duels Skeet Hub загружен! [" .. ((_G.MD_MenuToggleKey and _G.MD_MenuToggleKey.Name) or "RightControl") .. "]") or ("Murder Duels Skeet Hub loaded! [" .. ((_G.MD_MenuToggleKey and _G.MD_MenuToggleKey.Name) or "RightControl") .. "]"), 5)

Features & Information

this script built by gemini 3.8 it have silent aim, bhop, antiaim, third person, esp and other stuff maybe not optimized but
#murder#silent#rage#hvh#opensource

Community Comments (0)

No comments yet for this script.

More Scripts for Murder Duels