Roblox Huss Valley Script – Snowy Hub (Free)

PUBLISHEDUPDATED
What changed
  • 2026-11-13 — Added Script #21: Nice Scripttt & More.
  • 2026-11-05 — Added Script #20: + ESP (Runner & Catcher) & More.
  • 2026-11-03 — Added Script #19: Updated for BOSS Update.
  • 2026-10-24 — Added Script #18: Auto Revive — walks to downed teammates and revives them & More.
  • 2026-10-22 — Added Script #17: HUSS VALLEY & More.
  • 2026-10-22 — Added Script #16: Updated for undetected Update.
  • 2026-10-18 — Added Script #15: Updated for leaked open src Update.
  • 2026-10-17 — Added Script #14: Auto Run & More.
  • 2026-10-17 — Added Script #13: Working Script.
  • 2026-10-15 — Added Script #12: ESP & More.
  • 2026-10-14 — Added Script #11: Azure Hub.
  • 2026-10-13 — Added Script #10: 🐺 ▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬ 🐺 & More.
  • 2026-10-13 — Added Script #9: Escape & More.
  • 2026-10-13 — Added Script #8: Updated for OPEN SOURCE Update.
  • 2026-10-11 — Added Script #7: Auto Run & More.
1 Available ScriptFree

Looking for a Huss Valley script for Roblox? You found the right place. We’ve got a tested script that handles the hardest grinding so you can survive the chaos.

Huss Valley keeps things frantic with one clear rule: run. You spend matches sprinting across the map, dodging threats, and trying to grab every drop you see before it is too late. Running back and forth across dangerous zones over and over can get old pretty fast.

Using this script gives your hands a break. With Auto Farm and Auto Collect running in the background, you can scoop up resources and clear runs without breaking a sweat.

Huss Valley Script – Snowy Hub

Snowy HubFree
Auto FarmAuto Collect
loadstring(game:HttpGet("https://flowauth.net/v1/ui/a87f00d9adf63658655fcd02ab86a4ef.lua"))()
Executor compatibility changes over time. Check current reports before testing.

Script #2 Barrage

Script #2 · BarrageFree
Auto FarmESPSilent AimTeleportAuto Click
loadstring(game:HttpGet("https://barrage.cc/loader"))()
Executor compatibility changes over time. Check current reports before testing.

Script #3 Sottoro Hub

Script #3 · Sottoro HubFree
Auto FarmESPSilent AimAuto Click
loadstring(game:HttpGet("https://api.luarmor.net/files/v4/loaders/d792d2a2b58c6e3335851d13b4f4f3a3.lua"))()
Executor compatibility changes over time. Check current reports before testing.

Script #4 Auto Catch) & More

Script #4 · Auto Catch) & MoreFree
Auto Catch)
loadstring(game:HttpGet("https://aetherium.lol/api/free"))()
Executor compatibility changes over time. Check current reports before testing.

Script #5 Zero Hub

Script #5 · Zero HubFree
Instant CatchAuto PlayGod ModeAuto Collect GemsAuto DashAuto Chase
loadstring(game:HttpGet("https://raw.githubusercontent.com/gather1231-source/BEST/refs/heads/main/script"))()
Executor compatibility changes over time. Check current reports before testing.

Script #6 Working Script

Script #6 · Working ScriptFree
loadstring(game:HttpGet("https://raw.githubusercontent.com/BO3DYXAN777/Liquid_Hub/refs/heads/main/Liquid_Hub_HussValley.luau"))()
Executor compatibility changes over time. Check current reports before testing.

Script #7 Auto Run & More

Script #7 · Auto Run & MoreFree
Auto RunAuto Chase
loadstring(game:HttpGet("https://raw.githubusercontent.com/LSSOPS/OpenSource/refs/heads/main/HushHub_HussValley.lua"))()
Executor compatibility changes over time. Check current reports before testing.

Script #8 Auto Collect & More (OPEN SOURCE Update)

