local OrionLib = loadstring(game:HttpGet("https://raw.githubusercontent.com/mac671355-5/Orion/refs/heads/main/Orion.lua"))()

if not OrionLib then
    return
end

local Players = game:GetService("Players")
local RunService = game:GetService("RunService")
local UserInputService = game:GetService("UserInputService")
local TweenService = game:GetService("TweenService")
local StarterGui = game:GetService("StarterGui")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local TeleportService = game:GetService("TeleportService")
local HttpService = game:GetService("HttpService")
local CollectionService = game:GetService("CollectionService")
local Camera = workspace.CurrentCamera
local LocalPlayer = Players.LocalPlayer
local Mouse = LocalPlayer:GetMouse()

local networking = require(ReplicatedStorage:WaitForChild("Code"):WaitForChild("modules"):WaitForChild("networking"))
local interactRemote = networking.ClientEvents["a48d667e-b1da-420d-b2ae-4a445ad5b617"]

-- [ CONSTANTS ]
local WAYPOINT_TWEEN_SPEED = 150
local WAYPOINT_MAP_HEIGHT = 100
local waypointTeleportEnabled = false
local waypointTweenBusy = false
local waypointButtonConnections = {}
local waypointGroundRayParams = RaycastParams.new()
waypointGroundRayParams.FilterType = Enum.RaycastFilterType.Exclude


-- [ SETTINGS ]
local AimbotSettings = {
    Enabled = false,
    Keybind = Enum.UserInputType.MouseButton2,
    FOV = false,
    FOVRadius = 100,
    WallCheck = false,
    TeamCheck = false,
    Smoothness = 5,
    TargetPart = "Head",
    HUD = false
}

local AimbotWhitelist = {}

local function isWhitelisted(player)
    return AimbotWhitelist[player.Name] == true
end

local ESPSettings = {
    Box = false,
    Name = false,
    Health = false,
    Item = false,
    Wanted = false,
    Tracers = false,
    Team = false,
    Chams = false,
    CarESP = false,
    RenderDistance = 2000,
    Color = Color3.fromRGB(150, 150, 150)
}

local CFrameSpeed = 0
local CFrameSpeedEnabled = false
local NoclipEnabled = false
local CarFlySettings = {
    Enabled = false,
    Speed = 50
}
local InfJumpEnabled = false
local AntiTaserEnabled = false
local AntiCuffEnabled = false
local InfFuelEnabled = false
local CarGodmodeEnabled = false
local MobileCarFlyEnabled = false
local OGSniperEnabled = false
local AutoCollectEnabled = false
local VehicleUpgrades = {
    Engine = 0,
    Armor = 0,
    Brakes = 0
}
local BypassSettings = {
    VehicleDamage = false,
    InfStamina = false,
    Anticheat = false,
    EnterLockedCars = false
}

local function SaveConfig()
    local data = {
        Aimbot = AimbotSettings,
        ESP = {
            Box = ESPSettings.Box,
            Name = ESPSettings.Name,
            Health = ESPSettings.Health,
            Item = ESPSettings.Item,
            Wanted = ESPSettings.Wanted,
            Tracers = ESPSettings.Tracers,
            Team = ESPSettings.Team,
            Chams = ESPSettings.Chams,
            CarESP = ESPSettings.CarESP,
            RenderDistance = ESPSettings.RenderDistance,
            Color = {ESPSettings.Color.R, ESPSettings.Color.G, ESPSettings.Color.B}
        },
        Misc = {
            CFrameSpeed = CFrameSpeed,
            CFrameSpeedEnabled = CFrameSpeedEnabled,
            NoclipEnabled = NoclipEnabled,
            InfJumpEnabled = InfJumpEnabled,
            AntiFallEnabled = _G.AntiFallEnabled,
            AutoRejoin = _G.AutoRejoin,
            AntiTaserEnabled = AntiTaserEnabled,
            AntiCuffEnabled = AntiCuffEnabled,
            InfFuelEnabled = InfFuelEnabled,
            CarGodmodeEnabled = CarGodmodeEnabled,
            MobileCarFlyEnabled = MobileCarFlyEnabled,
            OGSniperEnabled = OGSniperEnabled,
            AutoCollectEnabled = AutoCollectEnabled,
            MapClickTP = waypointTeleportEnabled,
            TeleportSpeed = WAYPOINT_TWEEN_SPEED
        },
        VehicleUpgrades = VehicleUpgrades,
        Bypasses = BypassSettings
    }
    local success, encoded = pcall(function() return HttpService:JSONEncode(data) end)
    if success then
        writefile("CrypticHub_Config.json", encoded)
    end
end

local function LoadConfig()
    if isfile("CrypticHub_Config.json") then
        local success, decoded = pcall(function() return HttpService:JSONDecode(readfile("CrypticHub_Config.json")) end)
        if success and decoded then
            -- Aimbot
            if decoded.Aimbot then
                for i, v in pairs(decoded.Aimbot) do AimbotSettings[i] = v end
            end
            -- ESP
            if decoded.ESP then
                for i, v in pairs(decoded.ESP) do
                    if i == "Color" then
                        ESPSettings.Color = Color3.new(v[1], v[2], v[3])
                    else
                        ESPSettings[i] = v
                    end
                end
            end
            -- Misc
            if decoded.Misc then
                CFrameSpeed = decoded.Misc.CFrameSpeed or 0
                CFrameSpeedEnabled = decoded.Misc.CFrameSpeedEnabled or false
                NoclipEnabled = decoded.Misc.NoclipEnabled or false
                InfJumpEnabled = decoded.Misc.InfJumpEnabled or false
                _G.AntiFallEnabled = decoded.Misc.AntiFallEnabled or false
                _G.AutoRejoin = decoded.Misc.AutoRejoin or false
                AntiTaserEnabled = decoded.Misc.AntiTaserEnabled or false
                AntiCuffEnabled = decoded.Misc.AntiCuffEnabled or false
                InfFuelEnabled = decoded.Misc.InfFuelEnabled or false
                CarGodmodeEnabled = decoded.Misc.CarGodmodeEnabled or false
                MobileCarFlyEnabled = decoded.Misc.MobileCarFlyEnabled or false
                OGSniperEnabled = decoded.Misc.OGSniperEnabled or false
                AutoCollectEnabled = decoded.Misc.AutoCollectEnabled or false
                waypointTeleportEnabled = decoded.Misc.MapClickTP or false
                WAYPOINT_TWEEN_SPEED = decoded.Misc.TeleportSpeed or 165
            end
            -- Vehicle Upgrades
            if decoded.VehicleUpgrades then
                for i, v in pairs(decoded.VehicleUpgrades) do VehicleUpgrades[i] = v end
            end
            -- Bypasses
            if decoded.Bypasses then
                for i, v in pairs(decoded.Bypasses) do
                    BypassSettings[i] = v
                end
                getgenv().VehicleDamageBypass = BypassSettings.VehicleDamage
                getgenv().InfStamina = BypassSettings.InfStamina
                getgenv().AnticheatBypass = BypassSettings.Anticheat
                getgenv().EnterLockedCars = BypassSettings.EnterLockedCars
            end
        end
    end
end

LoadConfig()

-- [ DRAWING: FOV ]
local hasDrawing = (Drawing ~= nil)
local FOVCircle
if hasDrawing then
    pcall(function()
        FOVCircle = Drawing.new("Circle")
        FOVCircle.Color = Color3.fromRGB(255, 255, 255)
        FOVCircle.Thickness = 1
        FOVCircle.NumSides = 60
        FOVCircle.Filled = false
        FOVCircle.Transparency = 1
    end)
end




-- [ ESP FRAMEWORK ]
local ESPObjects = {}

local function CreateESP(player)
    if not hasDrawing then return end
    pcall(function()
        local esp = {
            Box = Drawing.new("Square"),
            Tracer = Drawing.new("Line"),
            NameText = Drawing.new("Text"),
            HealthText = Drawing.new("Text"),
            WantedText = Drawing.new("Text"),
            ItemText = Drawing.new("Text"),
            TeamText = Drawing.new("Text")
        }
        
        -- Text Styling
        for _, text in ipairs({esp.NameText, esp.HealthText, esp.WantedText, esp.ItemText, esp.TeamText}) do
            text.Size = 16
            text.Center = true
            text.Outline = true
            text.Font = 2
        end
        
        esp.Box.Thickness = 1
        esp.Box.Filled = false
        esp.Tracer.Thickness = 1
        
        ESPObjects[player] = esp
    end)
end

local function RemoveESP(player)
    if ESPObjects[player] then
        for _, obj in pairs(ESPObjects[player]) do
            obj:Remove()
        end
        ESPObjects[player] = nil
    end
end

for _, p in pairs(Players:GetPlayers()) do
    if p ~= LocalPlayer then CreateESP(p) end
end
Players.PlayerAdded:Connect(function(p) CreateESP(p) end)
Players.PlayerRemoving:Connect(function(p) RemoveESP(p) end)

-- [ AIMBOT FUNCTIONS ]
local function IsVisible(targetPart)
    local origin = Camera.CFrame.Position
    local direction = targetPart.Position - origin
    
    local raycastParams = RaycastParams.new()
    raycastParams.FilterDescendantsInstances = {LocalPlayer.Character, Camera}
    raycastParams.FilterType = Enum.RaycastFilterType.Blacklist
    raycastParams.IgnoreWater = true
    
    local raycastResult = workspace:Raycast(origin, direction, raycastParams)
    
    if raycastResult and raycastResult.Instance then
        if raycastResult.Instance:IsDescendantOf(targetPart.Parent) then
            return true
        end
        return false
    end
    return true
end

local function GetClosestPlayer()
    local closestDist = math.huge
    local closestPlayer = nil
    local mousePos = UserInputService:GetMouseLocation()
    
    for _, player in pairs(Players:GetPlayers()) do
        if player ~= LocalPlayer and player.Character and player.Character:FindFirstChild(AimbotSettings.TargetPart) and player.Character:FindFirstChild("Humanoid") and player.Character.Humanoid.Health > 0 and not isWhitelisted(player) then
            if AimbotSettings.TeamCheck and player.Team == LocalPlayer.Team then continue end
            local targetPart = player.Character[AimbotSettings.TargetPart]
            local pos, onScreen = Camera:WorldToViewportPoint(targetPart.Position)
            
            if onScreen then
                local dist = (Vector2.new(mousePos.X, mousePos.Y) - Vector2.new(pos.X, pos.Y)).Magnitude
                
                if AimbotSettings.FOV then
                    if dist <= AimbotSettings.FOVRadius then
                        if AimbotSettings.WallCheck then
                            if IsVisible(targetPart) and dist < closestDist then
                                closestDist = dist
                                closestPlayer = player
                            end
                        elseif dist < closestDist then
                            closestDist = dist
                            closestPlayer = player
                        end
                    end
                else
                    if AimbotSettings.WallCheck then
                        if IsVisible(targetPart) and dist < closestDist then
                            closestDist = dist
                            closestPlayer = player
                        end
                    elseif dist < closestDist then
                        closestDist = dist
                        closestPlayer = player
                    end
                end
            end
        end
    end
    
    return closestPlayer
end




local isAiming = false

-- [ HELPER FUNCTIONS ]
local function getExecutorLevel()
    local level = "Unknown"
    local success, res = pcall(function() return getidentity() end)
    if success then level = tostring(res) end
    if level == "Unknown" then
        success, res = pcall(function() return getthreadidentity() end)
        if success then level = tostring(res) end
    end
    return level
end

local function CoolNotification(title, text)
    OrionLib:MakeNotification({
        Name = title,
        Content = text,
        Time = 5
    })
    
    task.spawn(function()
        local coreGui = game:GetService("CoreGui")
        local orionGui = coreGui:FindFirstChild("Orion") or coreGui:FindFirstChildWhichIsA("ScreenGui")
        
        if orionGui then
            local holder = orionGui:FindFirstChild("NotificationHolder", true)
            if not holder then
                for _, v in pairs(orionGui:GetChildren()) do
                    if v:IsA("Frame") and v.Size.Y.Scale == 1 then
                        holder = v
                        break
                    end
                end
            end
            
            if holder then
                local function applyGradient(child)
                    task.wait(0.1)
                    local frame = child:FindFirstChildWhichIsA("Frame")
                    local titleLabel = frame and (frame:FindFirstChild("Title") or frame:FindFirstChild("NotificationTitle"))
                    if titleLabel then
                        local grad = Instance.new("UIGradient")
                        grad.Color = ColorSequence.new({
                            ColorSequenceKeypoint.new(0, Color3.fromRGB(255, 0, 255)),
                            ColorSequenceKeypoint.new(0.5, Color3.fromRGB(0, 255, 255)),
                            ColorSequenceKeypoint.new(1, Color3.fromRGB(255, 255, 0))
                        })
                        grad.Parent = titleLabel
                        task.spawn(function()
                            local rot = 0
                            while grad.Parent do
                                rot = (rot + 5) % 360
                                grad.Rotation = rot
                                task.wait()
                            end
                        end)
                    end
                end
                
                local conn
                conn = holder.ChildAdded:Connect(function(child)
                    applyGradient(child)
                    conn:Disconnect()
                end)
                task.delay(1, function() if conn then conn:Disconnect() end end)
            end
        end
    end)
end

-- [ AIMBOT HUD ]
local AimbotHUD = Instance.new("ScreenGui")
AimbotHUD.Name = "CrypticAimbotHUD"
AimbotHUD.Parent = (game:GetService("CoreGui"):FindFirstChild("RobloxGui") or game:GetService("CoreGui"))
AimbotHUD.Enabled = false

local HUDMain = Instance.new("Frame")
HUDMain.Name = "Main"
HUDMain.Size = UDim2.new(0, 220, 0, 90)
HUDMain.Position = UDim2.new(0.5, -110, 0.85, 0)
HUDMain.BackgroundColor3 = Color3.fromRGB(15, 15, 15)
HUDMain.BackgroundTransparency = 0.25
HUDMain.BorderSizePixel = 0
HUDMain.Parent = AimbotHUD

local HUDCorner = Instance.new("UICorner")
HUDCorner.CornerRadius = UDim.new(0, 15)
HUDCorner.Parent = HUDMain

local HUDStroke = Instance.new("UIStroke")
HUDStroke.Thickness = 2.5
HUDStroke.ApplyStrokeMode = Enum.ApplyStrokeMode.Border
HUDStroke.Parent = HUDMain

local HUDGradient = Instance.new("UIGradient")
HUDGradient.Color = ColorSequence.new({
    ColorSequenceKeypoint.new(0, Color3.fromRGB(255, 0, 255)),
    ColorSequenceKeypoint.new(0.5, Color3.fromRGB(0, 255, 255)),
    ColorSequenceKeypoint.new(1, Color3.fromRGB(255, 255, 0))
})
HUDGradient.Parent = HUDStroke

local HUDAvatar = Instance.new("ImageLabel")
HUDAvatar.Name = "Avatar"
HUDAvatar.Size = UDim2.new(0, 65, 0, 65)
HUDAvatar.Position = UDim2.new(0, 12, 0, 12)
HUDAvatar.BackgroundColor3 = Color3.fromRGB(30, 30, 30)
HUDAvatar.BackgroundTransparency = 0.4
HUDAvatar.Image = ""
HUDAvatar.Parent = HUDMain

local HUDAvatarCorner = Instance.new("UICorner")
HUDAvatarCorner.CornerRadius = UDim.new(0, 10)
HUDAvatarCorner.Parent = HUDAvatar

local HUDStatus = Instance.new("TextLabel")
HUDStatus.Name = "Status"
HUDStatus.Size = UDim2.new(1, -90, 0, 20)
HUDStatus.Position = UDim2.new(0, 85, 0, 20)
HUDStatus.BackgroundTransparency = 1
HUDStatus.Text = "STATUS: IDLE"
HUDStatus.TextColor3 = Color3.fromRGB(255, 50, 50)
HUDStatus.TextSize = 15
HUDStatus.Font = Enum.Font.GothamBold
HUDStatus.TextXAlignment = Enum.TextXAlignment.Left
HUDStatus.Parent = HUDMain

local HUDTarget = Instance.new("TextLabel")
HUDTarget.Name = "Target"
HUDTarget.Size = UDim2.new(1, -90, 0, 20)
HUDTarget.Position = UDim2.new(0, 85, 0, 45)
HUDTarget.BackgroundTransparency = 1
HUDTarget.Text = "TARGET: NONE"
HUDTarget.TextColor3 = Color3.fromRGB(255, 255, 255)
HUDTarget.TextSize = 13
HUDTarget.Font = Enum.Font.Gotham
HUDTarget.TextXAlignment = Enum.TextXAlignment.Left
HUDTarget.Parent = HUDMain

task.spawn(function()
    local rot = 0
    while true do
        rot = (rot + 3) % 360
        HUDGradient.Rotation = rot
        task.wait()
    end
end)

local currentHUDTargetId = 0
local function updateHUD(target)
    if not AimbotSettings.HUD then 
        AimbotHUD.Enabled = false
        return 
    end
    
    AimbotHUD.Enabled = true
    if target and isAiming then
        HUDStatus.Text = "STATUS: LOCKING"
        HUDStatus.TextColor3 = Color3.fromRGB(0, 255, 127)
        HUDTarget.Text = "TARGET: " .. (target.DisplayName or target.Name)
        
        if currentHUDTargetId ~= target.UserId then
            currentHUDTargetId = target.UserId
            HUDAvatar.Image = Players:GetUserThumbnailAsync(target.UserId, Enum.ThumbnailType.HeadShot, Enum.ThumbnailSize.Size100x100)
        end
    else
        HUDStatus.Text = "STATUS: IDLE"
        HUDStatus.TextColor3 = Color3.fromRGB(255, 69, 0)
        HUDTarget.Text = "TARGET: NONE"
        HUDAvatar.Image = ""
        currentHUDTargetId = 0
    end
end

local function ShowExecutorLevelHUD(level)
    local sg = Instance.new("ScreenGui")
    sg.Name = "ExecutorLevelHUD"
    sg.Parent = (game:GetService("CoreGui"):FindFirstChild("RobloxGui") or game:GetService("CoreGui"))
    
    local main = Instance.new("Frame")
    main.Size = UDim2.new(0, 260, 0, 110)
    main.Position = UDim2.new(0.5, -130, 0.4, -55)
    main.BackgroundColor3 = Color3.fromRGB(15, 15, 15)
    main.BackgroundTransparency = 0.2
    main.BorderSizePixel = 0
    main.Parent = sg
    
    local corner = Instance.new("UICorner")
    corner.CornerRadius = UDim.new(0, 18)
    corner.Parent = main
    
    local stroke = Instance.new("UIStroke")
    stroke.Thickness = 3.5
    stroke.ApplyStrokeMode = Enum.ApplyStrokeMode.Border
    stroke.Parent = main
    
    local grad = Instance.new("UIGradient")
    grad.Color = ColorSequence.new({
        ColorSequenceKeypoint.new(0, Color3.fromRGB(255, 0, 255)),
        ColorSequenceKeypoint.new(0.5, Color3.fromRGB(0, 255, 255)),
        ColorSequenceKeypoint.new(1, Color3.fromRGB(255, 255, 0))
    })
    grad.Parent = stroke
    
    local title = Instance.new("TextLabel")
    title.Size = UDim2.new(1, 0, 0, 40)
    title.Position = UDim2.new(0, 0, 0, 15)
    title.BackgroundTransparency = 1
    title.Text = "EXECUTOR IDENTITY"
    title.TextColor3 = Color3.fromRGB(200, 200, 200)
    title.TextSize = 16
    title.Font = Enum.Font.GothamBold
    title.Parent = main
    
    local info = Instance.new("TextLabel")
    info.Size = UDim2.new(1, 0, 0, 40)
    info.Position = UDim2.new(0, 0, 0, 50)
    info.BackgroundTransparency = 1
    info.Text = "LEVEL: " .. level
    info.TextColor3 = Color3.fromRGB(0, 255, 150)
    info.TextSize = 26
    info.Font = Enum.Font.GothamBold
    info.Parent = main
    
    task.spawn(function()
        local rot = 0
        while sg.Parent do
            rot = (rot + 4) % 360
            grad.Rotation = rot
            task.wait()
        end
    end)
    
    task.delay(5, function()
        local ts = game:GetService("TweenService")
        local ti = TweenInfo.new(1, Enum.EasingStyle.Quint, Enum.EasingDirection.Out)
        ts:Create(main, ti, {BackgroundTransparency = 1}):Play()
        ts:Create(info, ti, {TextTransparency = 1}):Play()
        ts:Create(title, ti, {TextTransparency = 1}):Play()
        local st = ts:Create(stroke, ti, {Transparency = 1})
        st:Play()
        st.Completed:Connect(function() sg:Destroy() end)
    end)
end

-- [ MAIN RENDER LOOP ]
RunService.Stepped:Connect(function()
    if NoclipEnabled and LocalPlayer.Character then
        for _, part in pairs(LocalPlayer.Character:GetDescendants()) do
            if part:IsA("BasePart") and part.CanCollide then
                part.CanCollide = false
            end
        end
    end
end)

UserInputService.JumpRequest:Connect(function()
	if InfJumpEnabled and LocalPlayer.Character and LocalPlayer.Character:FindFirstChildOfClass("Humanoid") then
		LocalPlayer.Character:FindFirstChildOfClass("Humanoid"):ChangeState("Jumping")
	end
end)

RunService.RenderStepped:Connect(function()
    -- CFrame Speed Boost
    if CFrameSpeedEnabled and CFrameSpeed > 0 and LocalPlayer.Character and LocalPlayer.Character:FindFirstChild("HumanoidRootPart") and LocalPlayer.Character:FindFirstChild("Humanoid") then
        local hrp = LocalPlayer.Character.HumanoidRootPart
        local hum = LocalPlayer.Character.Humanoid
        if hum.MoveDirection.Magnitude > 0 then
            hrp.CFrame = hrp.CFrame + (hum.MoveDirection * (CFrameSpeed / 10))
        end
    end

    -- Update FOV & HUD
    local target = GetClosestPlayer()
    
    if AimbotSettings.FOV and FOVCircle then
        FOVCircle.Visible = true
        FOVCircle.Position = UserInputService:GetMouseLocation()
        FOVCircle.Radius = AimbotSettings.FOVRadius
        
        if target and isAiming then
            FOVCircle.Color = Color3.fromRGB(0, 255, 0) -- Grün wenn locked
        else
            FOVCircle.Color = Color3.fromRGB(255, 0, 0) -- Rot wenn inaktiv
        end
    elseif FOVCircle then
        FOVCircle.Visible = false
    end



    
    updateHUD(target)
    
    -- Update Aimbot
    if AimbotSettings.Enabled and isAiming then
        if target and target.Character and target.Character:FindFirstChild(AimbotSettings.TargetPart) then
            local targetPos = target.Character[AimbotSettings.TargetPart].Position
            local aimPos = Camera:WorldToViewportPoint(targetPos)
            local mousePos = UserInputService:GetMouseLocation()
            
            local smoothX = (aimPos.X - mousePos.X) / AimbotSettings.Smoothness
            local smoothY = (aimPos.Y - mousePos.Y) / AimbotSettings.Smoothness
            
            if mousemoverel then
                mousemoverel(smoothX, smoothY)
            end
        end
    end
    
    -- Update ESP
    for player, esp in pairs(ESPObjects) do
        if player.Character and player.Character:FindFirstChild("HumanoidRootPart") and player.Character:FindFirstChild("Humanoid") and player.Character.Humanoid.Health > 0 then
            local hrp = player.Character.HumanoidRootPart
            local head = player.Character:FindFirstChild("Head")
            
            local distFromCam = (Camera.CFrame.Position - hrp.Position).Magnitude
            local pos, onScreen = Camera:WorldToViewportPoint(hrp.Position)
            
            local espColor = ESPSettings.Color
            local isWanted = hrp:GetAttribute("IsWanted")
            local teamName = player.Team and string.lower(player.Team.Name) or ""

            if isWanted then
                espColor = Color3.fromRGB(255, 165, 0) -- Orange
            elseif teamName:match("police") or teamName:match("polizei") or teamName:match("cop") then
                espColor = Color3.fromRGB(50, 150, 255) -- Blau
            elseif teamName:match("medic") or teamName:match("ems") or teamName:match("rettungsdienst") then
                espColor = Color3.fromRGB(255, 50, 50) -- Rot
            elseif teamName:match("fire") or teamName:match("feuerwehr") then
                espColor = Color3.fromRGB(255, 50, 50) -- Rot
            end

            -- Chams (Funktioniert auch Off-Screen)
            if distFromCam <= ESPSettings.RenderDistance then
                if ESPSettings.Chams then
                    local highlight = player.Character:FindFirstChild("ESP_Highlight")
                    if not highlight then
                        highlight = Instance.new("Highlight")
                        highlight.Name = "ESP_Highlight"
                        highlight.Parent = player.Character
                        highlight.FillTransparency = 0.5
                        highlight.OutlineTransparency = 0
                    end
                    highlight.FillColor = espColor
                    highlight.OutlineColor = Color3.fromRGB(255, 255, 255)
                    highlight.Enabled = true
                else
                    local highlight = player.Character:FindFirstChild("ESP_Highlight")
                    if highlight then highlight:Destroy() end
                end
            else
                local highlight = player.Character:FindFirstChild("ESP_Highlight")
                if highlight then highlight:Destroy() end
            end
            
            if onScreen and head and distFromCam <= ESPSettings.RenderDistance then
                local headPos = Camera:WorldToViewportPoint(head.Position + Vector3.new(0, 0.5, 0))
                local legPos = Camera:WorldToViewportPoint(hrp.Position - Vector3.new(0, 3, 0))
                
                local boxHeight = math.abs(headPos.Y - legPos.Y)
                local boxWidth = boxHeight / 1.5
                
                -- Box
                if ESPSettings.Box and esp.Box then
                    esp.Box.Visible = true
                    esp.Box.Size = Vector2.new(boxWidth, boxHeight)
                    esp.Box.Position = Vector2.new(pos.X - boxWidth / 2, headPos.Y)
                    esp.Box.Color = espColor
                elseif esp.Box then
                    esp.Box.Visible = false
                end
                
                -- Tracer
                if ESPSettings.Tracers and esp.Tracer then
                    esp.Tracer.Visible = true
                    esp.Tracer.From = Vector2.new(Camera.ViewportSize.X / 2, Camera.ViewportSize.Y)
                    esp.Tracer.To = Vector2.new(pos.X, legPos.Y)
                    esp.Tracer.Color = espColor
                elseif esp.Tracer then
                    esp.Tracer.Visible = false
                end
                
                -- Layout Logic (Bottom to Top for above, Top to Bottom for below)
                local currentTopY = headPos.Y - 5
                local currentBottomY = legPos.Y + 5
                
                -- Name
                if ESPSettings.Name and esp.NameText then
                    esp.NameText.Visible = true
                    esp.NameText.Text = player.DisplayName or player.Name
                    esp.NameText.Position = Vector2.new(pos.X, currentTopY - 16)
                    esp.NameText.Color = espColor
                    currentTopY = currentTopY - 16
                elseif esp.NameText then
                    esp.NameText.Visible = false
                end
                
                -- Team
                if ESPSettings.Team and esp.TeamText then
                    if player.Team then
                        esp.TeamText.Visible = true
                        esp.TeamText.Text = "[" .. player.Team.Name .. "]"
                        esp.TeamText.Color = player.TeamColor.Color
                        esp.TeamText.Position = Vector2.new(pos.X, currentTopY - 16)
                        currentTopY = currentTopY - 16
                    else
                        esp.TeamText.Visible = false
                    end
                elseif esp.TeamText then
                    esp.TeamText.Visible = false
                end
                
                -- Health
                if ESPSettings.Health and esp.HealthText then
                    esp.HealthText.Visible = true
                    local health = math.floor(player.Character.Humanoid.Health)
                    esp.HealthText.Text = "HP: " .. health
                    esp.HealthText.Color = Color3.fromRGB(0, 255, 0)
                    esp.HealthText.Position = Vector2.new(pos.X, currentTopY - 16)
                    currentTopY = currentTopY - 16
                elseif esp.HealthText then
                    esp.HealthText.Visible = false
                end
                
                -- Wanted
                if ESPSettings.Wanted and esp.WantedText then
                    if isWanted then
                        esp.WantedText.Visible = true
                        esp.WantedText.Text = "WANTED"
                        esp.WantedText.Color = Color3.fromRGB(255, 165, 0)
                        esp.WantedText.Position = Vector2.new(pos.X, currentTopY - 16)
                        currentTopY = currentTopY - 16
                    else
                        esp.WantedText.Visible = false
                    end
                elseif esp.WantedText then
                    esp.WantedText.Visible = false
                end
                
                -- Item
                if ESPSettings.Item and esp.ItemText then
                    local itemHeld = "None"
                    for _, child in pairs(player.Character:GetChildren()) do
                        if child:IsA("Tool") then
                            itemHeld = child.Name
                            break
                        end
                    end
                    if itemHeld ~= "None" then
                        esp.ItemText.Visible = true
                        esp.ItemText.Text = itemHeld
                        esp.ItemText.Color = Color3.fromRGB(200, 200, 200)
                        esp.ItemText.Position = Vector2.new(pos.X, currentBottomY)
                        currentBottomY = currentBottomY + 16
                    else
                        esp.ItemText.Visible = false
                    end
                elseif esp.ItemText then
                    esp.ItemText.Visible = false
                end
                
            else
                if esp.Box then esp.Box.Visible = false end
                if esp.Tracer then esp.Tracer.Visible = false end
                if esp.NameText then esp.NameText.Visible = false end
                if esp.HealthText then esp.HealthText.Visible = false end
                if esp.WantedText then esp.WantedText.Visible = false end
                if esp.ItemText then esp.ItemText.Visible = false end
                if esp.TeamText then esp.TeamText.Visible = false end
            end
        else
            if esp.Box then esp.Box.Visible = false end
            if esp.Tracer then esp.Tracer.Visible = false end
            if esp.NameText then esp.NameText.Visible = false end
            if esp.HealthText then esp.HealthText.Visible = false end
            if esp.WantedText then esp.WantedText.Visible = false end
            if esp.ItemText then esp.ItemText.Visible = false end
            if esp.TeamText then esp.TeamText.Visible = false end
            
            if player.Character then
                local hl = player.Character:FindFirstChild("ESP_Highlight")
                if hl then hl.Enabled = false end
            end
        end
    end
end)

-- [ UI BUILD ]
local Window = OrionLib:MakeWindow({
    Name = "Cryptic Hub - Vanta API", 
    HidePremium = false, 
    SaveConfig = true, 
    ConfigFolder = "CrypticHubConfig"
})

-- =====================
-- SILENT AIM TAB
-- =====================
local SilentAimTab = Window:MakeTab({ Name = "SilentAim", Icon = "rbxassetid://10734944510", PremiumOnly = false })

SilentAimTab:AddParagraph("Work in Progress", "We are currently reworking the Silent Aim system to ensure better compatibility and performance. Stay tuned for updates!")




-- =====================
-- AIMBOT TAB
-- =====================
local AimbotTab = Window:MakeTab({ Name = "Aimbot", Icon = "rbxassetid://10734944510", PremiumOnly = false })

AimbotTab:AddSection({ Name = "--- Main Settings ---" })
AimbotTab:AddToggle({ Name = "Enable Aimbot (Hold Key)", Default = AimbotSettings.Enabled, Callback = function(v) AimbotSettings.Enabled = v; SaveConfig() end })

AimbotTab:AddBind({
	Name = "Aimbot Keybind",
	Default = Enum.UserInputType.MouseButton2,
	Hold = true,
	Callback = function(Value)
		isAiming = Value
	end    
})

AimbotTab:AddDropdown({
	Name = "Target Part",
	Default = AimbotSettings.TargetPart,
	Options = {"Head", "Torso", "HumanoidRootPart"},
	Callback = function(v) AimbotSettings.TargetPart = v; SaveConfig() end
})

AimbotTab:AddSection({ Name = "--- Checks & Precision ---" })
AimbotTab:AddToggle({ Name = "Wall Check", Default = AimbotSettings.WallCheck, Callback = function(v) AimbotSettings.WallCheck = v; SaveConfig() end })
AimbotTab:AddToggle({ Name = "Team Check", Default = AimbotSettings.TeamCheck, Callback = function(v) AimbotSettings.TeamCheck = v; SaveConfig() end })
AimbotTab:AddSlider({ Name = "Smoothness", Min = 1, Max = 15, Default = AimbotSettings.Smoothness, Increment = 0.1, ValueName = "px", Callback = function(v) AimbotSettings.Smoothness = v; SaveConfig() end })

AimbotTab:AddSection({ Name = "--- FOV Settings ---" })
AimbotTab:AddToggle({ Name = "Show FOV Circle", Default = AimbotSettings.FOV, Callback = function(v) AimbotSettings.FOV = v; SaveConfig() end })
AimbotTab:AddSlider({ Name = "FOV Radius", Min = 10, Max = 800, Default = AimbotSettings.FOVRadius, Increment = 1, ValueName = "px", Callback = function(v) AimbotSettings.FOVRadius = v; SaveConfig() end })

AimbotTab:AddSection({ Name = "--- HUD & Status ---" })
AimbotTab:AddToggle({ Name = "Aimbot HUD Status", Default = AimbotSettings.HUD, Callback = function(v) 
    AimbotSettings.HUD = v
    if AimbotHUD then AimbotHUD.Enabled = v end
    SaveConfig() 
end })

-- [ AIMBOT HUD SYSTEM ]
local AimbotHUD, HUDFrame, StatusLabel, TargetLabel, SmoothLabel
local function CreateHUD()
    AimbotHUD = Instance.new("ScreenGui")
    AimbotHUD.Name = "AimbotHUD"
    AimbotHUD.Parent = (game:GetService("CoreGui"):FindFirstChild("Orion") and game:GetService("CoreGui")) or LocalPlayer:WaitForChild("PlayerGui")
    AimbotHUD.Enabled = AimbotSettings.HUD

    HUDFrame = Instance.new("Frame")
    HUDFrame.Size = UDim2.new(0, 180, 0, 90)
    HUDFrame.Position = UDim2.new(0.02, 0, 0.3, 0)
    HUDFrame.BackgroundColor3 = Color3.fromRGB(25, 25, 25)
    HUDFrame.BackgroundTransparency = 0.3
    HUDFrame.BorderSizePixel = 0
    HUDFrame.Parent = AimbotHUD

    local HUDCorner = Instance.new("UICorner")
    HUDCorner.CornerRadius = UDim.new(0, 6)
    HUDCorner.Parent = HUDFrame

    local HUDStroke = Instance.new("UIStroke")
    HUDStroke.Color = Color3.fromRGB(80, 80, 80)
    HUDStroke.Thickness = 1.5
    HUDStroke.Parent = HUDFrame

    local TitleLabel = Instance.new("TextLabel")
    TitleLabel.Size = UDim2.new(1, 0, 0, 25)
    TitleLabel.Text = "  AIMBOT STATUS"
    TitleLabel.TextColor3 = Color3.fromRGB(255, 255, 255)
    TitleLabel.TextSize = 14
    TitleLabel.Font = Enum.Font.GothamBold
    TitleLabel.TextXAlignment = Enum.TextXAlignment.Left
    TitleLabel.BackgroundTransparency = 1
    TitleLabel.Parent = HUDFrame

    StatusLabel = Instance.new("TextLabel")
    StatusLabel.Size = UDim2.new(1, 0, 0, 20)
    StatusLabel.Position = UDim2.new(0, 0, 0, 25)
    StatusLabel.Text = "  Status: [ INACTIVE ]"
    StatusLabel.TextColor3 = Color3.fromRGB(200, 50, 50)
    StatusLabel.TextSize = 13
    StatusLabel.Font = Enum.Font.Gotham
    StatusLabel.TextXAlignment = Enum.TextXAlignment.Left
    StatusLabel.BackgroundTransparency = 1
    StatusLabel.Parent = HUDFrame

    TargetLabel = Instance.new("TextLabel")
    TargetLabel.Size = UDim2.new(1, 0, 0, 20)
    TargetLabel.Position = UDim2.new(0, 0, 0, 45)
    TargetLabel.Text = "  Target: [ NONE ]"
    TargetLabel.TextColor3 = Color3.fromRGB(200, 200, 200)
    TargetLabel.TextSize = 13
    TargetLabel.Font = Enum.Font.Gotham
    TargetLabel.TextXAlignment = Enum.TextXAlignment.Left
    TargetLabel.BackgroundTransparency = 1
    TargetLabel.Parent = HUDFrame

    SmoothLabel = Instance.new("TextLabel")
    SmoothLabel.Size = UDim2.new(1, 0, 0, 20)
    SmoothLabel.Position = UDim2.new(0, 0, 0, 65)
    SmoothLabel.Text = "  Smooth: [ 5.0 ]"
    SmoothLabel.TextColor3 = Color3.fromRGB(200, 200, 200)
    SmoothLabel.TextSize = 13
    SmoothLabel.Font = Enum.Font.Gotham
    SmoothLabel.TextXAlignment = Enum.TextXAlignment.Left
    SmoothLabel.BackgroundTransparency = 1
    SmoothLabel.Parent = HUDFrame

    local BrandLabel = Instance.new("TextLabel")
    BrandLabel.Size = UDim2.new(1, -10, 0, 20)
    BrandLabel.Position = UDim2.new(0, 0, 1, -20)
    BrandLabel.Text = "Cryptic Hub  "
    BrandLabel.TextColor3 = Color3.fromRGB(150, 150, 150)
    BrandLabel.TextSize = 11
    BrandLabel.Font = Enum.Font.GothamBold
    BrandLabel.TextXAlignment = Enum.TextXAlignment.Right
    BrandLabel.BackgroundTransparency = 1
    BrandLabel.Parent = HUDFrame
end

CreateHUD()

RunService.RenderStepped:Connect(function()
    if AimbotSettings.HUD and StatusLabel and TargetLabel and SmoothLabel then
        local target = GetClosestPlayer()
        if isAiming and AimbotSettings.Enabled then
            StatusLabel.Text = "  Status: [ ACTIVE ]"
            StatusLabel.TextColor3 = Color3.fromRGB(50, 200, 50)
            if HUDStroke then HUDStroke.Color = Color3.fromRGB(50, 200, 50) end
        else
            StatusLabel.Text = "  Status: [ READY ]"
            StatusLabel.TextColor3 = Color3.fromRGB(200, 200, 200)
            if HUDStroke then HUDStroke.Color = Color3.fromRGB(80, 80, 80) end
        end
        
        if target then
            TargetLabel.Text = "  Target: [ " .. target.DisplayName .. " ]"
        else
            TargetLabel.Text = "  Target: [ NONE ]"
        end

        SmoothLabel.Text = "  Smooth: [ " .. string.format("%.1f", AimbotSettings.Smoothness) .. " ]"
    end
end)

AimbotTab:AddLabel("--- Whitelist ---")

local function getPlayerList()
    local names = {}
    for _, p in pairs(Players:GetPlayers()) do
        if p ~= LocalPlayer then
            table.insert(names, p.Name)
        end
    end
    return names
end

local WhitelistDropdown = AimbotTab:AddDropdown({
	Name = "Whitelist Player",
	Default = "None",
	Options = getPlayerList(),
	Callback = function(v)
		if v ~= "None" then
            AimbotWhitelist[v] = not AimbotWhitelist[v]
            local status = AimbotWhitelist[v] and "Whitelisted" or "Removed"
            OrionLib:MakeNotification({Name = "Whitelist", Content = v .. " is now " .. status, Time = 2})
        end
	end    
})

AimbotTab:AddButton({
	Name = "Refresh Player List",
	Callback = function()
		WhitelistDropdown:Refresh(getPlayerList(), true)
	end    
})


-- =====================
-- VISUALS TAB
-- =====================
local VisualsTab = Window:MakeTab({ Name = "Visuals", Icon = "rbxassetid://10734945415", PremiumOnly = false })

VisualsTab:AddSection({ Name = "--- ESP Toggles ---" })
VisualsTab:AddToggle({ Name = "Box ESP", Default = ESPSettings.Box, Callback = function(v) ESPSettings.Box = v; SaveConfig() end })
VisualsTab:AddToggle({ Name = "Name ESP", Default = ESPSettings.Name, Callback = function(v) ESPSettings.Name = v; SaveConfig() end })
VisualsTab:AddToggle({ Name = "Team ESP", Default = ESPSettings.Team, Callback = function(v) ESPSettings.Team = v; SaveConfig() end })
VisualsTab:AddToggle({ Name = "Health ESP", Default = ESPSettings.Health, Callback = function(v) ESPSettings.Health = v; SaveConfig() end })
VisualsTab:AddToggle({ Name = "Wanted ESP", Default = ESPSettings.Wanted, Callback = function(v) ESPSettings.Wanted = v; SaveConfig() end })
VisualsTab:AddToggle({ Name = "Item ESP", Default = ESPSettings.Item, Callback = function(v) ESPSettings.Item = v; SaveConfig() end })
VisualsTab:AddToggle({ Name = "Tracers", Default = ESPSettings.Tracers, Callback = function(v) ESPSettings.Tracers = v; SaveConfig() end })
VisualsTab:AddToggle({ Name = "Chams ESP", Default = ESPSettings.Chams, Callback = function(v) ESPSettings.Chams = v; SaveConfig() end })
VisualsTab:AddToggle({ Name = "Car ESP", Default = ESPSettings.CarESP, Callback = function(v) ESPSettings.CarESP = v; SaveConfig() end })

VisualsTab:AddSection({ Name = "--- Visual Settings ---" })
VisualsTab:AddSlider({ Name = "Render Distance", Min = 50, Max = 10000, Default = ESPSettings.RenderDistance, Increment = 50, ValueName = "Studs", Callback = function(v) ESPSettings.RenderDistance = v; SaveConfig() end })
VisualsTab:AddColorpicker({ Name = "ESP Color", Default = ESPSettings.Color, Callback = function(v) ESPSettings.Color = v; SaveConfig() end })

task.spawn(function()
    while true do
        task.wait(2)
        local folder = workspace:FindFirstChild("Vehicles")
        if folder then
            for _, car in ipairs(folder:GetChildren()) do
                if car:IsA("Model") and car.Name ~= LocalPlayer.Name then
                    local highlight = car:FindFirstChild("CarESP_Highlight")
                    if ESPSettings.CarESP then
                        if not highlight then
                            highlight = Instance.new("Highlight")
                            highlight.Name = "CarESP_Highlight"
                            highlight.FillColor = Color3.fromRGB(255, 100, 100)
                            highlight.OutlineColor = Color3.fromRGB(0, 0, 0)
                            highlight.FillTransparency = 0.5
                            highlight.OutlineTransparency = 0
                            highlight.Parent = car
                        end
                    else
                        if highlight then highlight:Destroy() end
                    end
                elseif car.Name == LocalPlayer.Name then
                    local highlight = car:FindFirstChild("CarESP_Highlight")
                    if highlight then highlight:Destroy() end
                end
            end
            
            if not ESPSettings.CarESP then
                for _, car in ipairs(folder:GetChildren()) do
                    local highlight = car:FindFirstChild("CarESP_Highlight")
                    if highlight then highlight:Destroy() end
                end
            end
        end
    end
end)

-- =====================
-- BYPASS TAB
-- =====================
local BypassTab = Window:MakeTab({ Name = "Bypasses", Icon = "rbxassetid://10734947963", PremiumOnly = false })

local supportsHooking = (hookmetamethod ~= nil and hookfunction ~= nil and getnamecallmethod ~= nil and checkcaller ~= nil and getgc ~= nil and debug ~= nil)
getgenv().VehicleDamageBypass = false
getgenv().AnticheatBypass = false
local vehicleDamageRemote
local acRemotes = {}

BypassTab:AddParagraph("Executor Info", "Executor: " .. (identifyexecutor and identifyexecutor() or "Unknown") .. "\nStatus: " .. (supportsHooking and "Full Support" or "Limited Support"))

if supportsHooking then
    task.spawn(function()
        pcall(function()
            local folder = game:GetService("ReplicatedStorage"):WaitForChild("0Mg")
            vehicleDamageRemote = folder:WaitForChild("c7e93278-72cc-4839-a68c-aff877486501")

            local acUUIDs = {
                "803c5a16-a32b-433e-8f0e-4dbbf9f6431a",
                "bb904d34-3dd8-45cf-8e2f-64bfc277567b",
                "2c0a65bb-72b2-43eb-a05e-2b3beb864f56",
                "1322511d-b6f4-4539-a9a4-b3caa794099d",
                "1c7d2426-302a-4648-9c17-478051a868f8",
                "19a86a6f-45a7-4796-930b-d7d8f3ec641f"
            }
            for _, id in ipairs(acUUIDs) do
                local r = folder:FindFirstChild(id) or folder:WaitForChild(id, 5)
                if r then acRemotes[r] = true end
            end
        end)
    end)

    local oldNamecall
    oldNamecall = hookmetamethod(game, "__namecall", function(self, ...)
        local method = getnamecallmethod()
        if not checkcaller() and method == "FireServer" then
            if getgenv().VehicleDamageBypass and self == vehicleDamageRemote then
                return nil
            end
            if getgenv().AnticheatBypass and acRemotes[self] then
                return nil
            end
        end
        return oldNamecall(self, ...)
    end)

    BypassTab:AddToggle({
        Name = "Vehicle Damage Bypass",
        Default = BypassSettings.VehicleDamage,
        Callback = function(Value)
            BypassSettings.VehicleDamage = Value
            getgenv().VehicleDamageBypass = Value
            SaveConfig()
        end
    })

    getgenv().InfStamina = false
    local staminaHooked = false
    local oldStaminaFunc

    BypassTab:AddToggle({
        Name = "Infinite Stamina",
        Default = BypassSettings.InfStamina,
        Callback = function(Value)
            BypassSettings.InfStamina = Value
            getgenv().InfStamina = Value
            if Value and not staminaHooked then
                local func
                for i, v in pairs(getgc(true)) do
                    if type(v) == "function" and debug.getinfo(v).name == "setStamina" then
                        func = v
                        break
                    end
                end
                if func then
                    staminaHooked = true
                    oldStaminaFunc = hookfunction(func, function(...)
                        if getgenv().InfStamina then
                             local args = {...}
                             return args[1], math.huge
                        end
                        return oldStaminaFunc(...)
                    end)
                else
                    game:GetService("StarterGui"):SetCore("SendNotification", {Title = "Exploits", Text = "Failed to find setStamina function.", Duration = 4})
                end
            end
            SaveConfig()
        end
    })

    BypassTab:AddToggle({
        Name = "Bypass Anticheat",
        Default = BypassSettings.Anticheat,
        Callback = function(Value)
            BypassSettings.Anticheat = Value
            getgenv().AnticheatBypass = Value
            if Value then
                game:GetService("StarterGui"):SetCore("SendNotification", {Title = "Exploits", Text = "Anticheat Bypass activated!", Duration = 3})
            end
            SaveConfig()
        end
    })

    BypassTab:AddToggle({
        Name = "Enter Locked Cars [Left Click]",
        Default = BypassSettings.EnterLockedCars,
        Callback = function(Value)
            BypassSettings.EnterLockedCars = Value
            getgenv().EnterLockedCars = Value
            SaveConfig()
        end
    })

    Mouse.Button1Down:Connect(function()
        if not getgenv().EnterLockedCars then return end
        local target = Mouse.Target
        if not target then return end
        
        local character = LocalPlayer.Character  
        if not character then return end
        local humanoid = character:FindFirstChildOfClass("Humanoid")
        local hrp = character:FindFirstChild("HumanoidRootPart")
        if not humanoid or not hrp then return end
        
        local model = target:FindFirstAncestorOfClass("Model") or target.Parent
        if not model then return end
        
        local vehiclesFolder = workspace:FindFirstChild("Vehicles")
        if not vehiclesFolder or not model:IsDescendantOf(vehiclesFolder) then return end
        
        local foundSeat = nil
        for _, obj in ipairs(model:GetDescendants()) do
            if (obj:IsA("Seat") or obj:IsA("VehicleSeat")) and not obj.Occupant then
                local name = obj.Name:lower()
                if name:find("beifahrer") or name:find("passenger") or name:find("copilot") then
                    foundSeat = obj
                    break
                end
            end
        end
        
        if not foundSeat then
            for _, obj in ipairs(model:GetDescendants()) do
                if (obj:IsA("Seat") or obj:IsA("VehicleSeat")) and not obj.Occupant then
                    foundSeat = obj
                    break
                end
            end
        end
        
        if foundSeat then
            pcall(function() foundSeat.Locked = false end)
            hrp.CFrame = foundSeat.CFrame + Vector3.new(0, 3, 0)
            task.wait(0.1)
            foundSeat:Sit(humanoid)
        end
    end)
else
    BypassTab:AddParagraph("Info", "Your executor does not support Hooking or advanced functions (getgc/hookmetamethod). Bypass features are hidden.")
end

-- =====================
-- MISC TAB
-- =====================
local MiscTab = Window:MakeTab({ Name = "Misc", Icon = "rbxassetid://10734947010", PremiumOnly = false })

MiscTab:AddBind({
	Name = "Noclip Toggle Bind",
	Default = Enum.KeyCode.N,
	Hold = false,
	Callback = function()
		NoclipEnabled = not NoclipEnabled
        OrionLib:MakeNotification({Name = "Noclip", Content = "Noclip is " .. (NoclipEnabled and "ON" or "OFF"), Time = 2})
        SaveConfig()
	end    
})

MiscTab:AddBind({
	Name = "Speed Boost Toggle Bind",
	Default = Enum.KeyCode.V,
	Hold = false,
	Callback = function()
		CFrameSpeedEnabled = not CFrameSpeedEnabled
        OrionLib:MakeNotification({Name = "Speed Boost", Content = "Speed Boost is " .. (CFrameSpeedEnabled and "ON" or "OFF"), Time = 2})
        SaveConfig()
	end    
})

MiscTab:AddSlider({
	Name = "Speed Boost",
	Min = 0,
	Max = 5,
	Default = CFrameSpeed,
	Color = Color3.fromRGB(255, 255, 255),
	Increment = 0.1,
	ValueName = "Boost",
	Callback = function(Value)
        CFrameSpeed = Value
        SaveConfig()
	end    
})

local Emotes = {
    ["Take The L"] = "86882213991020",
    ["Obby Head"] = "122814100170962",
    ["Hide"] = "84868707350198",
    ["Duck"] = "94228088054462",
    ["Tank"] = "114877931551932"
}
local currentAnim = nil

local function playAnimation(catalogId)
    local char = LocalPlayer.Character
    local hum = char and char:FindFirstChildOfClass("Humanoid")
    if not hum then return nil end
    
    local animObj = nil
    pcall(function()
        local objects = game:GetObjects("rbxassetid://" .. catalogId)
        if objects and objects[1] then
            local obj = objects[1]
            animObj = obj:IsA("Animation") and obj or obj:FindFirstChildWhichIsA("Animation", true)
        end
    end)
    
    if not animObj then
        animObj = Instance.new("Animation")
        animObj.AnimationId = "rbxassetid://" .. catalogId
    end
    
    local track = nil
    pcall(function()
        track = hum:LoadAnimation(animObj)
        track:Play()
    end)
    return track
end

MiscTab:AddDropdown({
	Name = "FE Emotes",
	Default = "None",
	Options = {"None", "Take The L", "Obby Head", "Hide", "Duck", "Tank"},
	Callback = function(v)
		if currentAnim then currentAnim:Stop() currentAnim = nil end
        if v ~= "None" then
            task.spawn(function()
                currentAnim = playAnimation(Emotes[v])
                if not currentAnim then
                    OrionLib:MakeNotification({Name = "Error", Content = "Emote konnte nicht geladen werden.", Time = 2})
                end
            end)
		end
	end    
})

local invisibleAnim = nil
MiscTab:AddToggle({
    Name = "Invisible Emote",
    Default = false, -- Emotes usually situational, but we'll save the state if wanted
    Callback = function(Value)
        if Value then
            task.spawn(function()
                invisibleAnim = playAnimation("110509161899145")
            end)
        else
            if invisibleAnim then
                invisibleAnim:Stop()
                invisibleAnim = nil
            end
        end
        SaveConfig()
    end
})

MiscTab:AddToggle({
    Name = "Anti Fall Damage",
    Default = _G.AntiFallEnabled,
    Callback = function(Value)
        _G.AntiFallEnabled = Value
        SaveConfig()
    end
})



MiscTab:AddToggle({
    Name = "Anti Taser",
    Default = AntiTaserEnabled,
    Callback = function(state)
        AntiTaserEnabled = state
        SaveConfig()
    end
})

game:GetService("RunService").Heartbeat:Connect(function()
    if AntiTaserEnabled then
        local char = LocalPlayer.Character
        if char and char:GetAttribute("Tased") == true then
            char:SetAttribute("Tased", false)
        end
    end
end)



MiscTab:AddToggle({
    Name = "Anti Cuff",
    Default = AntiCuffEnabled,
    Callback = function(state)
        AntiCuffEnabled = state
        SaveConfig()
    end
})

task.spawn(function()
    while task.wait(0.1) do
        if AntiCuffEnabled then
            local char = LocalPlayer.Character
            local hrp = char and char:FindFirstChild("HumanoidRootPart")
            if hrp then
                for _, plr in ipairs(Players:GetPlayers()) do
                    if plr ~= LocalPlayer and plr.Team and plr.Team.Name == "Police" then
                        local enemyChar = plr.Character
                        local enemyHrp = enemyChar and enemyChar:FindFirstChild("HumanoidRootPart")
                        if enemyHrp then
                            local dist = (hrp.Position - enemyHrp.Position).Magnitude
                            if dist < 7 then
                                local direction = (hrp.Position - enemyHrp.Position).Unit
                                if direction.Magnitude == 0 then direction = Vector3.new(0,0,1) end
                                
                                local targetPos = hrp.Position + (direction * 10)
                                
                                local tweenInfo = TweenInfo.new(0.3, Enum.EasingStyle.Quad, Enum.EasingDirection.Out)
                                local tween = TweenService:Create(hrp, tweenInfo, {CFrame = CFrame.new(targetPos, targetPos + hrp.CFrame.LookVector)})
                                tween:Play()
                                tween.Completed:Wait()
                            end
                        end
                    end
                end
            end
        end
    end
end)

task.spawn(function()
    while true do
        task.wait()
        if _G.AntiFallEnabled and LocalPlayer.Character and LocalPlayer.Character:FindFirstChild("HumanoidRootPart") then
            local hrp = LocalPlayer.Character.HumanoidRootPart
            local hum = LocalPlayer.Character:FindFirstChildOfClass("Humanoid")
            if hum and hum:GetState() == Enum.HumanoidStateType.Freefall and hrp.Velocity.Y < -50 then
                hrp.Velocity = Vector3.new(hrp.Velocity.X, 25, hrp.Velocity.Z)
            end
        end
    end
end)

MiscTab:AddSection({ Name = "--- Server & Connection ---" })
MiscTab:AddButton({
    Name = "Rejoin Server",
    Callback = function()
        game:GetService("TeleportService"):Teleport(game.PlaceId, LocalPlayer)
    end
})

MiscTab:AddToggle({
    Name = "Auto Rejoin on Kick",
    Default = _G.AutoRejoin,
    Callback = function(Value)
        _G.AutoRejoin = Value
        SaveConfig()
    end
})

MiscTab:AddButton({
    Name = "Server Hop",
    Callback = function()
        local HttpService = game:GetService("HttpService")
        local TeleportService = game:GetService("TeleportService")
        local Servers = HttpService:JSONDecode(game:HttpGet("https://games.roblox.com/v1/games/" .. game.PlaceId .. "/servers/Public?sortOrder=Asc&limit=100"))
        for i, v in pairs(Servers.data) do
            if v.playing < v.maxPlayers and v.id ~= game.JobId then
                TeleportService:TeleportToPlaceInstance(game.PlaceId, v.id, LocalPlayer)
                break
            end
        end
    end
})

MiscTab:AddSection({ Name = "--- Movement Utility ---" })
MiscTab:AddToggle({
    Name = "Infinite Jump",
    Default = InfJumpEnabled,
    Callback = function(v)
        InfJumpEnabled = v
        SaveConfig()
    end
})

MiscTab:AddToggle({
	Name = "Auto Collect Items",
	Default = AutoCollectEnabled,
	Callback = function(v) 
        AutoCollectEnabled = v 
        SaveConfig()
    end    
})

-- =====================
-- CAR MODS TAB
-- =====================
local CarTab = Window:MakeTab({ Name = "Car Mods", Icon = "rbxassetid://10734944062", PremiumOnly = false })


local function getRootPart(model)
    return model.PrimaryPart or model:FindFirstChild("DriveSeat") or model:FindFirstChildWhichIsA("BasePart")
end

local vehicleData = {
    flyEnabled = false,
    flySpeed = 100
}


local flyConnection = nil
local originalCollisions = {}

local function getVehicle()
    local vehiclesFolder = workspace:FindFirstChild("Vehicles")
    local vehicle = vehiclesFolder and vehiclesFolder:FindFirstChild(LocalPlayer.Name)
    
    if not vehicle then
        for _, obj in ipairs(workspace:GetDescendants()) do
            if obj:IsA("Model") and obj.Name:match(LocalPlayer.Name) then
                return obj
            end
        end
    end
    
    return vehicle
end

-- [ TIRE REPAIR HELPERS ]
local function getMetatableMethod(tbl, methodName)
    if type(tbl) ~= "table" then return nil end
    local mt = getmetatable(tbl)
    if type(mt) ~= "table" then return nil end
    local index = rawget(mt, "__index")
    if type(index) == "table" then
        local method = rawget(index, methodName)
        if type(method) == "function" then return method end
    elseif type(index) == "function" then
        local ok, method = pcall(index, tbl, methodName)
        if ok and type(method) == "function" then return method end
    end
    return nil
end

local function isVehicleDataObject(obj)
    if type(obj) ~= "table" then return false end
    local inst = rawget(obj, "instance")
    if typeof(inst) ~= "Instance" or not inst:IsA("Model") then return false end
    local repairTireMethod = rawget(obj, "repairTire") or getMetatableMethod(obj, "repairTire")
    return type(repairTireMethod) == "function"
end

local function getOwnedVehicleDataObjects()
    if type(getgc) ~= "function" then return {} end
    local results = {}
    local ownedModel = getVehicle()
    for _, obj in ipairs(getgc(true)) do
        if type(obj) == "table" and isVehicleDataObject(obj) then
            local inst = rawget(obj, "instance")
            if inst == ownedModel then
                table.insert(results, obj)
            end
        end
    end
    return results
end

local function addUniqueString(list, seen, value)
    if type(value) ~= "string" then return end
    local cleaned = value:match("^%s*(.-)%s*$")
    if cleaned == "" or seen[cleaned] then return end
    seen[cleaned] = true
    table.insert(list, cleaned)
end

local function getVehicleWheelNames(vehicleData)
    local names = {}
    local seen = {}
    local wheels = rawget(vehicleData, "wheels")
    if type(wheels) == "table" then
        for key, _ in pairs(wheels) do
            if type(key) == "string" then addUniqueString(names, seen, key) end
        end
    end
    local attrs = rawget(vehicleData, "attributes")
    if type(attrs) == "table" and type(attrs.flatTires) == "string" then
        for tireName in string.gmatch(attrs.flatTires, "[^,%s]+") do
            addUniqueString(names, seen, tireName)
        end
    end
    for _, name in ipairs({"FL", "FR", "RL", "RR", "F", "R"}) do addUniqueString(names, seen, name) end
    return names
end

local function getCurrentFlatTireNames(vehicleData)
    local names = {}
    local seen = {}
    local getFlatTiresMethod = rawget(vehicleData, "getFlatTires") or getMetatableMethod(vehicleData, "getFlatTires")
    if type(getFlatTiresMethod) == "function" then
        local ok, flatTires = pcall(getFlatTiresMethod, vehicleData)
        if ok and type(flatTires) == "table" then
            for _, tireName in ipairs(flatTires) do addUniqueString(names, seen, tireName) end
        end
    end
    local attrs = rawget(vehicleData, "attributes")
    if type(attrs) == "table" and type(attrs.flatTires) == "string" then
        for tireName in string.gmatch(attrs.flatTires, "[^,%s]+") do addUniqueString(names, seen, tireName) end
    end
    return names
end

local function refreshVehicleDataHandling(vehicleData)
    local methods = {"updateAcceleration", "updateBrake", "updateArmor", "updateWheelsetDistances", "updateWheelsets"}
    for _, methodName in ipairs(methods) do
        local method = rawget(vehicleData, methodName) or getMetatableMethod(vehicleData, methodName)
        if type(method) == "function" then pcall(method, vehicleData) end
    end
    
    -- Force wheel friction reset
    local model = rawget(vehicleData, "instance")
    if model then
        for _, v in ipairs(model:GetDescendants()) do
            if v:IsA("BasePart") and (v.Name:find("Wheel") or v.Name:find("Tire")) then
                v.CustomPhysicalProperties = PhysicalProperties.new(0.7, 0.3, 0.5, 1, 1) -- Standard friction
            end
        end
    end
end

local function repairVehicleDataTires(vehicleData, passes)
    local repairedAny = false
    local repairTireMethod = rawget(vehicleData, "repairTire") or getMetatableMethod(vehicleData, "repairTire")
    if type(repairTireMethod) ~= "function" then return false end

    for _ = 1, (passes or 3) do
        local flatTires = getCurrentFlatTireNames(vehicleData)
        local allWheels = getVehicleWheelNames(vehicleData)
        local targets = {}
        local seen = {}
        for _, n in ipairs(flatTires) do seen[n] = true; table.insert(targets, n) end
        for _, n in ipairs(allWheels) do if not seen[n] then seen[n] = true; table.insert(targets, n) end end

        for _, tireName in ipairs(targets) do
            pcall(repairTireMethod, vehicleData, tireName)
            repairedAny = true
        end

        local attrs = rawget(vehicleData, "attributes")
        if type(attrs) == "table" and type(attrs.flatTires) == "string" then attrs.flatTires = "" end
        refreshVehicleDataHandling(vehicleData)
        if #getCurrentFlatTireNames(vehicleData) == 0 then break end
    end
    return repairedAny
end

local function repairOwnedVehicleTires(passes)
    local dataObjects = getOwnedVehicleDataObjects()
    local repaired = false
    for _, data in ipairs(dataObjects) do
        if repairVehicleDataTires(data, passes) then repaired = true end
    end
    return repaired, #dataObjects
end


CarTab:AddSection({ Name = "--- Main Features ---" })
CarTab:AddToggle({
    Name = "Infinite Fuel",
    Default = InfFuelEnabled,
    Callback = function(v)
        InfFuelEnabled = v
        SaveConfig()
    end
})

CarTab:AddToggle({
    Name = "Car Godmode",
    Default = CarGodmodeEnabled,
    Callback = function(v)
        CarGodmodeEnabled = v
        if v then
            local vehicle = getVehicle()
            if not vehicle then
                OrionLib:MakeNotification({
                    Name = "Error",
                    Content = "Could not find your vehicle. Make sure your car is existing or not too far from you.",
                    Image = "rbxassetid://4483345998",
                    Time = 5
                })
            end
        end
        SaveConfig()
    end
})

CarTab:AddSection({ Name = "--- Vehicle Maintenance ---" })
CarTab:AddButton({
    Name = "Repair Tires",
    Callback = function()
        local repaired, count = repairOwnedVehicleTires(3)
        if repaired then
            OrionLib:MakeNotification({Name = "Vehicle", Content = "Tires fixed & Friction reset!", Time = 3})
        elseif count == 0 then
            OrionLib:MakeNotification({Name = "Vehicle", Content = "No active vehicle found.", Time = 2})
        else
            OrionLib:MakeNotification({Name = "Vehicle", Content = "Restoring Wheel Friction...", Time = 2})
            local data = getOwnedVehicleDataObjects()
            for _, d in ipairs(data) do refreshVehicleDataHandling(d) end
        end
    end
})

CarTab:AddButton({
	Name = "Bring My Car",
	Callback = function()
        local vehiclesFolder = workspace:FindFirstChild("Vehicles")
        local vehicle = vehiclesFolder and vehiclesFolder:FindFirstChild(LocalPlayer.Name)
        local char = LocalPlayer.Character
        local hrp = char and char:FindFirstChild("HumanoidRootPart")
        local hum = char and char:FindFirstChildOfClass("Humanoid")

        if hrp and hum and vehicle then
            local driveSeat = vehicle:FindFirstChild("DriveSeat", true)
            if driveSeat then
                vehicle.PrimaryPart = driveSeat
                vehicle:SetPrimaryPartCFrame(hrp.CFrame * CFrame.new(0, 0, -5))
                task.wait(0.1)
                driveSeat:Sit(hum)
            end
        end
	end    
})

RunService.Heartbeat:Connect(function()
    if InfFuelEnabled or CarGodmodeEnabled then
        local v = getVehicle()
        if v then
            if InfFuelEnabled then
                v:SetAttribute("currentFuel", 9999999)
            end
            if CarGodmodeEnabled then
                v:SetAttribute("currentHealth", 1000)
                v:SetAttribute("IsOn", true)
            end
        end
    end
end)

local bypassLoop = nil
local MobileFlyGui = nil
local MobileControls = {
    Forward = false,
    Backward = false,
    Left = false,
    Right = false
}

local function CreateMobileFlyGui()
    if MobileFlyGui then MobileFlyGui:Destroy() end
    
    MobileFlyGui = Instance.new("ScreenGui")
    MobileFlyGui.Name = "MobileFlyGui"
    MobileFlyGui.Parent = game:GetService("CoreGui"):FindFirstChild("Orion") and game:GetService("CoreGui") or LocalPlayer:WaitForChild("PlayerGui")
    MobileFlyGui.ResetOnSpawn = false

    local MainFrame = Instance.new("Frame")
    MainFrame.Size = UDim2.new(0, 150, 0, 150)
    MainFrame.Position = UDim2.new(0.75, 0, 0.6, 0)
    MainFrame.BackgroundTransparency = 1
    MainFrame.Parent = MobileFlyGui

    local function createArrow(name, pos, text, key)
        local btn = Instance.new("TextButton")
        btn.Name = name
        btn.Size = UDim2.new(0, 45, 0, 45)
        btn.Position = pos
        btn.BackgroundColor3 = Color3.fromRGB(30, 30, 30)
        btn.BackgroundTransparency = 0.3
        btn.Text = text
        btn.TextColor3 = Color3.fromRGB(255, 255, 255)
        btn.TextSize = 25
        btn.Font = Enum.Font.GothamBold
        btn.Parent = MainFrame
        
        local corner = Instance.new("UICorner")
        corner.CornerRadius = UDim.new(0, 8)
        corner.Parent = btn

        local stroke = Instance.new("UIStroke")
        stroke.Color = Color3.fromRGB(100, 100, 100)
        stroke.Thickness = 1.5
        stroke.Parent = btn

        btn.MouseButton1Down:Connect(function() 
            MobileControls[key] = true 
            btn.BackgroundColor3 = Color3.fromRGB(60, 60, 60)
        end)
        btn.MouseButton1Up:Connect(function() 
            MobileControls[key] = false 
            btn.BackgroundColor3 = Color3.fromRGB(30, 30, 30)
        end)
        btn.MouseLeave:Connect(function() 
            MobileControls[key] = false 
            btn.BackgroundColor3 = Color3.fromRGB(30, 30, 30)
        end)
    end

    createArrow("Forward", UDim2.new(0.5, -22, 0, 0), "▲", "Forward")
    createArrow("Backward", UDim2.new(0.5, -22, 1, -45), "▼", "Backward")
    createArrow("Left", UDim2.new(0, 0, 0.5, -22), "◀", "Left")
    createArrow("Right", UDim2.new(1, -45, 0.5, -22), "▶", "Right")
end

local function RemoveMobileFlyGui()
    if MobileFlyGui then
        MobileFlyGui:Destroy()
        MobileFlyGui = nil
    end
    for k in pairs(MobileControls) do MobileControls[k] = false end
end

local function startFly()
    if flyConnection then flyConnection:Disconnect() end
    if bypassLoop then task.cancel(bypassLoop) end
    
    bypassLoop = task.spawn(function()
        while vehicleData.flyEnabled do
            task.wait(5)
            if vehicleData.flyEnabled then
                local char = LocalPlayer.Character
                local hum = char and char:FindFirstChildOfClass("Humanoid")
                if hum and hum.SeatPart then 
                    hum.Sit = false 
                end
            end
        end
    end)
    
    flyConnection = RunService.Heartbeat:Connect(function(dt)
        if not vehicleData.flyEnabled then return end
        local vehicle = getVehicle()
        if not vehicle then return end
        local root = getRootPart(vehicle)
        if not root then return end
        
        local char = LocalPlayer.Character
        local hum = char and char:FindFirstChildOfClass("Humanoid")
        local hrp = char and char:FindFirstChild("HumanoidRootPart")
        
        if not hum or not hrp then return end

        local seat = vehicle:FindFirstChild("DriveSeat")
        local inVehicle = hum.SeatPart and hum.SeatPart:IsDescendantOf(vehicle)

        if not inVehicle then
            if seat and (hrp.Position - seat.Position).Magnitude < 25 then
                -- Anti-Fall Damage & Re-sit Logic
                hrp.CFrame = seat.CFrame
                hrp.Velocity = Vector3.new(root.Velocity.X, 0, root.Velocity.Z)
                seat:Sit(hum)
            else
                -- Not in car and too far away, don't fly the car
                return
            end
        end
        
        local moveDir = Vector3.zero
        local camCF = Camera.CFrame
        
        if MobileCarFlyEnabled then
            if MobileControls.Forward then moveDir = moveDir + camCF.LookVector end
            if MobileControls.Backward then moveDir = moveDir - camCF.LookVector end
            if MobileControls.Left then moveDir = moveDir - camCF.RightVector end
            if MobileControls.Right then moveDir = moveDir + camCF.RightVector end
            
            -- Fallback to MoveDirection if no buttons pressed
            if moveDir.Magnitude == 0 and hum and hum.MoveDirection.Magnitude > 0 then
                moveDir = (camCF.LookVector * hum.MoveDirection.Z) + (camCF.RightVector * hum.MoveDirection.X)
            end
        else
            if UserInputService:IsKeyDown(Enum.KeyCode.W) then moveDir = moveDir + camCF.LookVector end
            if UserInputService:IsKeyDown(Enum.KeyCode.S) then moveDir = moveDir - camCF.LookVector end
            if UserInputService:IsKeyDown(Enum.KeyCode.A) then moveDir = moveDir - camCF.RightVector end
            if UserInputService:IsKeyDown(Enum.KeyCode.D) then moveDir = moveDir + camCF.RightVector end
            if UserInputService:IsKeyDown(Enum.KeyCode.E) then moveDir = moveDir + Vector3.new(0, 1, 0) end
            if UserInputService:IsKeyDown(Enum.KeyCode.Q) then moveDir = moveDir - Vector3.new(0, 1, 0) end
        end
        
        local targetCF = root.CFrame
        if moveDir.Magnitude > 0 then
            local nextPos = root.Position + (moveDir * vehicleData.flySpeed * dt)
            targetCF = CFrame.lookAt(nextPos, nextPos + camCF.LookVector)
        end
        
        -- Smooth movement
        vehicle:SetPrimaryPartCFrame(root.CFrame:Lerp(targetCF, 0.85))

        -- Better Noclip & Physics Lock
        for _, part in ipairs(vehicle:GetDescendants()) do
            if part:IsA("BasePart") then
                if originalCollisions[part] == nil then originalCollisions[part] = part.CanCollide end
                part.CanCollide = false
                part.AssemblyLinearVelocity = Vector3.zero
                part.AssemblyAngularVelocity = Vector3.zero
                part.Velocity = Vector3.zero
            end
        end
        
        if char then
            for _, part in ipairs(char:GetDescendants()) do
                if part:IsA("BasePart") then
                    if originalCollisions[part] == nil then originalCollisions[part] = part.CanCollide end
                    part.CanCollide = false
                end
            end
        end
    end)
end

local function stopFly()
    if flyConnection then flyConnection:Disconnect() flyConnection = nil end
    if bypassLoop then task.cancel(bypassLoop) bypassLoop = nil end
    for part, originalValue in pairs(originalCollisions) do
        if part and part.Parent then
            pcall(function()
                part.CanCollide = originalValue
            end)
        end
    end
    originalCollisions = {}
end


local FlyToggle = CarTab:AddToggle({
    Name = "Vehicle Fly",
    Default = false,
    Callback = function(Value)
        vehicleData.flyEnabled = Value
        if Value then 
            local vehicle = getVehicle()
            local char = LocalPlayer.Character
            local hum = char and char:FindFirstChildOfClass("Humanoid")
            local hrp = char and char:FindFirstChild("HumanoidRootPart")
            if vehicle and hum and hrp and (not hum.SeatPart or not hum.SeatPart:IsDescendantOf(vehicle)) then
                local seat = vehicle:FindFirstChild("DriveSeat")
                if seat then
                    hrp.CFrame = seat.CFrame + Vector3.new(0, 2, 0)
                    task.wait(0.1)
                    seat:Sit(hum)
                end
            end
            startFly() 
        else 
            stopFly() 
        end
        SaveConfig()
    end
})

CarTab:AddToggle({
    Name = "Mobile Car Fly",
    Default = MobileCarFlyEnabled,
    Callback = function(Value)
        MobileCarFlyEnabled = Value
        if Value then 
            CreateMobileFlyGui()
        else 
            RemoveMobileFlyGui()
        end
        SaveConfig()
    end
})

CarTab:AddBind({
    Name = "Fly Keybind",
    Default = Enum.KeyCode.X,
    Hold = false,
    Callback = function() FlyToggle:Set(not vehicleData.flyEnabled) end    
})

CarTab:AddSlider({
    Name = "Fly Speed",
    Min = 10, Max = 500, Default = 100,
    Color = Color3.fromRGB(255,255,255),
    Increment = 1, ValueName = "Speed",
    Callback = function(Value) vehicleData.flySpeed = Value end    
})

CarTab:AddLabel("--- Vehicle Upgrades ---")

local function updateVehicleStat(stat, val)
    local vehicle = workspace:FindFirstChild("Vehicles") and workspace.Vehicles:FindFirstChild(LocalPlayer.Name)
    if vehicle then
        pcall(function()
            vehicle:SetAttribute(stat, val)
        end)
    end
end

CarTab:AddSlider({
	Name = "Engine Level",
	Min = 0, Max = 6, Default = VehicleUpgrades.Engine,
	Color = Color3.fromRGB(255, 255, 255),
	Increment = 1, ValueName = "Lvl",
	Callback = function(Value) 
        VehicleUpgrades.Engine = Value
        updateVehicleStat("engineLevel", Value) 
        SaveConfig()
    end    
})

CarTab:AddSlider({
	Name = "Armor Level",
	Min = 0, Max = 6, Default = VehicleUpgrades.Armor,
	Color = Color3.fromRGB(255, 255, 255),
	Increment = 1, ValueName = "Lvl",
	Callback = function(Value) 
        VehicleUpgrades.Armor = Value
        updateVehicleStat("armorLevel", Value) 
        SaveConfig()
    end    
})

CarTab:AddSlider({
	Name = "Brakes Level",
	Min = 0, Max = 6, Default = VehicleUpgrades.Brakes,
	Color = Color3.fromRGB(255, 255, 255),
	Increment = 1, ValueName = "Lvl",
	Callback = function(Value) 
        VehicleUpgrades.Brakes = Value
        updateVehicleStat("brakesLevel", Value) 
        SaveConfig()
    end    
})

-- [ TELEPORT FUNCTIONS ]
_G.flightSpeed = 170
local seatCheckConnection = nil

local function startSeatCheck()
    if seatCheckConnection then seatCheckConnection:Disconnect() end
    seatCheckConnection = RunService.Heartbeat:Connect(function()
        local character = LocalPlayer.Character
        local humanoid = character and character:FindFirstChildOfClass("Humanoid")
        local vehicle = workspace:FindFirstChild("Vehicles") and workspace.Vehicles:FindFirstChild(LocalPlayer.Name)
        
        if vehicle and humanoid and not humanoid.SeatPart then
            local driveSeat = vehicle:FindFirstChild("DriveSeat")
            if driveSeat then
                driveSeat:Sit(humanoid)
            end
        end
    end)
end

local function stopSeatCheck()
    if seatCheckConnection then
        seatCheckConnection:Disconnect()
        seatCheckConnection = nil
    end
end

function frameTween(targetCFrame)
    local character = LocalPlayer.Character or LocalPlayer.CharacterAdded:Wait()
    local humanoid = character:FindFirstChildOfClass("Humanoid")
    if not humanoid then return end

    local vehicle = workspace:FindFirstChild("Vehicles") and workspace.Vehicles:FindFirstChild(LocalPlayer.Name)
    if not vehicle then return end

    local driveSeat = vehicle:FindFirstChild("DriveSeat")
    if not driveSeat then return end
    
    if not vehicle.PrimaryPart then
        vehicle.PrimaryPart = vehicle:FindFirstChild("Body") and vehicle.Body:FindFirstChild("Mass")
        if not vehicle.PrimaryPart then return end
    end

    driveSeat:Sit(humanoid)
    task.wait(0.1)
    startSeatCheck()

    local originalProps = {}
    for _, part in pairs(vehicle:GetDescendants()) do
        if part:IsA("BasePart") then
            originalProps[part] = {
                v = part.Velocity, rv = part.RotVelocity,
                lv = part.AssemblyLinearVelocity, av = part.AssemblyAngularVelocity
            }
            part.Velocity, part.RotVelocity = Vector3.new(0,0,0), Vector3.new(0,0,0)
            part.AssemblyLinearVelocity, part.AssemblyAngularVelocity = Vector3.new(0,0,0), Vector3.new(0,0,0)
        end
    end

    local isTweenActive = true

    task.spawn(function()
        while isTweenActive do
            task.wait(5)
            if isTweenActive and humanoid then
                humanoid.Sit = false
            end
        end
    end)

    local function smoothMove(startCF, endCF, speedMult)
        local distance = (endCF.Position - startCF.Position).Magnitude
        local duration = distance > 0.5 and (distance / (WAYPOINT_TWEEN_SPEED * speedMult)) or 0.6
        
        local tVal = Instance.new("CFrameValue")
        tVal.Value = startCF

        local conn = tVal.Changed:Connect(function()
            if vehicle.PrimaryPart then
                vehicle:SetPrimaryPartCFrame(tVal.Value)
            end
        end)

        local tween = TweenService:Create(tVal, TweenInfo.new(duration, Enum.EasingStyle.Linear), {Value = endCF})
        tween:Play()
        tween.Completed:Wait()
        
        conn:Disconnect()
        tVal:Destroy()
    end

    local startCF = vehicle.PrimaryPart.CFrame
    local targetPos = targetCFrame.Position
    local travelY = -2
    
    local upCF = CFrame.new(startCF.X, travelY, startCF.Z) * (startCF - startCF.Position)
    smoothMove(startCF, upCF, 0.5)
    
    local diff = (Vector3.new(targetPos.X, travelY, targetPos.Z) - upCF.Position)
    if diff.Magnitude > 0.5 then
        local direction = diff.Unit
        local lookAtTargetCF = CFrame.lookAt(upCF.Position, upCF.Position + direction)
        smoothMove(upCF, lookAtTargetCF, 1)
        upCF = lookAtTargetCF
    end

    local forwardEndCF = CFrame.lookAt(Vector3.new(targetPos.X, travelY, targetPos.Z), Vector3.new(targetPos.X, travelY, targetPos.Z) + diff.Unit)
    smoothMove(upCF, forwardEndCF, 1)

    local finalLandCF = CFrame.new(targetPos) * (forwardEndCF - forwardEndCF.Position)
    smoothMove(forwardEndCF, finalLandCF, 0.5)

    isTweenActive = false
    stopSeatCheck()

    for part, props in pairs(originalProps) do
        if part and part.Parent then
            part.Velocity, part.RotVelocity = props.v, props.rv
            part.AssemblyLinearVelocity, part.AssemblyAngularVelocity = props.lv, props.av
        end
    end

    vehicle:SetPrimaryPartCFrame(finalLandCF)
    driveSeat:Sit(humanoid)
end

function findNearestDealer()
    local nearestDealer = nil
    local minDistance = math.huge
    local character = LocalPlayer.Character
    if not character or not character:FindFirstChild("HumanoidRootPart") then return nil end
    local pos = character.HumanoidRootPart.Position

    local dealersFolder = workspace:FindFirstChild("Dealers")
    if not dealersFolder then return nil end

    for _, dealer in ipairs(dealersFolder:GetChildren()) do
        if dealer.Name == "Dealer" then
            local dealerPos = dealer:GetPivot().Position
            local distance = (pos - dealerPos).Magnitude
            if distance < minDistance then
                minDistance = distance
                nearestDealer = dealer
            end
        end
    end
    return nearestDealer
end

function TweenToDealer()
    local nearest = findNearestDealer()
    if nearest then
        frameTween(nearest:GetPivot())
    else
        OrionLib:MakeNotification({Name = "Error", Content = "Kein Dealer gefunden!", Time = 2})
    end
end


-- =====================
-- TELEPORTS TAB
-- =====================
local TeleportTab = Window:MakeTab({ Name = "Teleports", Icon = "rbxassetid://10734947118", PremiumOnly = false })

TeleportTab:AddSection({ Name = "--- Main Teleports ---" })
TeleportTab:AddButton({
	Name = "Tween to Nearest Dealer",
	Callback = function()
        TweenToDealer()
	end    
})

local TeleportLocations = {
    ["Bank"] = CFrame.new(-1168.3020, 7.6776, 3143.5295),
    ["Juwelier"] = CFrame.new(-422.4608, 5.8499, 3537.7039),
    ["Prison"] = CFrame.new(-568.6785, 5.7717, 2853.5339),
    ["Police"] = CFrame.new(-1668.9340, 5.8270, 2766.4817),
    ["Erwins Club"] = CFrame.new(-1757.1986, 11.4692, 3019.8716),
    ["Ares Tanke"] = CFrame.new(-865.5728, 5.4276, 1520.6948),
    ["Gas-N-GO Tanke"] = CFrame.new(-1541.5182, 5.5981, 3808.9070),
    ["Osso Tanke"] = CFrame.new(-30.3058, 5.1776, -753.8921)
}

TeleportTab:AddDropdown({
    Name = "Normal Positions",
    Default = "None",
    Options = {"None", "Bank", "Juwelier", "Prison", "Police", "Erwins Club", "Ares Tanke", "Gas-N-GO Tanke", "Osso Tanke"},
    Callback = function(v)
        if v ~= "None" and TeleportLocations[v] then
            frameTween(TeleportLocations[v])
        end
    end
})


local playerGui = LocalPlayer:WaitForChild("PlayerGui")

local WAYPOINT_MAP_HEIGHT = 2.125
local WAYPOINT_TWEEN_SPEED = 165

local waypointTeleportEnabled = false
local waypointTweenBusy = false
local waypointSeatCheckConnection = nil
local waypointButtonConnections = {}

local waypointGroundRayParams = RaycastParams.new()
waypointGroundRayParams.FilterType = Enum.RaycastFilterType.Exclude
waypointGroundRayParams.IgnoreWater = true

local customWaypointPositions = {
    clothingstore = Vector3.new(475.6598, 5.3118, -1443.4369),
    jeweler = Vector3.new(-422.4608, 5.8499, 3537.7039),
    firestation = Vector3.new(-961.8547, 5.5766, 3889.8508),
    gasngofuel = Vector3.new(-1541.5182, 5.5981, 3808.9070),
    club = Vector3.new(-1757.1986, 11.4692, 3019.8716),
    farmshop = Vector3.new(-907.0965, 5.0566, -1170.1194),
    bank = Vector3.new(-1168.3020, 7.6776, 3143.5295),
    prison = Vector3.new(-568.6785, 5.7717, 2853.5339),
    policestation = Vector3.new(-1668.9340, 5.8270, 2766.4817),
    ossofuel = Vector3.new(-30.3058, 5.1776, -753.8921),
    aresfuel = Vector3.new(-865.5728, 5.4276, 1520.6948)
}



local function getRootPart(vehicle)
    return vehicle.PrimaryPart or vehicle:FindFirstChild("DriveSeat") or vehicle:FindFirstChildWhichIsA("BasePart")
end

local function startWaypointSeatCheck()
    if waypointSeatCheckConnection then
        waypointSeatCheckConnection:Disconnect()
    end

    waypointSeatCheckConnection = RunService.Heartbeat:Connect(function()
        local character = LocalPlayer.Character
        local humanoid = character and character:FindFirstChildOfClass("Humanoid")
        local vehiclesFolder = workspace:FindFirstChild("Vehicles")
        local vehicle = vehiclesFolder and vehiclesFolder:FindFirstChild(LocalPlayer.Name)

        if vehicle and humanoid and not humanoid.SeatPart then
            local driveSeat = vehicle:FindFirstChild("DriveSeat")
            if driveSeat then
                driveSeat:Sit(humanoid)
            end
        end
    end)
end

local function stopWaypointSeatCheck()
    if waypointSeatCheckConnection then
        waypointSeatCheckConnection:Disconnect()
        waypointSeatCheckConnection = nil
    end
end

local function frameTweenToWaypoint(targetCFrame)
    if waypointTweenBusy then
        return
    end

    waypointTweenBusy = true

    local ok = pcall(function()
        local character = LocalPlayer.Character or LocalPlayer.CharacterAdded:Wait()
        local humanoid = character:FindFirstChildOfClass("Humanoid")
        if not humanoid then return end

        local vehiclesFolder = workspace:FindFirstChild("Vehicles")
        local vehicle = vehiclesFolder and vehiclesFolder:FindFirstChild(LocalPlayer.Name)
        if not vehicle then return end

        local driveSeat = vehicle:FindFirstChild("DriveSeat")
        if not driveSeat then return end

        vehicle.PrimaryPart = getRootPart(vehicle)
        if not vehicle.PrimaryPart then return end

        driveSeat:Sit(humanoid)
        task.wait(0.1)
        startWaypointSeatCheck()

        local originalProps = {}
        for _, part in ipairs(vehicle:GetDescendants()) do
            if part:IsA("BasePart") then
                originalProps[part] = {
                    Velocity = part.Velocity,
                    RotVelocity = part.RotVelocity,
                    AssemblyLinearVelocity = part.AssemblyLinearVelocity,
                    AssemblyAngularVelocity = part.AssemblyAngularVelocity
                }
                part.Velocity = Vector3.zero
                part.RotVelocity = Vector3.zero
                part.AssemblyLinearVelocity = Vector3.zero
                part.AssemblyAngularVelocity = Vector3.zero
            end
        end

        local isTweenActive = true
        task.spawn(function()
            while isTweenActive do
                task.wait(5)
                if isTweenActive and humanoid then
                    humanoid.Sit = false
                end
            end
        end)

        local function smoothMove(startCF, endCF, isVertical)
            local distance = (endCF.Position - startCF.Position).Magnitude
            if distance <= 0.01 then return end

            local speed = isVertical and (WAYPOINT_TWEEN_SPEED / 2) or WAYPOINT_TWEEN_SPEED
            local tValue = Instance.new("CFrameValue")
            tValue.Value = startCF

            local updateConnection = tValue:GetPropertyChangedSignal("Value"):Connect(function()
                if vehicle.Parent and vehicle.PrimaryPart then
                    vehicle:SetPrimaryPartCFrame(tValue.Value)
                    for _, part in ipairs(vehicle:GetDescendants()) do
                        if part:IsA("BasePart") then
                            part.Velocity = Vector3.zero
                            part.RotVelocity = Vector3.zero
                            part.AssemblyLinearVelocity = Vector3.zero
                            part.AssemblyAngularVelocity = Vector3.zero
                        end
                    end
                end
            end)

            local tween = TweenService:Create(
                tValue,
                TweenInfo.new(distance / speed, Enum.EasingStyle.Linear),
                {Value = endCF}
            )
            tween:Play()
            tween.Completed:Wait()

            updateConnection:Disconnect()
            tValue:Destroy()
        end

        local startCF = vehicle.PrimaryPart.CFrame
        local travelY = -2

        local flatFace = Vector3.new(targetCFrame.LookVector.X, 0, targetCFrame.LookVector.Z)
        if flatFace.Magnitude < 0.1 then
            flatFace = Vector3.new(startCF.LookVector.X, 0, startCF.LookVector.Z)
        end
        if flatFace.Magnitude < 0.1 then
            flatFace = Vector3.new(0, 0, 1)
        end
        flatFace = flatFace.Unit

        local p1Pos = Vector3.new(startCF.X, travelY, startCF.Z)
        local p1EndCF = CFrame.lookAt(p1Pos, p1Pos + flatFace)
        smoothMove(startCF, p1EndCF, true)

        local p2Pos = Vector3.new(targetCFrame.X, travelY, targetCFrame.Z)
        local p2EndCF = CFrame.lookAt(p2Pos, p2Pos + flatFace)
        smoothMove(p1EndCF, p2EndCF, false)

        smoothMove(p2EndCF, targetCFrame, true)

        isTweenActive = false
        stopWaypointSeatCheck()

        for part, props in pairs(originalProps) do
            if part and part.Parent then
                part.Velocity = props.Velocity
                part.RotVelocity = props.RotVelocity
                part.AssemblyLinearVelocity = props.AssemblyLinearVelocity
                part.AssemblyAngularVelocity = props.AssemblyAngularVelocity
            end
        end

        if vehicle.Parent and vehicle.PrimaryPart then
            vehicle:SetPrimaryPartCFrame(targetCFrame)
            driveSeat:Sit(humanoid)
        end
    end)

    stopWaypointSeatCheck()
    waypointTweenBusy = false

    if not ok then
        notify("Tween failed.")
    end
end

local function normalizeWaypointName(nameText)
    if type(nameText) ~= "string" then
        return ""
    end

    local normalized = string.lower(nameText:gsub("[^%w]", ""))

    if normalized == "gasngo" or normalized == "gasngofuelstation" or normalized == "gasandgofuel" or normalized == "gasandgo" then
        normalized = "gasngofuel"
    elseif normalized == "jeweller" then
        normalized = "jeweler"
    end

    return normalized
end

local function getFacingVector()
    local vehiclesFolder = workspace:FindFirstChild("Vehicles")
    local vehicle = vehiclesFolder and vehiclesFolder:FindFirstChild(LocalPlayer.Name)
    local root = vehicle and getRootPart(vehicle)

    local face = root and root.CFrame.LookVector or (Camera and Camera.CFrame.LookVector or Vector3.new(0, 0, 1))
    face = Vector3.new(face.X, 0, face.Z)

    if face.Magnitude < 0.1 then
        return Vector3.new(0, 0, 1)
    end

    return face.Unit
end

local function isWaypointButton(button)
    if not button or (not button:IsA("ImageButton") and not button:IsA("TextButton")) then
        return false
    end

    local viewport = button:FindFirstAncestorWhichIsA("ViewportFrame")
    if not viewport or not viewport.CurrentCamera then
        return false
    end

    -- Filter out elements that definitely aren't waypoints (like big background frames)
    if button.AbsoluteSize.X > 200 or button.AbsoluteSize.Y > 200 then
        return false
    end

    return true
end

local function getWaypointTargetCFrame(button)
    local viewport = button:FindFirstAncestorWhichIsA("ViewportFrame")
    if not viewport or not viewport.CurrentCamera then
        return nil
    end

    local label = button:FindFirstChildOfClass("TextLabel")
    local key = normalizeWaypointName(label and label.Text or button.Name)
    local customPos = customWaypointPositions[key]

    local face = getFacingVector()

    if customPos then
        return CFrame.lookAt(customPos, customPos + face)
    end

    local mapCamera = viewport.CurrentCamera
    
    -- Absolute positions for more accuracy
    local vpAbsSize = viewport.AbsoluteSize
    local vpAbsPos = viewport.AbsolutePosition
    local btnAbsPos = button.AbsolutePosition
    local btnAbsSize = button.AbsoluteSize
    
    -- Center point of the button relative to the viewport
    local relX = (btnAbsPos.X - vpAbsPos.X + (btnAbsSize.X / 2)) / vpAbsSize.X
    local relY = (btnAbsPos.Y - vpAbsPos.Y + (btnAbsSize.Y / 2)) / vpAbsSize.Y
    
    local rayX = relX * mapCamera.ViewportSize.X
    local rayY = relY * mapCamera.ViewportSize.Y

    local ray = mapCamera:ViewportPointToRay(rayX, rayY)
    
    -- Raycast into the real world to find the ground at X/Z
    local ignore = {}
    if LocalPlayer.Character then table.insert(ignore, LocalPlayer.Character) end
    local vehiclesFolder = workspace:FindFirstChild("Vehicles")
    local myVeh = vehiclesFolder and vehiclesFolder:FindFirstChild(LocalPlayer.Name)
    if myVeh then table.insert(ignore, myVeh) end
    waypointGroundRayParams.FilterDescendantsInstances = ignore
    
    -- Project ray to a generic height then raycast down
    local planeDist = (WAYPOINT_MAP_HEIGHT - ray.Origin.Y) / ray.Direction.Y
    local worldPoint = ray.Origin + ray.Direction * planeDist
    
    local castOrigin = Vector3.new(worldPoint.X, 1200, worldPoint.Z)
    local hit = workspace:Raycast(castOrigin, Vector3.new(0, -2500, 0), waypointGroundRayParams)
    
    local targetPos = worldPoint
    if hit then
        targetPos = hit.Position + Vector3.new(0, 3, 0)
    end

    return CFrame.lookAt(targetPos, targetPos + face)
end

local function clearWaypointButtonConnections()
    for button, connection in pairs(waypointButtonConnections) do
        if connection then
            connection:Disconnect()
        end
        waypointButtonConnections[button] = nil
    end
end

local function refreshWaypointButtons()
    if not waypointTeleportEnabled then
        return
    end

    local activeButtons = {}

    for _, gui in ipairs(playerGui:GetChildren()) do
        if gui:IsA("ScreenGui") then
            for _, viewport in ipairs(gui:GetDescendants()) do
                if viewport:IsA("ViewportFrame") and viewport.CurrentCamera then
                    for _, desc in ipairs(viewport:GetDescendants()) do
                        if isWaypointButton(desc) then
                            local button = desc
                            activeButtons[button] = true

                            if not waypointButtonConnections[button] then
                                waypointButtonConnections[button] = button.MouseButton1Click:Connect(function()
                                    if not waypointTeleportEnabled or waypointTweenBusy then
                                        return
                                    end

                                    local label = button:FindFirstChildOfClass("TextLabel")
                                    if not label or not label.Visible then
                                        
                                        return
                                    end

                                    local targetCFrame = getWaypointTargetCFrame(button)
                                    if not targetCFrame then
                                        
                                        return
                                    end

                                    task.spawn(function()
                                        frameTweenToWaypoint(targetCFrame)
                                    end)
                                end)
                            end
                        end
                    end
                end
            end
        end
    end

    for button, connection in pairs(waypointButtonConnections) do
        if not activeButtons[button] or not button or not button.Parent then
            if connection then connection:Disconnect() end
            waypointButtonConnections[button] = nil
        end
    end
end

-- Background loop to ensure new map buttons are always hooked
task.spawn(function()
    while true do
        task.wait(3)
        if waypointTeleportEnabled then
            pcall(refreshWaypointButtons)
        end
    end
end)

TeleportTab:AddSection({ Name = "--- Map & Settings ---" })
TeleportTab:AddToggle({
    Name = "Map Click TP",
    Default = waypointTeleportEnabled,
    Callback = function(Value)
        waypointTeleportEnabled = Value
        if Value then
            task.spawn(refreshWaypointButtons)
        else
            clearWaypointButtonConnections()
        end
        SaveConfig()
    end
})

TeleportTab:AddSlider({
    Name = "Global Teleport Speed",
    Min = 50,
    Max = 600,
    Default = WAYPOINT_TWEEN_SPEED,
    Increment = 10,
    ValueName = "Speed",
    Callback = function(Value)
        WAYPOINT_TWEEN_SPEED = Value
    end
})

TeleportTab:AddParagraph("Info", "Activate 'Map Click TP' to teleport by clicking icons on the map, or use the button above for your custom GPS route.")



-- =====================
-- FLING TAB (STREETLAMP FLINGER)
-- =====================

-- // Settings \\ --
local FlingSettings = {
    FlingActive = false,
    FlingTargetMode = "Follow Target", -- "Click", "Follow Target", "Fling Full Server"
    SelectedPlayer = nil,
    FixedPos = Vector3.new(0, 0, 0),
    FlingForce = 5000,
    OrbitRadius = 5,
    AutoBreak = false,
    OPFling = false
}

local activeAmmo = {}
local kickLogData = {}
local breakRemote = ReplicatedStorage:FindFirstChild("6Dg") and ReplicatedStorage["6Dg"]:FindFirstChild("8fbc48b4-fbf0-41bd-bd4a-656c9c9c858f") 
                  or ReplicatedStorage:FindFirstChild("0Mg") and ReplicatedStorage["0Mg"]:FindFirstChild("5b8423ef-8a95-409b-9aca-5a930e421149")

-- // Helpers \\ --

local function getMyVehicle()
    local vehiclesFolder = workspace:FindFirstChild("Vehicles")
    local myVehicle = vehiclesFolder and vehiclesFolder:FindFirstChild(LocalPlayer.Name)
    if myVehicle then return myVehicle end
    local char = LocalPlayer.Character
    local hum = char and char:FindFirstChildOfClass("Humanoid")
    if hum and hum.SeatPart and hum.SeatPart:IsA("VehicleSeat") then
        return hum.SeatPart:FindFirstAncestorOfClass("Model") or hum.SeatPart.Parent
    end
end

local lampCache = {}
local function updateLampCache()
    local results = {}
    local modules = workspace:FindFirstChild("Roads") and workspace.Roads:FindFirstChild("Modules")
    if not modules then return end
    for _, item in ipairs(modules:GetDescendants()) do
        if item.Name == "Streetlamp" and item:IsA("Model") and item:FindFirstChild("Main") then
            table.insert(results, item)
        end
    end
    lampCache = results
end
task.spawn(updateLampCache)

local function findLamps(range)
    local results = {}
    local vehicle = getMyVehicle()
    if not vehicle or not vehicle.PrimaryPart then return results end
    
    local pos = vehicle.PrimaryPart.Position
    for _, lamp in ipairs(lampCache) do
        if lamp.Parent and lamp:FindFirstChild("Main") then
            if (pos - lamp.Main.Position).Magnitude <= (range or 5000) then
                table.insert(results, lamp)
            end
        else
            -- If lamp was deleted, schedule a cache update
            task.spawn(updateLampCache)
        end
    end
    return results
end

local function getFlingPlayerList()
    local t = {}
    for _, p in pairs(Players:GetPlayers()) do
        if p ~= LocalPlayer then
            table.insert(t, p.DisplayName .. " (@" .. p.Name .. ")")
        end
    end
    return t
end

task.spawn(function()
    while true do
        task.wait(0.5)
        if FlingSettings.AutoBreak then
            local vehicle = getMyVehicle()
            local lamps = findLamps(5000)
            if vehicle and breakRemote and #lamps > 0 then
                for _, lamp in ipairs(lamps) do
                    if not FlingSettings.AutoBreak then break end
                    breakRemote:FireServer(vehicle, lamp)
                    task.wait(0.12) -- Prevent "Gameplay Paused" by slowing down remotes
                end
            end
        end
    end
end)

local FlingTab = Window:MakeTab({
	Name = "Fling",
	Icon = "zap",
	PremiumOnly = false
})

local OPSection = FlingTab:AddSection({ Name = "Server Crasher" })

local PlayerCountLabel = OPSection:AddLabel("Players in Server: " .. #Players:GetPlayers())

local function updatePlayerCount()
    PlayerCountLabel:Set("Players in Server: " .. #Players:GetPlayers() .. " / " .. Players.MaxPlayers)
end

local godModeToggle = OPSection:AddToggle({
    Name = "Fling all Players.",
    Default = false,
    Callback = function(val)
        FlingSettings.OPFling = val
        FlingSettings.FlingActive = val
        FlingSettings.FlingTargetMode = val and "Fling Full Server" or "Follow Target"
        if val then
            
        end
    end
})

local autoBreakToggle = OPSection:AddToggle({
    Name = "Auto-Break",
    Default = false,
    Callback = function(val)
        FlingSettings.AutoBreak = val
    end
})

local TargetSection = FlingTab:AddSection({ Name = "🎯 Targeting & Search" })

local playerDropdown = TargetSection:AddDropdown({
    Name = "Target Selection",
    Options = getFlingPlayerList(),
    Callback = function(val)
        for _, p in pairs(Players:GetPlayers()) do
            if (p.DisplayName .. " (@" .. p.Name .. ")") == val then
                FlingSettings.SelectedPlayer = p
                break
            end
        end
    end
})

TargetSection:AddTextbox({
    Name = "Quick Search Player",
    Default = "",
    TextDisappear = true,
    Callback = function(Value)
        if Value == "" then return end
        for _, p in pairs(Players:GetPlayers()) do
            if p.Name:lower():find(Value:lower()) or p.DisplayName:lower():find(Value:lower()) then
                FlingSettings.SelectedPlayer = p
                playerDropdown:Set(p.DisplayName .. " (@" .. p.Name .. ")")
                break
            end
        end
    end
})

TargetSection:AddButton({Name = "Refresh Player List", Callback = function() playerDropdown:Refresh(getFlingPlayerList(), true) end})

TargetSection:AddDropdown({
    Name = "Attack Mode",
    Default = "Follow Target",
    Options = {"Click", "Follow Target"},
    Callback = function(val) FlingSettings.FlingTargetMode = val end
})

TargetSection:AddToggle({
    Name = "Active Flinger",
    Default = false,
    Callback = function(val) FlingSettings.FlingActive = val end
})

local LogSection = FlingTab:AddSection({ Name = "💀 Annihilation Log" })
local KickLabel = LogSection:AddLabel("Waiting for victims...")

local function updateKickLog(newName)
    local timeStr = os.date("%H:%M:%S")
    table.insert(kickLogData, 1, "[" .. timeStr .. "] " .. newName .. " ELIMINATED")
    if #kickLogData > 5 then table.remove(kickLogData, 6) end
    local combined = table.concat(kickLogData, "\n")
    KickLabel:Set(combined)
end

local SettingsSection = FlingTab:AddSection({ Name = "⚙️ Physics & Power" })

local powerSlider = SettingsSection:AddSlider({
    Name = "Fling Power (Extreme)",
    Min = 500, Max = 200000, Default = 5000,
    Increment = 500, ValueName = "WATT",
    Callback = function(v) FlingSettings.FlingForce = v end
})

local orbitSlider = SettingsSection:AddSlider({
    Name = "Orbit Range",
    Min = 1, Max = 100, Default = 5,
    Increment = 1, ValueName = "Studs",
    Callback = function(v) FlingSettings.OrbitRadius = v end
})

local ManualSection = FlingTab:AddSection({ Name = "🛠️ Tools" })

ManualSection:AddButton({
	Name = "Manual Break Lamps (5k studs)",
	Callback = function()
        local vehicle = getMyVehicle()
        local lamps = findLamps(5000)
        if not vehicle then return end
        if #lamps > 0 then
            for _, lamp in ipairs(lamps) do breakRemote:FireServer(vehicle, lamp) end
            
        else
            
        end
	end    
})

ManualSection:AddButton({
    Name = "🔴 Reset Full System (Reload & OP Settings)",
    Callback = function()
        
        
        -- Reset Ammo Cache
        activeAmmo = {}
        
        -- Apply Best Settings (Antigravity Optimized)
        powerSlider:Set(200000)
        orbitSlider:Set(3)
        godModeToggle:Set(true)
        autoBreakToggle:Set(true)
        
        -- Force Refresh Logic
        FlingSettings.FlingActive = true
        FlingSettings.OPFling = true
        FlingSettings.FlingTargetMode = "Fling Full Server"
        FlingSettings.AutoBreak = true
        
        
    end
})

-- // Player Event Listeners \\ --
Players.PlayerAdded:Connect(updatePlayerCount)
Players.PlayerRemoving:Connect(function(player)
    updatePlayerCount()
    if not FlingSettings.FlingActive then return end
    updateKickLog(player.Name)
    if FlingSettings.SelectedPlayer == player then FlingSettings.SelectedPlayer = nil end
end)

updatePlayerCount()

-- // ULTIMATE Flinger Logic \\ --

RunService.Heartbeat:Connect(function()
    if not FlingSettings.FlingActive then return end
    
    local folder = workspace:FindFirstChild("DestroyedObjects")
    if folder then
        for _, v in pairs(folder:GetDescendants()) do
            if v:IsA("MeshPart") and not table.find(activeAmmo, v) then
                -- Super-Heavy Physics Properties
                v.CustomPhysicalProperties = PhysicalProperties.new(100, 10, 10, 100, 100)
                v.CanCollide = false
                v.CanTouch = true
                pcall(function() v.Anchored = false end)
                table.insert(activeAmmo, v)
            end
        end
    end
    
    local liveAmmo = {}
    local spin = (tick() * 800) % 360 -- Optimized spin speed for physics stability
    local players = Players:GetPlayers()
    local victims = {}
    for _, p in ipairs(players) do
        if p ~= LocalPlayer and p.Character then table.insert(victims, p) end
    end
    
    for i, obj in ipairs(activeAmmo) do
        if obj and obj.Parent then
            local center = nil
            local targetPart = nil
            
            if FlingSettings.FlingTargetMode == "Click" then center = FlingSettings.FixedPos
            elseif FlingSettings.FlingTargetMode == "Follow Target" and FlingSettings.SelectedPlayer and FlingSettings.SelectedPlayer.Character then
                local char = FlingSettings.SelectedPlayer.Character
                targetPart = char:FindFirstChild("HumanoidRootPart") or char:FindFirstChild("Torso") or char:FindFirstChild("Head")
                center = targetPart and targetPart.Position
            elseif FlingSettings.FlingTargetMode == "Fling Full Server" and #victims > 0 then
                local vict = victims[(i % #victims) + 1]
                if vict and vict.Character then
                    targetPart = vict.Character:FindFirstChild("HumanoidRootPart") or vict.Character:FindFirstChild("Torso")
                    center = targetPart and targetPart.Position
                end
            end
            
            if center then
                local rad = math.rad(spin + (i * (360 / (#activeAmmo > 0 and #activeAmmo or 1))))
                
                -- High-Energy Jitter Logic
                local hOsc = math.sin(tick() * 10 + i) * 3 -- Faster oscillation
                local rJit = math.cos(tick() * 7 + i) * 2 -- More radical jitter
                
                local currentRadius = math.max(FlingSettings.OrbitRadius + rJit, 1)
                -- Dynamic Offset targeting different body parts slightly
                local tPos = center + Vector3.new(math.cos(rad) * currentRadius, hOsc, math.sin(rad) * currentRadius)
                
                -- Instant Lock Teleport (threshold reduced to 5 studs)
                if (obj.Position - center).Magnitude > 5 then 
                    pcall(function() obj.CFrame = CFrame.new(tPos) end) 
                end
                
                pcall(function()
                    local diff = (tPos - obj.Position)
                    local dir = (diff.Magnitude > 0 and diff.Unit or Vector3.new(0,1,0))
                    
                    -- Optimized Velocity
                    obj.AssemblyLinearVelocity = dir * FlingSettings.FlingForce
                    -- Stable High Angular Velocity
                    obj.AssemblyAngularVelocity = Vector3.new(12000, 12000, 12000)
                end)
                table.insert(liveAmmo, obj)
            end
        end
    end
    activeAmmo = liveAmmo
end)

Mouse.Button1Down:Connect(function()
    if FlingSettings.FlingTargetMode == "Click" then FlingSettings.FixedPos = Mouse.Hit.p end
end)





-- =====================
-- WORLD MODS TAB
-- =====================
local WorldTab = Window:MakeTab({ Name = "World Mods", Icon = "rbxassetid://10734946029", PremiumOnly = false })

WorldTab:AddParagraph("World Modification", "Here you can find features that modify the world or enhance performance.")

WorldTab:AddButton({
    Name = "Fix Lighting",
    Callback = function()
        local lighting = game:GetService("Lighting")
        for _, v in pairs(lighting:GetChildren()) do
            if v:IsA("PostProcessEffect") or v:IsA("BloomEffect") or v:IsA("BlurEffect") or v:IsA("DepthOfFieldEffect") or v:IsA("SunRaysEffect") or v:IsA("ColorCorrectionEffect") then
                v.Enabled = false
            end
        end
        
    end
})

WorldTab:AddLabel("--- Performance & Lighting ---")

WorldTab:AddToggle({
    Name = "Remove Shadows",
    Default = false,
    Callback = function(v)
        game:GetService("Lighting").GlobalShadows = not v
    end
})

WorldTab:AddToggle({
    Name = "Full Bright",
    Default = false,
    Callback = function(v)
        if v then
            game:GetService("Lighting").Ambient = Color3.fromRGB(255, 255, 255)
            game:GetService("Lighting").OutdoorAmbient = Color3.fromRGB(255, 255, 255)
            game:GetService("Lighting").Brightness = 2
        else
            game:GetService("Lighting").Ambient = Color3.fromRGB(127, 127, 127)
            game:GetService("Lighting").OutdoorAmbient = Color3.fromRGB(127, 127, 127)
            game:GetService("Lighting").Brightness = 1
        end
    end
})

WorldTab:AddToggle({
    Name = "Remove Fog",
    Default = false,
    Callback = function(v)
        if v then
            game:GetService("Lighting").FogEnd = 999999
        else
            game:GetService("Lighting").FogEnd = 1000
        end
    end
})

local fpsBoostConnection = nil
local function applyPartOptimization(part)
    if part:IsA("BasePart") or part:IsA("UnionOperation") or part:IsA("MeshPart") then
        part.Material = Enum.Material.Plastic
        part.Reflectance = 0
        part.CastShadow = false
        if part:IsA("MeshPart") then
            part.RenderFidelity = Enum.RenderFidelity.Performance
        end
    elseif part:IsA("Decal") or part:IsA("Texture") then
        part.Transparency = 1
    elseif part:IsA("ParticleEmitter") or part:IsA("Trail") then
        part.Lifetime = NumberRange.new(0)
        part.Enabled = false
    elseif part:IsA("Fire") or part:IsA("Smoke") or part:IsA("Sparkles") then
        part.Enabled = false
    end
end

WorldTab:AddToggle({
    Name = "FPS Boost",
    Default = false,
    Callback = function(v)
        local Lighting = game:GetService("Lighting")
        local Terrain = workspace:FindFirstChildOfClass("Terrain")

        if v then
            task.spawn(function()
                Lighting.GlobalShadows = false
                Lighting.FogEnd = 9e9
                
                if Terrain then
                    Terrain.WaterWaveSize = 0
                    Terrain.WaterWaveSpeed = 0
                    Terrain.WaterReflectance = 0
                    Terrain.WaterTransparency = 0
                    Terrain.Decoration = false
                end

                for _, effect in ipairs(Lighting:GetDescendants()) do
                    if effect:IsA("PostProcessEffect") or effect:IsA("BloomEffect") or effect:IsA("BlurEffect") or effect:IsA("DepthOfFieldEffect") or effect:IsA("SunRaysEffect") or effect:IsA("ColorCorrectionEffect") then
                        effect.Enabled = false
                    end
                end

                local descendants = workspace:GetDescendants()
                for i = 1, #descendants do
                    applyPartOptimization(descendants[i])
                    if i % 1000 == 0 then task.wait() end
                end

                fpsBoostConnection = workspace.DescendantAdded:Connect(applyPartOptimization)
                
                pcall(function()
                    settings().Rendering.QualityLevel = Enum.QualityLevel.Level01
                end)
            end)
        else
            if fpsBoostConnection then 
                fpsBoostConnection:Disconnect() 
                fpsBoostConnection = nil
            end
            Lighting.GlobalShadows = true
            Lighting.FogEnd = 1000
            if Terrain then Terrain.Decoration = true end
            
            for _, effect in ipairs(Lighting:GetDescendants()) do
                if effect:IsA("PostProcessEffect") or effect:IsA("BloomEffect") or effect:IsA("BlurEffect") or effect:IsA("DepthOfFieldEffect") or effect:IsA("SunRaysEffect") or effect:IsA("ColorCorrectionEffect") then
                    effect.Enabled = true
                end
            end
        end
    end
})

-- =====================
-- GUN MODS TAB
-- =====================
local GunModsTab = Window:MakeTab({ Name = "Gun Mods", Icon = "rbxassetid://11419711621", PremiumOnly = false })

local GunModsSettings = {
    FastBullet = false,
    InstantAim = false,
    AimFOV = 35,
    MinjiCrosshair = false
}

GunModsTab:AddToggle({
    Name = "Fast Bullet",
    Default = false,
    Save = true,
    Callback = function(v)
        GunModsSettings.FastBullet = v
    end
})

GunModsTab:AddToggle({
    Name = "Instant Aim",
    Default = false,
    Save = true,
    Callback = function(v)
        GunModsSettings.InstantAim = v
    end
})

GunModsTab:AddToggle({
    Name = "Minji Crosshair",
    Default = false,
    Save = true,
    Callback = function(v)
        GunModsSettings.MinjiCrosshair = v
    end
})

GunModsTab:AddSlider({
    Name = "Aim FOV Changer",
    Min = 10,
    Max = 120,
    Default = 35,
    Increment = 1,
    ValueName = "FOV",
    Save = true,
    Callback = function(v)
        GunModsSettings.AimFOV = v
    end
})

GunModsTab:AddSection({ Name = "--- OG Sniper ---" })
GunModsTab:AddToggle({
    Name = "OG Sniper",
    Default = OGSniperEnabled,
    Callback = function(v)
        OGSniperEnabled = v
        SaveConfig()
    end
})

RunService.Heartbeat:Connect(function()
    if not OGSniperEnabled then return end
    local character = LocalPlayer.Character
    if not character then return end

    for _, tool in pairs(character:GetChildren()) do
        if tool:IsA("Tool") and tool:GetAttribute("Scope") ~= nil then
            tool:SetAttribute("Scope", false)
        end
    end
end)

task.spawn(function()
    while true do
        task.wait(0.2)
        pcall(function()
            local char = LocalPlayer.Character
            local tool = char and char:FindFirstChildOfClass("Tool")
            if tool then
                if GunModsSettings.FastBullet then
                    tool:SetAttribute("ShootDelay", 0.01)
                end
                if GunModsSettings.InstantAim then
                    tool:SetAttribute("AimDelay", 0.1)
                end
                if GunModsSettings.MinjiCrosshair then
                    tool:SetAttribute("CrosshairSize", 5)
                end
                tool:SetAttribute("AimFieldOfView", GunModsSettings.AimFOV)
            end
        end)
    end
end)

-- =====================
-- SETTINGS TAB
-- =====================
local SettingsTab = Window:MakeTab({ Name = "Settings", Icon = "rbxassetid://10734950309", PremiumOnly = false })

SettingsTab:AddParagraph("Credits", "Credits to:\nFunnex, mr robot and y/mi6 for helping me coding this Hub!\n\nFounder:\n2rq1")

local FeedbackRating = "⭐⭐⭐⭐⭐"
local FeedbackLike = ""
local FeedbackBugs = ""

SettingsTab:AddLabel("--- Rate Cryptic Hub ---")

SettingsTab:AddDropdown({
	Name = "Your Rating",
	Default = "⭐⭐⭐⭐⭐",
	Options = {"⭐", "⭐⭐", "⭐⭐⭐", "⭐⭐⭐⭐", "⭐⭐⭐⭐⭐"},
	Callback = function(v)
		FeedbackRating = v
	end    
})

SettingsTab:AddTextbox({
	Name = "What do you like?",
	Default = "",
	TextDisappear = false,
	Callback = function(v)
		FeedbackLike = v
	end	  
})

SettingsTab:AddTextbox({
	Name = "Bugs found?",
	Default = "",
	TextDisappear = false,
	Callback = function(v)
		FeedbackBugs = v
	end	  
})

SettingsTab:AddButton({
	Name = "Submit Feedback",
	Callback = function()
        local WebhookURL = "https://discord.com/api/webhooks/1494843218221858956/lRRrW-ZsgTU8DLtoa8ssnazLLBP7n4ZXx3GWk67JccW1WThxCoTc06BCJf_mzulvk1AN"
        local path = "CrypticHub_Cooldown.json"
        local HWID = game:GetService("RbxAnalyticsService"):GetClientId()
        local cooldownTime = 36000 -- 10 Stunden
        
        -- Cooldown Check
        local cooldownData = {}
        if isfile(path) then
            pcall(function()
                cooldownData = game:GetService("HttpService"):JSONDecode(readfile(path))
            end)
        end
        
        if cooldownData[HWID] then
            local lastTime = tonumber(cooldownData[HWID])
            if lastTime and (os.time() - lastTime) < cooldownTime then
                local remaining = math.ceil((cooldownTime - (os.time() - lastTime)) / 60)
                
                return
            end
        end

        -- Send Webhook
        local requestFunc = syn and syn.request or http_request or request or fluxus and fluxus.request
        if requestFunc then
            local data = {
                ["embeds"] = {{
                    ["title"] = "New Script Rating! 🚀",
                    ["color"] = 5814783,
                    ["fields"] = {
                        {["name"] = "User", ["value"] = LocalPlayer.Name .. " (" .. LocalPlayer.UserId .. ")", ["inline"] = true},
                        {["name"] = "HWID", ["value"] = "||" .. HWID .. "||", ["inline"] = true},
                        {["name"] = "Rating", ["value"] = FeedbackRating or "N/A", ["inline"] = true},
                        {["name"] = "Feedback", ["value"] = (FeedbackLike and FeedbackLike ~= "") and FeedbackLike or "N/A"},
                        {["name"] = "Bugs", ["value"] = (FeedbackBugs and FeedbackBugs ~= "") and FeedbackBugs or "None"}
                    },
                    ["footer"] = {["text"] = "Cryptic Hub Feedback System"}
                }}
            }
            
            pcall(function()
                requestFunc({
                    Url = WebhookURL,
                    Method = "POST",
                    Headers = {["Content-Type"] = "application/json"},
                    Body = game:GetService("HttpService"):JSONEncode(data)
                })
                
                cooldownData[HWID] = os.time()
                writefile(path, game:GetService("HttpService"):JSONEncode(cooldownData))
                
                
            end)
        else
            
        end
	end    
})

SettingsTab:AddLabel("--- General Settings ---")


SettingsTab:AddButton({
	Name = "Close Cheat",
	Callback = function()
        -- Deactivate everything
        AimbotSettings.Enabled = false
        ESPSettings.Box = false
        ESPSettings.Name = false
        ESPSettings.Chams = false
        NoclipEnabled = false
        CFrameSpeedEnabled = false
        _G.AntiFallEnabled = false
        
        -- Destroy ESP Objects
        for _, esp in pairs(ESPObjects or {}) do
            for _, obj in pairs(esp) do pcall(function() obj:Remove() end) end
        end
        
        -- Close and Destroy UI
        OrionLib:Destroy()
	end    
})

SettingsTab:AddButton({
    Name = "Copy Discord Link",
    Callback = function()
        if setclipboard then
            setclipboard("https://discord.gg/G8Wf3Rzaz6")
            
        else
            
        end
    end
})


-- [ AUTO COLLECT SYSTEM ]
local activeCollections = {}
local function autoCollect(ins, id)
    if not AutoCollectEnabled or activeCollections[ins] then return end
    
    local char = LocalPlayer.Character
    local hrp = char and char:FindFirstChild("HumanoidRootPart")
    if not hrp then return end

    local pos = (ins:IsA("BasePart") and ins.Position) or (ins:FindFirstChild("DisplayPosition") and ins.DisplayPosition.WorldPosition) or (ins:IsA("Model") and ins:GetPivot().Position)
    if not pos or (hrp.Position - pos).Magnitude > 14 then return end

    activeCollections[ins] = true
    pcall(function()
        interactRemote(ins, id, true)
        task.wait(2.31)
        interactRemote(ins, id, false)
    end)
    activeCollections[ins] = nil
end

local function checkAutoCollect(ins)
    if not ins or not ins.Parent then return end
    if CollectionService:HasTag(ins, "Item Collect Interactable") then
        if ins:GetAttribute("Enabled") then autoCollect(ins, "yPK") end
    elseif CollectionService:HasTag(ins, "Item Drop Interactable") then
        autoCollect(ins, "ov6")
    elseif CollectionService:HasTag(ins, "Money Collect Interactable") then
        if ins:GetAttribute("Enabled") then autoCollect(ins, "M4j") end
    elseif ins.Parent and ins.Parent.Name == "Drops" then
        if ins.Name == LocalPlayer.Name or ins:FindFirstChild(LocalPlayer.Name) then
            autoCollect(ins, "ov6")
        end
    end
end

CollectionService:GetInstanceAddedSignal("Item Collect Interactable"):Connect(function(ins)
    if AutoCollectEnabled then task.spawn(checkAutoCollect, ins) end
end)
CollectionService:GetInstanceAddedSignal("Item Drop Interactable"):Connect(function(ins)
    if AutoCollectEnabled then task.spawn(checkAutoCollect, ins) end
end)
CollectionService:GetInstanceAddedSignal("Money Collect Interactable"):Connect(function(ins)
    if AutoCollectEnabled then task.spawn(checkAutoCollect, ins) end
end)

local dropsFolder = workspace:FindFirstChild("Drops")
if dropsFolder then
    dropsFolder.ChildAdded:Connect(function(ins)
        if AutoCollectEnabled then task.spawn(checkAutoCollect, ins) end
    end)
end

task.spawn(function()
    while task.wait(0.1) do
        if AutoCollectEnabled then
            for _, ins in ipairs(CollectionService:GetTagged("Item Collect Interactable")) do
                task.spawn(checkAutoCollect, ins)
            end
            for _, ins in ipairs(CollectionService:GetTagged("Item Drop Interactable")) do
                task.spawn(checkAutoCollect, ins)
            end
            for _, ins in ipairs(CollectionService:GetTagged("Money Collect Interactable")) do
                task.spawn(checkAutoCollect, ins)
            end
            if dropsFolder then
                for _, ins in ipairs(dropsFolder:GetChildren()) do
                    task.spawn(checkAutoCollect, ins)
                end
            end
        end
    end
end)

OrionLib:Init()

-- [ ANIMATED TITLE ]
task.spawn(function()
    local titleStr = "Cryptic Hub - dsc.gg/hJDvEdfy "
    local fullTitle = ""
    local mainGui = game:GetService("CoreGui"):FindFirstChild("Orion") or LocalPlayer:WaitForChild("PlayerGui"):FindFirstChild("Orion")
    if mainGui then
        local main = mainGui:FindFirstChild("Main")
        local topbar = main and main:FindFirstChild("Topbar")
        local titleLabel = topbar and topbar:FindFirstChild("Title")
        if titleLabel then
            while true do
                -- Typewriter Effekt
                for i = 1, #titleStr do
                    titleLabel.Text = string.sub(titleStr, 1, i)
                    task.wait(0.1)
                end
                task.wait(2)
                -- Kurz löschen oder warten
                for i = #titleStr, 1, -1 do
                    titleLabel.Text = string.sub(titleStr, 1, i)
                    task.wait(0.05)
                end
                task.wait(1)
            end
        end
    end
end)

