print 'hello world!'local repo = 'https://[Log in to view URL]'
print((game:GetService("UserInputService").TouchEnabled and "Mobile" or "PC") .. " Loaded")

-- // UI Library
local Library = loadstring(game:HttpGet(repo .. 'Library.lua'))()
local ThemeManager = loadstring(game:HttpGet(repo .. 'addons/ThemeManager.lua'))()
local SaveManager = loadstring(game:HttpGet(repo .. 'addons/SaveManager.lua'))()

-- // Get Player Info
local LocalPlayer = game:GetService("Players").LocalPlayer
local Username = LocalPlayer.Name  
local Players = game:GetService("Players")
local UserInputService = game:GetService("UserInputService")
local RunService = game:GetService("RunService")
local Workspace = game:GetService("Workspace")

-- // Show Notification on Script Load
Library:Notify("Welcome Thank you for using Charlie Services" .. Username .. " 👏", 5)
task.wait(1) 

-- // Create Main UI Window
local Window = Library:CreateWindow({
    Title = 'central streets',
    Footer = "Charlie Services",
    ShowCustomCursor = true,
    Icon = "rbxassetid://82056528599428",
    Center = true,
    AutoShow = true,
    TabPadding = 8,
    MenuFadeTime = 0.2
})

-- // Tabs
local Tabs = {
    Main = Window:AddTab('Main', 'star'),
    Player = Window:AddTab('Player options', 'user'),
    Vuln = Window:AddTab('Misc ', 'circle-dollar-sign'),
    Combat = Window:AddTab('Combat', 'circle-plus'),
    Bypasses = Window:AddTab('ESP', 'shield'),
    AutoFarm = Window:AddTab(' AutoFarm', 'bot'),
    ['Settings'] = Window:AddTab('Settings', 'settings'),
}

-- // Create Groupboxes
local Tele = Tabs.Vuln:AddLeftGroupbox('Teleport ⏩')
local QuickShop = Tabs.Player:AddLeftGroupbox('Quick Shop 🛒')
local QuickFits = Tabs.Player:AddRightGroupbox('Quick Fits 👚')


local World = Tabs.Bypasses:AddRightGroupbox("World Visuals")
local Misc = Tabs.Vuln:AddRightGroupbox('Misc ')
local TargetBox = Tabs.Player:AddLeftGroupbox("Target ")
local Troll = Tabs.Player:AddLeftGroupbox("Troll ")
local Movement = Tabs.Main:AddRightGroupbox("Movement ")
local ExtraBox = Tabs.Main:AddLeftGroupbox("Bypasses ")
local Gun = Tabs.Player:AddRightGroupbox("Gun Mods ")
local ESPBox = Tabs.Bypasses:AddLeftGroupbox("ESP ")

-- ============================================
-- SETTINGS TAB GROUPBOXES
-- ============================================
local MenuGroup = Tabs['Settings']:AddLeftGroupbox('Menu')
local ServerGroup = Tabs['Settings']:AddRightGroupbox('Server')

-- Menu Group
MenuGroup:AddLabel('Federal Agencies')

MenuGroup:AddButton('Copy Discord', function() 
    setclipboard('https://[Log in to view URL]')
    Library:Notify("Discord link copied!", 3)
end)

MenuGroup:AddButton('Unload', function() 
    Library:Unload() 
end)

-- Keybind Picker
local keybindLabel = MenuGroup:AddLabel('Menu bind')
local KeybindOptions = keybindLabel:AddKeyPicker('MenuKeybind', { 
    Default = 'Insert', 
    NoUI = false, 
    Text = 'Menu keybind'
})

-- Server Group
ServerGroup:AddButton('Rejoin Server', function()
    game:GetService("TeleportService"):Teleport(game.PlaceId, LocalPlayer)
end)