Script #8 · Auto Collect & MoreFree
Auto Collect
local Players = game:GetService("Players")
local RunService = game:GetService("RunService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local HttpService = game:GetService("HttpService")
local UserInputService = game:GetService("UserInputService")
local IS_MOBILE = UserInputService.TouchEnabled
local UTILITY_INTERVAL = IS_MOBILE and 0.5 or 0.25

-- Shared state for the loader (kept in one table to stay under Luau's 200-local limit)
local Hub = {
    genv = (getgenv and getgenv()) or _G,
    registry = {},
    cleaned = false,
}
-- Re-executing the script cleanly unloads the previous copy first
local previousUnload = Hub.genv.OziohubUnload or Hub.genv.HussValleyUnload
if previousUnload then
    pcall(previousUnload)
end

local LocalPlayer = Players.LocalPlayer
local COH = ReplicatedStorage:WaitForChild("ChickenOrHero")
local Movement = COH:WaitForChild("Movement")
local MovementProfiles = require(Movement:WaitForChild("MovementProfiles"))
local BoostInput = require(Movement:WaitForChild("BoostInput"))
local Game = COH:WaitForChild("Game")
local Session = Game:WaitForChild("Session")
local MapVoteState = Game:WaitForChild("MapVoteState")
local MapVoteEvent = Game:WaitForChild("MapVoteEvent")
local ContactCatchConfig = require(Game:WaitForChild("ContactCatchConfig"))
local TacklePrediction = require(Game:WaitForChild("TacklePrediction"))
local MeleeEvent = Game:WaitForChild("MeleeEvent")
local RescueConfig = require(Game:WaitForChild("RescueConfig"))
local RESCUE_RANGE = math.max(3, tonumber(RescueConfig.Range) or 6) - 0.25
local RESCUE_HOLD = math.max(0.1, tonumber(RescueConfig.HoldSeconds) or 1.2)
local RESCUE_FINISH_GRACE = math.max(0.1, tonumber(RescueConfig.FinishGrace) or 0.5)
local RescueEvent = Game:WaitForChild("RescueEvent")
local Gear = COH:WaitForChild("Gear")
local GearCatalog = require(Gear:WaitForChild("GearCatalog"))
local ArmoryEvent = COH:WaitForChild("Weapons"):WaitForChild("ArmoryEvent")
local SpinWheelEvent = COH:WaitForChild("SpinWheelEvent")
local JourneyConfig = require(COH:WaitForChild("Progression"):WaitForChild("JourneyConfig"))
local JourneyEvent = COH:WaitForChild("Progression"):WaitForChild("JourneyEvent")
local PlayerPreferences = COH:WaitForChild("Game"):WaitForChild("PlayerPreferences")
local Presentation = COH:WaitForChild("Presentation")
local HudNavigation = require(Presentation:WaitForChild("HudNavigation"))
local WindUI

local SETTINGS = {
    runnerEnabled = true,
    strategy = "Hero",
    customSpeed = false,
    speedMultiplier = 1.0,
    autoGems = true,
    gemScanInterval = 0.25,
    gemMaxDistance = 220,
    gemCollectDistance = 4.5,
    autoRevive = true,
    reviveBeforeGems = true,
    reviveMaxDistance = 220,
    avoidCatchers = true,
    predictionTime = 0.65,
    avoidStrength = 2.2,
    panicDistance = 15,
    safezoneDepthRatio = 0.52,
    safezoneValidationRatio = 0.44,
    safezoneEdgeMargin = 4.5,
    edgeRayHeight = 12,
    edgeRayDepth = 52,
    edgeLookAhead = 14,
    edgeSecondLookAhead = 28,
    autoDash = true,
    dashCooldown = 0.85,
    dashDistance = 48,
    dashClosingSpeed = 10,
    smoothMovement = true,
    turnRate = 9,
    emergencySafeZone = true,
    showThreats = true,
    showGoal = true,
    corridorEnabled = true,
    corridorMinWidth = 4.25,
    corridorCenterRange = 26,
    corridorLockTime = 1.65,
    corridorPassDistance = 20,
    corridorApproachDistance = 60,
    sideGapEnabled = true,
    sideGapAngles = {18, 30, 42, 54, 68, 82},
    sideGapMinClearance = 3.5,
    sideGapCommitTime = 0.8,
    sideGapForwardBias = 6.5,

    catcherChase = true,
    catcherCustomSpeed = false,
    catcherSpeedMultiplier = 1.0,
    catcherPrediction = 0.45,
    catcherSmoothing = 6,
    smartPriority = true,
    catcherAttackPriority = "Smart",
    autoTackle = true,
    tackleRange = 12,
    tackleCooldown = 1.2,
    autoMelee = true,
    meleeRange = 9,
    meleeCooldown = 0.35,
    smoothTurn = true,
    turnRateCatcher = 14,
    followTarget = true,

    showHitboxes = true,
    showGoalUtility = true,
    showThreatUtility = false,
    showDebugUI = false,
    cameraFollow = true,
    cameraResponse = 0.25,
    autoSpinWheel = false,
    wheelSpinInterval = 6,
    wheelMinimumCredits = 1,
    wheelAnnounce = true,
    autoClaimJourneyRewards = false,
    journeyClaimAnnounce = true,
    autoMapVote = false,
    mapVoteAnnounce = true,
    mapVoteSelections = {},
    disableBuiltinAFK = false,
}

local runtime = {
    profile = nil,
    profileRole = nil,
    runnerTick = 0,
    runnerPlanAt = -math.huge,
    runnerPlanDirection = Vector3.zero,
    runnerPlanGoal = Vector3.zero,
    catcherTick = 0,
    utilityTick = 0,
    lastMove = os.clock(),
    lastMovePosition = nil,
    moveCommandAt = -math.huge,
    stuck = false,
    path = Vector3.zero,
    goal = nil,
    goalMode = "SafeZone",
    goalSide = nil,
    assistMode = nil,
    assistTarget = nil,
    assistSince = -math.huge,
    gemTarget = nil,
    gemIgnored = {},
    gemScanAt = -math.huge,
    reviveTarget = nil,
    reviveStarted = false,
    reviveStartAt = 0,
    reviveInputToken = 0,
    catchers = {},
    catcherCacheAt = 0,
    threats = {},
    threatAt = 0,
    threatHistory = {},
    dashAt = -math.huge,
    dashStatus = "idle",
    dashLastRequestAt = -math.huge,
    dashLastCount = nil,
    ping = 0,
    pingAt = 0,
    armory = {loaded = false, abilities = {}},
    armoryAt = -math.huge,
    catcherTargets = {},
    catcherTargetAt = 0,
    catcherTarget = nil,
    edgeRisk = false,
    edgeDirection = Vector3.zero,
    catcherPath = Vector3.zero,
    catcherVelocity = {},
    meleeId = 0,
    lastMelee = -math.huge,
    lastTackle = -math.huge,
    mapCacheAt = -math.huge,
    mapCache = nil,
    edgeCheckAt = -math.huge,
    edgeCheckPosition = nil,
    edgeCheckDirection = Vector3.zero,
    edgeCheckGoal = Vector3.zero,
    edgeRecoveryAt = -math.huge,
    edgeRecoveryDirection = Vector3.zero,
    edgeRecoveryUntil = -math.huge,
    stuckRecoveryUntil = -math.huge,
    stuckRecoveryDirection = Vector3.zero,
    safeCheckAt = -math.huge,
    safeCheckPosition = nil,
    safeCheckA = false,
    safeCheckB = false,
    routeActive = false,
    routeComplete = false,
    routeStartSide = nil,
    routeTargetSide = nil,
    routeCompletePosition = nil,
    routeCompleteAt = -math.huge,
    corridorActive = false,
    corridorGoal = Vector3.zero,
    corridorCenter = Vector3.zero,
    corridorAxis = Vector3.zero,
    corridorGapWidth = 0,
    corridorStartedAt = -math.huge,
    sideGapDirection = Vector3.zero,
    sideGapUntil = -math.huge,
    sideGapReason = "",
    wheelScanAt = -math.huge,
    wheelActionAt = -math.huge,
    wheelStatus = "disabled",
    wheelLastButton = nil,
    wheelSpinCount = 0,
    wheelCredits = 0,
    wheelNextFreeAt = 0,
    wheelPurchasesAvailable = false,
    wheelDiscountAvailable = false,
    wheelStateRequestAt = -math.huge,
    wheelSpinRequestAt = -math.huge,
    wheelEventReady = false,
    wheelSpinning = false,
    wheelLastStateAt = -math.huge,
    wheelStatusAt = -math.huge,
    wheelNextAttemptAt = -math.huge,
    wheelMinimumCredits = 1,
    afkOverrideStatus = "disabled",
    afkOverrideLastRequestAt = -math.huge,
    afkOverrideRequestInterval = 2.0,
    afkOverrideInLobby = false,
    afkOverrideRequestCount = 0,
    journeyScanAt = -math.huge,
    journeyStatus = "disabled",
    journeyClaimCount = 0,
    journeyLastClaimAt = -math.huge,
    journeyClaimedButtons = {},
    journeyLoaded = false,
    journeySeasonId = nil,
    journeyRequestAt = -math.huge,
    journeyClaimInFlight = false,
    journeyLastStateAt = -math.huge,
    journeyTier = 1,
    journeyPremium = false,
    journeyClaims = {},
    journeyLastClaimResultAt = -math.huge,
    mapVoteScanAt = -math.huge,
    mapVoteStatus = "disabled",
    mapVoteOptions = {},
    mapVoteLastActionAt = -math.huge,
    mapVoteOpen = false,
    mapVotePhase = "Waiting",
    mapVoteToken = nil,
    mapVoteOptionIds = {},
    mapVoteLastStateAt = -math.huge,
    debugLastError = nil,
    debugLastErrorAt = -math.huge,
    debugEnabled = false,
    debugGui = nil,
    debugLabel = nil,
    debugPanelAt = -math.huge,
    journeyNextClaimAt = -math.huge,
    journeyManualPending = false,
}

local safezone = {
    map = nil,
    a = nil,
    b = nil,
    cached = false,
}

local visuals = {
    goal = nil,
    threats = {},
    hitboxes = {},
}

local MAP_VOTE_SLOT_IDS = {
    "Map 1",
    "Map 2",
    "Map 3",
}

local MapVoteDropdown

local function flat(v)
    return Vector3.new(v.X, 0, v.Z)
end

local function getCharacter(player)
    return (player or LocalPlayer).Character
end

local function getHumanoid(player)
    local c = getCharacter(player)
    return c and c:FindFirstChildOfClass("Humanoid") or nil
end

local function getRoot(player)
    local c = getCharacter(player)
    return c and c:FindFirstChild("HumanoidRootPart") or nil
end

local function getRole()
    return LocalPlayer:GetAttribute("GameRole") or "Lobby"
end

local function getRunState()
    return LocalPlayer:GetAttribute("RunState") or "Idle"
end

local function isRunnerActive()
    if LocalPlayer:GetAttribute("InMatch") ~= true then
        return false
    end
    local role = getRole()
    if role ~= "Runner" then
        return false
    end
    return getRunState() == "Active"
end

local function isCatcherActive()
    if LocalPlayer:GetAttribute("InMatch") ~= true then
        return false
    end
    if getRole() ~= "Catcher" then
        return false
    end
    return getRunState() == "Active"
end

local function canMove()
    if LocalPlayer:GetAttribute("ClientReady") ~= true then
        return false
    end
    if Session:GetAttribute("GlobalPaused") == true then
        return false
    end
    if Session:GetAttribute("MapChanging") == true then
        return false
    end
    local c = getCharacter()
    if not c then
        return false
    end
    if c:GetAttribute("Ragdolled") == true then
        return false
    end
    if c:GetAttribute("GearMotion") == true then
        return false
    end
    if c:GetAttribute("MovementLocked") == true then
        return false
    end
    local h = getHumanoid()
    if not h or h.Health <= 0 then
        return false
    end
    if h.PlatformStand or h.Sit then
        return false
    end
    return true
end

local function getBaseSpeed(role)
    role = role or getRole()
    if runtime.profile and runtime.profileRole == role then
        return runtime.profile.MaxSpeed or 16
    end
    local ok, profile = pcall(MovementProfiles.get, role, LocalPlayer)
    if ok and profile then
        runtime.profile = profile
        runtime.profileRole = role
        return profile.MaxSpeed or 16
    end
    return 16
end

local function getRunnerSpeed()
    local speed = math.max(getBaseSpeed("Runner"), 1)
    if SETTINGS.customSpeed then
        speed *= math.clamp(SETTINGS.speedMultiplier, 1, 2)
    end
    return speed
end

local function getCatcherSpeed()
    local speed = math.max(getBaseSpeed("Catcher"), 1)
    if SETTINGS.catcherCustomSpeed then
        speed *= math.clamp(SETTINGS.catcherSpeedMultiplier, 1, 2)
    end
    return speed
end

local function restoreNativeWalkSpeed()
    local hum = getHumanoid()
    local character = getCharacter()
    if not hum or not character then
        return
    end
    local native = tonumber(character:GetAttribute("MovementSpeed"))
    if native and native > 0 then
        hum.WalkSpeed = native
    end
end

local function refreshPing(now)
    if now - runtime.pingAt < 0.5 then
        return
    end
    runtime.pingAt = now
    local value = 0
    pcall(function()
        value = LocalPlayer:GetNetworkPing() * 0.5
    end)
    runtime.ping = math.max(value, 0)
end

local function getMap()
    local now = os.clock()
    if now - runtime.mapCacheAt < 0.35 then
        return runtime.mapCache
    end
    runtime.mapCacheAt = now
    local handle = Game:FindFirstChild("ActiveMap")
    if handle and handle:IsA("ObjectValue") and handle.Value and handle.Value:IsDescendantOf(workspace) then
        runtime.mapCache = handle.Value
        return runtime.mapCache
    end
    local found = nil
    for _, obj in ipairs(workspace:GetChildren()) do
        if obj:FindFirstChild("Field") then
            found = obj
            break
        end
    end
    runtime.mapCache = found
    return found
end

local edgeRayCache = {
    map = nil,
    field = nil,
    invisWall = nil,
    params = nil,
    wallParams = nil,
}

local function resolveActiveField(map)
    if not map then
        return nil
    end
    local field = map:FindFirstChild("Field")
    if field then
        return field
    end
    return map:FindFirstChild("Field", true)
end

local function resolveActiveInvisWall(field)
    if not field then
        return nil
    end
    return field:FindFirstChild("InvisWall", true)
end

local function refreshEdgeRayCache()
    local map = getMap()
    local field = resolveActiveField(map)
    local wall = resolveActiveInvisWall(field)
    local include = field or map

    if edgeRayCache.map == map
        and edgeRayCache.field == field
        and edgeRayCache.invisWall == wall
        and edgeRayCache.params then
        return
    end

    local params = RaycastParams.new()
    params.FilterType = Enum.RaycastFilterType.Include
    params.FilterDescendantsInstances = include and {include} or {}
    params.IgnoreWater = true

    edgeRayCache.map = map
    edgeRayCache.field = field
    edgeRayCache.invisWall = wall
    edgeRayCache.params = params
    edgeRayCache.wallParams = nil
end

local function getEdgeRayParams()
    refreshEdgeRayCache()
    return edgeRayCache.params
end

local function getInvisWallParams()
    refreshEdgeRayCache()
    local wall = edgeRayCache.invisWall
    if not wall or not wall:IsDescendantOf(workspace) then
        edgeRayCache.invisWall = nil
        edgeRayCache.wallParams = nil
        return nil
    end
    if edgeRayCache.wallParams then
        return edgeRayCache.wallParams
    end
    local wallParams = RaycastParams.new()
    wallParams.FilterType = Enum.RaycastFilterType.Include
    wallParams.FilterDescendantsInstances = {wall}
    wallParams.IgnoreWater = true
    edgeRayCache.wallParams = wallParams
    return wallParams
end

local function invisWallHit(position, direction, distance)
    local dir = flat(direction)
    if dir.Magnitude < 0.05 then
        return nil
    end
    local params = getInvisWallParams()
    if not params then
        return nil
    end
    dir = dir.Unit
    local origin = Vector3.new(position.X, position.Y + 2.5, position.Z)
    return workspace:Raycast(origin, dir * distance, params)
end

local function floorRay(point, y)
    local map = getMap()
    if not map then
        return true
    end
    local params = getEdgeRayParams()
    if not params or #params.FilterDescendantsInstances == 0 then
        return false
    end
    local origin = Vector3.new(point.X, math.max(y + 12, point.Y + 10), point.Z)
    local direction = Vector3.new(0, -(SETTINGS.edgeRayHeight + SETTINGS.edgeRayDepth), 0)
    local hit = workspace:Raycast(origin, direction, params)
    return hit ~= nil and hit.Normal.Y >= 0.35
end

local function hasFloorAt(point, y)
    return floorRay(point, y)
end

local function getPlayfieldCenter()
    if safezone.a and safezone.b then
        return (safezone.a.center + safezone.b.center) * 0.5
    end
    if safezone.a then
        return safezone.a.center
    end
    if safezone.b then
        return safezone.b.center
    end
    return nil
end

local function groundSupportScore(position, direction, y)
    local dir = flat(direction)
    if dir.Magnitude < 0.05 then
        return 0
    end
    dir = dir.Unit
    local side = Vector3.new(-dir.Z, 0, dir.X)
    local score = 0
    if hasFloorAt(position + dir * 6, y) then score += 2 end
    if hasFloorAt(position + dir * 14, y) then score += 2 end
    if hasFloorAt(position + dir * 24, y) then score += 1 end
    if hasFloorAt(position + dir * 14 + side * 3, y) then score += 1 end
    if hasFloorAt(position + dir * 14 - side * 3, y) then score += 1 end
    return score
end

local function boundaryInwardDirection(position, y)
    local dirs = {
        Vector3.new(1, 0, 0),
        Vector3.new(-1, 0, 0),
        Vector3.new(0, 0, 1),
        Vector3.new(0, 0, -1),
    }
    local outward = Vector3.zero
    local missing = 0
    for _, dir in ipairs(dirs) do
        local wallHit = invisWallHit(position, dir, 9)
        if wallHit or not hasFloorAt(position + dir * 7, y) then
            outward += dir
            missing += 1
        end
    end
    if missing == 0 or outward.Magnitude < 0.05 then
        return Vector3.zero
    end
    local inward = flat(-outward)
    if inward.Magnitude < 0.05 then
        return Vector3.zero
    end
    inward = inward.Unit
    if groundSupportScore(position, inward, y) < 3 then
        return Vector3.zero
    end
    return inward
end

local function edgeDirectionClear(position, direction, y, distance)
    local dir = flat(direction)
    if dir.Magnitude < 0.05 then
        return false
    end
    dir = dir.Unit
    if invisWallHit(position, dir, math.max(8, distance)) then
        return false
    end
    local score = groundSupportScore(position, dir, y)
    if distance <= 14 then
        return score >= 4
    end
    return score >= 5
end

local function edgeRiskForDirection(position, direction, y)
    local dir = flat(direction)
    if dir.Magnitude < 0.05 then
        return true
    end
    dir = dir.Unit
    return not edgeDirectionClear(position, dir, y, SETTINGS.edgeLookAhead)
        or not edgeDirectionClear(position, dir, y, SETTINGS.edgeSecondLookAhead)
end

local function rotateEdge(dir, angle)
    local r = math.rad(angle)
    local c = math.cos(r)
    local s = math.sin(r)
    return Vector3.new(dir.X * c - dir.Z * s, 0, dir.X * s + dir.Z * c)
end

local function chooseEdgeDirection(position, desired, goal, y)
    local dir = flat(desired)
    if dir.Magnitude < 0.05 then
        return Vector3.zero, false
    end
    dir = dir.Unit

    local now = os.clock()
    if runtime.edgeCheckPosition and runtime.edgeCheckDirection.Magnitude > 0.05
        and now - runtime.edgeCheckAt < 0.055
        and flat(position - runtime.edgeCheckPosition).Magnitude < 2.5
        and runtime.edgeCheckDirection:Dot(dir) > 0.96
        and runtime.edgeCheckGoal.Magnitude > 0.05
        and flat(goal - runtime.edgeCheckGoal).Magnitude < 8 then
        return runtime.edgeDirection, runtime.edgeRisk
    end

    local boundary = boundaryInwardDirection(position, y)
    local desiredRisk = edgeRiskForDirection(position, dir, y)
    local nearBoundary = boundary.Magnitude > 0.05 and boundary:Dot(dir) < 0.35

    runtime.edgeCheckAt = now
    runtime.edgeCheckPosition = position
    runtime.edgeCheckDirection = dir
    runtime.edgeCheckGoal = flat(goal)

    if not desiredRisk and not nearBoundary then
        runtime.edgeDirection = dir
        runtime.edgeRisk = false
        return dir, false
    end

    local toGoal = flat(goal - position)
    if toGoal.Magnitude < 0.05 then
        toGoal = dir
    else
        toGoal = toGoal.Unit
    end

    local inward = boundary
    if inward.Magnitude < 0.05 then
        local center = getPlayfieldCenter()
        if center then
            inward = flat(center - position)
            if inward.Magnitude > 0.05 then
                inward = inward.Unit
            end
        end
    end

    local candidates = {}
    local function addCandidate(v)
        v = flat(v)
        if v.Magnitude < 0.05 then
            return
        end
        v = v.Unit
        for _, item in ipairs(candidates) do
            if item:Dot(v) > 0.985 then
                return
            end
        end
        candidates[#candidates + 1] = v
    end

    addCandidate(inward)
    addCandidate(toGoal)
    addCandidate(dir)
    local base = inward.Magnitude > 0.05 and inward or dir
    for _, angle in ipairs({-35, 35, -70, 70, 90, -90, 135, -135, 180}) do
        addCandidate(rotateEdge(base, angle))
    end

    local best = nil
    local bestScore = -math.huge
    for _, candidate in ipairs(candidates) do
        local support = groundSupportScore(position, candidate, y)
        if support >= 6 then
            local score = support * 4.5 + candidate:Dot(toGoal) * 5
            if inward.Magnitude > 0.05 then
                score += candidate:Dot(inward) * (nearBoundary and 10 or 5)
            end
            if candidate:Dot(dir) > 0 then
                score += 2
            end
            if score > bestScore then
                bestScore = score
                best = candidate
            end
        end
    end

    if best then
        runtime.edgeDirection = best
        runtime.edgeRisk = true
        runtime.edgeRecoveryAt = now
        return best, true
    end

    if inward.Magnitude > 0.05 then
        runtime.edgeDirection = inward
        runtime.edgeRisk = true
        runtime.edgeRecoveryAt = now
        return inward, true
    end

    runtime.edgeDirection = -dir
    runtime.edgeRisk = true
    runtime.edgeRecoveryAt = now
    return -dir, true
end

local function findZone(parent, names)
    for _, name in ipairs(names) do
        local direct = parent:FindFirstChild(name)
        if direct then
            return direct
        end
    end
    for _, obj in ipairs(parent:GetDescendants()) do
        local lower = obj.Name:lower()
        for _, name in ipairs(names) do
            if lower == name:lower() then
                return obj
            end
        end
    end
    return nil
end

local function getBounds(instance)
    if not instance then
        return nil
    end
    local minP = Vector3.new(math.huge, math.huge, math.huge)
    local maxP = Vector3.new(-math.huge, -math.huge, -math.huge)
    local found = false
    local function add(part)
        local p = part.Position
        local h = part.Size * 0.5
        minP = Vector3.new(
            math.min(minP.X, p.X - h.X),
            math.min(minP.Y, p.Y - h.Y),
            math.min(minP.Z, p.Z - h.Z)
        )
        maxP = Vector3.new(
            math.max(maxP.X, p.X + h.X),
            math.max(maxP.Y, p.Y + h.Y),
            math.max(maxP.Z, p.Z + h.Z)
        )
        found = true
    end
    if instance:IsA("BasePart") then
        add(instance)
    end
    for _, obj in ipairs(instance:GetDescendants()) do
        if obj:IsA("BasePart") then
            add(obj)
        end
    end
    if not found then
        return nil
    end
    return minP, maxP
end

local function buildZone(instance)
    local minP, maxP = getBounds(instance)
    if not minP then
        return nil
    end
    return {
        instance = instance,
        name = instance.Name,
        min = minP,
        max = maxP,
        center = (minP + maxP) * 0.5,
    }
end

local function refreshSafezones()
    local map = getMap()
    if safezone.cached and safezone.map == map
        and safezone.a and safezone.b
        and safezone.a.instance and safezone.a.instance.Parent
        and safezone.b.instance and safezone.b.instance.Parent then
        return
    end
    safezone.map = map
    safezone.a = nil
    safezone.b = nil
    safezone.cached = true
    local field = map and map:FindFirstChild("Field")
    if not field then
        return
    end
    local a = findZone(field, {"SafezoneASide", "SafeZoneASide"})
    local b = findZone(field, {"SafezoneBSide", "SafeZoneBSide"})
    safezone.a = buildZone(a)
    safezone.b = buildZone(b)
end

local function inZone(position, zone)
    if not zone then
        return false
    end
    return position.X >= zone.min.X
        and position.X <= zone.max.X
        and position.Z >= zone.min.Z
        and position.Z <= zone.max.Z
        and position.Y >= zone.min.Y - 8
        and position.Y <= zone.max.Y + 8
end

local function currentZone(position)
    if inZone(position, safezone.a) then
        return safezone.a
    end
    if inZone(position, safezone.b) then
        return safezone.b
    end
    return nil
end

local function zoneInwardDirection(zone, other)
    if not zone then
        return Vector3.zero
    end
    local delta = other and flat(zone.center - other.center) or Vector3.zero
    if delta.Magnitude > 0.05 then
        if math.abs(delta.X) >= math.abs(delta.Z) then
            return Vector3.new(delta.X >= 0 and 1 or -1, 0, 0)
        end
        return Vector3.new(0, 0, delta.Z >= 0 and 1 or -1)
    end
    if zone.instance and zone.instance:IsA("BasePart") then
        local look = flat(zone.instance.CFrame.LookVector)
        if look.Magnitude > 0.05 then
            if math.abs(look.X) >= math.abs(look.Z) then
                return Vector3.new(look.X >= 0 and 1 or -1, 0, 0)
            end
            return Vector3.new(0, 0, look.Z >= 0 and 1 or -1)
        end
    end
    return Vector3.zero
end

local function zoneAxisHalfExtent(zone, inward)
    if not zone then
        return 0
    end
    local size = zone.max - zone.min
    if math.abs(inward.X) >= math.abs(inward.Z) then
        return math.abs(size.X) * 0.5
    end
    return math.abs(size.Z) * 0.5
end

local function zoneDeepPoint(zone, other, y)
    if not zone then
        return nil
    end
    local inward = zoneInwardDirection(zone, other)
    local half = zoneAxisHalfExtent(zone, inward)
    local edgeMargin = math.min(SETTINGS.safezoneEdgeMargin, math.max(0, half - 0.75))
    local depth = math.min(math.max(0, half - edgeMargin), half * SETTINGS.safezoneDepthRatio)
    local xMargin = math.min(edgeMargin, math.max(0, (zone.max.X - zone.min.X) * 0.5 - 0.75))
    local zMargin = math.min(edgeMargin, math.max(0, (zone.max.Z - zone.min.Z) * 0.5 - 0.75))
    local ratios = {SETTINGS.safezoneDepthRatio, 0.46, 0.40, 0.34}
    for _, ratio in ipairs(ratios) do
        local candidateDepth = math.min(math.max(0, half - edgeMargin), half * ratio)
        local point = zone.center + inward * candidateDepth
        point = Vector3.new(
            math.clamp(point.X, zone.min.X + xMargin, zone.max.X - xMargin),
            y,
            math.clamp(point.Z, zone.min.Z + zMargin, zone.max.Z - zMargin)
        )
        if edgeDirectionClear(point, inward, y, 6) and edgeDirectionClear(point, -inward, y, 4) then
            return point
        end
    end
    local point = zone.center + inward * depth
    return Vector3.new(
        math.clamp(point.X, zone.min.X + xMargin, zone.max.X - xMargin),
        y,
        math.clamp(point.Z, zone.min.Z + zMargin, zone.max.Z - zMargin)
    )
end

local function inValidatedZone(position, zone, other)
    if not zone or not inZone(position, zone) then
        return false
    end
    local inward = zoneInwardDirection(zone, other)
    if inward.Magnitude < 0.05 then
        return false
    end
    local half = zoneAxisHalfExtent(zone, inward)
    local margin = math.min(SETTINGS.safezoneEdgeMargin, math.max(0, half - 0.75))
    local xOk = position.X >= zone.min.X + margin and position.X <= zone.max.X - margin
    local zOk = position.Z >= zone.min.Z + margin and position.Z <= zone.max.Z - margin
    if not xOk or not zOk then
        return false
    end
    local depth = flat(position - zone.center):Dot(inward)
    local required = math.min(math.max(0, half - margin), half * SETTINGS.safezoneValidationRatio)
    return depth >= required and hasFloorAt(position, position.Y)
end

local function zoneCenter(zone, y)
    if not zone then
        return nil
    end
    return Vector3.new(zone.center.X, y, zone.center.Z)
end

local function detectRoundStartZone(position, a, b)
    local inA = inZone(position, a)
    local inB = inZone(position, b)
    if inA and not inB then
        return a
    end
    if inB and not inA then
        return b
    end
    local da = flat(position - a.center).Magnitude
    local db = flat(position - b.center).Magnitude
    return da <= db and a or b
end

local function beginRunnerRound(position)
    refreshSafezones()
    local a = safezone.a
    local b = safezone.b
    if not a or not b then
        runtime.routeActive = false
        runtime.routeComplete = false
        runtime.routeStartSide = nil
        runtime.routeTargetSide = nil
        runtime.routeCompletePosition = nil
        runtime.routeCompleteAt = -math.huge
        runtime.goalSide = nil
        runtime.goal = nil
        return nil, nil
    end

    local start = detectRoundStartZone(position, a, b)
    local target = start == a and b or a

    runtime.routeActive = true
    runtime.routeComplete = false
    runtime.routeStartSide = start.name
    runtime.routeTargetSide = target.name
    runtime.routeCompletePosition = nil
    runtime.routeCompleteAt = -math.huge
    runtime.goalSide = target.name
    runtime.goal = zoneDeepPoint(target, start, position.Y) or zoneCenter(target, position.Y)
    runtime.safeCheckAt = -math.huge
    runtime.safeCheckPosition = nil
    return runtime.goal, target
end

local function chooseSafeGoal(position)
    refreshSafezones()
    local a = safezone.a
    local b = safezone.b
    if not a or not b then
        runtime.goal = nil
        runtime.goalSide = nil
        runtime.routeActive = false
        runtime.routeComplete = false
        runtime.routeStartSide = nil
        runtime.routeTargetSide = nil
        runtime.routeCompletePosition = nil
        runtime.routeCompleteAt = -math.huge
        return nil, nil
    end

    if not runtime.routeActive or not runtime.routeTargetSide then
        return beginRunnerRound(position)
    end

    if runtime.routeComplete then
        return nil, nil
    end

    local now = os.clock()
    if not runtime.safeCheckPosition
        or now - runtime.safeCheckAt >= 0.08
        or flat(position - runtime.safeCheckPosition).Magnitude >= 2.0 then
        runtime.safeCheckAt = now
        runtime.safeCheckPosition = position
        runtime.safeCheckA = inValidatedZone(position, a, b)
        runtime.safeCheckB = inValidatedZone(position, b, a)
    end

    local target = runtime.routeTargetSide == a.name and a or b
    local other = target == a and b or a

    if (target == a and runtime.safeCheckA) or (target == b and runtime.safeCheckB) then
        runtime.routeComplete = true
        runtime.routeCompletePosition = position
        runtime.routeCompleteAt = now
        runtime.goal = nil
        runtime.goalSide = target.name
        return nil, target
    end

    runtime.goalSide = target.name
    if not runtime.goal then
        runtime.goal = zoneDeepPoint(target, other, position.Y) or zoneCenter(target, position.Y)
    else
        runtime.goal = Vector3.new(runtime.goal.X, position.Y, runtime.goal.Z)
    end

    return runtime.goal, target
end

local function getSafeFallback(position)
    refreshSafezones()
    local a = safezone.a
    local b = safezone.b
    if not a or not b then
        return nil
    end
    local target
    if runtime.routeTargetSide == a.name then
        target = a
    elseif runtime.routeTargetSide == b.name then
        target = b
    elseif runtime.goalSide == a.name then
        target = a
    elseif runtime.goalSide == b.name then
        target = b
    elseif inZone(position, a) and not inZone(position, b) then
        target = b
    elseif inZone(position, b) and not inZone(position, a) then
        target = a
    else
        target = b
    end
    return zoneDeepPoint(target, target == a and b or a, position.Y) or zoneCenter(target, position.Y)
end

local function isGemObject(obj)
    local name = obj.Name:lower()
    return obj:IsA("BasePart") and (
        name:sub(1, 4) == "gem_"
        or name == "gem"
        or name == "gems"
        or name:find("gempickup", 1, true) ~= nil
    )
end

local function refreshGems(now, position)
    if now - runtime.gemScanAt < SETTINGS.gemScanInterval then
        return
    end
    runtime.gemScanAt = now
    local folder = workspace:FindFirstChild("LocalRunnerGems")
    local best, bestDistance
    if folder then
        for _, obj in ipairs(folder:GetChildren()) do
            if isGemObject(obj) and obj.Parent then
                local d = flat(obj.Position - position).Magnitude
                local ignored = runtime.gemIgnored[obj]
                if d <= SETTINGS.gemMaxDistance and (not ignored or now >= ignored) then
                    if not bestDistance or d < bestDistance then
                        best = obj
                        bestDistance = d
                    end
                end
            end
        end
    end
    if not best then
        local generic = workspace:FindFirstChild("Gems") or workspace:FindFirstChild("Gem")
        if generic then
            for _, obj in ipairs(generic:GetDescendants()) do
                if isGemObject(obj) and obj.Parent then
                    local d = flat(obj.Position - position).Magnitude
                    local ignored = runtime.gemIgnored[obj]
                    if d <= SETTINGS.gemMaxDistance and (not ignored or now >= ignored) then
                        if not bestDistance or d < bestDistance then
                            best = obj
                            bestDistance = d
                        end
                    end
                end
            end
        end
    end
    runtime.gemTarget = best
end

local function findDownedPlayer(position)
    local best, bestDistance
    for _, player in ipairs(Players:GetPlayers()) do
        if player ~= LocalPlayer and player.Parent then
            local c = player.Character
            local root = c and c:FindFirstChild("HumanoidRootPart")
            if root and c:GetAttribute("RescueAvailable") == true and c:GetAttribute("Ragdolled") == true then
                local helper = c:GetAttribute("RescueHelperId")
                if helper == nil or helper == LocalPlayer.UserId then
                    local d = flat(root.Position - position).Magnitude
                    if d <= SETTINGS.reviveMaxDistance and (not bestDistance or d < bestDistance) then
                        best = player
                        bestDistance = d
                    end
                end
            end
        end
    end
    return best
end

local function cancelRevive()
    if runtime.reviveTarget and runtime.reviveStarted then
        pcall(function()
            RescueEvent:FireServer("Cancel", runtime.reviveTarget.UserId)
        end)
    end
    runtime.reviveTarget = nil
    runtime.reviveStarted = false
    runtime.reviveStartAt = 0
end

local function hasReviveLineOfSight(target)
    local myRoot = getRoot()
    local targetRoot = target and getRoot(target)
    if not myRoot or not targetRoot then
        return false
    end
    local params = RaycastParams.new()
    params.FilterType = Enum.RaycastFilterType.Exclude
    params.FilterDescendantsInstances = {myRoot.Parent, targetRoot.Parent}
    params.RespectCanCollide = true
    local ok, result = pcall(function()
        return workspace:Raycast(myRoot.Position, targetRoot.Position - myRoot.Position, params)
    end)
    return ok and result == nil
end

local function updateRevive(now, position)
    if not SETTINGS.autoRevive then
        cancelRevive()
        return nil
    end
    local target = runtime.reviveTarget
    local root = target and getRoot(target)
    if not target or not target.Parent or not root or target.Character:GetAttribute("RescueAvailable") ~= true or target.Character:GetAttribute("Ragdolled") ~= true then
        cancelRevive()
        target = nil
    end
    if not target then
        target = findDownedPlayer(position)
        if not target then
            return nil
        end
        runtime.reviveTarget = target
    end
    root = getRoot(target)
    if not root then
        cancelRevive()
        return nil
    end
    runtime.goalMode = "Revive"
    local distance = flat(root.Position - position).Magnitude
    if distance > math.max(RESCUE_RANGE, SETTINGS.reviveMaxDistance) then
        cancelRevive()
        return nil
    end
    if distance <= RESCUE_RANGE then
        if not runtime.reviveStarted and now < runtime.reviveStartAt then
            return root.Position
        end
        if hasReviveLineOfSight(target) then
            if not runtime.reviveStarted then
                runtime.reviveStarted = true
                runtime.reviveStartAt = now
                pcall(function()
                    RescueEvent:FireServer("Begin", target.UserId)
                end)
            elseif now - runtime.reviveStartAt >= RESCUE_HOLD then
                pcall(function()
                    RescueEvent:FireServer("Finish", target.UserId)
                end)
                runtime.reviveStarted = false
                runtime.reviveStartAt = now + RESCUE_FINISH_GRACE + 0.5
            end
        end
    else
        if runtime.reviveStarted then
            cancelRevive()
        end
    end
    return root.Position
end

local function refreshCatchers(now)
    if now - runtime.catcherCacheAt < 0.12 then
        return
    end
    runtime.catcherCacheAt = now
    local list = runtime.catchers
    table.clear(list)
    for _, player in ipairs(Players:GetPlayers()) do
        if player ~= LocalPlayer and player.Parent and player:GetAttribute("GameRole") == "Catcher" and player:GetAttribute("RunState") == "Active" then
            local c = player.Character
            local h = c and c:FindFirstChildOfClass("Humanoid")
            local r = c and c:FindFirstChild("HumanoidRootPart")
            if h and h.Health > 0 and r and c:GetAttribute("Ragdolled") ~= true and c:GetAttribute("MovementLocked") ~= true then
                list[#list + 1] = player
            end
        end
    end
end

local function updateThreats(now, position)
    if now - runtime.threatAt < 0.045 then
        return runtime.threats
    end
    runtime.threatAt = now
    table.clear(runtime.threats)
    local runRoot = getRoot()
    local runVelocity = runRoot and flat(runRoot.AssemblyLinearVelocity) or Vector3.zero
    local runSpeed = math.max(getRunnerSpeed(), 1)
    if runVelocity.Magnitude < 3 and runtime.path.Magnitude > 0.05 then
        runVelocity = runtime.path.Unit * runSpeed
    end

    local nowServer = 0
    pcall(function()
        nowServer = workspace:GetServerTimeNow()
    end)

    for _, player in ipairs(runtime.catchers) do
        local root = getRoot(player)
        if root then
            local current = flat(root.Position)
            local offset = current - position
            local distance = offset.Magnitude
            if distance <= 105 then
                local velocity = flat(root.AssemblyLinearVelocity)
                local history = runtime.threatHistory[player]
                if not history then
                    history = {position = current, velocity = velocity, time = now}
                    runtime.threatHistory[player] = history
                end
                local historyDt = now - history.time
                local acceleration = Vector3.zero
                if historyDt > 0.025 and historyDt < 0.25 then
                    acceleration = (velocity - history.velocity) / historyDt
                    if acceleration.Magnitude > 70 then
                        acceleration = acceleration.Unit * 70
                    end
                end
                history.position = current
                history.velocity = velocity
                history.time = now

                local relative = current - position
                local relativeVelocity = velocity - runVelocity
                local relSpeedSq = relativeVelocity:Dot(relativeVelocity)
                local closestTime = 0
                if relSpeedSq > 0.25 then
                    closestTime = math.clamp(-relative:Dot(relativeVelocity) / relSpeedSq, 0, 1.8)
                end

                local prediction = math.clamp(SETTINGS.predictionTime + runtime.ping * 0.85, 0.28, 1.15)
                local velocityFactor = math.clamp(velocity.Magnitude / math.max(runSpeed, 1), 0.65, 1.25)
                prediction = math.clamp(prediction * velocityFactor, 0.28, 1.15)
                local character = player.Character
                local tackle = character and character:GetAttribute("TackleActive") == true
                local tackleDirection = character and character:GetAttribute("TackleDirection")
                if typeof(tackleDirection) ~= "Vector3" then
                    tackleDirection = Vector3.zero
                end
                tackleDirection = flat(tackleDirection)
                if tackleDirection.Magnitude < 0.05 then
                    tackleDirection = velocity
                end
                if tackleDirection.Magnitude < 0.05 then
                    tackleDirection = flat(root.CFrame.LookVector)
                end
                if tackleDirection.Magnitude > 0.05 then
                    tackleDirection = tackleDirection.Unit
                end

                if tackle then
                    prediction = math.min(1.8, prediction + 0.32)
                end

                local relativeFuture = relative + relativeVelocity * prediction + acceleration * (0.5 * prediction * prediction)
                local futureDistance = relativeFuture.Magnitude

                local danger = math.max(8, tonumber(ContactCatchConfig.MinForward) or 0)
                    + math.max(0, tonumber(ContactCatchConfig.HandRadius) or 0)
                    + math.max(0, tonumber(ContactCatchConfig.ContactPadding) or 0)
                    + math.max(0, tonumber(ContactCatchConfig.RunnerRadius) or 0)
                if tackle then
                    local reach = tonumber(character:GetAttribute("TackleReach")) or 0
                    danger += 8 + math.min(reach, 8)
                elseif velocity.Magnitude > runSpeed * 0.8 then
                    danger += 2
                end

                local closing = 0
                if distance > 0.05 then
                    closing = math.max(0, velocity:Dot(-offset.Unit))
                end
                local timeToDanger = math.huge
                if closing > 0.5 then
                    timeToDanger = math.max(0, (distance - danger) / closing)
                elseif distance <= danger then
                    timeToDanger = 0
                end

                local interceptTime = math.min(closestTime, prediction)
                if timeToDanger < interceptTime then
                    interceptTime = timeToDanger
                end

                local interceptCatcher = current + velocity * interceptTime + acceleration * (0.5 * interceptTime * interceptTime)
                local interceptRunner = position + runVelocity * interceptTime
                local interceptGap = flat(interceptCatcher - interceptRunner).Magnitude
                local predicted = current + velocity * prediction + acceleration * (0.5 * prediction * prediction)

                if tackle and tackleDirection.Magnitude > 0.05 then
                    local duration = tonumber(character:GetAttribute("TackleDuration")) or 0.45
                    local started = tonumber(character:GetAttribute("TackleStartedAt")) or 0
                    local elapsed = nowServer > 0 and math.max(0, nowServer - started) or 0
                    local activeTime = math.clamp(duration - elapsed, 0, prediction)
                    local dashSpeed = math.max(velocity.Magnitude, runSpeed * 2.2)
                    local tackleTravel = math.min(dashSpeed * activeTime, danger + 18)
                    predicted = current + tackleDirection * tackleTravel
                    local tackleTime = math.min(interceptTime, activeTime)
                    interceptCatcher = current + tackleDirection * math.min(dashSpeed * tackleTime, danger + 18)
                    interceptGap = flat(interceptCatcher - interceptRunner).Magnitude
                end

                local collisionRisk = timeToDanger <= math.min(prediction + 0.04, 0.72)
                    or interceptGap <= danger * 1.35
                    or (tackle and interceptGap <= danger * 2.15)
                local preTackle = closing >= math.max(6.5, runSpeed * 0.34) and distance <= 50
                runtime.threats[#runtime.threats + 1] = {
                    player = player,
                    root = root,
                    position = current,
                    velocity = velocity,
                    acceleration = acceleration,
                    distance = distance,
                    closing = closing,
                    predicted = predicted,
                    intercept = interceptCatcher,
                    interceptRunner = interceptRunner,
                    interceptTime = math.max(0, interceptTime),
                    interceptGap = interceptGap,
                    danger = danger,
                    tackle = tackle,
                    collisionRisk = collisionRisk,
                    preTackle = preTackle,
                    timeToDanger = timeToDanger,
                }
            end
        end
    end

    table.sort(runtime.threats, function(a, b)
        if a.collisionRisk ~= b.collisionRisk then
            return a.collisionRisk
        end
        if a.timeToDanger ~= b.timeToDanger then
            return a.timeToDanger < b.timeToDanger
        end
        if a.tackle ~= b.tackle then
            return a.tackle
        end
        if a.interceptGap ~= b.interceptGap then
            return a.interceptGap < b.interceptGap
        end
        return a.distance < b.distance
    end)

    for player, history in pairs(runtime.threatHistory) do
        if not player.Parent or now - history.time > 1.2 then
            runtime.threatHistory[player] = nil
        end
    end
    return runtime.threats
end

local function rotate(dir, angle)
    local r = math.rad(angle)
    local c = math.cos(r)
    local s = math.sin(r)
    return Vector3.new(dir.X * c - dir.Z * s, 0, dir.X * s + dir.Z * c)
end

local function routeClear(position, direction, threats)
    if direction.Magnitude < 0.05 then
        return -math.huge
    end
    local dir = direction.Unit
    local speed = math.max(getRunnerSpeed(), 1)
    local clearance = math.huge
    local samples = {0.10, 0.22, 0.36, 0.52, 0.70, 0.90}
    for _, t in ipairs(samples) do
        local runner = position + dir * speed * t
        for _, threat in ipairs(threats) do
            local catchPos
            if threat.tackle and flat(threat.intercept - threat.position).Magnitude > 0.05 then
                local tackleDir = flat(threat.intercept - threat.position).Unit
                local tackleTime = math.min(t, math.max(threat.interceptTime, 0.12))
                local tackleSpeed = math.max(threat.velocity.Magnitude, speed * 2.2)
                catchPos = threat.position + tackleDir * math.min(tackleSpeed * tackleTime, threat.danger + 18)
            else
                catchPos = threat.position + threat.velocity * t + threat.acceleration * (0.5 * t * t)
            end
            local safe = flat(runner - catchPos).Magnitude - threat.danger
            if safe < clearance then
                clearance = safe
            end
        end
    end
    return clearance
end

local function addDirection(list, direction)
    direction = flat(direction)
    if direction.Magnitude < 0.05 then
        return
    end
    direction = direction.Unit
    for _, item in ipairs(list) do
        if item:Dot(direction) > 0.985 then
            return
        end
    end
    list[#list + 1] = direction
end

local function corridorAxes(position, goal)
    refreshSafezones()
    local a = safezone.a
    local b = safezone.b
    if not a or not b then
        return nil, nil, nil
    end
    local axis = flat(b.center - a.center)
    if axis.Magnitude < 0.05 then
        return nil, nil, nil
    end
    if math.abs(axis.X) >= math.abs(axis.Z) then
        axis = Vector3.new(axis.X >= 0 and 1 or -1, 0, 0)
    else
        axis = Vector3.new(0, 0, axis.Z >= 0 and 1 or -1)
    end
    local toGoal = flat(goal - position)
    if toGoal.Magnitude > 0.05 and axis:Dot(toGoal) < 0 then
        axis = -axis
    end
    local lateral = Vector3.new(-axis.Z, 0, axis.X)
    local center = (a.center + b.center) * 0.5
    return axis, lateral, center
end

local function clearCorridorLock()
    runtime.corridorActive = false
    runtime.corridorGoal = Vector3.zero
    runtime.corridorCenter = Vector3.zero
    runtime.corridorAxis = Vector3.zero
    runtime.corridorGapWidth = 0
    runtime.corridorStartedAt = -math.huge
end

local function findCorridorGoal(position, goal, threats, now)
    if not SETTINGS.corridorEnabled or #threats < 2 then
        clearCorridorLock()
        return nil
    end

    local axis, lateral, center = corridorAxes(position, goal)
    if not axis then
        clearCorridorLock()
        return nil
    end

    local forwardDistance = (center - position):Dot(axis)
    if forwardDistance < -12 or forwardDistance > SETTINGS.corridorApproachDistance then
        clearCorridorLock()
        return nil
    end

    local lineLat = center:Dot(lateral)
    local blockers = {}
    for _, threat in ipairs(threats) do
        local longitudinal = math.abs((threat.position - center):Dot(axis))
        local lateralPos = (threat.position - center):Dot(lateral)
        if longitudinal <= SETTINGS.corridorCenterRange and threat.distance <= 100 then
            blockers[#blockers + 1] = {
                threat = threat,
                lateral = lateralPos,
                buffer = math.clamp(threat.danger * 0.38, 2.25, 5.25),
            }
        end
    end
    if #blockers < 2 then
        if runtime.corridorActive and now - runtime.corridorStartedAt <= SETTINGS.corridorLockTime then
            return runtime.corridorGoal
        end
        clearCorridorLock()
        return nil
    end

    table.sort(blockers, function(x, y)
        return x.lateral < y.lateral
    end)

    local bestCenter = nil
    local bestWidth = -math.huge
    local bestScore = -math.huge
    local low = math.huge
    local high = -math.huge
    for _, item in ipairs(blockers) do
        low = math.min(low, item.lateral - item.buffer)
        high = math.max(high, item.lateral + item.buffer)
    end

    local gaps = {}
    for i = 1, #blockers - 1 do
        local left = blockers[i].lateral + blockers[i].buffer
        local right = blockers[i + 1].lateral - blockers[i + 1].buffer
        if right > left then
            gaps[#gaps + 1] = {left = left, right = right, center = (left + right) * 0.5}
        end
    end

    local lateralMin = math.min(low - 9, lineLat - 28)
    local lateralMax = math.max(high + 9, lineLat + 28)
    if blockers[1].lateral - blockers[1].buffer > lateralMin then
        gaps[#gaps + 1] = {
            left = lateralMin,
            right = blockers[1].lateral - blockers[1].buffer,
            center = (lateralMin + blockers[1].lateral - blockers[1].buffer) * 0.5,
        }
    end
    if blockers[#blockers].lateral + blockers[#blockers].buffer < lateralMax then
        gaps[#gaps + 1] = {
            left = blockers[#blockers].lateral + blockers[#blockers].buffer,
            right = lateralMax,
            center = (blockers[#blockers].lateral + blockers[#blockers].buffer + lateralMax) * 0.5,
        }
    end

    for _, gap in ipairs(gaps) do
        local width = gap.right - gap.left
        if width >= SETTINGS.corridorMinWidth then
            local lateralOffset = gap.center - lineLat
            local linePoint = center + lateral * lateralOffset
            local aheadPoint = linePoint + axis * SETTINGS.corridorPassDistance
            local entryPoint = linePoint - axis * math.min(12, math.max(6, forwardDistance * 0.15))
            local entryClear = routeClear(position, flat(entryPoint - position), threats)
            local passClear = routeClear(position, flat(aheadPoint - position), threats)
            local edgeSafe = edgeDirectionClear(linePoint - axis * 4, axis, position.Y, 8)
            local centrality = 1 - math.min(math.abs(lateralOffset) / 28, 1)
            local score = width * 2.8 + centrality * 6 + math.min(passClear, 15) * 1.4 + math.min(entryClear, 10)
            if edgeSafe then
                score += 4
            else
                score -= 6
            end
            if passClear < -1.5 or entryClear < -1.5 then
                score -= 20
            end
            if score > bestScore then
                bestScore = score
                bestCenter = gap.center
                bestWidth = width
            end
        end
    end

    if not bestCenter then
        if runtime.corridorActive and now - runtime.corridorStartedAt <= SETTINGS.corridorLockTime then
            local lockedProgress = (position - runtime.corridorCenter):Dot(runtime.corridorAxis)
            if lockedProgress > -8 and lockedProgress < SETTINGS.corridorPassDistance + 10 then
                return runtime.corridorGoal
            end
        end
        clearCorridorLock()
        return nil
    end

    if runtime.corridorActive then
        local sameAxis = runtime.corridorAxis:Dot(axis) > 0.98
        local sameCenter = math.abs((runtime.corridorCenter - center):Dot(lateral) - (bestCenter - lineLat)) <= 5
        local progress = (position - runtime.corridorCenter):Dot(runtime.corridorAxis)
        if sameAxis and sameCenter and progress > -10 and progress < SETTINGS.corridorPassDistance + 12 then
            return runtime.corridorGoal
        end
    end

    local gapOffset = bestCenter - lineLat
    local linePoint = center + lateral * gapOffset
    local passPoint = linePoint + axis * SETTINGS.corridorPassDistance
    runtime.corridorActive = true
    runtime.corridorGoal = Vector3.new(passPoint.X, position.Y, passPoint.Z)
    runtime.corridorCenter = linePoint
    runtime.corridorAxis = axis
    runtime.corridorGapWidth = bestWidth
    runtime.corridorStartedAt = now
    return runtime.corridorGoal
end

local function corridorDirection(position, goal, threats)
    local desired = flat(goal - position)
    if desired.Magnitude < 0.05 then
        return Vector3.zero
    end
    desired = desired.Unit
    local candidates = {}
    if runtime.sideGapDirection.Magnitude > 0.05 and os.clock() < runtime.sideGapUntil then
        addDirection(candidates, runtime.sideGapDirection)
    end
    addDirection(candidates, desired)
    for _, angle in ipairs({12, -12, 24, -24, 38, -38, 52, -52, 70, -70, 90, -90}) do
        addDirection(candidates, rotate(desired, angle))
    end
    local best = desired
    local bestScore = -math.huge
    for _, candidate in ipairs(candidates) do
        local progress = candidate:Dot(desired)
        if progress >= -0.05 then
            local clearance = routeClear(position, candidate, threats)
            local score = progress * 8 + math.min(clearance, 16) * 2.2
            if clearance < 0 then
                score -= math.abs(clearance) * 16
            elseif clearance < 4 then
                score -= (4 - clearance) * 7
            end
            if score > bestScore then
                bestScore = score
                best = candidate
            end
        end
    end
    return best.Unit
end

local function chooseSideGapDirection(position, desired, threats)
    if not SETTINGS.sideGapEnabled or #threats == 0 then
        return nil, nil, -math.huge
    end
    local front = flat(desired)
    if front.Magnitude < 0.05 then
        return nil, nil, -math.huge
    end
    front = front.Unit
    local lateral = Vector3.new(-front.Z, 0, front.X)

    local nearest = nil
    local nearestDistance = math.huge
    for _, threat in ipairs(threats) do
        local rel = flat(threat.predicted - position)
        if rel.Magnitude > 0.05 then
            local forward = rel:Dot(front)
            local lateralOffset = math.abs(rel:Dot(lateral))
            if forward > 0 and forward <= 34 and lateralOffset <= 16 and threat.distance < nearestDistance then
                nearest = threat
                nearestDistance = threat.distance
            end
        end
    end
    if not nearest then
        return nil, nil, -math.huge
    end

    local rel = flat(nearest.predicted - position)
    local forwardGap = rel:Dot(front)
    local lateralOffset = rel:Dot(lateral)
    local frontBlocked = forwardGap > 0 and forwardGap < math.max(12, nearest.danger * 2.2)
        and math.abs(lateralOffset) < 13
    if not frontBlocked then
        return nil, nil, -math.huge
    end

    local candidates = {}
    for _, angle in ipairs(SETTINGS.sideGapAngles) do
        local rad = math.rad(angle)
        local c = math.cos(rad)
        local sn = math.sin(rad)
        local leftDir = (front * c + lateral * sn)
        local rightDir = (front * c - lateral * sn)
        candidates[#candidates + 1] = {dir = leftDir.Unit, side = "left"}
        candidates[#candidates + 1] = {dir = rightDir.Unit, side = "right"}
    end

    local best, bestScore, bestSide = nil, -math.huge, nil
    for _, item in ipairs(candidates) do
        local candidate = item.dir
        local clearance = routeClear(position, candidate, threats)
        local support = groundSupportScore(position, candidate, position.Y)
        local wallBlocked = invisWallHit(position, candidate, 16) ~= nil
        if not wallBlocked and support >= 3 and clearance >= -1 then
            local forwardProgress = candidate:Dot(front)
            local sideProgress = math.abs(candidate:Dot(lateral))
            local score = forwardProgress * SETTINGS.sideGapForwardBias
                + sideProgress * 7
                + math.min(clearance, 14) * 3.2
                + support * 1.4
            local towardCatcher = rel:Dot(lateral)
            local away = item.side == "left" and -towardCatcher or towardCatcher
            score += math.clamp(away / 10, -1, 1) * 4
            if clearance >= SETTINGS.sideGapMinClearance then
                score += 5
            end
            if score > bestScore then
                best = candidate
                bestScore = score
                bestSide = item.side
            end
        end
    end

    if best then
        return best, bestSide, bestScore
    end
    return nil, nil, -math.huge
end

local function chooseRunnerDirection(position, goal, threats)
    local desired = flat(goal - position)
    if desired.Magnitude < 0.05 then
        return Vector3.zero
    end
    desired = desired.Unit

    local sideGap, sideName = chooseSideGapDirection(position, desired, threats)
    if sideGap then
        runtime.sideGapDirection = sideGap
        runtime.sideGapUntil = os.clock() + SETTINGS.sideGapCommitTime
        runtime.sideGapReason = "front-blocked:" .. tostring(sideName)
        return sideGap
    elseif runtime.sideGapDirection.Magnitude > 0.05 and os.clock() < runtime.sideGapUntil then
        local clear = routeClear(position, runtime.sideGapDirection, threats)
        if clear >= 0 and not invisWallHit(position, runtime.sideGapDirection, 14) then
            return runtime.sideGapDirection
        end
    else
        runtime.sideGapDirection = Vector3.zero
        runtime.sideGapReason = ""
    end

    if not SETTINGS.avoidCatchers or #threats == 0 then
        runtime.sideGapDirection = Vector3.zero
        runtime.sideGapUntil = -math.huge
        runtime.sideGapReason = ""
        return desired
    end

    local candidates = {}
    addDirection(candidates, desired)

    for _, angle in ipairs({
        10, -10, 22, -22, 34, -34, 48, -48, 62, -62, 76, -76, 88, -88
    }) do
        addDirection(candidates, rotate(desired, angle))
    end

    local blocker = threats[1]
    local nearestScore = math.huge
    for _, threat in ipairs(threats) do
        local toThreat = flat(threat.position - position)
        local ahead = toThreat:Dot(desired)
        local distance = toThreat.Magnitude
        if ahead > 0 and distance < nearestScore then
            nearestScore = distance
            blocker = threat
        end
    end

    if blocker then
        local toBlocker = flat(blocker.position - position)
        if toBlocker.Magnitude > 0.05 then
            local lateral = Vector3.new(-desired.Z, 0, desired.X)
            local side = toBlocker:Dot(lateral) >= 0 and -1 or 1
            addDirection(candidates, (desired + lateral * side * 0.55).Unit)
            addDirection(candidates, (desired + lateral * side * 0.95).Unit)
            addDirection(candidates, (desired - lateral * side * 0.55).Unit)
            addDirection(candidates, (desired - lateral * side * 0.95).Unit)
        end
    end

    if runtime.stuck then
        local lateral = Vector3.new(-desired.Z, 0, desired.X)
        addDirection(candidates, lateral)
        addDirection(candidates, -lateral)
        local center = getPlayfieldCenter()
        if center then
            addDirection(candidates, flat(center - position))
        end
    end

    local best = desired
    local bestScore = -math.huge
    local emergency = false
    for _, threat in ipairs(threats) do
        if threat.collisionRisk or threat.tackle
            or (threat.preTackle and threat.closing > 0) then
            emergency = true
            break
        end
    end

    for _, candidate in ipairs(candidates) do
        local progress = candidate:Dot(desired)
        local clearance = routeClear(position, candidate, threats)
        local wallBlocked = invisWallHit(position, candidate, 18) ~= nil
        if wallBlocked then
            continue
        end

        if not emergency and progress < 0.04 then
            continue
        end

        local score = progress * 10
        score += math.min(clearance, 20) * 2.4 * SETTINGS.avoidStrength

        if clearance < 0 then
            score -= math.abs(clearance) * 18 * SETTINGS.avoidStrength
        elseif clearance < 5 then
            score -= (5 - clearance) * 5 * SETTINGS.avoidStrength
        end

        if progress > 0.18 and math.abs(candidate:Dot(desired)) < 0.96 then
            score += math.min(math.max(clearance, 0), 8) * 1.15
        end

        for _, threat in ipairs(threats) do
            local away = flat(position - threat.intercept)
            if away.Magnitude > 0.05 then
                local urgency = math.clamp(
                    1 - math.min(
                        threat.interceptGap,
                        threat.timeToDanger * math.max(threat.closing, 1)
                    ) / math.max(threat.danger * 3, 1),
                    0,
                    1
                )
                local weight = (threat.collisionRisk and 14 or 4.5) * SETTINGS.avoidStrength
                if threat.tackle then
                    weight *= 1.45
                end
                score += candidate:Dot(away.Unit) * urgency * weight
            end
        end

        if runtime.edgeRisk then
            local inward = runtime.edgeDirection
            if inward.Magnitude > 0.05 then
                score += candidate:Dot(inward.Unit) * 7
            end
        end

        if score > bestScore then
            bestScore = score
            best = candidate
        end
    end

    if best.Magnitude < 0.05 then
        return desired
    end
    return best.Unit
end

local function chooseDashDirection(position, direction, threats)
    local desired = flat(direction)
    local root = getRoot()
    if desired.Magnitude < 0.05 and root then
        desired = flat(root.CFrame.LookVector)
    end
    if desired.Magnitude < 0.05 then
        return Vector3.zero
    end
    desired = desired.Unit

    local candidates = {}
    addDirection(candidates, desired)
    for _, angle in ipairs({
        18, -18, 32, -32, 48, -48, 64, -64, 82, -82, 90, -90
    }) do
        addDirection(candidates, rotate(desired, angle))
    end

    if runtime.edgeRisk and runtime.edgeDirection.Magnitude > 0.05 then
        addDirection(candidates, runtime.edgeDirection)
        addDirection(candidates, rotate(runtime.edgeDirection, 28))
        addDirection(candidates, rotate(runtime.edgeDirection, -28))
    end

    local awaySum = Vector3.zero
    for i = 1, math.min(6, #threats) do
        local threat = threats[i]
        local away = flat(position - threat.predicted)
        if away.Magnitude > 0.05 then
            local weight = math.clamp(1 - threat.distance / 60, 0.2, 1)
            if threat.tackle then
                weight *= 2.2
            elseif threat.preTackle then
                weight *= 1.5
            end
            awaySum += away.Unit * weight
        end
    end
    if awaySum.Magnitude > 0.05 then
        addDirection(candidates, awaySum.Unit)
        addDirection(candidates, rotate(awaySum.Unit, 28))
        addDirection(candidates, rotate(awaySum.Unit, -28))
    end

    local best = desired
    local bestScore = -math.huge
    for _, candidate in ipairs(candidates) do
        local clearance = routeClear(position, candidate, threats)
        local progress = candidate:Dot(desired)
        local score = progress * 4.5 + math.min(clearance, 20) * 5.0

        if progress < -0.05 then
            score -= 18
        end

        if clearance < 0 then
            score -= math.abs(clearance) * 22
        elseif clearance < 5 then
            score -= (5 - clearance) * 5
        end

        if awaySum.Magnitude > 0.05 then
            score += candidate:Dot(awaySum.Unit) * 7
        end

        if runtime.edgeRisk and runtime.edgeDirection.Magnitude > 0.05 then
            score += candidate:Dot(runtime.edgeDirection.Unit) * 10
        end

        for _, threat in ipairs(threats) do
            local predicted = threat.predicted
            local dashPoint = position + candidate * math.min(getRunnerSpeed() * 0.45, 11)
            local gap = flat(dashPoint - predicted).Magnitude
            if gap <= threat.danger * (threat.tackle and 1.55 or 1.2) then
                score -= threat.tackle and 14 or 8
            end
        end

        if score > bestScore then
            bestScore = score
            best = candidate
        end
    end

    return best.Unit
end

local function getAbilityKey()
    local state = runtime.armory
    if type(state) ~= "table" or state.loaded ~= true then
        return nil
    end

    local candidates = {}
    local function add(value)
        if type(value) ~= "string" or value == "" then
            return
        end
        for i = 1, #candidates do
            if candidates[i] == value then
                return
            end
        end
        candidates[#candidates + 1] = value
    end

    local ok, value = pcall(GearCatalog.equippedForRole, state, "Runner")
    if ok then add(value) end
    ok, value = pcall(GearCatalog.equippedForRole, "Runner", state)
    if ok then add(value) end
    ok, value = pcall(GearCatalog.equippedForRole, "Runner")
    if ok then add(value) end

    add(state.equippedAbility)
    add(state.RunnerAbility)
    add(state.runnerAbility)

    local equipped = state.equipped or state.Equipped or state.loadout or state.Loadout
    if type(equipped) == "table" then
        add(equipped.Runner)
        add(equipped.runner)
        add(equipped.Ability)
        add(equipped.ability)
    end

    for i = 1, #candidates do
        local key = candidates[i]
        local okDef, def = pcall(GearCatalog.get, key)
        if okDef and def and def.Kind == "Ability" then
            if (not def.UseRole or def.UseRole == "Runner")
                and type(state.abilities) == "table"
                and state.abilities[key] == true then
                return key
            end
        end
    end
    return nil
end

local function requestDash(direction, now)
    if not SETTINGS.autoDash or not isRunnerActive() then
        return false
    end

    local character = getCharacter()
    local root = getRoot()
    if not character or not root then
        runtime.dashStatus = "no-character"
        return false
    end

    local okAvailable, available = pcall(BoostInput.available, LocalPlayer)
    if not okAvailable then
        runtime.dashStatus = "available-error: " .. tostring(available)
        return false
    end
    if available ~= true then
        local cooldownUntil = tonumber(character:GetAttribute("DashCooldownUntil")) or 0
        runtime.dashStatus = cooldownUntil > os.clock() and "cooldown" or "not-available"
        return false
    end

    local cooldownUntil = tonumber(character:GetAttribute("DashCooldownUntil")) or 0
    if os.clock() < cooldownUntil then
        runtime.dashStatus = "cooldown"
        return false
    end

    if now - runtime.dashAt < SETTINGS.dashCooldown then
        runtime.dashStatus = "local-cooldown"
        return false
    end

    local hum = getHumanoid()
    local dir = hum and flat(hum.MoveDirection) or Vector3.zero
    if dir.Magnitude < 0.05 then
        dir = flat(direction)
    end
    if dir.Magnitude < 0.05 then
        dir = flat(root.CFrame.LookVector)
    end
    if dir.Magnitude < 0.05 then
        runtime.dashStatus = "no-direction"
        return false
    end

    local beforeCount = tonumber(character:GetAttribute("DashCount")) or 0
    local okRequest, result = pcall(BoostInput.request, nil)
    runtime.dashLastRequestAt = now
    runtime.dashLastCount = beforeCount

    if not okRequest then
        runtime.dashStatus = "request-error: " .. tostring(result)
        return false
    end
    if result == false then
        runtime.dashStatus = "request-rejected"
        return false
    end

    runtime.dashAt = now
    runtime.dashStatus = "requested:waiting-game-client"
    return true
end

local function shouldDash(position, threats, goalDistance)
    if not SETTINGS.autoDash or not isRunnerActive() then
        return false
    end

    local now = os.clock()
    if now - runtime.dashAt < 0.28 then
        return false
    end

    if #threats == 0 then
        return false
    end

    local nearestDistance = math.huge
    local nearestThreat = nil
    local immediateDanger = false
    local hardBlock = false
    local imminentTime = math.huge

    for _, threat in ipairs(threats) do
        if threat.distance < nearestDistance then
            nearestDistance = threat.distance
            nearestThreat = threat
        end
        local gap = tonumber(threat.interceptGap) or math.huge
        local danger = math.max(tonumber(threat.danger) or 4, 4)
        imminentTime = math.min(imminentTime, tonumber(threat.timeToDanger) or math.huge)

        if threat.tackle and (
            gap <= danger * 1.12
            or (threat.timeToDanger or math.huge) <= 0.38
            or threat.distance <= 10
        ) then
            immediateDanger = true
        elseif threat.preTackle and (
            gap <= danger * 1.05
            and (threat.timeToDanger or math.huge) <= 0.48
        ) then
            immediateDanger = true
        elseif threat.collisionRisk and (
            gap <= danger * 1.02
            and (threat.timeToDanger or math.huge) <= 0.42
        ) then
            immediateDanger = true
        end
    end

    local currentPath = runtime.path
    if currentPath.Magnitude > 0.05 then
        local pathClearance = routeClear(position, currentPath, threats)
        if pathClearance < -2.0 and nearestDistance <= 18 then
            hardBlock = true
        end
    end

    if runtime.sideGapDirection.Magnitude > 0.05
        and os.clock() < runtime.sideGapUntil
        and nearestDistance <= 14 then
        local sideClearance = routeClear(position, runtime.sideGapDirection, threats)
        if sideClearance >= SETTINGS.sideGapMinClearance and imminentTime <= 0.55 then
            return true
        end
    end

    if immediateDanger then
        return true
    end

    if hardBlock and nearestDistance <= 15 and imminentTime <= 0.55 then
        return true
    end

    if nearestThreat and nearestDistance <= 9 and imminentTime <= 0.45 then
        return true
    end

    return false
end
local function runnerGoal(position, now)
    runtime.goalMode = "SafeZone"
    local goal = select(1, chooseSafeGoal(position))
    if not goal and SETTINGS.emergencySafeZone then
        goal = getSafeFallback(position)
    end
    runtime.goal = goal
    return goal
end

local function routeDistance(position, goal, target)
    local a = flat(position)
    local b = flat(goal)
    local p = flat(target)
    local line = b - a
    local lengthSquared = line:Dot(line)
    if lengthSquared < 0.01 then
        return (p - a).Magnitude, 0
    end
    local t = math.clamp((p - a):Dot(line) / lengthSquared, 0, 1)
    local closest = a + line * t
    return (p - closest).Magnitude, t
end

local function validReviveTarget(target)
    if not target or not target.Parent then
        return false
    end
    local character = target.Character
    local root = character and character:FindFirstChild("HumanoidRootPart")
    if not root then
        return false
    end
    if character:GetAttribute("RescueAvailable") ~= true or character:GetAttribute("Ragdolled") ~= true then
        return false
    end
    local helper = character:GetAttribute("RescueHelperId")
    return helper == nil or helper == LocalPlayer.UserId
end

local function chooseAssistTarget(position, safeGoal, now)
    if not safeGoal then
        runtime.assistMode = nil
        runtime.assistTarget = nil
        return nil, nil
    end

    local currentAssist = runtime.assistTarget
    if runtime.assistMode == "Revive" then
        if validReviveTarget(currentAssist) then
            local targetRoot = getRoot(currentAssist)
            if targetRoot then
                local distance = flat(targetRoot.Position - position).Magnitude
                local lateral = routeDistance(position, safeGoal, targetRoot.Position)
                if runtime.reviveStarted or distance <= SETTINGS.reviveMaxDistance and (lateral <= 24 or distance <= RESCUE_RANGE + 5) then
                    return currentAssist, "Revive"
                end
            end
        end
        if runtime.reviveStarted then
            return currentAssist, "Revive"
        end
        runtime.assistMode = nil
        runtime.assistTarget = nil
    elseif runtime.assistMode == "Gem" then
        if currentAssist and currentAssist.Parent then
            local distance = flat(currentAssist.Position - position).Magnitude
            local lateral = routeDistance(position, safeGoal, currentAssist.Position)
            if distance <= SETTINGS.gemMaxDistance and lateral <= 18 then
                return currentAssist, "Gem"
            end
        end
        runtime.assistMode = nil
        runtime.assistTarget = nil
    end

    local reviveCandidate
    if SETTINGS.autoRevive then
        local target = findDownedPlayer(position)
        if target then
            local targetRoot = getRoot(target)
            if targetRoot then
                local distance = flat(targetRoot.Position - position).Magnitude
                local lateral, t = routeDistance(position, safeGoal, targetRoot.Position)
                if distance <= SETTINGS.reviveMaxDistance and t <= 1.05 and (lateral <= 24 or distance <= RESCUE_RANGE + 5) then
                    reviveCandidate = target
                end
            end
        end
    end

    local gemCandidate
    if SETTINGS.autoGems then
        refreshGems(now, position)
        local gem = runtime.gemTarget
        if gem and gem.Parent then
            local distance = flat(gem.Position - position).Magnitude
            local lateral, t = routeDistance(position, safeGoal, gem.Position)
            if distance <= SETTINGS.gemMaxDistance and t <= 1.05 and lateral <= 18 then
                gemCandidate = gem
            end
        end
    end

    if SETTINGS.reviveBeforeGems and reviveCandidate then
        runtime.assistMode = "Revive"
        runtime.assistTarget = reviveCandidate
        runtime.assistSince = now
        return reviveCandidate, "Revive"
    end
    if gemCandidate then
        runtime.assistMode = "Gem"
        runtime.assistTarget = gemCandidate
        runtime.assistSince = now
        return gemCandidate, "Gem"
    end
    if reviveCandidate then
        runtime.assistMode = "Revive"
        runtime.assistTarget = reviveCandidate
        runtime.assistSince = now
        return reviveCandidate, "Revive"
    end

    return nil, nil
end

local function handleGemArrival(position, now)
    local gem = runtime.gemTarget
    if not gem or not gem.Parent then
        return
    end
    if flat(gem.Position - position).Magnitude <= SETTINGS.gemCollectDistance then
        runtime.gemIgnored[gem] = now + 0.7
        runtime.gemTarget = nil
    end
end

local function movementStuck(now, position)
    local previous = runtime.lastMovePosition
    if not previous then
        runtime.lastMovePosition = position
        runtime.lastMove = now
        runtime.stuck = false
        return
    end
    if flat(position - previous).Magnitude >= 0.5 then
        runtime.lastMovePosition = position
        runtime.lastMove = now
        runtime.stuck = false
    elseif now - runtime.lastMove > 0.55 then
        runtime.stuck = true
        runtime.lastMove = now
        runtime.lastMovePosition = position
    end
end

local function runnerStep(now, dt)

    local role = getRole()
    local state = getRunState()

    if role ~= "Runner" or state ~= "Active" then
        runtime.path = Vector3.zero
        runtime.runnerPlanAt = -math.huge
        runtime.runnerPlanDirection = Vector3.zero
        runtime.runnerPlanGoal = Vector3.zero
        runtime.goal = nil
        runtime.goalSide = nil
        runtime.goalMode = "SafeZone"
        runtime.routeActive = false
        runtime.routeComplete = false
        runtime.routeStartSide = nil
        runtime.routeTargetSide = nil
        runtime.routeCompletePosition = nil
        runtime.routeCompleteAt = -math.huge
        clearCorridorLock()
        runtime.edgeRisk = false
        runtime.edgeDirection = Vector3.zero
        runtime.sideGapDirection = Vector3.zero
        runtime.sideGapUntil = -math.huge
        runtime.sideGapReason = ""
        runtime.assistMode = nil
        runtime.assistTarget = nil
        if runtime.reviveStarted then
            cancelRevive()
        end
        return
    end

    if not SETTINGS.runnerEnabled then
        return
    end

    local root = getRoot()
    local hum = getHumanoid()
    if not root or not hum then
        return
    end

    if not canMove() then
        runtime.path = Vector3.zero
        return
    end

    refreshPing(now)
    refreshSafezones()
    refreshCatchers(now)
    local position = root.Position

    local baseGoal = runnerGoal(position, now)
    if runtime.routeComplete then
        local targetZone = runtime.routeTargetSide == (safezone.a and safezone.a.name) and safezone.a or safezone.b
        local movedFromCompletion = runtime.routeCompletePosition and flat(position - runtime.routeCompletePosition).Magnitude or 0
        local newRoundPosition = targetZone and inZone(position, targetZone) and movedFromCompletion >= 5 and now - runtime.routeCompleteAt >= 0.25
        if newRoundPosition then
            runtime.routeActive = false
            runtime.routeComplete = false
            runtime.routeStartSide = nil
            runtime.routeTargetSide = nil
            runtime.routeCompletePosition = nil
            runtime.routeCompleteAt = -math.huge
            runtime.goal = nil
            runtime.goalSide = nil
            baseGoal = runnerGoal(position, now)
        end
        if runtime.routeComplete then
            clearCorridorLock()
            runtime.path = Vector3.zero
            runtime.goalMode = "SafeZone"
            runtime.assistMode = nil
            runtime.assistTarget = nil
            if runtime.reviveStarted then
                cancelRevive()
            end
            hum:Move(Vector3.zero, false)
                            return
        end
    end
    if not baseGoal then
        local fallback = getSafeFallback(position)
        if fallback then
            baseGoal = fallback
            runtime.goal = fallback
            runtime.goalMode = "SafeZone"
        else
            local forward = flat(root.CFrame.LookVector)
            if forward.Magnitude > 0.05 then
                baseGoal = position + forward.Unit * 40
            end
        end
    end

    if not baseGoal then
        hum:Move(Vector3.zero, false)
        runtime.path = Vector3.zero
        return
    end

    local assistTarget, assistMode = chooseAssistTarget(position, baseGoal, now)
    local movementGoal = baseGoal

    if assistTarget and assistMode == "Revive" then
        runtime.reviveTarget = assistTarget
        local targetRoot = getRoot(assistTarget)
        if targetRoot then
            local targetPosition = targetRoot.Position
            local distance = flat(targetPosition - position).Magnitude
            if distance <= RESCUE_RANGE + 0.75 or runtime.reviveStarted then
                updateRevive(now, position)
            end
            if not runtime.reviveStarted and distance > RESCUE_RANGE then
                movementGoal = targetPosition
            elseif runtime.reviveStarted then
                movementGoal = targetPosition
            end
        end
    elseif assistTarget and assistMode == "Gem" and assistTarget.Parent then
        movementGoal = assistTarget.Position
        runtime.goalMode = "Gem"
    else
        runtime.goalMode = "SafeZone"
    end

    if runtime.reviveStarted then
        local targetRoot = runtime.reviveTarget and getRoot(runtime.reviveTarget)
        if targetRoot then
            local reviveDistance = flat(targetRoot.Position - position).Magnitude
            if reviveDistance > RESCUE_RANGE + 1.25 then
                cancelRevive()
            else
                hum:Move(Vector3.zero, false)
                runtime.path = Vector3.zero
                                        return
            end
        else
            cancelRevive()
        end
    end

    movementStuck(now, position)
    local threats = updateThreats(now, position)

    local distanceToGoal = flat(movementGoal - position).Magnitude
    local arriveDistance = runtime.goalMode == "Gem" and SETTINGS.gemCollectDistance or 2.5

    if distanceToGoal <= arriveDistance then
        if runtime.goalMode == "Gem" then
            handleGemArrival(position, now)
            runtime.assistMode = nil
            runtime.assistTarget = nil
            runtime.goalMode = "SafeZone"
            movementGoal = baseGoal
        elseif runtime.goalMode == "SafeZone" then
            local nextGoal = select(1, chooseSafeGoal(position))
            if runtime.routeComplete then
                hum:Move(Vector3.zero, false)
                runtime.path = Vector3.zero
                                        return
            end
            movementGoal = nextGoal or baseGoal
            runtime.goal = movementGoal
        end
    end

    if not movementGoal then
        hum:Move(Vector3.zero, false)
        runtime.path = Vector3.zero
        return
    end

    local direction = flat(movementGoal - position)
    if direction.Magnitude < 0.05 then
        hum:Move(Vector3.zero, false)
        runtime.path = Vector3.zero
        return
    end
    if runtime.goalMode == "SafeZone" and runtime.goal then
        movementGoal = Vector3.new(runtime.goal.X, position.Y, runtime.goal.Z)
        direction = flat(movementGoal - position)
        if direction.Magnitude < 0.05 then
            local nextGoal = select(1, chooseSafeGoal(position))
            movementGoal = nextGoal or movementGoal
            runtime.goal = movementGoal
            direction = flat(movementGoal - position)
            if direction.Magnitude < 0.05 then
                hum:Move(Vector3.zero, false)
                runtime.path = Vector3.zero
                return
            end
        end
    end
    direction = direction.Unit

    local corridorGoal = nil
    if runtime.goalMode == "SafeZone" and SETTINGS.avoidCatchers and #threats >= 2 then
        corridorGoal = findCorridorGoal(position, movementGoal, threats, now)
        if corridorGoal then
            movementGoal = corridorGoal
            direction = flat(corridorGoal - position)
            if direction.Magnitude > 0.05 then
                direction = corridorDirection(position, corridorGoal, threats)
            end
        end
    elseif runtime.corridorActive then
        clearCorridorLock()
    end

    if SETTINGS.avoidCatchers and #threats > 0 and not (corridorGoal and direction.Magnitude > 0.05) then
        direction = chooseRunnerDirection(position, movementGoal, threats)
    elseif SETTINGS.avoidCatchers and #threats > 0 and corridorGoal then
        direction = chooseRunnerDirection(position, movementGoal, threats)
        if runtime.corridorActive then
            direction = corridorDirection(position, movementGoal, threats)
        end
    end

    if runtime.corridorActive then
        local axis = runtime.corridorAxis
        local progress = (position - runtime.corridorCenter):Dot(axis)
        if progress >= SETTINGS.corridorPassDistance + 3 then
            clearCorridorLock()
        end
    end

    local hardThreat = threats[1]
    local hardDodge = false
    if SETTINGS.avoidCatchers and hardThreat and (hardThreat.collisionRisk or hardThreat.tackle or hardThreat.preTackle and hardThreat.closing > 0) then
        local escape = flat(position - hardThreat.intercept)
        if escape.Magnitude > 0.05 then
            local escapeDir = escape.Unit
            local candidates = {escapeDir, rotate(escapeDir, 35), rotate(escapeDir, -35), rotate(escapeDir, 70), rotate(escapeDir, -70)}
            if runtime.corridorActive then
                local forward = flat(runtime.corridorGoal - position)
                if forward.Magnitude > 0.05 then
                    local keep = {}
                    for _, candidate in ipairs(candidates) do
                        if candidate:Dot(forward.Unit) > 0.05 then
                            keep[#keep + 1] = candidate
                        end
                    end
                    candidates = keep
                end
            end
            local best = direction
            local bestClearance = routeClear(position, direction, threats)
            local forward = flat(movementGoal - position)
            local forwardUnit = forward.Magnitude > 0.05 and forward.Unit or direction
            local nearestGap = hardThreat.interceptGap
            local allowReverse = nearestGap <= hardThreat.danger * 0.52
            local foundForward = false

            for _, candidate in ipairs(candidates) do
                local progress = candidate:Dot(forwardUnit)
                if progress >= 0.08 then
                    foundForward = true
                elseif not allowReverse then
                    continue
                end
                local clear = routeClear(position, candidate, threats)
                local adjusted = clear + progress * 2.5
                local bestAdjusted = bestClearance + best:Dot(forwardUnit) * 2.5
                if adjusted > bestAdjusted then
                    best = candidate
                    bestClearance = clear
                end
            end
            local emergency = hardThreat.interceptGap <= hardThreat.danger * (runtime.corridorActive and 1.05 or 1.35)
            if emergency or bestClearance < 3 then
                direction = best
                hardDodge = true
            elseif foundForward then
                hardDodge = false
            end
        end
    end

    local nearestThreat
    local nearestDistance = math.huge
    for _, threat in ipairs(threats) do
        if threat.distance < nearestDistance then
            nearestDistance = threat.distance
            nearestThreat = threat
        end
    end

    if SETTINGS.emergencySafeZone and nearestThreat and nearestDistance <= SETTINGS.panicDistance and runtime.stuck then
        local fallback = getSafeFallback(position)
        if fallback then
            local safeDirection = flat(fallback - position)
            if safeDirection.Magnitude > 0.05 then
                direction = safeDirection.Unit
                movementGoal = fallback
                runtime.goalMode = "SafeZone"
                runtime.assistMode = nil
                runtime.assistTarget = nil
            end
        end
    end

    local nowEdge = now
    local edgeDirection, edgeRisk = chooseEdgeDirection(position, direction, movementGoal, position.Y)
    runtime.edgeRisk = edgeRisk
    runtime.edgeDirection = edgeDirection
    if edgeRisk and edgeDirection.Magnitude > 0.05 then
        if runtime.edgeRecoveryDirection.Magnitude < 0.05
            or nowEdge >= runtime.edgeRecoveryUntil
            or runtime.edgeRecoveryDirection:Dot(edgeDirection) < 0.92 then
            runtime.edgeRecoveryDirection = edgeDirection.Unit
            runtime.edgeRecoveryAt = nowEdge
            runtime.edgeRecoveryUntil = nowEdge + 0.72
        end
        direction = runtime.edgeRecoveryDirection
        hardDodge = true
    elseif nowEdge >= runtime.edgeRecoveryUntil then
        runtime.edgeRecoveryDirection = Vector3.zero
    end

    if runtime.stuck and movementGoal then
        local center = getPlayfieldCenter()
        local recovery = center and flat(center - position) or flat(movementGoal - position)
        if recovery.Magnitude > 0.05 then
            recovery = recovery.Unit
            if runtime.stuckRecoveryDirection.Magnitude < 0.05
                or nowEdge >= runtime.stuckRecoveryUntil
                or runtime.stuckRecoveryDirection:Dot(recovery) < 0.75 then
                local candidates = {
                    recovery,
                    rotateEdge(recovery, 35),
                    rotateEdge(recovery, -35),
                    rotateEdge(recovery, 70),
                    rotateEdge(recovery, -70),
                }
                local best = recovery
                local bestScore = -math.huge
                for _, candidate in ipairs(candidates) do
                    local support = groundSupportScore(position, candidate, position.Y)
                    local progress = candidate:Dot(recovery)
                    local score = support * 5 + progress * 4
                    if score > bestScore then
                        bestScore = score
                        best = candidate.Unit
                    end
                end
                runtime.stuckRecoveryDirection = best
                runtime.stuckRecoveryUntil = nowEdge + 0.85
            end
            direction = runtime.stuckRecoveryDirection
            hardDodge = true
        end
    elseif nowEdge >= runtime.stuckRecoveryUntil then
        runtime.stuckRecoveryDirection = Vector3.zero
    end

    if SETTINGS.smoothMovement and not hardDodge and runtime.path.Magnitude > 0.05 and not runtime.stuck then
        local alpha = math.clamp(SETTINGS.turnRate * math.clamp(dt or (1 / 60), 0.001, 0.1), 0, 1)
        local blended = flat(runtime.path:Lerp(direction, alpha))
        if blended.Magnitude > 0.05 then
            direction = blended.Unit
        end
    end

    runtime.path = direction

    if hum.AutoRotate ~= true then
        hum.AutoRotate = true
    end
    hum:Move(direction, false)

    local character = getCharacter()
    local dashCount = character and tonumber(character:GetAttribute("DashCount")) or nil
    if dashCount and runtime.dashLastCount ~= nil and dashCount ~= runtime.dashLastCount then
        runtime.dashStatus = "active:count " .. tostring(dashCount)
        runtime.dashLastCount = dashCount
    elseif runtime.dashLastRequestAt > 0 and now - runtime.dashLastRequestAt > 0.35
        and now - runtime.dashAt > 0.35 and runtime.dashStatus == "requested:waiting-game-client" then
        runtime.dashStatus = "no-dash-state-change"
    end

    local goalDistance = flat(movementGoal - position).Magnitude
    if shouldDash(position, threats, goalDistance) then
        local dashDir = chooseDashDirection(position, direction, threats)
        if runtime.sideGapDirection.Magnitude > 0.05 and os.clock() < runtime.sideGapUntil then
            dashDir = runtime.sideGapDirection
        elseif runtime.edgeRisk and runtime.edgeRecoveryDirection.Magnitude > 0.05 then
            dashDir = runtime.edgeRecoveryDirection
        elseif runtime.stuck and runtime.stuckRecoveryDirection.Magnitude > 0.05 then
            dashDir = runtime.stuckRecoveryDirection
        end
        requestDash(dashDir, now)
    end

end
local function refreshRunnerTargets(now)
    if now - runtime.catcherTargetAt < 0.15 then
        return
    end
    runtime.catcherTargetAt = now
    table.clear(runtime.catcherTargets)
    for _, player in ipairs(Players:GetPlayers()) do
        if player ~= LocalPlayer and player.Parent and player:GetAttribute("GameRole") == "Runner" and player:GetAttribute("RunState") == "Active" then
            local c = player.Character
            local h = c and c:FindFirstChildOfClass("Humanoid")
            local r = c and c:FindFirstChild("HumanoidRootPart")
            if h and h.Health > 0 and r and c:GetAttribute("Ragdolled") ~= true then
                runtime.catcherTargets[#runtime.catcherTargets + 1] = player
            end
        end
    end
end

local function catcherVelocity(player, now)
    local root = getRoot(player)
    if not root then
        return Vector3.zero
    end
    local data = runtime.catcherVelocity[player]
    if not data then
        data = {velocity = flat(root.AssemblyLinearVelocity), time = now}
        runtime.catcherVelocity[player] = data
        return data.velocity
    end
    local raw = flat(root.AssemblyLinearVelocity)
    local dt = math.clamp(now - data.time, 0.01, 0.25)
    local alpha = math.clamp(dt * SETTINGS.catcherSmoothing, 0, 1)
    data.velocity = data.velocity:Lerp(raw, alpha)
    data.time = now
    return data.velocity
end

local function runnerSafeForCatcher(player)
    refreshSafezones()
    local root = getRoot(player)
    return root and currentZone(root.Position) ~= nil and (
        inZone(root.Position, safezone.a) or inZone(root.Position, safezone.b)
    )
end

local function selectCatcherTarget(now, myPosition)
    refreshRunnerTargets(now)
    local best, bestScore
    local currentScore
    local currentTarget = runtime.catcherTarget
    local chaseSpeed = math.max(getCatcherSpeed(), 1)

    for _, player in ipairs(runtime.catcherTargets) do
        local root = getRoot(player)
        if root then
            local position = root.Position
            local velocity = catcherVelocity(player, now)
            local predicted = position + velocity * SETTINGS.catcherPrediction
            local distance = flat(position - myPosition).Magnitude
            local predictedDistance = flat(predicted - myPosition).Magnitude
            local safe = runnerSafeForCatcher(player)
            local timeToReach = predictedDistance / chaseSpeed
            local score = predictedDistance + math.min(timeToReach * 10, 30) + distance * 0.05
            if SETTINGS.smartPriority and velocity.Magnitude >= 4 then
                score -= 6
            end
            if safe then
                score += 18
            end
            if player == currentTarget then
                currentScore = score
            end
            if not bestScore or score < bestScore then
                best = player
                bestScore = score
            end
        end
    end

    if currentTarget and currentScore and bestScore and currentTarget ~= best and currentScore <= bestScore + 8 then
        best = currentTarget
    end

    runtime.catcherTarget = best
    return best
end

local function catcherDirection(root, predicted, dt)
    local direction = flat(predicted - root.Position)
    if direction.Magnitude < 0.05 then
        return Vector3.zero
    end
    direction = direction.Unit
    if SETTINGS.smoothTurn and runtime.catcherPath and runtime.catcherPath.Magnitude > 0.05 then
        local alpha = math.clamp(1 - math.exp(-math.max(SETTINGS.turnRateCatcher, 1) * math.max(dt, 0.01)), 0, 1)
        local blended = runtime.catcherPath:Lerp(direction, alpha)
        if blended.Magnitude > 0.05 then
            direction = blended.Unit
        end
    end
    runtime.catcherPath = direction
    return direction
end

local function tackleRunning()
    local c = getCharacter()
    return c and c:GetAttribute("TackleActive") == true
end

local function catcherAttack(target, now, root)
    if not target or not root or tackleRunning() then
        return
    end
    local targetRoot = getRoot(target)
    if not targetRoot then
        return
    end

    local targetVelocity = catcherVelocity(target, now)
    local meleeLead = (ContactCatchConfig.Windup or 0.15) + (ContactCatchConfig.ActiveDuration or 0.1) * 0.5 + runtime.ping
    local meleePos = targetRoot.Position + targetVelocity * meleeLead
    local tacklePos = targetRoot.Position + targetVelocity * runtime.ping

    local meleeReady = SETTINGS.autoMelee and now - runtime.lastMelee >= SETTINGS.meleeCooldown
        and flat(meleePos - root.Position).Magnitude <= SETTINGS.meleeRange
    local tackleReady = SETTINGS.autoTackle and now - runtime.lastTackle >= SETTINGS.tackleCooldown
        and flat(tacklePos - root.Position).Magnitude <= SETTINGS.tackleRange

    if SETTINGS.catcherAttackPriority == "Tackle First" then
        if tackleReady then
            pcall(TacklePrediction.request)
            runtime.lastTackle = now
            return
        end
        if meleeReady then
            runtime.meleeId += 1
            pcall(MeleeEvent.FireServer, MeleeEvent, runtime.meleeId)
            runtime.lastMelee = now
        end
    elseif SETTINGS.catcherAttackPriority == "Melee First" then
        if meleeReady then
            runtime.meleeId += 1
            pcall(MeleeEvent.FireServer, MeleeEvent, runtime.meleeId)
            runtime.lastMelee = now
            return
        end
        if tackleReady then
            pcall(TacklePrediction.request)
            runtime.lastTackle = now
        end
    else
        if targetVelocity.Magnitude >= 5 and tackleReady then
            pcall(TacklePrediction.request)
            runtime.lastTackle = now
        elseif meleeReady then
            runtime.meleeId += 1
            pcall(MeleeEvent.FireServer, MeleeEvent, runtime.meleeId)
            runtime.lastMelee = now
        elseif tackleReady then
            pcall(TacklePrediction.request)
            runtime.lastTackle = now
        end
    end
end

local function catcherStep(now, dt)
    if not isCatcherActive() then
        runtime.catcherTarget = nil
        runtime.catcherPath = Vector3.zero
        return
    end
    local root = getRoot()
    local hum = getHumanoid()
    if not root or not hum or hum.Health <= 0 or hum.PlatformStand or hum.Sit then
        return
    end
    refreshPing(now)
    local needsTarget = SETTINGS.catcherChase or SETTINGS.autoTackle or SETTINGS.autoMelee or SETTINGS.followTarget
    if not needsTarget then
        runtime.catcherTarget = nil
        runtime.catcherPath = Vector3.zero
        return
    end

    local target = selectCatcherTarget(now, root.Position)
    if not target then
        runtime.catcherTarget = nil
        return
    end
    local targetRoot = getRoot(target)
    if not targetRoot then
        runtime.catcherTarget = nil
        return
    end

    local velocity = catcherVelocity(target, now)
    local predicted = targetRoot.Position + velocity * SETTINGS.catcherPrediction
    local direction = catcherDirection(root, predicted, dt)

    if SETTINGS.catcherChase and direction.Magnitude > 0.05 then
        hum.AutoRotate = true
        hum:Move(direction, false)
    end

    if SETTINGS.autoTackle or SETTINGS.autoMelee then
        catcherAttack(target, now, root)
    end

    if SETTINGS.followTarget then
        local camera = workspace.CurrentCamera
        if camera then
            camera.CFrame = camera.CFrame:Lerp(
                CFrame.lookAt(camera.CFrame.Position, predicted + Vector3.new(0, 1.5, 0)),
                math.clamp(SETTINGS.cameraResponse, 0.01, 1)
            )
        end
    end
end

local function ensurePart(store, key, size, color, transparency)
    local part = store[key]
    if part and part.Parent then
        return part
    end
    part = Instance.new("Part")
    part.Name = "CoH_Utility"
    part.Shape = Enum.PartType.Ball
    part.Size = Vector3.new(size, size, size)
    part.Anchored = true
    part.CanCollide = false
    part.CanTouch = false
    part.CanQuery = false
    part.CastShadow = false
    part.Material = Enum.Material.ForceField
    part.Color = color
    part.Transparency = transparency
    part.Parent = workspace
    store[key] = part
    return part
end

local function cleanupVisuals()
    if visuals.goal and visuals.goal.Parent then
        visuals.goal:Destroy()
    end
    visuals.goal = nil
    for key, part in pairs(visuals.threats) do
        if part.Parent then
            part:Destroy()
        end
        visuals.threats[key] = nil
    end
    for key, part in pairs(visuals.hitboxes) do
        if part.Parent then
            part:Destroy()
        end
        visuals.hitboxes[key] = nil
    end
end

local function getGuiText(gui)
    if not gui then
        return ""
    end
    local ok, value = pcall(function()
        if gui:IsA("TextButton") or gui:IsA("TextLabel") then
            return gui.Text or ""
        end
        return gui:GetAttribute("Text") or ""
    end)
    return ok and tostring(value or "") or ""
end

local function wheelNameScore(gui, mode)
    if not gui or not gui:IsA("GuiButton") then
        return -math.huge
    end
    local name = string.lower(gui.Name or "")
    local text = string.lower(getGuiText(gui))
    local all = name .. " " .. text
    local score = 0

    if mode == "spin" then
        if all:find("spin", 1, true) then score += 100 end
        if all:find("free", 1, true) then score += 20 end
        if all:find("roll", 1, true) then score += 12 end
        if all:find("claim", 1, true) then score -= 25 end
        if all:find("close", 1, true) then score -= 80 end
        if all:find("back", 1, true) then score -= 60 end
    else
        if all:find("spin", 1, true) then score += 90 end
        if all:find("wheel", 1, true) then score += 70 end
        if all:find("daily", 1, true) then score += 10 end
        if all:find("emote", 1, true) then score -= 100 end
        if all:find("close", 1, true) then score -= 50 end
    end

    if not gui.Visible then score -= 100 end
    if not gui.Active then score -= 20 end
    return score
end

local function findWheelButton(mode)
    local playerGui = LocalPlayer:FindFirstChildOfClass("PlayerGui")
    if not playerGui then
        return nil
    end

    local best, bestScore = nil, -math.huge
    local ok, descendants = pcall(function()
        return playerGui:GetDescendants()
    end)
    if not ok then
        return nil
    end

    for _, gui in ipairs(descendants) do
        if gui:IsA("GuiButton") and gui.Visible and gui.Active then
            local score = wheelNameScore(gui, mode)
            if score > bestScore then
                best, bestScore = gui, score
            end
        end
    end

    if bestScore >= (mode == "spin" and 90 or 70) then
        return best
    end

    return nil
end


local function guiContextText(gui, depth)
    local parts = {}
    local current = gui
    local levels = depth or 5
    for _ = 1, levels do
        if not current then
            break
        end
        local name = tostring(current.Name or "")
        local text = getGuiText(current)
        if name ~= "" then
            table.insert(parts, name)
        end
        if text ~= "" then
            table.insert(parts, text)
        end
        current = current.Parent
    end
    return string.lower(table.concat(parts, " "))
end

local function getGuiLabelText(gui)
    local direct = getGuiText(gui)
    if direct ~= "" then
        return direct
    end

    local ok, descendants = pcall(function()
        return gui:GetDescendants()
    end)
    if not ok then
        return ""
    end

    for index = 1, math.min(#descendants, 12) do
        local child = descendants[index]
        if child:IsA("TextLabel") or child:IsA("TextButton") then
            local text = tostring(child.Text or "")
            if text ~= "" then
                return text
            end
        end
    end

    return ""
end

local function requestJourneyState(force)
    local now = os.clock()
    if not force and now - runtime.journeyRequestAt < 1.5 then
        return false
    end
    runtime.journeyRequestAt = now
    local ok = pcall(function()
        JourneyEvent:FireServer("Get")
    end)
    if not ok then
        runtime.journeyStatus = "Journey state request failed"
        return false
    end
    return true
end

local function journeyClaimableCount()
    if not runtime.journeyLoaded then
        return 0
    end

    local trackId = JourneyConfig.TrackId
    local tier = math.max(1, tonumber(runtime.journeyTier) or 1)
    local premium = runtime.journeyPremium == true
    local claims = runtime.journeyClaims or {}
    local count = 0

    for index = 1, tier do
        local rewardTier = JourneyConfig.Rewards[index]
        if rewardTier then
            local freeReward = rewardTier.Free
            if freeReward and claims[trackId .. ":" .. tostring(freeReward.Key)] ~= true then
                count += 1
            end
            if premium then
                local premiumReward = rewardTier.Premium
                if premiumReward and claims[trackId .. ":" .. tostring(premiumReward.Key)] ~= true then
                    count += 1
                end
            end
        end
    end

    return count
end

local function journeyClaimOnce(manual)
    if not SETTINGS.autoClaimJourneyRewards and not manual then
        runtime.journeyStatus = "disabled"
        return false
    end

    if LocalPlayer:GetAttribute("InMatch") == true then
        runtime.journeyStatus = "waiting for lobby"
        return false
    end

    local now = os.clock()
    if now < (runtime.journeyNextClaimAt or -math.huge) then
        return false
    end

    if runtime.journeyClaimInFlight then
        runtime.journeyStatus = "claim request pending"
        return false
    end

    if not runtime.journeyLoaded then
        runtime.journeyManualPending = manual == true or runtime.journeyManualPending
        runtime.journeyStatus = "loading journey state"
        requestJourneyState(true)
        return false
    end

    local seasonId = runtime.journeySeasonId or JourneyConfig.SeasonId
    if type(seasonId) ~= "string" or seasonId == "" then
        runtime.journeyStatus = "season unavailable"
        return false
    end

    local available = journeyClaimableCount()
    if available <= 0 and not manual then
        runtime.journeyStatus = "no claimable rewards"
        runtime.journeyNextClaimAt = now + 2.5
        return false
    end

    runtime.journeyClaimInFlight = true
    runtime.journeyManualPending = false
    runtime.journeyLastClaimAt = now
    runtime.journeyNextClaimAt = now + 2.5
    runtime.journeyStatus = available > 0 and string.format("claiming %d reward%s", available, available == 1 and "" or "s") or "claiming available rewards"

    local fired = pcall(function()
        JourneyEvent:FireServer("ClaimAll", nil, seasonId)
    end)

    if not fired then
        runtime.journeyClaimInFlight = false
        runtime.journeyStatus = "claim request failed"
        runtime.journeyNextClaimAt = now + 1
        return false
    end

    task.delay(1.25, function()
        if runtime.journeyClaimInFlight then
            runtime.journeyClaimInFlight = false
            runtime.journeyStatus = "waiting for confirmation"
            requestJourneyState(true)
        end
    end)

    return true
end

local function getSelectedMapSlot()
    local selections = SETTINGS.mapVoteSelections or {}
    local selected = selections[1]
    if selected and table.find(MAP_VOTE_SLOT_IDS, selected) then
        return selected
    end
    return nil
end

local function setDebugError(value)
    runtime.debugLastError = tostring(value or "")
    runtime.debugLastErrorAt = os.clock()
end

local function getDebugGui()
    if runtime.debugGui and runtime.debugGui.Parent and runtime.debugLabel and runtime.debugLabel.Parent then
        return runtime.debugGui, runtime.debugLabel
    end

    local playerGui = LocalPlayer:FindFirstChildOfClass("PlayerGui") or LocalPlayer:WaitForChild("PlayerGui", 5)
    if not playerGui then
        return nil, nil
    end

    local old = playerGui:FindFirstChild("CoH_FullDebug")
    if old then
        old:Destroy()
    end

    local gui = Instance.new("ScreenGui")
    gui.Name = "CoH_FullDebug"
    gui.ResetOnSpawn = false
    gui.IgnoreGuiInset = true
    gui.DisplayOrder = 9999
    gui.Enabled = false
    gui.Parent = playerGui

    local frame = Instance.new("Frame")
    frame.Name = "Panel"
    frame.Size = UDim2.fromOffset(470, 360)
    frame.Position = UDim2.fromOffset(10, 70)
    frame.BackgroundTransparency = 0.12
    frame.BackgroundColor3 = Color3.fromRGB(10, 14, 22)
    frame.BorderSizePixel = 0
    frame.Parent = gui

    local corner = Instance.new("UICorner")
    corner.CornerRadius = UDim.new(0, 8)
    corner.Parent = frame

    local label = Instance.new("TextLabel")
    label.Name = "Status"
    label.Size = UDim2.new(1, -20, 1, -20)
    label.Position = UDim2.fromOffset(10, 10)
    label.BackgroundTransparency = 1
    label.TextColor3 = Color3.fromRGB(235, 240, 250)
    label.TextXAlignment = Enum.TextXAlignment.Left
    label.TextYAlignment = Enum.TextYAlignment.Top
    label.Font = Enum.Font.Code
    label.TextSize = 12
    label.TextWrapped = false
    label.Text = "Oziohub | FULL DEBUG"
    label.Parent = frame

    runtime.debugGui = gui
    runtime.debugLabel = label
    return gui, label
end

local function updateDebugPanel(now)
    if not runtime.debugEnabled then
        if runtime.debugGui then
            runtime.debugGui.Enabled = false
        end
        return
    end

    local gui, label = getDebugGui()
    if not gui or not label then
        return
    end

    gui.Enabled = true

    local character = getCharacter()
    local humanoid = getHumanoid()
    local root = getRoot()
    local position = root and root.Position or Vector3.zero
    local goalDistance = runtime.goal and flat(runtime.goal - position).Magnitude or -1
    local speed = humanoid and humanoid.WalkSpeed or -1
    local health = humanoid and humanoid.Health or -1
    local safeA = safezone.a and safezone.a.name or "nil"
    local safeB = safezone.b and safezone.b.name or "nil"
    local threat = runtime.threats[1]
    local errorText = runtime.debugLastError ~= nil and runtime.debugLastError ~= "" and runtime.debugLastError or "none"
    local errorAge = runtime.debugLastErrorAt > 0 and math.max(0, now - runtime.debugLastErrorAt) or -1
    local wheelStateAge = runtime.wheelLastStateAt > 0 and math.max(0, now - runtime.wheelLastStateAt) or -1
    local journeyAge = runtime.journeyLastStateAt > 0 and math.max(0, now - runtime.journeyLastStateAt) or -1
    local mapAge = runtime.mapVoteLastStateAt > 0 and math.max(0, now - runtime.mapVoteLastStateAt) or -1
    local selectedMap = getSelectedMapSlot() or "none"
    local path = runtime.path or Vector3.zero

    label.Text = table.concat({
        "Oziohub | FULL DEBUG",
        string.format("Role=%s | RunState=%s | InMatch=%s | ClientReady=%s", tostring(getRole()), tostring(getRunState()), tostring(LocalPlayer:GetAttribute("InMatch")), tostring(LocalPlayer:GetAttribute("ClientReady"))),
        string.format("MovementLocked=%s | Ragdolled=%s | GearMotion=%s | HP=%.1f | WalkSpeed=%.1f", tostring(character and character:GetAttribute("MovementLocked")), tostring(character and character:GetAttribute("Ragdolled")), tostring(character and character:GetAttribute("GearMotion")), health, speed),
        string.format("Position=%.1f, %.1f, %.1f | GoalMode=%s | GoalDistance=%.1f", position.X, position.Y, position.Z, tostring(runtime.goalMode), goalDistance),
        string.format("SafeA=%s | SafeB=%s | Cached=%s", safeA, safeB, tostring(safezone.cached)),
        string.format("Route=%s -> %s | Complete=%s | Stuck=%s | EdgeRisk=%s", tostring(runtime.routeStartSide or "none"), tostring(runtime.routeTargetSide or "none"), tostring(runtime.routeComplete), tostring(runtime.stuck), tostring(runtime.edgeRisk)),
        string.format("Assist=%s | Revive=%s | Gem=%s | SideGap=%s", tostring(runtime.assistMode or "none"), runtime.reviveStarted and "started" or "idle", runtime.gemTarget and runtime.gemTarget.Parent and runtime.gemTarget.Name or "none", runtime.sideGapReason ~= "" and runtime.sideGapReason or "none"),
        string.format("Threats=%d | Threat0=%s", #runtime.threats, threat and string.format("d=%.1f gap=%.1f t=%.2f risk=%s", threat.distance or -1, threat.interceptGap or -1, threat.interceptTime or -1, tostring(threat.collisionRisk)) or "none"),
        string.format("Dash=%s | DashCount=%s | Path=%.2f, %.2f", tostring(runtime.dashStatus), tostring(runtime.dashLastCount), path.X, path.Z),
        string.format("CatcherTarget=%s | Chase=%s | Tackle=%s | Melee=%s", runtime.catcherTarget and runtime.catcherTarget.Name or "none", tostring(SETTINGS.catcherChase), tostring(SETTINGS.autoTackle), tostring(SETTINGS.autoMelee)),
        string.format("Wheel=%s | Credits=%d | Spins=%d | Spinning=%s | StateAge=%.2fs", tostring(runtime.wheelStatus), math.floor(tonumber(runtime.wheelCredits) or 0), tonumber(runtime.wheelSpinCount) or 0, tostring(runtime.wheelSpinning), wheelStateAge),
        string.format("Journey=%s | Loaded=%s | Tier=%d | Claims=%d | StateAge=%.2fs", tostring(runtime.journeyStatus), tostring(runtime.journeyLoaded), tonumber(runtime.journeyTier) or 1, tonumber(runtime.journeyClaimCount) or 0, journeyAge),
        string.format("MapVote=%s | Phase=%s | Selected=%s | StateAge=%.2fs", tostring(runtime.mapVoteStatus), tostring(runtime.mapVotePhase), selectedMap, mapAge),
        string.format("AutoRun=%s | AutoSpin=%s | AutoClaim=%s | AutoVote=%s", tostring(SETTINGS.runnerEnabled), tostring(SETTINGS.autoSpinWheel), tostring(SETTINGS.autoClaimJourneyRewards), tostring(SETTINGS.autoMapVote)),
        string.format("Ping=%d ms | LastErrorAge=%.2fs | LastError=%s", math.floor((tonumber(runtime.ping) or 0) * 1000 + 0.5), errorAge, errorText),
    }, "\n")
end


local function readMapVoteState()
    if not MapVoteState or not MapVoteState:IsA("StringValue") then
        runtime.mapVoteOpen = false
        runtime.mapVotePhase = "Unavailable"
        return nil
    end

    local ok, state = pcall(function()
        return HttpService:JSONDecode(MapVoteState.Value)
    end)
    if not ok or type(state) ~= "table" then
        runtime.mapVoteOpen = false
        runtime.mapVotePhase = "Waiting"
        return nil
    end

    local options = type(state.options) == "table" and state.options or {}
    local ids = {}
    for index = 1, math.min(#options, #MAP_VOTE_SLOT_IDS) do
        local option = options[index]
        if type(option) == "table" then
            ids[index] = option.id or option.Id or option.key or option.Key
        end
    end

    runtime.mapVoteOptionIds = ids
    runtime.mapVoteToken = state.token
    runtime.mapVotePhase = tostring(state.phase or "Waiting")
    runtime.mapVoteOpen = runtime.mapVotePhase == "Voting"
    runtime.mapVoteLastStateAt = os.clock()
    return state
end

local function mapVoteOnce(manual)
    if not SETTINGS.autoMapVote and not manual then
        runtime.mapVoteStatus = "disabled"
        return false
    end

    if LocalPlayer:GetAttribute("InMatch") == true then
        runtime.mapVoteStatus = "waiting for lobby"
        return false
    end

    if LocalPlayer:GetAttribute("ClientReady") ~= true then
        runtime.mapVoteStatus = "waiting for client"
        return false
    end

    if LocalPlayer:GetAttribute("AFK") == true then
        runtime.mapVoteStatus = "waiting - AFK"
        return false
    end

    if Session:GetAttribute("GlobalPaused") == true then
        runtime.mapVoteStatus = "paused"
        return false
    end

    local state = readMapVoteState()
    if not state or runtime.mapVotePhase ~= "Voting" then
        runtime.mapVoteStatus = "waiting for vote"
        return false
    end

    local selected = getSelectedMapSlot()
    if not selected then
        runtime.mapVoteStatus = "choose Map 1, Map 2, or Map 3"
        return false
    end

    local index = table.find(MAP_VOTE_SLOT_IDS, selected)
    local optionId = index and runtime.mapVoteOptionIds[index]
    if optionId == nil then
        runtime.mapVoteStatus = selected .. " is unavailable"
        return false
    end

    local token = runtime.mapVoteToken
    if token == nil then
        runtime.mapVoteStatus = "vote token unavailable"
        return false
    end

    local votes = type(state.votes) == "table" and state.votes or nil
    local currentVote = votes and (votes[tostring(LocalPlayer.UserId)] or votes[LocalPlayer.UserId]) or nil
    if currentVote == optionId then
        runtime.mapVoteStatus = selected .. " already selected"
        return true
    end

    local now = os.clock()
    if now - runtime.mapVoteLastActionAt < 0.75 then
        return false
    end

    local fired = pcall(function()
        MapVoteEvent:FireServer("Vote", optionId, token)
    end)

    if not fired then
        runtime.mapVoteStatus = "vote request failed"
        return false
    end

    runtime.mapVoteLastActionAt = now
    runtime.mapVoteStatus = selected .. " vote sent"
    if SETTINGS.mapVoteAnnounce then
        pcall(function()
            WindUI:Notify({
                Title = "Map Vote",
                Content = selected .. " selected.",
                Duration = 2.5,
                Icon = "map",
            })
        end)
    end
    return true
end

local function wheelServerNow()
    local ok, value = pcall(function()
        return workspace:GetServerTimeNow()
    end)
    if ok and type(value) == "number" then
        return value
    end
    return os.time()
end

local function wheelCooldownRemaining()
    local nextFreeAt = tonumber(runtime.wheelNextFreeAt) or 0
    if nextFreeAt <= 0 then
        return 0
    end
    if nextFreeAt < 100000000 then
        return math.max(0, nextFreeAt)
    end
    return math.max(0, nextFreeAt - wheelServerNow())
end

local function wheelUpdateStatus(status)
    runtime.wheelStatus = tostring(status or runtime.wheelStatus or "waiting")
    runtime.wheelStatusAt = os.clock()
end

local function wheelRequestState(now, force)
    if not force and now - runtime.wheelStateRequestAt < 1.25 then
        return false
    end

    runtime.wheelStateRequestAt = now
    local ok = pcall(function()
        SpinWheelEvent:FireServer("State")
    end)
    runtime.wheelEventReady = ok

    if ok then
        return true
    end

    wheelUpdateStatus("state request failed")
    return false
end

local function wheelApplyState(payload)
    if type(payload) ~= "table" then
        return
    end
    runtime.wheelCredits = tonumber(payload.credits) or 0
    runtime.wheelNextFreeAt = tonumber(payload.nextFreeAt) or 0
    runtime.wheelPurchasesAvailable = payload.purchasesAvailable == true
    runtime.wheelDiscountAvailable = payload.discountAvailable == true
end

local function wheelCanSpinNow(manual)
    if not SETTINGS.autoSpinWheel and not manual then
        return false, "disabled"
    end

    if LocalPlayer:GetAttribute("InMatch") == true then
        return false, "cannot spin in match"
    end

    if runtime.wheelSpinning then
        return false, "spinning"
    end

    local now = os.clock()
    local nextAttempt = tonumber(runtime.wheelNextAttemptAt) or -math.huge
    if now < nextAttempt then
        return false, string.format("cooldown %.1fs", nextAttempt - now)
    end

    local minimum = math.max(1, math.floor(tonumber(SETTINGS.wheelMinimumCredits) or 1))
    local credits = math.floor(tonumber(runtime.wheelCredits) or 0)
    if credits < minimum then
        return false, string.format("not enough credits (%d/%d)", credits, minimum)
    end

    return true, "ready"
end

local function wheelNotify(title, content, icon)
    if not SETTINGS.wheelAnnounce then
        return
    end
    pcall(function()
        WindUI:Notify({
            Title = title,
            Content = content,
            Duration = 2.5,
            Icon = icon or "circle-dot",
        })
    end)
end

local function wheelSpinOnce(manual)
    local allowed, reason = wheelCanSpinNow(manual)
    if not allowed then
        wheelUpdateStatus(reason)
        return false
    end

    local now = os.clock()
    local delay = math.clamp(tonumber(SETTINGS.wheelSpinInterval) or 6, 5.5, 30)
    runtime.wheelSpinning = true
    runtime.wheelSpinRequestAt = now
    runtime.wheelNextAttemptAt = now + delay
    runtime.wheelActionAt = now
    runtime.wheelSpinCount += 1
    wheelUpdateStatus("spin requested")

    local fired = pcall(function()
        SpinWheelEvent:FireServer("Spin")
    end)

    if not fired then
        runtime.wheelSpinning = false
        runtime.wheelNextAttemptAt = now + 1
        wheelUpdateStatus("spin request failed")
        return false
    end

    if manual then
        wheelNotify("Wheel", "Spin request sent.", "zap")
    else
        wheelNotify("Auto Spin", string.format("Spin #%d fired.", runtime.wheelSpinCount), "circle-dot")
    end

    task.delay(0.85, function()
        runtime.wheelSpinning = false
        wheelRequestState(os.clock(), true)
    end)

    return true
end

local function autoSpinWheelStep(now)
    if not SETTINGS.autoSpinWheel then
        wheelUpdateStatus("disabled")
        return
    end

    wheelRequestState(now, false)

    local allowed, reason = wheelCanSpinNow(false)
    if allowed then
        wheelSpinOnce(false)
        return
    end

    wheelUpdateStatus(reason)
end

local function utilityStep(now)
    if now - runtime.utilityTick < 0.25 then
        return
    end
    runtime.utilityTick = now
    if SETTINGS.autoSpinWheel then
        autoSpinWheelStep(now)
    end
    if SETTINGS.showThreats or SETTINGS.showThreatUtility then
        if isRunnerActive() then
            local root = getRoot()
            local threats = root and updateThreats(now, root.Position) or {}
            for i = 1, math.min(#threats, 8) do
                local threat = threats[i]
                local part = ensurePart(visuals.threats, i, threat.danger * 2, Color3.fromRGB(255, 90, 90), 0.82)
                part.CFrame = CFrame.new(threat.position)
            end
            for i = #threats + 1, #visuals.threats do
                local part = visuals.threats[i]
                if part and part.Parent then
                    part:Destroy()
                end
                visuals.threats[i] = nil
            end
        end
    else
        for i, part in pairs(visuals.threats) do
            if part.Parent then
                part:Destroy()
            end
            visuals.threats[i] = nil
        end
    end

    local goalEnabled = SETTINGS.showGoal and SETTINGS.showGoalUtility
    if goalEnabled and runtime.goal then
        local part = visuals.goal
        if not part or not part.Parent then
            part = Instance.new("Part")
            part.Name = "CoH_Goal"
            part.Shape = Enum.PartType.Ball
            part.Size = Vector3.new(2.5, 2.5, 2.5)
            part.Anchored = true
            part.CanCollide = false
            part.CanTouch = false
            part.CanQuery = false
            part.CastShadow = false
            part.Material = Enum.Material.ForceField
            part.Color = Color3.fromRGB(80, 200, 255)
            part.Transparency = 0.45
            part.Parent = workspace
            visuals.goal = part
        end
        part.CFrame = CFrame.new(runtime.goal)
    elseif visuals.goal then
        if visuals.goal.Parent then
            visuals.goal:Destroy()
        end
        visuals.goal = nil
    end

    if SETTINGS.showHitboxes then
        local role = getRole()
        local seen = {}
        for _, player in ipairs(Players:GetPlayers()) do
            if player ~= LocalPlayer and player.Parent then
                local targetRole = player:GetAttribute("GameRole")
                local relevant = (role == "Runner" and targetRole == "Catcher") or (role == "Catcher" and targetRole == "Runner")
                local root = relevant and getRoot(player) or nil
                if root then
                    seen[player] = true
                    local part = visuals.hitboxes[player]
                    if not part or not part.Parent then
                        part = Instance.new("Part")
                        part.Name = "CoH_Hitbox"
                        part.Shape = Enum.PartType.Ball
                        part.Anchored = true
                        part.CanCollide = false
                        part.CanTouch = false
                        part.CanQuery = false
                        part.CastShadow = false
                        part.Material = Enum.Material.ForceField
                        part.Color = Color3.fromRGB(255, 180, 80)
                        part.Transparency = 0.75
                        part.Parent = workspace
                        visuals.hitboxes[player] = part
                    end
                    local radius = ContactCatchConfig.RunnerRadius * 2
                    part.Size = Vector3.new(radius, radius, radius)
                    part.CFrame = CFrame.new(root.Position)
                end
            end
        end
        for player, part in pairs(visuals.hitboxes) do
            if not seen[player] then
                if part.Parent then
                    part:Destroy()
                end
                visuals.hitboxes[player] = nil
            end
        end
    else
        for player, part in pairs(visuals.hitboxes) do
            if part.Parent then
                part:Destroy()
            end
            visuals.hitboxes[player] = nil
        end
    end
end

ArmoryEvent.OnClientEvent:Connect(function(kind, state)
    if kind == "State" and type(state) == "table" then
        runtime.armory = state
        runtime.armory.abilities = runtime.armory.abilities or {}
    end
end)

RescueEvent.OnClientEvent:Connect(function(kind, id)
    if kind == "Cancelled" and runtime.reviveTarget and runtime.reviveTarget.UserId == id then
        runtime.reviveStarted = false
        runtime.reviveStartAt = 0
    end
end)

LocalPlayer.CharacterAdded:Connect(function()
    runtime.profile = nil
    runtime.profileRole = nil
    runtime.lastMovePosition = nil
    runtime.moveCommandAt = -math.huge
    runtime.goal = nil
    runtime.goalMode = "SafeZone"
    runtime.goalSide = nil
    runtime.routeActive = false
    runtime.routeComplete = false
    runtime.routeStartSide = nil
    runtime.routeTargetSide = nil
    runtime.routeCompletePosition = nil
    runtime.routeCompleteAt = -math.huge
    runtime.gemTarget = nil
    runtime.reviveTarget = nil
    runtime.reviveStarted = false
    runtime.reviveStartAt = 0
    runtime.threatHistory = {}
    runtime.threats = {}
    runtime.catchers = {}
    runtime.catcherTargets = {}
    runtime.dashAt = -math.huge
    runtime.dashStatus = "idle"
    runtime.dashLastRequestAt = -math.huge
    runtime.dashLastCount = nil
    runtime.edgeRecoveryDirection = Vector3.zero
    runtime.edgeRecoveryUntil = -math.huge
    runtime.stuckRecoveryDirection = Vector3.zero
    runtime.stuckRecoveryUntil = -math.huge
    runtime.armoryAt = -math.huge
    runtime.armory = {loaded = false, abilities = {}}
    runtime.wheelScanAt = -math.huge
    runtime.wheelActionAt = -math.huge
    runtime.wheelStatus = SETTINGS.autoSpinWheel and "starting" or "disabled"
    runtime.wheelLastButton = nil
    runtime.wheelCredits = 0
    runtime.wheelNextFreeAt = 0
    runtime.wheelPurchasesAvailable = false
    runtime.wheelDiscountAvailable = false
    runtime.wheelStateRequestAt = -math.huge
    runtime.wheelSpinRequestAt = -math.huge
    runtime.wheelNextAttemptAt = -math.huge
    runtime.wheelEventReady = false
    runtime.wheelSpinning = false
    runtime.wheelLastStateAt = -math.huge
    runtime.wheelStatusAt = -math.huge
    runtime.wheelMinimumCredits = 1
end)

do
    local handle = Game:FindFirstChild("ActiveMap")
    if handle and handle:IsA("ObjectValue") then
        handle.Changed:Connect(function()
            safezone.cached = false
            safezone.map = nil
            runtime.mapCache = nil
            runtime.mapCacheAt = -math.huge
            runtime.safeCheckAt = -math.huge
            runtime.safeCheckPosition = nil
            edgeRayCache.map = nil
            edgeRayCache.params = nil
            runtime.goal = nil
            runtime.goalSide = nil
            runtime.routeActive = false
            runtime.routeComplete = false
            runtime.routeStartSide = nil
            runtime.routeTargetSide = nil
            runtime.routeCompletePosition = nil
            runtime.routeCompleteAt = -math.huge
        end)
    end
end

pcall(function()
    ArmoryEvent:FireServer("Get")
end)

task.spawn(function()
    pcall(function()
        local GemEvent = COH:WaitForChild("Collectibles"):WaitForChild("GemEvent")
        GemEvent:FireServer("Sync")
    end)
end)

SpinWheelEvent.OnClientEvent:Connect(function(kind, payload)
    if kind == "State" and type(payload) == "table" then
        wheelApplyState(payload)
        runtime.wheelLastStateAt = os.clock()
        if payload.result or payload.message then
            runtime.wheelSpinning = false
        end
        if SETTINGS.autoSpinWheel then
            local credits = tonumber(runtime.wheelCredits) or 0
            local minimum = math.max(1, math.floor(tonumber(SETTINGS.wheelMinimumCredits) or 1))
            if credits >= minimum then
                wheelUpdateStatus("ready")
            else
                wheelUpdateStatus(string.format("waiting - credits %d/%d", math.floor(credits), minimum))
            end
            task.defer(function()
                if SETTINGS.autoSpinWheel and LocalPlayer:GetAttribute("InMatch") ~= true then
                    autoSpinWheelStep(os.clock())
                end
            end)
        end
        return
    end

    if kind == "PromptProduct" then
        runtime.wheelPurchasesAvailable = true
        wheelUpdateStatus("free credits unavailable")
        return
    end

    if type(kind) == "table" and payload == nil then
        wheelApplyState(kind)
        if SETTINGS.autoSpinWheel then
            wheelUpdateStatus("state refreshed")
            task.defer(function()
                autoSpinWheelStep(os.clock())
            end)
        end
    end
end)

local function isLobbyForAFKOverride()
    return SETTINGS.disableBuiltinAFK and LocalPlayer:GetAttribute("InMatch") ~= true
end

local function forceBuiltinAFKOff(reason)
    if not isLobbyForAFKOverride() then
        runtime.afkOverrideInLobby = false
        if not SETTINGS.disableBuiltinAFK then
            runtime.afkOverrideStatus = "disabled"
        end
        return false
    end

    runtime.afkOverrideInLobby = true

    local now = os.clock()
    if reason ~= "attribute" and now - runtime.afkOverrideLastRequestAt < runtime.afkOverrideRequestInterval then
        return false
    end

    local ok, err = pcall(function()
        PlayerPreferences:FireServer("SetAFK", false)
    end)

    runtime.afkOverrideLastRequestAt = now

    if ok then
        runtime.afkOverrideRequestCount = (runtime.afkOverrideRequestCount or 0) + 1
        runtime.afkOverrideStatus = "AFK OFF"
        return true
    end

    runtime.afkOverrideStatus = "request failed"
    return false
end

LocalPlayer:GetAttributeChangedSignal("AFK"):Connect(function()
    if not SETTINGS.disableBuiltinAFK then
        runtime.afkOverrideStatus = "disabled"
        return
    end

    if LocalPlayer:GetAttribute("InMatch") == true then
        runtime.afkOverrideInLobby = false
        runtime.afkOverrideStatus = "in match"
        return
    end

    if LocalPlayer:GetAttribute("AFK") == true then
        forceBuiltinAFKOff("attribute")
    else
        runtime.afkOverrideStatus = "AFK OFF confirmed"
    end
end)

LocalPlayer:GetAttributeChangedSignal("InMatch"):Connect(function()
    if not SETTINGS.disableBuiltinAFK then
        return
    end

    if LocalPlayer:GetAttribute("InMatch") == true then
        runtime.afkOverrideInLobby = false
        runtime.afkOverrideStatus = "in match"
    else
        runtime.afkOverrideInLobby = true
        runtime.afkOverrideLastRequestAt = -math.huge
        forceBuiltinAFKOff("lobby")
    end
end)

task.spawn(function()
    while LocalPlayer.Parent do
        task.wait(0.5)
        if SETTINGS.disableBuiltinAFK then
            if LocalPlayer:GetAttribute("InMatch") == true then
                runtime.afkOverrideInLobby = false
                runtime.afkOverrideStatus = "in match"
            else
                runtime.afkOverrideInLobby = true
                forceBuiltinAFKOff("poll")
            end
        end
    end
end)

WindUI = loadstring(game:HttpGet("https://github.com/Footagesus/WindUI/releases/latest/download/main.lua"))()

local viewport = workspace.CurrentCamera and workspace.CurrentCamera.ViewportSize or Vector2.new(520, 860)
local windowWidth = math.max(280, math.min(520, viewport.X - 24))
local windowHeight = math.max(360, math.min(860, viewport.Y - 48))

local Window = WindUI:CreateWindow({
    Title = "Oziohub",
    Icon = "bird",
    Author = "Oziohub",
    Folder = "HussValley",
    Size = UDim2.fromOffset(windowWidth, windowHeight),
    Transparent = true,
    Theme = "Dark",
    ToggleKey = Enum.KeyCode.RightShift,
})

Window:Tag({Title = "Oziohub", Color = Color3.fromRGB(70, 205, 180)})

-- Notification gate (controlled from Settings tab)
SETTINGS.notifications = true
Hub.rawNotify = WindUI.Notify
WindUI.Notify = function(self, opts)
    if SETTINGS.notifications == false then
        return
    end
    return Hub.rawNotify(self, opts)
end

-- Element registry: every Toggle/Slider/Dropdown/... is recorded so the Settings tab
-- can save/load configs and reset everything to defaults.
function Hub.register(key, element, default)
    if element ~= nil then
        table.insert(Hub.registry, {key = key, element = element, default = default})
    end
end

function Hub.trackTab(tab, tabName)
    local TRACKED_KINDS = {"Toggle", "Slider", "Dropdown", "Input", "Keybind", "Colorpicker"}
    local used = {}
    for _, kind in ipairs(TRACKED_KINDS) do
        local original = tab[kind]
        if type(original) == "function" then
            tab[kind] = function(self, cfg)
                local element = original(self, cfg)
                if type(cfg) == "table" and type(cfg.Title) == "string" and element ~= nil then
                    local base = tabName .. "_" .. cfg.Title
                    local key, n = base, 1
                    while used[key] do
                        n = n + 1
                        key = base .. "_" .. n
                    end
                    used[key] = true
                    local default = cfg.Value
                    if kind == "Slider" then
                        default = type(default) == "table" and default.Default or nil
                    elseif kind == "Colorpicker" then
                        default = cfg.Default
                    end
                    Hub.register(key, element, default)
                end
                return element
            end
        end
    end
    return tab
end

Hub.rawTab = Window.Tab
Window.Tab = function(self, cfg)
    local tab = Hub.rawTab(self, cfg)
    return Hub.trackTab(tab, type(cfg) == "table" and cfg.Title or "Tab")
end

local RunnerTab = Window:Tab({Title = "Runner", Icon = "footprints"})

local RunnerStatusParagraph = RunnerTab:Paragraph({
    Title = "Runner Status",
    Desc = "Role: Lobby\nState: Idle\nGoal: None",
})

RunnerTab:Section({Title = "Movement"})

RunnerTab:Toggle({
    Title = "Auto Run",
    Desc = "Automatically travel between Safe Zones with threat and edge checks.",
    Icon = "play",
    Type = "Checkbox",
    Value = true,
    Callback = function(v)
        SETTINGS.runnerEnabled = v == true
        if not SETTINGS.runnerEnabled then
            runtime.path = Vector3.zero
            runtime.goal = nil
            runtime.assistMode = nil
            runtime.assistTarget = nil
            runtime.sideGapDirection = Vector3.zero
            runtime.sideGapUntil = -math.huge
            cancelRevive()
        end
    end,
})

RunnerTab:Toggle({
    Title = "Auto Revive Players",
    Desc = "Move to a downed Runner and complete the real revive hold before continuing.",
    Icon = "heart-pulse",
    Type = "Checkbox",
    Value = true,
    Callback = function(v)
        SETTINGS.autoRevive = v == true
        if not v then
            cancelRevive()
        end
    end,
})

RunnerTab:Toggle({
    Title = "Runner Speed Override",
    Desc = "Multiply the game's current Runner movement speed without replacing its acceleration or dash system.",
    Icon = "gauge",
    Type = "Checkbox",
    Value = false,
    Callback = function(v)
        SETTINGS.customSpeed = v == true
        if not SETTINGS.customSpeed then
            restoreNativeWalkSpeed()
        end
    end,
})

RunnerTab:Slider({
    Title = "Runner Speed Multiplier",
    Desc = "1.0x keeps the native speed; maximum is 2.0x.",
    Step = 0.05,
    Value = {Min = 1.0, Max = 2.0, Default = 1.0},
    Callback = function(v)
        SETTINGS.speedMultiplier = math.clamp(tonumber(v) or 1, 1, 2)
    end,
})

RunnerTab:Section({Title = "Collection and Safety"})

RunnerTab:Toggle({
    Title = "Revive Before Gems",
    Desc = "Prioritize downed players before collecting Gems.",
    Icon = "list-checks",
    Type = "Checkbox",
    Value = true,
    Callback = function(v)
        SETTINGS.reviveBeforeGems = v == true
    end,
})

RunnerTab:Toggle({
    Title = "Auto Collect Gems",
    Desc = "Collect visible Runner Gems, then return to the Safe Zone route when none remain.",
    Icon = "gem",
    Type = "Checkbox",
    Value = true,
    Callback = function(v)
        SETTINGS.autoGems = v == true
        if not v then
            runtime.gemTarget = nil
        end
    end,
})

RunnerTab:Toggle({
    Title = "Avoid Catchers",
    Desc = "Predict nearby Catchers and bend the route away from their projected path.",
    Icon = "shield",
    Type = "Checkbox",
    Value = true,
    Callback = function(v)
        SETTINGS.avoidCatchers = v == true
    end,
})

RunnerTab:Toggle({
    Title = "Auto Dash",
    Desc = "Use the equipped Runner ability before a Catcher reaches the predicted collision area.",
    Icon = "zap",
    Type = "Checkbox",
    Value = true,
    Callback = function(v)
        SETTINGS.autoDash = v == true
    end,
})

RunnerTab:Slider({
    Title = "Runner Threat Prediction",
    Desc = "How far ahead Catcher movement is predicted for Runner avoidance.",
    Step = 0.05,
    Value = {Min = 0.25, Max = 1.1, Default = 0.65},
    Callback = function(v)
        SETTINGS.predictionTime = math.clamp(tonumber(v) or 0.65, 0.25, 1.1)
    end,
})

RunnerTab:Slider({
    Title = "Emergency Threat Distance",
    Desc = "Distance at which emergency avoidance becomes more aggressive.",
    Step = 1,
    Value = {Min = 8, Max = 25, Default = 15},
    Callback = function(v)
        SETTINGS.panicDistance = math.clamp(tonumber(v) or 15, 8, 25)
    end,
})

RunnerTab:Section({Title = "Movement"})

RunnerTab:Toggle({
    Title = "Smooth Direction Changes",
    Desc = "Blend turns to reduce sudden movement changes.",
    Icon = "rotate-cw",
    Type = "Checkbox",
    Value = true,
    Callback = function(v)
        SETTINGS.smoothMovement = v == true
    end,
})

RunnerTab:Toggle({
    Title = "Emergency Safe Zone",
    Desc = "When movement stalls under heavy pressure, temporarily favor the nearest Safe Zone.",
    Icon = "life-buoy",
    Type = "Checkbox",
    Value = true,
    Callback = function(v)
        SETTINGS.emergencySafeZone = v == true
    end,
})

RunnerTab:Slider({
    Title = "Avoidance Strength",
    Desc = "How strongly the route moves away from projected Catcher paths.",
    Step = 0.1,
    Value = {Min = 0.5, Max = 2.5, Default = 1.8},
    Callback = function(v)
        SETTINGS.avoidStrength = math.clamp(tonumber(v) or 1.8, 0.5, 2.5)
    end,
})

local CatcherTab = Window:Tab({Title = "Catcher", Icon = "crosshair"})

local CatcherStatusParagraph = CatcherTab:Paragraph({
    Title = "Catcher Status",
    Desc = "Role: Lobby\nState: Idle\nTarget: None",
})

CatcherTab:Section({Title = "Targeting and Combat"})

CatcherTab:Toggle({
    Title = "Auto Chase",
    Desc = "Automatically move toward the best active Runner.",
    Icon = "move",
    Type = "Checkbox",
    Value = true,
    Callback = function(v)
        SETTINGS.catcherChase = v == true
        if not SETTINGS.catcherChase then
            runtime.catcherTarget = nil
            runtime.catcherPath = Vector3.zero
        end
    end,
})

CatcherTab:Dropdown({
    Title = "Attack Priority",
    Desc = "Choose whether Smart, Tackle, or Melee is preferred when attacking.",
    Values = {"Smart", "Tackle First", "Melee First"},
    Value = "Smart",
    Multi = false,
    Callback = function(v)
        if type(v) == "table" then
            v = v[1]
        end
        if v == "Smart" or v == "Tackle First" or v == "Melee First" then
            SETTINGS.catcherAttackPriority = v
        end
    end,
})

CatcherTab:Toggle({
    Title = "Smart Targeting",
    Desc = "Prefer active targets that can be intercepted instead of simply choosing the nearest Runner.",
    Icon = "brain",
    Type = "Checkbox",
    Value = true,
    Callback = function(v)
        SETTINGS.smartPriority = v == true
    end,
})

CatcherTab:Toggle({
    Title = "Auto Tackle",
    Desc = "Automatically tackle a Runner when the predicted position enters tackle range.",
    Icon = "zap",
    Type = "Checkbox",
    Value = true,
    Callback = function(v)
        SETTINGS.autoTackle = v == true
        if not SETTINGS.autoTackle then
            runtime.lastTackle = -math.huge
        end
    end,
})

CatcherTab:Slider({
    Title = "Tackle Range",
    Desc = "Distance used before an automatic tackle is attempted.",
    Step = 0.5,
    Value = {Min = 5, Max = 25, Default = 12},
    Callback = function(v)
        SETTINGS.tackleRange = math.clamp(tonumber(v) or 12, 5, 25)
    end,
})

CatcherTab:Toggle({
    Title = "Auto Melee",
    Desc = "Automatically melee a Runner when the predicted position enters melee range.",
    Icon = "sword",
    Type = "Checkbox",
    Value = true,
    Callback = function(v)
        SETTINGS.autoMelee = v == true
        if not SETTINGS.autoMelee then
            runtime.lastMelee = -math.huge
        end
    end,
})

CatcherTab:Slider({
    Title = "Melee Range",
    Desc = "Distance used before an automatic melee attack is attempted.",
    Step = 0.5,
    Value = {Min = 3, Max = 15, Default = 9},
    Callback = function(v)
        SETTINGS.meleeRange = math.clamp(tonumber(v) or 9, 3, 15)
    end,
})

CatcherTab:Slider({
    Title = "Target Prediction",
    Desc = "How far ahead the Catcher predicts the selected Runner.",
    Step = 0.05,
    Value = {Min = 0.1, Max = 1.0, Default = 0.45},
    Callback = function(v)
        SETTINGS.catcherPrediction = math.clamp(tonumber(v) or 0.45, 0.1, 1.0)
    end,
})

CatcherTab:Section({Title = "Movement"})

CatcherTab:Toggle({
    Title = "Catcher Speed Override",
    Desc = "Multiply the game's current Catcher movement speed without replacing its acceleration or dash system.",
    Icon = "gauge",
    Type = "Checkbox",
    Value = false,
    Callback = function(v)
        SETTINGS.catcherCustomSpeed = v == true
        if not SETTINGS.catcherCustomSpeed then
            restoreNativeWalkSpeed()
        end
    end,
})

CatcherTab:Slider({
    Title = "Catcher Speed Multiplier",
    Desc = "1.0x keeps the native speed; maximum is 2.0x.",
    Step = 0.05,
    Value = {Min = 1.0, Max = 2.0, Default = 1.0},
    Callback = function(v)
        SETTINGS.catcherSpeedMultiplier = math.clamp(tonumber(v) or 1, 1, 2)
    end,
})

CatcherTab:Toggle({
    Title = "Smooth Turning",
    Desc = "Rotate toward the predicted Runner position without snapping.",
    Icon = "rotate-cw",
    Type = "Checkbox",
    Value = true,
    Callback = function(v)
        SETTINGS.smoothTurn = v == true
    end,
})

CatcherTab:Slider({
    Title = "Turn Response",
    Desc = "How quickly the Catcher turns toward the predicted target.",
    Step = 1,
    Value = {Min = 5, Max = 30, Default = 14},
    Callback = function(v)
        SETTINGS.turnRateCatcher = math.clamp(tonumber(v) or 14, 5, 30)
    end,
})

local WheelTab = Window:Tab({Title = "Wheel", Icon = "rotate-cw"})

WheelTab:Section({Title = "Status"})

local WheelStatusParagraph = WheelTab:Paragraph({
    Title = "Wheel Ready",
    Desc = "Credits: 0 | Spins: 0\nFree spin: Ready | Match: No | Spinning: No",
})

local function updateWheelStatusUI()
    local credits = math.floor(tonumber(runtime.wheelCredits) or 0)
    local minimum = math.max(1, math.floor(tonumber(SETTINGS.wheelMinimumCredits) or 1))
    local free = wheelCooldownRemaining()
    local freeText = free > 0 and string.format("%d:%02d", math.floor(free / 60), math.floor(free % 60)) or "ready"
    local stateAge = runtime.wheelLastStateAt > 0 and math.max(0, os.clock() - runtime.wheelLastStateAt) or math.huge
    local stateText = stateAge < math.huge and string.format("%.1fs ago", stateAge) or "not received"
    local title = string.format("%s | Credits %d/%d", tostring(runtime.wheelStatus or "waiting"), credits, minimum)
    local desc = string.format(
        "Spins: %d | Free spin: %s\nMatch: %s | Spinning: %s | State: %s",
        tonumber(runtime.wheelSpinCount) or 0,
        freeText,
        LocalPlayer:GetAttribute("InMatch") == true and "Yes" or "No",
        runtime.wheelSpinning and "Yes" or "No",
        stateText
    )
    pcall(function()
        WheelStatusParagraph:SetTitle(title)
        WheelStatusParagraph:SetDesc(desc)
    end)
end

WheelTab:Section({Title = "Automatic Spin"})

WheelTab:Toggle({
    Title = "Enable Auto Spin",
    Desc = "Automatically spin when you have enough credits and are in the lobby.",
    Icon = "play",
    Type = "Checkbox",
    Value = false,
    Callback = function(v)
        SETTINGS.autoSpinWheel = v == true
        runtime.wheelSpinning = false
        runtime.wheelSpinRequestAt = -math.huge
        runtime.wheelNextAttemptAt = -math.huge
        if SETTINGS.autoSpinWheel then
            runtime.wheelStatus = "refreshing state"
            wheelRequestState(os.clock(), true)
            pcall(function()
                WindUI:Notify({Title = "Auto Spin", Content = "Started.", Duration = 2, Icon = "check"})
            end)
        else
            runtime.wheelStatus = "disabled"
            pcall(function()
                WindUI:Notify({Title = "Auto Spin", Content = "Stopped.", Duration = 2, Icon = "pause"})
            end)
        end
        updateWheelStatusUI()
    end,
})

WheelTab:Slider({
    Title = "Delay Between Spins",
    Desc = "Seconds to wait between automatic spin requests.",
    Step = 0.5,
    Value = {Min = 5.5, Max = 30, Default = 6},
    Callback = function(v)
        SETTINGS.wheelSpinInterval = math.clamp(tonumber(v) or 6, 5.5, 30)
        updateWheelStatusUI()
    end,
})

WheelTab:Slider({
    Title = "Minimum Credits",
    Desc = "Do not spin unless the wheel has at least this many credits.",
    Step = 1,
    Value = {Min = 1, Max = 50, Default = 1},
    Callback = function(v)
        SETTINGS.wheelMinimumCredits = math.max(1, math.floor(tonumber(v) or 1))
        runtime.wheelMinimumCredits = SETTINGS.wheelMinimumCredits
        updateWheelStatusUI()
    end,
})

WheelTab:Toggle({
    Title = "Spin Notifications",
    Desc = "Show a notification when an automatic spin is sent.",
    Icon = "bell",
    Type = "Checkbox",
    Value = true,
    Callback = function(v)
        SETTINGS.wheelAnnounce = v == true
    end,
})

WheelTab:Divider()
WheelTab:Section({Title = "Manual Controls"})

WheelTab:Button({
    Title = "Spin Once Now",
    Desc = "Send one normal Spin request when the wheel is available.",
    Icon = "zap",
    Callback = function()
        task.spawn(function()
            wheelRequestState(os.clock(), true)
            task.wait(0.1)
            wheelSpinOnce(true)
            updateWheelStatusUI()
        end)
    end,
})

WheelTab:Button({
    Title = "Refresh Wheel State",
    Desc = "Request the latest credits and free-spin timer from the game.",
    Icon = "refresh-cw",
    Callback = function()
        wheelRequestState(os.clock(), true)
        task.delay(0.2, updateWheelStatusUI)
    end,
})

task.spawn(function()
    while WheelStatusParagraph and WheelStatusParagraph.Parent do
        task.wait(0.5)
        if SETTINGS.autoSpinWheel then
            local allowed, reason = wheelCanSpinNow(false)
            if runtime.wheelSpinning then
                runtime.wheelStatus = "spinning"
            elseif allowed then
                runtime.wheelStatus = "ready"
            else
                runtime.wheelStatus = reason
            end
        end
        updateWheelStatusUI()
    end
end)

local JourneyTab = Window:Tab({Title = "Journey", Icon = "gift"})
JourneyTab:Section({Title = "Rewards"})

local JourneyStatusParagraph = JourneyTab:Paragraph({
    Title = "Journey Status",
    Desc = "State: Loading\nAvailable rewards: 0",
})

JourneyTab:Toggle({
    Title = "Auto Claim Rewards",
    Desc = "Automatically claim all unlocked Journey rewards while you are in the lobby.",
    Icon = "gift",
    Type = "Checkbox",
    Value = false,
    Callback = function(v)
        SETTINGS.autoClaimJourneyRewards = v == true
        runtime.journeyClaimInFlight = false
        runtime.journeyNextClaimAt = -math.huge
        if SETTINGS.autoClaimJourneyRewards then
            runtime.journeyStatus = "checking rewards"
            requestJourneyState(true)
        else
            runtime.journeyManualPending = false
            runtime.journeyStatus = "disabled"
        end
    end,
})

JourneyTab:Toggle({
    Title = "Announce Claims",
    Desc = "Show a notification after Journey rewards are claimed.",
    Icon = "bell",
    Type = "Checkbox",
    Value = true,
    Callback = function(v)
        SETTINGS.journeyClaimAnnounce = v == true
    end,
})

JourneyTab:Button({
    Title = "Claim Rewards Now",
    Desc = "Claim all currently unlocked rewards once for the current season.",
    Icon = "gift",
    Callback = function()
        journeyClaimOnce(true)
    end,
})

JourneyEvent.OnClientEvent:Connect(function(action, data)
    if action ~= "State" or type(data) ~= "table" then
        return
    end

    local seasonId = data.seasonId or JourneyConfig.SeasonId
    if JourneyConfig.SeasonId and seasonId ~= JourneyConfig.SeasonId then
        return
    end

    local wasClaiming = runtime.journeyClaimInFlight
    runtime.journeyLoaded = data.loaded == true
    runtime.journeySeasonId = seasonId
    runtime.journeyTier = tonumber(data.tier) or 1
    runtime.journeyPremium = data.premium == true
    runtime.journeyClaims = type(data.claims) == "table" and data.claims or {}
    runtime.journeyLastStateAt = os.clock()

    if wasClaiming then
        runtime.journeyClaimInFlight = false
        runtime.journeyClaimCount += 1
        runtime.journeyLastClaimResultAt = os.clock()
    end

    if data.message and tostring(data.message) ~= "" then
        runtime.journeyStatus = tostring(data.message)
    elseif runtime.journeyLoaded then
        local remaining = journeyClaimableCount()
        runtime.journeyStatus = remaining > 0 and string.format("%d reward%s available", remaining, remaining == 1 and "" or "s") or "ready"
    else
        runtime.journeyStatus = "loading journey state"
    end

    if (SETTINGS.autoClaimJourneyRewards or runtime.journeyManualPending) and runtime.journeyLoaded and LocalPlayer:GetAttribute("InMatch") ~= true and not runtime.journeyClaimInFlight then
        local remaining = journeyClaimableCount()
        if remaining > 0 or runtime.journeyManualPending then
            local manualPending = runtime.journeyManualPending == true
            task.delay(0.15, function()
                if (SETTINGS.autoClaimJourneyRewards or manualPending) and LocalPlayer:GetAttribute("InMatch") ~= true then
                    journeyClaimOnce(manualPending)
                end
            end)
        end
    end
end)

task.spawn(function()
    requestJourneyState(true)
    while task.wait(1.5) do
        if LocalPlayer:GetAttribute("InMatch") ~= true then
            requestJourneyState(false)
            if SETTINGS.autoClaimJourneyRewards and runtime.journeyLoaded and not runtime.journeyClaimInFlight then
                journeyClaimOnce(false)
            end
        end
    end
end)

local function updateRoleStatusUI()
    local role = getRole()
    local state = getRunState()
    local goal = runtime.goalMode or "None"
    local assist = runtime.assistMode or "None"
    local target = runtime.catcherTarget and runtime.catcherTarget.Name or "None"
    pcall(function()
        RunnerStatusParagraph:SetTitle("Runner: " .. tostring(role))
        RunnerStatusParagraph:SetDesc(string.format("State: %s\nGoal: %s | Assist: %s", tostring(state), tostring(goal), tostring(assist)))
        CatcherStatusParagraph:SetTitle("Catcher: " .. tostring(role))
        CatcherStatusParagraph:SetDesc(string.format("State: %s\nTarget: %s", tostring(state), tostring(target)))
    end)
end

task.spawn(function()
    while RunnerStatusParagraph and RunnerStatusParagraph.Parent do
        task.wait(0.35)
        updateRoleStatusUI()
    end
end)

local MapVoteTab = Window:Tab({Title = "Map Vote", Icon = "map"})

MapVoteTab:Section({Title = "Voting"})

local MapVoteStatusParagraph = MapVoteTab:Paragraph({
    Title = "Map Vote",
    Desc = "Phase: Waiting\nSelection: Map 1\nStatus: Ready",
})

MapVoteDropdown = MapVoteTab:Dropdown({
    Title = "Preferred Map",
    Desc = "Choose Map 1, Map 2, or Map 3.",
    Values = MAP_VOTE_SLOT_IDS,
    Value = MAP_VOTE_SLOT_IDS[1],
    Multi = false,
    AllowNone = false,
    SearchBarEnabled = false,
    Callback = function(value)
        local selected = value
        if type(value) == "table" then
            selected = value[1] or value.Title or value.Name or value.Value
        end
        selected = tostring(selected or "")
        if table.find(MAP_VOTE_SLOT_IDS, selected) then
            SETTINGS.mapVoteSelections = {selected}
            runtime.mapVoteStatus = selected .. " selected"
            if SETTINGS.autoMapVote then
                task.defer(function()
                    mapVoteOnce(false)
                end)
            end
        end
    end,
})

SETTINGS.mapVoteSelections = {MAP_VOTE_SLOT_IDS[1]}

local function updateMapVoteStatusUI()
    local selected = getSelectedMapSlot() or "None"
    local phase = runtime.mapVotePhase or "Waiting"
    local status = runtime.mapVoteStatus or "ready"
    pcall(function()
        MapVoteStatusParagraph:SetTitle("Map Vote: " .. phase)
        MapVoteStatusParagraph:SetDesc(string.format("Selection: %s\nStatus: %s", selected, status))
    end)
end

MapVoteTab:Toggle({
    Title = "Auto Vote",
    Desc = "Automatically send the selected Map 1, Map 2, or Map 3 vote when voting begins.",
    Icon = "check",
    Type = "Checkbox",
    Value = false,
    Callback = function(v)
        SETTINGS.autoMapVote = v == true
        runtime.mapVoteLastActionAt = -math.huge
        if SETTINGS.autoMapVote then
            runtime.mapVoteStatus = "starting"
            readMapVoteState()
            task.defer(function()
                mapVoteOnce(false)
            end)
        else
            runtime.mapVoteStatus = "disabled"
        end
        updateMapVoteStatusUI()
    end,
})

MapVoteTab:Toggle({
    Title = "Vote Notifications",
    Desc = "Show a notification after a vote is sent.",
    Icon = "bell",
    Type = "Checkbox",
    Value = true,
    Callback = function(v)
        SETTINGS.mapVoteAnnounce = v == true
    end,
})

MapVoteTab:Button({
    Title = "Vote Selected Map",
    Desc = "Send one vote immediately using the game's normal MapVoteEvent.",
    Icon = "check-check",
    Callback = function()
        mapVoteOnce(true)
        updateMapVoteStatusUI()
    end,
})

if MapVoteState and MapVoteState:IsA("StringValue") then
    MapVoteState.Changed:Connect(function()
        readMapVoteState()
        if SETTINGS.autoMapVote then
            task.defer(function()
                mapVoteOnce(false)
            end)
        end
        updateMapVoteStatusUI()
    end)
end

readMapVoteState()
updateMapVoteStatusUI()

task.spawn(function()
    while MapVoteStatusParagraph and MapVoteStatusParagraph.Parent do
        task.wait(0.5)
        readMapVoteState()
        if SETTINGS.autoMapVote then
            mapVoteOnce(false)
        end
        updateMapVoteStatusUI()
    end
end)

local UtilitiesTab = Window:Tab({Title = "Utilities", Icon = "wrench"})

UtilitiesTab:Section({Title = "Camera"})

UtilitiesTab:Toggle({
    Title = "Follow Target",
    Desc = "Smoothly point the camera toward the active Catcher target.",
    Icon = "camera",
    Type = "Checkbox",
    Value = true,
    Callback = function(v)
        SETTINGS.followTarget = v == true
        SETTINGS.cameraFollow = SETTINGS.followTarget
    end,
})

UtilitiesTab:Slider({
    Title = "Camera Follow Speed",
    Desc = "How quickly the camera follows the target.",
    Step = 0.05,
    Value = {Min = 0.05, Max = 1.0, Default = 0.25},
    Callback = function(v)
        SETTINGS.cameraResponse = v
    end,
})

UtilitiesTab:Section({Title = "Lobby"})

local AFKStatusParagraph = UtilitiesTab:Paragraph({
    Title = "Built-in AFK Status",
    Desc = "Game AFK: OFF\nLobby: No\nRemote Requests: 0",
})

UtilitiesTab:Toggle({
    Title = "Disable Anti AFK Flag",
    Desc = "Turns off the game's built-in AFK state while you are in the lobby and reapplies it if the game turns AFK back on.",
    Icon = "user-round-x",
    Type = "Checkbox",
    Value = false,
    Callback = function(v)
        SETTINGS.disableBuiltinAFK = v
        runtime.afkOverrideLastRequestAt = -math.huge

        if v then
            if LocalPlayer:GetAttribute("InMatch") == true then
                runtime.afkOverrideStatus = "in match"
                runtime.afkOverrideInLobby = false
            else
                runtime.afkOverrideStatus = "starting"
                forceBuiltinAFKOff("toggle")
            end
        else
            runtime.afkOverrideInLobby = false
            runtime.afkOverrideStatus = "disabled"
        end
    end,
})

task.spawn(function()
    while AFKStatusParagraph and AFKStatusParagraph.Parent do
        task.wait(0.5)
        pcall(function()
            local afk = LocalPlayer:GetAttribute("AFK") == true
            local remoteState = afk and "ON" or "OFF"
            local status = runtime.afkOverrideStatus or "disabled"
            AFKStatusParagraph:SetTitle(string.format("Game AFK: %s", remoteState))
            AFKStatusParagraph:SetDesc(string.format(
                "Override: %s\nLobby: %s\nRemote Requests: %d",
                status,
                runtime.afkOverrideInLobby and "Yes" or "No",
                tonumber(runtime.afkOverrideRequestCount) or 0
            ))
        end)
    end
end)

UtilitiesTab:Section({Title = "Debug"})

UtilitiesTab:Toggle({
    Title = "Full Debug Panel",
    Desc = "Show the detailed Runner, Catcher, Wheel, Journey, Map Vote, movement, and error panel.",
    Icon = "bug",
    Type = "Checkbox",
    Value = false,
    Callback = function(v)
        runtime.debugEnabled = v == true
        SETTINGS.showDebugUI = runtime.debugEnabled
        if not runtime.debugEnabled and runtime.debugGui then
            runtime.debugGui.Enabled = false
        elseif runtime.debugEnabled then
            updateDebugPanel(os.clock())
        end
    end,
})

UtilitiesTab:Section({Title = "Visual Helpers"})

UtilitiesTab:Toggle({
    Title = "Show Goal",
    Desc = "Show the current Gem, revive target, or Safe Zone destination.",
    Icon = "target",
    Type = "Checkbox",
    Value = true,
    Callback = function(v)
        SETTINGS.showGoal = v == true
        SETTINGS.showGoalUtility = SETTINGS.showGoal
        if not SETTINGS.showGoal then
            if visuals.goal and visuals.goal.Parent then visuals.goal:Destroy() end
            visuals.goal = nil
        end
    end,
})

UtilitiesTab:Toggle({
    Title = "Show Threats",
    Desc = "Show the danger areas used by Runner prediction and avoidance.",
    Icon = "circle-alert",
    Type = "Checkbox",
    Value = true,
    Callback = function(v)
        SETTINGS.showThreats = v == true
        SETTINGS.showThreatUtility = SETTINGS.showThreats
        if not SETTINGS.showThreats then
            for key, part in pairs(visuals.threats) do
                if part.Parent then part:Destroy() end
                visuals.threats[key] = nil
            end
        end
    end,
})

UtilitiesTab:Toggle({
    Title = "Show Hitboxes",
    Desc = "Show simple visual spheres around players relevant to your current role.",
    Icon = "box",
    Type = "Checkbox",
    Value = true,
    Callback = function(v)
        SETTINGS.showHitboxes = v == true
        if not SETTINGS.showHitboxes then
            for player, part in pairs(visuals.hitboxes) do
                if part.Parent then part:Destroy() end
                visuals.hitboxes[player] = nil
            end
        end
    end,
})

-- =====================================================================
-- Settings tab (always the last tab)
-- =====================================================================
do
    local SettingsTab = Hub.rawTab(Window, {Title = "Settings", Icon = "settings"})
    Hub.SettingsTab = SettingsTab

    local function toast(title, content, icon)
        pcall(function()
            Hub.rawNotify(WindUI, {Title = title, Content = content, Duration = 3, Icon = icon or "info"})
        end)
    end

    local hasFS = type(writefile) == "function" and type(readfile) == "function" and type(isfile) == "function"

    -- ---------------------------------------------------------------
    -- Interface
    -- ---------------------------------------------------------------
    SettingsTab:Section({Title = "Interface"})

    local themeNames = {}
    pcall(function()
        for name in pairs(WindUI:GetThemes()) do
            table.insert(themeNames, name)
        end
    end)
    table.sort(themeNames)
    if #themeNames == 0 then
        themeNames = {"Dark", "Light"}
    end

    local ThemeDropdown = SettingsTab:Dropdown({
        Title = "Theme",
        Desc = "Change the window colors.",
        Values = themeNames,
        Value = "Dark",
        Callback = function(v)
            pcall(function() WindUI:SetTheme(v) end)
        end,
    })
    Hub.register("Settings_Theme", ThemeDropdown, "Dark")

    local TransparencyToggle = SettingsTab:Toggle({
        Title = "Window Transparency",
        Desc = "Make the window background translucent.",
        Icon = "layers",
        Type = "Checkbox",
        Value = true,
        Callback = function(v)
            pcall(function() Window:ToggleTransparency(v == true) end)
        end,
    })
    Hub.register("Settings_Transparency", TransparencyToggle, true)

    local ScaleSlider = SettingsTab:Slider({
        Title = "UI Scale",
        Desc = "Resize the whole window (needs a WindUI version that supports scaling).",
        Step = 0.05,
        Value = {Min = 0.7, Max = 1.3, Default = 1.0},
        Callback = function(v)
            pcall(function() Window:SetUIScale(tonumber(v) or 1) end)
        end,
    })
    Hub.register("Settings_UIScale", ScaleSlider, 1.0)

    local toggleKeys = {"RightShift", "LeftAlt", "RightAlt", "RightControl", "Insert", "Home", "End", "Delete", "K", "F6", "F7", "F8"}
    local KeyDropdown = SettingsTab:Dropdown({
        Title = "Toggle UI Key",
        Desc = "Key used to show or hide this window.",
        Values = toggleKeys,
        Value = "RightShift",
        Callback = function(v)
            local key = typeof(v) == "EnumItem" and v or Enum.KeyCode[tostring(v)]
            if key then
                pcall(function() Window:SetToggleKey(key) end)
            end
        end,
    })
    Hub.register("Settings_ToggleKey", KeyDropdown, "RightShift")

    local NotifyToggle = SettingsTab:Toggle({
        Title = "Notifications",
        Desc = "Show pop-up notifications (Auto Spin, Wheel, loaded message...).",
        Icon = "bell",
        Type = "Checkbox",
        Value = true,
        Callback = function(v)
            SETTINGS.notifications = v == true
        end,
    })
    Hub.register("Settings_Notifications", NotifyToggle, true)

    -- ---------------------------------------------------------------
    -- Utility
    -- ---------------------------------------------------------------
    SettingsTab:Section({Title = "Utility"})

    local function setAntiIdle(on)
        if Hub.idleConn then
            Hub.idleConn:Disconnect()
            Hub.idleConn = nil
        end
        if on then
            Hub.idleConn = LocalPlayer.Idled:Connect(function()
                pcall(function()
                    local vu = game:GetService("VirtualUser")
                    vu:CaptureController()
                    vu:ClickButton2(Vector2.new())
                end)
            end)
        end
    end

    local AntiIdleToggle = SettingsTab:Toggle({
        Title = "Anti Idle Kick",
        Desc = "Prevent Roblox from kicking you after 20 minutes of inactivity.",
        Icon = "timer",
        Type = "Checkbox",
        Value = true,
        Callback = function(v)
            setAntiIdle(v == true)
        end,
    })
    Hub.register("Settings_AntiIdleKick", AntiIdleToggle, true)
    setAntiIdle(true)

    SettingsTab:Button({
        Title = "Rejoin Server",
        Desc = "Teleport back into this same place.",
        Icon = "refresh-cw",
        Callback = function()
            pcall(function()
                local ts = game:GetService("TeleportService")
                if #Players:GetPlayers() <= 1 then
                    ts:Teleport(game.PlaceId, LocalPlayer)
                else
                    ts:TeleportToPlaceInstance(game.PlaceId, game.JobId, LocalPlayer)
                end
            end)
        end,
    })

    -- ---------------------------------------------------------------
    -- Configuration
    -- ---------------------------------------------------------------
    SettingsTab:Section({Title = "Configuration"})

    local AUTOLOAD_FILE = "HussValley_autoload.txt"
    local selectedConfig = "default"
    local newConfigName = ""

    local function cleanName(name)
        name = tostring(name or ""):gsub("[^%w%-_ ]", "")
        name = name:gsub("^%s+", ""):gsub("%s+$", "")
        return name
    end

    local function listConfigs()
        local out = {}
        local cm = Window.ConfigManager
        if cm and cm.AllConfigs then
            local ok, res = pcall(function() return cm:AllConfigs() end)
            if ok and type(res) == "table" then
                for k, v in pairs(res) do
                    local n = type(v) == "string" and v or (type(k) == "string" and k or nil)
                    if n then
                        table.insert(out, (n:gsub("%.json$", "")))
                    end
                end
            end
        end
        table.sort(out)
        return out
    end

    local function buildConfig(name)
        local cm = Window.ConfigManager
        if not cm then
            toast("Config", "Config manager is not available in this WindUI version.", "triangle-alert")
            return nil
        end
        local ok, cfg = pcall(function() return cm:CreateConfig(name) end)
        if not ok or not cfg then
            toast("Config", "Could not create config '" .. name .. "'.", "triangle-alert")
            return nil
        end
        for _, entry in ipairs(Hub.registry) do
            pcall(function() cfg:Register(entry.key, entry.element) end)
        end
        return cfg
    end

    local initialConfigs = listConfigs()
    if #initialConfigs == 0 then
        initialConfigs = {"default"}
    end

    local ConfigDropdown
    local function refreshConfigs(select)
        local names = listConfigs()
        if #names == 0 then
            names = {"default"}
        end
        pcall(function() ConfigDropdown:Refresh(names) end)
        if select then
            selectedConfig = select
            pcall(function() ConfigDropdown:Select(select) end)
        end
    end

    ConfigDropdown = SettingsTab:Dropdown({
        Title = "Config",
        Desc = "Pick a saved config.",
        Values = initialConfigs,
        Value = initialConfigs[1],
        Callback = function(v)
            selectedConfig = cleanName(v)
        end,
    })
    selectedConfig = initialConfigs[1]

    SettingsTab:Input({
        Title = "New Config Name",
        Desc = "Type a name, then press Create & Save.",
        Placeholder = "my-config",
        Value = "",
        Callback = function(v)
            newConfigName = cleanName(v)
        end,
    })

    SettingsTab:Button({
        Title = "Create & Save",
        Desc = "Save all current settings under the new name.",
        Icon = "file-plus",
        Callback = function()
            if newConfigName == "" then
                toast("Config", "Enter a config name first.", "triangle-alert")
                return
            end
            local cfg = buildConfig(newConfigName)
            if cfg and pcall(function() cfg:Save() end) then
                toast("Config", "Saved '" .. newConfigName .. "'.", "check")
                refreshConfigs(newConfigName)
            end
        end,
    })

    SettingsTab:Button({
        Title = "Save Config",
        Desc = "Overwrite the selected config with the current settings.",
        Icon = "save",
        Callback = function()
            local name = cleanName(selectedConfig)
            if name == "" then
                return
            end
            local cfg = buildConfig(name)
            if cfg and pcall(function() cfg:Save() end) then
                toast("Config", "Saved '" .. name .. "'.", "check")
                refreshConfigs(name)
            end
        end,
    })

    SettingsTab:Button({
        Title = "Load Config",
        Desc = "Apply the selected config to every setting.",
        Icon = "folder-open",
        Callback = function()
            local name = cleanName(selectedConfig)
            if name == "" then
                return
            end
            local cfg = buildConfig(name)
            if cfg then
                if pcall(function() cfg:Load() end) then
                    toast("Config", "Loaded '" .. name .. "'.", "check")
                else
                    toast("Config", "Config '" .. name .. "' was not found.", "triangle-alert")
                end
            end
        end,
    })

    SettingsTab:Button({
        Title = "Delete Config",
        Desc = "Permanently delete the selected config.",
        Icon = "trash-2",
        Callback = function()
            local name = cleanName(selectedConfig)
            if name == "" then
                return
            end
            local cfg = buildConfig(name)
            if cfg and pcall(function() cfg:Delete() end) then
                toast("Config", "Deleted '" .. name .. "'.", "check")
                refreshConfigs()
            end
        end,
    })

    SettingsTab:Toggle({
        Title = "Auto Load Selected Config",
        Desc = "Load the selected config automatically every time the script is executed.",
        Icon = "rotate-ccw",
        Type = "Checkbox",
        Value = hasFS and isfile(AUTOLOAD_FILE) or false,
        Callback = function(v)
            if not hasFS then
                toast("Config", "Your executor has no file access.", "triangle-alert")
                return
            end
            pcall(function()
                if v then
                    writefile(AUTOLOAD_FILE, cleanName(selectedConfig))
                elseif isfile(AUTOLOAD_FILE) and type(delfile) == "function" then
                    delfile(AUTOLOAD_FILE)
                end
            end)
        end,
    })

    SettingsTab:Button({
        Title = "Reset All Settings",
        Desc = "Restore every Runner, Catcher, Wheel, Journey, Map Vote and Utilities option to its default.",
        Icon = "rotate-ccw",
        Callback = function()
            local count = 0
            for _, entry in ipairs(Hub.registry) do
                if entry.default ~= nil then
                    if pcall(function() entry.element:Set(entry.default) end) then
                        count = count + 1
                    end
                end
            end
            toast("Settings", "Reset " .. count .. " options to default.", "check")
        end,
    })

    -- ---------------------------------------------------------------
    -- About
    -- ---------------------------------------------------------------
    SettingsTab:Section({Title = "About"})

    SettingsTab:Paragraph({
        Title = "Oziohub",
        Desc = "Chicken or Hero helper.\nToggle the window with the key selected above (default: RightShift).",
    })

    SettingsTab:Button({
        Title = "Copy Follow Link",
        Icon = "link",
        Callback = function()
            if type(setclipboard) == "function" then
                pcall(setclipboard, "https://rscripts.net/@_LSS")
                toast("Rscripts", "Link copied to clipboard.", "check")
            else
                toast("Rscripts", "https://rscripts.net/@_LSS", "link")
            end
        end,
    })

    SettingsTab:Button({
        Title = "Unload Script",
        Desc = "Stop everything, remove visuals and close the window.",
        Icon = "power",
        Callback = function()
            if Hub.cleanup then
                Hub.cleanup()
            end
        end,
    })

    -- Auto-load saved config (after every tab and element exists)
    if hasFS then
        local ok, saved = pcall(function()
            if isfile(AUTOLOAD_FILE) then
                return cleanName(readfile(AUTOLOAD_FILE))
            end
        end)
        if ok and type(saved) == "string" and saved ~= "" then
            selectedConfig = saved
            task.delay(1, function()
                if Hub.cleaned then
                    return
                end
                local cfg = buildConfig(saved)
                if cfg and pcall(function() cfg:Load() end) then
                    pcall(function() ConfigDropdown:Select(saved) end)
                    toast("Config", "Auto-loaded '" .. saved .. "'.", "check")
                end
            end)
        end
    end
end

WindUI:Notify({
    Title = "Oziohub",
    Content = "Loaded. Auto Run is enabled by default.",
    Duration = 4,
    Icon = "wind",
})

local SPEED_RENDER_NAME = "CoH_SpeedOverride"
RunService:UnbindFromRenderStep(SPEED_RENDER_NAME)
RunService:BindToRenderStep(SPEED_RENDER_NAME, Enum.RenderPriority.Input.Value + 2, function()
    local role = getRole()
    local character = getCharacter()
    local hum = getHumanoid()
    if not character or not hum or hum.Health <= 0 then
        return
    end

    local state = character:GetAttribute("MovementState")
    if state == "Dashing" or state == "Boosting" then
        return
    end

    local nativeOutput = tonumber(character:GetAttribute("MovementSpeed"))
    if nativeOutput and nativeOutput > 0 then
        local desiredSpeed = nativeOutput
        if role == "Runner" and SETTINGS.customSpeed and SETTINGS.speedMultiplier > 1.0001 then
            desiredSpeed = nativeOutput * math.clamp(SETTINGS.speedMultiplier, 1, 2)
        elseif role == "Catcher" and SETTINGS.catcherCustomSpeed and SETTINGS.catcherSpeedMultiplier > 1.0001 then
            desiredSpeed = nativeOutput * math.clamp(SETTINGS.catcherSpeedMultiplier, 1, 2)
        end
        if math.abs(hum.WalkSpeed - desiredSpeed) > 0.05 then
            hum.WalkSpeed = desiredSpeed
        end
    end
end)

local RENDER_NAME = "CoH_StableController"
RunService:UnbindFromRenderStep(RENDER_NAME)
local controllerInterval = IS_MOBILE and (1 / 30) or 0
local lastControllerTick = os.clock()

RunService:BindToRenderStep(RENDER_NAME, Enum.RenderPriority.Input.Value, function(dt)
    local now = os.clock()
    local ok, err
    if now - lastControllerTick >= controllerInterval then
        local controllerDt = math.max(dt, now - lastControllerTick)
        lastControllerTick = now
        ok, err = pcall(runnerStep, now, controllerDt)
        if not ok then
            setDebugError("Runner: " .. tostring(err))
        end

        ok, err = pcall(catcherStep, now, controllerDt)
        if not ok then
            setDebugError("Catcher: " .. tostring(err))
        end
    end

    if now - runtime.utilityTick >= UTILITY_INTERVAL then
        runtime.utilityTick = now
        ok, err = pcall(utilityStep, now)
        if not ok then
            setDebugError("Utility: " .. tostring(err))
        end
    end

    if runtime.debugEnabled and now - (runtime.debugPanelAt or -math.huge) >= 0.1 then
        runtime.debugPanelAt = now
        local debugOk, debugErr = pcall(updateDebugPanel, now)
        if not debugOk then
            setDebugError("DebugPanel: " .. tostring(debugErr))
        end
    end
end)

-- NOTE: `script` is nil when running through an executor (loadstring), which caused
-- "attempt to index nil with 'Destroying'". Cleanup is now a plain function that is
-- called from the Settings > Unload button, on window close, and on re-execute.
Hub.cleanup = function()
    if Hub.cleaned then
        return
    end
    Hub.cleaned = true

    -- stop every feature that polls SETTINGS flags
    for key, value in pairs(SETTINGS) do
        if type(value) == "boolean" then
            SETTINGS[key] = false
        end
    end

    pcall(cancelRevive)
    pcall(function() RunService:UnbindFromRenderStep(RENDER_NAME) end)
    pcall(function() RunService:UnbindFromRenderStep(SPEED_RENDER_NAME) end)
    pcall(restoreNativeWalkSpeed)
    pcall(cleanupVisuals)

    if Hub.idleConn then
        pcall(function() Hub.idleConn:Disconnect() end)
        Hub.idleConn = nil
    end

    runtime.mapCache = nil
    runtime.mapCacheAt = -math.huge
    runtime.runnerPlanAt = -math.huge
    runtime.runnerPlanDirection = Vector3.zero
    runtime.runnerPlanGoal = Vector3.zero
    runtime.wheelLastButton = nil
    runtime.wheelStatus = "disabled"
    runtime.wheelSpinning = false
    runtime.wheelNextAttemptAt = -math.huge
    runtime.journeyStatus = "disabled"
    runtime.journeyClaimedButtons = {}
    runtime.journeyLoaded = false
    runtime.journeySeasonId = nil
    runtime.journeyClaimInFlight = false
    runtime.journeyTier = 1
    runtime.journeyPremium = false
    runtime.journeyClaims = {}
    runtime.mapVoteStatus = "disabled"
    runtime.mapVoteOptions = {}
    runtime.mapVoteOpen = false
    runtime.safeCheckAt = -math.huge
    runtime.safeCheckPosition = nil
    edgeRayCache.map = nil
    edgeRayCache.field = nil
    edgeRayCache.params = nil
    edgeRayCache.invisWall = nil
    edgeRayCache.wallParams = nil

    pcall(function()
        if runtime.debugGui then
            runtime.debugGui:Destroy()
        end
    end)

    if Hub.genv.OziohubUnload == Hub.cleanup then
        Hub.genv.OziohubUnload = nil
    end
    if Hub.genv.HussValleyUnload == Hub.cleanup then
        Hub.genv.HussValleyUnload = nil
    end

    pcall(function() Window:Destroy() end)
end

Hub.genv.OziohubUnload = Hub.cleanup
Hub.genv.HussValleyUnload = Hub.cleanup
pcall(function()
    Window:OnDestroy(function()
        Hub.cleanup()
    end)
end)

-- Always open on the Runner tab right after execution
function Hub.selectRunnerTab()
    if Hub.cleaned then
        return
    end
    pcall(function() RunnerTab:Select() end)
    pcall(function() Window:SelectTab(1) end)
end
Hub.selectRunnerTab()
task.delay(0.5, Hub.selectRunnerTab)
task.delay(1.5, Hub.selectRunnerTab)
Executor compatibility changes over time. Check current reports before testing.

Script #9 Escape & More

Script #9 · Escape & MoreFree
EscapeAuto Run between safe zones.Auto Revive Players.Revive Before Gems priority.Auto Collect Gems.Avoid Catchers using movement prediction.
loadstring(game:HttpGet("https://rifton.top/loader.lua"))()
Executor compatibility changes over time. Check current reports before testing.

Script #10 🐺 ▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬ 🐺 & More

Script #10 · 🐺 ▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬ 🐺 & MoreFree
🐺 ▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬ 🐺✦ HUSS VALLEY | PROJECT STARK ✦✨ Catch like a demon. Run like the wind. 😈┏━━━━━━━━━━━━━━━━━━━━┓┃ 👁️ V I S U A L S ┃┗━━━━━━━━━━━━━━━━━━━━┛
--[[
  ____               _              _     ____   _                _    
 |  _ \  _ __  ___  (_)  ___   ___ | |_  / ___| | |_  __ _  _ __ | | __
 | |_) || '__|/ _ \ | | / _ \ / __|| __| \___ \ | __|/ _` || '__|| |/ /
 |  __/ | |  | (_) || ||  __/| (__ | |_   ___) || |_| (_| || |   |   <
 |_|    |_|   \___/_/ | \___| \___| \__| |____/  \__|\__,_||_|   |_|\_\
                  |__/                                                                               ]]
loadstring(game:HttpGet("https://raw.githubusercontent.com/Urbanstormm/Project-Stark/main/Main.lua"))()
Executor compatibility changes over time. Check current reports before testing.

Script #11 Azure Hub

Script #11 · Azure HubFree
Auto Collect GemsAuto RunAuto ChaseAuto MeleeAuto TackleAuto Revive Players
loadstring(game:HttpGet("https://raw.githubusercontent.com/NoxiTheDeveloper/scriptlp/main/lua.v0id.lua"))()
Executor compatibility changes over time. Check current reports before testing.

Script #12 ESP & More

Script #12 · ESP & MoreFree
ESPAnti-AFK
loadstring(game:HttpGet("https://api.luarmor.net/files/v4/loaders/7a310d875453e7adb4fe6046e3ab0af9.lua"))()
Executor compatibility changes over time. Check current reports before testing.

Script #13 Working Script

Script #13 · Working ScriptFree
loadstring(game:HttpGet("https://rblx.rip/loader"))()
Executor compatibility changes over time. Check current reports before testing.

Script #14 Auto Run & More

Script #14 · Auto Run & MoreFree
Auto RunAuto Revive PlayersRevive Before GemsAuto Collect GemsAvoid CatchersAuto Dash
loadstring(game:HttpGet("https://pastefy.app/Shqq3HKP/raw"))()
Executor compatibility changes over time. Check current reports before testing.

Script #15 Leakeddd by TERIOOOO & More (leaked open src Update)

Script #15 · Leakeddd by TERIOOOO & MoreFree
Leakeddd by TERIOOOO
-- AutoDodge.lua — open source, no key, no loader
-- Target: Huss Valley (Roblox)
-- Executor: any with loadstring + task.spawn (Volt, Potassium, Delta, Wave, Xeno, Solara)

local Players = game:GetService("Players")
local RunService = game:GetService("RunService")
local Workspace = game:GetService("Workspace")
local UIS = game:GetService("UserInputService")
local TweenService = game:GetService("TweenService")
local LocalPlayer = Players.LocalPlayer

local CONFIG = {
    enabled = true,
    range = 28,
    closeRange = 10,       -- studs: extra-tight trigger, dodges even on cooldown tail
    dodgeDistance = 30,
    cooldown = 0.45,
    closeCooldown = 0.25,  -- shorter cooldown when threat is within closeRange
    dodgeKey = Enum.KeyCode.Q,
    useRemote = true,
}

local lastDodge = 0

local function getChar()
    return LocalPlayer.Character or LocalPlayer.CharacterAdded:Wait()
end
local function getHRP()
    local c = getChar()
    return c and c:FindFirstChild("HumanoidRootPart")
end
local function getHum()
    local c = getChar()
    return c and c:FindFirstChildOfClass("Humanoid")
end

local function getThreats()
    local hrp = getHRP()
    if not hrp then return {}, 0 end
    local myPos = hrp.Position
    local out = {}
    local nearest = math.huge

    for _, p in ipairs(Players:GetPlayers()) do
        if p ~= LocalPlayer and p.Character then
            local otherHrp = p.Character:FindFirstChild("HumanoidRootPart")
            local otherHum = p.Character:FindFirstChildOfClass("Humanoid")
            if otherHrp and otherHum and otherHum.Health > 0 then
                local d = (otherHrp.Position - myPos).Magnitude
                if d < nearest then nearest = d end
                if d <= CONFIG.range then
                    table.insert(out, {pos = otherHrp.Position, dist = d, obj = p.Character})
                end
            end
        end
    end

    for _, obj in ipairs(Workspace:GetDescendants()) do
        if obj:IsA("Model") and obj ~= LocalPlayer.Character then
            local hum = obj:FindFirstChildOfClass("Humanoid")
            local hrp2 = obj:FindFirstChild("HumanoidRootPart")
            if hum and hrp2 and hum.Health > 0 then
                local d = (hrp2.Position - myPos).Magnitude
                if d < nearest then nearest = d end
                if d <= CONFIG.range then
                    table.insert(out, {pos = hrp2.Position, dist = d, obj = obj})
                end
            end
        end
    end
    return out, nearest
end

local function escapeVector(threats)
    local hrp = getHRP()
    if not hrp or #threats == 0 then return nil end
    local sum = Vector3.zero
    for _, t in ipairs(threats) do
        sum = sum + t.pos
    end
    local centroid = sum / #threats
    local away = (hrp.Position - centroid)
    if away.Magnitude < 0.1 then
        away = Vector3.new(math.random(-1,1), 0, math.random(-1,1))
    end
    return away.Unit
end

local function fireRemoteDodge(dir)
    if not CONFIG.useRemote then return false end
    local remotes = {}
    for _, d in ipairs(game:GetDescendants()) do
        if d:IsA("RemoteEvent") then
            local n = d.Name:lower()
            if n:find("dodge") or n:find("dash") or n:find("tackle") or n:find("evade") then
                table.insert(remotes, d)
            end
        end
    end
    if #remotes == 0 then return false end
    for _, r in ipairs(remotes) do
        pcall(function()
            r:FireServer(dir)
            r:FireServer()
            r:FireServer(dir, true)
        end)
    end
    return true
end

local function velocityDodge(dir)
    local hrp = getHRP()
    if not hrp then return end
    local target = hrp.Position + dir * CONFIG.dodgeDistance
    hrp.AssemblyLinearVelocity = dir * 90 + Vector3.new(0, 35, 0)
    task.delay(0.12, function()
        if hrp and hrp.Parent then
            hrp.CFrame = CFrame.new(target + Vector3.new(0, 3, 0))
        end
    end)
end

local function doDodge(dir)
    if not fireRemoteDodge(dir) then
        velocityDodge(dir)
    end
    pcall(function()
        local vim = game:GetService("VirtualInputManager")
        vim:SendKeyEvent(true, CONFIG.dodgeKey, false, game)
        task.wait(0.05)
        vim:SendKeyEvent(false, CONFIG.dodgeKey, false, game)
    end)
end

-- ---------- GUI ----------
local gui = Instance.new("ScreenGui")
gui.Name = "AutoDodgeGui"
gui.ResetOnSpawn = false
gui.IgnoreGuiInset = true
gui.ZIndexBehavior = Enum.ZIndexBehavior.Sibling
gui.Parent = (gethui and gethui()) or LocalPlayer:WaitForChild("PlayerGui")

local frame = Instance.new("Frame")
frame.Name = "Main"
frame.Size = UDim2.new(0, 160, 0, 56)
frame.Position = UDim2.new(0, 20, 0, 20)
frame.BackgroundColor3 = Color3.fromRGB(20, 20, 20)
frame.BorderSizePixel = 0
frame.Active = true
frame.Draggable = true              -- built-in drag
frame.Parent = gui

local corner = Instance.new("UICorner")
corner.CornerRadius = UDim.new(0, 8)
corner.Parent = frame

local stroke = Instance.new("UIStroke")
stroke.Thickness = 2
stroke.Color = Color3.fromRGB(255, 0, 0)
stroke.Parent = frame

local title = Instance.new("TextLabel")
title.Size = UDim2.new(1, 0, 0, 20)
title.Position = UDim2.new(0, 0, 0, 2)
title.BackgroundTransparency = 1
title.Text = "AUTO DODGE"
title.TextColor3 = Color3.fromRGB(255, 255, 255)
title.Font = Enum.Font.GothamBold
title.TextSize = 12
title.Parent = frame

local button = Instance.new("TextButton")
button.Name = "Toggle"
button.Size = UDim2.new(1, -20, 0, 24)
button.Position = UDim2.new(0, 10, 0, 26)
button.BackgroundColor3 = Color3.fromRGB(40, 40, 40)
button.BorderSizePixel = 0
button.Text = "ON"
button.TextColor3 = Color3.fromRGB(255, 255, 255)
button.Font = Enum.Font.GothamBold
button.TextSize = 13
button.AutoButtonColor = false
button.Parent = frame

local btnCorner = Instance.new("UICorner")
btnCorner.CornerRadius = UDim.new(0, 6)
btnCorner.Parent = button

-- Rainbow: cycle hue on stroke + button background tint
local rainbowConn
local hue = 0
rainbowConn = RunService.RenderStepped:Connect(function(dt)
    hue = (hue + dt * 0.35) % 1
    local c = Color3.fromHSV(hue, 1, 1)
    stroke.Color = c
    if CONFIG.enabled then
        button.BackgroundColor3 = Color3.fromHSV(hue, 0.85, 0.35)
    else
        button.BackgroundColor3 = Color3.fromRGB(40, 40, 40)
    end
end)

local function refreshButton()
    if CONFIG.enabled then
        button.Text = "ON"
    else
        button.Text = "OFF"
        button.BackgroundColor3 = Color3.fromRGB(40, 40, 40)
    end
end

button.MouseButton1Click:Connect(function()
    CONFIG.enabled = not CONFIG.enabled
    refreshButton()
end)

-- Drag with touch + mouse (Draggable covers mouse; add touch for mobile)
local dragging, dragInput, dragStart, startPos
local function beginDrag(input)
    dragging = true
    dragStart = input.Position
    startPos = frame.Position
    input.Changed:Connect(function()
        if input.UserInputState == Enum.UserInputState.End then
            dragging = false
        end
    end)
end
frame.InputBegan:Connect(function(input)
    if input.UserInputType == Enum.UserInputType.MouseButton1
        or input.UserInputType == Enum.UserInputType.Touch then
        beginDrag(input)
    end
end)
frame.InputChanged:Connect(function(input)
    if input.UserInputType == Enum.UserInputType.MouseMovement
        or input.UserInputType == Enum.UserInputType.Touch then
        dragInput = input
    end
end)
UIS.InputChanged:Connect(function(input)
    if input == dragInput and dragging then
        local delta = input.Position - dragStart
        frame.Position = UDim2.new(
            startPos.X.Scale, startPos.X.Offset + delta.X,
            startPos.Y.Scale, startPos.Y.Offset + delta.Y
        )
    end
end)

refreshButton()

-- ---------- Loop ----------
RunService.Heartbeat:Connect(function()
    if not CONFIG.enabled then return end
    local now = os.clock()

    local hum = getHum()
    if not hum or hum.Health <= 0 then return end

    local threats, nearest = getThreats()
    if #threats == 0 then return end

    local cd = (nearest <= CONFIG.closeRange) and CONFIG.closeCooldown or CONFIG.cooldown
    if now - lastDodge < cd then return end

    local dir = escapeVector(threats)
    if not dir then return end

    lastDodge = now
    doDodge(dir)
end)

-- RightShift also toggles
UIS.InputBegan:Connect(function(input, gp)
    if gp then return end
    if input.KeyCode == Enum.KeyCode.RightShift then
        CONFIG.enabled = not CONFIG.enabled
        refreshButton()
    end
end)
Executor compatibility changes over time. Check current reports before testing.

Script #16 [+] Noclip & More (undetected Update)

Script #16 · [+] Noclip & MoreFree
[+] Noclip[+] Anti-Ragdoll[+] Reset Character[+] Clear Screen Overlays[+] Hitbox Expander[+] Hitbox Size Adjuster
loadstring(game:HttpGet("https://raw.githubusercontent.com/AM1HUB/script/refs/heads/main/scriptcolection/HV/v1.lua"))()
Executor compatibility changes over time. Check current reports before testing.

Script #17 HUSS VALLEY & More

Script #17 · HUSS VALLEY & MoreFree
HUSS VALLEYAutoAuto play: plays the rounds for you.As a chaser: chases and catches.RunnerAuto revive: gets downed teammates next to you back up.
loadstring(game:HttpGet("https://raw.githubusercontent.com/9okVR/VALOR_HUB/refs/heads/main/ValorHub_Loader"))()
Executor compatibility changes over time. Check current reports before testing.

Script #18 Auto Revive — walks to downed teammates and revives them & More

Script #18 · Auto Revive — walks to downed teammates and revives them & MoreFree
Auto Revive — walks to downed teammates and revives themCollect Gems — grabs gems along your route automaticallyDash Away — auto dashes when a catcher gets too closeAuto Chase — runs down the best reachable runner as catcherAuto Tackle — tackles runners once inside tackle rangeAuto Melee — swings at runners in melee range
loadstring(game:HttpGet("https://raw.githubusercontent.com/Ziorxddd/hussvalley/refs/heads/main/hussvalleywind.lua"))()
Executor compatibility changes over time. Check current reports before testing.

Script #19 K0rdHub (BOSS Update)

Script #19 · K0rdHubFree
Auto TackleAuto CatchAuto ChaseAuto HuntAuto RunAuto Cross
loadstring(game:HttpGet("https://raw.githubusercontent.com/k0rdhub/scripts/main/huss-valley-keyless-script.lua"))()
Executor compatibility changes over time. Check current reports before testing.

Script #20 + ESP (Runner & Catcher) & More

Script #20 · + ESP (Runner & Catcher) & MoreFree
+ ESP (Runner & Catcher)+ Auto Dodge+ Auto Catcher+ Auto Lunge+ Customizable Speed & Lunge+ Visual Indicators
loadstring(game:HttpGet("https://api.jnkie.com/api/v1/luascripts/public/0858084d4c5d970e0404f4c685044676f4129d385ae4e44f47d77f0c2f734429/download"))()
Executor compatibility changes over time. Check current reports before testing.

Script #21 Nice Scripttt & More

Script #21 · Nice Scripttt & MoreFree
Nice Scripttt
loadstring(game:HttpGet("https://flowauth.net/v1/loaders/e25a1868cdbf1fbdb3697cc06ee1cd52.lua"))()
Executor compatibility changes over time. Check current reports before testing.

Updated and tested for the latest BOSS Update, this script automates the newest event tasks so you can keep up without the extra grind.

Updated and tested for the latest undetected Update, this script automates the newest event tasks so you can keep up without the extra grind.

Updated and tested for the latest leaked open src Update, this script automates the newest event tasks so you can keep up without the extra grind.

Updated and tested for the latest OPEN SOURCE Update, this script automates the newest event tasks so you can keep up without the extra grind.

Copy the code above into a compatible Roblox script executor if you choose to test it.

Huss Valley Script Status

Availability
Listed
Price
Free
Compatibility
Check before use
Safety
Not guaranteed

Roblox and game updates can affect compatibility, so the script’s status should be treated as temporary rather than guaranteed.

What Is a Huss Valley Script?

A Huss Valley script is Lua code intended to run alongside the Roblox game through a third-party script executor.

Different scripts can contain different code and features. This version includes the following features:

✓ Auto Farm✓ Auto Collect

How to Use the Huss Valley Script

If you decide to test a third-party Roblox script, the general process involves a compatible executor and the Lua code provided above.

01
Choose a Roblox Script Executor
Pick a compatible executor such as Hydrogen, MacSploit, AWP.GG, Delta, Fluxus, Codex. Compatibility changes over time, so a name here doesn’t guarantee current support.
02
Open Roblox and Join the Game
Launch Roblox, join the game, and keep it open while you prepare the executor.
03
Copy the Lua Script
Copy the complete code from the script card above without changing any part of it.
04
Run Your Executor
Open your executor and paste the code into its editor.
05
Execute the Script
Click Run or Execute. If the script still supports the current game version, it should load.

Can a Huss Valley Script Get Your Roblox Account Banned?

⚠️ Yes, it can. Third-party scripts can violate Roblox rules and may put an account at risk.
  • Only use code from a source you trust.
  • Never enter your Roblox password into a script or executor.
  • Test on an alternate account first.

Huss Valley Script for Mobile

If you’re searching for a Huss Valley script for mobile, check whether both the executor and the script support your device and current Roblox version. Mobile executor support does not guarantee that every script will work.

Frequently Asked Questions

What is a Huss Valley script?

A Huss Valley script is third-party Lua code intended to run alongside the Roblox game through a compatible script executor.

What features does this Huss Valley script include?

Different scripts contain different code. This version includes: Auto Farm, Kill Aura, ESP, Silent Aim, Teleport, Speed Boost, Fly, Noclip, God Mode, Auto Collect, Auto Click, Anti-AFK, Auto Spin, Nice Scripttt.

How do you use the Huss Valley script?

Pick a compatible executor such as Hydrogen, MacSploit, AWP.GG, Delta, Fluxus, Codex, launch Roblox and join the game, copy the complete Lua code from the script card above, paste it into the executor’s editor, and click Run or Execute. Compatibility changes over time, so a name here doesn’t guarantee current support.

Can a Huss Valley script get your Roblox account banned?

Yes. Third-party scripts can violate Roblox rules and may put an account at risk. Only use code from a source you trust, never enter your Roblox password into a script or executor, and test on an alternate account first.

Does the Huss Valley script work on mobile?

Check whether both the executor and the script support your device and the current Roblox version. Mobile executor support does not guarantee that every script will work.

Check out our Roblox Scripts hub and Roblox Games Directory for more.