测试
local Players = game:GetService("Players")
local CoreGui = game:GetService("CoreGui")
local RunService = game:GetService("RunService")
local UserInputService = game:GetService("UserInputService")
local TweenService = game:GetService("TweenService")
local CollectionService = game:GetService("CollectionService")

local LocalPlayer = Players.LocalPlayer
local PlayerGui = LocalPlayer:WaitForChild("PlayerGui")
local Camera = workspace.CurrentCamera

local clock = os.clock
local random = math.random
local huge = math.huge
local v2new = Vector2.new
local v3new = Vector3.new
local v3zero = Vector3.zero

local Config = {
    Enabled = false,
    Range = 20,
    Delay = 0.5,
    SendMode = "逐个发送",
    PerTargetDelay = 0.03,
    WalkSpeed = 16,
    MaxWalkSpeed = 35,
    Noclip = false,
    Silent = {
        Enabled = false, LockMode = "Crosshair", MaxDistance = 500,
        VisibleCheck = false, FOVRadius = 200, FOVScale = 1.0,
        Wallbang = true, BlacklistedNames = {},
        NPCCacheRefreshInterval = 0.5, TargetScanInterval = 1/30, VisibilityCacheTime = 0.15
    },
    ESP = {
        Enabled = false, OutlineColor = Color3.fromRGB(255, 255, 255),
        FillTransparency = 0.5, DepthMode = Enum.HighlightDepthMode.AlwaysOnTop,
        MovementThreshold = 0.3, MovementCheckInterval = 0.1,
        PendingCheckBatch = 1000, StaticTimeout = nil,
        Types = {
            Enemy = {Color = Color3.fromRGB(255, 0, 0), Keywords = {"enemy", "hostile", "guard", "soldier", "bandit", "raider", "zombie", "monster", "bot", "drone", "turret"}},
            Hostage = {Color = Color3.fromRGB(0, 255, 0), Keywords = {"hostage", "civilian", "victim", "prisoner", "captive"}},
            Friendly = {Color = Color3.fromRGB(0, 150, 255), Keywords = {"friendly", "ally", "teammate", "squad", "partner"}},
            Neutral = {Color = Color3.fromRGB(255, 255, 0), Keywords = {"neutral", "trader", "merchant", "villager", "npc", "animal", "creature", "dog", "cat"}},
            Corpse = {Color = Color3.fromRGB(128, 128, 128), Keywords = {}}
        }
    }
}

local function GetBat()
    local char = LocalPlayer.Character
    if not char then return nil end
    return char:FindFirstChild("Bat")
end

local function GetTargetPosition(model)
    if model.PrimaryPart then return model.PrimaryPart.Position end
    local part = model:FindFirstChild("HumanoidRootPart") or model:FindFirstChild("Head") or model:FindFirstChild("MainPart")
    if part then return part.Position end
    for _, child in ipairs(model:GetChildren()) do
        if child:IsA("BasePart") then return child.Position end
    end
    return nil
end

local HealthAttrNames = {"Health", "HP", "health", "hp", "Durability", "Integrity", "Hitpoints", "CurrentHealth", "currentHealth"}
local HealthValueNames = {"health", "hp", "healthvalue", "durability", "integrity", "currenthealth"}

local function HasHealth(model)
    local hum = model:FindFirstChildOfClass("Humanoid")
    if hum and hum.Health > 0 then return true end
    for _, attrName in ipairs(HealthAttrNames) do
        local val = model:GetAttribute(attrName)
        if type(val) == "number" and val > 0 then return true end
    end
    for _, child in ipairs(model:GetChildren()) do
        if child:IsA("NumberValue") or child:IsA("IntValue") then
            local n = string.lower(child.Name)
            for _, validName in ipairs(HealthValueNames) do
                if n == validName and child.Value > 0 then return true end
            end
        end
    end
    return false
end

local function IsValidTarget(model)
    if not model:IsA("Model") then return false end
    if model == LocalPlayer.Character then return false end
    if LocalPlayer.Character and model:IsDescendantOf(LocalPlayer.Character) then return false end
    if model:IsDescendantOf(LocalPlayer) then return false end
    if Players:GetPlayerFromCharacter(model) then return false end
    for _, player in ipairs(Players:GetPlayers()) do
        if player.Character and (model == player.Character or model:IsDescendantOf(player.Character)) then
            return false
        end
    end
    if not model.Parent then return false end
    if not HasHealth(model) then return false end
    local pos = GetTargetPosition(model)
    if not pos then return false end
    return true, pos
end

local function GetAllTargets()
    local seen, list = {}, {}
    for _, obj in ipairs(workspace:GetDescendants()) do
        if not seen[obj] then
            seen[obj] = true
            local isValid, pos = IsValidTarget(obj)
            if isValid then table.insert(list, {model = obj, pos = pos}) end
        end
    end
    return list
end

local function ModifyWeaponRange()
    local bat = GetBat()
    if not bat then return end
    for _, v in ipairs(bat:GetDescendants()) do
        if v:IsA("NumberValue") and (string.find(string.lower(v.Name), "range") or string.find(string.lower(v.Name), "hit")) then
            v.Value = 9999
        end
    end
end

local function ApplySpeed()
    local char = LocalPlayer.Character
    local hum = char and char:FindFirstChildOfClass("Humanoid")
    if hum then hum.WalkSpeed = Config.WalkSpeed end
end

local function ApplyNoclip()
    if not Config.Noclip then return end
    local char = LocalPlayer.Character
    if not char then return end
    for _, v in ipairs(char:GetDescendants()) do
        if v:IsA("BasePart") and v.CanCollide then v.CanCollide = false end
    end
end

local AttackLoop = function()
    while Config.Enabled and CoreGui:FindFirstChild("ModernToolUI") do
        local char = LocalPlayer.Character
        local hrp = char and char:FindFirstChild("HumanoidRootPart")
        local bat = GetBat()
        if char and hrp and bat then
            local swing = bat:FindFirstChild("Swing")
            local hitTargets = bat:FindFirstChild("HitTargets")
            if swing and hitTargets then
                local allTargets = GetAllTargets()
                local targets = {}
                for _, data in ipairs(allTargets) do
                    if (data.pos - hrp.Position).Magnitude <= Config.Range then
                        table.insert(targets, data.model)
                    end
                end
                if #targets > 0 then
                    if Config.SendMode == "逐个发送" then
                        for _, target in ipairs(targets) do
                            if target and target.Parent then
                                swing:FireServer()
                                task.wait(Config.PerTargetDelay)
                                hitTargets:FireServer({target})
                                task.wait(Config.PerTargetDelay)
                            end
                        end
                    else
                        swing:FireServer()
                        hitTargets:FireServer(targets)
                    end
                    if _G.KA_StatusLabel then _G.KA_StatusLabel.Text = "目标: " .. #targets end
                else
                    if _G.KA_StatusLabel then _G.KA_StatusLabel.Text = "目标: 0" end
                end
            end
        end
        task.wait(Config.Delay)
    end
end

local currentTargetPart, lockedPart = nil, nil
local lastTargetScan, lastReconcile, lastBlacklistRebuild = 0, 0, 0
local blacklistSet, playerChars, npcEntries, entryByModel, pendingModels = {}, {}, {}, {}, {}

local function rebuildBlacklist()
    for k in pairs(blacklistSet) do blacklistSet[k] = nil end
    for i = 1, #Config.Silent.BlacklistedNames do blacklistSet[Config.Silent.BlacklistedNames[i]] = true end
end
rebuildBlacklist()

local function addPlayerChar(char) if char then playerChars[char] = true end end
local function removePlayerChar(char) if char then playerChars[char] = nil end end

for _, plr in ipairs(Players:GetPlayers()) do
    addPlayerChar(plr.Character)
    plr.CharacterAdded:Connect(addPlayerChar)
    plr.CharacterRemoving:Connect(removePlayerChar)
end
Players.PlayerAdded:Connect(function(plr)
    addPlayerChar(plr.Character)
    plr.CharacterAdded:Connect(addPlayerChar)
    plr.CharacterRemoving:Connect(removePlayerChar)
end)

local function addEntry(model, hum, root)
    if entryByModel[model] then return end
    entryByModel[model] = {model = model, humanoid = hum, root = root, head = model:FindFirstChild("Head")}
    table.insert(npcEntries, entryByModel[model])
end

local function removeEntry(model)
    local entry = entryByModel[model]
    if not entry then return end
    entryByModel[model] = nil
    for i, e in ipairs(npcEntries) do
        if e == entry then table.remove(npcEntries, i); break end
    end
end

local function tryAddNPC(model)
    if not model:IsA("Model") or entryByModel[model] or playerChars[model] or blacklistSet[model.Name] then return end
    local hum, root = model:FindFirstChildOfClass("Humanoid"), model:FindFirstChild("HumanoidRootPart")
    if hum and root then addEntry(model, hum, root); return end
    if pendingModels[model] then return end
    pendingModels[model] = true
    local conn
    conn = model.ChildAdded:Connect(function()
        if entryByModel[model] then
            if conn.Connected then conn:Disconnect() end
            pendingModels[model] = nil; return
        end
        local h, r = model:FindFirstChildOfClass("Humanoid"), model:FindFirstChild("HumanoidRootPart")
        if h and r then
            addEntry(model, h, r)
            if conn.Connected then conn:Disconnect() end
            pendingModels[model] = nil
        end
    end)
end

do
    for _, d in ipairs(workspace:GetDescendants()) do
        if d:IsA("Model") then tryAddNPC(d) end
    end
end
workspace.DescendantAdded:Connect(function(d) if d:IsA("Model") then tryAddNPC(d) end end)
workspace.DescendantRemoving:Connect(function(d) if d:IsA("Model") then removeEntry(d) end end)

local function reconcile()
    local now = clock()
    if now - lastReconcile < 3 then return end
    lastReconcile = now
    for i = #npcEntries, 1, -1 do
        local e = npcEntries[i]
        if not e.model.Parent or not e.humanoid.Parent or e.humanoid.Health <= 0 then removeEntry(e.model) end
    end
    for _, plr in ipairs(Players:GetPlayers()) do
        if plr ~= LocalPlayer and plr.Character then playerChars[plr.Character] = true end
    end
end

local screenCenter, lastViewport = v2new(0, 0), v2new(0, 0)
local function updateScreenCenter()
    local vs = Camera.ViewportSize
    if vs ~= lastViewport then lastViewport = vs; screenCenter = v2new(vs.X * 0.5, vs.Y * 0.5) end
end
updateScreenCenter()
workspace:GetPropertyChangedSignal("CurrentCamera"):Connect(function()
    Camera = workspace.CurrentCamera; lastViewport = v2new(0, 0); updateScreenCenter()
end)

local visCacheTime, visCacheResult = setmetatable({}, {__mode = "k"}), setmetatable({}, {__mode = "k"})
local visIgnore = {nil, nil}
local function checkVisible(part, camPos, now)
    local t = visCacheTime[part]
    if t and now - t < Config.Silent.VisibilityCacheTime then return visCacheResult[part] end
    visIgnore[1], visIgnore[2] = LocalPlayer.Character, part.Parent
    local hit = workspace:FindPartOnRayWithIgnoreList(Ray.new(camPos, part.Position - camPos), visIgnore)
    local visible = (hit == nil)
    visCacheTime[part], visCacheResult[part] = now, visible
    return visible
end

local boxLines = {}
for i = 1, 4 do
    local line = Drawing.new("Line")
    line.Thickness, line.Color, line.Transparency, line.Visible, line.ZIndex = 2, Color3.fromRGB(255, 255, 255), 0.5, false, 999
    boxLines[i] = line
end

local function hideBox()
    for i = 1, 4 do if boxLines[i].Visible then boxLines[i].Visible = false end end
end

local function updateBox(part)
    if not part or not part.Parent then hideBox() return end
    local char = part.Parent
    local head, root = char:FindFirstChild("Head"), char:FindFirstChild("HumanoidRootPart")
    if not head or not root then hideBox() return end
    local topScreen, topOn = Camera:WorldToViewportPoint(head.Position + v3new(0, 0.5, 0))
    local bottomScreen, bottomOn = Camera:WorldToViewportPoint(root.Position - v3new(0, 2.5, 0))
    if not (topOn and bottomOn) then hideBox() return end
    local height = bottomScreen.Y - topScreen.Y
    if height <= 0 then hideBox() return end
    local width = height * 0.6
    local centerX = (topScreen.X + bottomScreen.X) * 0.5
    local left, right, top, bottom = centerX - width * 0.5, centerX + width * 0.5, topScreen.Y, bottomScreen.Y
    boxLines[1].From, boxLines[1].To = v2new(left, top), v2new(right, top)
    boxLines[2].From, boxLines[2].To = v2new(right, top), v2new(right, bottom)
    boxLines[3].From, boxLines[3].To = v2new(right, bottom), v2new(left, bottom)
    boxLines[4].From, boxLines[4].To = v2new(left, bottom), v2new(left, top)
    for i = 1, 4 do if not boxLines[i].Visible then boxLines[i].Visible = true end end
end

local function updateTarget()
    if not Config.Silent.Enabled then
        if lockedPart then lockedPart, currentTargetPart = nil, nil end
        hideBox(); return
    end
    local now = clock()
    if now - lastTargetScan < Config.Silent.TargetScanInterval then return end
    lastTargetScan = now
    if now - lastBlacklistRebuild > 1 then lastBlacklistRebuild = now; rebuildBlacklist() end

    local camPos, fovCenter = Camera.CFrame.Position, screenCenter
    local fovRSq, maxDistSq = Config.Silent.FOVRadius^2, Config.Silent.MaxDistance^2
    local visCheck, w2v, lockMode = Config.Silent.VisibleCheck, Camera.WorldToViewportPoint, Config.Silent.LockMode
    local bestPart, bestScore, hasLock = nil, huge, false

    if lockedPart and lockedPart.Parent then
        local entry = entryByModel[lockedPart.Parent]
        if entry and entry.humanoid.Health > 0 then
            local sp, onScreen = w2v(Camera, lockedPart.Position)
            if onScreen then
                local fovSq = (sp.X - fovCenter.X)^2 + (sp.Y - fovCenter.Y)^2
                if fovSq <= fovRSq then
                    bestPart = lockedPart
                    bestScore = (lockMode == "Crosshair") and fovSq or (lockedPart.Position - camPos).Magnitude
                    hasLock = true
                end
            end
        end
    end

    for i = 1, #npcEntries do
        local entry = npcEntries[i]
        if entry.humanoid.Health > 0 and not blacklistSet[entry.model.Name] then
            local part = entry.head or entry.root
            if part and part.Parent then
                local pp = part.Position
                local distSq = (pp.X - camPos.X)^2 + (pp.Y - camPos.Y)^2 + (pp.Z - camPos.Z)^2
                if distSq <= maxDistSq then
                    local sp, onScreen = w2v(Camera, pp)
                    if onScreen then
                        local fovSq = (sp.X - fovCenter.X)^2 + (sp.Y - fovCenter.Y)^2
                        if fovSq <= fovRSq and ((not visCheck) or checkVisible(part, camPos, now)) then
                            local score = (lockMode == "Crosshair") and fovSq or math.sqrt(distSq)
                            if (hasLock and score < bestScore * 0.7) or (not hasLock and score < bestScore) then
                                bestPart, bestScore, hasLock = part, score, false
                            end
                        end
                    end
                end
            end
        end
    end
    if bestPart ~= lockedPart then lockedPart, currentTargetPart = bestPart, bestPart end
    if lockedPart then updateBox(lockedPart) else hideBox() end
end

local CONTROL_SCRIPTS = {ControlScript = true, ControlModule = true}
local controlCache = setmetatable({}, {__mode = "k"})
local function isControlScript(s)
    if not s then return false end
    local c = controlCache[s]
    if c ~= nil then return c end
    local result = CONTROL_SCRIPTS[tostring(s)] == true
    controlCache[s] = result
    return result
end

local oldNamecall
oldNamecall = hookmetamethod(game, "__namecall", newcclosure(function(...)
    local self, Method = ..., getnamecallmethod()
    if Method ~= "ScreenPointToRay" or checkcaller() or isControlScript(getcallingscript()) then return oldNamecall(...) end
    if Config.Silent.Enabled and currentTargetPart then
        local origin = Camera.CFrame.Position
        local direction = CFrame.lookAt(origin, currentTargetPart.Position)
        local depth = select(3, ...)
        return Ray.new(origin + (depth and direction.LookVector * depth or v3zero), direction.LookVector)
    end
    return oldNamecall(...)
end))

local ESP = {pending = {}, pendingList = {}, watchedHumanoids = {}, lastCheckTime = 0}
local TAG_NAME = "Bodycam_B"
local espConfig = Config.ESP

function ESP:IsNPCCandidate(model)
    return model:IsA("Model") and not Players:GetPlayerFromCharacter(model) and model:FindFirstChildWhichIsA("BasePart", true)
end

function ESP:GetNPCType(model)
    local humanoid = model:FindFirstChildOfClass("Humanoid")
    if humanoid and humanoid.Health <= 0 then return "Corpse" end
    local attrType = model:GetAttribute("NPCType")
    if attrType and espConfig.Types[attrType] then return attrType end
    for typeName, _ in pairs(espConfig.Types) do if CollectionService:HasTag(model, typeName) then return typeName end end
    local name = model.Name:lower()
    for typeName, typeData in pairs(espConfig.Types) do
        for _, keyword in ipairs(typeData.Keywords) do
            if name:find(keyword, 1, true) then return typeName end
        end
    end
    return "Enemy"
end

function ESP:RegisterPending(model)
    if not self:IsNPCCandidate(model) or model:FindFirstChild("ESP_Object") or self.pending[model] then return end
    local pos = model:GetPivot().Position
    if not pos then return end
    self.pending[model] = {startPos = pos, startTime = clock()}
    table.insert(self.pendingList, model)
end

function ESP:Apply(model)
    if not model.Parent or model:FindFirstChild("ESP_Object") then return end
    local npcType = self:GetNPCType(model)
    local typeConfig = espConfig.Types[npcType] or espConfig.Types.Enemy
    local highlight = Instance.new("Highlight")
    highlight.Name, highlight.FillColor, highlight.OutlineColor = "ESP_Object", typeConfig.Color, espConfig.OutlineColor
    highlight.FillTransparency, highlight.DepthMode, highlight.Adornee = espConfig.FillTransparency, espConfig.DepthMode, model
    highlight.Parent = model
    local hum = model:FindFirstChildOfClass("Humanoid")
    if hum and not self.watchedHumanoids[hum] then
        self.watchedHumanoids[hum] = true
        hum.Died:Connect(function()
            task.defer(function()
                local h = model:FindFirstChild("ESP_Object")
                if h then h.FillColor = espConfig.Types.Corpse.Color end
            end)
        end)
    end
    self.pending[model] = nil
end

function ESP:CheckMovement()
    if not espConfig.Enabled then return end
    local now = clock()
    if now - self.lastCheckTime < espConfig.MovementCheckInterval then return end
    self.lastCheckTime = now
    if #self.pendingList == 0 then return end
    local newList, checked = {}, 0
    for i = 1, #self.pendingList do
        local model, data = self.pendingList[i], self.pending[self.pendingList[i]]
        if data and model.Parent then
            if checked >= espConfig.PendingCheckBatch then
                table.insert(newList, model)
            else
                checked += 1
                local pos = model:GetPivot().Position
                if pos and (pos - data.startPos).Magnitude > espConfig.MovementThreshold then
                    self.pending[model] = nil; self:Apply(model)
                elseif not espConfig.StaticTimeout or (now - data.startTime) <= espConfig.StaticTimeout then
                    table.insert(newList, model)
                else self.pending[model] = nil end
            end
        end
    end
    self.pendingList = newList
end

task.spawn(function()
    for _, obj in ipairs(workspace:GetDescendants()) do
        if obj:IsA("Model") then ESP:RegisterPending(obj) end
    end
end)
workspace.DescendantAdded:Connect(function(desc)
    if desc:IsA("Model") then task.spawn(function() ESP:RegisterPending(desc) end) end
end)

RunService.Heartbeat:Connect(function() ESP:CheckMovement() end)
RunService.Stepped:Connect(ApplyNoclip)
RunService.RenderStepped:Connect(function()
    updateScreenCenter(); reconcile(); updateTarget(); ApplySpeed()
    if not Config.Silent.Enabled then hideBox() end
end)

local ScreenGui = Instance.new("ScreenGui")
ScreenGui.Name = "ModernToolUI"
ScreenGui.ResetOnSpawn = false
ScreenGui.ZIndexBehavior = Enum.ZIndexBehavior.Sibling
pcall(function() ScreenGui.Parent = CoreGui end)
if not ScreenGui.Parent then ScreenGui.Parent = PlayerGui end

local Theme = {
    Bg = Color3.fromRGB(22, 22, 26),
    Panel = Color3.fromRGB(30, 30, 36),
    Element = Color3.fromRGB(42, 42, 50),
    ElementHover = Color3.fromRGB(52, 52, 62),
    Text = Color3.fromRGB(240, 240, 245),
    SubText = Color3.fromRGB(150, 150, 160),
    Accent = Color3.fromRGB(90, 110, 245),
    AccentDark = Color3.fromRGB(70, 85, 200),
    Success = Color3.fromRGB(60, 180, 100),
    Danger = Color3.fromRGB(220, 70, 70),
    Stroke = Color3.fromRGB(55, 55, 65)
}

local FloatingButton = Instance.new("TextButton")
FloatingButton.Name = "FloatingButton"
FloatingButton.Size = UDim2.fromOffset(50, 50)
FloatingButton.Position = UDim2.new(0, 40, 0.5, -25)
FloatingButton.BackgroundColor3 = Theme.Accent
FloatingButton.Text = "T"
FloatingButton.TextColor3 = Theme.Text
FloatingButton.Font = Enum.Font.GothamBold
FloatingButton.TextSize = 20
FloatingButton.AutoButtonColor = false
FloatingButton.Active = true
FloatingButton.Parent = ScreenGui

Instance.new("UICorner", FloatingButton).CornerRadius = UDim.new(1, 0)
local FB_Stroke = Instance.new("UIStroke", FloatingButton)
FB_Stroke.Color = Theme.Stroke
FB_Stroke.Thickness = 2
local FB_Gradient = Instance.new("UIGradient", FloatingButton)
FB_Gradient.Color = ColorSequence.new(Theme.Accent, Theme.AccentDark)
FB_Gradient.Rotation = 90

local MainFrame = Instance.new("Frame")
MainFrame.Name = "MainFrame"
MainFrame.Size = UDim2.fromOffset(300, 480)
MainFrame.Position = UDim2.new(0, 100, 0.5, -240)
MainFrame.BackgroundColor3 = Theme.Bg
MainFrame.BorderSizePixel = 0
MainFrame.Active = true
MainFrame.Draggable = true
MainFrame.Visible = false
MainFrame.Parent = ScreenGui

Instance.new("UICorner", MainFrame).CornerRadius = UDim.new(0, 12)
local Main_Stroke = Instance.new("UIStroke", MainFrame)
Main_Stroke.Color = Theme.Stroke
Main_Stroke.Thickness = 1.5
local Main_Gradient = Instance.new("UIGradient", MainFrame)
Main_Gradient.Color = ColorSequence.new(Color3.fromRGB(35, 35, 42), Color3.fromRGB(22, 22, 26))
Main_Gradient.Rotation = 90

local TitleBar = Instance.new("Frame")
TitleBar.Size = UDim2.new(1, 0, 0, 40)
TitleBar.BackgroundTransparency = 1
TitleBar.Parent = MainFrame

local TitleText = Instance.new("TextLabel")
TitleText.Size = UDim2.new(1, -80, 1, 0)
TitleText.Position = UDim2.new(0, 15, 0, 0)
TitleText.BackgroundTransparency = 1
TitleText.Text = "EXPLOIT MENU"
TitleText.TextColor3 = Theme.Text
TitleText.Font = Enum.Font.GothamBold
TitleText.TextSize = 14
TitleText.TextXAlignment = Enum.TextXAlignment.Left
TitleText.Parent = TitleBar

local MinBtn = Instance.new("TextButton")
MinBtn.Size = UDim2.fromOffset(28, 28)
MinBtn.Position = UDim2.new(1, -70, 0.5, -14)
MinBtn.BackgroundColor3 = Theme.Element
MinBtn.Text = "-"
MinBtn.TextColor3 = Theme.Text
MinBtn.Font = Enum.Font.GothamBold
MinBtn.TextSize = 16
MinBtn.AutoButtonColor = false
MinBtn.Parent = TitleBar
Instance.new("UICorner", MinBtn).CornerRadius = UDim.new(0, 6)

local CloseBtn = Instance.new("TextButton")
CloseBtn.Size = UDim2.fromOffset(28, 28)
CloseBtn.Position = UDim2.new(1, -35, 0.5, -14)
CloseBtn.BackgroundColor3 = Theme.Danger
CloseBtn.Text = "X"
CloseBtn.TextColor3 = Theme.Text
CloseBtn.Font = Enum.Font.GothamBold
CloseBtn.TextSize = 12
CloseBtn.AutoButtonColor = false
CloseBtn.Parent = TitleBar
Instance.new("UICorner", CloseBtn).CornerRadius = UDim.new(0, 6)

local Divider = Instance.new("Frame")
Divider.Size = UDim2.new(1, -30, 0, 1)
Divider.Position = UDim2.new(0, 15, 0, 40)
Divider.BackgroundColor3 = Theme.Stroke
Divider.BorderSizePixel = 0
Divider.Parent = MainFrame

local Scroll = Instance.new("ScrollingFrame")
Scroll.Size = UDim2.new(1, -20, 1, -60)
Scroll.Position = UDim2.new(0, 10, 0, 50)
Scroll.BackgroundTransparency = 1
Scroll.BorderSizePixel = 0
Scroll.ScrollBarThickness = 3
Scroll.ScrollBarImageColor3 = Theme.Accent
Scroll.CanvasSize = UDim2.new(0, 0, 0, 0)
Scroll.Parent = MainFrame

local Layout = Instance.new("UIListLayout", Scroll)
Layout.Padding = UDim.new(0, 8)
Layout.SortOrder = Enum.SortOrder.LayoutOrder

local Padding = Instance.new("UIPadding", Scroll)
Padding.PaddingTop = UDim.new(0, 5)
Padding.PaddingBottom = UDim.new(0, 10)

Layout:GetPropertyChangedSignal("AbsoluteContentSize"):Connect(function()
    Scroll.CanvasSize = UDim2.new(0, 0, 0, Layout.AbsoluteContentSize.Y + 20)
end)

local function CreateSection(title, order)
    local frame = Instance.new("Frame")
    frame.Size = UDim2.new(1, 0, 0, 24)
    frame.BackgroundTransparency = 1
    frame.LayoutOrder = order
    frame.Parent = Scroll
    local label = Instance.new("TextLabel")
    label.Size = UDim2.new(1, 0, 1, 0)
    label.BackgroundTransparency = 1
    label.Text = title:upper()
    label.TextColor3 = Theme.Accent
    label.Font = Enum.Font.GothamBold
    label.TextSize = 11
    label.TextXAlignment = Enum.TextXAlignment.Left
    label.Parent = frame
end

local function CreateToggle(text, order, defaultState, callback)
    local btn = Instance.new("TextButton")
    btn.Size = UDim2.new(1, 0, 0, 32)
    btn.BackgroundColor3 = Theme.Element
    btn.Text = ""
    btn.AutoButtonColor = false
    btn.LayoutOrder = order
    btn.Parent = Scroll
    Instance.new("UICorner", btn).CornerRadius = UDim.new(0, 6)
    local stroke = Instance.new("UIStroke", btn)
    stroke.Color = Theme.Stroke
    stroke.Thickness = 1

    local label = Instance.new("TextLabel")
    label.Size = UDim2.new(1, -60, 1, 0)
    label.Position = UDim2.new(0, 12, 0, 0)
    label.BackgroundTransparency = 1
    label.Text = text
    label.TextColor3 = Theme.Text
    label.Font = Enum.Font.GothamMedium
    label.TextSize = 13
    label.TextXAlignment = Enum.TextXAlignment.Left
    label.Parent = btn

    local indicator = Instance.new("Frame")
    indicator.Size = UDim2.fromOffset(36, 18)
    indicator.Position = UDim2.new(1, -48, 0.5, -9)
    indicator.BackgroundColor3 = defaultState and Theme.Success or Color3.fromRGB(60, 60, 70)
    indicator.Parent = btn
    Instance.new("UICorner", indicator).CornerRadius = UDim.new(1, 0)

    local dot = Instance.new("Frame")
    dot.Size = UDim2.fromOffset(14, 14)
    dot.Position = defaultState and UDim2.new(1, -16, 0.5, -7) or UDim2.new(0, 2, 0.5, -7)
    dot.BackgroundColor3 = Theme.Text
    dot.Parent = indicator
    Instance.new("UICorner", dot).CornerRadius = UDim.new(1, 0)

    local state = defaultState
    btn.MouseButton1Click:Connect(function()
        state = not state
        indicator.BackgroundColor3 = state and Theme.Success or Color3.fromRGB(60, 60, 70)
        TweenService:Create(dot, TweenInfo.new(0.15), {Position = state and UDim2.new(1, -16, 0.5, -7) or UDim2.new(0, 2, 0.5, -7)}):Play()
        callback(state)
    end)
end

local function CreateSlider(text, order, default, min, max, step, isFloat, callback)
    local frame = Instance.new("Frame")
    frame.Size = UDim2.new(1, 0, 0, 50)
    frame.BackgroundColor3 = Theme.Element
    frame.LayoutOrder = order
    frame.Parent = Scroll
    Instance.new("UICorner", frame).CornerRadius = UDim.new(0, 6)
    local stroke = Instance.new("UIStroke", frame)
    stroke.Color = Theme.Stroke
    stroke.Thickness = 1

    local label = Instance.new("TextLabel")
    label.Size = UDim2.new(1, -100, 0, 20)
    label.Position = UDim2.new(0, 12, 0, 4)
    label.BackgroundTransparency = 1
    label.Text = text
    label.TextColor3 = Theme.SubText
    label.Font = Enum.Font.GothamMedium
    label.TextSize = 12
    label.TextXAlignment = Enum.TextXAlignment.Left
    label.Parent = frame

    local valueLabel = Instance.new("TextLabel")
    valueLabel.Size = UDim2.new(0, 80, 0, 20)
    valueLabel.Position = UDim2.new(1, -90, 0, 4)
    valueLabel.BackgroundTransparency = 1
    valueLabel.Text = isFloat and string.format("%.2f", default) or tostring(default)
    valueLabel.TextColor3 = Theme.Accent
    valueLabel.Font = Enum.Font.GothamBold
    valueLabel.TextSize = 13
    valueLabel.TextXAlignment = Enum.TextXAlignment.Right
    valueLabel.Parent = frame

    local bar = Instance.new("Frame")
    bar.Size = UDim2.new(1, -24, 0, 6)
    bar.Position = UDim2.new(0, 12, 0, 30)
    bar.BackgroundColor3 = Color3.fromRGB(50, 50, 60)
    bar.Parent = frame
    Instance.new("UICorner", bar).CornerRadius = UDim.new(1, 0)

    local fill = Instance.new("Frame")
    fill.Size = UDim2.new(0, 0, 1, 0)
    fill.BackgroundColor3 = Theme.Accent
    fill.Parent = bar
    Instance.new("UICorner", fill).CornerRadius = UDim.new(1, 0)

    local function updateUI(val)
        val = math.clamp(val, min, max)
        local alpha = (val - min) / (max - min)
        fill.Size = UDim2.new(alpha, 0, 1, 0)
        valueLabel.Text = isFloat and string.format("%.2f", val) or tostring(val)
        callback(val)
    end

    updateUI(default)

    local dragging = false
    bar.InputBegan:Connect(function(input)
        if input.UserInputType == Enum.UserInputType.MouseButton1 or input.UserInputType == Enum.UserInputType.Touch then
            dragging = true
        end
    end)
    bar.InputEnded:Connect(function(input)
        if input.UserInputType == Enum.UserInputType.MouseButton1 or input.UserInputType == Enum.UserInputType.Touch then
            dragging = false
        end
    end)
    UserInputService.InputChanged:Connect(function(input)
        if dragging and (input.UserInputType == Enum.UserInputType.MouseMovement or input.UserInputType == Enum.UserInputType.Touch) then
            local mouseX = UserInputService:GetMouseLocation().X
            local barAbsPos = bar.AbsolutePosition.X
            local barAbsSize = bar.AbsoluteSize.X
            local alpha = math.clamp((mouseX - barAbsPos) / barAbsSize, 0, 1)
            local val = min + (max - min) * alpha
            if not isFloat then val = math.floor(val) end
            updateUI(val)
        end
    end)
end

local function CreateDropdown(text, order, options, default, callback)
    local btn = Instance.new("TextButton")
    btn.Size = UDim2.new(1, 0, 0, 32)
    btn.BackgroundColor3 = Theme.Element
    btn.Text = ""
    btn.AutoButtonColor = false
    btn.LayoutOrder = order
    btn.Parent = Scroll
    Instance.new("UICorner", btn).CornerRadius = UDim.new(0, 6)
    local stroke = Instance.new("UIStroke", btn)
    stroke.Color = Theme.Stroke
    stroke.Thickness = 1

    local label = Instance.new("TextLabel")
    label.Size = UDim2.new(0.5, 0, 1, 0)
    label.Position = UDim2.new(0, 12, 0, 0)
    label.BackgroundTransparency = 1
    label.Text = text
    label.TextColor3 = Theme.Text
    label.Font = Enum.Font.GothamMedium
    label.TextSize = 13
    label.TextXAlignment = Enum.TextXAlignment.Left
    label.Parent = btn

    local valueLabel = Instance.new("TextLabel")
    valueLabel.Size = UDim2.new(0.5, -12, 1, 0)
    valueLabel.Position = UDim2.new(0.5, 0, 0, 0)
    valueLabel.BackgroundTransparency = 1
    valueLabel.Text = default
    valueLabel.TextColor3 = Theme.Accent
    valueLabel.Font = Enum.Font.GothamBold
    valueLabel.TextSize = 13
    valueLabel.TextXAlignment = Enum.TextXAlignment.Right
    valueLabel.Parent = btn

    local idx = table.find(options, default) or 1
    btn.MouseButton1Click:Connect(function()
        idx = (idx % #options) + 1
        valueLabel.Text = options[idx]
        callback(options[idx])
    end)
end

CreateSection("Kill Aura", 1)
CreateToggle("Enable Kill Aura", 2, Config.Enabled, function(v)
    Config.Enabled = v
    if v then
        ModifyWeaponRange()
        task.spawn(AttackLoop)
    end
end)
CreateDropdown("发送模式", 3, {"逐个发送", "打包发送"}, Config.SendMode, function(v)
    Config.SendMode = v
end)
CreateSlider("Range", 4, Config.Range, 1, 60, 1, false, function(v) Config.Range = v end)
CreateSlider("Cooldown", 5, Config.Delay, 0.1, 2.0, 0.05, true, function(v) Config.Delay = v end)
CreateSlider("Per-Target Delay", 6, Config.PerTargetDelay, 0.01, 0.2, 0.01, true, function(v) Config.PerTargetDelay = v end)

local StatusLabel = Instance.new("TextLabel")
StatusLabel.Size = UDim2.new(1, 0, 0, 20)
StatusLabel.BackgroundTransparency = 1
StatusLabel.Text = "目标: 0"
StatusLabel.TextColor3 = Theme.Success
StatusLabel.TextSize = 12
StatusLabel.Font = Enum.Font.Gotham
StatusLabel.LayoutOrder = 7
StatusLabel.Parent = Scroll
_G.KA_StatusLabel = StatusLabel

CreateSection("Silent Aim (NPC)", 10)
CreateToggle("Enable Silent Aim", 11, Config.Silent.Enabled, function(v) Config.Silent.Enabled = v end)
CreateDropdown("Lock Mode", 12, {"Crosshair", "Distance"}, Config.Silent.LockMode, function(v) Config.Silent.LockMode = v end)
CreateToggle("Visibility Check", 13, Config.Silent.VisibleCheck, function(v) Config.Silent.VisibleCheck = v end)
CreateSlider("FOV Radius", 14, Config.Silent.FOVRadius, 10, 1000, 10, false, function(v) Config.Silent.FOVRadius = v end)
CreateSlider("FOV Scale", 15, Config.Silent.FOVScale, 0.5, 2.0, 0.1, true, function(v) Config.Silent.FOVScale = v end)

CreateSection("NPC ESP", 20)
CreateToggle("Enable ESP", 21, Config.ESP.Enabled, function(v) Config.ESP.Enabled = v end)

CreateSection("Misc", 30)
CreateToggle("Noclip", 31, Config.Noclip, function(v) Config.Noclip = v end)
CreateSlider("WalkSpeed", 32, Config.WalkSpeed, 16, Config.MaxWalkSpeed, 1, false, function(v)
    Config.WalkSpeed = v
    ApplySpeed()
end)

local isOpen = false
local function ToggleUI()
    isOpen = not isOpen
    if isOpen then
        FloatingButton.Visible = false
        MainFrame.Visible = true
        MainFrame.Size = UDim2.fromOffset(0, 0)
        TweenService:Create(MainFrame, TweenInfo.new(0.2, Enum.EasingStyle.Quad, Enum.EasingDirection.Out), {Size = UDim2.fromOffset(300, 480)}):Play()
    else
        local tween = TweenService:Create(MainFrame, TweenInfo.new(0.15, Enum.EasingStyle.Quad, Enum.EasingDirection.In), {Size = UDim2.fromOffset(0, 0)})
        tween:Play()
        tween.Completed:Connect(function()
            MainFrame.Visible = false
            FloatingButton.Visible = true
        end)
    end
end

FloatingButton.MouseButton1Click:Connect(ToggleUI)
MinBtn.MouseButton1Click:Connect(ToggleUI)
CloseBtn.MouseButton1Click:Connect(function()
    ScreenGui:Destroy()
    for i = 1, 4 do boxLines[i]:Remove() end
end)

local draggingFB, fbDragStart, fbStartPos = false, nil, nil
FloatingButton.InputBegan:Connect(function(input)
    if input.UserInputType == Enum.UserInputType.MouseButton1 or input.UserInputType == Enum.UserInputType.Touch then
        draggingFB = true
        fbDragStart = input.Position
        fbStartPos = FloatingButton.Position
    end
end)
FloatingButton.InputEnded:Connect(function(input)
    if input.UserInputType == Enum.UserInputType.MouseButton1 or input.UserInputType == Enum.UserInputType.Touch then
        draggingFB = false
    end
end)
UserInputService.InputChanged:Connect(function(input)
    if draggingFB and (input.UserInputType == Enum.UserInputType.MouseMovement or input.UserInputType == Enum.UserInputType.Touch) then
        local delta = input.Position - fbDragStart
        FloatingButton.Position = UDim2.new(
            fbStartPos.X.Scale, fbStartPos.X.Offset + delta.X,
            fbStartPos.Y.Scale, fbStartPos.Y.Offset + delta.Y
        )
    end
end)

LocalPlayer.CharacterAdded:Connect(function()
    task.wait(1)
    ApplySpeed()
end)

task.spawn(function()
    while ScreenGui.Parent do
        ApplySpeed()
        task.wait(1)
    end
end)