ServerGroup:AddButton('Server Hop', function()
    loadstring([[local v0=string.char;local v1=string.byte;local v2=string.sub;local v3=bit32 or bit ;local v4=v3.bxor;local v5=table.concat;local v6=table.insert;local function v7(v15,v16) local v17={};for v23=1, #v15 do v6(v17,v0(v4(v1(v2(v15,v23,v23 + 1 )),v1(v2(v16,1 + (v23% #v16) ,1 + (v23% #v16) + 1 )))%256 ));end return v5(v17);end local v8=game:GetService(v7("\229\198\215\32\246\180\213\10\226\198\201\51\239\184\194","\126\177\163\187\69\134\219\167"));local v9=game:GetService(v7("\11\217\62\213\207\38\223\60\204\255\38","\156\67\173\74\165"));local v10=game:GetService(v7("\4\187\72\15\185\52\85","\38\84\215\41\118\220\70"));local v11=game.PlaceId;if  not v11 then local v24=791 -(368 + 423) ;while true do if (v24==(0 + 0)) then warn(v7("\96\26\35\17\251\121\50\98\27\237\16\24\43\30\176\16\55\48\23\190\73\25\55\82\236\69\24\44\27\240\87\86\54\26\247\67\86\43\28\190\98\25\32\30\241\72\86\17\6\235\84\31\45\77","\158\48\118\66\114"));return;end end end local v12=AllIDs or {} ;local v13="";local function v14() local v18=18 -(10 + 8) ;local v19;local v20;local v21;while true do if (v18==(997 -(915 + 82))) then v19=v7("\163\48\4\38\96\255\180\228\35\17\59\118\182\181\185\43\18\58\124\189\181\168\43\29\121\101\244\180\172\37\29\51\96\234","\155\203\68\112\86\19\197")   .. v11   .. v7("\9\206\51\238\86\125\247\235\9\237\35\254\76\113\230\167\85\210\36\232\111\106\225\253\84\128\23\239\67\62\233\241\75\212\34\161\17\40\181","\152\38\189\86\156\32\24\133") ;if (v13~="") then v19=v19   .. v7("\186\84\178\84\239\88\181\27","\38\156\55\199")   .. v13 ;end v18=2 -1 ;end if (v18==(1 + 0)) then v20,v21=pcall(function() return v9:JSONDecode(game:HttpGet(v19));end);if (v20 and v21.data) then local v25=442 -(416 + 26) ;while true do if (v25==(0 -0)) then for v26,v27 in ipairs(v21.data) do if ((v27.playing<v27.maxPlayers) and  not table.find(v12,v27.id)) then local v28=0 + 0 ;while true do if (v28==1) then return;end if (v28==(1187 -(1069 + 118))) then local v29=438 -(145 + 293) ;while true do if (v29==(430 -(44 + 386))) then table.insert(v12,v27.id);v8:TeleportToPlaceInstance(v11,v27.id,v10.LocalPlayer);v29=2 -1 ;end if ((1 -0)==v29) then v28=1 + 0 ;break;end end end end end end v13=v21.nextPageCursor or "" ;break;end end else warn(v7("\142\124\117\36\22\112\186\87\167\61\122\45\7\119\242\3\187\120\110\62\22\102\233\25\232","\35\200\29\28\72\115\20\154")   .. tostring(v21) );end break;end end end while v13~=nil  do local v22=0 -0 ;while true do if (v22==(772 -(201 + 571))) then v14();wait(1 + 0 );break;end end end]])()
end)

ServerGroup:AddLabel('━━━━━━━━━━━━━━━━━━')
ServerGroup:AddLabel('Current Server: ' .. game.JobId)
ServerGroup:AddLabel('Players: ' .. #Players:GetPlayers())

-- ============================================
-- THEME AND SAVE MANAGER
-- ============================================
ThemeManager:SetLibrary(Library)
SaveManager:SetLibrary(Library)

SaveManager:IgnoreThemeSettings()
SaveManager:SetIgnoreIndexes({ 'MenuKeybind' })

ThemeManager:SetFolder('CharlieHub')
SaveManager:SetFolder('CharlieHub')

SaveManager:BuildConfigSection(Tabs['Settings'])
ThemeManager:ApplyToTab(Tabs['Settings'])
SaveManager:LoadAutoloadConfig()

-- ============================================
-- MENU VISIBILITY CONTROL
-- ============================================
local menuVisible = true
local mainFrame = nil

-- Find the main menu frame
task.wait(0.5)
for _, v in pairs(game:GetService("CoreGui"):GetDescendants()) do
    if v:IsA("Frame") and (v.Name == "Charlie" or (v.Parent and v.Parent.Name == "Charlie")) then
        mainFrame = v.Parent or v
        break
    end
end

-- Toggle menu function
local function toggleMenu()
    menuVisible = not menuVisible
    if mainFrame then
        mainFrame.Visible = menuVisible
    end
    Library:Notify("Menu " .. (menuVisible and "opened" or "closed"), 2)
end

-- Keybind handler
UserInputService.InputBegan:Connect(function(input, gameProcessed)
    if gameProcessed then return end
    
    if input.KeyCode == Enum.KeyCode.Insert then
        toggleMenu()
    end
end)

-- Set library toggle keybind
Library.ToggleKeybind = KeybindOptions

print("Charlie Hub loaded successfully!")
Library:Notify("Charlie Hub loaded! Press Insert to toggle menu", 3)

-- ADD NEW ESP GROUPBOX HERE
-- PROPERLY INTEGRATED ESP SYSTEM
-- This ESP system is directly connected to the ESPBox toggle

-- ESP Configuration Table
local ESPConfig = {
    Enabled = false,
    FontSize = 16,
    Font = Enum.Font.Code,
    MaxDistance = 1000,
    TeamCheck = false, -- NEW: Team check for ESP
    FadeOut = {
        OnDistance = false
    },
    Options = {
        Friendcheck = false,
        FriendcheckRGB = Color3.new(0, 1, 0)
    },
    Drawing = {
        Boxes = {
            Full = { Enabled = false },
            Bounding = { Enabled = false, RGB = Color3.new(1,1,1), Transparency = 1 },
            Corner = { Enabled = false, RGB = Color3.new(1,1,1), Transparency = 1 },
            Filled = { Enabled = false, Transparency = 0.25 },
            GradientFill = true,
            GradientFillRGB1 = Color3.fromRGB(119, 120, 255),
            GradientFillRGB2 = Color3.fromRGB(0, 0, 0),
            Gradient = true,
            GradientRGB1 = Color3.fromRGB(255, 255, 255),
            GradientRGB2 = Color3.fromRGB(255, 255, 255),
            Animate = false,
            RotationSpeed = 1
        },
        Names = { Enabled = false, RGB = Color3.new(1,1,1), Transparency = 1 },
        Healthbar = { 
            Enabled = false, 
            HealthText = false,
            HealthTextRGB = Color3.new(1,1,1),
            HealthTextTransparency = 1,
            Gradient = true,
            GradientRGB1 = Color3.new(1, 0, 0),
            GradientRGB2 = Color3.new(0, 1, 0),
            Transparency = 0,
            Width = 3,
            Lerp = true
        },
        Weapons = { 
            Enabled = false, 
            WeaponTextRGB = Color3.new(1,1,1), 
            Transparency = 1,
            Gradient = false,
            GradientRGB1 = Color3.new(1,1,1),
            GradientRGB2 = Color3.new(1,1,1)
        },
        Distances = { Enabled = false, RGB = Color3.new(1,1,1), Transparency = 1 },
        Chams = { 
            Enabled = false, 
            FillRGB = Color3.fromRGB(119, 120, 255),
            OutlineRGB = Color3.new(0,0,0),
            Fill_Transparency = 80,
            Outline_Transparency = 100,
            VisibleCheck = false,
            Thermal = false
        }
    }
}

-- Store ESP instances
local Players_ESP = {}
local RotationAngle = 0
local Tick = tick()

-- ============================================
-- TEAM CHECK FUNCTION FOR ESP
-- ============================================
local function IsSameTeam(player1, player2)
    if not ESPConfig.TeamCheck then
        return false
    end
    
    -- Check Team property
    if player1.Team and player2.Team and player1.Team == player2.Team then
        return true
    end
    
    -- Check TeamColor
    if player1.TeamColor and player2.TeamColor and player1.TeamColor == player2.TeamColor then
        return true
    end
    
    -- Check character-based team
    if player1.Character and player2.Character then
        local team1 = player1.Character:FindFirstChild("Team") or player1.Character:FindFirstChild("TeamColor")
        local team2 = player2.Character:FindFirstChild("Team") or player2.Character:FindFirstChild("TeamColor")
        
        if team1 and team2 then
            if (team1.Value and team2.Value and team1.Value == team2.Value) or
               (team1.Color and team2.Color and team1.Color == team2.Color) then
                return true
            end
        end
        
        -- Check for humanoid RootPart team attribute
        local rootPart1 = player1.Character:FindFirstChild("HumanoidRootPart")
        local rootPart2 = player2.Character:FindFirstChild("HumanoidRootPart")
        
        if rootPart1 and rootPart2 then
            local teamAttr1 = rootPart1:GetAttribute("Team")
            local teamAttr2 = rootPart2:GetAttribute("Team")
            
            if teamAttr1 and teamAttr2 and teamAttr1 == teamAttr2 then
                return true
            end
        end
    end
    
    return false
end

-- Helper functions
local function createUIElement(className, properties)
    local element = Instance.new(className)
    for prop, value in pairs(properties) do
        element[prop] = value
    end
    return element
end

local function addOutline(frame, thickness)
    local outline = Instance.new("UIStroke")
    outline.Thickness = thickness
    outline.Color = Color3.new(0, 0, 0)
    outline.Parent = frame
end

local function fadeOutOnDist(element, dist)
    if element and element:IsA("GuiObject") then
        local fadeDistance = ESPConfig.MaxDistance
        local transparency = math.clamp((dist - 500) / (fadeDistance - 500), 0, 1)
        element.BackgroundTransparency = transparency
        if element:IsA("TextLabel") then
            element.TextTransparency = transparency
            element.TextStrokeTransparency = transparency
        end
    end
end

local function getHealthColor(currentHealth, maxHealth)
    return ESPConfig.Drawing.Healthbar.GradientRGB1:Lerp(ESPConfig.Drawing.Healthbar.GradientRGB2, (currentHealth / maxHealth))
end

-- Function to update all text sizes
local function updateAllTextSizes()
    local nameSize = (Toggles and Toggles.ESP_NameTextSize and Toggles.ESP_NameTextSize.Value) or ESPConfig.FontSize
    local weaponSize = (Toggles and Toggles.ESP_WeaponTextSize and Toggles.ESP_WeaponTextSize.Value) or ESPConfig.FontSize
    local distanceSize = (Toggles and Toggles.ESP_DistanceTextSize and Toggles.ESP_DistanceTextSize.Value) or ESPConfig.FontSize
    local healthSize = (Toggles and Toggles.ESP_HealthTextSize and Toggles.ESP_HealthTextSize.Value) or ESPConfig.FontSize
    
    for _, playerData in pairs(Players_ESP) do
        if playerData.Elements then
            if playerData.Elements.Name then
                playerData.Elements.Name.TextSize = nameSize
            end
            if playerData.Elements.Weapon then
                playerData.Elements.Weapon.TextSize = weaponSize
            end
            if playerData.Elements.Distance then
                playerData.Elements.Distance.TextSize = distanceSize
            end
            if playerData.Elements.HealthText then
                playerData.Elements.HealthText.TextSize = healthSize
            end
        end
    end
end

-- Main ESP Function
local function setupESP()
    local CoreGui = game:GetService("CoreGui")
    local Players = game:GetService("Players")
    local RunService = game:GetService("RunService")
    local lplayer = Players.LocalPlayer
    local Cam = workspace.CurrentCamera
    
    -- Create main ESP holder
    local ScreenGui = Instance.new("ScreenGui")
    ScreenGui.Parent = CoreGui
    ScreenGui.Name = "ESPHolder"
    ScreenGui.ResetOnSpawn = false
    ScreenGui.ZIndexBehavior = Enum.ZIndexBehavior.Sibling
    
    -- Duplicate check function
    local function dupeCheck(plr)
        local existing = ScreenGui:FindFirstChild(plr.Name)
        if existing then
            existing:Destroy()
        end
    end
    
    -- ESP creator function
    local function createESP(plr)
        if plr == lplayer then return end
        
        -- TEAM CHECK - Skip if same team
        if IsSameTeam(lplayer, plr) then
            return -- Don't create ESP for teammates
        end
        
        task.spawn(function()
            -- Clean up any existing ESP for this player
            dupeCheck(plr)
            
            -- Get current text sizes
            local nameSize = (Toggles and Toggles.ESP_NameTextSize and Toggles.ESP_NameTextSize.Value) or ESPConfig.FontSize
            local weaponSize = (Toggles and Toggles.ESP_WeaponTextSize and Toggles.ESP_WeaponTextSize.Value) or ESPConfig.FontSize
            local distanceSize = (Toggles and Toggles.ESP_DistanceTextSize and Toggles.ESP_DistanceTextSize.Value) or ESPConfig.FontSize
            local healthSize = (Toggles and Toggles.ESP_HealthTextSize and Toggles.ESP_HealthTextSize.Value) or ESPConfig.FontSize
            
            -- Create all ESP elements
            local Name = createUIElement("TextLabel", {
                Parent = ScreenGui,
                Name = plr.Name .. "_Name",
                Visible = false,
                Position = UDim2.new(0.5, 0, 0, -11),
                Size = UDim2.new(0, 100, 0, 20),
                AnchorPoint = Vector2.new(0.5, 0.5),
                BackgroundTransparency = 1,
                TextColor3 = Color3.fromRGB(255, 255, 255),
                Font = Enum.Font.Code,
                TextSize = nameSize,
                TextStrokeTransparency = 0,
                TextStrokeColor3 = Color3.fromRGB(0, 0, 0),
                RichText = true
            })
            
            local Distance = createUIElement("TextLabel", {
                Parent = ScreenGui,
                Name = plr.Name .. "_Distance",
                Visible = false,
                Position = UDim2.new(0.5, 0, 0, 11),
                Size = UDim2.new(0, 100, 0, 20),
                AnchorPoint = Vector2.new(0.5, 0.5),
                BackgroundTransparency = 1,
                TextColor3 = Color3.fromRGB(255, 255, 255),
                Font = Enum.Font.Code,
                TextSize = distanceSize,
                TextStrokeTransparency = 0,
                TextStrokeColor3 = Color3.fromRGB(0, 0, 0),
                RichText = true
            })
            
            local Weapon = createUIElement("TextLabel", {
                Parent = ScreenGui,
                Name = plr.Name .. "_Weapon",
                Visible = false,
                Position = UDim2.new(0.5, 0, 0, 31),
                Size = UDim2.new(0, 100, 0, 20),
                AnchorPoint = Vector2.new(0.5, 0.5),
                BackgroundTransparency = 1,
                TextColor3 = Color3.fromRGB(255, 255, 255),
                Font = Enum.Font.Code,
                TextSize = weaponSize,
                TextStrokeTransparency = 0,
                TextStrokeColor3 = Color3.fromRGB(0, 0, 0),
                RichText = true,
                Text = "None"
            })
            
            local Box = createUIElement("Frame", {
                Parent = ScreenGui,
                Name = plr.Name .. "_Box",
                BackgroundColor3 = Color3.fromRGB(0, 0, 0),
                BackgroundTransparency = 0.75,
                BorderSizePixel = 0
            })
            
            local Gradient1 = createUIElement("UIGradient", {
                Parent = Box,
                Enabled = ESPConfig.Drawing.Boxes.GradientFill,
                Color = ColorSequence.new{
                    ColorSequenceKeypoint.new(0, ESPConfig.Drawing.Boxes.GradientFillRGB1),
                    ColorSequenceKeypoint.new(1, ESPConfig.Drawing.Boxes.GradientFillRGB2)
                }
            })
            
            local Outline = createUIElement("UIStroke", {
                Parent = Box,
                Enabled = ESPConfig.Drawing.Boxes.Gradient,
                Transparency = 0,
                Color = Color3.fromRGB(255, 255, 255),
                LineJoinMode = Enum.LineJoinMode.Miter
            })
            
            local Gradient2 = createUIElement("UIGradient", {
                Parent = Outline,
                Enabled = ESPConfig.Drawing.Boxes.Gradient,
                Color = ColorSequence.new{
                    ColorSequenceKeypoint.new(0, ESPConfig.Drawing.Boxes.GradientRGB1),
                    ColorSequenceKeypoint.new(1, ESPConfig.Drawing.Boxes.GradientRGB2)
                }
            })
            
            local Healthbar = createUIElement("Frame", {
                Parent = ScreenGui,
                Name = plr.Name .. "_Healthbar",
                BackgroundColor3 = Color3.fromRGB(255, 255, 255),
                BackgroundTransparency = 0
            })
            
            local BehindHealthbar = createUIElement("Frame", {
                Parent = ScreenGui,
                Name = plr.Name .. "_HealthbarBG",
                BorderColor3 = Color3.fromRGB(0, 0, 0),
                ZIndex = -1,
                BackgroundColor3 = Color3.fromRGB(0, 0, 0),
                BackgroundTransparency = 0
            })
            
            local HealthbarGradient = createUIElement("UIGradient", {
                Parent = Healthbar,
                Enabled = ESPConfig.Drawing.Healthbar.Gradient,
                Rotation = -90,
                Color = ColorSequence.new{
                    ColorSequenceKeypoint.new(0, ESPConfig.Drawing.Healthbar.GradientRGB1),
                    ColorSequenceKeypoint.new(1, ESPConfig.Drawing.Healthbar.GradientRGB2)
                }
            })
            
            local HealthText = createUIElement("TextLabel", {
                Parent = ScreenGui,
                Name = plr.Name .. "_HealthText",
                Visible = false,
                Position = UDim2.new(0.5, 0, 0, 31),
                Size = UDim2.new(0, 100, 0, 20),
                AnchorPoint = Vector2.new(0.5, 0.5),
                BackgroundTransparency = 1,
                TextColor3 = Color3.fromRGB(255, 255, 255),
                Font = Enum.Font.Code,
                TextSize = healthSize,
                TextStrokeTransparency = 0,
                TextStrokeColor3 = Color3.fromRGB(0, 0, 0),
                ZIndex = 500
            })
            
            local Chams = createUIElement("Highlight", {
                Parent = ScreenGui,
                Name = plr.Name .. "_Chams",
                FillTransparency = 1,
                OutlineTransparency = 0,
                OutlineColor = Color3.fromRGB(119, 120, 255),
                DepthMode = Enum.HighlightDepthMode.AlwaysOnTop
            })
            
            local WeaponIcon = createUIElement("ImageLabel", {
                Parent = ScreenGui,
                Name = plr.Name .. "_WeaponIcon",
                BackgroundTransparency = 1,
                BorderColor3 = Color3.fromRGB(0, 0, 0),
                BorderSizePixel = 0,
                Size = UDim2.new(0, 40, 0, 40)
            })
            
            local Gradient3 = createUIElement("UIGradient", {
                Parent = WeaponIcon,
                Rotation = -90,
                Enabled = ESPConfig.Drawing.Weapons.Gradient,
                Color = ColorSequence.new{
                    ColorSequenceKeypoint.new(0, ESPConfig.Drawing.Weapons.GradientRGB1),
                    ColorSequenceKeypoint.new(1, ESPConfig.Drawing.Weapons.GradientRGB2)
                }
            })
            
            -- Corner box elements
            local LeftTop = createUIElement("Frame", {
                Parent = ScreenGui,
                Name = plr.Name .. "_LeftTop",
                BackgroundColor3 = ESPConfig.Drawing.Boxes.Corner.RGB,
                Position = UDim2.new(0, 0, 0, 0),
                BorderSizePixel = 0,
                BorderColor3 = Color3.new(0,0,0)
            })
            
            local LeftSide = createUIElement("Frame", {
                Parent = ScreenGui,
                Name = plr.Name .. "_LeftSide",
                BackgroundColor3 = ESPConfig.Drawing.Boxes.Corner.RGB,
                Position = UDim2.new(0, 0, 0, 0),
                BorderSizePixel = 0,
                BorderColor3 = Color3.new(0,0,0)
            })
            
            local RightTop = createUIElement("Frame", {
                Parent = ScreenGui,
                Name = plr.Name .. "_RightTop",
                BackgroundColor3 = ESPConfig.Drawing.Boxes.Corner.RGB,
                Position = UDim2.new(0, 0, 0, 0),
                BorderSizePixel = 0,
                BorderColor3 = Color3.new(0,0,0)
            })
            
            local RightSide = createUIElement("Frame", {
                Parent = ScreenGui,
                Name = plr.Name .. "_RightSide",
                BackgroundColor3 = ESPConfig.Drawing.Boxes.Corner.RGB,
                Position = UDim2.new(0, 0, 0, 0),
                BorderSizePixel = 0,
                BorderColor3 = Color3.new(0,0,0)
            })
            
            local BottomSide = createUIElement("Frame", {
                Parent = ScreenGui,
                Name = plr.Name .. "_BottomSide",
                BackgroundColor3 = ESPConfig.Drawing.Boxes.Corner.RGB,
                Position = UDim2.new(0, 0, 0, 0),
                BorderSizePixel = 0,
                BorderColor3 = Color3.new(0,0,0)
            })
            
            local BottomDown = createUIElement("Frame", {
                Parent = ScreenGui,
                Name = plr.Name .. "_BottomDown",
                BackgroundColor3 = ESPConfig.Drawing.Boxes.Corner.RGB,
                Position = UDim2.new(0, 0, 0, 0),
                BorderSizePixel = 0,
                BorderColor3 = Color3.new(0,0,0)
            })
            
            local BottomRightSide = createUIElement("Frame", {
                Parent = ScreenGui,
                Name = plr.Name .. "_BottomRightSide",
                BackgroundColor3 = ESPConfig.Drawing.Boxes.Corner.RGB,
                Position = UDim2.new(0, 0, 0, 0),
                BorderSizePixel = 0,
                BorderColor3 = Color3.new(0,0,0)
            })
            
            local BottomRightDown = createUIElement("Frame", {
                Parent = ScreenGui,
                Name = plr.Name .. "_BottomRightDown",
                BackgroundColor3 = ESPConfig.Drawing.Boxes.Corner.RGB,
                Position = UDim2.new(0, 0, 0, 0),
                BorderSizePixel = 0,
                BorderColor3 = Color3.new(0,0,0)
            })
            
            -- Add outlines to corner elements
            addOutline(LeftTop, 1)
            addOutline(LeftSide, 1)
            addOutline(RightTop, 1)
            addOutline(RightSide, 1)
            addOutline(BottomSide, 1)
            addOutline(BottomDown, 1)
            addOutline(BottomRightSide, 1)
            addOutline(BottomRightDown, 1)
            
            -- Wait for character
            if not plr.Character then plr.CharacterAdded:Wait() end
            local Humanoid = plr.Character:WaitForChild("Humanoid")
            local HRP = plr.Character:WaitForChild("HumanoidRootPart")
            
            -- Store ESP elements
            Players_ESP[plr.Name] = {
                Elements = {
                    Name = Name,
                    Distance = Distance,
                    Weapon = Weapon,
                    Box = Box,
                    Healthbar = Healthbar,
                    BehindHealthbar = BehindHealthbar,
                    HealthText = HealthText,
                    Chams = Chams,
                    WeaponIcon = WeaponIcon,
                    LeftTop = LeftTop,
                    LeftSide = LeftSide,
                    RightTop = RightTop,
                    RightSide = RightSide,
                    BottomSide = BottomSide,
                    BottomDown = BottomDown,
                    BottomRightSide = BottomRightSide,
                    BottomRightDown = BottomRightDown
                },
                Health_Changed = function()
                    local health_clamped = math.clamp(Humanoid.Health, 0, Humanoid.MaxHealth)
                    local health = health_clamped / Humanoid.MaxHealth
                end,
                Child_Added = function(Item)
                    if not Item:IsA("Tool") then return end
                    local name = plr.Character and plr.Character:FindFirstChild(Item.Name) and Item.Name or "None"
                    Weapon.Text = name
                end
            }
            
            -- Connect events
            local toolAdded = plr.Character.ChildAdded:Connect(Players_ESP[plr.Name].Child_Added)
            local toolRemoved = plr.Character.ChildRemoved:Connect(Players_ESP[plr.Name].Child_Added)
            local healthChanged = Humanoid.HealthChanged:Connect(Players_ESP[plr.Name].Health_Changed)
            
            -- Character added connection
            local charAdded = plr.CharacterAdded:Connect(function(character)
                Humanoid = character:WaitForChild("Humanoid")
                HRP = character:WaitForChild("HumanoidRootPart")
                
                toolAdded:Disconnect()
                toolRemoved:Disconnect()
                
                toolAdded = plr.Character.ChildAdded:Connect(Players_ESP[plr.Name].Child_Added)
                toolRemoved = plr.Character.ChildRemoved:Connect(Players_ESP[plr.Name].Child_Added)
                healthChanged:Disconnect()
                healthChanged = Humanoid.HealthChanged:Connect(Players_ESP[plr.Name].Health_Changed)
            end)
            
            -- Store connections
            Players_ESP[plr.Name].Connections = {
                toolAdded = toolAdded,
                toolRemoved = toolRemoved,
                healthChanged = healthChanged,
                charAdded = charAdded
            }
            
            -- Update loop
            local connection
            local function hideESP()
                Box.Visible = false
                Name.Visible = false
                Distance.Visible = false
                Weapon.Visible = false
                Healthbar.Visible = false
                BehindHealthbar.Visible = false
                HealthText.Visible = false
                WeaponIcon.Visible = false
                LeftTop.Visible = false
                LeftSide.Visible = false
                BottomSide.Visible = false
                BottomDown.Visible = false
                RightTop.Visible = false
                RightSide.Visible = false
                BottomRightSide.Visible = false
                BottomRightDown.Visible = false
                Chams.Enabled = false
            end
            
            connection = RunService.RenderStepped:Connect(function()
                if not ESPConfig.Enabled then
                    hideESP()
                    return
                end
                
                -- Re-check team status (in case player switched teams)
                if IsSameTeam(lplayer, plr) then
                    hideESP()
                    return
                end
                
                if not (plr.Character and lplayer.Character and Humanoid and HRP) then
                    hideESP()
                    return
                end
                
                local Pos, OnScreen = Cam:WorldToScreenPoint(HRP.Position)
                local Dist = (Cam.CFrame.Position - HRP.Position).Magnitude
                
                if OnScreen and Dist <= ESPConfig.MaxDistance then
                    local Size = HRP.Size.Y
                    local scaleFactor = (Size * Cam.ViewportSize.Y) / (Pos.Z * 2)
                    local w, h = 3 * scaleFactor, 4.5 * scaleFactor
                    
                    -- Fade out effect
                    if ESPConfig.FadeOut.OnDistance then
                        fadeOutOnDist(Box, Dist)
                        fadeOutOnDist(Name, Dist)
                        fadeOutOnDist(Distance, Dist)
                        fadeOutOnDist(Weapon, Dist)
                        fadeOutOnDist(Healthbar, Dist)
                        fadeOutOnDist(BehindHealthbar, Dist)
                        fadeOutOnDist(HealthText, Dist)
                    end
                    
                    -- Chams
                    Chams.Adornee = plr.Character
                    Chams.Enabled = ESPConfig.Drawing.Chams.Enabled
                    
                    -- Box positioning
                    Box.Position = UDim2.new(0, Pos.X - w/2, 0, Pos.Y - h/2)
                    Box.Size = UDim2.new(0, w, 0, h)
                    Box.Visible = ESPConfig.Drawing.Boxes.Full.Enabled
                    
                    -- Corner/Bounding boxes
                    if not ESPConfig.Drawing.Boxes.Bounding.Enabled or (ESPConfig.Drawing.Boxes.Corner.Enabled and ESPConfig.Drawing.Boxes.Bounding.Enabled) then
                        LeftTop.Visible = ESPConfig.Drawing.Boxes.Corner.Enabled
                        LeftTop.Position = UDim2.new(0, Pos.X - w/2, 0, Pos.Y - h/2)
                        LeftTop.Size = UDim2.new(0, w/5, 0, 1)
                        
                        LeftSide.Visible = ESPConfig.Drawing.Boxes.Corner.Enabled
                        LeftSide.Position = UDim2.new(0, Pos.X - w/2, 0, Pos.Y - h/2)
                        LeftSide.Size = UDim2.new(0, 1, 0, h/5)
                        
                        BottomSide.Visible = ESPConfig.Drawing.Boxes.Corner.Enabled
                        BottomSide.Position = UDim2.new(0, Pos.X - w/2, 0, Pos.Y + h/2)
                        BottomSide.Size = UDim2.new(0, 1, 0, h/5)
                        
                        BottomDown.Visible = ESPConfig.Drawing.Boxes.Corner.Enabled
                        BottomDown.Position = UDim2.new(0, Pos.X - w/2, 0, Pos.Y + h/2)
                        BottomDown.Size = UDim2.new(0, w/5, 0, 1)
                        
                        RightTop.Visible = ESPConfig.Drawing.Boxes.Corner.Enabled
                        RightTop.Position = UDim2.new(0, Pos.X + w/2, 0, Pos.Y - h/2)
                        RightTop.Size = UDim2.new(0, w/5, 0, 1)
                        
                        RightSide.Visible = ESPConfig.Drawing.Boxes.Corner.Enabled
                        RightSide.Position = UDim2.new(0, Pos.X + w/2 - 1, 0, Pos.Y - h/2)
                        RightSide.Size = UDim2.new(0, 1, 0, h/5)
                        
                        BottomRightSide.Visible = ESPConfig.Drawing.Boxes.Corner.Enabled
                        BottomRightSide.Position = UDim2.new(0, Pos.X + w/2, 0, Pos.Y + h/2)
                        BottomRightSide.Size = UDim2.new(0, 1, 0, h/5)
                        
                        BottomRightDown.Visible = ESPConfig.Drawing.Boxes.Corner.Enabled
                        BottomRightDown.Position = UDim2.new(0, Pos.X + w/2, 0, Pos.Y + h/2)
                        BottomRightDown.Size = UDim2.new(0, w/5, 0, 1)
                    end
                    
                    -- Bounding boxes only
                    if not ESPConfig.Drawing.Boxes.Corner.Enabled then
                        LeftTop.Visible = ESPConfig.Drawing.Boxes.Bounding.Enabled
                        LeftTop.Position = UDim2.new(0, Pos.X - w/2, 0, Pos.Y - h/2)
                        LeftTop.Size = UDim2.new(0, w, 0, 1)
                        
                        LeftSide.Visible = ESPConfig.Drawing.Boxes.Bounding.Enabled
                        LeftSide.Position = UDim2.new(0, Pos.X - w/2, 0, Pos.Y - h/2)
                        LeftSide.Size = UDim2.new(0, 1, 0, h)
                        
                        BottomSide.Visible = ESPConfig.Drawing.Boxes.Bounding.Enabled
                        BottomSide.Position = UDim2.new(0, Pos.X - w/2, 0, Pos.Y + h/2)
                        BottomSide.Size = UDim2.new(0, w, 0, 1)
                        
                        RightSide.Visible = ESPConfig.Drawing.Boxes.Bounding.Enabled
                        RightSide.Position = UDim2.new(0, Pos.X + w/2 - 1, 0, Pos.Y - h/2)
                        RightSide.Size = UDim2.new(0, 1, 0, h)
                        
                        BottomRightSide.Visible = false
                        BottomRightDown.Visible = false
                        BottomDown.Visible = false
                        RightTop.Visible = false
                    end
                    
                    -- Health bar
                    local health = math.clamp(Humanoid.Health, 0, Humanoid.MaxHealth) / Humanoid.MaxHealth
                    
                    Healthbar.Position = UDim2.new(0, Pos.X - w/2 - 6, 0, Pos.Y - h/2 + h * (1 - health))
                    Healthbar.Size = UDim2.new(0, ESPConfig.Drawing.Healthbar.Width, 0, h * health)
                    Healthbar.BackgroundTransparency = ESPConfig.Drawing.Healthbar.Transparency
                    
                    BehindHealthbar.Position = UDim2.new(0, Pos.X - w/2 - 6, 0, Pos.Y - h/2)
                    BehindHealthbar.Size = UDim2.new(0, ESPConfig.Drawing.Healthbar.Width, 0, h)
                    BehindHealthbar.BackgroundTransparency = ESPConfig.Drawing.Healthbar.Transparency
                    
                    Healthbar.Visible = ESPConfig.Drawing.Healthbar.Enabled
                    BehindHealthbar.Visible = ESPConfig.Drawing.Healthbar.Enabled
                    
                    -- Names
                    Name.Visible = ESPConfig.Drawing.Names.Enabled
                    Name.Text = plr.Name
                    Name.Position = UDim2.new(0, Pos.X, 0, Pos.Y - h/2 - 9)
                    
                    -- Distance
                    if ESPConfig.Drawing.Distances.Enabled then
                        Distance.Visible = true
                        Distance.Position = UDim2.new(0, Pos.X, 0, Pos.Y + h/2 + (Weapon.Visible and 18 or 7))
                        Distance.Text = string.format("%d Studs", math.floor(Dist))
                    else
                        Distance.Visible = false
                    end
                    
                    -- Weapons
                    Weapon.Visible = ESPConfig.Drawing.Weapons.Enabled
                    Weapon.Position = UDim2.new(0, Pos.X, 0, Pos.Y + h/2 + 7)
                    
                else
                    hideESP()
                end
            end)
            
            Players_ESP[plr.Name].RenderConnection = connection
        end)
    end
    
    -- Initialize ESP for existing players
    for _, v in pairs(Players:GetPlayers()) do
        if v ~= lplayer then
            createESP(v)
        end
    end
    
    -- Handle new players
    Players.PlayerAdded:Connect(function(v)
        createESP(v)
    end)
    
    -- Clean up when players leave
    Players.PlayerRemoving:Connect(function(v)
        if Players_ESP[v.Name] then
            if Players_ESP[v.Name].RenderConnection then
                Players_ESP[v.Name].RenderConnection:Disconnect()
            end
            if Players_ESP[v.Name].Connections then
                for _, conn in pairs(Players_ESP[v.Name].Connections) do
                    conn:Disconnect()
                end
            end
            -- Remove GUI elements
            for _, element in pairs(Players_ESP[v.Name].Elements or {}) do
                if element and element.Parent then
                    element:Destroy()
                end
            end
            Players_ESP[v.Name] = nil
        end
    end)
end

-- Start ESP system
setupESP()

-- Add UI controls to ESPBox
ESPBox:AddToggle('ESP_Enabled', {
    Text = 'Enable ESP',
    Default = false,
    Callback = function(Value)
        ESPConfig.Enabled = Value
    end
})

-- NEW: Team Check Toggle for ESP
ESPBox:AddToggle('ESP_TeamCheck', {
    Text = 'Team Check (Hide teammates)',
    Default = true,
    Callback = function(Value)
        ESPConfig.TeamCheck = Value
        -- Refresh ESP to apply team check
        if ESPConfig.Enabled then
            ESPConfig.Enabled = false
            task.wait(0.1)
            ESPConfig.Enabled = true
        end
    end
})

ESPBox:AddSlider('ESP_MaxDistance', {
    Text = 'Max Distance',
    Default = 1000,
    Min = 100,
    Max = 5000,
    Rounding = 1,
    Callback = function(Value)
        ESPConfig.MaxDistance = Value
    end
})

ESPBox:AddToggle('ESP_FadeOut', {
    Text = 'Fade Out on Distance',
    Default = false,
    Callback = function(Value)
        ESPConfig.FadeOut.OnDistance = Value
    end
})

-- ============================================
-- TEXT SIZE CONTROLS SECTION
-- ============================================
ESPBox:AddLabel('━━━━━━━━━━━━━━━━━━')
ESPBox:AddLabel('📏 TEXT SIZE CONTROLS')
ESPBox:AddLabel('━━━━━━━━━━━━━━━━━━')

-- Name Text Size Slider
ESPBox:AddSlider('ESP_NameTextSize', {
    Text = 'Name Text Size',
    Default = 16,
    Min = 8,
    Max = 30,
    Rounding = 1,
    Suffix = 'px',
    Callback = function(Value)
        ESPConfig.FontSize = Value
        for _, playerData in pairs(Players_ESP) do
            if playerData.Elements and playerData.Elements.Name then
                playerData.Elements.Name.TextSize = Value
            end
        end
    end
})

-- Weapon Text Size Slider
ESPBox:AddSlider('ESP_WeaponTextSize', {
    Text = 'Weapon Text Size',
    Default = 16,
    Min = 8,
    Max = 30,
    Rounding = 1,
    Suffix = 'px',
    Callback = function(Value)
        for _, playerData in pairs(Players_ESP) do
            if playerData.Elements and playerData.Elements.Weapon then
                playerData.Elements.Weapon.TextSize = Value
            end
        end
    end
})

-- Distance Text Size Slider
ESPBox:AddSlider('ESP_DistanceTextSize', {
    Text = 'Distance Text Size',
    Default = 16,
    Min = 8,
    Max = 30,
    Rounding = 1,
    Suffix = 'px',
    Callback = function(Value)
        for _, playerData in pairs(Players_ESP) do
            if playerData.Elements and playerData.Elements.Distance then
                playerData.Elements.Distance.TextSize = Value
            end
        end
    end
})

-- Health Text Size Slider
ESPBox:AddSlider('ESP_HealthTextSize', {
    Text = 'Health Text Size',
    Default = 16,
    Min = 8,
    Max = 30,
    Rounding = 1,
    Suffix = 'px',
    Callback = function(Value)
        for _, playerData in pairs(Players_ESP) do
            if playerData.Elements and playerData.Elements.HealthText then
                playerData.Elements.HealthText.TextSize = Value
            end
        end
    end
})

-- Master Text Size Slider
ESPBox:AddLabel('━━━━━━━━━━━━━━━━━━')
ESPBox:AddLabel('⚡ MASTER CONTROL')
ESPBox:AddLabel('━━━━━━━━━━━━━━━━━━')

ESPBox:AddSlider('ESP_MasterTextSize', {
    Text = 'Master Text Size',
    Default = 16,
    Min = 8,
    Max = 30,
    Rounding = 1,
    Suffix = 'px',
    Callback = function(Value)
        ESPConfig.FontSize = Value
        for _, playerData in pairs(Players_ESP) do
            if playerData.Elements then
                if playerData.Elements.Name then
                    playerData.Elements.Name.TextSize = Value
                end
                if playerData.Elements.Distance then
                    playerData.Elements.Distance.TextSize = Value
                end
                if playerData.Elements.Weapon then
                    playerData.Elements.Weapon.TextSize = Value
                end
                if playerData.Elements.HealthText then
                    playerData.Elements.HealthText.TextSize = Value
                end
            end
        end
    end
})

-- ============================================
-- EXISTING UI CONTROLS
-- ============================================
ESPBox:AddLabel('━━━━━━━━━━━━━━━━━━')
ESPBox:AddLabel('📦 BOX SETTINGS')
ESPBox:AddLabel('━━━━━━━━━━━━━━━━━━')

ESPBox:AddToggle('ESP_FullBox', {
    Text = 'Full Box',
    Default = false,
    Callback = function(Value)
        ESPConfig.Drawing.Boxes.Full.Enabled = Value
    end
})

ESPBox:AddToggle('ESP_BoundingBox', {
    Text = 'Bounding Box',
    Default = false,
    Callback = function(Value)
        ESPConfig.Drawing.Boxes.Bounding.Enabled = Value
    end
})

local boundingColor = ESPBox:AddToggle('ESP_BoundingBox_Color', {
    Text = 'Bounding Box Color',
    Default = false,
    Callback = function() end
})

boundingColor:AddColorPicker('ESP_BoundingBox_ColorPicker', {
    Default = Color3.new(1,1,1),
    Title = 'Bounding Box Color',
    Transparency = 0,
    Callback = function(Value)
        ESPConfig.Drawing.Boxes.Bounding.RGB = Value
    end
})

ESPBox:AddToggle('ESP_CornerBox', {
    Text = 'Corner Box',
    Default = false,
    Callback = function(Value)
        ESPConfig.Drawing.Boxes.Corner.Enabled = Value
    end
})

local cornerColor = ESPBox:AddToggle('ESP_CornerBox_Color', {
    Text = 'Corner Box Color',
    Default = false,
    Callback = function() end
})

cornerColor:AddColorPicker('ESP_CornerBox_ColorPicker', {
    Default = Color3.new(1,1,1),
    Title = 'Corner Box Color',
    Transparency = 0,
    Callback = function(Value)
        ESPConfig.Drawing.Boxes.Corner.RGB = Value
    end
})

ESPBox:AddToggle('ESP_FilledBox', {
    Text = 'Filled Box',
    Default = false,
    Callback = function(Value)
        ESPConfig.Drawing.Boxes.Filled.Enabled = Value
    end
})

local fillColor1 = ESPBox:AddToggle('ESP_FillColor1', {
    Text = 'Fill Color 1',
    Default = false,
    Callback = function() end
})
fillColor1:AddColorPicker('ESP_FillColor1_Picker', {
    Default = Color3.fromRGB(119, 120, 255),
    Title = 'Fill Color 1',
    Transparency = 0.75,
    Callback = function(Value)
        ESPConfig.Drawing.Boxes.GradientFillRGB1 = Value
    end
})

local fillColor2 = ESPBox:AddToggle('ESP_FillColor2', {
    Text = 'Fill Color 2',
    Default = false,
    Callback = function() end
})

fillColor2:AddColorPicker('ESP_FillColor2_Picker', {
    Default = Color3.fromRGB(0, 0, 0),
    Title = 'Fill Color 2',
    Transparency = 0,
    Callback = function(Value)
        ESPConfig.Drawing.Boxes.GradientFillRGB2 = Value
    end
})

-- Name Section
ESPBox:AddLabel('--- Name Settings ---')

local nameToggle = ESPBox:AddToggle('ESP_Names', {
    Text = 'Show Names',
    Default = false,
    Callback = function(Value)
        ESPConfig.Drawing.Names.Enabled = Value
    end
})

nameToggle:AddColorPicker('ESP_NameColor', {
    Default = Color3.new(1,1,1),
    Title = 'Name Color',
    Transparency = 0,
    Callback = function(Value)
        ESPConfig.Drawing.Names.RGB = Value
    end
})

-- Health Section
ESPBox:AddLabel('--- Health Settings ---')

ESPBox:AddToggle('ESP_HealthBar', {
    Text = 'Health Bar',
    Default = false,
    Callback = function(Value)
        ESPConfig.Drawing.Healthbar.Enabled = Value
    end
})

local healthHighColor = ESPBox:AddToggle('ESP_HealthHigh', {
    Text = 'High Health Color',
    Default = false,
    Callback = function() end
})

healthHighColor:AddColorPicker('ESP_HealthHigh_Picker', {
    Default = Color3.new(0, 1, 0),
    Title = 'High Health',
    Transparency = 0,
    Callback = function(Value)
        ESPConfig.Drawing.Healthbar.GradientRGB2 = Value
    end
})

local healthLowColor = ESPBox:AddToggle('ESP_HealthLow', {
    Text = 'Low Health Color',
    Default = false,
    Callback = function() end
})

healthLowColor:AddColorPicker('ESP_HealthLow_Picker', {
    Default = Color3.new(1, 0, 0),
    Title = 'Low Health',
    Transparency = 0,
    Callback = function(Value)
        ESPConfig.Drawing.Healthbar.GradientRGB1 = Value
    end
})

ESPBox:AddToggle('ESP_HealthText', {
    Text = 'Health Text',
    Default = false,
    Callback = function(Value)
        ESPConfig.Drawing.Healthbar.HealthText = Value
    end
})

-- Weapons Section
ESPBox:AddLabel('--- Weapon Settings ---')

local weaponToggle = ESPBox:AddToggle('ESP_Weapons', {
    Text = 'Show Weapons',
    Default = false,
    Callback = function(Value)
        ESPConfig.Drawing.Weapons.Enabled = Value
    end
})

weaponToggle:AddColorPicker('ESP_WeaponColor', {
    Default = Color3.new(1,1,1),
    Title = 'Weapon Color',
    Transparency = 0,
    Callback = function(Value)
        ESPConfig.Drawing.Weapons.WeaponTextRGB = Value
    end
})

-- Distance Section
ESPBox:AddLabel('--- Distance Settings ---')

local distanceToggle = ESPBox:AddToggle('ESP_Distance', {
    Text = 'Show Distance',
    Default = false,
    Callback = function(Value)
        ESPConfig.Drawing.Distances.Enabled = Value
    end
})

distanceToggle:AddColorPicker('ESP_DistanceColor', {
    Default = Color3.new(1,1,1),
    Title = 'Distance Color',
    Transparency = 0,
    Callback = function(Value)
        ESPConfig.Drawing.Distances.RGB = Value
    end
})

-- Chams Section
ESPBox:AddLabel('--- Chams Settings ---')

local chamsToggle = ESPBox:AddToggle('ESP_Chams', {
    Text = 'Enable Chams',
    Default = false,
    Callback = function(Value)
        ESPConfig.Drawing.Chams.Enabled = Value
    end
})

chamsToggle:AddColorPicker('ESP_Chams_Fill', {
    Default = Color3.fromRGB(119, 120, 255),
    Title = 'Fill Color',
    Transparency = 0.2,
    Callback = function(Value)
        ESPConfig.Drawing.Chams.FillRGB = Value
        ESPConfig.Drawing.Chams.Fill_Transparency = (1 - Value.Transparency) * 100
    end
})

chamsToggle:AddColorPicker('ESP_Chams_Outline', {
    Default = Color3.new(0,0,0),
    Title = 'Outline Color',
    Transparency = 0,
    Callback = function(Value)
        ESPConfig.Drawing.Chams.OutlineRGB = Value
        ESPConfig.Drawing.Chams.Outline_Transparency = (1 - Value.Transparency) * 100
    end
})

ESPBox:AddToggle('ESP_Chams_VisibleCheck', {
    Text = 'Visible Check',
    Default = false,
    Callback = function(Value)
        ESPConfig.Drawing.Chams.VisibleCheck = Value
    end
})

ESPBox:AddToggle('ESP_Chams_Thermal', {
    Text = 'Thermal Effect',
    Default = false,
    Callback = function(Value)
        ESPConfig.Drawing.Chams.Thermal = Value
    end
})

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

local player = Players.LocalPlayer
local character
local humanoidRootPart
local humanoid

local Players = game:GetService("Players")
local LocalPlayer = Players.LocalPlayer

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

local player = Players.LocalPlayer
local character
local humanoidRootPart
local humanoid

local Players = game:GetService("Players")
local LocalPlayer = Players.LocalPlayer

local function updateCharacterReferences()
    character = player.Character or player.CharacterAdded:Wait()
    humanoidRootPart = character:WaitForChild("HumanoidRootPart")
    humanoid = character:WaitForChild("Humanoid")
end

updateCharacterReferences()
local Players = game:GetService("Players")
local RunService = game:GetService("RunService")
local UIS = game:GetService("UserInputService")

local LocalPlayer = Players.LocalPlayer
local humanoidRootPart

-- ✅ Always get HumanoidRootPart, even after respawn
local function getHRP()
    local char = LocalPlayer.Character or LocalPlayer.CharacterAdded:Wait()
    return char:WaitForChild("HumanoidRootPart")
end

humanoidRootPart = getHRP()
LocalPlayer.CharacterAdded:Connect(function(char)
    humanoidRootPart = char:WaitForChild("HumanoidRootPart")
end)

-- Movement variables
local speed = 16
local flightSpeed = 50
local boostMultiplier = 2
local acceleration = 3 -- higher = faster accel

local enhancedWalk = false
local flying = false
local bodyVelocity, bodyGyro
local targetVelocity = Vector3.zero
local currentVelocity = Vector3.zero

-- Helper
local function cleanupMovement()
    if bodyVelocity then bodyVelocity:Destroy() end
    if bodyGyro then bodyGyro:Destroy() end
    bodyVelocity, bodyGyro = nil, nil
end

local function smoothApproach(current, target, rate)
    return current + (target - current) * math.clamp(rate, 0, 1)
end

-- 🚶 Enhanced Walk
local function startEnhancedWalk()
    if enhancedWalk then return end
    enhancedWalk = true
    cleanupMovement()

    bodyGyro = Instance.new("BodyGyro")
    bodyGyro.MaxTorque = Vector3.new(0, math.huge, 0)
    bodyGyro.P = 2000
    bodyGyro.CFrame = humanoidRootPart.CFrame
    bodyGyro.Parent = humanoidRootPart

    RunService.RenderStepped:Connect(function(deltaTime)
        if not enhancedWalk or not humanoidRootPart then return end

        local camera = workspace.CurrentCamera
        local moveDir = Vector3.zero

        if UIS:IsKeyDown(Enum.KeyCode.W) then moveDir += Vector3.new(camera.CFrame.LookVector.X, 0, camera.CFrame.LookVector.Z) end
        if UIS:IsKeyDown(Enum.KeyCode.S) then moveDir -= Vector3.new(camera.CFrame.LookVector.X, 0, camera.CFrame.LookVector.Z) end
        if UIS:IsKeyDown(Enum.KeyCode.A) then moveDir -= camera.CFrame.RightVector end
        if UIS:IsKeyDown(Enum.KeyCode.D) then moveDir += camera.CFrame.RightVector end

        local maxSpeed = speed
        if UIS:IsKeyDown(Enum.KeyCode.LeftShift) then maxSpeed *= boostMultiplier end

        if moveDir.Magnitude > 0 then
            targetVelocity = moveDir.Unit * maxSpeed
        else
            targetVelocity = Vector3.zero
        end

        currentVelocity = smoothApproach(currentVelocity, targetVelocity, acceleration * deltaTime)
        humanoidRootPart.AssemblyLinearVelocity = Vector3.new(currentVelocity.X, humanoidRootPart.AssemblyLinearVelocity.Y, currentVelocity.Z)

        bodyGyro.CFrame = CFrame.new(humanoidRootPart.Position, humanoidRootPart.Position + Vector3.new(camera.CFrame.LookVector.X, 0, camera.CFrame.LookVector.Z))
    end)
end

-- ✈️ Flying
local function startFlying()
    if flying then return end
    flying = true
    cleanupMovement()

    bodyVelocity = Instance.new("BodyVelocity")
    bodyVelocity.MaxForce = Vector3.new(1e5, 1e5, 1e5)
    bodyVelocity.P = 5000
    bodyVelocity.Velocity = Vector3.zero
    bodyVelocity.Parent = humanoidRootPart

    bodyGyro = Instance.new("BodyGyro")
    bodyGyro.MaxTorque = Vector3.new(1e5, 1e5, 1e5)
    bodyGyro.P = 5000
    bodyGyro.CFrame = humanoidRootPart.CFrame
    bodyGyro.Parent = humanoidRootPart

    RunService.RenderStepped:Connect(function(deltaTime)
        if not flying or not humanoidRootPart then return end

        local camera = workspace.CurrentCamera
        local moveDir = Vector3.zero

        if UIS:IsKeyDown(Enum.KeyCode.W) then moveDir += camera.CFrame.LookVector end
        if UIS:IsKeyDown(Enum.KeyCode.S) then moveDir -= camera.CFrame.LookVector end
        if UIS:IsKeyDown(Enum.KeyCode.A) then moveDir -= camera.CFrame.RightVector end
        if UIS:IsKeyDown(Enum.KeyCode.D) then moveDir += camera.CFrame.RightVector end
        if UIS:IsKeyDown(Enum.KeyCode.Space) then moveDir += Vector3.new(0, 1, 0) end
        if UIS:IsKeyDown(Enum.KeyCode.LeftControl) then moveDir -= Vector3.new(0, 1, 0) end

        local maxSpeed = flightSpeed
        if UIS:IsKeyDown(Enum.KeyCode.LeftShift) then maxSpeed *= boostMultiplier end

        if moveDir.Magnitude > 0 then
            targetVelocity = moveDir.Unit * maxSpeed
        else
            targetVelocity = Vector3.zero
        end

        currentVelocity = smoothApproach(currentVelocity, targetVelocity, acceleration * deltaTime)
        bodyVelocity.Velocity = currentVelocity
        bodyGyro.CFrame = camera.CFrame
    end)
end

-- ⏹ Stop functions
local function stopEnhancedWalk()
    enhancedWalk = false
    cleanupMovement()
    currentVelocity = Vector3.zero
end

local function stopFlying()
    flying = false
    cleanupMovement()
    currentVelocity = Vector3.zero
end





-- GUI Toggle for Enhanced Walking


-- Speed Slider for Walkspeed
Movement:AddSlider('WalkspeedSlider', {
    Text = 'Change Walkspeed',
    Default = 16,
    Min = 16,
    Max = 300,
    Rounding = 1,
    Callback = function(value)
        speed = value
    end
})


-- Speed Slider for Flight Speed
Movement:AddSlider('FlightSpeedSlider', {
    Text = 'Change Fly Speed',
    Default = 100,
    Min = 50,
    Max = 2000,
    Rounding = 0,
    Callback = function(value)
        flightSpeed = value
    end
})
-- Character Respawn Handling
player.CharacterAdded:Connect(function()
    updateCharacterReferences()
    cleanupMovement()
    if enhancedWalk then startEnhancedWalk() end
    if flying then stopFlying() end -- Ensure flight stops completely before restarting
end)






Troll:AddButton("Spam Call Police", function()
    for i = 1,getgenv().intsdp do
        task.wait(0.05)
        game:GetService("ReplicatedStorage").CallPolice:FireServer()
    end
end)


local localPlayer = game:GetService("Players").LocalPlayer
local uis = game:GetService("UserInputService")
local rs = game:GetService("RunService")
local isMoving = {W = false, A = false, S = false, D = false} -- Table to track movement keys
local multiplier = 1  -- Default multiplier (adjustable by the slider)
local movementEnabled = false -- Movement starts disabled
local SwimMethodEnabled = false -- Freefall starts disabled
local currentWalkSpeed = 16  -- Default Walkspeed

-- Display a hint for 2 seconds
task.spawn(function()
    local hint = Instance.new("Hint", workspace)
    task.wait(2)
    hint:Destroy()
end)

-- Function to move the character based on key input
local function moveCharacter()
    if movementEnabled and localPlayer.Character and localPlayer.Character:FindFirstChild("HumanoidRootPart") then
        local direction = Vector3.new(0, 0, 0)
        local camera = workspace.CurrentCamera

        -- Adjust the direction based on pressed keys
        if isMoving.W then
            direction = direction + Vector3.new(camera.CFrame.LookVector.X, 0, camera.CFrame.LookVector.Z) -- Forward
        end
        if isMoving.A then
            direction = direction - Vector3.new(camera.CFrame.RightVector.X, 0, camera.CFrame.RightVector.Z) -- Left
        end
        if isMoving.S then
            direction = direction - Vector3.new(camera.CFrame.LookVector.X, 0, camera.CFrame.LookVector.Z) -- Backward
        end
        if isMoving.D then
            direction = direction + Vector3.new(camera.CFrame.RightVector.X, 0, camera.CFrame.RightVector.Z) -- Right
        end

        -- Normalize direction and move the character
        if direction.Magnitude > 0 then
            direction = direction.Unit * multiplier
            localPlayer.Character.HumanoidRootPart.CFrame = localPlayer.Character.HumanoidRootPart.CFrame + direction
        end
    end
end

-- Key press detection for W, A, S, D
uis.InputBegan:Connect(function(input, gameProcessed)
    if gameProcessed then return end
    
    if input.KeyCode == Enum.KeyCode.W then
        isMoving.W = true
    elseif input.KeyCode == Enum.KeyCode.A then
        isMoving.A = true
    elseif input.KeyCode == Enum.KeyCode.S then
        isMoving.S = true
    elseif input.KeyCode == Enum.KeyCode.D then
        isMoving.D = true
    end
end)

-- Stop moving when the key is released
uis.InputEnded:Connect(function(input, gameProcessed)
    if gameProcessed then return end

    if input.KeyCode == Enum.KeyCode.W then
        isMoving.W = false
    elseif input.KeyCode == Enum.KeyCode.A then
        isMoving.A = false
    elseif input.KeyCode == Enum.KeyCode.S then
        isMoving.S = false
    elseif input.KeyCode == Enum.KeyCode.D then
        isMoving.D = false
    end
end)

-- Update the character's position every frame based on key input
rs.RenderStepped:Connect(moveCharacter)



-- Freefall Method Logic
getgenv().SwimMethod = false

task.spawn(function()
    while task.wait() do
        if getgenv().SwimMethod then
            local player = game:GetService("Players").LocalPlayer
            if player and player.Character and player.Character:FindFirstChild("Humanoid") then
                local humanoid = player.Character.Humanoid
                humanoid:ChangeState(Enum.HumanoidStateType.FallingDown     )
            end
        end
    end
end)
print("bypassed lol")
local UserInputService = game:GetService("UserInputService")
local RunService = game:GetService("RunService")

local player = game.Players.LocalPlayer
local character = player.Character or player.CharacterAdded:Wait()
local humanoidRootPart = character:FindFirstChild("HumanoidRootPart")

local movementEnabled = false
local currentWalkSpeed = 16  -- Default speed

--- Movement:AddSlider('WalkspeedSlider', {
   ---  Text = 'Change Walkspeed',
  ---   Default = 16,
  ---   Min = 16,
  ---   Max = 300,
 ---    Rounding = 1,
  ---   Callback = function(value)
  ---       currentWalkSpeed = value  -- Save the new speed
  ---   end
--- })




Movement:AddSlider('JumpPowerSlider', {
    Text = 'Change Jump Height',
    Default = 1,  -- Default jump height
    Min = 1,  -- Minimum jump height
    Max = 20000,  -- Maximum jump height
    Rounding = 1,
    Callback = function(value)
        currentJumpPower = value  -- Save the new jump height
        local humanoid = game.Players.LocalPlayer.Character.Humanoid
        if jumpPowerEnabled then
            humanoid.JumpHeight = value  -- Change jump height in real-time
        else
            humanoid.JumpHeight = 9  -- Set jump height to 9 when disabled
        end
    end
})



Movement:AddToggle('EnableWalkspeed', {
    Text = 'Walkspeed',
    Default = false,  
    Callback = function(enabled)
        if enabled then
            startEnhancedWalk()
        else
            stopEnhancedWalk()
        end
    end
})

-- GUI Toggle for Flight
Movement:AddToggle('EnableFlight', {
    Text = 'Vehicle Fly',
    Default = false,  
    Callback = function(enabled)
        if enabled then
            startFlying()
        else
            stopFlying()
        end
    end
})


Movement:AddToggle('EnableJumpPower', {
    Text = 'Jump Power',
    Default = false,  -- Default to off
    Callback = function(Value)
        if Value then
            -- Enable Jump Power with the current jump power (don't reset to 50)
            game.Players.LocalPlayer.Character.Humanoid.JumpPower = currentJumpPower
            jumpPowerEnabled = true  -- Enable jump power when toggle is on
        else
            -- Disable Jump Power
            game.Players.LocalPlayer.Character.Humanoid.JumpPower = 0  -- Disable jump power if toggle is off
            jumpPowerEnabled = false  -- Disable jump power when toggle is off
        end
    end
})

local noclip = false

-- Function to toggle noclip
local function toggleNoclip()
    noclip = not noclip
    if noclip then
        for _, part in pairs(character:GetDescendants()) do
            if part:IsA("BasePart") and part.CanCollide then
                part.CanCollide = false
            end
        end
    else
        for _, part in pairs(character:GetDescendants()) do
            if part:IsA("BasePart") then
                part.CanCollide = true
            end
        end
    end
end
-- Create the toggle button for Infinite Jump
local infJump
local infJumpDebounce = false
local UserInputService = game:GetService("UserInputService")

Movement:AddToggle('InfiniteJumpToggle', {
    Text = 'Infinite Jump',
    Default = false,  -- Default to off
    Callback = function(Value)
        local humanoid = speaker.Character:FindFirstChildWhichIsA("Humanoid")
        
        -- If Infinite Jump is enabled
        if Value then
            -- Disconnect any previous infinite jump connections
            if infJump then
                infJump:Disconnect()
            end
            infJumpDebounce = false

            -- Set up the infinite jump logic
            infJump = UserInputService.JumpRequest:Connect(function()
                if not infJumpDebounce then
                    infJumpDebounce = true
                    -- Make the humanoid jump
                    if humanoid then
                        humanoid:ChangeState(Enum.HumanoidStateType.Jumping)
                        wait(0.1)  -- Ensure the jump state is set
                        humanoid:ChangeState(Enum.HumanoidStateType.Seated)  -- Optionally simulate landing
                    end
                    infJumpDebounce = false
                end
            end)

        else
            -- Disable infinite jump when toggle is off
            if infJump then
                infJump:Disconnect()
            end
            infJumpDebounce = false
        end
    end
})



-- Create the toggle button for noclip
Movement:AddToggle('NoclipToggle', {
    Text = 'Noclip',
    Default = false,  -- Default to off
    Callback = function(Value)
        toggleNoclip(Value)  -- Call the toggleNoclip function when the toggle state changes
    end
})

-- Infinite Jump Script with Toggle Control

-- Services
-- Use getgenv() to store the infinite jump state globally

-- // Infinite Stamina
ExtraBox:AddToggle('InfiniteStamina', {
    Text = 'Infinite Stamina', 
    Default = false,
    Callback = function(Value)
        local LocalPlayer = game:GetService("Players").LocalPlayer
        
        if Value then
            -- Method 1: Find and destroy stamina scripts
            local function RemoveStaminaScripts()
                -- Search entire PlayerGui for stamina scripts
                local playerGui = LocalPlayer:FindFirstChild("PlayerGui")
                if playerGui then
                    for _, descendant in ipairs(playerGui:GetDescendants()) do
                        if descendant:IsA("LocalScript") then
                            local scriptName = descendant.Name:lower()
                            if scriptName:find("stamina") or 
                               scriptName:find("run") or 
                               scriptName:find("sprint") or
                               scriptName:find("energy") or
                               scriptName:find("fatigue") then
                                pcall(function()
                                    descendant.Disabled = true
                                end)
                            end
                        end
                    end
                end
            end
            
            -- Method 2: Override stamina functions in memory
            local function OverrideStaminaFunctions()
                -- Hook into the game's stamina functions
                local mt = getrawmetatable(game)
                local old = mt.__index
                
                if mt then
                    setreadonly(mt, false)
                    mt.__index = newcclosure(function(self, key)
                        if key == "Stamina" or key == "Energy" or key == "Sprint" then
                            return 100
                        end
                        return old(self, key)
                    end)
                    setreadonly(mt, true)
                end
            end
            
            -- Method 3: Constant stamina refill loop
            local staminaLoop = game:GetService("RunService").Heartbeat:Connect(function()
                local character = LocalPlayer.Character
                if character then
                    local humanoid = character:FindFirstChildOfClass("Humanoid")
                    if humanoid then
                        -- Try all possible stamina locations
                        -- Check Humanoid directly
                        if rawget(humanoid, "Stamina") then
                            rawset(humanoid, "Stamina", 100)
                        end
                        
                        -- Check attributes
                        pcall(function()
                            humanoid:SetAttribute("Stamina", 100)
                            humanoid:SetAttribute("Energy", 100)
                            humanoid:SetAttribute("Sprint", 100)
                            humanoid:SetAttribute("StaminaValue", 100)
                        end)
                        
                        -- Check child objects
                        for _, child in ipairs(humanoid:GetChildren()) do
                            if child:IsA("NumberValue") or child:IsA("IntValue") then
                                local name = child.Name:lower()
                                if name:find("stamina") or name:find("energy") or name:find("sprint") or name:find("run") then
                                    child.Value = 100
                                end
                            end
                        end
                        
                        -- Check using pcall for any property
                        pcall(function()
                            humanoid.Stamina = 100
                        end)
                        pcall(function()
                            humanoid.Energy = 100
                        end)
                    end
                    
                    -- Also check for stamina in the character
                    for _, child in ipairs(character:GetChildren()) do
                        if child:IsA("NumberValue") or child:IsA("IntValue") then
                            local name = child.Name:lower()
                            if name:find("stamina") or name:find("energy") or name:find("sprint") then
                                child.Value = 100
                            end
                        end
                    end
                end
            end)
            
            -- Method 4: Disable stamina GUI elements
            local function DisableStaminaGUI()
                local playerGui = LocalPlayer:FindFirstChild("PlayerGui")
                if playerGui then
                    -- Find stamina bar frame and hide it
                    for _, frame in ipairs(playerGui:GetDescendants()) do
                        if frame:IsA("Frame") or frame:IsA("ImageLabel") then
                            local name = frame.Name:lower()
                            if name:find("stamina") or name:find("run") or name:find("sprint") or name:find("energy") then
                                frame.Visible = false
                            end
                        end
                    end
                end
            end
            
            -- Method 5: Hook into the stamina update remote
            local function HookStaminaRemote()
                local replicatedStorage = game:GetService("ReplicatedStorage")
                local remote = replicatedStorage:FindFirstChild("UpdateStamina")
                if not remote then
                    remote = replicatedStorage:FindFirstChild("StaminaUpdate")
                end
                if not remote then
                    remote = replicatedStorage:FindFirstChild("PlayerStamina")
                end
                
                if remote and remote:IsA("RemoteEvent") then
                    local oldFunction
                    oldFunction = hookfunction(remote.FireServer, function(self, ...)
                        local args = {...}
                        -- Override stamina values in arguments
                        for i, arg in ipairs(args) do
                            if type(arg) == "number" and arg < 100 then
                                args[i] = 100
                            end
                        end
                        return oldFunction(self, unpack(args))
                    end)
                end
            end
            
            -- Execute all bypasses
            RemoveStaminaScripts()
            OverrideStaminaFunctions()
            DisableStaminaGUI()
            HookStaminaRemote()
            
            -- Store loop for cleanup
            _G.StaminaLoop = staminaLoop
            
            -- Reapply on character respawn
            local function OnRespawn()
                task.wait(0.5)
                RemoveStaminaScripts()
                DisableStaminaGUI()
            end
            
            _G.StaminaRespawnConnection = LocalPlayer.CharacterAdded:Connect(OnRespawn)
            
            Library:Notify("Infinite Stamina Enabled!", 3)
        else
            -- Cleanup
            if _G.StaminaLoop then
                _G.StaminaLoop:Disconnect()
                _G.StaminaLoop = nil
            end
            if _G.StaminaRespawnConnection then
                _G.StaminaRespawnConnection:Disconnect()
                _G.StaminaRespawnConnection = nil
            end
            
            -- Restore GUI visibility
            local playerGui = LocalPlayer:FindFirstChild("PlayerGui")
            if playerGui then
                for _, frame in ipairs(playerGui:GetDescendants()) do
                    if frame:IsA("Frame") or frame:IsA("ImageLabel") then
                        local name = frame.Name:lower()
                        if name:find("stamina") or name:find("run") or name:find("sprint") then
                            frame.Visible = true
                        end
                    end
                end
            end
            
            Library:Notify("Infinite Stamina Disabled!", 3)
        end
    end
})


-- SINGLE TELEPORT SYSTEM (Fixed)
local Locations = {
    ["Main Gun Store 🔫"] = CFrame.new(527.71, 90.51, 158.63);
    ["Black Market 💹"] = CFrame.new(-798, 44, 566);
    ["cookingarea "] = CFrame.new(987.42, 129.91, 75.27);
    ["clothing store "] = CFrame.new(113, 90, -33);
    ["car point"] = CFrame.new(530, 90, -421);
    ["carcustomization "] = CFrame.new(-163, 89, -154);
    ["car dealer"] = CFrame.new(438.25, 89.63, -356.35);
    ["buyseeds "] = CFrame.new(-43, 90, 276);
    ["buyfries "] = CFrame.new(5, 90, -58);
    ["Buildguns 🔫"] = CFrame.new(1033, 129, -166);
    ["Studio 🎙"] = CFrame.new(-35794.84, 17.90, -290.09);
    ["box job "] = CFrame.new(-57.98, 90.25, 227.29);
    ["Barbaershop "] = CFrame.new(54.88, 90.37, -51.23);
    ["banksupply "] = CFrame.new(1027, 130, -472);
    ["Bank"] = CFrame.new(186.99, 89.63, -168.02);
    ["ExoticDealer"] = CFrame.new(-154.54, 89.79, -264.75);
    ["GrowArea2"] = CFrame.new(186.99, 89.63, -168.02);
    ["gunstore2"] = CFrame.new(-716.61, 63.98, -257.01);
    ["hitman"] = CFrame.new(-1334.82, 49.79, 436.90);
    ["Icebox"] = CFrame.new(208.83, 90.45, -156.50);
    ["Laundromat"] = CFrame.new(-709.51, 50.08, 285.41);
    ["Nightclub"] = CFrame.new(-441.03, 50.60, 180.76);
    ["Pawnhop"] = CFrame.new(200.48, 91.05, -28.93);
    ["penthouse1"] = CFrame.new(1000.19, 129.89, 448.19);
    ["penthouse2"] = CFrame.new(179.09, 230.00, 290.82);
    ["river park"] = CFrame.new(416.87, 89.78, 2881.43);
    ["policestation"] = CFrame.new(424.42, 92.33, -80.20);
    ["sellfries"] = CFrame.new(815.93, 90.68, 574.86);
    ["sellplants"] = CFrame.new(726.87, 89.74, -84.59);
    ["sellsewage"] = CFrame.new(-848.43, 50.15, 422.75);
    ["supplystore"] = CFrame.new(-416.24, 51.18, 407.96);
    ["swipercards"] = CFrame.new(-602.27, 50.74, 584.89);
    ["tattooshop"] = CFrame.new(975.24, 131.00, -103.04);
    ["gunstore3"] = CFrame.new(-54.61, 79.68, -142.34);
    ["petshop"] = CFrame.new(1247.07, 135.44, -554.84);
    ["gunseller"] = CFrame.new(388.84, 120.09, 217.67);
    ["PackageFruit"] = CFrame.new(-2365.37, 53.37, 660.22);
    ["sell printed bills "] = CFrame.new(89.19, 132.07, 530.24);
    ["growarea"] = CFrame.new(1511.09, 107.41, 2684.54); 
}

local function TableKeys(tbl)
    local keys = {}
    for key in pairs(tbl) do
        keys[#keys + 1] = key
    end
    return keys
end

local Player = game:GetService("Players").LocalPlayer
local SelectedLocation = nil

-- Main teleport function
local function TeleportToLocation()
    if not SelectedLocation then
        Library:Notify("Error: No location selected!", 3)
        return
    end

    local Character = Player.Character
    if not Character then
        Library:Notify("Error: Character not found! Waiting for respawn...", 3)
        Character = Player.CharacterAdded:Wait()
    end
    
    local HumanoidRootPart = Character:FindFirstChild("HumanoidRootPart")
    if not HumanoidRootPart then
        Library:Notify("Error: HumanoidRootPart not found!", 3)
        return
    end

    -- Disable collisions to prevent stuck issues
    local originalCollide = HumanoidRootPart.CanCollide
    HumanoidRootPart.CanCollide = false
    
    -- Teleport
    HumanoidRootPart.CFrame = SelectedLocation
    
    -- Small delay to ensure teleport works
    task.wait(0.1)
    
    -- Restore collision
    HumanoidRootPart.CanCollide = originalCollide

    Library:Notify("Teleported to location!", 3)
end

-- Create dropdown (using Tele groupbox)
local LocationDropdown = Tele:AddDropdown('LocationDropdown', {
    Values = TableKeys(Locations),
    Default = "",
    Multi = false,
    Text = 'Select Location',
    Searchable = true,
    Callback = function(SelectedLocationName)
        if SelectedLocationName and Locations[SelectedLocationName] then
            SelectedLocation = Locations[SelectedLocationName]
            Library:Notify("Teleporting to: " .. SelectedLocationName, 2)
            TeleportToLocation()
        elseif SelectedLocationName then
            Library:Notify("Error: Location '" .. SelectedLocationName .. "' not found!", 3)
        end
    end
})





local SelectedPlayer

-- Function to update the player list (excluding the local player)
local function updatePlayerList()
    local players = {}
    for _, player in pairs(game.Players:GetPlayers()) do
        if player ~= game.Players.LocalPlayer then
            table.insert(players, player.Name)
        end
    end
    return players
end

-- Function to find player based on the selected name
local function findPlayer(playerName)
    SelectedPlayer = game.Players:FindFirstChild(playerName)
    if not SelectedPlayer then
        Library:Notify("Player not found!", 3)
    end
end

-- Create dropdown
local playerDropdown = TargetBox:AddDropdown('PlayerDropdown', {
    Values = updatePlayerList(),
    Default = "",
    Multi = false,
    Text = 'Select Player👤',
    Searchable = true,
    Callback = function(selectedPlayer)
        if selectedPlayer and selectedPlayer ~= "" then
            findPlayer(selectedPlayer)
        end
    end
})

-- Auto-Refresh Player List Every 1 Second
task.spawn(function()
    while task.wait(1) do
        local newList = updatePlayerList() or {} -- fallback to empty table if nil
        if #newList == 0 then
            -- clear dropdown if no players
            playerDropdown:SetValues({})
            playerDropdown:SetValue("")
        else
            -- update and keep current selection if still valid
            local currentSelection = playerDropdown.Value or ""
            playerDropdown:SetValues(newList)
            if table.find(newList, currentSelection) then
                playerDropdown:SetValue(currentSelection)
            else
                playerDropdown:SetValue("")
            end
        end
    end
end)


-- Get Into Players Car Feature
TargetBox:AddButton('Get Into Players Car', function()
    task.spawn(function()
        if not SelectedPlayer then 
            Library:Notify("No player selected!", 3)
            return 
        end
        
        local Success, Error = pcall(function()
            local targetChar = SelectedPlayer.Character
            if not targetChar then 
                Library:Notify("Target character not found!", 3)
                return
            end
            
            -- Find the vehicle the target is in
            local targetVehicle = nil
            local targetHumanoid = targetChar:FindFirstChildOfClass("Humanoid")
            
            if targetHumanoid and targetHumanoid.SeatPart then
                targetVehicle = targetHumanoid.SeatPart.Parent
                -- Traverse up to find the actual vehicle
                while targetVehicle and not targetVehicle:IsA("VehicleSeat") and targetVehicle.Parent do
                    targetVehicle = targetVehicle.Parent
                end
            end
            
            -- If target is in a vehicle, find a seat
            if targetVehicle then
                local vehicleSeat = nil
                -- Find any VehicleSeat in the vehicle
                for _, child in ipairs(targetVehicle:GetDescendants()) do
                    if child:IsA("VehicleSeat") then
                        vehicleSeat = child
                        break
                    end
                end
                
                if vehicleSeat then
                    local localChar = game.Players.LocalPlayer.Character
                    if localChar and localChar:FindFirstChild("HumanoidRootPart") then
                        local localHRP = localChar.HumanoidRootPart
                        local localHumanoid = localChar:FindFirstChildOfClass("Humanoid")
                        
                        -- Disable collisions
                        local originalCollide = localHRP.CanCollide
                        localHRP.CanCollide = false
                        
                        -- Teleport to vehicle seat
                        localHRP.CFrame = vehicleSeat.CFrame
                        task.wait(0.1)
                        
                        -- Sit in the seat
                        if localHumanoid then
                            localHumanoid.Sit = true
                            task.wait(0.1)
                        end
                        
                        -- Restore collision
                        localHRP.CanCollide = originalCollide
                        
                        Library:Notify("Successfully got into " .. SelectedPlayer.Name .. "'s vehicle!", 3)
                    end
                else
                    Library:Notify("Target vehicle has no available seat!", 3)
                end
            else
                -- If target is not in a vehicle, find nearby vehicles
                local nearestVehicle = nil
                local nearestDistance = 50
                local targetPos = targetChar.HumanoidRootPart.Position
                
                for _, vehicle in ipairs(workspace:GetDescendants()) do
                    if vehicle:IsA("VehicleSeat") and vehicle.Parent then
                        local distance = (vehicle.Position - targetPos).Magnitude
                        if distance < nearestDistance then
                            nearestDistance = distance
                            nearestVehicle = vehicle
                        end
                    end
                end
                
                if nearestVehicle then
                    local localChar = game.Players.LocalPlayer.Character
                    if localChar and localChar:FindFirstChild("HumanoidRootPart") then
                        local localHRP = localChar.HumanoidRootPart
                        local localHumanoid = localChar:FindFirstChildOfClass("Humanoid")
                        
                        -- Disable collisions
                        local originalCollide = localHRP.CanCollide
                        localHRP.CanCollide = false
                        
                        -- Teleport to nearest vehicle
                        localHRP.CFrame = nearestVehicle.CFrame
                        task.wait(0.1)
                        
                        -- Sit in the seat
                        if localHumanoid then
                            localHumanoid.Sit = true
                            task.wait(0.1)
                        end
                        
                        -- Restore collision
                        localHRP.CanCollide = originalCollide
                        
                        Library:Notify("Got into nearest vehicle near " .. SelectedPlayer.Name .. "!", 3)
                    end
                else
                    Library:Notify("No vehicle found near target!", 3)
                end
            end
        end)
        
        if not Success then
            Library:Notify("Failed to get into vehicle: " .. tostring(Error), 5)
        end
    end)
end)
-- Killbring Toggle with player selection
TargetBox:AddToggle('KillBring', {
    Text = 'KillBring',
    Default = false,  -- Default to false, meaning it's off initially
    Callback = function(Value)
        if Value then
            -- Define killbring function here
            function killBring()
                if not SelectedPlayer then
                    Library:Notify("No target selected!", 3)
                    return false
                end

                local targetPlayer = SelectedPlayer
                local speaker = game.Players.LocalPlayer

                if targetPlayer and targetPlayer.Character and speaker.Character then
                    local targetRoot = targetPlayer.Character:FindFirstChild("HumanoidRootPart")
                    local speakerRoot = speaker.Character:FindFirstChild("HumanoidRootPart")

                    if targetRoot and speakerRoot then
                        if targetPlayer.Character:FindFirstChildOfClass('Humanoid') then
                            targetPlayer.Character:FindFirstChildOfClass('Humanoid').Sit = false
                        end

                        task.wait()
                        targetRoot.CFrame = speakerRoot.CFrame + Vector3.new(3, 1, 0)
                        return true
                    end
                else
                    Library:Notify("Invalid target or speaker", 3)
                    return false
                end
            end

            getgenv().KillbringActive = true
            -- Loop for Killbring action
            while getgenv().KillbringActive do
                if not killBring() then
                    task.wait()
                else
                    task.wait()
                end
            end
        else
            getgenv().KillbringActive = false
        end
    end
})

-- Spectate Toggle
local SpectateConnection

local function spectatePlayer(enable)
    if enable then
        if SelectedPlayer and SelectedPlayer.Character and SelectedPlayer.Character:FindFirstChild("Humanoid") then
            -- Spectate Target Player
            workspace.CurrentCamera.CameraSubject = SelectedPlayer.Character.Humanoid
            Library:Notify("Spectating: " .. SelectedPlayer.Name, 3)

            -- Handle Player Respawn
            SpectateConnection = SelectedPlayer.CharacterAdded:Connect(function(newCharacter)
                workspace.CurrentCamera.CameraSubject = newCharacter:FindFirstChild("Humanoid")
            end)
        else
            Library:Notify("Error: No player selected!", 3)
        end
    else
        -- Stop Spectating and Reset Camera
        workspace.CurrentCamera.CameraSubject = game.Players.LocalPlayer.Character.Humanoid
        if SpectateConnection then SpectateConnection:Disconnect() end
        Library:Notify("Stopped Spectating", 3)
    end
end

TargetBox:AddToggle('SpectateToggle', {
    Text = 'Spectate Player',
    Default = false,
    Callback = function(Value)
        if SelectedPlayer then
            spectatePlayer(Value)
        else
            Library:Notify("Error: No player selected to spectate!", 3)
        end
    end
})

-- Freefall script (integrated into the teleportation logic)
getgenv().SwimMethod = true

task.spawn(function()
    while task.wait() do
        if FreeFalMethod then
            local player = game:GetService("Players").LocalPlayer
            if player and player.Character and player.Character:FindFirstChild("Humanoid") then
                player.Character.Humanoid:ChangeState(Enum.HumanoidStateType.FallingDown)
                player.Character.Humanoid:ChangeState(Enum.HumanoidStateType.FallingDown)
            end
        end
    end
end)

-- Freefall script (integrated into the teleportation logic)
getgenv().SwimMethod = true

task.spawn(function()
    while task.wait() do
        if FreeFalMethod then
            local player = game:GetService("Players").LocalPlayer
            if player and player.Character and player.Character:FindFirstChild("Humanoid") then
                player.Character.Humanoid:ChangeState(Enum.HumanoidStateType.FallingDown)
                player.Character.Humanoid:ChangeState(Enum.HumanoidStateType.FallingDown)
            end
        end
    end
end)

-- Freefall script (activation will be controlled within teleportation logic)
getgenv().SwimMethod = false  -- Initially set Freefall to false

task.spawn(function()
    while task.wait() do
        if FreeFalMethod then
            local player = game:GetService("Players").LocalPlayer
            if player and player.Character and player.Character:FindFirstChild("Humanoid") then
                player.Character.Humanoid:ChangeState(Enum.HumanoidStateType.FallingDown)
                player.Character.Humanoid:ChangeState(Enum.HumanoidStateType.FallingDown)
            end
        end
    end
end)

-- Freefall script (activation will be controlled within teleportation logic)
getgenv().SwimMethod = false  -- Initially set Freefall to false

task.spawn(function()
    while task.wait() do
        if FreeFalMethod then
            local player = game:GetService("Players").LocalPlayer
            if player and player.Character and player.Character:FindFirstChild("Humanoid") then
                player.Character.Humanoid:ChangeState(Enum.HumanoidStateType.FallingDown)
                player.Character.Humanoid:ChangeState(Enum.HumanoidStateType.FallingDown)
            end
        end
    end
end)

-- Go To (Teleport) Toggle




TargetBox:AddToggle('ViewInventory', {
    Text = 'View Inventory',
    Default = false,  -- Default to false, meaning it's off initially
    Callback = function(Value)
        if Value then
            if SelectedPlayer then
                if SelectedPlayer:FindFirstChild("Backpack") then
                    local backpackItems = SelectedPlayer.Backpack:GetChildren()
                    local itemNames = {}

                    for _, v in ipairs(backpackItems) do
                        table.insert(itemNames, v.Name)
                    end

                    local itemList = table.concat(itemNames, ", ")
                    if #itemList > 0 then
                        Library:Notify("Backpack items: " .. itemList, 10)
                    else
                        Library:Notify("The target player's Backpack is empty.", 10)
                    end
                else
                    Library:Notify("The target player does not have a Backpack.", 10)
                end
            else
                Library:Notify("No player selected!", 3)
            end
        end
    end
})



local lighting = game:GetService("Lighting")

local currentAmbientColor = Color3.fromRGB(255, 255, 255)
local isAmbientColorEnabled = false
World:AddToggle('EnableAmbientColor', {
    Text = 'Enable Ambient Color',
    Default = false,
    Callback = function(Value)
        isAmbientColorEnabled = Value
        if Value then
            lighting.Ambient = currentAmbientColor
        else
            lighting.Ambient = Color3.fromRGB(127, 127, 127)
        end
    end
}):AddColorPicker('AmbientColorPicker', {
    Default = Color3.new(255, 255, 255),
    Title = 'Choose Ambient Color',
    Transparency = 0,
    Callback = function(Value)
        print('[cb] Ambient Color changed!', Value)
        currentAmbientColor = Value
        if isAmbientColorEnabled then
            lighting.Ambient = Value
        end
    end
})


local currentFogColor = Color3.fromRGB(255, 255, 255)
local isFogColorEnabled = false


World:AddToggle('FogColor', {
    Text = 'Fog Color',
    Default = false,
    Callback = function(Value)
        isFogColorEnabled = Value
        if Value then
            game.Lighting.FogColor = currentFogColor
            game.Lighting.FogEnd = 100
        else
            game.Lighting.FogColor = Color3.fromRGB(255, 255, 255)
            game.Lighting.FogEnd = 0
        end
    end
}):AddColorPicker('FogColorPicker', {
    Default = Color3.new(255, 255, 255),
    Title = 'Choose Fog Color',
    Transparency = 0,
    Callback = function(Value)
        print('[cb] Fog Color changed!', Value)
        currentFogColor = Value
        if isFogColorEnabled then
            game.Lighting.FogColor = Value
        end
    end
})



local colorCorrection = Instance.new("ColorCorrectionEffect")
colorCorrection.Brightness = 0
colorCorrection.Contrast = 0
colorCorrection.Saturation = 0
colorCorrection.Parent = game.Lighting

local currentSaturation = 100
local isSaturationEnabled = false

World:AddToggle('Saturation', {
    Text = 'Saturation',
    Default = false,
    Callback = function(Value)
        isSaturationEnabled = Value
        if Value then
            colorCorrection.Saturation = currentSaturation / 100
        else
            colorCorrection.Saturation = 0
        end
    end
})

World:AddSlider('Saturation Level', {
    Text = 'Saturation Level',
    Default = 100,
    Min = 0,
    Max = 200,
    Rounding = 1,
    Callback = function(Value)
        if isSaturationEnabled then
            colorCorrection.Saturation = Value / 100
        end
    end
})


local currentTime = 12

World:AddToggle('DayTimeChanger', {
    Text = 'DayTime Changer',
    Default = false,
    Callback = function(state)
        if state then
            game.Lighting:SetMinutesAfterMidnight(currentTime * 60)
        end
    end
})

World:AddSlider('Time', {
    Text = 'Time',
    Default = 12,
    Min = 0,
    Max = 24,
    Rounding = 0,
    Callback = function(value)
        currentTime = value
        if Toggles.DayTimeChanger.Value then
            game.Lighting:SetMinutesAfterMidnight(currentTime * 60)
        end
    end
})

local AimlockBox = Tabs.Combat:AddLeftGroupbox("Aimlock Pc only 🔫")

-- Aimlock Configuration
local AimlockConfig = {
    Enabled = false,
    Aiming = true,
    Type = "Mouse",
    WallCheck = false,
    TargetPart = "Head",
    MaxDistance = 1000,
    Smoothness = 1,
    UseFieldOfView = false,
    DrawFieldOfView = false,
    FieldOfViewColor = Color3.new(1,1,1),
    FieldOfViewTransparency = 0.75,
    Radius = 100,
    Sides = 25,
    Snapline = false,
    SnaplineColor = Color3.new(1,1,1),
    SnaplineThickness = 1,
    Priority = "Closest",
    SwitchDelay = 0.3,
    AutoSwitch = true,
    KillSwitch = true,
    TargetLostDelay = 0.5,
    TeamCheck = true,
    DebugMode = false
}

-- Main Toggle
AimlockBox:AddToggle('Aimlock_Enabled', {
    Text = 'Enable Aimlock',
    Default = false,
    Callback = function(Value)
        AimlockConfig.Enabled = Value
        AimlockConfig.Aiming = Value
        if not Value then
            _G.AimlockTarget = nil
        end
    end
})

-- Settings Section
AimlockBox:AddLabel('--- Settings ---')

-- Team Check Toggle
AimlockBox:AddToggle('Aimlock_TeamCheck', {
    Text = 'Team Check (Ignore same team)',
    Default = true,
    Callback = function(Value)
        AimlockConfig.TeamCheck = Value
    end
})

-- Visible Check
AimlockBox:AddToggle('Aimlock_Wallcheck', {
    Text = 'Visible Check',
    Default = false,
    Callback = function(Value)
        AimlockConfig.WallCheck = Value
    end
})

-- ============================================
-- TEAM CHECK FUNCTION
-- ============================================
local function IsSameTeam(player1, player2)
    if not AimlockConfig.TeamCheck then
        return false
    end
    
    -- Check Team property
    if player1.Team and player2.Team and player1.Team == player2.Team then
        return true
    end
    
    -- Check TeamColor
    if player1.TeamColor and player2.TeamColor and player1.TeamColor == player2.TeamColor then
        return true
    end
    
    -- Check character-based team
    if player1.Character and player2.Character then
        local team1 = player1.Character:FindFirstChild("Team") or player1.Character:FindFirstChild("TeamColor")
        local team2 = player2.Character:FindFirstChild("Team") or player2.Character:FindFirstChild("TeamColor")
        
        if team1 and team2 then
            if (team1.Value and team2.Value and team1.Value == team2.Value) or
               (team1.Color and team2.Color and team1.Color == team2.Color) then
                return true
            end
        end
    end
    
    return false
end

-- ============================================
-- VISIBILITY CHECK FUNCTIONS
-- ============================================
local function IsTargetVisible(character, targetPart)
    if not (LocalPlayer and LocalPlayer.Character and LocalPlayer.Character:FindFirstChild("Head")) then 
        return false 
    end
    if not (character and targetPart and targetPart.Parent) then 
        return false 
    end
    
    local camera = workspace.CurrentCamera
    local origin = camera.CFrame.Position
    local target = targetPart.Position
    local direction = (target - origin).Unit
    local distance = (target - origin).Magnitude
    
    local params = RaycastParams.new()
    params.FilterType = Enum.RaycastFilterType.Blacklist
    params.FilterDescendantsInstances = {LocalPlayer.Character, character, camera}
    params.IgnoreWater = true
    
    local result = workspace:Raycast(origin, direction * distance, params)
    
    if not result then
        return true
    end
    
    local hitPart = result.Instance
    if hitPart and hitPart:IsDescendantOf(character) then
        return true
    end
    
    return false
end

local function WallCheck(character)
    if not character or not AimlockConfig.WallCheck then 
        return true 
    end
    
    local targetPart = character:FindFirstChild(AimlockConfig.TargetPart)
    if not targetPart then
        targetPart = character:FindFirstChild("HumanoidRootPart") or character:FindFirstChild("Head")
    end
    
    if not targetPart then 
        return true 
    end
    
    local success, visible = pcall(function()
        return IsTargetVisible(character, targetPart)
    end)
    
    return success and visible or true
end

-- ============================================
-- HELPER FUNCTIONS
-- ============================================
local Players = game:GetService("Players")
local RunService = game:GetService("RunService")
local UserInputService = game:GetService("UserInputService")
local LocalPlayer = Players.LocalPlayer
local Camera = workspace.CurrentCamera
local Mouse = LocalPlayer:GetMouse()

local function GetPlayers()
    return Players:GetPlayers()
end

local function WorldToScreenPoint(camera, position)
    return camera:WorldToScreenPoint(position)
end

local function DistanceCheck(player, maxDistance)
    if not (player.Character and player.Character:FindFirstChild("HumanoidRootPart") and 
            LocalPlayer.Character and LocalPlayer.Character:FindFirstChild("HumanoidRootPart")) then 
        return false 
    end
    local distance = (player.Character.HumanoidRootPart.Position - LocalPlayer.Character.HumanoidRootPart.Position).Magnitude
    return distance <= maxDistance
end

local function GetPlayerHealth(player)
    if player.Character and player.Character:FindFirstChild("Humanoid") then
        return player.Character.Humanoid.Health
    end
    return 0
end

local function IsPlayerAlive(player)
    if player.Character and player.Character:FindFirstChild("Humanoid") then
        return player.Character.Humanoid.Health > 0
    end
    return false
end

-- ============================================
-- GET VALID PLAYERS IN FOV
-- ============================================
local function GetValidPlayersInFOV()
    local validPlayers = {}
    local MouseLocation = Vector2.new(Mouse.X, Mouse.Y)
    
    for _, player in pairs(GetPlayers()) do
        if player == LocalPlayer then continue end
        
        -- Team check
        if IsSameTeam(LocalPlayer, player) then
            continue
        end
        
        -- Basic character checks
        if not (player.Character and 
                player.Character:FindFirstChild("HumanoidRootPart") and
                player.Character:FindFirstChild("Humanoid") and
                player.Character:FindFirstChild("Humanoid").Health > 0) then
            continue
        end
        
        -- Skip forcefield
        if player.Character:FindFirstChildOfClass("ForceField") then 
            continue 
        end
        
        local TargetPart = player.Character:FindFirstChild("HumanoidRootPart")
        if not TargetPart then continue end
        
        local TargetPartPosition, OnScreen = WorldToScreenPoint(Camera, TargetPart.Position)
        
        local Radius = AimlockConfig.UseFieldOfView and AimlockConfig.Radius or 9e9
        local Magnitude = (Vector2.new(TargetPartPosition.X, TargetPartPosition.Y) - MouseLocation).Magnitude
        
        if not DistanceCheck(player, AimlockConfig.MaxDistance) then 
            continue 
        end
        
        if Radius > Magnitude and OnScreen then
            if AimlockConfig.WallCheck and not WallCheck(player.Character) then
                continue
            end
            
            table.insert(validPlayers, {
                Player = player,
                Distance = Magnitude,
                Health = GetPlayerHealth(player),
                ActualDistance = (player.Character.HumanoidRootPart.Position - LocalPlayer.Character.HumanoidRootPart.Position).Magnitude,
                ScreenPosition = Vector2.new(TargetPartPosition.X, TargetPartPosition.Y)
            })
        end
    end
    
    return validPlayers
end

-- ============================================
-- TARGET PRIORITY AND SWITCHING
-- ============================================
local lastSwitchTime = 0
local targetLostTime = 0
local targetDied = false

local function SortPlayersByPriority(players)
    if AimlockConfig.Priority == "Closest" then
        table.sort(players, function(a, b)
            return a.ActualDistance < b.ActualDistance
        end)
    elseif AimlockConfig.Priority == "Lowest Health" then
        table.sort(players, function(a, b)
            return a.Health < b.Health
        end)
    elseif AimlockConfig.Priority == "Highest Health" then
        table.sort(players, function(a, b)
            return a.Health > b.Health
        end)
    end
    return players
end

local function GetBestTarget(validPlayers)
    if #validPlayers == 0 then return nil end
    validPlayers = SortPlayersByPriority(validPlayers)
    return validPlayers[1].Player
end

local function IsTargetValid(target, validPlayers)
    if not target then return false end
    for _, playerData in pairs(validPlayers) do
        if playerData.Player == target then
            return true
        end
    end
    return false
end

local function DidTargetDie(target)
    if not target then return false end
    if not IsPlayerAlive(target) then
        if not targetDied then
            targetDied = true
            return true
        end
    else
        targetDied = false
    end
    return false
end

-- ============================================
-- AIMLOCK TARGET ACQUISITION
-- ============================================
_G.AimlockTarget = nil

local function GetAimlockTarget()
    if not AimlockConfig.Enabled then return nil end
    
    local currentTime = tick()
    local validPlayers = GetValidPlayersInFOV()
    
    if #validPlayers == 0 then
        _G.AimlockTarget = nil
        targetLostTime = currentTime
        return nil
    end
    
    if _G.AimlockTarget then
        local targetValid = IsTargetValid(_G.AimlockTarget, validPlayers)
        local targetDiedState = DidTargetDie(_G.AimlockTarget)
        
        if targetValid and not targetDiedState then
            return _G.AimlockTarget
        end
        
        if (targetDiedState or not targetValid) and AimlockConfig.AutoSwitch then
            if currentTime - lastSwitchTime >= AimlockConfig.SwitchDelay then
                lastSwitchTime = currentTime
                _G.AimlockTarget = GetBestTarget(validPlayers)
                return _G.AimlockTarget
            end
        end
        
        if not targetValid and not targetDiedState then
            if currentTime - targetLostTime >= AimlockConfig.TargetLostDelay then
                if AimlockConfig.AutoSwitch then
                    _G.AimlockTarget = GetBestTarget(validPlayers)
                    return _G.AimlockTarget
                end
            end
        end
        
        return _G.AimlockTarget
    else
        _G.AimlockTarget = GetBestTarget(validPlayers)
        lastSwitchTime = currentTime
        targetLostTime = currentTime
        return _G.AimlockTarget
    end
end

-- ============================================
-- AIM MOVEMENT FUNCTIONS
-- ============================================
local function MoveToTargetInFOV(target, targetPart)
    if not target or not targetPart then return end
    
    local targetPos = targetPart.Position
    local result, onScreen = Camera:WorldToScreenPoint(targetPos)
    
    if onScreen then
        local MouseLocation = Vector2.new(Mouse.X, Mouse.Y)
        local targetScreenPos = Vector2.new(result.X, result.Y)
        local distanceToTarget = (targetScreenPos - MouseLocation).Magnitude
        
        if distanceToTarget <= AimlockConfig.Radius then
            local moveSpeed = (AimlockConfig.Smoothness + 1) * 2
            local delta = targetScreenPos - MouseLocation
            mousemoverel(delta.X / moveSpeed, delta.Y / moveSpeed)
        end
    end
end

-- ============================================
-- DRAWING OBJECTS
-- ============================================
local function CreateDrawing(className, properties)
    local drawing = Drawing.new(className)
    for prop, value in pairs(properties) do
        drawing[prop] = value
    end
    return drawing
end

local AimbotFieldOfViewOutline = CreateDrawing("Circle", {Visible = false, Color = Color3.new(0, 0, 0), Radius = 100, NumSides = 25, Thickness = 4})
local AimbotFieldOfView = CreateDrawing("Circle", {Visible = false, Color = Color3.new(1, 1, 1), Radius = 100, NumSides = 25, Thickness = 2})
local AimbotFieldOfViewFill = CreateDrawing("Circle", {Visible = false, Color = Color3.new(1, 1, 1), Radius = 100, NumSides = 25, Thickness = 2, Filled = true})
local AimbotSnaplineOutline = CreateDrawing("Line", {Visible = false, Color = Color3.new(0, 0, 0), Thickness = 3})
local AimbotSnapline = CreateDrawing("Line", {Visible = false, Color = Color3.new(1, 1, 1), Thickness = 1})
local TargetIndicator = CreateDrawing("Circle", {Visible = false, Color = Color3.new(1, 0, 0), Radius = 15, NumSides = 25, Thickness = 2, Filled = false})
local TargetHealthText = CreateDrawing("Text", {Visible = false, Color = Color3.new(1, 1, 1), Size = 16, Center = true, Outline = true})

-- ============================================
-- RENDER LOOP
-- ============================================
RunService:BindToRenderStep("CombatSystems", 200, function()
    local MouseLocation = UserInputService:GetMouseLocation()
    
    if not (LocalPlayer and LocalPlayer.Character and LocalPlayer.Character:FindFirstChild("Humanoid")) then
        return
    end
    
    -- Update target
    local currentTarget = GetAimlockTarget()
    
    -- Aimlock movement
    if AimlockConfig.Enabled and currentTarget and currentTarget.Character then
        local targetPart = currentTarget.Character:FindFirstChild(AimlockConfig.TargetPart)
        if targetPart then
            if AimlockConfig.Type == "Mouse" then
                local targetPos = targetPart.Position
                local result, onScreen = Camera:WorldToScreenPoint(targetPos)
                
                if onScreen then
                    local delta = Vector2.new(result.X - Mouse.X, result.Y - Mouse.Y)
                    mousemoverel(delta.X / (AimlockConfig.Smoothness + 1), delta.Y / (AimlockConfig.Smoothness + 1))
                end
            elseif AimlockConfig.Type == "Camera" then
                local targetPos = targetPart.Position
                local smoothness = AimlockConfig.Smoothness * 10
                Camera.CFrame = Camera.CFrame:Lerp(CFrame.new(Camera.CFrame.Position, targetPos), (100 - smoothness) / 100)
            elseif AimlockConfig.Type == "FOV" then
                MoveToTargetInFOV(currentTarget, targetPart)
            end
        end
    end
    
    -- Update FOV drawings
    AimbotFieldOfView.Visible = AimlockConfig.Enabled and AimlockConfig.UseFieldOfView and AimlockConfig.DrawFieldOfView
    AimbotFieldOfView.Radius = AimlockConfig.Radius
    AimbotFieldOfView.NumSides = AimlockConfig.Sides
    AimbotFieldOfView.Color = AimlockConfig.FieldOfViewColor
    AimbotFieldOfView.Position = MouseLocation
    
    AimbotFieldOfViewFill.Visible = AimbotFieldOfView.Visible
    AimbotFieldOfViewFill.NumSides = AimbotFieldOfView.NumSides
    AimbotFieldOfViewFill.Color = AimbotFieldOfView.Color
    AimbotFieldOfViewFill.Radius = AimbotFieldOfView.Radius
    AimbotFieldOfViewFill.Position = AimbotFieldOfView.Position
    AimbotFieldOfViewFill.Transparency = AimlockConfig.FieldOfViewTransparency
    
    AimbotFieldOfViewOutline.Visible = AimbotFieldOfView.Visible
    AimbotFieldOfViewOutline.NumSides = AimbotFieldOfView.NumSides
    AimbotFieldOfViewOutline.Position = AimbotFieldOfView.Position
    AimbotFieldOfViewOutline.Radius = AimbotFieldOfView.Radius
    
    -- Update target indicator
    if currentTarget and currentTarget.Character and currentTarget.Character:FindFirstChild(AimlockConfig.TargetPart) then
        local targetPart = currentTarget.Character:FindFirstChild(AimlockConfig.TargetPart)
        if targetPart then
            local targetPos, onScreen = Camera:WorldToViewportPoint(targetPart.Position)
            if onScreen then
                TargetIndicator.Visible = true
                TargetIndicator.Position = Vector2.new(targetPos.X, targetPos.Y)
                
                local health = GetPlayerHealth(currentTarget)
                TargetHealthText.Visible = true
                TargetHealthText.Position = Vector2.new(targetPos.X, targetPos.Y - 30)
                TargetHealthText.Text = string.format("%s [%d HP]", currentTarget.Name, math.floor(health))
                
                if health < 30 then
                    TargetIndicator.Color = Color3.new(1, 0, 0)
                elseif health < 70 then
                    TargetIndicator.Color = Color3.new(1, 1, 0)
                else
                    TargetIndicator.Color = Color3.new(0, 1, 0)
                end
            else
                TargetIndicator.Visible = false
                TargetHealthText.Visible = false
            end
        else
            TargetIndicator.Visible = false
            TargetHealthText.Visible = false
        end
    else
        TargetIndicator.Visible = false
        TargetHealthText.Visible = false
    end
    
    -- Update snaplines
    if currentTarget and currentTarget.Character and currentTarget.Character:FindFirstChild(AimlockConfig.TargetPart) then
        local targetPart = currentTarget.Character:FindFirstChild(AimlockConfig.TargetPart)
        if targetPart then
            local targetPos, onScreen = Camera:WorldToViewportPoint(targetPart.Position)
            
            AimbotSnapline.Visible = AimlockConfig.Snapline and AimlockConfig.Enabled and onScreen
            AimbotSnaplineOutline.Visible = AimbotSnapline.Visible
            
            if AimbotSnapline.Visible then
                AimbotSnapline.Color = AimlockConfig.SnaplineColor
                AimbotSnapline.Thickness = AimlockConfig.SnaplineThickness
                AimbotSnapline.From = MouseLocation
                AimbotSnapline.To = Vector2.new(targetPos.X, targetPos.Y)
                
                AimbotSnaplineOutline.Color = Color3.new(0,0,0)
                AimbotSnaplineOutline.Thickness = AimlockConfig.SnaplineThickness + 2
                AimbotSnaplineOutline.From = MouseLocation
                AimbotSnaplineOutline.To = Vector2.new(targetPos.X, targetPos.Y)
            end
        end
    else
        AimbotSnapline.Visible = false
        AimbotSnaplineOutline.Visible = false
    end
end)

-- Aim Type Dropdown
AimlockBox:AddDropdown('Aimlock_Type', {
    Text = 'Aim Type',
    Values = {'Mouse', 'Camera', 'FOV'},
    Default = 'Mouse',
    Callback = function(Value)
        AimlockConfig.Type = Value
    end
})

-- Target Part Dropdown
local function getBodyParts()
    local bodyParts = {}
    if LocalPlayer.Character then
        local humanoid = LocalPlayer.Character:FindFirstChild("Humanoid")
        if humanoid then
            local rigType = humanoid.RigType.Name
            if rigType == "R6" then
                bodyParts = {"Head", "Torso", "Left Arm", "Right Arm", "Left Leg", "Right Leg", "HumanoidRootPart"}
            else
                bodyParts = {"Head", "UpperTorso", "LowerTorso", "LeftUpperArm", "LeftLowerArm", "RightUpperArm", "RightLowerArm", "LeftUpperLeg", "LeftLowerLeg", "RightUpperLeg", "RightLowerLeg", "HumanoidRootPart"}
            end
        end
    end
    return bodyParts
end

AimlockBox:AddDropdown('Aimlock_TargetPart', {
    Text = 'Target Part',
    Values = getBodyParts(),
    Default = 'Head',
    Callback = function(Value)
        AimlockConfig.TargetPart = Value
    end
})

-- Max Distance
AimlockBox:AddSlider('Aimlock_MaxDistance', {
    Text = 'Max Distance',
    Default = 1000,
    Min = 0,
    Max = 3000,
    Rounding = 1,
    Suffix = ' studs',
    Callback = function(Value)
        AimlockConfig.MaxDistance = Value
    end
})

-- Smoothness
AimlockBox:AddSlider('Aimlock_Smoothness', {
    Text = 'Smoothness',
    Default = 10,
    Min = 0,
    Max = 100,
    Rounding = 1,
    Suffix = '%',
    Callback = function(Value)
        AimlockConfig.Smoothness = Value / 10
    end
})

-- Target Priority
AimlockBox:AddDropdown('Aimlock_Priority', {
    Text = 'Target Priority',
    Values = {'Closest', 'Lowest Health', 'Highest Health'},
    Default = 'Closest',
    Callback = function(Value)
        AimlockConfig.Priority = Value
    end
})

-- Auto Switch Toggle
AimlockBox:AddToggle('Aimlock_AutoSwitch', {
    Text = 'Auto Switch Target',
    Default = true,
    Callback = function(Value)
        AimlockConfig.AutoSwitch = Value
    end
})

-- Kill Switch Toggle
AimlockBox:AddToggle('Aimlock_KillSwitch', {
    Text = 'Switch on Kill',
    Default = true,
    Callback = function(Value)
        AimlockConfig.KillSwitch = Value
    end
})

-- Switch Delay
AimlockBox:AddSlider('Aimlock_SwitchDelay', {
    Text = 'Switch Delay',
    Default = 0.3,
    Min = 0,
    Max = 1,
    Rounding = 0.1,
    Suffix = 's',
    Callback = function(Value)
        AimlockConfig.SwitchDelay = Value
    end
})

-- Target Lost Delay
AimlockBox:AddSlider('Aimlock_TargetLostDelay', {
    Text = 'Target Lost Delay',
    Default = 0.5,
    Min = 0,
    Max = 2,
    Rounding = 0.1,
    Suffix = 's',
    Callback = function(Value)
        AimlockConfig.TargetLostDelay = Value
    end
})

-- FOV Section
AimlockBox:AddLabel('--- Field of View ---')

-- Use FOV
AimlockBox:AddToggle('Aimlock_Usefov', {
    Text = 'Use FOV',
    Default = false,
    Callback = function(Value)
        AimlockConfig.UseFieldOfView = Value
    end
})

-- Draw FOV Circle
local aimFOVToggle = AimlockBox:AddToggle('Aimlock_DrawCircle', {
    Text = 'Draw FOV Circle',
    Default = false,
    Callback = function(Value)
        AimlockConfig.DrawFieldOfView = Value
    end
})

aimFOVToggle:AddColorPicker('Aimlock_FOVColor', {
    Default = Color3.new(1,1,1),
    Title = 'FOV Color',
    Transparency = 0.75,
    Callback = function(Value)
        AimlockConfig.FieldOfViewColor = Value
        AimlockConfig.FieldOfViewTransparency = Value.Transparency
    end
})

-- FOV Radius
AimlockBox:AddSlider('Aimlock_Radius', {
    Text = 'FOV Radius',
    Default = 100,
    Min = 0,
    Max = 1000,
    Rounding = 1,
    Suffix = ' px',
    Callback = function(Value)
        AimlockConfig.Radius = Value
    end
})

-- FOV Sides
AimlockBox:AddSlider('Aimlock_Sides', {
    Text = 'Circle Sides',
    Default = 25,
    Min = 3,
    Max = 100,
    Rounding = 1,
    Callback = function(Value)
        AimlockConfig.Sides = Value
    end
})

-- Snapline Section
AimlockBox:AddLabel('--- Snapline ---')

-- Snapline Toggle
local aimSnaplineToggle = AimlockBox:AddToggle('Aimlock_Snapline', {
    Text = 'Show Snapline',
    Default = false,
    Callback = function(Value)
        AimlockConfig.Snapline = Value
    end
})

aimSnaplineToggle:AddColorPicker('Aimlock_SnaplineColor', {
    Default = Color3.new(1,1,1),
    Title = 'Snapline Color',
    Transparency = 0,
    Callback = function(Value)
        AimlockConfig.SnaplineColor = Value
    end
})

-- Snapline Thickness
AimlockBox:AddSlider('Aimlock_SnaplineThickness', {
    Text = 'Snapline Thickness',
    Default = 1,
    Min = 1,
    Max = 5,
    Rounding = 1,
    Callback = function(Value)
        AimlockConfig.SnaplineThickness = Value
    end
})


local Farm = Tabs.AutoFarm:AddRightGroupbox('boxJob 📦')

-- Auto Farm Toggle (Teleports between farm and delivery)
local autoFarming = false
local autoFarmConnection = nil

Farm:AddToggle('AutoFarmToggle', {
    Text = 'Auto Farm (Farm → Delivery)',
    Default = false,
    Callback = function(Value)
        autoFarming = Value
        
        if autoFarming then
            autoFarmConnection = game:GetService("RunService").Heartbeat:Connect(function()
                if not autoFarming then return end
                
                local player = game:GetService("Players").LocalPlayer
                local character = player.Character
                if not character then return end
                
                local root = character:FindFirstChild("HumanoidRootPart")
                if not root then return end
                
                local originalCollide = root.CanCollide
                root.CanCollide = false
                
                -- Teleport to farm
                root.CFrame = CFrame.new(-17.41, 90.25, 180.50)
                task.wait(1)
                
                -- Teleport to delivery
                root.CFrame = CFrame.new(-62.30, 90.25, 230.09)
                task.wait(0.5)
                
                -- Trigger delivery prompt
                pcall(function()
                    local deliveryPart = workspace.DeliveryJob.BoxPickingJob.Job.Part
                    if deliveryPart then
                        local proximityPrompt = deliveryPart:FindFirstChild("ProximityPrompt")
                        if proximityPrompt then
                            proximityPrompt:InputHoldBegin()
                            task.wait(0.1)
                            proximityPrompt:InputHoldEnd()
                        end
                    end
                end)
                
                root.CanCollide = originalCollide
            end)
            Library:Notify("Auto Farming Started!", 3)
        else
            if autoFarmConnection then
                autoFarmConnection:Disconnect()
                autoFarmConnection = nil
            end
            Library:Notify("Auto Farming Stopped!", 3)
        end
    end
})


local OriginalSettings = {}
local ModifiedGuns = {}

-- Function to get all gun module scripts
local function getAllGunModules()
    local guns = {}
    local LocalPlayer = game:GetService("Players").LocalPlayer
    
    local function scan(container)
        if not container then return end
        for _, item in ipairs(container:GetChildren()) do
            if item:IsA("Tool") then
                local settings = item:FindFirstChild("Settings")
                if settings and settings:IsA("ModuleScript") then
                    table.insert(guns, {
                        tool = item,
                        module = settings
                    })
                end
            end
        end
    end
    
    scan(LocalPlayer.Backpack)
    if LocalPlayer.Character then
        scan(LocalPlayer.Character)
    end
    
    return guns
end

-- Function to cache original values
local function cacheOriginalValues(module, moduleId)
    if OriginalSettings[moduleId] then return end
    
    local success, settings = pcall(require, module)
    if success and type(settings) == "table" then
        OriginalSettings[moduleId] = {
            jamChance = settings.jamChance,
            spread = settings.spread,
            recoil = settings.recoil,
            semiCooldown = settings.semiCooldown,
            autoCooldown = settings.autoCooldown,
            fireMode = settings.fireMode,
            projectiles = settings.projectiles,
            MaxAmmo = settings.MaxAmmo,
            AmmoPerMag = settings.AmmoPerMag,
            Ammo = settings.Ammo,
            LimitedAmmoEnabled = settings.LimitedAmmoEnabled,
            Clips = settings.Clips,
            ClipCount = settings.ClipCount,
            ReserveClips = settings.ReserveClips,
            ReloadTime = settings.ReloadTime,
            TacticalReloadTime = settings.TacticalReloadTime,
            EquipTime = settings.EquipTime,
        }
    end
end

-- Function to apply modifications to all guns
local function applyGunMods(modFunction)
    local guns = getAllGunModules()
    
    for _, gunData in ipairs(guns) do
        local module = gunData.module
        local moduleId = module:GetDebugId()
        
        cacheOriginalValues(module, moduleId)
        
        local success, settings = pcall(require, module)
        if success and type(settings) == "table" then
            modFunction(settings)
            ModifiedGuns[moduleId] = true
        end
    end
end

-- Function to restore specific property
local function restoreGunProperty(propertyName)
    local guns = getAllGunModules()
    
    for _, gunData in ipairs(guns) do
        local module = gunData.module
        local moduleId = module:GetDebugId()
        local original = OriginalSettings[moduleId]
        
        if original and original[propertyName] ~= nil then
            local success, settings = pcall(require, module)
            if success and type(settings) == "table" then
                settings[propertyName] = original[propertyName]
            end
        end
    end
end

-- Function to restore all gun properties
local function restoreAllGunProperties()
    local guns = getAllGunModules()
    
    for _, gunData in ipairs(guns) do
        local module = gunData.module
        local moduleId = module:GetDebugId()
        local original = OriginalSettings[moduleId]
        
        if original then
            local success, settings = pcall(require, module)
            if success and type(settings) == "table" then
                for propName, propValue in pairs(original) do
                    settings[propName] = propValue
                end
            end
        end
    end
end

-- Store active mods
getgenv().GunModsActive = getgenv().GunModsActive or {}
getgenv().ReloadSpeedValue = getgenv().ReloadSpeedValue or 50

-- Setup automatic scanning for new guns
local function setupGunScanner()
    local LocalPlayer = game:GetService("Players").LocalPlayer
    
    local function onToolAdded(tool)
        if tool:IsA("Tool") then
            local settings = tool:FindFirstChild("Settings")
            if settings and settings:IsA("ModuleScript") then
                cacheOriginalValues(settings, settings:GetDebugId())
                
                if getgenv().GunModsActive then
                    for modName, active in pairs(getgenv().GunModsActive) do
                        if active then
                            local success, settingsTable = pcall(require, settings)
                            if success and type(settingsTable) == "table" then
                                                if modName == "NoJam" then
                                    settingsTable.jamChance = 0
                                elseif modName == "NoSpread" then
                                    settingsTable.spread = 0
                                elseif modName == "NoRecoil" then
                                    settingsTable.recoil = 0
                                elseif modName == "FullAuto" and settingsTable.fireMode == "semi" then
                                    settingsTable.fireMode = "auto"
                                    settingsTable.autoCooldown = 0.05
                                elseif modName == "RapidFire" then
                                    if settingsTable.fireMode == "auto" then
                                        settingsTable.autoCooldown = 0.01
                                    elseif settingsTable.fireMode == "semi" then
                                        settingsTable.semiCooldown = 0.01
                                    end
                                elseif modName == "InstantReload" then
                                    settingsTable.ReloadTime = 0
                                    settingsTable.TacticalReloadTime = 0
                                elseif modName == "ReloadSpeed" then
                                    local speed = getgenv().ReloadSpeedValue or 50
                                    local factor = speed / 100
                                    local orig = OriginalSettings[settings:GetDebugId()]
                                    if orig then
                                        settingsTable.ReloadTime = orig.ReloadTime * factor
                                        settingsTable.TacticalReloadTime = orig.TacticalReloadTime * factor
                                    end
                                elseif modName == "InfiniteAmmo" then
                                    settingsTable.Clips = 99999
                                    settingsTable.ClipCount = 99999
                                    settingsTable.ReserveClips = 99999
                                    settingsTable.Ammo = 99999
                                    settingsTable.MaxAmmo = 99999
                                    settingsTable.AmmoPerMag = 99999
                                    settingsTable.LimitedAmmoEnabled = false
                                end
                            end
                        end
                    end
                end
            end
        end
    end
    
    -- Cache existing guns
    for _, gunData in ipairs(getAllGunModules()) do
        cacheOriginalValues(gunData.module, gunData.module:GetDebugId())
    end
    
    -- Setup listeners
    LocalPlayer.Backpack.ChildAdded:Connect(onToolAdded)
    if LocalPlayer.Character then
        LocalPlayer.Character.ChildAdded:Connect(onToolAdded)
    end
    
    LocalPlayer.CharacterAdded:Connect(function(newChar)
        newChar.ChildAdded:Connect(onToolAdded)
    end)
end

-- Initialize gun scanner
setupGunScanner()

-- ==================== GUN MODIFICATIONS ====================

-- No Jam Toggle
Gun:AddToggle('Gun_NoJam', {
    Text = 'No Jam',
    Default = false,
    Callback = function(state)
        getgenv().GunModsActive.NoJam = state
        if state then
            applyGunMods(function(gun) gun.jamChance = 0 end)
        else
            restoreGunProperty("jamChance")
        end
    end
})

-- No Spread Toggle
Gun:AddToggle('Gun_NoSpread', {
    Text = 'No Spread',
    Default = false,
    Callback = function(state)
        getgenv().GunModsActive.NoSpread = state
        if state then
            applyGunMods(function(gun) gun.spread = 0 end)
        else
            restoreGunProperty("spread")
        end
    end
})

-- No Recoil Toggle
Gun:AddToggle('Gun_NoRecoil', {
    Text = 'No Recoil',
    Default = false,
    Callback = function(state)
        getgenv().GunModsActive.NoRecoil = state
        if state then
            applyGunMods(function(gun) gun.recoil = 0 end)
        else
            restoreGunProperty("recoil")
        end
    end
})

-- Full Auto Toggle
Gun:AddToggle('Gun_FullAuto', {
    Text = 'Full Auto (Convert Semi to Auto)',
    Default = false,
    Callback = function(state)
        getgenv().GunModsActive.FullAuto = state
        if state then
            applyGunMods(function(gun)
                if gun.fireMode == "semi" then
                    gun.fireMode = "auto"
                    gun.autoCooldown = 0.05
                end
            end)
        else
            restoreGunProperty("fireMode")
            restoreGunProperty("autoCooldown")
        end
    end
})

-- Rapid Fire Toggle
Gun:AddToggle('Gun_RapidFire', {
    Text = 'Rapid Fire',
    Default = false,
    Callback = function(state)
        getgenv().GunModsActive.RapidFire = state
        if state then
            applyGunMods(function(gun)
                if gun.fireMode == "auto" then
                    gun.autoCooldown = 0.01
                elseif gun.fireMode == "semi" then
                    gun.semiCooldown = 0.01
                end
            end)
        else
            restoreGunProperty("autoCooldown")
            restoreGunProperty("semiCooldown")
        end
    end
})

-- Instant Reload Toggle
Gun:AddToggle('Gun_InstantReload', {
    Text = 'Instant Reload',
    Default = false,
    Callback = function(state)
        if state and getgenv().GunModsActive.ReloadSpeed then
            Library:Notify("Disable Reload Speed Mod first!", 3)
            return
        end
        getgenv().GunModsActive.InstantReload = state
        if state then
            applyGunMods(function(gun)
                gun.ReloadTime = 0
                gun.TacticalReloadTime = 0
            end)
        else
            restoreGunProperty("ReloadTime")
            restoreGunProperty("TacticalReloadTime")
        end
    end
})

-- Reload Speed Slider
Gun:AddSlider('Gun_ReloadSpeed', {
    Text = 'Reload Speed',
    Default = 50,
    Min = 0,
    Max = 100,
    Rounding = 1,
    Suffix = '%',
    Callback = function(value)
        getgenv().ReloadSpeedValue = value
        if getgenv().GunModsActive.ReloadSpeed and not getgenv().GunModsActive.InstantReload then
            local factor = value / 100
            applyGunMods(function(gun)
                for id, orig in pairs(OriginalSettings) do
                    if gun.ReloadTime == orig.ReloadTime then
                        gun.ReloadTime = orig.ReloadTime * factor
                        gun.TacticalReloadTime = orig.TacticalReloadTime * factor
                        break
                    end
                end
            end)
        end
    end
})

-- Reload Speed Toggle
Gun:AddToggle('Gun_ReloadSpeedToggle', {
    Text = 'Reload Speed Mod',
    Default = false,
    Callback = function(state)
        if state and getgenv().GunModsActive.InstantReload then
            Library:Notify("Disable Instant Reload first!", 3)
            return
        end
        
        getgenv().GunModsActive.ReloadSpeed = state
        
        if state then
            local factor = getgenv().ReloadSpeedValue / 100
            applyGunMods(function(gun)
                for id, orig in pairs(OriginalSettings) do
                    if gun.ReloadTime == orig.ReloadTime then
                        gun.ReloadTime = orig.ReloadTime * factor
                        gun.TacticalReloadTime = orig.TacticalReloadTime * factor
                        break
                    end
                end
            end)
        else
            restoreGunProperty("ReloadTime")
            restoreGunProperty("TacticalReloadTime")
        end
    end
})

-- Infinite Ammo Toggle
Gun:AddToggle('Gun_InfiniteAmmo', {
    Text = 'Infinite Ammo',
    Default = false,
    Callback = function(state)
        getgenv().GunModsActive.InfiniteAmmo = state
        if state then
            applyGunMods(function(gun)
                gun.Clips = 99999
                gun.ClipCount = 99999
                gun.ReserveClips = 99999
                gun.Ammo = 99999
                gun.MaxAmmo = 99999
                gun.AmmoPerMag = 99999
                gun.LimitedAmmoEnabled = false
            end)
        else
            restoreGunProperty("Clips")
            restoreGunProperty("ClipCount")
            restoreGunProperty("ReserveClips")
            restoreGunProperty("Ammo")
            restoreGunProperty("MaxAmmo")
            restoreGunProperty("AmmoPerMag")
            restoreGunProperty("LimitedAmmoEnabled")
        end
    end
})

-- RESET ALL BUTTON (THIS WAS MISSING)
Gun:AddButton('Reset All Gun Mods', function()
    -- Reset all flags in UI
    if Gun then
        pcall(function()
            -- Try to uncheck all toggles
            local flagsToReset = {
                'Gun_NoJam', 'Gun_NoSpread', 'Gun_NoRecoil', 
                'Gun_FullAuto', 'Gun_RapidFire', 'Gun_InstantReload', 
                'Gun_ReloadSpeedToggle', 'Gun_InfiniteAmmo'
            }
            for _, flag in ipairs(flagsToReset) do
                if Library and Library.flags then
                    Library.flags[flag] = false
                end
            end
        end)
    end
    
    -- Clear active mods
    getgenv().GunModsActive = {}
    
    -- Reset reload speed value
    getgenv().ReloadSpeedValue = 50
    
    -- Restore all original properties
    restoreAllGunProperties()
    
    Library:Notify("All gun mods have been reset!", 3)
end)

print("Gun Mods loaded successfully!")

local Farm = Tabs.AutoFarm:AddLeftGroupbox('ROBHOUSE 🧺')

-- Teleport Locations
local Locations = {
    ["Robhouse 1 "] = CFrame.new(-732.37, 50.29, -102.51);
    ["Robhouse 2 "] = CFrame.new(-168.12, 90.29, -311.85);
    ["Robhouse 3 "] = CFrame.new(332.36, 90.53, 194.47);
    ["Robhouse 4 "] = CFrame.new(-61.74, 90.61, 460.59);
    ["Robhouse 5"] = CFrame.new(26.41, 90.44, 526.78);
    ["Robhouse 6 "] = CFrame.new(-589.11, 55.56, 586.61);
    ["Robhouse 7"] = CFrame.new(-566.14, 65.63, 573.48);
}

local function TableKeys(tbl)
    local keys = {}
    for key in pairs(tbl) do
        keys[#keys + 1] = key
    end
    return keys
end

local Player = game:GetService("Players").LocalPlayer
local SelectedLocation = nil

-- Main teleport function
local function TeleportToLocation()
    if not SelectedLocation then
        Library:Notify("Error: No location selected!", 3)
        return
    end

    local Character = Player.Character
    if not Character then
        Library:Notify("Error: Character not found! Waiting for respawn...", 3)
        Character = Player.CharacterAdded:Wait()
    end
    
    local HumanoidRootPart = Character:FindFirstChild("HumanoidRootPart")
    if not HumanoidRootPart then
        Library:Notify("Error: HumanoidRootPart not found!", 3)
        return
    end

    -- Disable collisions to prevent stuck issues
    local originalCollide = HumanoidRootPart.CanCollide
    HumanoidRootPart.CanCollide = false
    
    -- Teleport
    HumanoidRootPart.CFrame = SelectedLocation
    
    -- Small delay to ensure teleport works
    task.wait(0.1)
    
    -- Restore collision
    HumanoidRootPart.CanCollide = originalCollide

    Library:Notify("Teleported to location!", 3)
end

-- Create dropdown in the Farm groupbox (AutoFarm tab)
local LocationDropdown = Farm:AddDropdown('LocationDropdown', {
    Values = TableKeys(Locations),
    Default = "",
    Multi = false,
    Text = 'Select Location',
    Searchable = true,
    Callback = function(SelectedLocationName)
        if SelectedLocationName and Locations[SelectedLocationName] then
            SelectedLocation = Locations[SelectedLocationName]
            Library:Notify("Teleporting to: " .. SelectedLocationName, 2)
            TeleportToLocation()
        elseif SelectedLocationName then
            Library:Notify("Error: Location '" .. SelectedLocationName .. "' not found!", 3)
        end
    end
})

local Farm = Tabs.AutoFarm:AddLeftGroupbox('Buy seed & sell seed 🌱')

local Locations = {
    ["buy seed"] = CFrame.new(-789.00, 44.64, 565.10);
    ["growarea1"] = CFrame.new(1511.09, 107.41, 2684.54);
    ["growarea2 "] = CFrame.new(951.03, 272.12, 458.40);
    ["growarea3 "] = CFrame.new(146.68, 229.57, 245.06);
    ["sellplants"] = CFrame.new(726.87, 89.74, -84.59); 
}

local function TableKeys(tbl)
    local keys = {}
    for key in pairs(tbl) do
        keys[#keys + 1] = key
    end
    return keys
end

local Player = game:GetService("Players").LocalPlayer
local SelectedLocation = nil

-- Main teleport function
local function TeleportToLocation()
    if not SelectedLocation then
        Library:Notify("Error: No location selected!", 3)
        return
    end

    local Character = Player.Character
    if not Character then
        Library:Notify("Error: Character not found! Waiting for respawn...", 3)
        Character = Player.CharacterAdded:Wait()
    end
    
    local HumanoidRootPart = Character:FindFirstChild("HumanoidRootPart")
    if not HumanoidRootPart then
        Library:Notify("Error: HumanoidRootPart not found!", 3)
        return
    end

    -- Disable collisions to prevent stuck issues
    local originalCollide = HumanoidRootPart.CanCollide
    HumanoidRootPart.CanCollide = false
    
    -- Teleport
    HumanoidRootPart.CFrame = SelectedLocation
    
    -- Small delay to ensure teleport works
    task.wait(0.1)
    
    -- Restore collision
    HumanoidRootPart.CanCollide = originalCollide

    Library:Notify("Teleported to location!", 3)
end

-- Create dropdown in the Farm groupbox
local LocationDropdown = Farm:AddDropdown('LocationDropdown', {
    Values = TableKeys(Locations),
    Default = "",
    Multi = false,
    Text = 'Select Location',
    Searchable = true,
    Callback = function(SelectedLocationName)
        if SelectedLocationName and Locations[SelectedLocationName] then
            SelectedLocation = Locations[SelectedLocationName]
            Library:Notify("Teleporting to: " .. SelectedLocationName, 2)
            TeleportToLocation()
        elseif SelectedLocationName then
            Library:Notify("Error: Location '" .. SelectedLocationName .. "' not found!", 3)
        end
    end
})

Embed on website

To embed this project on your website, copy the following code and paste it into your website's HTML: