local SHARKWOW_DEVICE_OVERRIDE='mobile'
local getthreadidentity=getthreadidentity or getidentity
local setthreadidentity=setthreadidentity or setidentity
local queue_on_teleport=queue_on_teleport or queueonteleport or (syn and syn.queue_on_teleport)
local debug=table.clone(debug)
debug.getupvalues=debug.getupvalues or getupvalues
debug.getupvalue=debug.getupvalue or getupvalue
local DevicePolicy=(function()
local Policy={}
function Policy.inspect(mode,touch,api)
    assert(mode=='auto' or mode=='pc' or mode=='mobile','Device mode must be auto, pc or mobile')
    local report={Mode=mode=='auto' and (touch and 'mobile' or 'pc') or mode,Missing={},Capabilities={}}
    report.Touch=report.Mode=='mobile'
    for _,name in ipairs({'getgenv','loadstring','readfile','writefile','isfile'}) do
        if type(api[name])~='function' then table.insert(report.Missing,name) end
    end
    for _,name in ipairs({'getconnections','firesignal','fireproximityprompt','request','queue','getupvalues'}) do
        report.Capabilities[name]=type(api[name])=='function' and 'present-unverified' or 'absent'
    end
    report.Ready=#report.Missing==0
    return report
end
-- Select exactly one callback path; never retry a potentially accepted click.
function Policy.activate(button,connections,signalFire,spawn)
    if not button or not button.Visible or not button.Active then return false end
    for _,signal in ipairs({button.Activated,button.MouseButton1Click}) do
        if type(connections)=='function' then
            local ok,list=pcall(connections,signal)
            if ok and type(list)=='table' then
                for _,connection in ipairs(list) do
                    if connection.Enabled~=false and type(connection.Function)=='function' then
                        spawn(connection.Function);return true
                    end
                end
            end
        end
    end
    if type(signalFire)=='function' then signalFire(button.Activated);return true end
    error('Native button activation unavailable on this executor',0)
end
return Policy

end)()
local deviceReport=DevicePolicy.inspect(SHARKWOW_DEVICE_OVERRIDE or (type(getgenv)=='function' and getgenv().SHARKWOW_DEVICE_MODE) or 'auto',game:GetService('UserInputService').TouchEnabled,{
 getgenv=getgenv,loadstring=loadstring,readfile=readfile,writefile=writefile,isfile=isfile,
 getconnections=getconnections,firesignal=firesignal,fireproximityprompt=fireproximityprompt,
 request=request or http_request or (syn and syn.request),queue=queue_on_teleport,getupvalues=debug.getupvalues})
assert(deviceReport.Ready,'SHARKWOW STAND OUT / missing executor APIs: '..table.concat(deviceReport.Missing,', '))

--!strict
local initialThreadIdentity = type(getthreadidentity) == "function" and getthreadidentity() or nil
if initialThreadIdentity and initialThreadIdentity ~= 2 and type(setthreadidentity) == "function" then setthreadidentity(2) end
local HttpService = game:GetService("HttpService")
local Players = game:GetService("Players")
local RunService = game:GetService("RunService")
local TweenService = game:GetService("TweenService")
local UserInputService = game:GetService("UserInputService")
local VirtualUser = game:GetService("VirtualUser")
local Workspace = game:GetService("Workspace")

assert(game.PlaceId == 128828638194450, "item finder: unsupported place")
assert(type(getgenv) == "function", "item finder: shared environment unavailable")
local environment = getgenv()
local key = "MT_ArrowRokakaFinder"
local previous = environment[key]
if previous and previous.Alive then
 local ps=Players.LocalPlayer:FindFirstChild("PlayerScripts")
 local core=ps and ps:FindFirstChild("Core")
 assert(core and core:FindFirstChild("TrainRaidClient"),"Hot reload deferred: native modules unavailable; existing hub preserved")
end
local retained = {}
if previous and previous.Alive then
    for _, setting in ipairs({"AutoArrow", "AutoRokaka", "Flying", "Noclip", "NoFall", "FarmHide"}) do
        if type(previous[setting]) == "boolean" then retained[setting] = previous[setting] end
    end
    retained.FlySpeed = previous.FlySpeed
    retained.Appearance = previous.Appearance
    retained.Advanced = previous.Advanced and previous.Advanced.Snapshot()
    if retained.Advanced and type(retained.Advanced.FeatureStates) ~= "table" then
        retained.Advanced.FeatureStates = {}
        for id, feature in pairs(previous.Advanced.Features) do
            if not feature.Action and not feature.Locked and not feature.HeldForReview then
                local ok, value = pcall(previous.Advanced.Get, id)
                if ok and type(value) == "boolean" then retained.Advanced.FeatureStates[id] = id ~= "Webhook" and value or false end
            end
        end
    end
    retained.AutoCollected = previous.AutoCollected
    retained.LastPickup = previous.LastPickup
    local previousGui = Players.LocalPlayer and Players.LocalPlayer:FindFirstChild("PlayerGui")
    local previousWindow = previousGui and previousGui:FindFirstChild("MT_ArrowRokakaFinder")
    local previousPanel = previousWindow and previousWindow:FindFirstChild("Panel")
    if previousPanel and previousPanel:IsA("GuiObject") then retained.Position = previousPanel.AbsolutePosition end
end
local gardenBeforeReload = environment.MT_RokakaGardenRun
if gardenBeforeReload and gardenBeforeReload.Alive and gardenBeforeReload.Busy and type(gardenBeforeReload.WantedArrow) == "boolean" then
    retained.AutoArrow = gardenBeforeReload.WantedArrow
    if type(gardenBeforeReload.WantedRokaka) == "boolean" then retained.AutoRokaka = gardenBeforeReload.WantedRokaka end
end
local resume = environment.SHARKWOW_STANDOUT_RESUME
environment.SHARKWOW_STANDOUT_RESUME = nil
if type(resume) == "table" and resume.UserId == Players.LocalPlayer.UserId and resume.Schema == 1 and resume.Enabled == true
    and type(resume.Created) == "number" and math.abs(os.time() - resume.Created) < 900 then
    for _, setting in ipairs({"AutoArrow", "AutoRokaka", "FarmHide"}) do
        if type(resume[setting]) == "boolean" then retained[setting] = resume[setting] end
    end
end
if previous and type(previous.Unload) == "function" then previous.Unload() end
local player = Players.LocalPlayer
assert(player, "item finder: local player unavailable")
do
    local deadline = os.clock() + 60
    repeat
        local data = player:FindFirstChild("Data")
        local stats = data and data:FindFirstChild("Stats")
        if data and data:GetAttribute("Loaded") and stats and stats:FindFirstChild("Inventory")
            and stats:FindFirstChild("ActiveBounties") and stats:FindFirstChild("BountyProgress")
            and data:FindFirstChild("Skills") and data:FindFirstChild("Stand") then break end
        assert(os.clock() < deadline, "stand out player data did not become ready")
        task.wait(0.2)
    until false
end
local playerGui = player:WaitForChild("PlayerGui", 10)
assert(playerGui, "item finder: player gui unavailable")

type Target = {instance: Instance, part: BasePart, name: string, kind: string, detail: string, distance: number}
type Marker = {gui: BillboardGui, text: TextLabel}
local alive = true
local connections: {RBXScriptConnection} = {}
local markers: {[Instance]: Marker} = {}
local state = {Version = "1.8.3", Alive = true, Count = 0, Arrow = 0, Rokaka = 0, Seeds = 0, LastError = "", AntiAFK = "ready; awaiting idle", TeleportStatus = "choose an item above", TeleportBusy = false, Flying = false, Noclip = false, NoFall = true, FallBraking = false, MovementError = "", FlySpeed = 40, AutoArrow = false, AutoRokaka = false, AutoBusy = false, AutoStatus = "auto farming is off", AutoAttempts = 0}
state.RaidBusy=player:GetAttribute("TrainRaidActive")==true
if type(readfile)=="function" then
    local ok,raid=pcall(function() return HttpService:JSONDecode(readfile("sharkwow-standout-raid-"..player.UserId..".json")) end)
    if ok and type(raid)=="table" and raid.Schema==1 and raid.UserId==player.UserId and raid.PendingResult then state.RaidBusy=true end
end
state.ExtensionPause=state.RaidBusy
state.CraftBusy=state.RaidBusy
do
    local options = retained.Advanced
    if not options and type(readfile) == "function" then
        local ok,data=pcall(function()
            local path="sharkwow-standout-modules-"..player.UserId..".json"
            if type(isfile)=="function" and not isfile(path) then path="sharkwow-standout-modules.json" end
            return HttpService:JSONDecode(readfile(path))
        end)
        if ok and type(data)=="table" and data.Schema==1 then options=data end
    end
    state.WaitForArrow=type(options)=="table" and type(options.Options)=="table" and type(options.Options.WaitForArrow)=="table" and options.Options.WaitForArrow.ResumeEnabled==true or false
    if type(readfile)=="function" then
        local ok,phone=pcall(function() return HttpService:JSONDecode(readfile("sharkwow-standout-phone-"..player.UserId..".json")) end)
        state.PhoneBusy=ok and type(phone)=="table" and phone.Schema==1 and phone.UserId==player.UserId and (phone.Enabled==true or phone.Handoff==true) or false
    end
end
state.AutoCollected = type(retained.AutoCollected) == "number" and retained.AutoCollected or 0
state.LastPickup = retained.LastPickup
do
    local installSkip=(function()
return function(state,environment,job)
    local saved=environment.SHARKWOW_STANDOUT_ARROW_SKIPS
    if type(saved)~="table" or saved.Job~=job or type(saved.Entries)~="table" then
        saved={Job=job,Entries=setmetatable({},{__mode="k"}),Total=0}
        environment.SHARKWOW_STANDOUT_ARROW_SKIPS=saved
    end
    state.SkippedArrowCount=saved.Total or 0
    state.ArrowSkipVersion=4
    function state.IsArrowSkipped(instance)
        local record=saved.Entries[instance]
        if not record then return false end
        if instance:GetAttribute("WorldItemSpawnedAt")~=record.SpawnedAt or instance:GetAttribute("ItemName")~=record.Name then
            saved.Entries[instance]=nil
            return false
        end
        local retryAt=math.min(record.RetryAt or(record.At or 0)+5,(record.At or 0)+30)
        return os.time()<retryAt
    end
    function state.ArrowNeedsGround(instance)
        state.IsArrowSkipped(instance)
        local record=saved.Entries[instance]
        return record~=nil and(record.Ground==true or record.Reason=="inventory gain not confirmed")
    end
    function state.SkipArrow(instance,reason)
        if not instance or not instance.Parent or state.IsArrowSkipped(instance) then return end
        local previous=saved.Entries[instance]
        local attempts=previous and(previous.Attempts or 1)+1 or 1
        local delay=math.min(30,5*2^math.min(attempts-1,3))
        saved.Entries[instance]={Reason=reason,At=os.time(),RetryAt=os.time()+delay,Attempts=attempts,
            Ground=reason=="inventory gain not confirmed"or(previous and previous.Ground==true),
            SpawnedAt=instance:GetAttribute("WorldItemSpawnedAt"),Name=instance:GetAttribute("ItemName")}
        saved.Total=(saved.Total or 0)+1
        state.SkippedArrowCount=saved.Total
        state.LastSkippedArrow={Name=instance:GetAttribute("ItemName") or instance.Name,Reason=reason,At=os.time(),RetryIn=delay}
    end
end

    end)()
    installSkip(state,environment,game.JobId)
end
state.InventoryCounts = {}
state.InventoryReady = false
state.TransferPending = false
state.ResumeStatus = "preparing"
state.RouteBusy = false
state.RouteCount = 0
state.RouteVisits = 0
state.RouteArrivals = 0
state.RouteError = ""
state.RouteStatus = ""
state.RouteLog = {}
state.FarmHide = false
state.FarmHideActive = false
state.HopBusy = false
state.HopStatus = ""
state.RestoredFromHop = type(resume) == "table" and resume.Enabled == true or false
local resumeFile = "sharkwow-standout-resume-"..player.UserId..".json"
state.ResumeFile=resumeFile
local autoGeneration = 0
for _, setting in ipairs({"AutoArrow", "AutoRokaka", "Flying", "Noclip", "NoFall", "FarmHide"}) do
    if retained[setting] ~= nil then state[setting] = retained[setting] end
end
local visualTweens: {[Instance]: Tween} = {}
local appearance = {Scale = 100, Glow = 65, Speed = 100, Effects = true, Particles = true, ReducedMotion = false}
local appearanceFile = "sharkwow-stand-out-appearance-" .. player.UserId .. ".json"
local savedAppearance = retained.Appearance
if not savedAppearance and type(readfile) == "function" and type(isfile) == "function" then
    local ok, data = pcall(function()
        if isfile(appearanceFile) then return HttpService:JSONDecode(readfile(appearanceFile)) end
        if isfile("sharkwow-stand-out-appearance.json") then return HttpService:JSONDecode(readfile("sharkwow-stand-out-appearance.json")) end
        return nil
    end)
    if ok and type(data) == "table" and data.Schema == 1 then
        savedAppearance = data.Appearance
        retained.FlySpeed = data.FlySpeed
        local position = data.WindowPosition
        if not retained.Position and type(position) == "table" and type(position.X) == "number" and type(position.Y) == "number"
            and position.X == position.X and position.Y == position.Y and math.abs(position.X) < 100000 and math.abs(position.Y) < 100000 then
            retained.Position = Vector2.new(position.X, position.Y)
        end
    end
end
if type(savedAppearance) == "table" then
    for name, bounds in pairs({Scale = {65, 115}, Glow = {0, 100}, Speed = {50, 200}}) do
        local value = savedAppearance[name]
        if type(value) == "number" and value == value and math.abs(value) < math.huge then appearance[name] = math.clamp(value, bounds[1], bounds[2]) end
    end
    for _, name in ipairs({"Effects", "Particles", "ReducedMotion"}) do
        if type(savedAppearance[name]) == "boolean" then appearance[name] = savedAppearance[name] end
    end
end
if type(retained.FlySpeed) == "number" and retained.FlySpeed == retained.FlySpeed and math.abs(retained.FlySpeed) < math.huge then state.FlySpeed = math.clamp(retained.FlySpeed, 10, 200) end
state.Appearance = appearance
local saveGeneration = 0
local function savePreferences(immediate: boolean?)
    saveGeneration += 1
    local generation = saveGeneration
    local function persist()
        if not alive or generation ~= saveGeneration or type(writefile) ~= "function" then return end
        local ok, err = pcall(function()
            local position = state.WindowPosition
            writefile(appearanceFile, HttpService:JSONEncode({Schema = 1, Appearance = appearance, FlySpeed = state.FlySpeed,
                WindowPosition = position and {X = position.X, Y = position.Y} or nil}))
        end)
        state.PreferenceError = ok and "" or tostring(err)
    end
    if immediate then persist() else task.delay(0.3, persist) end
end
local activePrompt: ProximityPrompt? = nil
local releaseFastPickup = nil
local gui = Instance.new("ScreenGui")
gui.Name = "MT_ArrowRokakaFinder"
gui.ResetOnSpawn = false
gui.DisplayOrder = 100
gui.ZIndexBehavior = Enum.ZIndexBehavior.Sibling
gui.Parent = playerGui
local panel = Instance.new("ScrollingFrame")
panel.Name = "Panel"
panel.Position = UDim2.new(0, 14, 0.08, 0)
panel.Size = UDim2.new(0.92, 0, 0.84, 0)
panel.CanvasSize = UDim2.fromOffset(0, 878)
panel.ScrollBarThickness = 6
panel.ScrollingDirection = Enum.ScrollingDirection.Y
panel.Active = true
panel.BackgroundColor3 = Color3.fromRGB(23, 25, 30)
panel.BorderSizePixel = 0
panel.Parent = gui
local limit = Instance.new("UISizeConstraint")
limit.MaxSize = Vector2.new(440, 710)
limit.Parent = panel
local corner = Instance.new("UICorner")
corner.CornerRadius = UDim.new(0, 10)
corner.Parent = panel
local function label(name: string, y: number, height: number, size: number): TextLabel
    local text = Instance.new("TextLabel")
    text.Name = name
    text.Position = UDim2.new(0, 12, 0, y)
    text.Size = UDim2.new(1, -24, 0, height)
    text.BackgroundTransparency = 1
    text.TextColor3 = Color3.fromRGB(233, 235, 239)
    text.Font = Enum.Font.GothamBold
    text.TextSize = size
    text.TextXAlignment = Enum.TextXAlignment.Left
    text.TextYAlignment = Enum.TextYAlignment.Top
    text.TextWrapped = true
    text.Parent = panel
    return text
end
local title = label("Title", 14, 30, 22)
title.Text = "arrow + rokaka finder"
title.Font = Enum.Font.GothamBold
local summary = label("Summary", 52, 40, 16)
local listTitle = label("ListTitle", 518, 26, 18)
listTitle.Text = "nearest available items"
local list = label("Nearest", 552, 150, 16)
local status = label("Status", 710, 42, 14)
status.TextColor3 = Color3.fromRGB(165, 175, 188)
local teleportStatus = label("TeleportStatus", 760, 50, 16)
teleportStatus.Text = state.TeleportStatus
local function button(name: string, text: string, x: number): TextButton
    local b = Instance.new("TextButton")
    b.Name = name
    b.Position = UDim2.new(x, 12, 0, 818)
    b.Size = UDim2.new(0.5, -20, 0, 44)
    b.BackgroundColor3 = Color3.fromRGB(47, 51, 59)
    b.BorderSizePixel = 0
    b.TextColor3 = Color3.fromRGB(235, 237, 240)
    b.Font = Enum.Font.GothamBold
    b.TextSize = 17
    b.TextWrapped = true
    b.Text = text
    b.Parent = panel
    local radius = Instance.new("UICorner")
    radius.CornerRadius = UDim.new(0, 8)
    radius.Parent = b
    return b
end
local hide = button("HideMarkers", "markers: on", 0)
local close = button("Unload", "unload", 0.5)
local warpArrow = button("TeleportArrow", "tp arrow", 0)
local warpRokaka = button("TeleportRokaka", "tp rokaka", 0.5)
warpArrow.Position = UDim2.new(0, 12, 0, 100)
warpRokaka.Position = UDim2.new(0.5, 12, 0, 100)
warpArrow.TextColor3 = Color3.fromRGB(255, 211, 110)
warpRokaka.TextColor3 = Color3.fromRGB(244, 142, 178)
local flyButton = button("Fly", "fly: off", 0)
local noclipButton = button("Noclip", "noclip: off", 0.5)
local autoArrowButton = button("AutoArrow", "auto arrow: off", 0)
local autoRokakaButton = button("AutoRokaka", "auto rokaka: off", 0.5)
autoArrowButton.Position = UDim2.new(0, 12, 0, 152)
autoRokakaButton.Position = UDim2.new(0.5, 12, 0, 152)
local autoStatus = label("AutoStatus", 204, 44, 16)
autoStatus.Text = state.AutoStatus
flyButton.Position = UDim2.new(0, 12, 0, 256)
noclipButton.Position = UDim2.new(0.5, 12, 0, 256)
local upButton = button("FlyUp", "hold: up", 0)
local downButton = button("FlyDown", "hold: down", 0.5)
upButton.Position = UDim2.new(0, 12, 0, 308)
downButton.Position = UDim2.new(0.5, 12, 0, 308)
local noFallButton = button("NoFall", "no fall: on", 0)
noFallButton.Position = UDim2.fromOffset(12, 360)
noFallButton.Size = UDim2.new(1, -28, 0, 44)
local movementStatus = label("MovementStatus", 422, 40, 15)
local help = label("Help", 470, 42, 16)
help.Text = "fly: wasd / joystick to move\nspace: up    left ctrl: down"
local cleanupMovement: () -> ()
local visible = true
local function unload(preserveResume)
    preserveResume = preserveResume == true
    if not alive then return end
    savePreferences(true)
    if state.Advanced then state.Advanced.Stop() end
    alive = false
    state.Alive = false
    for thread in pairs(state.StreamWorkers or {}) do pcall(task.cancel, thread) end
    if not preserveResume then
    if type(writefile) == "function" then pcall(writefile, resumeFile, '{"Schema":1,"Enabled":false}') end
    end
    for _, tween in pairs(visualTweens) do tween:Cancel() end
    table.clear(visualTweens)
    autoGeneration += 1
    state.AutoArrow, state.AutoRokaka = false, false
    if releaseFastPickup then releaseFastPickup(); releaseFastPickup=nil end
    if activePrompt then pcall(function() activePrompt:InputHoldEnd() end); activePrompt = nil end
    cleanupMovement()
    for _, connection in ipairs(connections) do connection:Disconnect() end
    table.clear(connections)
    gui:Destroy()
    table.clear(markers)
    if environment[key] == state then environment[key] = nil end
end
state.Unload = unload
environment[key] = state
table.insert(connections, close.Activated:Connect(unload))
table.insert(connections, hide.Activated:Connect(function()
    visible = not visible
    hide.Text = visible and "markers: on" or "markers: off"
    for _, marker in pairs(markers) do marker.gui.Enabled = visible end
end))
table.insert(connections, gui.Destroying:Connect(unload))

type Flight = {root: BasePart, humanoid: Humanoid, platform: boolean, autoRotate: boolean, attachment: Attachment?, velocity: LinearVelocity?, orientation: AlignOrientation?}
local flight: Flight? = nil
local fallAttachment: Attachment? = nil
local fallVelocity: LinearVelocity? = nil
local fallRoot: BasePart? = nil
local collisionOriginals: {[BasePart]: boolean} = {}
local noclipCharacter: Model? = nil
local noclipAdded: RBXScriptConnection? = nil
local hiddenMotion = nil
local stopHidden: (boolean) -> ()
local heldUp, heldDown = false, false
local focused = true
local function repaintMovement()
    flyButton.Text = state.Flying and "fly: on" or "fly: off"
    noclipButton.Text = state.Noclip and "noclip: on" or "noclip: off"
    flyButton.BackgroundColor3 = state.Flying and Color3.fromRGB(35, 101, 78) or Color3.fromRGB(47, 51, 59)
    noclipButton.BackgroundColor3 = state.Noclip and Color3.fromRGB(35, 101, 78) or Color3.fromRGB(47, 51, 59)
    noFallButton.Text = state.NoFall and "no fall: on / gentle landing" or "no fall: off"
    noFallButton.BackgroundColor3 = state.NoFall and Color3.fromRGB(35, 101, 78) or Color3.fromRGB(47, 51, 59)
    movementStatus.Text = state.MovementError ~= "" and state.MovementError or string.format("fly speed: %d studs/s | noclip %s", state.FlySpeed, state.Noclip and "on" or "off")
    if state.RefreshUI then state.RefreshUI() end
end
local function stopFlight()
    local old = flight
    flight = nil
    if not old then return end
    if old.velocity then old.velocity:Destroy() end
    if old.orientation then old.orientation:Destroy() end
    if old.attachment then old.attachment:Destroy() end
    if old.humanoid.Parent then
        old.humanoid.PlatformStand = old.platform
        old.humanoid.AutoRotate = old.autoRotate
        if old.humanoid.Health > 0 and not old.platform then
            old.humanoid:ChangeState(Enum.HumanoidStateType.GettingUp)
        end
    end
    if old.root.Parent then
        old.root.AssemblyLinearVelocity = Vector3.zero
        old.root.AssemblyAngularVelocity = Vector3.zero
    end
end
local function restoreCollisions()
    if noclipAdded then noclipAdded:Disconnect(); noclipAdded = nil end
    noclipCharacter = nil
    for part, original in pairs(collisionOriginals) do
        local ok, err = pcall(function() part.CanCollide = original end)
        if not ok then warn("item finder collision restore: " .. tostring(err)) end
    end
    table.clear(collisionOriginals)
end
local function stopFallBrake()
    if fallVelocity then fallVelocity:Destroy(); fallVelocity = nil end
    if fallAttachment then fallAttachment:Destroy(); fallAttachment = nil end
    fallRoot = nil
    state.FallBraking = false
end
cleanupMovement = function()
    state.Flying, state.Noclip, state.NoFall = false, false, false
    heldUp, heldDown = false, false
    stopFlight()
    stopHidden(true)
    restoreCollisions()
    stopFallBrake()
end
local function rememberPart(instance: Instance)
    if instance:IsA("BasePart") and collisionOriginals[instance] == nil then
        collisionOriginals[instance] = instance.CanCollide
    end
end
stopHidden = function(returnToGround: boolean)
    local old = hiddenMotion
    hiddenMotion = nil
    state.FarmHideActive = false
    state.IdleHoldActive = false
    if not old then return end
    if old.velocity then old.velocity:Destroy() end
    if old.attachment then old.attachment:Destroy() end
    if old.anchorBefore ~= nil and old.root.Parent then old.root.Anchored = old.anchorBefore end
    if returnToGround and player.Character == old.character and old.root.Parent
        and (old.root.Position - old.position).Magnitude < 25 then
        old.character:PivotTo(old.ground * old.root.CFrame:ToObjectSpace(old.character:GetPivot()))
        old.root.AssemblyLinearVelocity = Vector3.zero
    end
    if not state.Noclip then restoreCollisions() end
end
local function beginHidden(character: Model, root: BasePart, point: Vector3, ground: Vector3): Vector3
    stopHidden(false)
    stopFallBrake()
    local position = point - Vector3.new(0, 6, 0)
    local owned = {character = character, root = root, position = position, ground = CFrame.new(ground)}
    hiddenMotion = owned
    state.FarmHideActive = true
    if noclipCharacter ~= character then
        restoreCollisions()
        noclipCharacter = character
        for _, part in ipairs(character:GetDescendants()) do rememberPart(part) end
        noclipAdded = character.DescendantAdded:Connect(rememberPart)
    end
    for part in pairs(collisionOriginals) do if part:IsDescendantOf(character) then part.CanCollide = false end end
    local attachment = Instance.new("Attachment")
    attachment.Name = "MT_FarmHoldAttachment"
    attachment.Parent = root
    owned.attachment = attachment
    local velocity = Instance.new("LinearVelocity")
    velocity.Name = "MT_FarmHoldVelocity"
    velocity.Attachment0 = attachment
    velocity.RelativeTo = Enum.ActuatorRelativeTo.World
    velocity.VelocityConstraintMode = Enum.VelocityConstraintMode.Vector
    velocity.VectorVelocity = Vector3.zero
    velocity.ForceLimitsEnabled = false
    velocity.Parent = root
    owned.velocity = velocity
    return position
end
function state.ReleaseIdleHide()
    if state.IdleHoldActive then stopHidden(true) end
end
function state.WaitHidden()
    if not state.WaitForArrow or not state.FarmHide or not (state.AutoArrow or state.AutoRokaka or state.AutoParts)
        or state.AutoBusy or state.TeleportBusy or state.CraftBusy or state.AutoHopPause or state.HopBusy or state.TransferPending or state.Flying then return end
    local gardener=environment.MT_RokakaGardenRun
    if gardener and gardener.Alive and gardener.Busy then return end
    local character=player.Character
    local root=character and character:FindFirstChild("HumanoidRootPart")
    local humanoid=character and character:FindFirstChildOfClass("Humanoid")
    if not root or not humanoid or humanoid.Health<=0 or root.Anchored or humanoid.SeatPart then return end
    local anchor=state.IdleAnchor
    if not anchor or anchor.Character~=character then
        local point,ground
        if hiddenMotion and hiddenMotion.character==character then
            ground=hiddenMotion.ground.Position
            point=hiddenMotion.position+Vector3.new(0,6,0)
        else
            local params=RaycastParams.new();params.FilterType=Enum.RaycastFilterType.Exclude;params.FilterDescendantsInstances={character}
            local hit=Workspace:Raycast(root.Position+Vector3.new(0,4,0),Vector3.new(0,-30,0),params)
            if not hit or hit.Normal.Y<0.5 or hit.Position.Y-6<Workspace.FallenPartsDestroyHeight+20 then
                state.TeleportStatus="waiting for a supported hide spot"
                return
            end
            point=hit.Position
            ground=point+Vector3.new(0,humanoid.HipHeight+root.Size.Y/2+0.3,0)
        end
        anchor={Character=character,Point=point,Ground=ground}
        state.IdleAnchor=anchor
    end
    if state.IdleHoldActive and hiddenMotion and hiddenMotion.character==character then return end
    local destination=beginHidden(character,root,anchor.Point,anchor.Ground)
    root.CFrame=CFrame.new(destination)*root.CFrame.Rotation
    root.AssemblyLinearVelocity=Vector3.zero
    root.AssemblyAngularVelocity=Vector3.zero
    hiddenMotion.anchorBefore=root.Anchored
    root.Anchored=true
    state.IdleHoldActive=true
end

function state.SetFarmHide(enabled: boolean)
    state.FarmHide = enabled == true
    autoGeneration += 1
    if not state.FarmHide then stopHidden(true) end
    if state.RefreshUI then state.RefreshUI() end
end
local function setFlying(value: boolean)
    if value then stopHidden(true) end
    state.Flying = value
    state.MovementError = ""
    if not value then heldUp, heldDown = false, false; stopFlight() end
    repaintMovement()
end
local function setNoclip(value: boolean)
    state.Noclip = value
    state.MovementError = ""
    if not value and not state.FarmHideActive then restoreCollisions() end
    repaintMovement()
end
table.insert(connections, flyButton.Activated:Connect(function() setFlying(not state.Flying) end))
table.insert(connections, noclipButton.Activated:Connect(function() setNoclip(not state.Noclip) end))
function state.SetNoFall(value)
    state.NoFall=value==true
    if not state.NoFall then stopFallBrake() end
    repaintMovement()
end
table.insert(connections, noFallButton.Activated:Connect(function()
    state.NoFall = not state.NoFall
    if not state.NoFall then stopFallBrake() end
    repaintMovement()
end))
table.insert(connections, upButton.MouseButton1Down:Connect(function() heldUp = true end))
table.insert(connections, upButton.MouseButton1Up:Connect(function() heldUp = false end))
table.insert(connections, downButton.MouseButton1Down:Connect(function() heldDown = true end))
table.insert(connections, downButton.MouseButton1Up:Connect(function() heldDown = false end))
local touchUp: InputObject? = nil
local touchDown: InputObject? = nil
table.insert(connections, upButton.InputBegan:Connect(function(input)
    if input.UserInputType == Enum.UserInputType.Touch then touchUp = input; heldUp = true end
end))
table.insert(connections, downButton.InputBegan:Connect(function(input)
    if input.UserInputType == Enum.UserInputType.Touch then touchDown = input; heldDown = true end
end))
table.insert(connections, UserInputService.InputEnded:Connect(function(input)
    if input == touchUp then touchUp = nil; heldUp = false end
    if input == touchDown then touchDown = nil; heldDown = false end
    if input.UserInputType == Enum.UserInputType.MouseButton1 then heldUp, heldDown = false, false end
end))
table.insert(connections, UserInputService.WindowFocusReleased:Connect(function()
    focused = false; heldUp, heldDown = false, false
end))
table.insert(connections, UserInputService.WindowFocused:Connect(function() focused = true end))
table.insert(connections, player.CharacterRemoving:Connect(function()
    autoGeneration += 1
    stopHidden(false)
    heldUp, heldDown = false, false
    stopFlight(); restoreCollisions(); stopFallBrake()
end))
local function movementStep()
    if state.FarmHideActive and (not state.FarmHide or not (state.AutoArrow or state.AutoRokaka or state.AutoParts) or state.Flying) then stopHidden(true) end
    if not alive or not state.Flying and not state.Noclip and not state.NoFall and not state.FarmHideActive then return end
    local character = player.Character
    local root = character and character:FindFirstChild("HumanoidRootPart")
    local humanoid = character and character:FindFirstChildOfClass("Humanoid")
    if not character or not root or not root:IsA("BasePart") or not humanoid or humanoid.Health <= 0 then
        stopHidden(false); stopFlight(); restoreCollisions(); stopFallBrake()
        return
    end
    local humanoidState = humanoid:GetState()
    if state.NoFall and not state.Flying and not state.FarmHideActive and not root.Anchored and not humanoid.SeatPart
        and humanoid.FloorMaterial == Enum.Material.Air
        and humanoidState ~= Enum.HumanoidStateType.Swimming
        and humanoidState ~= Enum.HumanoidStateType.Climbing then
        if fallRoot and fallRoot ~= root then stopFallBrake() end
        if root.AssemblyLinearVelocity.Y < -8 or fallRoot == root then
            if not fallVelocity then
                fallRoot = root
                fallAttachment = Instance.new("Attachment")
                fallAttachment.Name = "MT_FallAttachment"
                fallAttachment.Parent = root
                fallVelocity = Instance.new("LinearVelocity")
                fallVelocity.Name = "MT_FallVelocity"
                fallVelocity.Attachment0 = fallAttachment
                fallVelocity.RelativeTo = Enum.ActuatorRelativeTo.World
                fallVelocity.VelocityConstraintMode = Enum.VelocityConstraintMode.Line
                fallVelocity.LineDirection = Vector3.new(0, 1, 0)
                fallVelocity.LineVelocity = -8
                fallVelocity.ForceLimitsEnabled = false
                fallVelocity.Parent = root
            end
            state.FallBraking = true
        end
    else stopFallBrake() end
    if state.Noclip or state.FarmHideActive then
        if noclipCharacter ~= character then
            restoreCollisions()
            noclipCharacter = character
            for _, part in ipairs(character:GetDescendants()) do rememberPart(part) end
            noclipAdded = character.DescendantAdded:Connect(rememberPart)
        end
        for part, original in pairs(collisionOriginals) do
            if part:IsDescendantOf(character) then part.CanCollide = false
            else part.CanCollide = original; collisionOriginals[part] = nil end
        end
    end
    if not state.Flying then return end
    if root.Anchored or humanoid.SeatPart then
        setFlying(false)
        state.MovementError = "fly paused: stand up or wait for movement"
        repaintMovement()
        return
    end
    if flight and flight.root ~= root then stopFlight() end
    if not flight then
        local current: Flight = {root = root, humanoid = humanoid, platform = humanoid.PlatformStand, autoRotate = humanoid.AutoRotate}
        flight = current
        local attachment = Instance.new("Attachment")
        current.attachment = attachment
        attachment.Name = "MT_FlightAttachment"
        attachment.Parent = root
        local velocity = Instance.new("LinearVelocity")
        current.velocity = velocity
        velocity.Name = "MT_FlightVelocity"
        velocity.Attachment0 = attachment
        velocity.RelativeTo = Enum.ActuatorRelativeTo.World
        velocity.VelocityConstraintMode = Enum.VelocityConstraintMode.Vector
        velocity.ForceLimitsEnabled = false
        velocity.VectorVelocity = Vector3.zero
        velocity.Parent = root
        local orientation = Instance.new("AlignOrientation")
        current.orientation = orientation
        orientation.Name = "MT_FlightOrientation"
        orientation.Mode = Enum.OrientationAlignmentMode.OneAttachment
        orientation.Attachment0 = attachment
        orientation.MaxTorque = 1000000
        orientation.Responsiveness = 25
        orientation.Parent = root
    end
    local current = flight
    if not current or not current.velocity or not current.orientation then return end
    humanoid.PlatformStand = true
    humanoid.AutoRotate = false
    local camera = Workspace.CurrentCamera
    local direction = Vector3.zero
    if camera and focused and not UserInputService:GetFocusedTextBox() then
        local function pressed(code: Enum.KeyCode): number return UserInputService:IsKeyDown(code) and 1 or 0 end
        local forward = pressed(Enum.KeyCode.W) - pressed(Enum.KeyCode.S)
        local sideways = pressed(Enum.KeyCode.D) - pressed(Enum.KeyCode.A)
        direction = camera.CFrame.LookVector * forward + camera.CFrame.RightVector * sideways
        if forward == 0 and sideways == 0 then direction = humanoid.MoveDirection end
        local up = (heldUp or pressed(Enum.KeyCode.Space) == 1) and 1 or 0
        local down = (heldDown or pressed(Enum.KeyCode.LeftControl) == 1) and 1 or 0
        direction += Vector3.new(0, up - down, 0)
        local look = camera.CFrame.LookVector
        local flat = Vector3.new(look.X, 0, look.Z)
        if flat.Magnitude > 0.01 then current.orientation.CFrame = CFrame.lookAt(Vector3.zero, flat.Unit) end
    end
    if direction.Magnitude > 1 then direction = direction.Unit end
    current.velocity.VectorVelocity = direction * state.FlySpeed
end
table.insert(connections, RunService.PreSimulation:Connect(function()
    local ok, err = pcall(movementStep)
    if not ok then
        cleanupMovement()
        state.MovementError = "movement stopped: " .. tostring(err):sub(1, 80)
        repaintMovement()
        warn("item finder movement: " .. tostring(err))
    end
end))
repaintMovement()

local idleDue = false
local nextAttempt = 0
local failures = 0
local lastPulse = 0
table.insert(connections, player.Idled:Connect(function() idleDue = true end))
local function keepalive()
    local now = os.clock()
    if now < nextAttempt or now - lastPulse < (idleDue and 45 or 60) then return end
    local identity = type(getthreadidentity) == "function" and getthreadidentity() or nil
    local ok, err = pcall(function()
        if identity and type(setthreadidentity) == "function" then setthreadidentity(8) end
        VirtualUser:CaptureController()
        VirtualUser:ClickButton2(Vector2.new(0, 0))
    end)
    if identity and type(setthreadidentity) == "function" then setthreadidentity(identity) end
    if ok then
        idleDue = false
        failures = 0
        lastPulse = now
        state.AntiAFK = "keepalive sent"
    else
        failures += 1
        nextAttempt = now + math.min(60, 2 ^ math.min(failures, 6))
        state.AntiAFK = "retrying: " .. tostring(err):sub(1, 100)
        if failures == 1 then warn("item finder anti-afk: " .. tostring(err)) end
    end
end
local function classify(value: unknown): string?
    if type(value) ~= "string" then return nil end
    local name = string.lower(value)
    if name == "arrow part" then return "part" end
    if string.find(name, "arrow", 1, true) then return "arrow" end
    if string.find(name, "roka", 1, true) or string.find(name, "locacaca", 1, true) then
        return string.find(name, "seed", 1, true) and "seed" or "rokaka"
    end
    return nil
end
state.ClassifyItem = classify
local inventoryText: string? = nil
local function readInventory()
    local data = player:FindFirstChild("Data")
    local stats = data and data:FindFirstChild("Stats")
    local inventory = stats and stats:FindFirstChild("Inventory")
    if not inventory or not inventory:IsA("StringValue") then state.InventoryReady = false; return nil end
    if state.InventoryReady and inventoryText == inventory.Value then return state.InventoryCounts end
    local ok, decoded = pcall(HttpService.JSONDecode, HttpService, inventory.Value)
    if not ok or type(decoded) ~= "table" then state.InventoryReady = false; return nil end
    local counts = {}
    for _, item in ipairs(decoded) do
        local name = type(item) == "string" and item or type(item) == "table" and item.Name
        local amount = type(item) == "table" and tonumber(item.Amount) or 1
        amount = amount or 1
        if type(name) == "string" and amount == amount and amount >= 0 and amount < math.huge then
            counts[name] = (counts[name] or 0) + amount
        end
    end
    inventoryText, state.InventoryCounts, state.InventoryReady = inventory.Value, counts, true
    return counts
end
local function ownedTargetCount(target: Target): number?
    local counts = readInventory()
    if not counts then return nil end
    if not target.instance:GetAttribute("Contains") then return counts[target.name] or 0 end
    local count = 0
    for name, amount in pairs(counts) do if classify(name) == target.kind then count += amount end end
    return count
end
state.ReadInventory = readInventory
local function foreignOwner(instance: Instance): boolean
    for _, name in ipairs({"OwnerUserId", "GardenOwnerId", "OwnerId"}) do
        local owner = tonumber(instance:GetAttribute(name))
        if owner and owner > 0 and owner ~= player.UserId then return true end
    end
    return false
end
local function collectibleRokaka(instance: Instance, source: string): boolean
    if foreignOwner(instance) then return false end
    if source == "pot" then
        if state.ShouldCollectRokaka and not state.ShouldCollectRokaka(instance:GetAttribute("Contains")) then return false end
        local kind = classify(instance:GetAttribute("Contains"))
        if kind ~= "seed" and kind ~= "rokaka" then return false end
        if tonumber(instance:GetAttribute("OwnerUserId")) ~= player.UserId or instance:GetAttribute("Stage") ~= "Ready" then return false end
        local prompt = instance:FindFirstChild("GardenWork", true)
        return prompt ~= nil and prompt:IsA("ProximityPrompt") and not foreignOwner(prompt)
            and prompt.ActionText == "Harvest fruit"
            and (prompt:GetAttribute("StoryPromptAvailable") == true or prompt.Enabled)
    end
    local name = instance:GetAttribute(source == "foraging" and "GardenSupplyItem" or "ItemName") or instance.Name
    if classify(name) ~= "rokaka" then return false end
    if state.ShouldCollectRokaka and not state.ShouldCollectRokaka(name) then return false end
    if source == "foraging" and instance:GetAttribute("GardenSupplyAvailable") ~= true then return false end
    for _, prompt in ipairs(instance:GetDescendants()) do
        if prompt:IsA("ProximityPrompt") and not foreignOwner(prompt)
            and prompt:GetAttribute("StoryPromptAvailable") ~= false
            and (prompt.Enabled or prompt:GetAttribute("StoryPromptAvailable") == true) then
            local action = string.lower(prompt.ActionText .. " " .. prompt.Name)
            for _, verb in ipairs({"pick", "collect", "harvest", "take", "gather", "dig"}) do
                if string.find(action, verb, 1, true) then return true end
            end
        end
    end
    return false
end
state.IsCollectibleRokaka = collectibleRokaka
local function partOf(instance: Instance): BasePart?
    if instance:IsA("BasePart") then return instance end
    local handle = instance:FindFirstChild("Handle", true)
    if handle and handle:IsA("BasePart") then return handle end
    return instance:FindFirstChildWhichIsA("BasePart", true)
end
local colors = {part = Color3.fromRGB(125, 190, 255), arrow = Color3.fromRGB(255, 211, 110), rokaka = Color3.fromRGB(244, 142, 178), seed = Color3.fromRGB(125, 221, 178)}
local partsPolicy=(function()
local P={}
function P.IsPart(name)
    return type(name)=="string" and name:lower():gsub("^%s+",""):gsub("%s+$","")=="arrow part"
end
function P.OwnerAllowed(object,userId,boundary)
    local node=object
    for _=1,12 do
        if not node or node==boundary then return true end
        for _,key in ipairs({"OwnerUserId","GardenOwnerId","OwnerId","StoryOwnerUserId"}) do
            local owner=tonumber(node:GetAttribute(key))
            if owner and owner>0 and owner~=userId then return false end
        end
        node=node.Parent
    end
    return false
end
function P.PromptAllowed(prompt)
    if not prompt:IsA("ProximityPrompt") or not prompt.Enabled or prompt:GetAttribute("StoryPromptAvailable")==false then return false end
    local duration=prompt.HoldDuration
    if type(duration)~="number" or duration~=duration or duration<0 or duration>15 then return false end
    local action=(prompt.ActionText.." "..prompt.Name):lower()
    return action:find("collect",1,true)~=nil or action:find("pickup",1,true)~=nil
        or action:find("pick up",1,true)~=nil or action:find("take",1,true)~=nil
end
function P.LootEvent(event)
    if type(event)~="table" or event.Phase~="Loot" then return false end
    return event.Id=="Meteor" or type(event.Id)=="string" and event.Id:match("^RainMeteor%d+$")~=nil
end
return P

end)()
local partSkips=setmetatable({},{__mode="k"})
function state.IsPartSkipped(instance)
    local record=partSkips[instance]
    return record and os.clock()<(record.RetryAt or 0) and record.Stamp==instance:GetAttribute("WorldItemSpawnedAt") and record.Name==instance:GetAttribute("ItemName")
        and record.Drop==instance:GetAttribute("WorldDropId") and record.Event==instance:GetAttribute("WorldEventId") or false
end
function state.SkipPart(instance,reason)
    if not instance or not instance.Parent then return end
    local previous=partSkips[instance]
    local same=previous and previous.Stamp==instance:GetAttribute("WorldItemSpawnedAt") and previous.Drop==instance:GetAttribute("WorldDropId") and previous.Event==instance:GetAttribute("WorldEventId")
    local attempts=same and (previous.Attempts or 0)+1 or 1
    partSkips[instance]={Attempts=attempts,RetryAt=os.clock()+math.min(30,5*2^math.min(attempts-1,3)),Stamp=instance:GetAttribute("WorldItemSpawnedAt"),Name=instance:GetAttribute("ItemName"),Drop=instance:GetAttribute("WorldDropId"),Event=instance:GetAttribute("WorldEventId")}
    state.LastPartFailure=tostring(reason)
end
function state.PartPrompt(instance)
    if not partsPolicy.OwnerAllowed(instance,player.UserId,Workspace) then return end
    for _,prompt in ipairs(instance:GetDescendants()) do
        if partsPolicy.PromptAllowed(prompt) and partsPolicy.OwnerAllowed(prompt,player.UserId,Workspace) then return prompt end
    end
end
local function scanParts(add)
    local world=Workspace:FindFirstChild("Game")
    if not world then return end
    local seen={}
    local function consider(item)
        if seen[item] or state.IsPartSkipped(item) then return end
        seen[item]=true
        local name=item:GetAttribute("ItemName") or item.Name
        if not partsPolicy.IsPart(name) then
            local model=item:FindFirstChildWhichIsA("Model")
            if model then name=model.Name end
        end
        if partsPolicy.IsPart(name) and state.PartPrompt(item) then add(item,"Arrow Part","part","collectible part") end
    end
    for _,folderName in ipairs({"SpawnedItems","WorldEventDrops"}) do
        local folder=world:FindFirstChild(folderName)
        if folder then
            for _,item in ipairs(folder:GetChildren()) do
                if item:IsA("Folder") then
                    for _,child in ipairs(item:GetChildren()) do consider(child) end
                else consider(item) end
            end
        end
    end
end

local function scan(): {Target}
    local targets: {Target} = {}
    local world = Workspace:FindFirstChild("Game")
    if not world then return targets end
    local root = player.Character and player.Character:FindFirstChild("HumanoidRootPart")
    local function add(instance: Instance, name: string, kind: string, detail: string)
        if kind == "arrow" and state.IsArrowSkipped(instance) then return end
        local part = partOf(instance)
        if not part then return end
        local distance = if root and root:IsA("BasePart") then (root.Position - part.Position).Magnitude else math.huge
        table.insert(targets, {instance = instance, part = part, name = name, kind = kind, detail = detail, distance = distance})
    end
    local drops = world:FindFirstChild("SpawnedItems")
    if drops then
        for _, item in ipairs(drops:GetChildren()) do
            local name = item:GetAttribute("ItemName")
            if type(name) ~= "string" then
                local model = item:FindFirstChildWhichIsA("Model")
                name = model and model.Name or item.Name
            end
            local kind = classify(name)
            if kind and kind ~= "part" and (kind ~= "rokaka" or collectibleRokaka(item, "drop")) then add(item, tostring(name), kind, "ground item") end
        end
    end
    local garden = world:FindFirstChild("Gardening")
    if garden then
        local pots = garden:FindFirstChild("Pots")
        if pots then
            for _, pot in ipairs(pots:GetChildren()) do
                if collectibleRokaka(pot, "pot") then
                    add(pot, "rokaka harvest", "rokaka", "ready / your plant")
                end
            end
        end
        local foraging = garden:FindFirstChild("Foraging")
        if foraging then
            for _, item in ipairs(foraging:GetChildren()) do
                local name = item:GetAttribute("GardenSupplyItem")
                local kind = classify(name)
                if kind and not foreignOwner(item) and item:GetAttribute("GardenSupplyAvailable") ~= false
                    and (kind ~= "rokaka" or collectibleRokaka(item, "foraging")) then add(item, tostring(name), kind, "buried supply") end
            end
        end
    end
    scanParts(add)
    table.sort(targets, function(a, b) return a.distance < b.distance end)
    return targets
end
local function setTeleportStatus(message: string)
    state.TeleportStatus = message
    if alive then teleportStatus.Text = message end
end
local function landingPositionAt(point: Vector3, excluded: Instance?, character: Model, root: BasePart, humanoid: Humanoid, pickupRange: number?): Vector3?
    local filter = RaycastParams.new()
    filter.FilterType = Enum.RaycastFilterType.Exclude
    filter.FilterDescendantsInstances = if excluded then {character, excluded} else {character}
    filter.RespectCanCollide = true
    local overlap = OverlapParams.new()
    overlap.FilterType = Enum.RaycastFilterType.Exclude
    overlap.FilterDescendantsInstances = filter.FilterDescendantsInstances
    overlap.RespectCanCollide = true
    overlap.MaxParts = 1
    local height = humanoid.HipHeight + root.Size.Y / 2
    if humanoid.RigType == Enum.HumanoidRigType.R6 then
        local leg = character:FindFirstChild("Left Leg")
        height += if leg and leg:IsA("BasePart") then leg.Size.Y else 2
    end
    local radii = if pickupRange then {0, 2, 3.5, 5} else {5}
    for _, radius in ipairs(radii) do
    for i = 0, (if radius == 0 then 0 else 7) do
        local angle = i * math.pi / 4
        local offset = Vector3.new(math.cos(angle) * radius, 6, math.sin(angle) * radius)
        local hit = Workspace:Raycast(point + offset, Vector3.new(0, -22, 0), filter)
        if hit and hit.Normal.Y > 0.65 and hit.Material ~= Enum.Material.Water then
            local position = hit.Position + Vector3.new(0, height + 0.4, 0)
            local clearance = CFrame.new(hit.Position + Vector3.new(0, height + 1, 0))
            if (not pickupRange or (position-point).Magnitude <= pickupRange)
                and #Workspace:GetPartBoundsInBox(clearance, Vector3.new(3, height * 2, 3), overlap) == 0 then
                return position
            end
        end
    end
    end
    return nil
end
local awaitPickupArrival=(function()
return function(current,nearby,wait,clock)
    local deadline=clock()+1.5
    local stable=0
    repeat
        wait(0.05)
        if not current() then return false end
        stable=nearby() and stable+1 or 0
        if stable>=2 then return true end
    until clock()>=deadline
    return false
end

end)()
state.PickupArrivalVersion=1
local function teleportTo(kind: string, requested: Target?): Target?
    if not alive or state.TeleportBusy then return end
    local character = player.Character
    local root = character and character:FindFirstChild("HumanoidRootPart")
    local humanoid = character and character:FindFirstChildOfClass("Humanoid")
    if not character or not root or not root:IsA("BasePart") or not humanoid or humanoid.Health <= 0 then
        setTeleportStatus("wait for your character to respawn")
        return
    end
    if root.Anchored or humanoid.SeatPart then
        setTeleportStatus("stand up and wait until movement is available")
        return
    end
    state.TeleportBusy = true
    local movedTarget: Target? = nil
    local ok, err = pcall(function()
        local selected: Target? = requested
        if not selected then
            for _, target in ipairs(scan()) do
                if target.kind == kind then selected = target; break end
            end
        end
        if not selected then
            setTeleportStatus(kind == "rokaka" and "no collectible rokaka loaded; other players' plants excluded" or "no " .. kind .. " loaded nearby")
            state.TeleportBusy = false
            return
        end
        local target = selected
        if not target.instance:IsDescendantOf(Workspace) or not target.part:IsDescendantOf(target.instance) and target.part ~= target.instance then
            setTeleportStatus("item disappeared; try again")
            state.TeleportBusy = false
            return
        end
        local prompt = if target.kind == "part" then state.PartPrompt(target.instance) else target.instance:FindFirstChildWhichIsA("ProximityPrompt", true)
        local parent = prompt and prompt.Parent
        local point = if parent and parent:IsA("Attachment") then parent.WorldPosition
            elseif parent and parent:IsA("BasePart") then parent.Position
            elseif parent and parent:IsA("Model") then parent:GetPivot().Position else target.part.Position
        local range = if prompt then math.max(0, prompt.MaxActivationDistance - 0.5) else 8
        local destination = landingPositionAt(point, target.instance, character, root, humanoid, range)
        state.PickupPositionVersion=2
        state.LastPickupPosition={Name=target.name,Range=range,Distance=destination and (destination-point).Magnitude,Found=destination~=nil}
        if not destination then
            setTeleportStatus("no clear landing spot near this item")
            state.TeleportBusy = false
            return
        end
        stopHidden(false)
        local rootToPivot = root.CFrame:ToObjectSpace(character:GetPivot())
        local facing = Vector3.new(target.part.Position.X, destination.Y, target.part.Position.Z)
        if (facing - destination).Magnitude < 0.01 then facing = destination + Vector3.new(0, 0, -1) end
        character:PivotTo(CFrame.lookAt(destination, facing) * rootToPivot)
        root.AssemblyLinearVelocity = Vector3.zero
        root.AssemblyAngularVelocity = Vector3.zero
        movedTarget = target
        setTeleportStatus("moving to " .. string.lower(target.name))
        local movedAt=os.clock()
        task.spawn(function()
            local fastArrival=requested~=nil and state.AutoBusy and (target.kind=="arrow" or target.kind=="part")
            local arrived=true
            if fastArrival then
                arrived=awaitPickupArrival(function()
                    return alive and player.Character==character and root.Parent~=nil and humanoid.Health>0
                end,function() return (root.Position-destination).Magnitude<=6 end,task.wait,os.clock)
            else task.wait(1.5) end
            if not alive then return end
            state.LastPickupArrival={Name=target.name,Fast=fastArrival,Stable=arrived,Elapsed=os.clock()-movedAt}
            state.TeleportBusy = false
            if player.Character ~= character or not root.Parent or humanoid.Health <= 0 then
                setTeleportStatus("character changed; try after respawn")
            elseif not arrived or (root.Position - destination).Magnitude > 15 then
                local owner = target.instance:GetAttribute("OwnerUserId")
                local suffix = if type(owner) == "number" and owner > 0 and owner ~= player.UserId then " / other owner's plant" else ""
                setTeleportStatus("teleport did not stay" .. suffix)
            else
                setTeleportStatus("arrived: " .. string.lower(target.name) .. " / " .. target.detail)
            end
        end)
    end)
    if not ok then
        state.TeleportBusy = false
        setTeleportStatus("teleport failed: " .. tostring(err):sub(1, 100))
        warn("item finder teleport: " .. tostring(err))
    end
    return movedTarget
end
table.insert(connections, warpArrow.Activated:Connect(function() if not state.AutoBusy then teleportTo("arrow", nil) end end))
table.insert(connections, warpRokaka.Activated:Connect(function() if not state.AutoBusy then teleportTo("rokaka", nil) end end))
local function setAutoStatus(message: string)
    state.AutoStatus = message
    if alive then autoStatus.Text = message end
end
state.OpalFarmVersion=2
function state.WantsGardenSeed(name)
    local garden=environment.MT_RokakaGardenRun
    if not (garden and garden.Alive and state.AutoRokaka) then return false end
    if state.ShouldCollectRokaka and not state.ShouldCollectRokaka(name) then return false end
    if name=="Opal Roka Seed" then return true end
    return name=="Rokaka Seed" and state.WantsRokakaSeed()
end
function state.WantsRokakaSeed()
    local garden = environment.MT_RokakaGardenRun
    return garden and garden.Alive and state.AutoRokaka and ((readInventory() or {})["Rokaka Seed"] or 0) < 1
end
local function autoEnabled(kind: string): boolean
    if kind == "seed" then
        local garden = environment.MT_RokakaGardenRun
        return state.AutoRokaka and garden ~= nil and garden.Alive == true
    end
    return kind == "part" and state.AutoParts or kind == "arrow" and state.AutoArrow or kind == "rokaka" and state.AutoRokaka
end
local function refreshAuto()
    autoGeneration += 1
    if releaseFastPickup then releaseFastPickup(); releaseFastPickup=nil end
    if activePrompt then pcall(function() activePrompt:InputHoldEnd() end); activePrompt = nil end
    autoArrowButton.Text = state.AutoArrow and "auto arrow: on" or "auto arrow: off"
    autoRokakaButton.Text = state.AutoRokaka and "auto rokaka: on" or "auto rokaka: off"
    autoArrowButton.BackgroundColor3 = state.AutoArrow and Color3.fromRGB(35, 101, 78) or Color3.fromRGB(47, 51, 59)
    autoRokakaButton.BackgroundColor3 = state.AutoRokaka and Color3.fromRGB(35, 101, 78) or Color3.fromRGB(47, 51, 59)
    setAutoStatus((state.AutoArrow or state.AutoRokaka or state.AutoParts) and "searching loaded items..." or "auto farming is off")
    if state.RefreshUI then state.RefreshUI() end
end
state.AutoControlVersion=2
function state.SetAuto(kind: string, enabled: boolean)
    assert(kind == "arrow" or kind == "rokaka" or kind == "part", "unknown auto farm kind")
    if not alive then return end
    if (autoEnabled(kind) == true) == (enabled == true) then return end
    if kind == "part" then state.AutoParts = enabled == true elseif kind == "arrow" then state.AutoArrow = enabled == true else state.AutoRokaka = enabled == true end
    refreshAuto()
end
table.insert(connections, autoArrowButton.Activated:Connect(function() state.AutoArrow = not state.AutoArrow; refreshAuto() end))
table.insert(connections, autoRokakaButton.Activated:Connect(function() state.AutoRokaka = not state.AutoRokaka; refreshAuto() end))
local retryAfter: {[Instance]: number} = setmetatable({}, {__mode = "k"})
local lastAutoKind = "rokaka"
local function pickupPrompt(target: Target): ProximityPrompt?
    if target.kind == "rokaka" and state.ShouldCollectRokaka and not state.ShouldCollectRokaka(target.instance:GetAttribute("Contains") or target.name) then return nil end
    if target.kind == "part" then return state.PartPrompt(target.instance) end
    for _, prompt in ipairs(target.instance:GetDescendants()) do
        if prompt:IsA("ProximityPrompt") and prompt.Enabled and not foreignOwner(prompt)
            and prompt:GetAttribute("StoryPromptAvailable") ~= false then
            local action = string.lower(prompt.ActionText .. " " .. prompt.Name)
            local valid = string.find(action, "pick", 1, true) or string.find(action, "collect", 1, true)
            if target.kind == "seed" then
                valid = state.WantsGardenSeed(target.name) and not foreignOwner(target.instance)
                    and ((target.instance:GetAttribute("GardenSupplyAvailable") == true and prompt.Name == "GardenGather")
                        or (target.instance:GetAttribute("GardenSupplyAvailable") == nil and valid))
            end
            if target.kind == "rokaka" and target.instance:GetAttribute("Contains") then
                valid = prompt.Name == "GardenWork" and prompt.ActionText == "Harvest fruit"
                    and collectibleRokaka(target.instance, "pot")
            end
            if valid then return prompt end
        end
    end
    return nil
end
local tryFastPickup=(function()
return function(prompt,before,readCount,current,fire,wait,clock,registerCleanup)
    local started=clock()
    local result={Attempted=false,Confirmed=false}
    if type(fire)~="function" or type(before)~="number" or before~=before or before<0 or before==math.huge then return result end
    if not current() then result.Cancelled=true;return result end
    local hold
    local readOK=pcall(function() hold=prompt.HoldDuration end)
    if readOK and type(hold)=="number" and hold>0 and hold<math.huge then
        result.OriginalHold=hold
        result.HoldBypassAttempted=pcall(function() prompt.HoldDuration=0 end)
    end
    local released=false
    local function release()
        if released then return end
        released=true
        if not result.HoldBypassAttempted then return end
        local restored,restoreError=pcall(function()
            if prompt.HoldDuration==0 then prompt.HoldDuration=hold end
        end)
        if not restored then result.RestoreError=tostring(restoreError) end
    end
    if registerCleanup then registerCleanup(release) end
    result.Attempted=true
    local ok,err=pcall(fire,prompt)
    release()
    if registerCleanup then registerCleanup(nil) end
    if not ok then result.Error=tostring(err);result.Elapsed=clock()-started;return result end
    local deadline=clock()+0.2
    repeat
        if not current() then result.Cancelled=true;break end
        local after=readCount()
        if type(after)=="number" and after>before and after<math.huge then
            result.Confirmed=true;result.After=after;break
        end
        wait(.05)
    until clock()>=deadline
    result.Elapsed=clock()-started
    return result
end

end)()
state.FastPickupVersion=3
local function autoAttempt(target: Target)
    local function pickupStatus(message: string)
        if state.LastPickup then state.LastPickup.result = message end
        setAutoStatus(message)
    end
    local generation = autoGeneration
    local character = player.Character
    local function current(): boolean
        return alive and generation == autoGeneration and autoEnabled(target.kind) and player.Character == character
    end
    local function pickupFailed(reason: string)
        if target.kind == "part" and current() then
            state.SkipPart(target.instance, reason)
            pickupStatus("skipped arrow part: " .. reason)
        elseif target.kind == "arrow" and current() then
            state.SkipArrow(target.instance, reason)
            pickupStatus("skipped arrow: " .. reason)
        else pickupStatus(reason .. "; retry after 30 seconds") end
    end
    retryAfter[target.instance] = os.clock() + 5
    state.AutoAttempts += 1
    local ownedBefore = ownedTargetCount(target)
    state.LastPickup = {name = target.name, before = ownedBefore, verified = false, result = "travelling"}
    pickupStatus("travelling: " .. string.lower(target.name))
    if not teleportTo(target.kind, target) then pickupFailed(state.TeleportStatus); return end
    local deadline = os.clock() + 3
    while current() and state.TeleportBusy and os.clock() <= deadline do task.wait(0.05) end
    if not current() then return end
    if state.TeleportBusy or not string.find(state.TeleportStatus, "arrived:", 1, true) then
        pickupFailed("arrival failed")
        return
    end
    local prompt: ProximityPrompt? = nil
    deadline = os.clock() + 3
    repeat
        if not current() or not target.instance:IsDescendantOf(Workspace) then return end
        prompt = pickupPrompt(target)
        if prompt then break end
        task.wait(0.1)
    until os.clock() > deadline
    if not prompt then pickupFailed("pickup unavailable"); return end
    local root = character and character:FindFirstChild("HumanoidRootPart")
    local parent = prompt.Parent
    local position = if parent and parent:IsA("Attachment") then parent.WorldPosition
        elseif parent and parent:IsA("BasePart") then parent.Position
        elseif parent and parent:IsA("Model") then parent:GetPivot().Position else target.part.Position
    if not root or not root:IsA("BasePart") or (root.Position - position).Magnitude > prompt.MaxActivationDistance then
        pickupFailed("pickup out of range")
        return
    end
    if prompt.HoldDuration > 15 then pickupFailed("pickup hold is unexpectedly long"); return end
    pickupStatus("collecting: " .. string.lower(target.name))
    if state.PrepareBizarrePickup and target.name=="Bizarre Arrow" then
        if not state.PrepareBizarrePickup(target,prompt,current) then
            pickupStatus("bizarre capacity or protected stand; skipped")
            return
        end
        ownedBefore=ownedTargetCount(target)
    end
    local pickupStarted=os.clock()
    local pickupMode="hold"
    if target.kind=="arrow" or target.kind=="part" then
        activePrompt=prompt
        local fast=tryFastPickup(prompt,ownedBefore,function() return ownedTargetCount(target) end,current,fireproximityprompt,task.wait,os.clock,function(cleanup) releaseFastPickup=cleanup end)
        state.LastFastPickup={Name=target.name,Attempted=fast.Attempted,Confirmed=fast.Confirmed,Elapsed=fast.Elapsed,Error=fast.Error,HoldBypassAttempted=fast.HoldBypassAttempted,OriginalHold=fast.OriginalHold,RestoreError=fast.RestoreError}
        if activePrompt==prompt then activePrompt=nil end
        if fast.Cancelled or not current() then return end
        if fast.Confirmed then
            if target.kind=="part" then state.PartsCollected=(state.PartsCollected or 0)+fast.After-ownedBefore end
            state.AutoCollected+=fast.After-ownedBefore
            state.LastPickup={name=target.name,before=ownedBefore,after=fast.After,verified=true,result="inventory increased",mode="fast",elapsed=fast.Elapsed}
            state.FastPickupsConfirmed=(state.FastPickupsConfirmed or 0)+1
            pickupStatus("collected: "..string.lower(target.name))
            return
        end
        if fast.Attempted then pickupMode="hold fallback" end
    end
    local observedAfterFast=ownedTargetCount(target)
    local alreadyCollected=ownedBefore and observedAfterFast and observedAfterFast>ownedBefore
    if alreadyCollected then pickupMode="fast late" end
    if not alreadyCollected and prompt.Parent and target.instance:IsDescendantOf(Workspace) then
    activePrompt = prompt
    prompt:InputHoldBegin()
    deadline = os.clock() + prompt.HoldDuration + 0.2
    while current() and prompt.Parent and os.clock() < deadline do
        local observed=ownedTargetCount(target)
        if ownedBefore and observed and observed>ownedBefore then break end
        task.wait(0.05)
    end
    pcall(function() prompt:InputHoldEnd() end)
    if activePrompt == prompt then activePrompt = nil end
    end
    if not current() then return end
    deadline = os.clock() + 4
    repeat
        local ownedAfter = ownedTargetCount(target)
        if ownedBefore and ownedAfter and ownedAfter > ownedBefore then
            if target.kind == "part" then state.PartsCollected = (state.PartsCollected or 0) + ownedAfter - ownedBefore end
            state.AutoCollected += ownedAfter - ownedBefore
            state.LastPickup = {name = target.name, before = ownedBefore, after = ownedAfter, verified = true, result = "inventory increased", mode=pickupMode, elapsed=os.clock()-pickupStarted}
            pickupStatus("collected: " .. string.lower(target.name))
            return
        end
        if not target.instance:IsDescendantOf(Workspace) or target.instance:GetAttribute("Contains") and target.instance:GetAttribute("Stage") ~= "Ready" then
            state.LastPickup.result = "target cleared; awaiting inventory"
        end
        task.wait(0.1)
    until not current() or os.clock() > deadline
    if current() then
        state.LastPickup.result = "inventory increase not confirmed"
        pickupFailed("inventory gain not confirmed")
    end
end
type ArrowNode = {id: string, name: string, position: Vector3, instance: BasePart?, enabled: boolean,
    occupied: boolean, visitedAt: number, nextVisit: number, failures: number}
local arrowNodes: {[string]: ArrowNode} = {}
state.ArrowRouteNodes = arrowNodes
-- Verified map markers retain a route when the entry area has not streamed them yet.
for _, row in ipairs({
    {"Arrow01", -848.892639, 16.841635, 1773.041748},
    {"Arrow02", -1279.739380, 16.619987, 1276.716797},
    {"Arrow03", -1010.266602, 16.619999, 1605.316040},
    {"Arrow03", -278.363098, 17.394133, 1321.718018},
    {"Arrow04", -819.527283, 17.200000, 1471.208740},
    {"Arrow06", -421.713013, 17.200001, 822.866089},
    {"Arrow07", -735.913086, 17.200001, 862.066101},
    {"Arrow08", -739.513062, 17.200001, 1462.666260},
    {"Arrow09", -1313.513184, 17.200001, 1598.666260},
}) do
    local id = string.format("%s:%.2f:%.2f:%.2f", row[1], row[2], row[3], row[4])
    arrowNodes[id] = {id = id, name = row[1], position = Vector3.new(row[2], row[3], row[4]),
        enabled = true, occupied = false, visitedAt = 0, nextVisit = 0, failures = 0}
end
local function refreshArrowNodes()
    local world = Workspace:FindFirstChild("Game")
    local container = world and world:FindFirstChild("ItemSpawnNodes")
    local arrows = container and container:FindFirstChild("Arrows")
    if arrows then
        for _, node in ipairs(arrows:GetChildren()) do
            if node:IsA("BasePart") then
                local p = node.Position
                -- Names repeat in the real map; coordinates distinguish the spawn markers.
                local id = string.format("%s:%.2f:%.2f:%.2f", node.Name, p.X, p.Y, p.Z)
                local known = arrowNodes[id]
                if not known then
                    known = {id = id, name = node.Name, position = p, instance = node, enabled = true,
                        occupied = false, visitedAt = 0, nextVisit = 0, failures = 0}
                    arrowNodes[id] = known
                end
                known.instance, known.position = node, p
                known.enabled = node:GetAttribute("Enabled") ~= false
                known.occupied = node:GetAttribute("Occupied") == true
            end
        end
    end
    local count = 0
    for _, node in pairs(arrowNodes) do if node.enabled then count += 1 end end
    state.RouteCount = count
end
local function selectArrowNode(position: Vector3): ArrowNode?
    local now = os.clock()
    local selected: ArrowNode? = nil
    for _, node in pairs(arrowNodes) do
        if node.enabled and now >= node.nextVisit then
            if not selected
                or node.occupied and not selected.occupied
                or node.occupied == selected.occupied and node.visitedAt < selected.visitedAt
                or node.occupied == selected.occupied and node.visitedAt == selected.visitedAt
                    and (node.position - position).Magnitude < (selected.position - position).Magnitude then
                selected = node
            end
        end
    end
    return selected
end
state.StreamWorkers = {}
function state.RequestStream(position, seconds)
    if not alive then return false, "unloaded" end
    local finished, success, failure = false, false, nil
    local timeout = math.clamp(tonumber(seconds) or 2, 0.2, 5)
    local thread = task.spawn(function()
        success, failure = pcall(function() player:RequestStreamAroundAsync(position, timeout) end)
        finished = true
    end)
    state.StreamWorkers[thread] = true
    local deadline = os.clock() + timeout
    while alive and not finished and os.clock() < deadline do task.wait(0.05) end
    state.StreamWorkers[thread] = nil
    if not finished then
        pcall(task.cancel, thread)
        state.StreamTimeouts = (state.StreamTimeouts or 0) + 1
        return false, alive and "stream deadline reached" or "unloaded"
    end
    return success, failure
end

local function routeVisit(node: ArrowNode)
    local generation = autoGeneration
    local character = player.Character
    local root = character and character:FindFirstChild("HumanoidRootPart")
    local humanoid = character and character:FindFirstChildOfClass("Humanoid")
    if not character or not root or not root:IsA("BasePart") or not humanoid
        or humanoid.Health <= 0 or root.Anchored or humanoid.SeatPart or state.Flying then return end
    local function current(): boolean
        return alive and generation == autoGeneration and state.AutoArrow and not state.Flying
            and player.Character == character and root.Parent ~= nil and humanoid.Health > 0
            and not root.Anchored and humanoid.SeatPart == nil
    end
    state.RouteBusy, state.TeleportBusy = true, true
    state.RouteStatus = string.format("patrol %s / %d points", string.lower(node.name), state.RouteCount)
    state.RouteError = ""
    setAutoStatus(state.RouteStatus)
    node.visitedAt = os.clock()
    node.nextVisit = os.clock() + 30
    state.RouteVisits += 1
    local outcome = "cancelled"
    local ok, err = pcall(function()
        if Workspace.StreamingEnabled and not landingPositionAt(node.position, node.instance, character, root, humanoid) then
            local streamed, streamError = state.RequestStream(node.position, 2)
            if not current() then return end
            if not streamed then state.RouteError = "stream request: " .. tostring(streamError):sub(1, 90) end
        end
        if not current() then return end
        refreshArrowNodes()
        if not node.enabled then outcome = "disabled"; return end
        local excluded = node.instance
        if excluded and not excluded:IsDescendantOf(Workspace) then excluded = nil end
        local destination = landingPositionAt(node.position, excluded, character, root, humanoid)
        if not destination then outcome = "no clear landing"; return end
        if not current() then return end
        if state.FarmHide then destination = beginHidden(character, root, node.position, destination) end
        local rootToPivot = root.CFrame:ToObjectSpace(character:GetPivot())
        local facing = Vector3.new(node.position.X, destination.Y, node.position.Z)
        if (facing - destination).Magnitude < 0.01 then facing = destination + Vector3.new(0, 0, -1) end
        character:PivotTo(CFrame.lookAt(destination, facing) * rootToPivot)
        root.AssemblyLinearVelocity, root.AssemblyAngularVelocity = Vector3.zero, Vector3.zero
        local deadline = os.clock() + 1.5
        repeat task.wait(0.1) until not current() or os.clock() >= deadline
        if not current() then return end
        if (root.Position - destination).Magnitude > (state.FarmHideActive and 3 or 15) then
            if state.FarmHideActive then stopHidden(true); state.FarmHide = false end
            outcome = "arrival corrected"; return
        end
        state.RouteArrivals += 1
        node.failures = 0
        outcome = "arrived"
        deadline = os.clock() + 3
        repeat
            if not current() then return end
            refreshArrowNodes()
            for _, target in ipairs(scan()) do
                local gardener = environment.MT_RokakaGardenRun
                    local gardenOwned = target.kind == "rokaka" and target.instance:GetAttribute("Contains") and gardener and gardener.Alive
                    if not gardenOwned and (target.kind ~= "seed" or state.WantsGardenSeed(target.name)) and autoEnabled(target.kind) and (retryAfter[target.instance] or 0) <= os.clock() then return end
            end
            task.wait(0.2)
        until os.clock() >= deadline
    end)
    state.RouteBusy, state.TeleportBusy = false, false
    if not alive then return end
    if not ok then outcome = "error: " .. tostring(err):sub(1, 90) end
    if outcome ~= "arrived" and outcome ~= "cancelled" and outcome ~= "disabled" then
        node.failures += 1
        node.nextVisit = os.clock() + math.min(120, 15 * 2 ^ math.min(node.failures, 3))
        state.RouteError = outcome
    end
    table.insert(state.RouteLog, {id = node.id, outcome = outcome, at = os.clock()})
    if #state.RouteLog > 30 then table.remove(state.RouteLog, 1) end
    if current() then setAutoStatus(outcome == "arrived" and "checking next arrow spawn" or "route retry: " .. outcome) end
end
state.ItemPriorityVersion=1
function state.HasPriorityItems()
    if not alive then return false end
    if state.AutoBusy then return true end
    for _,target in ipairs(scan()) do
        local gardener=environment.MT_RokakaGardenRun
        local gardenOwned=target.kind=="rokaka" and target.instance:GetAttribute("Contains") and gardener and gardener.Alive
        if not gardenOwned and autoEnabled(target.kind)
            and (target.kind~="seed" or state.WantsGardenSeed(target.name))
            and (retryAfter[target.instance] or 0)<=os.clock()
            and pickupPrompt(target) then
            return true
        end
    end
    return false
end

refreshArrowNodes()

state.FarmRecoveryVersion=1
state.FarmRecoveryCount=0
task.spawn(function()
    while alive do
        local recovered, recoveryError=pcall(function()
    while alive do
        state.FarmHeartbeat=os.clock()
        local garden=environment.MT_RokakaGardenRun
        local blockedReason=state.TransferPending and "server transfer"
            or state.PhoneBusy and "phone quest"
            or (garden and garden.Busy) and "garden interaction"
            or state.MaterialBusy and "material work"
            or state.CraftBusy and "craft or mask interaction"
            or state.AutoHopPause and "server selection"
            or state.ExtensionPause and "other enabled activity"
        state.WorkPauseReason=blockedReason
        if blockedReason and not state.AutoBusy then setAutoStatus("pickup waiting: "..blockedReason) end
        local pickupDelay=0.5
        local workerOK, workerError = pcall(function()
        if (state.AutoArrow or state.AutoRokaka or state.AutoParts) and not state.TeleportBusy and not state.TransferPending and not state.ExtensionPause and not state.PhoneBusy and not state.CraftBusy and not state.AutoHopPause and not (environment.MT_RokakaGardenRun and environment.MT_RokakaGardenRun.Busy) then
            local character = player.Character
            local humanoid = character and character:FindFirstChildOfClass("Humanoid")
            if humanoid and humanoid.Health > 0 then
                local selected: Target? = nil
                for _, target in ipairs(scan()) do
                    local gardener = environment.MT_RokakaGardenRun
                    local gardenOwned = target.kind == "rokaka" and target.instance:GetAttribute("Contains") and gardener and gardener.Alive
                    if not gardenOwned and (target.kind ~= "seed" or state.WantsGardenSeed(target.name)) and autoEnabled(target.kind) and (retryAfter[target.instance] or 0) <= os.clock() then
                        selected = selected or target
                        if target.kind ~= lastAutoKind then selected = target; break end
                    end
                end
                if selected then
                    if state.ReleaseIdleHide then state.ReleaseIdleHide() end
                    state.AutoBusy = true
                    lastAutoKind = selected.kind
                    local ok, err = pcall(autoAttempt, selected)
                    if ok and state.LastPickup and state.LastPickup.verified then pickupDelay=0.05 end
                    if releaseFastPickup then releaseFastPickup(); releaseFastPickup=nil end
    if activePrompt then pcall(function() activePrompt:InputHoldEnd() end); activePrompt = nil end
                    state.AutoBusy = false
                    if not ok and alive then setAutoStatus("auto retry: " .. tostring(err):sub(1, 70)) end
                elseif state.WaitForArrow then
                    state.WaitHidden()
                    setAutoStatus("waiting hidden for loaded items")
                elseif state.AutoArrow then
                    refreshArrowNodes()
                    local root = character:FindFirstChild("HumanoidRootPart")
                    local node = root and root:IsA("BasePart") and selectArrowNode(root.Position)
                    if node and not state.Flying then
                        state.AutoBusy = true
                        routeVisit(node)
                        state.AutoBusy = false
                    else
                        setAutoStatus(state.Flying and "arrow patrol paused while flying"
                            or state.RouteCount == 0 and "waiting for arrow spawn markers"
                            or "waiting before next arrow patrol")
                    end
                else setAutoStatus("waiting for collectible items in loaded areas") end
            end
        end
        end)
        if not workerOK then
            state.AutoBusy, state.RouteBusy, state.TeleportBusy = false, false, false
            if releaseFastPickup then releaseFastPickup(); releaseFastPickup=nil end
    if activePrompt then pcall(function() activePrompt:InputHoldEnd() end); activePrompt = nil end
            if alive then setAutoStatus("auto retry: " .. tostring(workerError):sub(1, 90)) end
        end
        task.wait(pickupDelay)
    end
        end)
        if not alive then break end
        if not recovered then
            state.FarmRecoveryCount+=1
            state.FarmRecoveryError=tostring(recoveryError):sub(1,200)
            state.AutoBusy,state.RouteBusy,state.TeleportBusy=false,false,false
            local release=releaseFastPickup
            releaseFastPickup=nil
            if release then pcall(release) end
            local prompt=activePrompt
            activePrompt=nil
            if prompt then pcall(function() prompt:InputHoldEnd() end) end
            task.wait(math.min(30,5*state.FarmRecoveryCount))
        end
    end
end)
local function render(targets: {Target})
    local seen: {[Instance]: boolean} = {}
    local counts = {arrow = 0, rokaka = 0, seed = 0, part = 0}
    local lines: {string} = {}
    for i, target in ipairs(targets) do
        counts[target.kind] += 1
        seen[target.instance] = true
        local marker = markers[target.instance]
        if not marker then
            local billboard = Instance.new("BillboardGui")
            billboard.Name = "ItemMarker"
            billboard.Size = UDim2.fromOffset(290, 56)
            billboard.StudsOffsetWorldSpace = Vector3.new(0, 3, 0)
            billboard.AlwaysOnTop = true
            billboard.MaxDistance = 100000
            billboard.Parent = gui
            local text = Instance.new("TextLabel")
            text.Size = UDim2.fromScale(1, 1)
            text.BackgroundColor3 = Color3.fromRGB(20, 22, 27)
            text.BackgroundTransparency = 0.2
            text.Font = Enum.Font.GothamBold
            text.TextSize = 15
            text.TextWrapped = true
            text.Parent = billboard
            marker = {gui = billboard, text = text}
            markers[target.instance] = marker
        end
        local distance = target.distance == math.huge and "respawning" or string.format("%.0f studs", target.distance)
        marker.gui.Adornee = target.part
        marker.gui.Enabled = visible
        marker.text.TextColor3 = colors[target.kind]
        marker.text.Text = string.lower(target.name) .. " | " .. distance .. "\n" .. target.detail
        if i <= 4 then table.insert(lines, string.lower(target.name) .. " | " .. distance .. "\n" .. target.detail) end
    end
    for item, marker in pairs(markers) do
        if not seen[item] then marker.gui:Destroy(); markers[item] = nil end
    end
    state.Parts = counts.part
    state.Count, state.Arrow, state.Rokaka, state.Seeds = #targets, counts.arrow, counts.rokaka, counts.seed
    warpArrow.Text = string.format("tp arrow (%d)", counts.arrow)
    warpRokaka.Text = string.format("tp rokaka (%d)", counts.rokaka)
    summary.Text = string.format("arrows: %d  |  collectible rokaka: %d\nrokaka seeds: %d", counts.arrow, counts.rokaka, counts.seed)
    list.Text = #lines > 0 and table.concat(lines, "\n") or "no matching items loaded nearby"
    status.Text = "loaded area only | updates every second\nanti-afk: " .. state.AntiAFK
    if state.RefreshUI then state.RefreshUI() end
end
local resumePayload = [=[
if isfile("sharkwow-standout-no-autorun.flag") then return end
task.spawn(function()
    local deadline=os.clock()+180
    local players=game:GetService("Players")
    repeat task.wait(.25) until (game:IsLoaded() and players.LocalPlayer) or os.clock()>=deadline
    local player=players.LocalPlayer
    if not player or not game:IsLoaded() or game.PlaceId~=128828638194450 then return end
    local env=getgenv()
    local key=tostring(player.UserId)..":"..game.JobId
    if env.SHARKWOW_STANDOUT_BOOTSTRAP==key then return end
    env.SHARKWOW_STANDOUT_BOOTSTRAP=key
    env.SHARKWOW_STANDOUT_BOOT_STATUS="waiting for destination"
    local ok,err=pcall(function()
        local http=game:GetService("HttpService")
        local path="sharkwow-standout-resume-"..player.UserId..".json"
        local data=http:JSONDecode(readfile(path))
        if type(data)~="table" or data.Schema~=1 or data.UserId~=player.UserId or not data.Enabled
            or type(data.Created)~="number" or math.abs(os.time()-data.Created)>900 then env.SHARKWOW_STANDOUT_BOOTSTRAP=nil;env.SHARKWOW_STANDOUT_BOOT_STATUS="no active resume intent";return end
        local stable=0
        repeat
            local d=player:FindFirstChild("Data")
            local stats=d and d:FindFirstChild("Stats")
            local character=player.Character
            local core=character and character:FindFirstChild("Core")
            local scripts=player:FindFirstChild("PlayerScripts")
            local clientCore=scripts and scripts:FindFirstChild("Core")
            local clientReady=clientCore and clientCore:FindFirstChild("Crafting") and clientCore:FindFirstChild("Gardening") and clientCore:FindFirstChild("WorldEvents")
            local ready=d and d:GetAttribute("Loaded") and stats and stats:FindFirstChild("Inventory")
                and stats:FindFirstChild("ActiveBounties") and stats:FindFirstChild("BountyProgress")
                and d:FindFirstChild("Skills") and d:FindFirstChild("Stand")
                and player:FindFirstChild("PlayerGui") and core and core:FindFirstChild("PlayerController")
                and character:FindFirstChild("HumanoidRootPart") and workspace:FindFirstChild("Game")
                and (clientReady or workspace:GetAttribute("ServerClosing")==true)
            stable=ready and stable+1 or 0
            if stable>=4 then break end
            task.wait(.25)
        until os.clock()>=deadline
        assert(stable>=4,"destination data/character not ready")
        local existing=env.MT_ArrowRokakaFinder
        if existing and existing.Alive then env.SHARKWOW_STANDOUT_BOOT_STATUS="already running";return end
        if isfile("sharkwow-standout-no-autorun.flag") then return end
        local latest=http:JSONDecode(readfile(path))
        if not latest.Enabled or latest.UserId~=player.UserId then env.SHARKWOW_STANDOUT_BOOTSTRAP=nil;env.SHARKWOW_STANDOUT_BOOT_STATUS="cancelled";return end
        env.SHARKWOW_STANDOUT_RESUME=data
        if data.Licensed then env.SharkwowTeleportResume=true end
        local loader=data.Licensed and "sharkwow-license-loader.lua" or "sharkwow-standout-owner.lua"
        assert(loadstring(readfile(loader),"@sharkwow-standout-resume"))()
        env.SHARKWOW_STANDOUT_BOOT_STATUS="resumed"
    end)
    if not ok then env.SHARKWOW_STANDOUT_BOOT_STATUS="failed: "..tostring(err);env.SHARKWOW_STANDOUT_BOOTSTRAP=nil;warn("sharkwow resume: "..tostring(err)) end
end)

]=]
local resumeRetryAt = 0
local resumeFailures = 0
local transferGeneration = 0
local function ensureResumeReady(): (boolean, string?)
    if isfile("sharkwow-standout-no-autorun.flag") then state.ResumeStatus="disabled by owner";return true end
    if environment.SHARKWOW_STANDOUT_QUEUE_JOB == game.JobId and environment.SHARKWOW_STANDOUT_QUEUE_REVISION==3 then
        state.ResumeStatus = "ready"
        return true
    end
    local ok, err = pcall(function()
        local queue = queue_on_teleport or (syn and syn.queue_on_teleport)
        assert(type(queue) == "function" and type(readfile) == "function" and type(writefile) == "function", "executor resume API unavailable")
        local path = state.LicensedBuild and "sharkwow-license-loader.lua" or "sharkwow-standout-owner.lua"
        local source = readfile(path)
        assert(type(source) == "string" and #source > 100, "resume loader cache unavailable")
        assert(queue(resumePayload) ~= false, "resume queue rejected")
        environment.SHARKWOW_STANDOUT_QUEUE_JOB = game.JobId
        environment.SHARKWOW_STANDOUT_QUEUE_REVISION=3
    end)
    if ok then
        state.ResumeStatus = "ready"
        resumeFailures = 0
        return true
    end
    resumeFailures += 1
    resumeRetryAt = os.clock() + math.min(60, 2 ^ math.min(resumeFailures, 6))
    state.ResumeStatus = "retrying: " .. tostring(err):sub(1, 90)
    return false, state.ResumeStatus
end
state.EnsureResumeReady = ensureResumeReady
local function cancelTransfer(message: string)
    transferGeneration += 1
    state.TransferPending = false
    if type(writefile) == "function" then pcall(writefile, resumeFile, '{"Schema":1,"Enabled":false}') end
    if message ~= "" then setAutoStatus(message) end
end
table.insert(connections, player.OnTeleport:Connect(function(teleportState)
    if not alive or state.HopBusy then return end
    if teleportState == Enum.TeleportState.Failed then cancelTransfer("server transfer failed; farm resumed"); return end
    local ready = ensureResumeReady()
    if not ready then return end
    local saved, message = pcall(writefile, resumeFile, HttpService:JSONEncode({Schema = 1, Enabled = not isfile("sharkwow-standout-no-autorun.flag"),
        Created = os.time(), UserId=player.UserId, Licensed = state.LicensedBuild == true, AutoArrow = state.AutoArrow,
        AutoRokaka = state.AutoRokaka, FarmHide = state.FarmHide}))
    if not saved then state.ResumeStatus = "retrying: " .. tostring(message):sub(1, 90); return end
    state.TransferPending = true
    autoGeneration += 1
    transferGeneration += 1
    local generation = transferGeneration
    if releaseFastPickup then releaseFastPickup(); releaseFastPickup=nil end
    if activePrompt then pcall(function() activePrompt:InputHoldEnd() end); activePrompt = nil end
    task.delay(35, function()
        if alive and state.TransferPending and generation == transferGeneration then cancelTransfer("transfer timed out; farm resumed") end
    end)
end))
table.insert(connections, game:GetService("TeleportService").TeleportInitFailed:Connect(function(who)
    if alive and who == player and state.TransferPending then cancelTransfer("server transfer failed; farm resumed") end
end))

function state.HopLowServer(options): boolean
    options = type(options) == "table" and options or {}
    local function hopAllowed() return alive and (state.ServerTransfersEnabled==true or options.Manual==true) and (not options.CanContinue or options.CanContinue()) end
    if not alive or state.HopBusy then return false end
    if os.clock() < (state.HopNextRead or 0) then state.HopStatus = "server browser cooldown"; return false end
    state.HopBusy = true
    state.HopStatus = "finding a low population server..."
    task.spawn(function()
        local wanted = {AutoArrow = state.AutoArrow, AutoRokaka = state.AutoRokaka, FarmHide = state.FarmHide}
        local stoppedGeneration: number? = nil
        local failedConnection: RBXScriptConnection? = nil
        local function fail(message: string)
            if failedConnection then failedConnection:Disconnect(); failedConnection = nil end
            if not alive or not state.HopBusy then return end
            state.HopBusy = false
            state.HopStatus = message
            if type(writefile) == "function" then pcall(writefile, resumeFile, '{"Schema":1,"Enabled":false}') end
            if stoppedGeneration and autoGeneration == stoppedGeneration then
                state.AutoArrow, state.AutoRokaka = wanted.AutoArrow, wanted.AutoRokaka
                refreshAuto()
            end
            if options.OnFailure then pcall(options.OnFailure,message) end
        end
        local ok, err = pcall(function()
            local queue = queue_on_teleport or (syn and syn.queue_on_teleport)
            assert(type(queue) == "function" and type(writefile) == "function" and type(readfile) == "function", "executor cannot resume after teleport")
            local loaderFile = state.LicensedBuild and "sharkwow-license-loader.lua" or "sharkwow-standout-owner.lua"
            local cached = readfile(loaderFile)
            assert(type(cached) == "string" and #cached > 100, "run the latest installer before server hopping")
            local requester = request or http_request or (syn and syn.request)
            local cursor = nil
            local best = options.Target
            local sampled = 0
            state.HopNextRead = os.clock() + 15
            for _ = 1, (options.Target and 0 or 2) do
                if not alive then return end
                local url = "https://games.roblox.com/v1/games/" .. game.PlaceId .. "/servers/Public?sortOrder=Asc&limit=100&excludeFullGames=true"
                if cursor then url ..= "&cursor=" .. HttpService:UrlEncode(cursor) end
                local response = if type(requester) == "function" then requester({Url = url, Method = "GET", Timeout = 10})
                    else {StatusCode = 200, Body = game:HttpGet(url)}
                if not alive then return end
                assert(type(response) == "table", "server list unavailable")
                local code = tonumber(response.StatusCode or response.Status)
                if code == 429 then state.HopNextRead = os.clock() + 60 end
                assert(code == 200 and type(response.Body) == "string", "server list HTTP " .. tostring(code))
                local body = HttpService:JSONDecode(response.Body)
                assert(type(body) == "table" and type(body.data) == "table", "invalid server list")
                for _, server in ipairs(body.data) do
                    if type(server) == "table" and type(server.id) == "string" and #server.id == 36
                        and server.id:match("^[%x%-]+$") and type(server.playing) == "number"
                        and type(server.maxPlayers) == "number" and server.playing >= 0
                        and server.playing < server.maxPlayers then
                        sampled += 1
                        if server.id ~= game.JobId and (not options.Accept or options.Accept(server)) and (not best or server.playing < best.playing) then best = server end
                    end
                end
                if best then break end
                if type(body.nextPageCursor) ~= "string" or body.nextPageCursor == cursor then break end
                cursor = body.nextPageCursor
            end
            assert(best, "no unvisited joinable server in sampled pages")
            assert(hopAllowed(), "server hop cancelled")
            if not alive then return end
            local data = {Schema = 1, Enabled = not isfile("sharkwow-standout-no-autorun.flag"), Created = os.time(), UserId=player.UserId, Licensed = state.LicensedBuild == true,
                AutoArrow = wanted.AutoArrow, AutoRokaka = wanted.AutoRokaka, FarmHide = wanted.FarmHide}
            if options.PauseFarm then data.AutoArrow=false;data.AutoRokaka=false;data.HoldForJoin=true end
            writefile(resumeFile, HttpService:JSONEncode(data))
            local resumeOK, resumeError = ensureResumeReady()
            assert(resumeOK, resumeError)
            assert(hopAllowed(), "server hop cancelled")
            if options.BeforeTransfer then options.BeforeTransfer(best) end
            assert(hopAllowed(),"server transfers disabled")
            state.HopTarget = {id = best.id, playing = best.playing, sampled = sampled}
            local teleports = game:GetService("TeleportService")
            failedConnection = teleports.TeleportInitFailed:Connect(function(who, result, _, place)
                if who == player and place == game.PlaceId then fail("server hop failed: " .. tostring(result)) end
            end)
            table.insert(connections, failedConnection)
            state.AutoArrow, state.AutoRokaka = false, false
            refreshAuto()
            stoppedGeneration = autoGeneration
            stopHidden(true)
            state.HopStatus = string.format("joining server / %d players", best.playing)
            assert(state.BeginTransfer,"transfer lifecycle unavailable")()
            teleports:TeleportToPlaceInstance(game.PlaceId, best.id, player)
            task.delay(35, function() fail("server transfer not confirmed; farm restored") end)
        end)
        if not ok then
            if state.RecoverTransfer then state.RecoverTransfer(err) else fail(tostring(err):sub(1,120)) end
        end
    end)
    return true
end

local function installCompactTheme()
    local cyan = Color3.fromRGB(0, 240, 255)
    local purple = Color3.fromRGB(168, 85, 247)
    local surface = Color3.fromRGB(22, 30, 40)
    local ink = Color3.fromRGB(243, 247, 255)
    local bold = Font.new("rbxasset://fonts/families/BuilderSans.json", Enum.FontWeight.ExtraBold)
    local brand = Font.new("rbxasset://fonts/families/Montserrat.json", Enum.FontWeight.ExtraBold)
    local panelScale = Instance.new("UIScale")
    panelScale.Parent = panel
    local targetScale = 1
    local appearanceOpen = false
    local function animate(object: Instance, duration: number, values)
        if visualTweens[object] then visualTweens[object]:Cancel() end
        if not appearance.Effects or appearance.ReducedMotion then
            visualTweens[object] = nil
            for name, value in pairs(values) do object[name] = value end
            return
        end
        duration = duration / (appearance.Speed / 100)
        local tween = TweenService:Create(object, TweenInfo.new(duration, Enum.EasingStyle.Quart, Enum.EasingDirection.Out), values)
        visualTweens[object] = tween
        tween:Play()
        task.delay(duration + 0.05, function()
            if visualTweens[object] == tween then visualTweens[object] = nil end
        end)
    end
    panel.BackgroundColor3 = Color3.fromRGB(9, 17, 24)
    panel.CanvasSize = UDim2.new()
    panel.ScrollingEnabled = false
    panel.ScrollBarThickness = 0
    panel.ClipsDescendants = true
    limit.MaxSize = Vector2.new(720, 540)
    corner.CornerRadius = UDim.new(0, 12)
    local border = Instance.new("UIStroke")
    border.Thickness = 1.2
    border.Color = Color3.new(1, 1, 1)
    border.Parent = panel
    local gradient = Instance.new("UIGradient")
    gradient.Color = ColorSequence.new(cyan, purple)
    gradient.Rotation = 35
    gradient.Parent = border
    for _, text in ipairs({summary, listTitle, list, status, teleportStatus, autoStatus, movementStatus, help}) do text.Visible = false end
    title.Position = UDim2.fromOffset(12, 10)
    title.Size = UDim2.new(1, -136, 0, 25)
    title.Text = "SHARKWOW HUB"
    title.FontFace = brand
    title.TextSize = 17
    title.TextColor3 = ink
    title.Active = true
    local gameName = label("GameName", 34, 16, 12)
    gameName.Text = "STAND OUT / v" .. state.Version
    gameName.TextColor3 = Color3.fromRGB(166, 177, 204)
    gameName.FontFace = bold
    local minimize = button("Minimize", "-", 0)
    minimize.Position = UDim2.new(1, -78, 0, 10)
    minimize.Size = UDim2.fromOffset(32, 32)
    close.Position = UDim2.new(1, -40, 0, 10)
    close.Size = UDim2.fromOffset(32, 32)
    close.Text = "x"
    local appearanceButton = button("Appearance", "ui", 0)
    appearanceButton.Position = UDim2.new(1, -116, 0, 10)
    appearanceButton.Size = UDim2.fromOffset(32, 32)
    local divider = Instance.new("Frame")
    divider.Position = UDim2.fromOffset(12, 54)
    divider.Size = UDim2.new(1, -24, 0, 1)
    divider.BackgroundColor3 = purple
    divider.BackgroundTransparency = 0.5
    divider.BorderSizePixel = 0
    divider.Parent = panel
    local function place(b: TextButton, row: number, column: number)
        b.Position = UDim2.new(column * 0.5, 12, 0, 64 + row * 50)
        b.Size = UDim2.new(0.5, -18, 0, 44)
        b.BackgroundColor3 = surface
        b.TextColor3 = ink
        b.FontFace = bold
        b.TextSize = 16
    end
    place(autoArrowButton, 0, 0); place(autoRokakaButton, 0, 1)
    place(warpArrow, 1, 0); place(warpRokaka, 1, 1)
    place(flyButton, 2, 0); place(noclipButton, 2, 1)
    place(noFallButton, 3, 0); place(hide, 3, 1)
    local hideFarmButton = button("HideFarm", "", 0)
    local lowServerButton = button("LowServer", "low server", 0.5)
    place(hideFarmButton, 4, 0); place(lowServerButton, 4, 1)
    table.insert(connections, hideFarmButton.Activated:Connect(function() state.SetFarmHide(not state.FarmHide) end))
    table.insert(connections, lowServerButton.Activated:Connect(state.HopLowServer))
    place(upButton, 5, 0); place(downButton, 5, 1)
    upButton.Text = "hold: up"
    downButton.Text = "hold: down"
    local speedMinus = button("FlySpeedMinus", "-", 0)
    local speedPlus = button("FlySpeedPlus", "+", 0)
    speedMinus.Position = UDim2.fromOffset(12, 364)
    speedMinus.Size = UDim2.fromOffset(44, 40)
    speedPlus.Position = UDim2.new(1, -56, 0, 364)
    speedPlus.Size = UDim2.fromOffset(44, 40)
    local speedBox = Instance.new("TextBox")
    speedBox.Name = "FlySpeed"
    speedBox.Position = UDim2.fromOffset(64, 364)
    speedBox.Size = UDim2.new(1, -128, 0, 40)
    speedBox.BackgroundColor3 = surface
    speedBox.TextColor3 = ink
    speedBox.BorderSizePixel = 0
    speedBox.FontFace = bold
    speedBox.TextSize = 17
    speedBox.ClearTextOnFocus = false
    speedBox.PlaceholderText = "speed 10-200"
    speedBox.Text = tostring(state.FlySpeed)
    speedBox.Parent = panel
    local speedRound = Instance.new("UICorner")
    speedRound.CornerRadius = UDim.new(0, 8)
    speedRound.Parent = speedBox
    local function setFlySpeed(value: number)
        if value ~= value or math.abs(value) == math.huge then return end
        state.FlySpeed = math.clamp(math.floor(value + 0.5), 10, 200)
        speedBox.Text = tostring(state.FlySpeed)
        savePreferences()
    end
    state.SetFlySpeed = setFlySpeed
    table.insert(connections, speedMinus.Activated:Connect(function() setFlySpeed(state.FlySpeed - 10) end))
    table.insert(connections, speedPlus.Activated:Connect(function() setFlySpeed(state.FlySpeed + 10) end))
    table.insert(connections, speedBox.FocusLost:Connect(function()
        local value = tonumber(speedBox.Text)
        if value then setFlySpeed(value) else speedBox.Text = tostring(state.FlySpeed) end
    end))
    local switches = {}
    local function switch(b: TextButton, caption: string, getter: () -> boolean)
        local text = Instance.new("TextLabel")
        text.Name = "Caption"
        text.BackgroundTransparency = 1
        text.Position = UDim2.fromOffset(9, 0)
        text.Size = UDim2.new(1, -58, 1, 0)
        text.Text = caption
        text.FontFace = bold
        text.TextSize = 16
        text.TextColor3 = ink
        text.TextXAlignment = Enum.TextXAlignment.Left
        text.Parent = b
        local track = Instance.new("Frame")
        track.Name = "Track"
        track.Position = UDim2.new(1, -47, 0.5, -11)
        track.Size = UDim2.fromOffset(38, 22)
        track.BorderSizePixel = 0
        track.Parent = b
        local round = Instance.new("UICorner")
        round.CornerRadius = UDim.new(1, 0)
        round.Parent = track
        local thumb = Instance.new("Frame")
        thumb.Size = UDim2.fromOffset(18, 18)
        thumb.BackgroundColor3 = ink
        thumb.BorderSizePixel = 0
        thumb.Parent = track
        round:Clone().Parent = thumb
        table.insert(switches, {button = b, track = track, thumb = thumb, getter = getter, value = nil})
    end
    switch(autoArrowButton, "auto arrow", function() return state.AutoArrow end)
    switch(autoRokakaButton, "auto roka", function() return state.AutoRokaka end)
    switch(flyButton, "fly", function() return state.Flying end)
    switch(noclipButton, "noclip", function() return state.Noclip end)
    switch(noFallButton, "no fall", function() return state.NoFall end)
    switch(hide, "item esp", function() return visible end)
    switch(hideFarmButton, "hide farm", function() return state.FarmHide end)
    local appearanceFrame = Instance.new("Frame")
    appearanceFrame.Name = "AppearancePage"
    appearanceFrame.Position = UDim2.fromOffset(12, 64)
    appearanceFrame.Size = UDim2.new(1, -24, 0, 366)
    appearanceFrame.BackgroundTransparency = 1
    appearanceFrame.Visible = false
    appearanceFrame.Parent = panel
    local appearanceRefreshers = {}
    local function changeAppearance(name: string, value)
        appearance[name] = value
        for _, callback in ipairs(appearanceRefreshers) do callback() end
        if state.RefreshUI then state.RefreshUI() end
        savePreferences()
    end
    local function appearanceRow(name: string, y: number): TextButton
        local row = button(name, "", 0)
        row.Parent = appearanceFrame
        row.Position = UDim2.fromOffset(0, y)
        row.Size = UDim2.new(1, 0, 0, 42)
        row.BackgroundColor3 = surface
        row.FontFace = bold
        row.TextSize = 16
        return row
    end
    local function numericSetting(name: string, caption: string, y: number, minimum: number, maximum: number, step: number)
        local row = appearanceRow(name, y)
        row.TextXAlignment = Enum.TextXAlignment.Left
        local text = Instance.new("TextLabel")
        text.Position = UDim2.fromOffset(10, 0)
        text.Size = UDim2.new(1, -108, 1, 0)
        text.BackgroundTransparency = 1
        text.TextXAlignment = Enum.TextXAlignment.Left
        text.FontFace = bold
        text.TextSize = 16
        text.TextColor3 = ink
        text.Parent = row
        for _, spec in ipairs({{symbol = "-", delta = -step, offset = -92}, {symbol = "+", delta = step, offset = -44}}) do
            local b = appearanceRow(name .. spec.symbol, 0)
            b.Parent = row
            b.Position = UDim2.new(1, spec.offset, 0, 0)
            b.Size = UDim2.fromOffset(42, 42)
            b.Text = spec.symbol
            b.TextColor3 = cyan
            table.insert(connections, b.Activated:Connect(function() changeAppearance(name, math.clamp(appearance[name] + spec.delta, minimum, maximum)) end))
        end
        table.insert(appearanceRefreshers, function() text.Text = caption .. "  " .. tostring(math.floor(appearance[name])) .. "%" end)
    end
    numericSetting("Scale", "size", 0, 65, 115, 5)
    numericSetting("Glow", "glow", 48, 0, 100, 5)
    numericSetting("Speed", "animation", 96, 50, 200, 10)
    for _, spec in ipairs({{key = "Effects", caption = "neon effects", y = 144}, {key = "Particles", caption = "particles", y = 192}, {key = "ReducedMotion", caption = "reduced motion", y = 240}}) do
        local row = appearanceRow(spec.key, spec.y)
        switch(row, spec.caption, function() return appearance[spec.key] end)
        table.insert(connections, row.Activated:Connect(function() changeAppearance(spec.key, not appearance[spec.key]) end))
    end
    local reset = appearanceRow("ResetLayout", 288)
    reset.Text = "reset size / center"
    table.insert(connections, reset.Activated:Connect(function()
        changeAppearance("Scale", 100)
        local view = gui.AbsoluteSize
        state.MoveWindow(Vector2.new((view.X - panel.AbsoluteSize.X) / 2, (view.Y - panel.AbsoluteSize.Y) / 2))
    end))
    local identity = Instance.new("TextLabel")
    identity.Position = UDim2.new(0, 0, 0, 338)
    identity.Size = UDim2.new(1, -36, 0, 26)
    identity.BackgroundTransparency = 1
    identity.Text = player.DisplayName
    identity.TextXAlignment = Enum.TextXAlignment.Right
    identity.TextColor3 = Color3.fromRGB(166, 177, 204)
    identity.FontFace = bold
    identity.TextSize = 14
    identity.Parent = appearanceFrame
    local avatar = Instance.new("ImageLabel")
    avatar.Position = UDim2.new(1, -28, 0, 338)
    avatar.Size = UDim2.fromOffset(26, 26)
    avatar.BackgroundTransparency = 1
    avatar.Parent = appearanceFrame
    task.spawn(function()
        local ok, image = pcall(function() return Players:GetUserThumbnailAsync(player.UserId, Enum.ThumbnailType.HeadShot, Enum.ThumbnailSize.Size48x48) end)
        if alive and ok then avatar.Image = image end
    end)
    for _, callback in ipairs(appearanceRefreshers) do callback() end
    local notice = label("Notice", 266, 36, 14)
    notice.TextColor3 = Color3.fromRGB(255, 190, 80)
    notice.FontFace = bold
    local dock = button("SharkDock", "", 0)
    dock.Parent = gui
    dock.Size = UDim2.fromOffset(210, 50)
    dock.Position = UDim2.new(0.5, -105, 0, 6)
    dock.BackgroundColor3 = Color3.fromRGB(9, 17, 24)
    dock.ClipsDescendants = true
    local dockBorder = border:Clone()
    dockBorder.Parent = dock
    local dockText = Instance.new("TextLabel")
    dockText.Size = UDim2.new(1, 0, 0, 26)
    dockText.BackgroundTransparency = 1
    dockText.Text = "SHARKWOW"
    dockText.FontFace = brand
    dockText.TextSize = 14
    dockText.TextColor3 = ink
    dockText.Parent = dock
    local water = Instance.new("Frame")
    water.Position = UDim2.new(0, 0, 1, -22)
    water.Size = UDim2.new(1, 0, 0, 22)
    water.ClipsDescendants = true
    water.BackgroundColor3 = Color3.fromRGB(0, 117, 173)
    water.BorderSizePixel = 0
    water.Parent = dock
    local fish = Instance.new("Frame")
    fish.Position = UDim2.new(0.72, 0, 0, 4)
    fish.Size = UDim2.fromOffset(28, 6)
    fish.BackgroundColor3 = Color3.fromRGB(186, 231, 245)
    fish.BorderSizePixel = 0
    fish.Parent = water
    local curve = Instance.new("UICorner")
    curve.CornerRadius = UDim.new(1, 0)
    curve.Parent = fish
    for _, shape in ipairs({{x = 9, y = -3, w = 7, h = 7}, {x = -3, y = 0, w = 6, h = 6}}) do
        local fin = Instance.new("Frame")
        fin.Position = UDim2.fromOffset(shape.x, shape.y)
        fin.Size = UDim2.fromOffset(shape.w, shape.h)
        fin.BackgroundColor3 = fish.BackgroundColor3
        fin.BorderSizePixel = 0
        fin.Rotation = 45
        fin.Parent = fish
    end
    fish.Visible = false
    local shark = Instance.new("Frame")
    shark.Name = "PixelShark"
    shark.Size = UDim2.fromOffset(48, 20)
    shark.Position = UDim2.fromOffset(95, 1)
    shark.BackgroundTransparency = 1
    shark.Parent = water
    local pixels = {"............ss..........", "...........ssss.........", "ss........ssssss........", ".sss..ssssssssssssss....", "..ssssssssssssssssses...", "...sssssssssssssssssss..", "..ssswwwwwwwwwwwwwwww...", ".sss...wwwwwwwwwwww.....", "ss.......sss..ss........", "..........ss............"}
    local pixelColors = {s = Color3.fromRGB(137, 165, 182), w = Color3.fromRGB(232, 248, 255), e = Color3.fromRGB(5, 19, 28)}
    for y, line in ipairs(pixels) do
        local x = 1
        while x <= #line do
            local symbol = string.sub(line, x, x)
            local last = x
            while last < #line and string.sub(line, last + 1, last + 1) == symbol do last += 1 end
            if pixelColors[symbol] then
                local piece = Instance.new("Frame")
                piece.Position = UDim2.fromOffset((x - 1) * 2, (y - 1) * 2)
                piece.Size = UDim2.fromOffset((last - x + 1) * 2, 2)
                piece.BackgroundColor3 = pixelColors[symbol]
                piece.BorderSizePixel = 0
                piece.Parent = shark
            end
            x = last + 1
        end
    end
    local waves = {}
    for layer = 1, 2 do
        for column = 0, 17 do
            local segment = Instance.new("Frame")
            segment.Size = UDim2.fromOffset(13, 22)
            segment.BorderSizePixel = 0
            segment.BackgroundColor3 = layer == 1 and Color3.fromRGB(52, 173, 231) or Color3.fromRGB(21, 113, 183)
            segment.BackgroundTransparency = 0.45
            segment.ZIndex = 0
            segment.Parent = water
            table.insert(waves, {node = segment, layer = layer, column = column})
        end
    end
    local particles = {}
    for i = 1, 6 do
        local dot = Instance.new("Frame")
        dot.Name = "AmbientDot"
        dot.Size = UDim2.fromOffset(2, 2)
        dot.BorderSizePixel = 0
        dot.BackgroundColor3 = i % 2 == 0 and cyan or purple
        dot.BackgroundTransparency = 0.5
        dot.ZIndex = 0
        dot.Parent = panel
        table.insert(particles, dot)
    end
    local showGeneration = 0
    local isShown = true
    local function setShown(value: boolean)
        showGeneration += 1
        for _, object in ipairs(panel:GetChildren()) do
            if object.Name == "OpeningWave" then
                if visualTweens[object] then visualTweens[object]:Cancel(); visualTweens[object] = nil end
                object:Destroy()
            end
        end
        local generation = showGeneration
        isShown = value
        state.WindowVisible = value
        if value then
            panel.Visible = true
            panelScale.Scale = 0.97 * targetScale
            animate(panelScale, 0.19, {Scale = targetScale})
            for i = 1, (appearance.Effects and not appearance.ReducedMotion) and 3 or 0 do
                local wave = Instance.new("Frame")
                wave.Name = "OpeningWave"
                wave.BackgroundColor3 = i == 2 and purple or cyan
                wave.BackgroundTransparency = 0.86
                wave.BorderSizePixel = 0
                wave.Size = UDim2.fromScale(1, 0.25)
                wave.Position = UDim2.fromScale(0, 1)
                wave.ZIndex = 10
                wave.Active = false
                wave.Parent = panel
                animate(wave, 0.16 + i * 0.02, {Position = UDim2.fromScale(0, -0.25), BackgroundTransparency = 1})
                task.delay(0.22 / (appearance.Speed / 100) + 0.05, function() visualTweens[wave] = nil; wave:Destroy() end)
            end
        else
            animate(panelScale, 0.13, {Scale = 0.97 * targetScale})
            local delay = (appearance.Effects and not appearance.ReducedMotion) and (0.13 / (appearance.Speed / 100) + 0.01) or 0.01
            task.delay(delay, function() if alive and showGeneration == generation then panel.Visible = false end end)
        end
    end
    state.SetWindowVisible = setShown
    state.Hybrid=(function()
local Hybrid = {Version = "ocean-original-2"}
local cyan, purple = Color3.fromRGB(0,240,255), Color3.fromRGB(168,85,247)
local background, surface = Color3.fromRGB(9,17,24), Color3.fromRGB(22,30,40)
local input = game:GetService("UserInputService")
local tweenService = game:GetService("TweenService")
local owners = setmetatable({}, {__mode="k"})

function Hybrid.mount(config)
    local dock, panel = assert(config.Dock), assert(config.Panel)
    if owners[dock] then owners[dock]:Destroy() end
    local self = {Alive=true, Version=Hybrid.Version, Connections={}, Tweens={}, Nodes={}, Toasts={}, Hidden={}, Drag=nil, BlockUntil=0}
    owners[dock]=self
    local function connect(signal, callback)
        local c=signal:Connect(function(...) if self.Alive then callback(...) end end)
        self.Connections[#self.Connections+1]=c;return c
    end
    local function make(class, parent, props)
        local n=Instance.new(class)
        for k,v in pairs(props) do n[k]=v end
        n.Parent=parent;self.Nodes[#self.Nodes+1]=n;return n
    end
    local function corner(n,r)
        local c=n:FindFirstChildOfClass("UICorner")
        if not c then c=make("UICorner",n,{}) end
        c.CornerRadius=UDim.new(0,r)
    end
    local function motion() return not config.ReducedMotion or not config.ReducedMotion() end
    local function animate(n,props)
        local old=self.Tweens[n]
        if old then old.Connection:Disconnect();old.Tween:Cancel();self.Tweens[n]=nil end
        if not motion() then for k,v in pairs(props) do n[k]=v end;return end
        local t=tweenService:Create(n,TweenInfo.new(.16,Enum.EasingStyle.Quart,Enum.EasingDirection.Out),props)
        local entry={Tween=t};self.Tweens[n]=entry
        entry.Connection=t.Completed:Connect(function()
            entry.Connection:Disconnect()
            if self.Tweens[n]==entry then self.Tweens[n]=nil end
        end)
        t:Play()
    end
    local originalWidth,originalHeight=dock.Size.X.Offset,dock.Size.Y.Offset
    dock:SetAttribute("SharkHybrid",Hybrid.Version)
    dock:SetAttribute("OriginalOceanLauncher",true)
    local stroke=dock:FindFirstChildOfClass("UIStroke") or make("UIStroke",dock,{Color=cyan,Transparency=.38,Thickness=1})
    function self:CanActivate()
        return self.Alive and (not self.Drag or not self.Drag.Moved) and os.clock()>=self.BlockUntil and (not config.CanInteract or config.CanInteract())
    end
    function self:Clamp(position,viewport,extent)
        return Vector2.new(math.clamp(position.X,8,math.max(8,viewport.X-extent.X-8)),math.clamp(position.Y,8,math.max(8,viewport.Y-extent.Y-8)))
    end
    function self:Layout()
        if not self.Alive or not dock.Parent then return end
        local v=dock.Parent.AbsoluteSize
        local compact=v.X<600
        dock.Size=UDim2.fromOffset(math.min(originalWidth,math.max(80,v.X-16)),originalHeight)
        local p=self:Clamp(dock.AbsolutePosition-dock.Parent.AbsolutePosition,v,dock.AbsoluteSize)
        dock.Position=UDim2.fromOffset(p.X+dock.AnchorPoint.X*dock.AbsoluteSize.X,p.Y+dock.AnchorPoint.Y*dock.AbsoluteSize.Y)

    end
    function self:Begin(key,position)
        if self.Drag or (config.CanInteract and not config.CanInteract()) then return end
        self.Drag={Key=key,Origin=position,Start=dock.AbsolutePosition-dock.Parent.AbsolutePosition,Moved=false}
        animate(stroke,{Transparency=.08})
    end
    function self:Move(key,position,mouse)
        local d=self.Drag;if not d or (key~=d.Key and not mouse) then return end
        local delta=position-d.Origin
        if delta.Magnitude<6 and not d.Moved then return end
        d.Moved=true;self.BlockUntil=os.clock()+.3
        local p=self:Clamp(d.Start+delta,dock.Parent.AbsoluteSize,dock.AbsoluteSize)
        dock.Position=UDim2.fromOffset(p.X+dock.AnchorPoint.X*dock.AbsoluteSize.X,p.Y+dock.AnchorPoint.Y*dock.AbsoluteSize.Y)
    end
    function self:Finish(key)
        if not self.Drag or self.Drag.Key~=key then return end
        if self.Drag.Moved then self.BlockUntil=os.clock()+.3 end
        self.Drag=nil;animate(stroke,{Transparency=.38})
    end
    connect(dock.InputBegan,function(e)
        if e.UserInputType==Enum.UserInputType.MouseButton1 or e.UserInputType==Enum.UserInputType.Touch then self:Begin(e,Vector2.new(e.Position.X,e.Position.Y)) end
    end)
    connect(input.InputChanged,function(e)
        local d=self.Drag
        self:Move(e,Vector2.new(e.Position.X,e.Position.Y),d and d.Key.UserInputType==Enum.UserInputType.MouseButton1 and e.UserInputType==Enum.UserInputType.MouseMovement)
    end)
    connect(input.InputEnded,function(e) self:Finish(e) end)
    connect(input.WindowFocusReleased,function() if self.Drag then self.BlockUntil=os.clock()+.3 end;self.Drag=nil;animate(stroke,{Transparency=.38}) end)
    connect(dock.MouseEnter,function() animate(stroke,{Transparency=.08}); end)
    connect(dock.MouseLeave,function() animate(stroke,{Transparency=.38});if not self.Drag then animate(stroke,{Transparency=.38}) end end)
    connect(dock.Parent:GetPropertyChangedSignal("AbsoluteSize"),function() self:Layout() end)
    function self:Refresh()
        dock:SetAttribute("WindowOpen",config.IsShown())
    end
    connect(panel:GetPropertyChangedSignal("Visible"),function() self:Refresh() end)
    local colors={
        ["0a0a12"]=background,["10101c"]=Color3.fromRGB(13,23,32),["161625"]=surface,
        ["0f0f1a"]=Color3.fromRGB(13,23,32),["302a45"]=Color3.fromRGB(41,60,74),
    }
    local function skin(n)
        if n:IsA("GuiObject") then
            local mapped=colors[n.BackgroundColor3:ToHex():lower()]
            if mapped then n.BackgroundColor3=mapped end
            if n:IsA("TextBox") then n.TextColor3=Color3.fromRGB(239,249,255);n.PlaceholderColor3=Color3.fromRGB(151,177,193);corner(n,8) end
        end
    end
    skin(panel)
    for _,n in ipairs(panel:GetDescendants()) do skin(n) end
    connect(panel.DescendantAdded,skin)
    local rail=make("Frame",panel,{Name="HybridAccentRail",Position=UDim2.fromOffset(14,1),Size=UDim2.new(1,-28,0,2),BackgroundColor3=Color3.new(1,1,1),BorderSizePixel=0,ZIndex=12,Active=false})
    make("UIGradient",rail,{Color=ColorSequence.new(cyan,purple),Transparency=NumberSequence.new({NumberSequenceKeypoint.new(0,.6),NumberSequenceKeypoint.new(.5,.1),NumberSequenceKeypoint.new(1,.6)})})
    function self:Notify(title,message)
        if not self.Alive then return end
        if #self.Toasts>=3 then local old=table.remove(self.Toasts,1);self:ReleaseToast(old.Node) end
        local n=make("Frame",config.Gui,{Name="SharkHybridNotification",AnchorPoint=Vector2.new(1,1),Size=UDim2.fromOffset(math.min(300,config.Gui.AbsoluteSize.X-20),66),Position=UDim2.new(1,-12,1,-12),BackgroundColor3=surface,BorderSizePixel=0,ZIndex=90});corner(n,12)
        make("UIStroke",n,{Color=cyan,Transparency=.6})
        make("TextLabel",n,{Position=UDim2.fromOffset(12,8),Size=UDim2.new(1,-24,0,20),Text=title,TextColor3=cyan,TextSize=14,Font=Enum.Font.BuilderSansBold,BackgroundTransparency=1,TextXAlignment=Enum.TextXAlignment.Left,ZIndex=91})
        make("TextLabel",n,{Position=UDim2.fromOffset(12,30),Size=UDim2.new(1,-24,0,29),Text=message,TextColor3=Color3.fromRGB(208,222,235),TextSize=12,Font=Enum.Font.BuilderSans,BackgroundTransparency=1,TextWrapped=true,TextXAlignment=Enum.TextXAlignment.Left,ZIndex=91})
        self.Toasts[#self.Toasts+1]={Node=n,Until=os.clock()+4}
        for i,t in ipairs(self.Toasts) do animate(t.Node,{Position=UDim2.new(1,-12,1,-12-(#self.Toasts-i)*74)}) end
    end
    function self:ReleaseToast(node)
        for i=#self.Nodes,1,-1 do
            local n=self.Nodes[i]
            if n==node or n:IsDescendantOf(node) then
                local t=self.Tweens[n]
                if t then t.Connection:Disconnect();t.Tween:Cancel();self.Tweens[n]=nil end
                table.remove(self.Nodes,i)
            end
        end
        node:Destroy()
    end
    local elapsed=0
    connect(game:GetService("RunService").Heartbeat,function(dt)
        elapsed+=dt;if elapsed<.25 then return end;elapsed=0
        for i=#self.Toasts,1,-1 do local t=self.Toasts[i];if os.clock()>t.Until then self:ReleaseToast(t.Node);table.remove(self.Toasts,i) end end
    end)
    function self:Destroy()
        if not self.Alive then return end;self.Alive=false;self.Drag=nil
        for _,c in ipairs(self.Connections) do c:Disconnect() end;table.clear(self.Connections)
        for _,t in pairs(self.Tweens) do t.Connection:Disconnect();t.Tween:Cancel() end;table.clear(self.Tweens)
        for i=#self.Nodes,1,-1 do self.Nodes[i]:Destroy() end;table.clear(self.Nodes);table.clear(self.Toasts)
        for n,visible in pairs(self.Hidden) do if n.Parent then n.Visible=visible end end;table.clear(self.Hidden)
        if owners[dock]==self then owners[dock]=nil end
    end
    connect(dock.Destroying,function() self:Destroy() end)
    self:Layout();self:Refresh()
    return self
end
return Hybrid

    end)().mount({Dock=dock,Panel=panel,Gui=gui,Game="Stand Out",IsShown=function()return isShown end,ReducedMotion=function()return appearance.ReducedMotion or not appearance.Effects end})
    local function safeArea(): Vector2
        return gui.AbsoluteSize
    end
    local function moveWindow(position: Vector2)
        local viewport = safeArea()
        local size = panel.AbsoluteSize
        panel.Position = UDim2.fromOffset(math.clamp(position.X, 4, math.max(4, viewport.X - size.X - 4)), math.clamp(position.Y, 4, math.max(4, viewport.Y - size.Y - 4)))
        state.WindowPosition = Vector2.new(panel.Position.X.Offset, panel.Position.Y.Offset)
    end
    state.MoveWindow = moveWindow
    local dragInput: InputObject? = nil
    local dragging: GuiObject? = nil
    local startPointer = Vector2.zero
    local startPosition = Vector2.zero
    local dragDistance = 0
    local suppressDockClick = false
    local function beginDrag(object: GuiObject, input: InputObject)
        if input.UserInputType ~= Enum.UserInputType.MouseButton1 and input.UserInputType ~= Enum.UserInputType.Touch then return end
        dragging = object
        dragInput = input
        startPointer = Vector2.new(input.Position.X, input.Position.Y)
        startPosition = Vector2.new(object.Position.X.Offset, object.Position.Y.Offset)
        if object == dock then
            local viewport = safeArea()
            startPosition += Vector2.new(object.Position.X.Scale * viewport.X, object.Position.Y.Scale * viewport.Y)
        end
        dragDistance = 0
    end
    table.insert(connections, title.InputBegan:Connect(function(input) beginDrag(panel, input) end))
    table.insert(connections, gameName.InputBegan:Connect(function(input) beginDrag(panel, input) end))
    gameName.Active = true

    table.insert(connections, UserInputService.InputChanged:Connect(function(input)
        if not dragging then return end
        if input.UserInputType ~= Enum.UserInputType.MouseMovement and input ~= dragInput then return end
        local delta = Vector2.new(input.Position.X, input.Position.Y) - startPointer
        dragDistance = delta.Magnitude
        if dragging == panel then moveWindow(startPosition + delta)
        else
            local view = safeArea()
            local pos = startPosition + delta
            dock.Position = UDim2.fromOffset(math.clamp(pos.X, 0, math.max(0, view.X - dock.AbsoluteSize.X)), math.clamp(pos.Y, 0, math.max(0, view.Y - dock.AbsoluteSize.Y)))
        end
    end))
    table.insert(connections, UserInputService.InputEnded:Connect(function(input)
        if dragging and (input == dragInput or input.UserInputType == Enum.UserInputType.MouseButton1) then
            if dragging == dock and dragDistance > 5 then
                suppressDockClick = true
                task.delay(0.1, function() suppressDockClick = false end)
            end
            dragging, dragInput = nil, nil
            savePreferences()
        end
    end))
    table.insert(connections, UserInputService.WindowFocusReleased:Connect(function() dragging, dragInput = nil, nil end))
    table.insert(connections, minimize.Activated:Connect(function() setShown(false) end))
    table.insert(connections, dock.Activated:Connect(function() if not suppressDockClick and (not state.Hybrid or state.Hybrid:CanActivate()) then setShown(not isShown) end end))
    table.insert(connections, UserInputService.InputBegan:Connect(function(input, processed)
        if not processed and input.KeyCode == Enum.KeyCode.RightShift and not UserInputService:GetFocusedTextBox() then setShown(not isShown) end
    end))
    local function refresh()
        for _, entry in ipairs(switches) do
            local value = entry.getter()
            entry.button.Text = ""
            entry.button.BackgroundColor3 = surface
            if value ~= entry.value then
                entry.value = value
                entry.track.BackgroundColor3 = value and Color3.fromRGB(0, 120, 136) or Color3.fromRGB(56, 47, 77)
                animate(entry.thumb, 0.12, {Position = UDim2.fromOffset(value and 18 or 2, 2), BackgroundColor3 = value and cyan or Color3.fromRGB(166, 177, 204)})
            end
        end
        warpArrow.Text = string.format("warp arrow (%d)", state.Arrow)
        warpRokaka.Text = string.format("warp roka (%d)", state.Rokaka)
        for _, b in ipairs({autoArrowButton, autoRokakaButton, warpArrow, warpRokaka, flyButton, noclipButton, noFallButton, hide, hideFarmButton, lowServerButton}) do b.Visible = not appearanceOpen and not state.ModulesOpen end
        lowServerButton.Text = state.HopBusy and "joining..." or "low server"
        appearanceFrame.Visible = appearanceOpen and not state.ModulesOpen
        gameName.Text = appearanceOpen and "APPEARANCE" or "STAND OUT / v" .. state.Version
        appearanceButton.Text = appearanceOpen and "<" or "ui"
        local flightControls = state.Flying and not appearanceOpen and not state.ModulesOpen
        upButton.Visible, downButton.Visible = flightControls, flightControls
        speedBox.Visible, speedMinus.Visible, speedPlus.Visible = flightControls, flightControls, flightControls
        if not speedBox:IsFocused() then speedBox.Text = tostring(state.FlySpeed) end
        local message = ""
        if state.HopStatus ~= "" then message = state.HopStatus
        elseif state.MovementError ~= "" then message = "movement error: toggle off / on"
        elseif string.find(state.AntiAFK, "retrying:", 1, true) then message = "anti-afk retrying"
        elseif state.LastError ~= "" then message = "item scan retrying"
        elseif state.TransferPending then message = "changing server..."
        elseif state.RouteBusy then message = state.RouteStatus .. " / +" .. state.AutoCollected
        elseif state.AutoBusy then message = "collecting item..."
        elseif state.WaitForArrow and (state.AutoArrow or state.AutoRokaka or state.AutoParts) then message = "waiting for items / no patrol"
        elseif state.AutoArrow and state.RouteCount > 0 then message = string.format("arrow patrol / %d points", state.RouteCount)
        elseif (state.AutoArrow or state.AutoRokaka or state.AutoParts) and state.Arrow + state.Rokaka == 0 then message = "waiting for items"
        elseif string.find(state.AutoStatus, "retry", 1, true) then message = "pickup unavailable; waiting"
        end
        notice.Visible = message ~= "" and not appearanceOpen and not state.ModulesOpen
        notice.Text = message
        notice.Position = UDim2.fromOffset(12, state.Flying and 414 or 316)
        local height = appearanceOpen and 440 or (state.Flying and 418 or 320) + (message ~= "" and 34 or 0)
        if state.ModulesOpen then height = 510 end
        local width = state.ModulesOpen and math.min(720, math.max(320, safeArea().X - 12)) or 356
        local view = safeArea()
        targetScale = math.min(appearance.Scale / 100, (view.Y - 12) / height, (view.X - 12) / width)
        targetScale = math.max(0.4, targetScale)
        panel.Size = UDim2.fromOffset(width, height)
        if not visualTweens[panelScale] then panelScale.Scale = targetScale end
        border.Transparency = appearance.Effects and (1 - appearance.Glow / 100 * 0.8) or 0.85
        for _, dot in ipairs(particles) do dot.Visible = appearance.Effects and appearance.Particles and not appearance.ReducedMotion and isShown end
        moveWindow(Vector2.new(panel.Position.X.Offset, panel.Position.Y.Offset))
    end
    state.RefreshUI = refresh
    table.insert(connections, appearanceButton.Activated:Connect(function() state.ModulesOpen = false; appearanceOpen = not appearanceOpen; refresh() end))
    local restoredPosition = retained.Position or Vector2.new(20, 100)
    panel.Position = UDim2.fromOffset(restoredPosition.X, restoredPosition.Y)
    refresh()
    table.insert(connections, hide.Activated:Connect(refresh))
    table.insert(connections, gui:GetPropertyChangedSignal("AbsoluteSize"):Connect(refresh))
    for _, b in ipairs({autoArrowButton, autoRokakaButton, warpArrow, warpRokaka, flyButton, noclipButton, noFallButton, hide, hideFarmButton, lowServerButton, upButton, downButton, close, minimize, appearanceButton, speedMinus, speedPlus}) do
        local scale = Instance.new("UIScale")
        scale.Parent = b
        local outline = Instance.new("UIStroke")
        outline.Color = purple
        outline.Transparency = 0.78
        outline.Parent = b
        table.insert(connections, b.MouseEnter:Connect(function() animate(outline, 0.12, {Color = cyan, Transparency = 0.3}) end))
        table.insert(connections, b.MouseLeave:Connect(function() animate(outline, 0.12, {Color = purple, Transparency = 0.78}); animate(scale, 0.14, {Scale = 1}) end))
        table.insert(connections, b.MouseButton1Down:Connect(function() animate(scale, 0.08, {Scale = 0.975}) end))
        table.insert(connections, b.MouseButton1Up:Connect(function() animate(scale, 0.14, {Scale = 1}) end))
        table.insert(connections, b.Activated:Connect(function()
            if not appearance.Effects or appearance.ReducedMotion then return end
            local old = b:FindFirstChild("Ripple")
            if old then if visualTweens[old] then visualTweens[old]:Cancel(); visualTweens[old] = nil end; old:Destroy() end
            local ripple = Instance.new("Frame")
            ripple.Name = "Ripple"
            ripple.AnchorPoint = Vector2.new(0.5, 0.5)
            ripple.Position = UDim2.fromScale(0.5, 0.5)
            ripple.Size = UDim2.fromOffset(1, 1)
            ripple.BackgroundColor3 = cyan
            ripple.BackgroundTransparency = 0.82
            ripple.BorderSizePixel = 0
            ripple.Active = false
            ripple.Parent = b
            local r = Instance.new("UICorner")
            r.CornerRadius = UDim.new(1, 0)
            r.Parent = ripple
            b.ClipsDescendants = true
            animate(ripple, 0.3, {Size = UDim2.fromScale(1.5, 2), BackgroundTransparency = 1})
            task.delay(0.65, function() visualTweens[ripple] = nil; ripple:Destroy() end)
        end))
    end
    local grip = button("Resize", "/", 0)
    grip.Position = UDim2.new(1, -22, 1, -22)
    grip.Size = UDim2.fromOffset(20, 20)
    grip.BackgroundTransparency = 1
    grip.TextColor3 = cyan
    local resizeInput: InputObject? = nil
    local resizeStart = Vector2.zero
    local resizeScale = 100
    local resizeMoved = false
    local resizeAt = 0
    table.insert(connections, grip.InputBegan:Connect(function(input)
        if input.UserInputType == Enum.UserInputType.MouseButton1 or input.UserInputType == Enum.UserInputType.Touch then
            resizeInput = input; resizeStart = Vector2.new(input.Position.X, input.Position.Y); resizeScale = appearance.Scale; resizeMoved = false
        end
    end))
    table.insert(connections, UserInputService.InputChanged:Connect(function(input)
        if not resizeInput or (input ~= resizeInput and input.UserInputType ~= Enum.UserInputType.MouseMovement) or os.clock() - resizeAt < 1 / 30 then return end
        resizeAt = os.clock()
        local delta = Vector2.new(input.Position.X, input.Position.Y) - resizeStart
        resizeMoved = resizeMoved or delta.Magnitude > 4
        changeAppearance("Scale", math.clamp(math.floor(resizeScale + delta.X / 3.56), 65, 115))
    end))
    table.insert(connections, UserInputService.InputEnded:Connect(function(input)
        if resizeInput and (input == resizeInput or input.UserInputType == Enum.UserInputType.MouseButton1) then
            resizeInput = nil
            if not resizeMoved then changeAppearance("Scale", math.max(65, appearance.Scale - 5)) end
        end
    end))
    table.insert(connections, UserInputService.WindowFocusReleased:Connect(function() resizeInput = nil end))
    local elapsed, clock = 0, 0
    table.insert(connections, RunService.Heartbeat:Connect(function(dt)
        if not alive or not appearance.Effects or appearance.ReducedMotion then return end
        elapsed += math.min(dt, 0.1)
        if elapsed < 1 / 12 then return end
        clock += elapsed * appearance.Speed / 100; elapsed = 0
        for _, wave in ipairs(waves) do wave.node.Position = UDim2.fromOffset(wave.column * 12, 4 + wave.layer * 3 + math.sin(wave.column * 0.43 + clock * 1.8) * 2) end
        shark.Position = UDim2.fromOffset((clock * 17 + 95) % 270 - 48, 1 + math.floor(math.sin(clock * 2)))
        if panel.Visible then
            gradient.Rotation = 35 + math.sin(clock * 0.2) * 20
            if appearance.Particles then for i, dot in ipairs(particles) do dot.Position = UDim2.fromScale((i * 0.173 + math.sin(clock * 0.1 + i) * 0.025) % 1, 1 - ((clock * 0.018 + i * 0.16) % 1)) end end
        end
    end))
    setShown(true)
end
installCompactTheme()
do
    state.HoldForJoin = resume and resume.HoldForJoin == true
    local bridge = {
        State = state, Player = player, Gui = gui, Panel = panel,
        Alive = function() return alive end,
        SetFly = setFlying, SetNoclip = setNoclip,
        SetESP = function(value) visible = value end,
        GetESP = function() return visible end,
        Scan = scan, Teleport = teleportTo, LandingPosition = landingPositionAt,
        ReleaseFarmHold = function() stopHidden(false) end,
        Retained = retained.Advanced,
    }
    local install = (function()
return function(B)
    local Http = game:GetService("HttpService")
    local A = {Alive = true, Features = {}, Order = {}, Connections = {}, Cleanups = {}, Workers = {}, Errors = {}, Status = "ready", Favorites = {}, Binds = {}, Options = {}, Metrics = {}}
    B.State.Advanced = A
    local userId = B.Player and B.Player.UserId
    local settingsFile = userId and ("sharkwow-standout-modules-" .. userId .. ".json") or "sharkwow-standout-modules.json"
    A.SettingsFile = settingsFile
    A.SettingsReady = false
    A.FeatureStates = {}
    local settingDepth = 0
    local saved = B.Retained
    if not saved and type(readfile) == "function" then
        for _, path in ipairs({settingsFile, settingsFile .. ".bak", "sharkwow-standout-modules.json"}) do
            local ok, data = pcall(function() return Http:JSONDecode(readfile(path)) end)
            if ok and type(data) == "table" and data.Schema == 1 and type(data.Options) == "table"
                and (data.UserId == nil or data.UserId == userId) then saved = data; break end
        end
    end
    if type(saved) == "table" then
        A.Favorites = type(saved.Favorites) == "table" and saved.Favorites or {}
        A.Binds = type(saved.Binds) == "table" and saved.Binds or {}
        A.Options = type(saved.Options) == "table" and saved.Options or {}
        for id, enabled in pairs(type(saved.FeatureStates) == "table" and saved.FeatureStates or {}) do
            if type(id) == "string" and type(enabled) == "boolean" then A.FeatureStates[id] = enabled end
        end
    end
    function A.Current() return A.Alive and B.Alive() and B.State.Advanced == A end
    function A.Error(name, message)
        A.Errors[name] = tostring(message):sub(1, 180)
        A.Status = name .. ": " .. A.Errors[name]
    end
    function A.Snapshot()
        local options=table.clone(A.Options)
        if options.Webhook then options.Webhook=table.clone(options.Webhook);options.Webhook.URL="" end
        local states = table.clone(A.FeatureStates)
        states.Webhook = false -- The destination remains session-only.
        return {Schema = 1, UserId = userId, PersistenceVersion = 1, FeatureStates = states, Favorites = A.Favorites, Binds = A.Binds, Options = options}
    end
    function A.Save()
        if not A.Alive or not A.SettingsReady or A.RestoringSettings or settingDepth > 0 then return true end
        if type(writefile) ~= "function" then return false, "file storage unavailable" end
        local ok, err = pcall(function()
            local encoded = Http:JSONEncode(A.Snapshot())
            if type(readfile) == "function" then
                local valid, previous = pcall(function()
                    local text = readfile(settingsFile)
                    local data = Http:JSONDecode(text)
                    assert(type(data) == "table" and data.Schema == 1 and data.UserId == userId and type(data.Options) == "table")
                    return text
                end)
                if valid then writefile(settingsFile .. ".bak", previous) end
            end
            writefile(settingsFile, encoded)
            if type(readfile) == "function" then assert(readfile(settingsFile) == encoded, "settings readback mismatch") end
        end)
        A.SettingsStatus = ok and "saved automatically" or "save failed"
        if not ok then A.Error("settings", err) else A.Errors.settings = nil end
        return ok, err
    end
    function A.Connect(signal, callback)
        local c = signal:Connect(function(...) if A.Current() then callback(...) end end)
        A.Connections[#A.Connections + 1] = c
        return c
    end
    function A.Loop(name, period, callback)
        A.Workers[name] = task.spawn(function()
            while A.Current() do
                if not A.SettingsReady then task.wait(0.1); continue end
                if (B.Player:GetAttribute("TrainRaidActive")==true or B.State.RaidBusy) and not ({["auto raid"]=true,["raid autopilot"]=true,["raid cycle"]=true,["auto health"]=true,["module ui"]=true,["inventory report"]=true,["server info"]=true,["notifications"]=true,["server safety"]=true,["session recovery"]=true})[name] then task.wait(period);continue end
                if B.State.PhoneBusy and not ({["phone quest"]=true,["esp"]=true,["player roster"]=true,["module ui"]=true,["notifications"]=true,["inventory report"]=true,["server info"]=true,["server safety"]=true,["session recovery"]=true})[name] then task.wait(period);continue end
                local ok, err = pcall(callback)
                if not ok then A.Error(name, err) end
                task.wait(ok and period or math.max(2, period))
            end
        end)
    end
    function A.Add(feature)
        assert(not A.Features[feature.Id], "duplicate feature: " .. feature.Id)
        feature.Enabled = false
        feature.Description = feature.Description or ""
        feature.Fields = feature.Fields or {}
        A.Features[feature.Id] = feature
        A.Order[#A.Order + 1] = feature.Id
        local options = A.Options[feature.Id]
        if type(options) ~= "table" then options = {}; A.Options[feature.Id] = options end
        for _, field in ipairs(feature.Fields) do
            local value = options[field.Key]
            local valid = type(value) == type(field.Default)
            if field.Min then valid = valid and value == value and math.abs(value) < math.huge and value >= field.Min and value <= field.Max end
            if field.Choices then valid = valid and table.find(field.Choices, value) ~= nil end
            if not valid then options[field.Key] = field.Default end
        end
        return feature
    end
    function A.Get(id)
        local f = A.Features[id]
        if not f then return false end
        if f.Get then return f.Get() end
        return f.Enabled
    end
    function A.Set(id, enabled)
        local f = assert(A.Features[id], "unknown feature")
        if f.Locked then return false, "always enabled while hub runs" end
        enabled = enabled == true
        local before = settingDepth == 0 and table.clone(A.FeatureStates) or nil
        settingDepth += 1
        local old = f.Enabled
        f.Enabled = enabled
        local ok, err = pcall(function() if f.Set then f.Set(enabled) end end)
        settingDepth -= 1
        if not ok then
            if before then A.FeatureStates = before end
            f.Enabled = old; A.Error(id, err); return false, err
        end
        if A.Alive and A.SettingsReady and not A.RestoringSettings then
            A.FeatureStates[id] = id ~= "Webhook" and enabled or false
            if settingDepth == 0 then A.Save() end
        end
        A.Errors[id] = nil
        A.Status = f.Name .. (enabled and " on" or " off")
        if A.Refresh then A.Refresh() end
        return true
    end
    function A.RestoreSettings()
        if A.SettingsReady then return true end
        A.RestoringSettings = true
        local desired = table.clone(A.FeatureStates)
        local paused = B.State.ConfigHoldForJoin or (userId and type(isfile) == "function" and isfile("sharkwow-farm-paused-" .. userId .. ".flag"))
        local farmIds = {AutoPhone=true,FarmAndCraft=true, ArrowFarm=true, Rokaka=true, ArrowPartFarm=true, GardenHarvest=true,
            AutoCraftBizarre=true, FreeArrowMaterials=true, StoneMaskFarm=true, WaitForArrow=true}
        local failed = {}
        local function restore(id)
            local f, value = A.Features[id], desired[id]
            if not f or f.Action or f.Locked or f.HeldForReview then return end
            if paused and farmIds[id] then value = false end
            if id == "Webhook" or id == "AutoRaid" then value = false end
            if type(value) == "boolean" then
                local ok, err = A.Set(id, value)
                if not ok then failed[id] = tostring(err) end
            end
        end
        -- Composite switches run first; individual choices win afterward.
        restore("FarmAndCraft")
        restore("AutoCraftBizarre")
        for _, id in ipairs(A.Order) do
            if id ~= "FarmAndCraft" and id ~= "AutoCraftBizarre" and id ~= "FarmHide" then restore(id) end
        end
        restore("FarmHide") -- Quiet-wait initialization sets the legacy hide flag.
        for _, id in ipairs(A.Order) do
            local f = A.Features[id]
            if not f.Action and not f.Locked and not f.HeldForReview then
                local ok, value = pcall(A.Get, id)
                if ok and type(value) == "boolean" then A.FeatureStates[id] = id ~= "Webhook" and value or false end
            end
        end
        A.RestoringSettings = false
        A.SettingsReady = true
        B.State.PersistenceVersion = 1
        A.SettingsRestoreErrors = failed
        local savedOK, saveError = A.Save()
        if next(failed) then A.Error("settings restore", "some controls could not be restored; check their errors") end
        return savedOK and next(failed) == nil, saveError
    end
    function A.Option(id, key, value)
        local feature = assert(A.Features[id], "unknown feature")
        local field
        for _, candidate in ipairs(feature.Fields) do if candidate.Key == key then field = candidate end end
        assert(field, "unknown setting")
        assert(type(value) == type(field.Default), "invalid setting type")
        if field.Min then assert(value == value and math.abs(value) < math.huge, "invalid number"); value = math.clamp(value, field.Min, field.Max) end
        if field.Choices then assert(table.find(field.Choices, value), "invalid choice") end
        if type(value) == "string" then value = value:sub(1, field.Length or 200) end
        A.Options[id][key] = value
        if feature.Changed then feature.Changed(key, value) end
        A.Save()
    end
    function A.Character()
        local c = B.Player.Character
        local r = c and c:FindFirstChild("HumanoidRootPart")
        local h = c and c:FindFirstChildOfClass("Humanoid")
        if r and h and h.Health > 0 then return c, r, h end
    end
    function A.Native()
        local c = B.Player.Character
        local core = c and c:FindFirstChild("Core")
        local module = core and core:FindFirstChild("PlayerController")
        if not module then return end
        if A.NativeModule ~= module then A.Controller = require(module); A.NativeModule = module end
        return A.Controller
    end
    function A.GardenBusy()
        local g = getgenv().MT_RokakaGardenRun
        return g and g.Alive and g.Busy == true
    end
    function A.MovementFree()
        return not (B.State.PhoneBusy or B.State.Flying or B.State.TeleportBusy or B.State.TransferPending or B.State.AutoBusy or B.State.RouteBusy or B.State.CraftBusy or B.State.AutoHopPause or B.State.HopBusy or A.GardenBusy())
    end
    function A.Stop()
        if not A.Alive then return end
        A.Save()
        A.Alive = false
        local gardener = getgenv().MT_RokakaGardenRun
        if gardener and gardener.Hub == B.State and gardener.Alive then gardener.Stop() end
        B.State.ExtensionPause = false
        for _, c in ipairs(A.Connections) do c:Disconnect() end
        for _, fn in ipairs(A.Cleanups) do local ok, err = pcall(fn); if not ok then A.Error("cleanup", err) end end
        for _, worker in pairs(A.Workers) do if coroutine.status(worker) ~= "dead" then pcall(task.cancel, worker) end end
        table.clear(A.Connections)
    end
    A.Add({Id="ArrowFarm", Name="arrow farm", Group="farm", Description="Original fast teleport farm. Collects every arrow type. No slow travel.", Get=function() return B.State.AutoArrow end, Set=function(v) B.State.SetAuto("arrow",v) end})
    A.Add({Id="Rokaka", Name="rokaka pickup", Group="farm", Description="Original collectible-only search. Other players' gardens are excluded.", Get=function() return B.State.AutoRokaka end, Set=function(v) B.State.SetAuto("rokaka",v) end})
    A.Add({Id="GardenHarvest", Name="auto grow + harvest rokaka", Group="farm", Description="Collects available Rokaka Seeds when needed, plants in your own pot, and harvests ripe fruit. Item farming continues while plants grow. Planting and harvesting briefly own movement. Enable rokaka pickup for repeated cycles.",Get=function() local g=getgenv().MT_RokakaGardenRun;return g and g.Alive or false end,Set=function(v)
        local g=getgenv().MT_RokakaGardenRun
        if v then if not g or not g.Alive then assert(B.State.StartGarden,"garden helper unavailable")() end
        elseif g and g.Alive then g.Stop() end
    end})
    A.Add({Id="FarmHide", Name="farm position", Group="farm", Description="Keeps the existing pickup position underneath the item.", Get=function() return B.State.FarmHide end, Set=B.State.SetFarmHide})
    A.Add({Id="AntiAFK", Name="anti-afk", Group="utility", Locked=true, Get=function() return true end, Description="Owned keepalive stays active with the UI hidden. Explicit unload cleans it up."})
    return A
end

    end)()
    local advanced = install(bridge);
    state.ConfigHoldForJoin = resume and resume.HoldForJoin == true or false
    (function(A, B)
B.State.Device=deviceReport
A.Device=deviceReport
A.ActivateNativeButton=function(button)
    return DevicePolicy.activate(button,getconnections,firesignal,task.spawn)
end

    end)(advanced, bridge);
    (function(A, B)
local UIS = game:GetService("UserInputService")
local Run = game:GetService("RunService")
local function toggle(id, name, description, fields)
    return A.Add({Id=id,Name=name,Group="move",Description=description,Fields=fields})
end
A.Add({Id="Fly",Name="fly",Group="move",Description="Original flight. WASD, space up, control down. Touch buttons stay in quick view.",Fields={{Key="Speed",Name="speed",Default=B.State.FlySpeed,Min=10,Max=200}},Get=function() return B.State.Flying end,Set=B.SetFly,Changed=function(_,v) B.State.SetFlySpeed(v) end})
A.Add({Id="Noclip",Name="noclip",Group="move",Description="Original collision control. Restores collision on disable.",Get=function() return B.State.Noclip end,Set=B.SetNoclip})
A.Add({Id="NoFall",Name="no fall damage / slow descent",Group="move",Description="Existing fall brake. Slows descent; does not promise damage immunity at full speed.",Get=function() return B.State.NoFall end,Set=function(v) B.State.SetNoFall(v) end})
toggle("Speed","speed","Adds movement at the selected speed. Pauses during farming, flight and garden work.",{{Key="Speed",Name="studs / second",Default=40,Min=16,Max=150}})
toggle("InfiniteJump","infinite jump","Jump again in midair. Pauses during flight and gardening.")
toggle("JumpPower","jump power","Changes local jump strength and restores it when disabled.",{{Key="Power",Name="jump power",Default=65,Min=20,Max=180}})
toggle("ClickTeleport","click teleport","Hold left control and click a supported surface. Refuses moving targets and void landings.")
toggle("AntiVoid","anti-void","Returns to the last supported position before the destruction plane.")
toggle("NoDashCooldown","dash cooldown override","Clears local dash cooldown flags. Server cooldowns and movement checks can still apply.")
toggle("DashExtender","dash extender","Adds a bounded extra distance during a native dash. Pauses during item and garden operations.",{{Key="Distance",Name="extra studs per dash",Default=6,Min=1,Max=25}})
toggle("NoStun","local stun recovery","Clears the client movement stun flag. Server damage and action restrictions remain authoritative.")
toggle("NoRagdoll","local ragdoll recovery","Disables local humanoid ragdoll states. Restores their previous availability on disable; server constraints may still hold the body.")
local jumpOriginal = setmetatable({}, {__mode="k"})
local ragdollOriginal=setmetatable({},{__mode="k"})
local function restoreRagdoll()
    for h,states in pairs(ragdollOriginal) do if h.Parent then for state,value in pairs(states) do h:SetStateEnabled(state,value) end end end
    table.clear(ragdollOriginal)
end
A.Features.NoRagdoll.Set=function(v) if not v then restoreRagdoll() end end
A.Cleanups[#A.Cleanups+1]=restoreRagdoll
local dashExtra,dashWas=0,false
local lastSafe, lastCharacter, lastJump = nil, nil, 0
local function restoreJump()
    for h,v in pairs(jumpOriginal) do if h.Parent then h.JumpPower=v.Power; h.JumpHeight=v.Height end end
    table.clear(jumpOriginal)
end
A.Features.JumpPower.Set=function(v) if not v then restoreJump() end end
A.Cleanups[#A.Cleanups+1]=restoreJump
A.Connect(UIS.JumpRequest,function()
    if not A.Get("InfiniteJump") or B.State.Flying or A.GardenBusy() or os.clock()-lastJump<0.15 then return end
    local _,_,h=A.Character()
    if h then lastJump=os.clock(); h:ChangeState(Enum.HumanoidStateType.Jumping) end
end)
A.Connect(UIS.InputBegan,function(input,processed)
    if processed or UIS:GetFocusedTextBox() or not A.Get("ClickTeleport") then return end
    if input.UserInputType~=Enum.UserInputType.MouseButton1 or not UIS:IsKeyDown(Enum.KeyCode.LeftControl) or not A.MovementFree() then return end
    local mouse=B.Player:GetMouse()
    local c,r,h=A.Character()
    if not c or not mouse.Target or not mouse.Target.Anchored then return end
    local params=RaycastParams.new(); params.FilterType=Enum.RaycastFilterType.Exclude; params.FilterDescendantsInstances={c}
    local point=mouse.Hit.Position
    local hit=workspace:Raycast(point+Vector3.new(0,6,0),Vector3.new(0,-12,0),params)
    if hit and hit.Normal.Y>0.55 then
        r.AssemblyLinearVelocity=Vector3.zero
        c:PivotTo(CFrame.new(hit.Position+Vector3.new(0,h.HipHeight+r.Size.Y/2+0.3,0))*c:GetPivot().Rotation)
        A.Metrics.ClickTeleports=(A.Metrics.ClickTeleports or 0)+1
    end
end)
A.Connect(Run.Heartbeat,function(dt)
    local c,r,h=A.Character()
    if not c then return end
    if lastCharacter~=c then lastCharacter=c; lastSafe=nil end
    if A.Get("NoDashCooldown") or A.Get("DashExtender") or A.Get("NoStun") then
        local n=A.Native()
        if n then
            local s=n:getStates()
            if A.Get("NoDashCooldown") then s.DashCooldown=false;s.GlobalDashCD=false end
            if A.Get("NoStun") and not A.GardenBusy() then s.Stunned=false end
            if not s.Dashing then dashExtra=0 end
            if A.Get("DashExtender") and s.Dashing and A.MovementFree() and not B.State.ExtensionPause then
                if not dashWas then dashExtra=0 end
                local velocity=Vector3.new(r.AssemblyLinearVelocity.X,0,r.AssemblyLinearVelocity.Z)
                if velocity.Magnitude>1 then
                    local distance=math.min(A.Options.DashExtender.Distance-dashExtra,math.min(dt,0.05)*35)
                    if distance>0 then r.CFrame+=velocity.Unit*distance;dashExtra+=distance end
                end
            end
            dashWas=s.Dashing==true
        end
    end
    if A.Get("NoRagdoll") then
        if not ragdollOriginal[h] then
            ragdollOriginal[h]={}
            for _,s in ipairs({Enum.HumanoidStateType.Ragdoll,Enum.HumanoidStateType.FallingDown}) do ragdollOriginal[h][s]=h:GetStateEnabled(s);h:SetStateEnabled(s,false) end
        end
        if not A.GardenBusy() and not B.State.Flying and (h:GetState()==Enum.HumanoidStateType.Ragdoll or h:GetState()==Enum.HumanoidStateType.FallingDown) then h:ChangeState(Enum.HumanoidStateType.GettingUp) end
    end
    if A.Get("JumpPower") then
        if not jumpOriginal[h] then jumpOriginal[h]={Power=h.JumpPower,Height=h.JumpHeight} end
        local power=A.Options.JumpPower.Power
        h.JumpPower=power; h.JumpHeight=power*power/(2*workspace.Gravity)
    end
    if A.Get("Speed") and A.MovementFree() and not B.State.ExtensionPause and h.MoveDirection.Magnitude>0.05 and not h.Sit then
        r.CFrame += h.MoveDirection*math.max(0,A.Options.Speed.Speed-h.WalkSpeed)*math.min(dt,0.05)
    end
    if A.Get("AntiVoid") then
        if not B.State.FarmHideActive and h.FloorMaterial~=Enum.Material.Air and r.Position.Y>workspace.FallenPartsDestroyHeight+80 then lastSafe=c:GetPivot() end
        if r.Position.Y<workspace.FallenPartsDestroyHeight+60 and lastSafe then
            r.AssemblyLinearVelocity=Vector3.zero; c:PivotTo(lastSafe+Vector3.new(0,3,0))
            A.Metrics.VoidRecoveries=(A.Metrics.VoidRecoveries or 0)+1
        end
    end
end)

    end)(advanced, bridge);
    (function(A, B)
local Players=game:GetService("Players")
local function field(key,name,value,min,max) return {Key=key,Name=name,Default=value,Min=min,Max=max} end
local mobFields={
    {Key="Targets",Name="mob names (comma separated)",Default="",Length=300},
    {Key="Pick",Name="pick first",Default="closest",Choices={"closest","lowest health"}},
    field("Radius","search radius",1500,20,5000),field("Timeout","give up after seconds",30,5,180),
    {Key="Position",Name="position",Default="behind",Choices={"behind","above","front"}},
    field("Distance","distance",3,2,12),field("Height","height offset",0,-3,8),
    {Key="M1",Name="light attacks",Default=true},
    {Key="Skills",Name="use skills",Default=true},{Key="Summon",Name="summon stand",Default=true},
    field("Health","pause below health %",25,5,90),{Key="Bosses",Name="include unclaimed bosses",Default=false},
}
A.Add({Id="AutoFarm",Name="mob farm",Group="farm",Description="Fast positioning with native attacks. Arrow pickup and garden harvest take priority. Choose targets explicitly.",Fields=mobFields})
A.Add({Id="AutoSummon",Name="auto summon",Group="combat",Description="Summons the current stand through the native controller."})
A.Add({Id="AutoSkills",Name="auto skills",Group="combat",Description="Uses available skill slots against the selected nearby mob. Respects native cooldowns.",Fields={field("Range","target range",18,3,80)}})
local defense={field("Range","detect range",14,4,40),field("Ahead","look ahead studs",8,0,20),{Key="Facing",Name="only attacks facing me",Default=true},{Key="Players",Name="include players",Default=false},field("Hold","guard hold seconds",0.18,0.08,0.8)}
A.Add({Id="AutoParry",Name="auto parry",Group="combat",Description="Detects nearby attack starts and briefly guards. Timing varies with ping and attack type.",Fields=defense})
A.Add({Id="AutoBlock",Name="auto block",Group="combat",Description="Holds native guard while a nearby attacker swings.",Fields={field("Range","detect range",14,4,40)}})
A.Add({Id="AutoDash",Name="auto dash",Group="combat",Description="Requests a native dash when a nearby heavy attack begins.",Fields={field("Range","detect range",12,4,30)}})
A.Add({Id="AutoSprint",Name="auto sprint",Group="combat",Description="Uses the game's running controller while moving."})
A.Add({Id="IgnoreFriends",Name="ignore friends",Group="combat",Description="Excludes friends from optional player defense detection."})
A.Features.IgnoreFriends.Enabled=true
local friendCache={}
local function friendly(p)
    if not A.Get("IgnoreFriends") then return false end
    if friendCache[p.UserId]==nil then
        friendCache[p.UserId]=true
        task.spawn(function() local ok,v=pcall(B.Player.IsFriendsWith,B.Player,p.UserId); if ok and A.Current() then friendCache[p.UserId]=v end end)
    end
    return friendCache[p.UserId]
end
local function allowed(m, bosses)
    if m==B.Player.Character or Players:GetPlayerFromCharacter(m) then return false end
    local h=m:FindFirstChildOfClass("Humanoid")
    local r=m:FindFirstChild("HumanoidRootPart")
    if not h or h.Health<=0 or not r or m:GetAttribute("FightableNPC")~=true then return false end
    local owner=m:GetAttribute("StoryOwnerUserId") or m:GetAttribute("OwnerUserId")
    if owner and owner~=0 and owner~=B.Player.UserId then return false end
    if m:GetAttribute("BossNPC") and not bosses then return false end
    local target=m:GetAttribute("Target")
    if target and target~="" and target~=B.Player.Name then return false end
    return true
end
function A.Mobs()
    local names,seen={},{}
    for _,m in ipairs(workspace.Game.Players:GetChildren()) do
        if allowed(m,true) then local name=m:GetAttribute("Config") or m.Name; if not seen[name] then names[#names+1]=name;seen[name]=true end end
    end
    table.sort(names);return names
end
local function matches(name,text)
    for token in text:lower():gmatch("[^,]+") do
        token=token:match("^%s*(.-)%s*$")
        if token~="" and (token==name:lower() or token=="all") then return true end
    end
    return false
end
A.MatchTarget=matches
local ignored=setmetatable({},{__mode="k"})
local target,started,lightAt=nil,0,0
local blocked=false
local function releaseBlock()
    if blocked then
        local n=A.Native(); if n then local s=n:getStates(); s.HoldingBlock=false; n:blockStop() end
        blocked=false
    end
end
A.Cleanups[#A.Cleanups+1]=releaseBlock
local installSkills=(function()
return function(A,B)
    local cachedNative,cached,lastSlot,readyAt=nil,nil,0,0
    local held
    local function adapter(n)
        if n==cachedNative then return cached end
        local result={}
        for _,v in pairs(debug.getupvalues(n.processSkillInputQueue))do
            if type(v)=="function" and debug.info(v,"n")=="useSkill"then result.Invoke=v;break end
        end
        assert(result.Invoke,"native skill input unavailable")
        for _,v in pairs(debug.getupvalues(result.Invoke))do
            if type(v)=="function" and debug.info(v,"n")=="getSkillMouseHit"then result.MouseHit=v
            elseif type(v)=="table"then
                if type(v.sendCombat)=="function"then result.Combat=v end
                if type(v.getClosestMouse)=="function"then result.Utility=v end
            end
        end
        assert(result.MouseHit and result.Combat and result.Utility,"native skill release unavailable")
        cachedNative=n;cached=result
        return result
    end
    local function release(owner)
        local record=held
        if not record or (owner and record.Owner~=owner)then return end
        held=nil
        if record.Thread and record.Thread~=coroutine.running()then pcall(task.cancel,record.Thread)end
        if B.Player.Character~=record.Character then return end
        local good,err=pcall(function()
            local n,api,s=record.Native,record.API,record.Native:getStates()
            s.HoldingSkill=false
            if n:releaseAimInput(record.Name,false) or n:releaseGrappleInput(record.Name)then return end
            local hit,extra=api.MouseHit(record.Name)
            local closest=api.Utility:getClosestMouse(record.Character,B.Player:GetMouse(),workspace.CurrentCamera)
            if record.Name=="Super Leap"then closest[8]=extra end
            api.Combat.sendCombat("ReleasedSkill",record.Name,hit,s.Shiftlocked,closest,s)
        end)
        if not good then A.Error("skill release",err)end
    end
    A.ReleaseFarmSkill=release
    A.Cleanups[#A.Cleanups+1]=function()release()end
    function A.UseSkill(n,owner,allowedNames)
        if held or os.clock()<readyAt or B.Player.Data.SkillActive.Value then return false end
        local s=n:getStates()
        if s.Stunned or s.Blocking or s.Swinging or s.HeavySwinging then return false end
        local api=adapter(n)
        local slots=B.Player.Data.Skills:GetChildren()
        table.sort(slots,function(x,y)return x.Name<y.Name end)
        if #slots==0 then return false end
        for offset=1,#slots do
            local index=(lastSlot+offset-1)%#slots+1
            local slot=slots[index]
            if slot:IsA("StringValue") and slot.Value~="" and (not allowedNames or allowedNames[slot.Value])and not slot:GetAttribute("OnCooldown")
                and not slot:GetAttribute("InUse") and not (s.OnCooldown or {})[slot.Value]then
                readyAt=os.clock()+.8
                local record={Native=n,API=api,Character=B.Player.Character,Name=slot.Value,Owner=owner or "mob"}
                held=record
                local ok,result=pcall(api.Invoke,slot.Name,nil,nil)
                if not ok then release();error(result)end
                if result then
                    lastSlot=index
                    A.Metrics.SkillRequests=(A.Metrics.SkillRequests or 0)+1
                    B.State.LastFarmSkill={Name=slot.Value,At=os.clock(),Owner=record.Owner}
                    -- Native keyboard input releases its hold after at most 1.25 seconds.
                    record.Thread=task.delay(1.25,function()if held==record then release(record.Owner)end end)
                    return true
                end
                held=nil
            end
        end
        return false
    end
end

end)()
installSkills(A,B)
A.Features.AutoFarm.Set=function(v) if not v then A.ReleaseFarmSkill("mob");target=nil;B.State.ExtensionPause=false;A.FarmTarget=nil end end
local function choose(root,opts)
    local best,score=nil,math.huge
    for _,m in ipairs(workspace.Game.Players:GetChildren()) do
        if allowed(m,opts.Bosses) and (ignored[m] or 0)<os.clock() and matches(tostring(m:GetAttribute("Config") or m.Name),opts.Targets) then
            local r=m.HumanoidRootPart;local distance=(root.Position-r.Position).Magnitude
            local rank=opts.Pick=="lowest health" and m.Humanoid.Health or distance
            if distance<=opts.Radius and rank<score then best,score=m,rank end
        end
    end
    return best
end
local preferBasic=false
local ownsMobPause=false
local function releaseMobPause()
    if ownsMobPause then
        ownsMobPause=false
        if not (B.State.CraftBusy or B.State.MaterialBusy or B.State.PhoneBusy) then B.State.ExtensionPause=false end
    end
end
A.Cleanups[#A.Cleanups+1]=releaseMobPause
A.Loop("mob farm",0.12,function()
    local enabled=A.Get("AutoFarm")
    local c,r,h=A.Character()
    local opts=A.Options.AutoFarm
    if not enabled or not c or A.GardenBusy() or B.State.TransferPending or B.State.Flying or B.State.CraftBusy or B.State.MaterialBusy then releaseMobPause();return end
    if opts.Targets:match("^%s*$") then A.Status="choose mob names in farm settings";releaseMobPause();return end
    if h.Health/h.MaxHealth*100<opts.Health then A.Status="mob farm paused: low health";releaseMobPause();return end
    if (B.State.HasPriorityItems and B.State.HasPriorityItems()) or (B.State.AutoArrow and B.State.Arrow>0) or (B.State.AutoRokaka and B.State.Rokaka>0) then releaseMobPause();return end
    if target and (not target.Parent or not allowed(target,opts.Bosses) or os.clock()-started>opts.Timeout) then
        if target.Parent and target:FindFirstChildOfClass("Humanoid") and target.Humanoid.Health<=0 then A.Metrics.Kills=(A.Metrics.Kills or 0)+1 else ignored[target]=os.clock()+10 end
        target=nil
    end
    if not target then target=choose(r,opts);started=os.clock() end
    A.FarmTarget=target
    if not target then releaseMobPause();A.Status="waiting for selected mobs";return end
    if not A.MovementFree() then return end
    B.State.ExtensionPause=true;ownsMobPause=true
    local tr=target.HumanoidRootPart
    local offset=opts.Position=="above" and Vector3.new(0,opts.Distance+opts.Height,0) or Vector3.new(0,opts.Height,opts.Position=="front" and -opts.Distance or opts.Distance)
    local point=tr.CFrame:PointToWorldSpace(offset)
    r.AssemblyLinearVelocity=Vector3.zero
    c:PivotTo(CFrame.lookAt(point,tr.Position+Vector3.new(0,opts.Height,0)))
    local n=A.Native();if not n then return end
    local s=n:getStates()
    if opts.Summon and not s.Summoned then n:summonStand(true);return end
    A.Status="farming "..tostring(target:GetAttribute("Config") or target.Name)
    if B.Player.Data.SkillActive.Value then return end
    if opts.Skills and (not opts.M1 or not preferBasic) and (not A.IsFeatureAvailable or A.IsFeatureAvailable("AutoSkills")) and A.UseSkill(n,"mob") then preferBasic=true;return end
    if opts.M1 and os.clock()>lightAt and not (s.Swinging or s.HeavySwinging or s.Stunned or s.Blocking) then
        lightAt=os.clock()+0.45;preferBasic=false
        task.spawn(function() if A.Current() and A.Get("AutoFarm") and A.Options.AutoFarm.M1 and not B.Player.Data.SkillActive.Value then n:lightSwing() end end)
    end
end)
local summonAt,sprintAt,parryUntil,dashAt=0,0,0,0
local attacks=setmetatable({},{__mode="k"})
A.Loop("combat assist",0.08,function()
    if not (A.Get("AutoSummon") or A.Get("AutoSprint") or A.Get("AutoParry") or A.Get("AutoBlock") or A.Get("AutoDash") or A.Get("AutoSkills")) then releaseBlock();return end
    local c,r,h=A.Character();if not c or A.GardenBusy() then releaseBlock();return end
    local n=A.Native();if not n then return end
    local s=n:getStates(); local now=os.clock()
    if A.Get("AutoSummon") and not s.Summoned and now>summonAt then summonAt=now+2;n:summonStand(true) end
    if A.Get("AutoSprint") and h.MoveDirection.Magnitude>0.05 and now>sprintAt and not B.State.Flying then sprintAt=now+0.5;n:runStart() end
    if A.Get("AutoSkills") and not A.Get("AutoFarm") and A.FarmTarget and A.FarmTarget.Parent and (A.FarmTarget.HumanoidRootPart.Position-r.Position).Magnitude<=A.Options.AutoSkills.Range then A.UseSkill(n) end
    local needBlock=false
    local opts=A.Options.AutoParry
    for _,m in ipairs(workspace.Game.Players:GetChildren()) do
        local other=Players:GetPlayerFromCharacter(m)
        local mr=m:FindFirstChild("HumanoidRootPart")
        local mh=m:FindFirstChildOfClass("Humanoid")
        local swinging=m:GetAttribute("Swinging") or m:GetAttribute("HeavySwinging") or m:GetAttribute("HitEnabled")
        if m~=c and mr and mh and mh.Health>0 and (not other or opts.Players and not friendly(other)) then
            local distance=(mr.Position-r.Position).Magnitude
            local delta=r.Position-mr.Position
            local facing=delta.Magnitude<0.1 or mr.CFrame.LookVector:Dot(delta.Unit)>0.1
            local predicted=(mr.Position+mr.AssemblyLinearVelocity*0.1-r.Position).Magnitude
            if swinging and (not opts.Facing or facing) then
                if A.Get("AutoParry") and not attacks[m] and distance<=opts.Range and predicted<=opts.Range+opts.Ahead then
                    parryUntil=now+opts.Hold; A.Metrics.ParryAttempts=(A.Metrics.ParryAttempts or 0)+1
                end
                if A.Get("AutoBlock") and distance<=A.Options.AutoBlock.Range then needBlock=true end
                if A.Get("AutoDash") and m:GetAttribute("HeavySwinging") and distance<=A.Options.AutoDash.Range and now>dashAt then dashAt=now+1.2;task.spawn(function() if A.Current() then n:startDash() end end) end
            end
        end
        attacks[m]=swinging==true
    end
    needBlock=needBlock or now<parryUntil
    if needBlock and not blocked then s.HoldingBlock=true;n:blockStart();blocked=true
    elseif not needBlock then releaseBlock() end
end)

    end)(advanced, bridge);
    (function(A, B)
local RS=game:GetService("ReplicatedStorage")
local Http=game:GetService("HttpService")
local definitions=require(RS.Modules.Stands).stands
A.Add({Id="AutoPilot",Name="auto pilot",Group="combat",Description="Keeps native pilot mode active for compatible stands. Pauses while item or garden farming owns movement."})
A.Add({Id="PilotRange",Name="extended pilot range",Group="combat",Description="Extends the local pilot limit. Server range enforcement can still apply.",Fields={{Key="Range",Name="pilot range studs",Default=4000,Min=50,Max=100000}}})
A.Add({Id="AttachStand",Name="attach stand to target",Group="combat",Description="Positions your piloted stand beside the selected mob. Requires a compatible stand and a mob-farm target.",Fields={{Key="Distance",Name="behind target studs",Default=3,Min=2,Max=10}}})
local originalDefinitions=setmetatable({},{__mode="k"})
local originalModels=setmetatable({},{__mode="k"})
local pilotOwned=false
local function restoreRange()
    for def,v in pairs(originalDefinitions) do if def.PilotRange==v.Applied then def.PilotRange=v.Original end end
    for model,v in pairs(originalModels) do if model.Parent and model:GetAttribute("PilotRange")==v.Applied then model:SetAttribute("PilotRange",v.Original) end end
    table.clear(originalDefinitions);table.clear(originalModels)
end
A.Features.PilotRange.Set=function(v) if not v then restoreRange() end end
A.Features.AutoPilot.Set=function(v)
    if not v and pilotOwned then local n=A.Native();if n then n:pilot(false) end;pilotOwned=false end
end
A.Cleanups[#A.Cleanups+1]=function() restoreRange();if pilotOwned then local n=A.Native();if n then n:pilot(false) end end end
local pilotAt=0
A.Loop("stand control",0.2,function()
    local name=B.Player.Data.Stand.Value
    local def=definitions[name]
    if not def or not def.Pilot then return end
    local model=workspace.Game.Stands:FindFirstChild(B.Player.Name)
    if A.Get("PilotRange") then
        local range=A.Options.PilotRange.Range
        if not originalDefinitions[def] then originalDefinitions[def]={Original=def.PilotRange} end
        originalDefinitions[def].Applied=range;def.PilotRange=range
        if model then
            if not originalModels[model] then originalModels[model]={Original=model:GetAttribute("PilotRange")} end
            originalModels[model].Applied=range;model:SetAttribute("PilotRange",range)
        end
    end
    if not (A.Get("AutoPilot") or A.Get("AttachStand")) then return end
    local n=A.Native();if not n then return end
    local s=n:getStates()
    if A.Get("AutoPilot") and not s.Piloting and A.MovementFree() and not B.State.AutoArrow and not B.State.AutoRokaka and os.clock()>pilotAt then
        pilotAt=os.clock()+2
        if not s.Summoned then n:summonStand(true) else n:pilot(true);pilotOwned=true end
    end
    if A.Get("AttachStand") and s.Piloting and model and A.FarmTarget and A.FarmTarget.Parent and not A.GardenBusy() then
        local root=A.FarmTarget:FindFirstChild("HumanoidRootPart")
        if root then model:PivotTo(root.CFrame*CFrame.new(0,0,A.Options.AttachStand.Distance)) end
    end
end)
A.Add({Id="AutoRoll",Name="auto roll",Group="farm",Description="Consumes selected arrows until a desired stand appears or the roll limit is reached. Replacing your current stand must be enabled explicitly. Never starts from a saved profile.",Fields={
    {Key="Wanted",Name="wanted stands, comma separated",Default="",Length=600},
    {Key="Arrow",Name="arrow to use",Default="Mysterious Arrow",Choices={"Mysterious Arrow","Lucky Arrow","Bizarre Arrow","Mysterious Arrow [Part 3]","Mysterious Arrow [Part 5]"}},
    {Key="Limit",Name="maximum arrows this run",Default=1,Min=1,Max=100},
    {Key="Replace",Name="allow replacing current stand",Default=false},
}})
local rollCount=0
local pending=nil
local rollAt=0
local function inventoryItem(name)
    local items=Http:JSONDecode(B.Player.Data.Stats.Inventory.Value)
    for _,item in ipairs(items) do
        if type(item)=="table" and item.Name==name and (item.Amount or 1)>0 then return item end
        if item==name then return {Name=name,Amount=1} end
    end
end
local function validTargets(text)
    local found=false
    for token in text:gmatch("[^,]+") do
        token=token:match("^%s*(.-)%s*$")
        local match=false
        for name in pairs(definitions) do if name:lower()==token:lower() then match=true;break end end
        if not match then return false end
        found=true
    end
    return found
end
A.ValidRollTargets=validTargets
A.Features.AutoRoll.Set=function(v)
    if not v then return end
    local opts=A.Options.AutoRoll
    assert(validTargets(opts.Wanted),"enter exact desired stand names first")
    assert(B.Player.Data.Stand.Value=="" or opts.Replace,"enable allow replacing current stand first")
    assert(not pending,"previous roll outcome still pending")
    rollCount=0
end
A.Loop("auto roll",0.4,function()
    local current=B.Player.Data.Stand.Value
    if pending then
        local c=B.Player.Character
        local count=B.State.InventoryCounts[pending.Name] or 0
        if c and not c:GetAttribute("ArrowUseToken") and os.clock()-pending.At>2 and count<pending.Before then
            rollCount+=1;A.Metrics.Rolls=(A.Metrics.Rolls or 0)+1
            if A.Notify then A.Notify("Stand","arrow roll completed: "..current) end
            pending=nil;rollAt=os.clock()+2
        elseif os.clock()-pending.At>45 then
            A.Set("AutoRoll",false);A.Error("AutoRoll","roll result not confirmed; reconcile inventory before restarting");return
        else return end
    end
    if not A.Get("AutoRoll") or os.clock()<rollAt then return end
    local opts=A.Options.AutoRoll
    if A.MatchTarget(current,opts.Wanted) then A.Set("AutoRoll",false);A.Status="desired stand obtained: "..current;return end
    if rollCount>=opts.Limit then A.Set("AutoRoll",false);A.Status="arrow roll limit reached";return end
    if current~="" and not opts.Replace then A.Set("AutoRoll",false);return end
    if not A.MovementFree() or A.Get("AutoFarm") or B.State.AutoArrow or B.State.AutoRokaka then A.Status="auto roll waiting for farming to stop";return end
    local c,_,h=A.Character();if not c or h.Health<h.MaxHealth*0.5 or c:GetAttribute("ArrowUseToken") then return end
    local item=inventoryItem(opts.Arrow)
    if not item then A.Set("AutoRoll",false);A.Status="selected arrows unavailable";return end
    pending={Name=item.Name,Before=B.State.InventoryCounts[item.Name] or item.Amount or 1,At=os.clock()}
    RS.Remotes.Item:FireServer("Use",item.Name,item.ID)
end)

    end)(advanced, bridge);
    (function(A, B)
local Players=game:GetService("Players")
local function fields()
    return {{Key="Names",Name="names",Default=true},{Key="Distance",Name="distance",Default=true},{Key="Health",Name="health",Default=true},{Key="HealthBar",Name="health bar",Default=true},{Key="Stand",Name="stand",Default=true},{Key="Summoned",Name="summoned status",Default=false},{Key="Boxes",Name="boxes",Default=false},{Key="Tracers",Name="tracers",Default=false},{Key="Chams",Name="chams",Default=false},{Key="Range",Name="maximum distance",Default=1500,Min=50,Max=6000}}
end
A.Add({Id="ItemESP",Name="item esp",Group="visuals",Description="Original arrow, rokaka fruit and seed markers.",Get=B.GetESP,Set=B.SetESP})
for _,def in ipairs({{"PlayerESP","player esp"},{"MobESP","mob esp"},{"StandESP","stand esp"},{"NPCESP","npc esp"},{"ObjectiveESP","objective esp"}}) do
    A.Add({Id=def[1],Name=def[2],Group="visuals",Description="Markers for loaded objects only. Details can be customized below.",Fields=fields()})
end
A.Add({Id="ESPWidget",Name="inventory widget",Group="visuals",Description="Small live arrow and rokaka inventory count. Drag using the widget title."})
local folder=Instance.new("Folder");folder.Name="AdvancedESP";folder.Parent=B.Gui
local entries={}
local colors={PlayerESP=Color3.fromRGB(0,240,255),MobESP=Color3.fromRGB(255,145,110),StandESP=Color3.fromRGB(168,85,247),NPCESP=Color3.fromRGB(125,225,175),ObjectiveESP=Color3.fromRGB(255,215,110)}
local function destroy(entry) for _,v in pairs(entry) do if typeof(v)=="Instance" then v:Destroy() end end end
local function make(model,root,kind)
    local billboard=Instance.new("BillboardGui");billboard.Name=kind;billboard.Size=UDim2.fromOffset(210,58);billboard.StudsOffsetWorldSpace=Vector3.new(0,3.5,0);billboard.AlwaysOnTop=true;billboard.Adornee=root;billboard.Parent=folder
    local text=Instance.new("TextLabel");text.Size=UDim2.new(1,0,1,-6);text.BackgroundTransparency=1;text.Font=Enum.Font.BuilderSansBold;text.TextSize=13;text.TextColor3=colors[kind];text.TextStrokeTransparency=0.25;text.Parent=billboard
    local back=Instance.new("Frame");back.BorderSizePixel=0;back.BackgroundColor3=Color3.fromRGB(30,30,40);back.Position=UDim2.new(0.2,0,1,-5);back.Size=UDim2.new(0.6,0,0,4);back.Parent=billboard
    local bar=Instance.new("Frame");bar.BorderSizePixel=0;bar.BackgroundColor3=Color3.fromRGB(80,240,155);bar.Size=UDim2.fromScale(1,1);bar.Parent=back
    local highlight=Instance.new("Highlight");highlight.Name="SHARKWOWESP";highlight.Adornee=model;highlight.FillColor=colors[kind];highlight.FillTransparency=0.7;highlight.OutlineColor=colors[kind];highlight.Parent=folder
    local box=Instance.new("BoxHandleAdornment");box.Adornee=root;box.AlwaysOnTop=true;box.ZIndex=1;box.Color3=colors[kind];box.Transparency=0.8;box.Size=Vector3.new(4,6,2);box.Parent=folder
    local line=Instance.new("Frame");line.AnchorPoint=Vector2.new(0.5,0.5);line.BorderSizePixel=0;line.BackgroundColor3=colors[kind];line.Parent=B.Gui;line.Visible=false
    return {Gui=billboard,Text=text,Back=back,Bar=bar,Highlight=highlight,Box=box,Line=line,Root=root,Model=model,Kind=kind}
end
local widget=Instance.new("TextLabel");widget.Name="InventoryWidget";widget.Size=UDim2.fromOffset(200,52);widget.Position=UDim2.fromOffset(20,55);widget.BackgroundColor3=Color3.fromRGB(22,22,37);widget.TextColor3=Color3.fromRGB(243,247,255);widget.Font=Enum.Font.BuilderSansBold;widget.TextSize=14;widget.Visible=false;widget.Active=true;widget.Parent=B.Gui
local corner=Instance.new("UICorner");corner.CornerRadius=UDim.new(0,8);corner.Parent=widget
local dragging,start,origin
A.Connect(widget.InputBegan,function(i) if i.UserInputType==Enum.UserInputType.MouseButton1 or i.UserInputType==Enum.UserInputType.Touch then dragging=i;start=Vector2.new(i.Position.X,i.Position.Y);origin=widget.AbsolutePosition end end)
A.Connect(game:GetService("UserInputService").InputChanged,function(i)
    if dragging and (i==dragging or i.UserInputType==Enum.UserInputType.MouseMovement) then
        local p=origin+Vector2.new(i.Position.X,i.Position.Y)-start;local view=B.Gui.AbsoluteSize
        widget.Position=UDim2.fromOffset(math.clamp(p.X,0,math.max(0,view.X-200)),math.clamp(p.Y,0,math.max(0,view.Y-52)))
    end
end)
A.Connect(game:GetService("UserInputService").InputEnded,function(i) if i==dragging or i.UserInputType==Enum.UserInputType.MouseButton1 then dragging=nil end end)
A.Connect(game:GetService("UserInputService").WindowFocusReleased,function() dragging=nil end)
A.Loop("esp",0.2,function()
    local _,root=A.Character();local seen={};local count=0
    local function add(model,kind)
        if count>=100 or not root or not A.Get(kind) then return end
        local part=model:IsA("BasePart") and model or model:FindFirstChild("HumanoidRootPart") or model:FindFirstChildWhichIsA("BasePart",true)
        if not part then return end
        local opts=A.Options[kind];local distance=(part.Position-root.Position).Magnitude
        if distance>opts.Range then return end
        seen[model]=true;count+=1
        local e=entries[model]
        if e and (e.Kind~=kind or e.Root~=part) then destroy(e);e=nil end
        if not e then e=make(model,part,kind);entries[model]=e end
        local h=model:FindFirstChildOfClass("Humanoid")
        local p=Players:GetPlayerFromCharacter(model)
        local lines={}
        if opts.Names then lines[#lines+1]=p and p.DisplayName or tostring(model:GetAttribute("Config") or model.Name) end
        if opts.Distance then lines[#lines+1]=string.format("%.0f studs",distance) end
        if h and opts.Health then lines[#lines+1]=string.format("hp %.0f / %.0f",h.Health,h.MaxHealth) end
        if p and opts.Stand then local d=p:FindFirstChild("Data");local s=d and d:FindFirstChild("Stand");if s and s.Value~="" then lines[#lines+1]=s.Value end end
        if opts.Summoned then lines[#lines+1]=model:GetAttribute("Summoned") and "summoned" or "not summoned" end
        e.Text.Text=table.concat(lines," | ");e.Text.TextWrapped=true
        e.Back.Visible=opts.HealthBar and h~=nil;e.Bar.Size=UDim2.fromScale(h and math.clamp(h.Health/math.max(1,h.MaxHealth),0,1) or 0,1)
        e.Highlight.Enabled=opts.Chams;e.Box.Visible=opts.Boxes
    end
    for _,p in ipairs(Players:GetPlayers()) do if p~=B.Player and p.Character then add(p.Character,"PlayerESP") end end
    for _,m in ipairs(workspace.Game.Players:GetChildren()) do if not Players:GetPlayerFromCharacter(m) then add(m,"MobESP") end end
    for name,kind in pairs({Stands="StandESP",NPCs="NPCESP",QuestZones="ObjectiveESP",QuestInteractables="ObjectiveESP"}) do
        local f=workspace.Game:FindFirstChild(name);if f then for _,m in ipairs(f:GetChildren()) do add(m,kind) end end
    end
    for model,e in pairs(entries) do if not seen[model] then destroy(e);entries[model]=nil end end
    widget.Visible=A.Get("ESPWidget")
    if widget.Visible then
        local arrows,fruit=0,0
        for name,n in pairs(B.State.InventoryCounts or {}) do
            local lower=name:lower();if lower:find("arrow",1,true) then arrows+=n end
            if lower:find("roka",1,true) and not lower:find("seed",1,true) then fruit+=n end
        end
        widget.Text=string.format("SHARKWOW  /  inventory\narrows %d    rokaka %d",arrows,fruit)
    end
    A.Metrics.ESPObjects=count
end)
local elapsed=0
A.Connect(game:GetService("RunService").RenderStepped,function(dt)
    elapsed+=dt;if elapsed<1/30 then return end;elapsed=0
    local camera=workspace.CurrentCamera;if not camera then return end
    for _,e in pairs(entries) do
        local point,onScreen=camera:WorldToViewportPoint(e.Root.Position)
        local enabled=A.Options[e.Kind].Tracers and onScreen
        e.Line.Visible=enabled
        if enabled then
            local start=Vector2.new(camera.ViewportSize.X/2,camera.ViewportSize.Y)
            local finish=Vector2.new(point.X,point.Y);local delta=finish-start
            e.Line.Position=UDim2.fromOffset((start.X+finish.X)/2,(start.Y+finish.Y)/2)
            e.Line.Size=UDim2.fromOffset(delta.Magnitude,1)
            e.Line.Rotation=math.deg(math.atan2(delta.Y,delta.X))
        end
    end
end)
A.Cleanups[#A.Cleanups+1]=function() for _,e in pairs(entries) do destroy(e) end;table.clear(entries);widget:Destroy();folder:Destroy() end

    end)(advanced, bridge);
    (function(A, B)
local Http=game:GetService("HttpService")
local UIS=game:GetService("UserInputService")
local prompts=game:GetService("ProximityPromptService")
local original=setmetatable({},{__mode="k"})
local function restorePrompts()
    for p,value in pairs(original) do if p.Parent and p.HoldDuration==0 then p.HoldDuration=value end end
    table.clear(original)
end
A.Add({Id="InstantPrompts",Name="instant prompts",Group="utility",Description="Removes the local hold duration on ordinary prompts. Garden minigames keep their native timing.",Set=function(v) if not v then restorePrompts() end end})
A.Connect(prompts.PromptShown,function(p)
    if A.Get("InstantPrompts") and p.Name~="GardenWork" and not p:GetAttribute("GardeningPrompt") then
        if original[p]==nil then original[p]=p.HoldDuration end
        p.HoldDuration=0
    end
end)
A.Cleanups[#A.Cleanups+1]=restorePrompts
A.Add({Id="Servers",Name="lowest population server",Group="utility",Description="Uses the existing server picker and teleport resume.",Action=B.State.HopLowServer})
A.Add({Id="WarpArrow",Name="warp to arrow",Group="farm",Description="Original fast arrow teleport.",Action=function() B.Teleport("arrow") end})
A.Add({Id="WarpRokaka",Name="warp to rokaka",Group="farm",Description="Original collectible rokaka teleport.",Action=function() B.Teleport("rokaka") end})
A.Add({Id="AutoDialogue",Name="auto dialogue",Group="farm",Description="Activates only dialogue choices matching your exact text list. Purchases and stand resets are never selected implicitly.",Fields={{Key="Choices",Name="allowed text, comma separated",Default="continue,next,okay",Length=400},{Key="Delay",Name="delay seconds",Default=0.7,Min=0.3,Max=5}}})
local lastDialogue=0
function A.DialogueChoices()
    local dialogue=B.Player.PlayerGui:FindFirstChild("Dialogue")
    local holder=dialogue and dialogue:FindFirstChild("Holder")
    local choices=holder and holder:FindFirstChild("Choices")
    local result={}
    if not dialogue or not dialogue.Enabled or not choices then return result end
    for _,button in ipairs(choices:GetDescendants()) do
        if button:IsA("GuiButton") and button.Visible and button.Active and button.Name~="Template" then
            local visible=true;local parent=button.Parent
            while parent and parent~=dialogue do if parent:IsA("GuiObject") and not parent.Visible then visible=false;break end;parent=parent.Parent end
            local label=button:IsA("TextButton") and button or button:FindFirstChild("Box",true)
            if visible and label and (label:IsA("TextLabel") or label:IsA("TextButton")) then
                local value=label.Text:gsub("<[^>]+>",""):gsub("^%s*%d+[%.%)]%s*",""):lower():match("^%s*(.-)%s*$")
                if value~="" then result[#result+1]={Button=button,Text=value} end
            end
        end
    end
    return result
end
function A.ClickDialogue(button)
    if A.ActivateNativeButton then return A.ActivateNativeButton(button) end
    assert(type(getconnections)=="function","dialogue activation unavailable")
    for _,signal in ipairs({button.Activated,button.MouseButton1Click}) do
        for _,connection in ipairs(getconnections(signal)) do
            if connection.Enabled and type(connection.Function)=="function" then task.spawn(connection.Function);return true end
        end
    end
    return false
end
A.Loop("dialogue",0.25,function()
    if not A.Get("AutoDialogue") or os.clock()-lastDialogue<A.Options.AutoDialogue.Delay then return end
    for _,choice in ipairs(A.DialogueChoices()) do
        if A.MatchTarget(choice.Text,A.Options.AutoDialogue.Choices) and A.ClickDialogue(choice.Button) then
            lastDialogue=os.clock();A.Metrics.DialogueChoices=(A.Metrics.DialogueChoices or 0)+1;break
        end
    end
end)
A.Add({Id="QuestTravel",Name="quest objective travel",Group="farm",Description="Travels to the game's current tracked objective. Complex story actions still require their native interaction. Arrows and garden work take priority.",Fields={{Key="Interact",Name="interact with nearby objective",Default=false}}})
local questAt=0
A.Loop("quest travel",0.5,function()
    if not A.Get("QuestTravel") or A.GardenBusy() or A.Get("AutoFarm") or A.Get("BountyFarm") or A.Get("AutoQuest") or os.clock()<questAt then return end
    if (B.State.AutoArrow and B.State.Arrow>0) or (B.State.AutoRokaka and B.State.Rokaka>0) then return end
    local point=B.Player:GetAttribute("VisibleQuestTrackerPosition")
    if typeof(point)~="Vector3" then return end
    local c,r,h=A.Character();if not c then return end
    if (point-r.Position).Magnitude<9 then return end
    B.State.ExtensionPause=true
    local deadline=os.clock()+5
    while A.Current() and A.Get("QuestTravel") and not A.MovementFree() and os.clock()<deadline do task.wait(0.1) end
    if not A.Current() or not A.Get("QuestTravel") or not A.MovementFree() then B.State.ExtensionPause=false;return end
    B.State.RequestStream(point,3)
    if not A.Current() or not A.Get("QuestTravel") or A.GardenBusy() or B.Player.Character~=c then B.State.ExtensionPause=false;return end
    local params=RaycastParams.new();params.FilterType=Enum.RaycastFilterType.Exclude;params.FilterDescendantsInstances={c}
    local floor=workspace:Raycast(point+Vector3.new(0,15,3),Vector3.new(0,-35,0),params)
    if floor and floor.Normal.Y>0.5 then
        r.AssemblyLinearVelocity=Vector3.zero
        c:PivotTo(CFrame.new(floor.Position+Vector3.new(0,h.HipHeight+r.Size.Y/2+0.3,0)))
        A.Metrics.QuestTrips=(A.Metrics.QuestTrips or 0)+1
        if A.Options.QuestTravel.Interact then
            task.wait(0.4)
            for _,container in ipairs({workspace.Game.QuestInteractables,workspace.Game.NPCs}) do
                for _,p in ipairs(container:GetDescendants()) do
                    if p:IsA("ProximityPrompt") and p.Enabled and p.Parent:IsA("BasePart") and (p.Parent.Position-r.Position).Magnitude<math.min(9,p.MaxActivationDistance) and A.Current() and A.Get("QuestTravel") then
                        p:InputHoldBegin();task.wait(math.min(p.HoldDuration+0.1,4));p:InputHoldEnd();break
                    end
                end
            end
        end
    end
    questAt=os.clock()+12;B.State.ExtensionPause=false
end)
A.Features.QuestTravel.Set=function(v) if not v and not A.Get("AutoFarm") then B.State.ExtensionPause=false end end
local function profileName(name)
    assert(type(name)=="string" and name:match("^[%w_-]+$") and #name<=32,"profile names use letters, numbers, _ or -")
    return "sharkwow-standout-profile-"..name..".json"
end
function A.SaveProfile(name)
    assert(type(writefile)=="function","file storage unavailable")
    writefile(profileName(name),Http:JSONEncode(A.Snapshot()))
    A.Status="saved profile "..name
end
function A.LoadProfile(name)
    assert(type(readfile)=="function","file storage unavailable")
    local data=Http:JSONDecode(readfile(profileName(name)))
    assert(type(data)=="table" and data.Schema==1 and type(data.Options)=="table","invalid profile")
    for id,options in pairs(data.Options) do
        if A.Features[id] and not A.Features[id].Hidden and type(options)=="table" then for _,field in ipairs(A.Features[id].Fields) do if options[field.Key]~=nil then A.Option(id,field.Key,options[field.Key]) end end end
    end
    A.Favorites=type(data.Favorites)=="table" and data.Favorites or {}
    A.Binds=type(data.Binds)=="table" and data.Binds or {}
    A.Save();A.Status="loaded profile "..name
    if A.Refresh then A.Refresh() end
end
A.Add({Id="Profiles",Name="profiles",Group="utility",Description="Saves settings, favorites and bindings. Loading a profile preserves current farming and always-on anti-afk.",Fields={{Key="Name",Name="profile name",Default="default",Length=32}},Actions={{Name="save profile",Run=function() A.SaveProfile(A.Options.Profiles.Name) end},{Name="load profile",Run=function() A.LoadProfile(A.Options.Profiles.Name) end}}})
A.Connect(UIS.InputBegan,function(input,processed)
    if processed or UIS:GetFocusedTextBox() or input.KeyCode==Enum.KeyCode.Unknown or input.KeyCode==Enum.KeyCode.RightShift then return end
    if A.Binding then A.Binds[A.Binding]=input.KeyCode.Name;A.Binding=nil;A.Save();if A.RefreshDetails then A.RefreshDetails() end;return end
    for id,key in pairs(A.Binds) do
        local f=A.Features[id]
        if f and not f.Hidden and key==input.KeyCode.Name and not f.Action and not f.Locked then A.Set(id,not A.Get(id)) end
    end
end)
local InventoryFormat=(function()
local F={}
local priority={"Bizarre Arrow","Mysterious Arrow","Lucky Arrow","Arrow Part","Opal Roka","Opal Roka Seed","Rokaka","Rokaka Seed","Stone Mask","Wood","Steel","Phone"}
function F.Payload(rows)
    table.sort(rows,function(a,b)return a.name<b.name end)
    local fields={}
    for _,r in ipairs(rows)do
        if #fields>=7 then break end
        local names,seen={},{}
        for _,n in ipairs(priority)do names[#names+1]=n;seen[n]=true end
        local extra={};for n in pairs(r.items or{})do if type(n)=="string"and not seen[n]then extra[#extra+1]=n end end;table.sort(extra)
        for _,n in ipairs(extra)do names[#names+1]=n end
        local lines,line={},""
        for _,n in ipairs(names)do
            local count=tonumber(r.items[n])
            if count and count>0 and count<math.huge then
                local entry=n:sub(1,80)..": "..math.floor(count)
                if #line>0 and #line+#entry+3<=44 then line..=" | "..entry
                else if #line>0 then lines[#lines+1]=line end;line=entry end
            end
        end
        if #line>0 then lines[#lines+1]=line end
        local value=#lines>0 and table.concat(lines,"\n")or"No items"
        if #value>700 then value=value:sub(1,670).."\n… more items"end
        fields[#fields+1]={name=r.name:sub(1,60).." | Farm "..(r.farm and "ON"or"OFF"),value=value,inline=true}
    end
    return {allowed_mentions={parse={}},embeds={{title="STAND OUT | Inventory",color=3066993,fields=fields}}}
end
return F

end)()
A.Add({Id="Webhook",Name="discord farm notifications",Group="notify",Description="Paste your Discord webhook, then enable. Sends a combined Inventory card with current item totals from this computer. URL stays in this session; enter it again after reload.",Fields={
    {Key="URL",Name="discord webhook url",Default="",Length=1000},
    {Key="Summary",Name="periodic farm summary",Default=true},
    {Key="Arrows",Name="arrow gains",Default=true},
    {Key="Items",Name="item gains",Default=true},
    {Key="Interval",Name="summary interval seconds",Default=300,Min=60,Max=3600},
}})
A.Options.Webhook.URL=""
local queue,totals,counts={}, {}, nil
local nextSend,summaryAt=0,os.clock()
local function validURL(url)
    return type(url)=="string" and (url:match("^https://discord%.com/api/webhooks/%d+/[%w_-]+$")
        or url:match("^https://discordapp%.com/api/webhooks/%d+/[%w_-]+$"))~=nil
end
local function reset()
    table.clear(queue);table.clear(totals)
    counts=nil;summaryAt=os.clock();nextSend=0
end
A.Features.Webhook.Set=function(enabled)
    if enabled then
        assert(validURL(A.Options.Webhook.URL),"enter a valid discord webhook url")
        assert(type(request or http_request or (syn and syn.request))=="function","http requests unavailable")
    end
    reset()
end
A.Features.Webhook.Changed=function(key)
    if key=="URL" then A.Set("Webhook",false) end
end
A.Cleanups[#A.Cleanups+1]=function() reset();A.Options.Webhook.URL="" end
function A.Notify(kind,message)
    if not A.Current() or not A.Get("Webhook") or not A.Options.Webhook[kind] then return end
    if #queue>=50 then A.Metrics.WebhookOverflow=(A.Metrics.WebhookOverflow or 0)+1;return end
    queue[#queue+1]={Message=message,Attempts=0}
end
local snapshotPrefix="sharkwow-standout-inventory-live-"
local function inventoryPayload()
    local now=os.time and os.time()or os.clock()
    local own={userId=B.Player.UserId or 0,name=B.Player.Name,items=B.State.ReadInventory()or{},farm=B.State.AutoArrow or B.State.AutoRokaka or B.State.AutoParts or false,at=now}
    local rows={own}
    if type(readfile)=="function"and type(listfiles)=="function"then
        for index,path in ipairs(listfiles(""))do
            if index>1000 then break end
            local uid=tonumber(path:match(snapshotPrefix:gsub("([^%w])","%%%1").."(%d+)%.json$"))
            if uid and uid~=own.userId then
                local ok,r=pcall(function()local body=readfile(path);assert(#body<=40000);return Http:JSONDecode(body)end)
                if ok and type(r)=="table"and r.userId==uid and r.place==128828638194450 and type(r.at)=="number"and math.abs(now-r.at)<=45 and type(r.items)=="table"and type(r.name)=="string"then rows[#rows+1]=r end
            end
        end
    end
    return InventoryFormat.Payload(rows)
end
local function deliver(entry)
    local url=A.Options.Webhook.URL
    if not A.Current() or not A.Get("Webhook") or not validURL(url) then return end
    local requestFn=request or http_request or (syn and syn.request)
    if type(requestFn)~="function" then A.Set("Webhook",false);A.Error("Webhook","http requests unavailable");return end
    local payload=inventoryPayload()
    local ok,response=pcall(requestFn,{Url=url.."?wait=true",Method="POST",Headers={["Content-Type"]="application/json"},Body=Http:JSONEncode(payload)})
    if not A.Current() or not A.Get("Webhook") or A.Options.Webhook.URL~=url then return end
    local status=ok and type(response)=="table" and tonumber(response.StatusCode) or nil
    if status and status>=200 and status<300 then
        table.remove(queue,1);A.Errors.Webhook=nil
        local decoded,message=pcall(Http.JSONDecode,Http,response.Body or "")
        B.State.WebhookReceipt={HTTP=status,Fields=#payload.embeds[1].fields,
            MessageId=decoded and type(message)=="table"and message.id or nil,
            ChannelId=decoded and type(message)=="table"and message.channel_id or nil}
        A.Metrics.Webhooks=(A.Metrics.Webhooks or 0)+1
        local headers=response.Headers or {}
        if tonumber(headers["x-ratelimit-remaining"] or headers["X-RateLimit-Remaining"])==0 then
            local delay=tonumber(headers["x-ratelimit-reset-after"] or headers["X-RateLimit-Reset-After"]) or 3
            if delay==delay and delay>0 and delay<math.huge then nextSend=math.max(nextSend,os.clock()+delay) end
        end
    elseif status==429 then
        entry.Attempts+=1
        local decoded,data=pcall(Http.JSONDecode,Http,response.Body or "")
        local headers=response.Headers or {}
        local delay=tonumber(decoded and type(data)=="table" and data.retry_after) or tonumber(headers["Retry-After"] or headers["retry-after"]) or 5
        if delay~=delay or delay<=0 or delay==math.huge then delay=5 end
        nextSend=os.clock()+delay
        if entry.Attempts>=5 then A.Set("Webhook",false);A.Error("Webhook","rate limited repeatedly; enable again later") end
    else
        A.Set("Webhook",false)
        A.Error("Webhook",status and ("delivery rejected: HTTP "..status) or "delivery outcome unknown; stopped to avoid duplicate reports")
    end
end
A.Features.Webhook.Actions={{Name="send test",Run=function()
    assert(A.Get("Webhook"),"enable notifications first")
    if #queue<50 then queue[#queue+1]={Message="Test notification",Attempts=0} end
end}}
local snapshotAt=0
A.Loop("notifications",1,function()
    if type(writefile)=="function"and B.Player.UserId and B.State.InventoryReady and os.clock()>=snapshotAt then
        snapshotAt=os.clock()+10
        local farm=B.State.AutoArrow or B.State.AutoRokaka or B.State.AutoParts or A.Get("AutoCraftBizarre")or A.Get("GardenHarvest")or A.Get("FreeArrowMaterials")
        local ok=pcall(writefile,snapshotPrefix..B.Player.UserId..".json",Http:JSONEncode({userId=B.Player.UserId,name=B.Player.Name,items=B.State.ReadInventory()or{},farm=farm==true,at=os.time(),place=game.PlaceId}))
        if not ok then A.Error("inventory snapshot","local inventory snapshot unavailable")end
    end
    if not A.Get("Webhook") then return end
    local inventory=B.State.ReadInventory()
    if not B.State.InventoryReady or type(inventory)~="table" then return end
    if counts then
        for name,value in pairs(inventory) do
            local delta=value-(counts[name] or 0)
            if delta>0 then
                totals[name]=(totals[name] or 0)+delta
                A.Notify(name:lower():find("arrow",1,true) and "Arrows" or "Items",name.." +"..delta.." | now "..value)
            end
        end
    end
    counts=table.clone(inventory)
    if os.clock()-summaryAt>=A.Options.Webhook.Interval then
        summaryAt=os.clock()
        local lines={"Observed inventory gains since notifications enabled:"}
        local names={};for name in pairs(totals) do names[#names+1]=name end;table.sort(names)
        for _,name in ipairs(names) do lines[#lines+1]=name.." +"..totals[name] end
        if #names==0 then lines[#lines+1]="No new items observed." end
        A.Notify("Summary",table.concat(lines,"\n"))
    end
    if #queue>0 and os.clock()>=nextSend then nextSend=os.clock()+3;deliver(queue[1]) end
end)

    end)(advanced, bridge);
    (function(A, B)
local RS=game:GetService("ReplicatedStorage")
local Http=game:GetService("HttpService")
local Collection=game:GetService("CollectionService")
local Bounties=require(RS.Modules.Bounty)
local Quests=require(RS.Modules.Quests)
local Locations=require(RS.Modules.QuestLocations)
local stats=B.Player.Data.Stats
local function decode(value)
    local ok,data=pcall(Http.JSONDecode,Http,value)
    return ok and type(data)=="table" and data or {}
end
local function pointOf(object)
    if not object then return end
    if object:IsA("BasePart") then return object.Position end
    if object:IsA("Model") then return object:GetPivot().Position end
    if object:IsA("Attachment") then return object.WorldPosition end
end
local function promptPosition(prompt)
    return pointOf(prompt.Parent)
end
local function originalFarm()
    return {Enabled=A.Get("AutoFarm"),Targets=A.Options.AutoFarm.Targets,Bosses=A.Options.AutoFarm.Bosses}
end
local function restoreFarm(saved)
    if not saved then return end
    A.Options.AutoFarm.Targets=saved.Targets;A.Options.AutoFarm.Bosses=saved.Bosses
    A.Set("AutoFarm",saved.Enabled)
end
local function hasPriority()
    return A.GardenBusy() or (B.State.AutoArrow and B.State.Arrow>0) or (B.State.AutoRokaka and B.State.Rokaka>0)
end
local function visit(point,id,interactFilter)
    if typeof(point)~="Vector3" or hasPriority() or B.State.Flying or B.State.TransferPending then return false end
    local c,r,h=A.Character();if not c then return false end
    B.State.ExtensionPause=true
    local deadline=os.clock()+4
    while A.Current() and A.Get(id) and not A.MovementFree() and os.clock()<deadline do task.wait(0.1) end
    if not A.Current() or not A.Get(id) or not A.MovementFree() or hasPriority() then B.State.ExtensionPause=false;return false end
    local ok,err=pcall(function()
        local params=RaycastParams.new();params.FilterType=Enum.RaycastFilterType.Exclude;params.FilterDescendantsInstances={c}
        local floor=workspace:Raycast(point+Vector3.new(3,3,3),Vector3.new(0,-18,0),params)
        if not floor then B.State.RequestStream(point,2);floor=workspace:Raycast(point+Vector3.new(3,3,3),Vector3.new(0,-18,0),params) end
        assert(floor and floor.Normal.Y>0.5,"objective floor unavailable")
        if not A.Current() or not A.Get(id) or hasPriority() or B.Player.Character~=c then return end
        r.AssemblyLinearVelocity=Vector3.zero
        c:PivotTo(CFrame.new(floor.Position+Vector3.new(0,h.HipHeight+r.Size.Y/2+0.3,0)))
        task.wait(0.4)
        if interactFilter then
            local candidates={}
            for _,folderName in ipairs({"NPCs","BountyWorld","QuestInteractables"}) do
                local folder=workspace.Game:FindFirstChild(folderName)
                for _,p in ipairs(folder and folder:GetDescendants() or {}) do
                    if p:IsA("ProximityPrompt") and p.Enabled then
                        local pos=promptPosition(p)
                        if pos and (pos-r.Position).Magnitude<=math.min(12,p.MaxActivationDistance) and interactFilter(p) then candidates[#candidates+1]=p end
                    end
                end
            end
            local prompt=candidates[1]
            if prompt and A.Current() and A.Get(id) and not hasPriority() then
                prompt:InputHoldBegin()
                local untilAt=os.clock()+math.min(prompt.HoldDuration+0.15,5)
                repeat task.wait(0.05) until os.clock()>=untilAt or not A.Current() or not A.Get(id)
                prompt:InputHoldEnd()
            end
        end
    end)
    B.State.ExtensionPause=false
    if not ok then A.Error(id,err) end
    return ok
end
local function related(prompt,id)
    local node=prompt
    for _=1,7 do
        if not node or node==workspace then break end
        local owner=node:GetAttribute("BountyLeaderId") or node:GetAttribute("StoryOwnerUserId") or node:GetAttribute("OwnerUserId")
        if owner and owner~=0 and tonumber(owner)~=B.Player.UserId then return false end
        local bounty=node:GetAttribute("BountyId") or node:GetAttribute("Bounty")
        if bounty and tostring(bounty)==id then return true end
        if tonumber(owner)==B.Player.UserId and node:GetAttribute("BountyLeaderId") then return true end
        node=node.Parent
    end
    return false
end
local function supported(offer)
    for _,step in ipairs(offer.Steps or {}) do
        if not ({Find=true,Interact=true,Summon=true,Defend=true})[step.Type] then return false end
    end
    return #(offer.Steps or {})>0
end
A.Add({Id="BountyFarm",Name="field bounty farm",Group="farm",Description="Requires Report to Meryl at Iko Iko. Supports find, interact, summon and defend. Story incidents, karaoke, drawings and card games are excluded.",Fields={{Key="Name",Name="bounty name (blank = eligible)",Default="",Length=120},{Key="Repeat",Name="accept next eligible bounty",Default=false}}})
local bountySaved,bountyId,bountyAt,bountyCompleted=nil,nil,0,0
local acceptDeadline,seenActive=0,false
local accepted={}
local function bountyCleanup()
    if bountySaved then restoreFarm(bountySaved);bountySaved=nil end
    bountyId=nil;B.State.ExtensionPause=false
end
A.Features.BountyFarm.Set=function(v)
    if v then
        assert(table.find(string.split(stats.CompletedQuests.Value,","),"P9_32_RETURN_TO_IKO_IKO"),"finish Report to Meryl at Iko Iko to unlock bounties")
        assert(not A.Get("QuestFarm") and not A.Get("AutoQuest"),"stop quest automation first");bountySaved=originalFarm();bountyAt=0
    else bountyCleanup() end
end
A.Cleanups[#A.Cleanups+1]=bountyCleanup
function A.BountyOffers()
    local offers=Bounties.GetCurrentBounties(workspace:GetServerTimeNow(),1,Bounties.GetPlayerLevel(B.Player))
    local result={}
    for _,offer in ipairs(offers) do if supported(offer) then result[#result+1]={Id=offer.Id,Name=offer.Name} end end
    return result
end
A.Loop("bounty farm",1,function()
    if not A.Get("BountyFarm") or hasPriority() or os.clock()<bountyAt then return end
    local active=decode(stats.ActiveBounties.Value)
    local progress=decode(stats.BountyProgress.Value)
    if bountyId and not table.find(active,bountyId) then
        if not seenActive then
            if os.clock()<acceptDeadline then A.Status="waiting for bounty acceptance";return end
            A.Set("BountyFarm",false);A.Error("BountyFarm","acceptance unconfirmed; no additional bounty was requested");return
        end
        if progress[bountyId] and progress[bountyId].ReadyToClaim then return end
        if Bounties.HasCompleted(B.Player,bountyId) then
            if A.PendingBountyClaim and A.PendingBountyClaim.Id==bountyId then A.PendingBountyClaim=nil end
            bountyCompleted+=1;A.Metrics.Bounties=bountyCompleted
            if not A.Options.BountyFarm.Repeat then A.Set("BountyFarm",false);A.Status="bounty completed";return end
        end
        bountyId=nil
    end
    if not bountyId then
        if #active>0 then A.Status="bounty farm: existing bounty preserved";return end
        for _,offer in ipairs(Bounties.GetCurrentBounties(workspace:GetServerTimeNow(),1,Bounties.GetPlayerLevel(B.Player))) do
            if supported(offer) and not accepted[offer.Id] and offer.MinLevel<=Bounties.GetPlayerLevel(B.Player) and (A.Options.BountyFarm.Name=="" or offer.Name:lower()==A.Options.BountyFarm.Name:lower()) then
                local npc=workspace.Game.NPCs:FindFirstChild("Petyr")
                local point=pointOf(npc) or Locations.Get({"NPCs","Petyr"})
                if not visit(point,"BountyFarm",function(p) return npc and p:IsDescendantOf(npc) end) then bountyAt=os.clock()+5;return end
                if not A.Current() or not A.Get("BountyFarm") or hasPriority() then return end
                accepted[offer.Id]=true;bountyId=offer.Id;bountyAt=os.clock()+5;acceptDeadline=os.clock()+20;seenActive=false
                RS.Remotes.Bounty:FireServer("Accept",offer.Id)
                A.Status="accepting "..offer.Name;return
            end
        end
        A.Status="waiting for an eligible field bounty";return
    end
    local record=progress[bountyId]
    if table.find(active,bountyId) then seenActive=true end
    if not record then A.Status="waiting for bounty acceptance";return end
    local rotation,index,tier=Bounties.ParseBountyId(bountyId)
    local offer=Bounties.GenerateBounty(rotation,index,tier,Bounties.GetPlayerLevel(B.Player))
    local step=offer.Steps[record.StepIndex or 1]
    local point=B.Player:GetAttribute("VisibleBountyTrackerPosition")
    if record.ReadyToClaim or not step then
        A.Set("AutoFarm",false)
        local npc=Bounties.GetRewardNPC();point=pointOf(npc) or point
        local arrived=visit(point,"BountyFarm",function(p) return npc and p:IsDescendantOf(npc) end)
        if arrived and Bounties.GetPendingRewardId(B.Player)==bountyId then
            if A.PendingBountyClaim then
                if os.clock()-A.PendingBountyClaim.At>15 then A.Set("BountyFarm",false);A.Error("BountyFarm","reward claim unconfirmed; inspect native bounty status") end
            else
                A.PendingBountyClaim={Id=bountyId,At=os.clock()}
                RS.Remotes.Bounty:FireServer("ClaimAtPetyr",bountyId)
            end
        end
        bountyAt=os.clock()+3;A.Status="claiming bounty reward";return
    end
    if step.Type=="Summon" or step.Type=="Defend" then
        local names={}
        if step.Type=="Summon" then names={step.Target} else for _,wave in ipairs(step.Enemies or {}) do for _,name in ipairs(wave) do if not table.find(names,name) then names[#names+1]=name end end end end
        A.Options.AutoFarm.Targets=table.concat(names,", ");A.Options.AutoFarm.Bosses=false
        A.Set("AutoFarm",true)
        if A.FarmTarget then return end
    else A.Set("AutoFarm",false) end
    if not point then
        local npc=step.Target and workspace.Game.NPCs:FindFirstChild(step.Target)
        point=pointOf(npc)
        if not point then for _,tag in ipairs({"BountyTarget","BountyObjective"}) do for _,node in ipairs(Collection:GetTagged(tag)) do if tostring(node:GetAttribute("BountyId"))==bountyId then point=pointOf(node);break end end end end
    end
    visit(point,"BountyFarm",function(p) return related(p,bountyId) end)
    bountyAt=os.clock()+2;A.Status=offer.Name.." / "..step.Objective
end)
A.Add({Id="AutoQuest",Name="auto quest accept",Group="farm",Description="Visits the selected quest giver and selects an exact matching quest title when offered. Unknown dialogue branches stop for manual selection.",Fields={{Key="Quest",Name="quest id",Default="",Length=150}}})
A.Add({Id="QuestFarm",Name="quest mob farm",Group="farm",Description="Combines the selected accepted quest with your chosen mob names. Stops attacks when that quest leaves the active list. Special story minigames remain manual.",Fields={{Key="Quest",Name="quest id",Default="",Length=150},{Key="Targets",Name="mob names, comma separated",Default="",Length=300}}})
local questSaved,questAt=nil,0
A.Features.AutoQuest.Set=function(v)
    if v then assert(not A.Get("BountyFarm"),"stop bounty farm first");assert(Quests.Quests[A.Options.AutoQuest.Quest],"enter a valid quest id") end
end
A.Features.QuestFarm.Set=function(v)
    if v then
        assert(not A.Get("BountyFarm"),"stop bounty farm first")
        assert(Quests.Quests[A.Options.QuestFarm.Quest],"enter a valid quest id")
        assert(A.Options.QuestFarm.Targets:find("%S"),"choose quest mobs first")
        questSaved=originalFarm()
    elseif questSaved then restoreFarm(questSaved);questSaved=nil end
end
A.Cleanups[#A.Cleanups+1]=function() if questSaved then restoreFarm(questSaved);questSaved=nil end end
local function activeQuest(id) return table.find(string.split(stats.ActiveQuest.Value,","),id)~=nil end
A.Loop("quest farm",1,function()
    if A.Get("QuestFarm") then
        if activeQuest(A.Options.QuestFarm.Quest) then
            A.Options.AutoFarm.Targets=A.Options.QuestFarm.Targets
            if not A.Get("AutoFarm") then A.Set("AutoFarm",true) end
        elseif A.Get("AutoFarm") then A.Set("AutoFarm",false);A.Status="waiting for selected quest acceptance" end
    end
    if not A.Get("AutoQuest") or activeQuest(A.Options.AutoQuest.Quest) or hasPriority() or os.clock()<questAt then return end
    local quest=Quests.Quests[A.Options.AutoQuest.Quest]
    local npc=quest.QuestGiver and workspace.Game.NPCs:FindFirstChild(quest.QuestGiver)
    if not npc then A.Status="selected quest giver is not loaded";return end
    if A.Get("AutoFarm") then return end
    visit(pointOf(npc),"AutoQuest",function(p) return p:IsDescendantOf(npc) end)
    for _,choice in ipairs(A.DialogueChoices()) do if choice.Text==quest.Title:lower() then A.ClickDialogue(choice.Button);break end end
    questAt=os.clock()+4
end)

    end)(advanced, bridge);
    (function(A, B)
A.Add({Id="ItemFarm",Name="item farm",Group="farm",Description="Collects selected loose world items with native prompts. Keeps arrows and garden fruit with their original farmers. Skips other owners' drops and pauses during combat or quests.",Fields={{Key="Names",Name="item names, comma separated",Default="",Length=400},{Key="Range",Name="search radius",Default=1500,Min=10,Max=6000}}})
local retry=setmetatable({},{__mode="k"})
local function eligible(model)
    local name=model:GetAttribute("ItemName") or model.Name
    if type(name)~="string" then return end
    local lower=name:lower()
    if lower:find("arrow",1,true) or lower:find("roka",1,true) and not lower:find("seed",1,true) then return end
    for _,node in ipairs({model,model.Parent}) do
        local owner=node and (node:GetAttribute("OwnerUserId") or node:GetAttribute("StoryOwnerUserId"))
        if owner and tonumber(owner)~=0 and tonumber(owner)~=B.Player.UserId then return end
    end
    local prompt=model:FindFirstChildWhichIsA("ProximityPrompt",true)
    local part=model:IsA("BasePart") and model or model:FindFirstChildWhichIsA("BasePart",true)
    if not prompt or not prompt.Enabled or not part then return end
    local action=prompt.ActionText:lower()
    if not (action:find("pick",1,true) or action:find("collect",1,true) or action:find("take",1,true)) then return end
    return name,prompt,part
end
function A.WorldItemNames()
    local result,seen={},{}
    for _,folderName in ipairs({"SpawnedItems","WorldEventDrops"}) do
        local folder=workspace.Game:FindFirstChild(folderName)
        if folder then for _,model in ipairs(folder:GetChildren()) do local name=eligible(model);if name and not seen[name] then result[#result+1]=name;seen[name]=true end end end
    end
    table.sort(result);return result
end
local held
A.Cleanups[#A.Cleanups+1]=function() if held then pcall(held.InputHoldEnd,held);held=nil end end
A.Loop("item farm",0.5,function()
    if not A.Get("ItemFarm") or A.Get("AutoFarm") or A.Get("BountyFarm") or A.Get("AutoQuest") or A.Get("QuestTravel") or A.GardenBusy() then return end
    if (B.State.AutoArrow and B.State.Arrow>0) or (B.State.AutoRokaka and B.State.Rokaka>0) then return end
    local c,r,h=A.Character();if not c then return end
    if not A.Options.ItemFarm.Names:find("%S") then A.Status="choose item names in item farm settings";return end
    local best,distance=nil,A.Options.ItemFarm.Range
    for _,folderName in ipairs({"SpawnedItems","WorldEventDrops"}) do
        local folder=workspace.Game:FindFirstChild(folderName)
        if folder then
            for _,model in ipairs(folder:GetChildren()) do
                local name,prompt,part=eligible(model)
                if name and (retry[model] or 0)<os.clock() and A.MatchTarget(name,A.Options.ItemFarm.Names) then
                    local d=(r.Position-part.Position).Magnitude
                    if d<distance then best={Model=model,Name=name,Prompt=prompt,Part=part};distance=d end
                end
            end
        end
    end
    if not best then return end
    B.State.ExtensionPause=true
    local ok,err=pcall(function()
        local deadline=os.clock()+4
        while A.Current() and A.Get("ItemFarm") and not A.MovementFree() and os.clock()<deadline do task.wait(0.1) end
        if not A.Current() or not A.Get("ItemFarm") or not A.MovementFree() or not best.Model.Parent then return end
        local point=best.Part.Position
        local params=RaycastParams.new();params.FilterType=Enum.RaycastFilterType.Exclude;params.FilterDescendantsInstances={c,best.Model}
        local floor=workspace:Raycast(point+Vector3.new(0,10,3),Vector3.new(0,-25,0),params)
        assert(floor and floor.Normal.Y>0.5,"no supported item landing")
        local before=B.State.ReadInventory()[best.Name] or 0
        c:PivotTo(CFrame.new(floor.Position+Vector3.new(0,h.HipHeight+r.Size.Y/2+0.2,0)));r.AssemblyLinearVelocity=Vector3.zero
        task.wait(0.4)
        if not A.Current() or not A.Get("ItemFarm") or A.GardenBusy() or not best.Prompt.Parent then return end
        assert((r.Position-best.Part.Position).Magnitude<=best.Prompt.MaxActivationDistance+1,"item is out of range")
        assert(best.Prompt.HoldDuration<=5,"unexpected prompt duration")
        held=best.Prompt;held:InputHoldBegin()
        deadline=os.clock()+held.HoldDuration+0.15
        repeat task.wait(0.05) until not A.Current() or not A.Get("ItemFarm") or os.clock()>=deadline
        held:InputHoldEnd();held=nil
        deadline=os.clock()+4
        while A.Current() and A.Get("ItemFarm") and os.clock()<deadline do
            if (B.State.ReadInventory()[best.Name] or 0)>before then A.Metrics.Items=(A.Metrics.Items or 0)+1;A.Status="collected "..best.Name;return end
            task.wait(0.2)
        end
        error("item inventory gain unconfirmed")
    end)
    if held then pcall(held.InputHoldEnd,held);held=nil end
    retry[best.Model]=os.clock()+15;B.State.ExtensionPause=false
    if not ok then A.Error("ItemFarm",err) end
end)

    end)(advanced, bridge);
    (function(A, B)
local S=B.State
local id="StoneMaskFarm"
local file="sharkwow-stone-mask-"..B.Player.UserId..".json"
local Http=game:GetService("HttpService")
local enabled=false
if type(readfile)=="function" then
    local ok,data=pcall(function() return Http:JSONDecode(readfile(file)) end)
    enabled=ok and type(data)=="table" and data.UserId==B.Player.UserId and data.Enabled==true
end
local held,owned=false,false
local retry=setmetatable({},{__mode="k"})
local function cleanup()
    if held then pcall(held.InputHoldEnd,held);held=false end
    if owned then S.CraftBusy=false;S.ExtensionPause=false;owned=false end
end
A.Cleanups[#A.Cleanups+1]=cleanup
A.Add({Id=id,Name="stone mask pickup",Group="farm",Description="Collects loose Stone Masks, confirms inventory gain, and waits for farming and crafting movement. Stops at the item stack limit.",Get=function()return enabled end,Set=function(v)
    assert(type(writefile)=="function","mask settings storage unavailable")
    writefile(file,Http:JSONEncode({UserId=B.Player.UserId,Enabled=v==true}))
    enabled=v==true
end})
S.StoneMaskVersion=1
local function valid(c)
    return A.Current() and enabled and not S.TransferPending and not S.HopBusy and not S.AutoHopPause
        and not S.PhoneBusy and B.Player.Character==c and c.Parent
        and c:FindFirstChildOfClass("Humanoid") and c:FindFirstChildOfClass("Humanoid").Health>0
end
local function candidate(model)
    local child=model:FindFirstChildWhichIsA("Model")
    local name=model:GetAttribute("ItemName") or (child and child.Name) or model.Name
    if name~="Stone Mask" then return end
    for _,node in ipairs({model,model.Parent}) do
        local owner=node:GetAttribute("OwnerUserId") or node:GetAttribute("StoryOwnerUserId")
        if owner and tonumber(owner)~=0 and tonumber(owner)~=B.Player.UserId then return end
    end
    local prompt=model:FindFirstChildWhichIsA("ProximityPrompt",true)
    local part=model:IsA("BasePart") and model or model:FindFirstChildWhichIsA("BasePart",true)
    if prompt and prompt.Enabled and part and prompt.HoldDuration<=5 then return prompt,part end
end
A.Loop("stone mask pickup",0.5,function()
    if not enabled or not A.MovementFree() or S.ExtensionPause or S.RaidBusy then return end
    for _,other in ipairs({"AutoFarm","AutoQuest","BountyFarm","QuestTravel","AutoRoll","AutoPilot"}) do if A.Get(other) then return end end
    local count=S.ReadInventory()["Stone Mask"] or 0
    local definition=require(game.ReplicatedStorage.Modules.Items).items["Stone Mask"]
    local cap=definition and definition.MaxStack
    if type(cap)~="number" then A.Error(id,"mask stack limit unavailable");return end
    if count>=cap then S.StoneMaskStatus="inventory full";return end
    local c,r,h=A.Character();if not c then return end
    local best,distance=nil,math.huge
    for _,folderName in ipairs({"SpawnedItems","WorldEventDrops"}) do
        local folder=workspace.Game:FindFirstChild(folderName)
        if folder then for _,model in ipairs(folder:GetChildren()) do
            local prompt,part=candidate(model)
            if prompt and (retry[model] or 0)<=os.clock() then
                local d=(r.Position-part.Position).Magnitude
                if d<distance then best={Model=model,Prompt=prompt,Part=part};distance=d end
            end
        end end
    end
    if not best then S.StoneMaskStatus="waiting for stone mask";return end
    owned=true;S.CraftBusy=true;S.ExtensionPause=true
    local ok,err=pcall(function()
        if S.ReleaseIdleHide then S.ReleaseIdleHide() end
        if B.ReleaseFarmHold then B.ReleaseFarmHold() end
        local params=RaycastParams.new();params.FilterType=Enum.RaycastFilterType.Exclude;params.FilterDescendantsInstances={c,best.Model}
        local floor=workspace:Raycast(best.Part.Position+Vector3.new(0,8,2),Vector3.new(0,-25,0),params)
        assert(floor and floor.Normal.Y>0.5,"mask landing not loaded")
        if not valid(c) then return end
        c:PivotTo(CFrame.new(floor.Position+Vector3.new(0,h.HipHeight+r.Size.Y/2+0.2,0)))
        r.AssemblyLinearVelocity=Vector3.zero
        task.wait(0.4)
        if not valid(c) or not best.Model.Parent or not best.Prompt.Parent then return end
        assert(best.Prompt.Enabled and (r.Position-best.Part.Position).Magnitude<=best.Prompt.MaxActivationDistance,"mask out of range")
        local before=S.ReadInventory()["Stone Mask"] or 0
        if before>=cap then return end
        held=best.Prompt;held:InputHoldBegin()
        local deadline=os.clock()+held.HoldDuration+0.15
        repeat task.wait(0.05) until not valid(c) or os.clock()>=deadline or (S.ReadInventory()["Stone Mask"] or 0)>before
        held:InputHoldEnd();held=false
        deadline=os.clock()+4
        repeat
            if (S.ReadInventory()["Stone Mask"] or 0)>before then
                A.Metrics.StoneMasks=(A.Metrics.StoneMasks or 0)+1
                S.StoneMaskStatus="stone mask collected";A.Errors[id]=nil;return
            end
            task.wait(0.1)
        until not valid(c) or os.clock()>=deadline
        if valid(c) then error("mask inventory gain unconfirmed") end
    end)
    cleanup();retry[best.Model]=os.clock()+30
    if not ok then S.StoneMaskStatus=tostring(err);A.Error(id,err) end
end)

    end)(advanced, bridge);
    (function(A, B)
local Run=game:GetService("RunService")
local Players=game:GetService("Players")
local lease
local U={Version=2,AttackRange=8.25,FallbackRange=7.25,SteelRange=4.25,SteelFallback=3.75}
A.Underground=U
function U.HeavyShape(native,part)
    if not debug or type(debug.getupvalues)~="function" or type(native.heavySwing)~="function" then return end
    local ok,values=pcall(debug.getupvalues,native.heavySwing)
    if not ok then return end
    for _,profile in pairs(values) do
        if type(profile)=="table" and type(profile.M2Hitbox)=="table" and #profile.M2Hitbox==1 then
            local size=profile.M2Hitbox[1]
            if typeof(size)=="Vector3" and size.X>0 and size.Y>0 and size.Z>0 and size.Magnitude<100 then
                local offset=profile.M2HitboxOffsets and profile.M2HitboxOffsets[1] or CFrame.new(0,0,-size.Z/2)
                if typeof(offset)=="CFrame" then return {Size=size,Offset=offset,Part=part} end
            end
        end
    end
end
function U.Overlaps(model,pose,shape)
    if not model.Parent or not shape then return false end
    local params=OverlapParams.new();params.FilterType=Enum.RaycastFilterType.Include
    params.FilterDescendantsInstances={shape.Part or model};params.MaxParts=1;params.RespectCanCollide=false
    return #workspace:GetPartBoundsInBox(pose*shape.Offset,shape.Size,params)>0
end
function U.Release(owner,ground)
    local old=lease
    if not old or (owner and old.Owner~=owner) then return end
    lease=nil;B.State.UndergroundLock=nil
    if old.Prompt then pcall(old.Prompt.InputHoldEnd,old.Prompt) end
    for _,connection in ipairs(old.Connections) do connection:Disconnect() end
    for _,instance in ipairs(old.Instances) do instance:Destroy() end
    if B.Player.Character==old.Character and old.Root.Parent then
        if ground and (old.Root.Position-old.Pose.Position).Magnitude<20 then old.Root.CFrame=old.Ground end
        old.Root.AssemblyLinearVelocity=Vector3.zero
        old.Root.AssemblyAngularVelocity=Vector3.zero
        old.Humanoid.AutoRotate=old.AutoRotate
    end
    for part,value in pairs(old.Collisions) do
        if part.Parent and not B.State.Noclip and not B.State.FarmHideActive then part.CanCollide=value end
    end
end
function U.Finish(owner)
    if lease and lease.Owner==owner then lease.Idle=true;B.State.UndergroundLock.Idle=true end
end
function U.Park(owner,valid)
    if lease or not A.MovementFree() then return end
    local character,root,humanoid=A.Character()
    if not character or root.Anchored then return end
    local params=RaycastParams.new();params.FilterType=Enum.RaycastFilterType.Exclude;params.FilterDescendantsInstances={character};params.RespectCanCollide=true
    local floor=workspace:Raycast(root.Position+Vector3.new(0,3,0),Vector3.new(0,-35,0),params)
    if not floor or floor.Normal.Y<.65 then return end
    U.Begin(owner,character,root,humanoid,floor.Position+Vector3.new(0,3,0),character,9.25,"idle",valid)
    U.Finish(owner)
end
function U.Check(owner)
    return lease~=nil and lease.Owner==owner and not lease.Idle and lease.Root.Parent~=nil
        and B.Player.Character==lease.Character and (lease.Root.Position-lease.Pose.Position).Magnitude<=2
end
function U.Prompt(owner,prompt,valid)
    assert(U.Check(owner) and valid() and prompt.Parent and prompt.Enabled,"underground prompt unavailable")
    assert(prompt.HoldDuration<=5,"unexpected prompt duration")
    lease.Prompt=prompt
    if type(fireproximityprompt)=="function" then
        fireproximityprompt(prompt)
    else
        prompt:InputHoldBegin()
        local deadline=os.clock()+prompt.HoldDuration+.2
        repeat task.wait(.05) until not valid() or os.clock()>=deadline
        prompt:InputHoldEnd()
    end
    if lease and lease.Owner==owner then lease.Prompt=nil end
    assert(valid(),"underground prompt cancelled")
end
local function nearestPlayer(point)
    local distance=math.huge
    for _,other in ipairs(Players:GetPlayers()) do
        local root=other~=B.Player and other.Character and other.Character:FindFirstChild("HumanoidRootPart")
        if root then distance=math.min(distance,(point-root.Position).Magnitude) end
    end
    return distance
end
function U.Begin(owner,character,root,humanoid,point,model,range,mode,valid,shape)
    if B.ReleaseFarmHold then B.ReleaseFarmHold() end
    assert(valid() and not root.Anchored,"underground character unavailable")
    assert(type(range)=="number" and range>=3.5 and range<=10,"invalid underground reach")
    local params=RaycastParams.new();params.FilterType=Enum.RaycastFilterType.Exclude
    params.FilterDescendantsInstances={character,model};params.RespectCanCollide=true
    local best,bestScore
    for index=0,7 do
        local angle=index*math.pi/4
        local offset=Vector3.new(math.cos(angle)*2,0,math.sin(angle)*2)
        local floor=workspace:Raycast(point+offset+Vector3.new(0,3,0),Vector3.new(0,-32,0),params)
        if floor and floor.Normal.Y>=0.65 and floor.Material~=Enum.Material.Water then
            local dest=point+offset-Vector3.new(0,math.sqrt(range*range-4),0)
            local cover=floor.Position.Y-dest.Y
            local safe=dest.Y>workspace.FallenPartsDestroyHeight+25 and cover>=(mode=="attack" and 2.5 or 4)
            if safe and mode=="craft" then safe=(dest-model:GetPivot().Position).Magnitude<=11.25 end
            if safe and shape then safe=U.Overlaps(model,CFrame.lookAt(dest,point),shape) end
            if safe then
                local score=nearestPlayer(dest)
                if not best or score>bestScore then
                    best={Position=dest,Floor=floor.Position,Cover=cover};bestScore=score
                end
            end
        end
    end
    assert(best,"no covered underground position within interaction range")
    U.Release(nil,false)
    local pose=mode=="attack" and CFrame.lookAt(best.Position,point) or CFrame.lookAt(best.Position,Vector3.new(point.X,best.Position.Y,point.Z))
    local ground=Vector3.new(best.Position.X,best.Floor.Y+humanoid.HipHeight+root.Size.Y/2+.3,best.Position.Z)
    local old={Owner=owner,Character=character,Root=root,Humanoid=humanoid,AutoRotate=humanoid.AutoRotate,
        Pose=pose,Ground=CFrame.new(ground),Valid=valid,Collisions={},Connections={},Instances={},At=os.clock()}
    lease=old
    local function remember(part)
        if part:IsA("BasePart") then old.Collisions[part]=part.CanCollide;part.CanCollide=false end
    end
    for _,part in ipairs(character:GetDescendants()) do remember(part) end
    old.Connections[#old.Connections+1]=character.DescendantAdded:Connect(remember)
    local attachment=Instance.new("Attachment");attachment.Name="SHARKWOW_UndergroundAttachment";attachment.Parent=root
    old.Instances[#old.Instances+1]=attachment
    local velocity=Instance.new("LinearVelocity");velocity.Name="SHARKWOW_UndergroundHold";velocity.Attachment0=attachment
    velocity.RelativeTo=Enum.ActuatorRelativeTo.World;velocity.VectorVelocity=Vector3.zero;velocity.ForceLimitsEnabled=false;velocity.Parent=root
    old.Instances[#old.Instances+1]=velocity
    humanoid.AutoRotate=false;root.CFrame=pose;root.AssemblyLinearVelocity=Vector3.zero;root.AssemblyAngularVelocity=Vector3.zero
    B.State.UndergroundLock={Owner=owner,Mode=mode,Range=range,Cover=best.Cover,Point=point,Position=best.Position,Idle=false}
    local function live()
        if lease~=old then return false end
        if old.Idle and not A.MovementFree() then U.Release(owner,false);return false end
        if not A.Current() or B.Player.Character~=character or not root.Parent or humanoid.Health<=0 or not valid() then U.Release(owner,true);return false end
        return true
    end
    old.Connections[#old.Connections+1]=Run.PreSimulation:Connect(function()
        if not live() then return end
        for part in pairs(old.Collisions) do if part.Parent then part.CanCollide=false end end
        root.AssemblyLinearVelocity=Vector3.zero;root.AssemblyAngularVelocity=Vector3.zero
    end)
    old.Connections[#old.Connections+1]=Run.PostSimulation:Connect(function()
        if not live() then return end
        if (root.Position-pose.Position).Magnitude>18 then U.Release(owner,false);return end
        root.CFrame=pose;root.AssemblyLinearVelocity=Vector3.zero;root.AssemblyAngularVelocity=Vector3.zero
        local state=B.State.UndergroundLock
        if state then state.ActualDistance=(root.Position-point).Magnitude;state.Pulses=(state.Pulses or 0)+1 end
    end)
    return best
end
A.Cleanups[#A.Cleanups+1]=function() U.Release(nil,true) end

    end)(advanced, bridge);
    (function(A, B)
local Http=game:GetService("HttpService")
local id="AutoCraftBizarre"
local owner=tostring(B.Player.UserId)
local ledgerFile="sharkwow-standout-bizarre-craft-"..owner..".json"
local legacyLedgerFile="sharkwow-standout-bizarre-craft.json"
local ledger,ownedSession,ownedBrowser,held,controller
local nextAttempt=0
local acquired=false
local function stockFull(count)
    local cap=B.State.BizarreStockCap or 9
    return type(cap)=="number" and count>=cap
end
local function writeLedger(record)
    assert(type(writefile)=="function","craft recovery storage unavailable")
    writefile(ledgerFile,Http:JSONEncode(record))
    ledger=record
end
local readLedgerFile=ledgerFile
if type(isfile)=="function" and not isfile(ledgerFile) and isfile(legacyLedgerFile) then readLedgerFile=legacyLedgerFile end
if type(isfile)=="function" and isfile(readLedgerFile) then
    local ok,data=pcall(function() return Http:JSONDecode(readfile(readLedgerFile)) end)
    if ok and type(data)=="table" and data.Owner==owner then ledger=data;if readLedgerFile~=ledgerFile then writeLedger(data) end
    elseif not ok then ledger={Owner=owner,Status="invalid"} end
end
local function counts()
    local inventory=B.State.ReadInventory()
    assert(inventory,"inventory not ready")
    return inventory["Mysterious Arrow"] or 0,inventory["Bizarre Arrow"] or 0
end
local function confirmed(record,arrows,bizarre)
    return record and type(record.Arrows)=="number" and type(record.Bizarre)=="number"
        and arrows<=record.Arrows-9 and bizarre>=record.Bizarre+1
end
local function reconcile()
    if not ledger or ledger.Status=="confirmed" or ledger.Status=="rejected" then B.State.CraftReconciliationPending=false;return true end
    local arrows,bizarre=counts()
    if confirmed(ledger,arrows,bizarre) then
        writeLedger({Owner=owner,Status="confirmed",At=os.time(),Arrows=arrows,Bizarre=bizarre})
        B.State.CraftReconciliationPending=false
        return true
    end
    B.State.CraftReconciliationPending=true
    A.Status="craft outcome unconfirmed; automatic retry stopped"
    return false
end
local function cleanup()
    if held then pcall(held.InputHoldEnd,held);held=nil end
    if controller and ownedSession and controller.Session==ownedSession then pcall(controller.Close,controller,true) end
    if controller and ownedBrowser and controller.Browser==ownedBrowser then pcall(controller.CloseBrowser,controller,true) end
    ownedSession=nil;ownedBrowser=nil
    if acquired then B.State.CraftBusy=false;B.State.ExtensionPause=false;acquired=false end
    if A.Underground then
        if A.Current() and A.Get(id) then A.Underground.Finish(id) else A.Underground.Release(id,true) end
    end
end
A.Add({Id=id,Name="auto craft bizarre arrow",Group="farm",Description="Every 9 Mysterious Arrows become 1 Bizarre Arrow below Big Chop's workbench. Locks position with noclip, verifies inventory, then resumes farming. Never uses the crafted arrow. Saved across reloads.",Fields={{Key="Reserve",Name="keep mysterious arrows",Default=0,Min=0,Max=999}}})
A.Features[id].Set=function(value)
    if value then
        assert(type(writefile)=="function","craft recovery storage unavailable")
        if not reconcile() then
            A.Options[id].ResumeWhenConfirmed=true
            A.Save()
            error("previous craft outcome unconfirmed; waiting for inventory confirmation")
        end
    end
    if value or not A.RestoringSettings then A.Options[id].ResumeWhenConfirmed=false end
    A.Options[id].ResumeEnabled=value
    A.Save()
end
A.Features[id].Enabled=A.Options[id].ResumeEnabled==true
B.State.CraftConfirmationWatchVersion=1
local function holdForConfirmation()
    A.Features[id].Enabled=false
    A.Options[id].ResumeEnabled=false
    A.Options[id].ResumeWhenConfirmed=true
    B.State.CraftReconciliationPending=true
    A.Save()
end
local function checkLateConfirmation()
    if not A.Options[id].ResumeWhenConfirmed then return end
    if getgenv().SHARKWOW_FLEET_PAUSED then return end
    if not reconcile() then return end
    local ok,err=A.Set(id,true)
    if ok then
        A.Features[id].Enabled=true
        A.Errors[id]=nil
        B.State.FarmCraftHold=nil
        B.State.CraftRecoveryStatus="late inventory confirmation received; crafting resumed"
    else A.Error(id,err) end
end
B.State.CheckCraftConfirmation=checkLateConfirmation

A.Cleanups[#A.Cleanups+1]=cleanup
local function current(character)
    return A.Current() and A.Get(id) and B.Player.Character==character and character.Parent
        and character:FindFirstChildOfClass("Humanoid").Health>0 and not B.State.TransferPending
end
local function waitFor(predicate,seconds,character)
    local deadline=os.clock()+seconds
    repeat
        assert(current(character),"craft cancelled")
        if predicate() then return true end
        task.wait(0.1)
    until os.clock()>=deadline
    return predicate()
end
local function craft()
    local character,root,humanoid=A.Character()
    if not character then return end
    acquired=true
    B.State.CraftBusy=true
    B.State.ExtensionPause=true
    if B.State.ReleaseIdleHide then B.State.ReleaseIdleHide() end
    local ok,err=pcall(function()
        assert(waitFor(function() return not B.State.AutoBusy and not B.State.RouteBusy and not B.State.TeleportBusy end,6,character),"farm did not yield")
        controller=require(B.Player.PlayerScripts.Core.Crafting)
        assert(not controller.Session and not controller.Pending and not controller.Browser,"another crafting interaction is open")
        local function station()
            local world=workspace:FindFirstChild("Game")
            local garden=world and world:FindFirstChild("Gardening")
            local stations=garden and garden:FindFirstChild("ProcessingStations")
            return stations and stations:FindFirstChild("Crafting")
        end
        local bench=station()
        if not bench then B.State.RequestStream(Vector3.new(-1777.389,28.126,851.942),3);bench=station() end
        assert(bench and bench:GetAttribute("StationId")=="SpawnGarden_Crafting","crafting bench not loaded")
        assert(not bench:GetAttribute("InUse"),"crafting bench is occupied")
        local mat=bench:FindFirstChild("WorkMat")
        local prompt=mat and mat:FindFirstChild("GardenCraft")
        assert(prompt and prompt.Enabled and prompt.HoldDuration<=5,"crafting prompt unavailable")
        assert(current(character),"craft cancelled")
        assert(A.Underground,"underground position module unavailable")
        A.Underground.Begin(id,character,root,humanoid,mat.Position,bench,math.min(9.25,prompt.MaxActivationDistance-.75),"craft",function() return current(character) end)
        task.wait(0.6)
        assert(current(character) and (root.Position-mat.Position).Magnitude<=prompt.MaxActivationDistance,"crafting out of range")
        held=prompt;A.Underground.Prompt(id,prompt,function() return current(character) end);held=nil
        assert(waitFor(function() return controller.Browser and controller.Browser.Model==bench end,5,character),"craft browser did not open")
        ownedBrowser=controller.Browser
        local arrows,bizarre=counts()
        if stockFull(bizarre) then A.Status="bizarre stock full; collecting normal arrows";return end
        assert(arrows>=9+math.floor(A.Options[id].Reserve),"waiting for 9 unreserved arrows")
        local record={Owner=owner,Status="requested",At=os.time(),Arrows=arrows,Bizarre=bizarre}
        writeLedger(record)
        assert(current(character),"craft cancelled")
        if not controller:Request("Bizarre Arrow",1) then
            record.Status="rejected";writeLedger(record);error("native crafting request rejected")
        end
        A.Status="crafting bizarre arrow"
        local deadline=os.clock()+45
        while os.clock()<deadline do
            local afterArrows,afterBizarre=counts()
            if confirmed(record,afterArrows,afterBizarre) then
                writeLedger({Owner=owner,Status="confirmed",At=os.time(),Arrows=afterArrows,Bizarre=afterBizarre})
                A.Metrics.BizarreCrafted=(A.Metrics.BizarreCrafted or 0)+1
                A.Errors[id]=nil
                A.Status="bizarre arrow crafted; farming resumes"
                return
            end
            assert(current(character),"craft cancelled; inventory reconciliation required")
            assert(A.Underground.Check(id),"underground crafting hold lost")
            local session=controller.Session
            if session then
                if not ownedSession then
                    assert(session.Payload.Recipe=="Bizarre Arrow" and session.Payload.Model==bench,"unexpected crafting session")
                    ownedSession=session
                end
                assert(session==ownedSession,"crafting session changed")
                local phase=session.Payload.Phase
                assert(phase=="Place" or phase=="Ready" or phase=="Success","unexpected craft phase: "..tostring(phase))
                if not session.Pending and phase~="Success" then controller:Act() end
            end
            task.wait(0.3)
        end
        error("craft inventory outcome unconfirmed; no repeated request")
    end)
    cleanup()
    nextAttempt=os.clock()+(ok and 5 or 20)
    if not ok then
        A.Error(id,err)
        if ledger and ledger.Status=="requested" then holdForConfirmation();A.Error(id,err) end
    end
end
A.Loop("bizarre crafting",1,function()
    checkLateConfirmation()
    if not A.Get(id) or os.clock()<nextAttempt or B.State.CraftBusy or B.State.ExtensionPause
        or B.State.Flying or B.State.TransferPending or B.State.AutoHopPause or B.State.HopBusy or A.GardenBusy() then return end
    for _,other in ipairs({"AutoFarm","AutoQuest","QuestFarm","BountyFarm","QuestTravel","AutoRoll","AutoPilot","ItemFarm"}) do if A.Get(other) then return end end
    if not reconcile() then holdForConfirmation();A.Error(id,"previous craft outcome unconfirmed; awaiting inventory confirmation");return end
    if B.State.AutoBusy or B.State.TeleportBusy or B.State.HasPriorityItems and B.State.HasPriorityItems() then return end
    local arrows,bizarre=counts()
    if stockFull(bizarre) then A.Status="bizarre stock full; collecting normal arrows";return end
    if arrows<9+math.floor(A.Options[id].Reserve) then return end
    craft()
end)

    end)(advanced, bridge);
    (function(A, B)
local RS=game:GetService("ReplicatedStorage")
local Http=game:GetService("HttpService")
-- Owner-confirmed inventory capacity differs from the client item definition.
local cap=9
B.State.BizarreStockCap=cap
B.State.BizarreStockVersion=2
local targets={}
for _,tier in ipairs(require(RS.Modules.Arrows).getPool())do
    if tier.rarity=="Pinnacle" then
        for _,entry in ipairs(tier.items)do targets[entry.name]=true end
    end
end
assert(next(targets),"pinnacle targets unavailable")
local file="sharkwow-bizarre-space-"..B.Player.UserId..".json"
local record
if isfile(file)then
    local ok,value=pcall(function()return Http:JSONDecode(readfile(file))end)
    if ok and type(value)=="table"then record=value else record={Status="unknown"}end
end
local used=setmetatable({},{__mode="k"})
local function save(value)writefile(file,Http:JSONEncode(value));record=value end
B.State.PrepareBizarrePickup=function(target,prompt,current)
    if target.name~="Bizarre Arrow"then return true end
    local inventory=B.State.ReadInventory()
    if not inventory then return false end
    local count=inventory["Bizarre Arrow"]or 0
    if count<cap then return true end
    if targets[B.Player.Data.Stand.Value]then
        B.State.BizarreStockStatus="pinnacle protected; full bizarre drop skipped"
        return false
    end
    if record and record.Status~="confirmed"then
        B.State.BizarreStockStatus="previous arrow use unconfirmed; stopped"
        return false
    end
    if used[target.instance]then return false end
    if not current()or not prompt.Parent or not prompt.Enabled or not target.instance:IsDescendantOf(workspace)then return false end
    local character=B.Player.Character
    local h=character and character:FindFirstChildOfClass("Humanoid")
    if not h or h.Health<h.MaxHealth*.5 or character:GetAttribute("ArrowUseToken")then return false end
    local item
    for _,entry in pairs(Http:JSONDecode(B.Player.Data.Stats.Inventory.Value))do
        if type(entry)=="table"and entry.Name=="Bizarre Arrow"and entry.ID and not entry.Bound then item=entry;break end
    end
    if not item then return false end
    used[target.instance]=true
    save({Status="requested",Before=count,At=os.time(),Job=game.JobId,Stand=B.Player.Data.Stand.Value})
    B.State.BizarreStockStatus="using one arrow for visible full-stack drop"
    RS.Remotes.Item:FireServer("Use",item.Name,item.ID)
    local started=os.clock()
    repeat
        task.wait(.2)
        if not current()or B.Player.Character~=character then return false end
        local after=B.State.ReadInventory()
        if after and(after["Bizarre Arrow"]or 0)==count-1 and not character:GetAttribute("ArrowUseToken")and os.clock()-started>=2 then
            save({Status="confirmed",After=after["Bizarre Arrow"]or 0,At=os.time(),Stand=B.Player.Data.Stand.Value})
            B.State.BizarreStockStatus=targets[B.Player.Data.Stand.Value]and"pinnacle obtained; further use stopped"or"one arrow used; collecting replacement"
            return prompt.Parent~=nil and prompt.Enabled and target.instance:IsDescendantOf(workspace)
        end
    until os.clock()-started>45
    B.State.BizarreStockStatus="arrow use unconfirmed; further use stopped"
    return false
end
A.Cleanups[#A.Cleanups+1]=function()B.State.PrepareBizarrePickup=nil end

    end)(advanced, bridge);
    (function(A, B)
local P=(function()
local P={}
function P.Prune(history,now,ttl,limit)
    local rows={}
    for job,at in pairs(history) do
        if type(job)=="string" and #job==36 and job:match("^[%x%-]+$") and type(at)=="number" and at==at and at<=now+60 and now-at<ttl then
            rows[#rows+1]={Job=job,At=at}
        end
    end
    table.sort(rows,function(a,b) return a.At>b.At end)
    local result={}
    for i=1,math.min(#rows,limit) do result[rows[i].Job]=rows[i].At end
    return result
end
function P.Eligible(job,current,history,now,ttl)
    return job~=current and (not history[job] or now-history[job]>=ttl)
end
function P.Ready(age,quiet,visited,total,loaded,minStay,quietTime,maxStay,waitOnly)
    if age<minStay or quiet<quietTime then return false end
    return age>=maxStay or (waitOnly or total>0 and visited>=total) and loaded==0
end
return P

end)()
local Http=game:GetService("HttpService")
local id="AutoHopArrows"
local path="sharkwow-standout-visited-servers.json"
local history={}
local started,lastGain=os.clock(),os.clock()
local priorCount=0
local generation,failures,nextTry=0,0,0
local pending=false
local function countArrows()
    local sum=0
    for name,amount in pairs(B.State.ReadInventory() or {}) do
        if B.State.ClassifyItem(name)=="arrow" then sum+=amount end
    end
    return sum
end
if type(isfile)=="function" and isfile(path) then
    local ok,data=pcall(function() return Http:JSONDecode(readfile(path)) end)
    if ok and type(data)=="table" and data.Place==game.PlaceId and type(data.Visited)=="table" then history=data.Visited end
end
local function saveHistory()
    local ttl=A.Options[id].RevisitHours*3600
    history[game.JobId]=os.time()
    history=P.Prune(history,os.time(),ttl,500)
    assert(type(writefile)=="function","server history storage unavailable")
    writefile(path,Http:JSONEncode({Place=game.PlaceId,Visited=history}))
end
local function status(message)
    B.State.AutoHopStatus=message
    A.Status=message
end
local function craftReady()
    if not A.Get("AutoCraftBizarre") or A.Errors.AutoCraftBizarre then return false end
    local inventory=B.State.ReadInventory() or {}
    return (inventory["Mysterious Arrow"] or 0)>=9+math.floor(A.Options.AutoCraftBizarre.Reserve)
end
local function blockers()
    if A.Get("AutoLevel20") or A.Get("AutoStory") then return true end
    if B.State.CraftBusy or A.GardenBusy() or B.State.Flying or B.State.TransferPending or craftReady() or B.State.PlayerWarpBusy or B.State.PartsStreamBusy or B.State.AutoParts and (B.State.Parts or 0)>0 then return true end
    for _,other in ipairs({"AutoFarm","AutoQuest","QuestFarm","BountyFarm","QuestTravel","AutoRoll","AutoPilot","ItemFarm"}) do if A.Get(other) then return true end end
    return false
end
A.Add({Id=id,Name="auto hop for arrows",Group="farm",Description="Patrols arrow points, collects items, then joins a different low-population server. Remembers up to 500 servers for 6 hours by default. Waits for crafting and gardening; saved across reloads.",Fields={
    {Key="MinStay",Name="minimum seconds per server",Default=45,Min=30,Max=600},
    {Key="Quiet",Name="seconds without a new arrow",Default=12,Min=5,Max=120},
    {Key="MaxStay",Name="retry another server after seconds",Default=180,Min=60,Max=900},
    {Key="RevisitHours",Name="avoid visited servers for hours",Default=6,Min=1,Max=24},
}})
A.Features[id].Set=function(value)
    if value then
        assert(B.State.EnsureResumeReady(),"teleport resume unavailable")
        saveHistory()
        B.State.SetAuto("arrow",true)
        started,lastGain=os.clock(),os.clock();priorCount=countArrows();nextTry=0;failures=0
    end
    generation+=1
    A.Options[id].ResumeEnabled=value
    assert(A.Save(),"auto-hop setting could not be saved")
    if not value and not B.State.HopBusy then B.State.AutoHopPause=false end
end
A.Features[id].Enabled=A.Options[id].ResumeEnabled==true
priorCount=countArrows()
history=P.Prune(history,os.time(),A.Options[id].RevisitHours*3600,500)
history[game.JobId]=os.time()
B.State.AutoHopStatus="waiting for arrow patrol"
A.Cleanups[#A.Cleanups+1]=function() generation+=1;B.State.AutoHopPause=false end
A.Loop("arrow server hopping",1,function()
    if pending then
        if B.State.HopBusy then return end
        pending=false;B.State.AutoHopPause=false
        failures+=1;nextTry=os.clock()+math.min(180,15*2^math.min(failures,4))
        status(B.State.HopStatus or "server hop retry delayed")
    end
    if not A.Get(id) or not B.State.AutoArrow or os.clock()<nextTry then return end
    local currentCount=countArrows()
    if currentCount>priorCount then lastGain=os.clock() end
    priorCount=currentCount
    if blockers() or B.State.HopBusy then return end
    local character=A.Character();if not character then return end
    local visited,total=0,0
    for _,node in pairs(B.State.ArrowRouteNodes or {}) do
        if node.enabled then total+=1;if node.visitedAt>0 then visited+=1 end end
    end
    local opts=A.Options[id]
    B.State.AutoHopCoverage={Visited=visited,Total=total}
    if not P.Ready(os.clock()-started,os.clock()-lastGain,visited,total,(B.State.Arrow or 0)+(B.State.Rokaka or 0),opts.MinStay,opts.Quiet,math.max(opts.MaxStay,opts.MinStay),B.State.WaitForArrow) then return end
    B.State.AutoHopPause=true
    local token=generation
    local function allowed()
        return A.Current() and A.Get(id) and generation==token and B.State.AutoArrow and not blockers()
    end
    local deadline=os.clock()+8
    while allowed() and (B.State.AutoBusy or B.State.TeleportBusy or B.State.RouteBusy) and os.clock()<deadline do task.wait(0.1) end
    if not allowed() or B.State.AutoBusy or B.State.TeleportBusy or B.State.RouteBusy then B.State.AutoHopPause=false;nextTry=os.clock()+5;return end
    local ok,err=pcall(saveHistory)
    if not ok then B.State.AutoHopPause=false;nextTry=os.clock()+30;A.Error(id,err);return end
    status("finding an unvisited arrow server")
    pending=B.State.HopLowServer({
        CanContinue=allowed,
        Accept=function(server) return P.Eligible(server.id,game.JobId,history,os.time(),opts.RevisitHours*3600) end,
        BeforeTransfer=function(server)
            assert(allowed(),"auto hop cancelled")
            history[server.id]=os.time();saveHistory()
            A.Errors[id]=nil
        end,
    })
    if not pending then B.State.AutoHopPause=false;nextTry=os.clock()+15 end
end)

    end)(advanced, bridge);
    (function(A, B)
local P=(function()
local P={}
function P.UserId(value)
    local text=tostring(value):match("^%s*(.-)%s*$")
    assert(text:match("^%d+$"),"Enter a numeric Roblox user ID, not a username")
    local id=tonumber(text)
    assert(id and id>0 and id<=9007199254740991 and id%1==0,"Invalid Roblox user ID")
    return id
end
function P.Username(value)
    local name=tostring(value):match("^%s*(.-)%s*$"):gsub("^@","")
    assert(#name>=3 and #name<=20 and name:match("^[%w_]+$"),"enter the Roblox username, not display name")
    return name
end
function P.Destination(place,job,expected)
    place=tonumber(place)
    assert(not place or place==expected,"Player is in a different game/place")
    assert(place and type(job)=="string" and #job==36 and job:match("^[%x%-]+$"),"Roblox did not share a joinable server; privacy or private-server access may apply")
    return {Place=place,Job=job}
end
return P

end)()
local Players=game:GetService("Players")
local Http=game:GetService("HttpService")
local id="JoinPlayer"
local generation,busy,cooldown=0,false,0
local function status(message) B.State.JoinPlayerStatus=message;A.Status=message end
local function bounded(name,callback,token)
    local done,result=false,nil
    local key="join lookup "..name
    local worker=task.spawn(function() result=table.pack(pcall(callback));done=true end)
    A.Workers[key]=worker
    local deadline=os.clock()+10
    while not done and A.Current() and token==generation and os.clock()<deadline do task.wait(0.05) end
    if not done then pcall(task.cancel,worker) end
    if A.Workers[key]==worker then A.Workers[key]=nil end
    assert(A.Current() and token==generation,"join cancelled")
    assert(done,"player lookup timed out")
    assert(result[1],tostring(result[2]))
    return table.unpack(result,2,result.n)
end
local function lookup(userId,token)
    local name=bounded("user ID",function() return Players:GetNameFromUserIdAsync(userId) end,token)
    local present=Players:GetPlayerByUserId(userId)
    if present then return {UserId=userId,Username=present.Name,Place=game.PlaceId,Job=game.JobId} end
    local ok,friends=pcall(function()
        return bounded("friends",function()
            local identity=type(getthreadidentity)=="function" and getthreadidentity() or nil
            if identity and type(setthreadidentity)=="function" then setthreadidentity(8) end
            local success,result=pcall(B.Player.GetFriendsOnlineAsync,B.Player,200)
            if identity and type(setthreadidentity)=="function" then setthreadidentity(identity) end
            assert(success,result);return result
        end,token)
    end)
    if ok and type(friends)=="table" then
        for _,friend in ipairs(friends) do
            if tonumber(friend.VisitorId)==userId and friend.IsOnline then
                local valid,dest=pcall(P.Destination,friend.PlaceId,friend.GameId,game.PlaceId)
                if valid then dest.UserId=userId;dest.Username=name;return dest end
            end
        end
    end
    local requester=request or http_request or (syn and syn.request)
    assert(type(requester)=="function","friend server unavailable and public lookup unsupported")
    local response=bounded("presence",function()
        return requester({Url="https://presence.roblox.com/v1/presence/users",Method="POST",Headers={["Content-Type"]="application/json"},Body=Http:JSONEncode({userIds={userId}}),Timeout=8})
    end,token)
    assert(type(response)=="table" and tonumber(response.StatusCode or response.Status)==200,"Roblox presence request failed (HTTP "..tostring(type(response)=="table"and(response.StatusCode or response.Status)or"unavailable")..")")
    local body=Http:JSONDecode(response.Body)
    for _,presence in ipairs(body.userPresences or {}) do
        if presence.userId==userId then
            assert(presence.userPresenceType==2,presence.userPresenceType==0 and "Player is offline" or "Player is online but not in a playable game")
            local dest=P.Destination(presence.placeId,presence.gameId,game.PlaceId)
            dest.UserId=userId;dest.Username=name;return dest
        end
    end
    error("Roblox did not share this player's server")
end
local function pauseForMeeting()
    A.Set("ArrowPartFarm",false)
    A.Set("AutoHopArrows",false)
    A.Set("AutoCraftBizarre",false)
    A.Set("GardenHarvest",false)
    B.State.SetAuto("arrow",false);B.State.SetAuto("rokaka",false)
end
local function requestJoin(join)
    if busy or B.State.HopBusy or B.State.TransferPending then status("Cannot check yet: another server request is running");return end
    if os.clock()<cooldown then status("Cannot check yet: wait "..math.ceil(cooldown-os.clock()).." seconds");return end
    local input=tostring(A.Options[id].UserId):match("^%s*(.-)%s*$")
    local numeric=input:match("^%d+$")~=nil
    local valid,userId=pcall(numeric and P.UserId or P.Username,input)
    if not valid then status("Cannot join: "..tostring(userId));return end
    local name=tostring(userId)
    B.State.JoinPlayerFound=nil
    generation+=1;local token=generation;busy=true;cooldown=os.clock()+5
    A.Errors[id]=nil;status("Checking user ID "..name.."...")
    A.Workers["join player request"]=task.spawn(function()
        local ok,err=pcall(function()
            if not numeric then userId=bounded("username",function()return Players:GetUserIdFromNameAsync(userId)end,token) end
            local dest=lookup(userId,token)
            name=dest.Username or tostring(userId)
            assert(A.Current() and token==generation,"join cancelled")
            B.State.JoinPlayerFound={Username=dest.Username,UserId=dest.UserId,Job=dest.Job}
            if not join then status(dest.Job==game.JobId and "@"..name.." is already in this server" or "Server found for @"..name.."; join can be attempted. Roblox verifies access when joining");return end
            assert(not B.State.CraftBusy and not A.GardenBusy(),"wait for crafting or gardening to finish")
            for _,other in ipairs({"AutoFarm","AutoQuest","QuestFarm","BountyFarm","QuestTravel","AutoRoll"}) do assert(not A.Get(other),"stop combat/quest/roll automation first") end
            local saved={Parts=A.Get("ArrowPartFarm"),Arrow=B.State.AutoArrow,Roka=B.State.AutoRokaka,Hop=A.Get("AutoHopArrows"),Craft=A.Get("AutoCraftBizarre"),Garden=A.Get("GardenHarvest")}
            if dest.Job==game.JobId then pauseForMeeting();status("already together; farming paused for transfer");return end
            B.State.AutoHopPause=true
            local deadline=os.clock()+8
            while A.Current() and token==generation and (B.State.AutoBusy or B.State.TeleportBusy) and os.clock()<deadline do task.wait(0.1) end
            assert(A.Current() and token==generation,"join cancelled")
            assert(not B.State.AutoBusy and not B.State.TeleportBusy,"farm did not yield")
            local started=B.State.HopLowServer({Target={id=dest.Job,playing=0},PauseFarm=true,Manual=true,
                CanContinue=function() return A.Current() and token==generation and not B.State.CraftBusy and not A.GardenBusy() end,
                BeforeTransfer=function() pauseForMeeting();status("joining @"..name) end,
                OnFailure=function(message)
                    if not A.Current() or token~=generation then return end
                    B.State.AutoHopPause=false
                    B.State.SetAuto("arrow",saved.Arrow);B.State.SetAuto("rokaka",saved.Roka);A.Set("ArrowPartFarm",saved.Parts)
                    A.Set("AutoCraftBizarre",saved.Craft);A.Set("GardenHarvest",saved.Garden);A.Set("AutoHopArrows",saved.Hop)
                    A.Error(id,message);status("Cannot join: "..tostring(message).."; previous farming restored")
                end,
            })
            assert(started,"server request is cooling down")
        end)
        if token==generation then busy=false end
        if not ok and A.Current() and token==generation then B.State.AutoHopPause=false;A.Error(id,err);status("Cannot join: "..tostring(err):sub(1,240)) end
    end)
end
A.Add({Id=id,Name="follow player to server",Group="move",Description="Enter a Roblox username or numeric user ID. Follows their accessible STAND OUT server and pauses farming.",Action=function() requestJoin(true) end,Fields={{Key="UserId",Name="username or user ID",Default="",Length=32}},Actions={
    {Name="check player server",Run=function() requestJoin(false) end},
    {Name="join player server",Run=function() requestJoin(true) end},
    {Name="cancel lookup",Run=function() generation+=1;busy=false;if not B.State.HopBusy then B.State.AutoHopPause=false end;status("lookup cancelled") end},
}})
local function cleanup() generation+=1;busy=false;B.State.AutoHopPause=false end
B.State.JoinPlayerCleanup=cleanup
A.Cleanups[#A.Cleanups+1]=cleanup

    end)(advanced, bridge);
    (function(A, B)
local id="WaitForArrow"
A.Add({Id=id,Name="wait hidden for arrows",Group="farm",Description="Waits at one hide spot instead of patrolling spawn points. Warps only for loaded collectibles, then returns here. Distant unstreamed items may not be visible. Craft/garden controls remain separate.",Get=function() return B.State.WaitForArrow==true end,Set=function(value)
    B.State.WaitForArrow=value
    A.Options[id].ResumeEnabled=value
    if value then B.State.SetFarmHide(true)
    else B.State.ReleaseIdleHide();B.State.IdleAnchor=nil end
    A.Save()
end,Actions={{Name="use current position as waiting spot",Run=function()
    B.State.ReleaseIdleHide();B.State.IdleAnchor=nil
    B.State.WaitHidden()
end}}})
if A.Options[id].NoPatrolVersion~=1 then
    A.Options[id].ResumeEnabled=true
    A.Options[id].NoPatrolVersion=1
end
B.State.WaitForArrow=A.Options[id].ResumeEnabled==true

    end)(advanced, bridge);
    (function(A, B)
local S=B.State
local Run=game:GetService("RunService")
local Players=game:GetService("Players")
local Paths=game:GetService("PathfindingService")
local Input=game:GetService("UserInputService")
local binding="SHARKWOW_QuietWalk_"..B.Player.UserId
local generation,route,planning,nextTry=0,nil,false,0
local resting,restCharacter,planningAt
local rejected={}
local releaseFarm=S.IdlePlatformBaseReleaseFarm or B.ReleaseFarmHold
local releaseIdle=S.IdlePlatformBaseReleaseIdle or S.ReleaseIdleHide
S.IdlePlatformBaseReleaseFarm=releaseFarm
S.IdlePlatformBaseReleaseIdle=releaseIdle
releaseIdle()
local function status(message)S.IdlePlatformStatus=message end
local function release()
    generation+=1;planning=false
    Run:UnbindFromRenderStep(binding)
    local old=route;route=nil
    if old and old.Humanoid.Parent and B.Player.Character==old.Character then old.Humanoid:Move(Vector3.zero,false)end
    resting=nil;restCharacter=nil
    S.IdlePlatformStanding=false;S.IdlePlatformFlying=false
end
local function destroy()
    release();S.QuietWaitTarget=nil
end
S.ReleaseIdleHide=function()release();releaseIdle()end
B.ReleaseFarmHold=function()release();releaseFarm()end
S.DestroyIdlePlatform=destroy
S.IdlePlatform=nil;S.IdlePlatformContext=B;S.IdlePlatformVersion=5
S.QuietWaitVersion=2
A.Cleanups[#A.Cleanups+1]=destroy
A.Connect(B.Player.CharacterRemoving,destroy)
local function eligible()
    return S.WaitForArrow and(S.AutoArrow or S.AutoRokaka)and not S.ExtensionPause
        and not S.RaidBusy and A.MovementFree()
end
local function crowd(point)
    local nearest=600
    for _,p in ipairs(Players:GetPlayers())do
        if p~=B.Player then
            local r=p.Character and p.Character:FindFirstChild("HumanoidRootPart")
            if r then nearest=math.min(nearest,(point-r.Position).Magnitude)end
        end
    end
    return nearest
end
local function pointKey(point)return string.format("%.0f:%.0f:%.0f",point.X/12,point.Y/12,point.Z/12)end
local function params()
    local ray=RaycastParams.new();ray.FilterType=Enum.RaycastFilterType.Include
    ray.FilterDescendantsInstances={workspace.Game.Map,workspace.Terrain};ray.RespectCanCollide=true
    return ray
end
local function floorAt(point,ray)
    local hit=workspace:Raycast(point+Vector3.new(0,80,0),Vector3.new(0,-180,0),ray)
    if not hit or hit.Normal.Y<.85 or hit.Material==Enum.Material.Water then return end
    if hit.Instance:IsA("BasePart")and not hit.Instance.Anchored then return end
    if hit.Position.Y<workspace.FallenPartsDestroyHeight+50 then return end
    for _,offset in ipairs({Vector3.new(2,0,0),Vector3.new(-2,0,0),Vector3.new(0,0,2),Vector3.new(0,0,-2)})do
        local edge=workspace:Raycast(hit.Position+offset+Vector3.new(0,3,0),Vector3.new(0,-6,0),ray)
        if not edge or edge.Material==Enum.Material.Water or edge.Normal.Y<.8 or math.abs(edge.Position.Y-hit.Position.Y)>1.5 then return end
    end
    if workspace:Raycast(hit.Position+Vector3.new(0,.2,0),Vector3.new(0,6,0),ray)then return end
    return hit.Position
end
local function candidates(root)
    local ray=params();local list={}
    local prior=S.QuietWaitTarget
    if prior and(prior-root.Position).Magnitude<350 and crowd(prior)>=80
        and(not rejected[pointKey(prior)]or rejected[pointKey(prior)]<os.clock())then
        local supported=floorAt(prior,ray)
        if supported and(supported-prior).Magnitude<3 then list[#list+1]={Point=supported,Score=1000}end
    end
    for _,radius in ipairs({80,140,220})do
        for angle=0,315,45 do
            local a=math.rad(angle+B.Player.UserId%45)
            local point=floorAt(root.Position+Vector3.new(math.cos(a)*radius,0,math.sin(a)*radius),ray)
            if point and crowd(point)>=80 and(not rejected[pointKey(point)]or rejected[pointKey(point)]<os.clock())then
                local nearNpc=false
                for _,npc in ipairs(workspace.Game.NPCs:GetChildren())do
                    local r=npc:FindFirstChild("HumanoidRootPart")
                    if r and(r.Position-point).Magnitude<35 then nearNpc=true;break end
                end
                if not nearNpc then
                    local cover=0
                    for _,direction in ipairs({Vector3.new(12,0,0),Vector3.new(-12,0,0),Vector3.new(0,0,12),Vector3.new(0,0,-12)})do
                        if workspace:Raycast(point+Vector3.new(0,3,0),direction,ray)then cover+=1 end
                    end
                    list[#list+1]={Point=point,Score=math.min(300,crowd(point))+cover*55-radius*.35}
                end
            end
        end
    end
    table.sort(list,function(a,b)return a.Score>b.Score end)
    return list
end
local function fail(message,point)
    if point then rejected[pointKey(point)]=os.clock()+120 end
    release();nextTry=os.clock()+30;status(message)
end
local function begin(c,r,h,points,goal,token)
    route={Character=c,Humanoid=h,Root=r,Points=points,Index=2,Goal=goal,Token=token,Last=r.Position,ProgressAt=os.clock(),Began=os.clock()}
    local owner=route
    S.QuietWaitTarget=goal
    Run:BindToRenderStep(binding,Enum.RenderPriority.Input.Value+1,function()
        if route~=owner or token~=generation then return end
        if not A.Current()or B.Player.Character~=c or h.Health<=0 or not eligible()then release();return end
        for _,key in ipairs({Enum.KeyCode.W,Enum.KeyCode.A,Enum.KeyCode.S,Enum.KeyCode.D})do
            if Input:IsKeyDown(key)and not Input:GetFocusedTextBox()then fail("quiet walk yielded to your movement",goal);return end
        end
        if r.Anchored or h.PlatformStand or h.SeatPart then fail("waiting for normal character movement",goal);return end
        if(r.Position-owner.Last).Magnitude>28 then fail("position changed; quiet walk stopped",goal);return end
        owner.Last=r.Position
        local waypoint=points[owner.Index]
        if not waypoint then
            release();resting=goal;restCharacter=c;S.IdlePlatformStanding=true
            S.QuietWaitArrivedAt=os.clock();status("waiting on real ground / not anchored");return
        end
        local delta=waypoint.Position-r.Position
        local flat=Vector3.new(delta.X,0,delta.Z)
        if flat.Magnitude<2.5 and math.abs(delta.Y)<6 then owner.Index+=1;owner.ProgressAt=os.clock();owner.Best=nil;return end
        if not owner.Best or flat.Magnitude<owner.Best-.3 then owner.Best=flat.Magnitude;owner.ProgressAt=os.clock()end
        if os.clock()-owner.ProgressAt>5 or os.clock()-owner.Began>70 then fail("path obstructed; will choose another quiet spot",goal);return end
        if h:GetState()==Enum.HumanoidStateType.Swimming then fail("water encountered; choosing dry ground",goal);return end
        h:Move(flat.Magnitude>.1 and flat.Unit or Vector3.zero,false)
        status(string.format("walking to quiet ground / %.0f studs",(r.Position-goal).Magnitude))
    end)
end
S.WaitHidden=function()
    if not eligible()or route or planning or os.clock()<nextTry then return end
    local c,r,h=A.Character();if not c or r.Anchored or h.PlatformStand or h.SeatPart then return end
    if resting and restCharacter==c then
        if(r.Position-resting).Magnitude<12 and crowd(r.Position)>=35 then return end
        resting=nil;S.IdlePlatformStanding=false;nextTry=os.clock()+5;return
    end
    if S.UndergroundLock then return end
    if S.QuietWaitTarget then
        local goal=S.QuietWaitTarget
        local floor=floorAt(goal,params())
        if not floor or (floor-goal).Magnitude>3 then
            status("waiting for saved hiding spot to load")
            nextTry=os.clock()+5
            if S.RequestStream then S.RequestStream(goal,2) end
            return
        end
        releaseFarm();releaseIdle()
        r.AssemblyLinearVelocity=Vector3.zero
        c:PivotTo(CFrame.new(floor+Vector3.new(0,h.HipHeight+r.Size.Y/2+.2,0)))
        resting=goal;restCharacter=c;S.IdlePlatformStanding=true
        S.QuietWaitReturns=(S.QuietWaitReturns or 0)+1
        status("returned to saved hiding spot; waiting for loaded items")
        return
    end
    releaseFarm();releaseIdle()
    generation+=1;local token=generation
    planning=true;planningAt=os.clock();status("finding quiet, walkable ground")
    A.Workers["quiet path"]=task.spawn(function()
        local ok,err=pcall(function()
            for index,entry in ipairs(candidates(r))do
                if index>5 then break end
                if token~=generation or not A.Current()or not eligible()then return end
                local path=Paths:CreatePath({AgentRadius=2,AgentHeight=5,AgentCanJump=false,WaypointSpacing=5,Costs={Water=math.huge}})
                local computed=pcall(path.ComputeAsync,path,r.Position,entry.Point)
                if token~=generation or not A.Current()or not eligible()then return end
                if computed and path.Status==Enum.PathStatus.Success then
                    local points=path:GetWaypoints()
                    if #points>=2 then planning=false;begin(c,r,h,points,entry.Point,token);return end
                end
            end
            if token==generation then fail("no quiet walkable spot nearby; staying on current ground")end
        end)
        if not ok and token==generation then A.Error("quiet path",err);fail("quiet path unavailable; staying on current ground")end
        if token==generation then planning=false end
    end)
end
A.Features.WaitForArrow.Name="quiet ground waiting spot"
A.Features.WaitForArrow.Description="Chooses one supported quiet spot. Waits without patrol teleports, collects detected items, then teleports back to that same spot. Distant unstreamed items cannot be detected."
A.Features.WaitForArrow.Actions={{Name="choose another quiet spot",Run=function()if resting then rejected[pointKey(resting)]=os.clock()+120 end;destroy();nextTry=0 end}}
A.Loop("idle platform",.5,function()
    if not eligible()then
        if route or planning or resting then release();status("waiting for farming movement to be free")end
        return
    end
    if planning and os.clock()-planningAt>12 then fail("path search timed out; staying on current ground");return end
    S.WaitHidden()
end)

    end)(advanced, bridge);
    (function(A, B)
local P=(function()
local P={}
function P.IsPart(name)
    return type(name)=="string" and name:lower():gsub("^%s+",""):gsub("%s+$","")=="arrow part"
end
function P.OwnerAllowed(object,userId,boundary)
    local node=object
    for _=1,12 do
        if not node or node==boundary then return true end
        for _,key in ipairs({"OwnerUserId","GardenOwnerId","OwnerId","StoryOwnerUserId"}) do
            local owner=tonumber(node:GetAttribute(key))
            if owner and owner>0 and owner~=userId then return false end
        end
        node=node.Parent
    end
    return false
end
function P.PromptAllowed(prompt)
    if not prompt:IsA("ProximityPrompt") or not prompt.Enabled or prompt:GetAttribute("StoryPromptAvailable")==false then return false end
    local duration=prompt.HoldDuration
    if type(duration)~="number" or duration~=duration or duration<0 or duration>15 then return false end
    local action=(prompt.ActionText.." "..prompt.Name):lower()
    return action:find("collect",1,true)~=nil or action:find("pickup",1,true)~=nil
        or action:find("pick up",1,true)~=nil or action:find("take",1,true)~=nil
end
function P.LootEvent(event)
    if type(event)~="table" or event.Phase~="Loot" then return false end
    return event.Id=="Meteor" or type(event.Id)=="string" and event.Id:match("^RainMeteor%d+$")~=nil
end
return P

end)()
local id="ArrowPartFarm"
local generation=0
local attempts={}
local native
A.Add({Id=id,Name="auto arrow part",Group="farm",Description="Collects loose Arrow Parts already loaded in the world. Seeking meteor event areas is a separate option, off by default.",Fields={{Key="MeteorLoot",Name="seek meteor loot areas",Default=false}},Get=function() return B.State.AutoParts==true end,Set=function(value)
    generation+=1
    B.State.SetAuto("part",value)
    if value and B.State.WaitHidden then B.State.WaitHidden() end
    A.Options[id].ResumeEnabled=value
    if not value then B.State.PartsStreamBusy=false end
    A.Save()
end})
B.State.AutoParts=A.Options[id].ResumeEnabled==true
if B.State.HoldForJoin then B.State.AutoParts=false end
A.Cleanups[#A.Cleanups+1]=function() generation+=1;B.State.PartsStreamBusy=false end
local function points(event)
    local result={}
    local function add(point)
        if typeof(point)~="Vector3" or point.X~=point.X or point.Y~=point.Y or point.Z~=point.Z or point.Magnitude==math.huge then return end
        for _,old in ipairs(result) do if (old-point).Magnitude<60 then return end end
        if #result<12 then result[#result+1]=point end
    end
    for _,meteor in ipairs(event.Meteors or {}) do if type(meteor)=="table" then add(meteor.Position) end end
    add(event.Position)
    for _,point in ipairs(event.Positions or {}) do add(point) end
    return result
end
A.Loop("arrow part events",2,function()
    if not A.Get(id) or B.State.TransferPending or B.State.AutoHopPause or B.State.HopBusy then return end
    if A.Options[id].MeteorLoot~=true then
        B.State.PartEventStatus="loose arrow parts only / meteor search off"
        return
    end
    native=native or require(B.Player.PlayerScripts.Core.WorldEvents)
    local aliveEvents={}
    local states={}
    for eventId,object in pairs(native.Active or {}) do
        for index,meteor in ipairs(object.Meteors or {}) do
            if not meteor.Dead then states[tostring(eventId)..":"..index]=meteor.State end
        end
    end
    for eventId,event in pairs(states) do
        if P.LootEvent(event) then
            aliveEvents[eventId]=true
            local destinations=points(event)
            local record=attempts[eventId] or {Count=0,Next=0,Index=1}
            attempts[eventId]=record
            if #destinations>0 and record.Count<#destinations*3 and os.clock()>=record.Next then
                local point=destinations[record.Index]
                record.Index=record.Index%#destinations+1
                record.Count+=1;record.Next=os.clock()+10
                local token=generation
                B.State.PartsStreamBusy=true
                local ok,reason=B.State.RequestStream(point,2)
                if not A.Current() or token~=generation or not A.Get(id) then B.State.PartsStreamBusy=false;return end
                B.State.PartsStreamBusy=false
                B.State.PartEventStatus=ok and "meteor loot area requested" or "meteor area unavailable: "..tostring(reason)
                return
            end
        end
    end
    for eventId in pairs(attempts) do if not aliveEvents[eventId] then attempts[eventId]=nil end end
    B.State.PartEventStatus=next(aliveEvents) and "watching meteor loot" or "waiting for arrow parts"
end)

    end)(advanced, bridge);
    (function(A, B)
local Players=game:GetService("Players")
local id="WarpPlayer"
local generation=0
local saved
local departed={}
local worker
local function roster()
    local list={}
    for _,player in ipairs(Players:GetPlayers()) do
        if player~=B.Player and not departed[player] then
            local character=player.Character
            local root=character and character:FindFirstChild("HumanoidRootPart")
            local humanoid=character and character:FindFirstChildOfClass("Humanoid")
            list[#list+1]={Id=player.UserId,Username=player.Name,DisplayName=player.DisplayName,Ready=root~=nil and humanoid~=nil and humanoid.Health>0}
        end
    end
    table.sort(list,function(a,b) return a.Username:lower()<b.Username:lower() end)
    return list
end
A.ServerPlayers=roster
local farmIds={"ArrowFarm","Rokaka","ArrowPartFarm","AutoCraftBizarre","AutoHopArrows","GardenHarvest"}
local function restore()
    if not saved then return end
    local original=saved;saved=nil
    for _,featureId in ipairs(farmIds) do
        local ok,reason=A.Set(featureId,original[featureId])
        if not ok then A.Error(id,"resume "..featureId..": "..tostring(reason)) end
    end
end
function A.WarpToPlayer(userId)
    assert(not worker or coroutine.status(worker)=="dead","player teleport is already running")
    assert(type(userId)=="number" and userId~=B.Player.UserId,"choose another player")
    generation+=1
    local token=generation
    worker=task.spawn(function()
        local paused=false
        local locked=false
        local function current() return A.Current() and generation==token and not B.State.TransferPending end
        local ok,reason=pcall(function()
            assert(not B.State.HopBusy and not B.State.AutoHopPause and not B.State.CraftBusy and not A.GardenBusy(),"wait for the current craft, garden or server transfer")
            for _,featureId in ipairs({"AutoFarm","AutoQuest","QuestFarm","BountyFarm","QuestTravel","AutoRoll","ItemFarm"}) do
                assert(not A.Get(featureId),"stop "..featureId.." before player teleport")
            end
            local target=Players:GetPlayerByUserId(userId)
            assert(target and not departed[target],"player left this server")
            local targetCharacter=target.Character
            local targetRoot=targetCharacter and targetCharacter:FindFirstChild("HumanoidRootPart")
            local targetHumanoid=targetCharacter and targetCharacter:FindFirstChildOfClass("Humanoid")
            assert(targetRoot and targetHumanoid and targetHumanoid.Health>0,"player character is not loaded or is respawning")
            local character,root,humanoid=A.Character()
            assert(character,"wait for your character to respawn")
            B.State.PlayerWarpBusy=true;B.State.AutoHopPause=true;locked=true
            local deadline=os.clock()+8
            while current() and (B.State.AutoBusy or B.State.TeleportBusy or B.State.RouteBusy) and os.clock()<deadline do task.wait(0.1) end
            assert(current() and not B.State.AutoBusy and not B.State.TeleportBusy and not B.State.RouteBusy,"farm did not yield")
            B.State.RequestStream(targetRoot.Position,2)
            assert(current() and B.Player.Character==character and humanoid.Health>0,"teleport cancelled")
            assert(target.Parent==Players and target.Character==targetCharacter and targetRoot.Parent and targetHumanoid.Health>0,"target left or respawned")
            local destination=B.LandingPosition(targetRoot.Position,targetCharacter,character,root,humanoid)
            assert(destination,"no clear supported ground beside this player")
            assert(not humanoid.SeatPart,"stand up before teleporting")
            if not saved then
                saved={}
                for _,featureId in ipairs(farmIds) do saved[featureId]=A.Get(featureId)==true end
            end
            paused=true
            for _,featureId in ipairs(farmIds) do assert(A.Set(featureId,false)) end
            B.State.AutoHopPause=true
            if B.State.Flying then B.SetFly(false) end
            if B.State.ReleaseIdleHide then B.State.ReleaseIdleHide() end
            assert(not root.Anchored,"character movement is locked")
            local pivotOffset=root.CFrame:ToObjectSpace(character:GetPivot())
            character:PivotTo(CFrame.new(destination)*root.CFrame.Rotation*pivotOffset)
            root.AssemblyLinearVelocity=Vector3.zero;root.AssemblyAngularVelocity=Vector3.zero
            task.wait(1.5)
            assert(current() and B.Player.Character==character and humanoid.Health>0,"character changed during teleport")
            assert(target.Parent==Players and target.Character==targetCharacter and targetRoot.Parent,"target left or respawned during teleport")
            assert((root.Position-destination).Magnitude<=12,"teleport position was corrected")
            A.Metrics.PlayerWarps=(A.Metrics.PlayerWarps or 0)+1
            B.State.LastPlayerWarp={UserId=userId,Username=target.Name,Distance=(root.Position-targetRoot.Position).Magnitude,Verified=true}
            A.Errors[id]=nil
            A.Status="near @"..target.Name.." / farming paused"
        end)
        if A.Current() and generation==token then
            if locked then B.State.PlayerWarpBusy=false;B.State.AutoHopPause=false end
            if not ok then
                if paused then restore() end
                A.Error(id,reason)
            end
        end
    end)
    A.Workers["player teleport action"]=worker
end
A.Add({Id=id,Name="warp to player",Group="move",Description="Choose a player in this server. Farming pauses after a successful warp. Players without a loaded character cannot be targeted yet.",Action=function() if A.OpenFeature then A.OpenFeature(id) end end,
    Actions={{Name="resume previous farming",Run=function() assert(not B.State.PlayerWarpBusy,"wait for player teleport");restore();A.Status="previous farming restored" end}},
    ListActions=function()
        local actions={}
        for _,entry in ipairs(roster()) do
            local userId=entry.Id
            actions[#actions+1]={Name=entry.DisplayName.." (@"..entry.Username..")"..(entry.Ready and "" or " / not loaded"),Run=function() A.WarpToPlayer(userId) end}
        end
        return actions
    end})
local function changed()
    if A.RefreshPlayerList then A.RefreshPlayerList() end
end
A.Connect(Players.PlayerAdded,function(player) departed[player]=nil;changed() end)
A.Connect(Players.PlayerRemoving,function(player) departed[player]=true;changed() end)
local signature=""
A.Loop("player roster",2,function()
    local fields={}
    for _,entry in ipairs(roster()) do fields[#fields+1]=tostring(entry.Id)..":"..tostring(entry.Ready) end
    local value=table.concat(fields,",")
    if value~=signature then signature=value;changed() end
end)
A.Cleanups[#A.Cleanups+1]=function()
    generation+=1
    if B.State.PlayerWarpBusy then B.State.PlayerWarpBusy=false;B.State.AutoHopPause=false end
end

    end)(advanced, bridge);
    (function(A, B)
local Policy=(function()
local Policy = {}
function Policy.stage(s)
    if not s.InventoryReady then return "loading" end
    if (s.Phone or 0) > 0 then return "complete" end
    if s.Finished then
        if s.Active.P9_01_MEET_MERYL then return "meryl" end
        return "waiting for phone quest"
    end
    if s.Step <= 3 then return s.Step == 2 and "movement" or "intro" end
    if s.Active["DEFEAT AGENT"] then return "cop" end
    if s.Active.TUTORIAL_MEET_JODIO then return "jodio" end
    if s.Active.TUTORIAL_FIND_ARROW then return "sand" end
    if s.Step == 5 then return "first stand" end
    if s.Step == 6 then return "summon" end
    if s.Step == 7 then return "ex skill" end
    if s.Step == 8 then return "archive and stats" end
    if s.Step >= 9 then return "finish tutorial" end
    return "waiting for tutorial quest"
end
function Policy.ownedCop(attrs, userId, name)
    return attrs.TutorialCop == true and tonumber(attrs.TutorialCopOwner) == userId
        and (not attrs.ForcedTargetName or attrs.ForcedTargetName == name)
end
function Policy.choice(stage, title, text, phone)
    if (phone or 0) > 0 then return false end
    if stage == "jodio" and (title == "jodio" or title == "stranger") then
        return text == "what happened here?" or text == "i'll keep that in mind." or text == "i'll take a look."
    end
    return stage == "meryl" and (title == "meryl mei qi" or title == "meryl") and text == "i'm in."
end
return Policy

end)()
local CopLock=(function()
return function(A,B,Policy,options)
    options=options or {}
    local prefix=options.Prefix or "PhoneCop"
    local Run=game:GetService("RunService")
    local lock
    local retry=setmetatable({},{__mode="k"})
    local C={Version=2}
    A[options.Store or "PhoneCopLock"]=C
    local function shape(native)
        if not debug or type(debug.getupvalues)~="function" then return end
        for _,profile in pairs(debug.getupvalues(native.lightSwing)) do
            if type(profile)=="table" and type(profile.M1Hitbox)=="table" and #profile.M1Hitbox>0 then
                local boxes={}
                for i,size in ipairs(profile.M1Hitbox) do
                    if typeof(size)~="Vector3" or size.X<=0 or size.Y<=0 or size.Z<=0 or size.Magnitude>100 then return end
                    local offset=profile.M1HitboxOffsets and profile.M1HitboxOffsets[i] or CFrame.new(0,0,-size.Z/2)
                    if typeof(offset)~="CFrame" then return end
                    boxes[#boxes+1]={Size=size,Offset=offset}
                end
                return boxes
            end
        end
    end
    function C.Release()
        local old=lock
        if not old then return end
        lock=nil
        for _,connection in ipairs(old.Connections) do connection:Disconnect() end
        for _,object in ipairs(old.Objects) do object:Destroy() end
        for part,value in pairs(old.Collisions) do if part.Parent then part.CanCollide=value end end
        if old.Root.Parent then
            old.Root.AssemblyLinearVelocity=Vector3.zero;old.Root.AssemblyAngularVelocity=Vector3.zero
            if B.Player.Character==old.Character then
                local position=old.Root.Position
                local look=old.TargetRoot.Parent and old.TargetRoot.CFrame.LookVector or Vector3.new(0,0,-1)
                old.Root.CFrame=CFrame.lookAt(position,position+Vector3.new(look.X,0,look.Z))
                old.Humanoid.AutoRotate=old.AutoRotate
            end
        end
        B.State[prefix.."LockActive"]=false
    end
    function C.Begin(target,native,current)
        if lock and lock.Target==target and lock.Character==B.Player.Character
            and target:FindFirstChild("HumanoidRootPart")==lock.TargetRoot
            and target:FindFirstChildOfClass("Humanoid")==lock.TargetHumanoid
            and lock.Character:FindFirstChild("HumanoidRootPart")==lock.Root
            and lock.Character:FindFirstChildOfClass("Humanoid")==lock.Humanoid
            and target.Parent and lock.TargetHumanoid.Health>0 and current()then lock.Valid=current;return true end
        C.Release()
        if not target.Parent or not current()then return false end
        if (retry[target] or 0)>os.clock() then return false end
        if not Policy.ownedCop(target:GetAttributes(),B.Player.UserId,B.Player.Name) then return false end
        local character,root,humanoid=A.Character()
        local targetRoot=target:FindFirstChild("HumanoidRootPart")
        local targetHumanoid=target:FindFirstChildOfClass("Humanoid")
        local boxes=shape(native)
        if not character or root.Anchored or not targetRoot or not targetHumanoid or targetHumanoid.Health<=0 or not boxes then return false end
        local params=OverlapParams.new();params.FilterType=Enum.RaycastFilterType.Include;params.FilterDescendantsInstances={targetRoot};params.MaxParts=1
        local old={Target=target,TargetRoot=targetRoot,TargetHumanoid=targetHumanoid,Character=character,Root=root,Humanoid=humanoid,AutoRotate=humanoid.AutoRotate,Collisions={},Objects={},Connections={},Valid=current,Height=options.Height or 4.75,Started=os.clock(),HP=targetHumanoid.Health,LastDamage=os.clock()}
        old.Offset=targetRoot.CFrame:VectorToWorldSpace(Vector3.new(0,0,options.Distance or 3))
        old.Distance=options.Distance or 3
        old.Depth=options.Depth or 5.5
        old.DepthStepAt=os.clock()
        old.PlayerHP=humanoid.Health
        local floorParams
        if options.Mode=="below"then
            floorParams=RaycastParams.new();floorParams.FilterType=Enum.RaycastFilterType.Include
            floorParams.FilterDescendantsInstances={workspace.Game.Map}
        end
        local function pose()
            if options.Mode=="below"then
                local position=targetRoot.Position-Vector3.new(0,old.Depth,0)
                local floor=workspace:Raycast(targetRoot.Position,Vector3.new(0,-32,0),floorParams)
                if not floor or floor.Position.Y-position.Y<1.25 then return nil end
                return CFrame.lookAt(position,targetRoot.Position,targetRoot.CFrame.RightVector)
            end
            if options.Mode=="behind" then
                if options.ResolveBehind then return options.ResolveBehind(targetRoot,old.Distance)end
                local offset=options.FollowFacing and targetRoot.CFrame:VectorToWorldSpace(Vector3.new(0,0,old.Distance))or old.Offset
                local position=targetRoot.Position+offset
                return CFrame.lookAt(position,targetRoot.Position)
            end
            local position=targetRoot.Position+Vector3.new(0,old.Height,0)
            return CFrame.lookAt(position,targetRoot.Position,targetRoot.CFrame.RightVector)
        end
        local function overlaps(at)
            for _,box in ipairs(boxes) do
                if options.Overlap then
                    if not options.Overlap(at*box.Offset,box.Size,targetRoot.CFrame,targetRoot.Size)then return false end
                elseif #workspace:GetPartBoundsInBox(at*box.Offset,box.Size,params)==0 then return false end
            end
            return true
        end
        local initialPose=pose()
        if options.Mode=="behind"and options.AdaptDistance then
            initialPose=nil
            for distance=old.Distance,3,-.25 do
                old.Distance=distance
                local candidate=pose()
                if candidate and overlaps(candidate)then
                    old.Distance=math.max(3,distance-.25);initialPose=pose();break
                end
            end
        end
        if options.Mode=="below" and options.MaxDepth then
            initialPose=nil
            for depth=options.MaxDepth,options.Depth or 5.5,-.25 do
                old.Depth=depth
                local candidate=pose()
                if candidate and overlaps(candidate)then
                    old.Depth=math.max(options.Depth or 5.5,depth-.35)
                    initialPose=pose();break
                end
            end
        end
        if not initialPose or not overlaps(initialPose)or(options.ValidatePose and not options.ValidatePose(initialPose,targetRoot))then return false end
        lock=old
        local attachment=Instance.new("Attachment");attachment.Name="SHARKWOW"..prefix.."Hold";attachment.Parent=root;old.Objects[#old.Objects+1]=attachment
        local velocity=Instance.new("LinearVelocity");velocity.Name="SHARKWOW"..prefix.."Hold";velocity.Attachment0=attachment;velocity.RelativeTo=Enum.ActuatorRelativeTo.World;velocity.MaxForce=math.huge;velocity.VectorVelocity=Vector3.zero;velocity.Parent=root;old.Objects[#old.Objects+1]=velocity
        humanoid.AutoRotate=false
        local telemetry={Version=2,Target=target.Name,Owner=B.Player.UserId,Mode=options.Mode or "above",Distance=options.Mode=="behind" and old.Distance or nil,Depth=options.Mode=="below" and old.Depth or nil,Height=old.Height,Before=old.HP,After=old.HP,Damage=0,IncomingDamage=0,PlayerBefore=humanoid.Health,PlayerAfter=humanoid.Health,Started=old.Started}
        B.State[prefix.."Result"]=telemetry;B.State[prefix.."LockActive"]=true
        local function pulse()
            if lock~=old then return end
            telemetry.PlayerAfter=humanoid.Health
            if humanoid.Health<old.PlayerHP then
                telemetry.IncomingDamage+=old.PlayerHP-humanoid.Health
                if options.RetreatOnDamage then
                    telemetry.Result="incoming damage; retreating";retry[target]=os.clock()+30;C.Release();return
                end
            end
            old.PlayerHP=humanoid.Health
            if not A.Current() or not old.Valid() or B.Player.Character~=character or not root.Parent or humanoid.Health<=0
                or not target.Parent or not targetRoot.Parent or targetHumanoid.Health<=0
                or target:FindFirstChild("HumanoidRootPart")~=targetRoot or target:FindFirstChildOfClass("Humanoid")~=targetHumanoid
                or character:FindFirstChild("HumanoidRootPart")~=root or character:FindFirstChildOfClass("Humanoid")~=humanoid
                or not Policy.ownedCop(target:GetAttributes(),B.Player.UserId,B.Player.Name) then
                telemetry.After=targetHumanoid.Health;telemetry.Damage=math.max(0,telemetry.Before-telemetry.After);C.Release();return
            end
            if targetHumanoid.Health<old.HP then old.LastDamage=os.clock() end
            old.HP=targetHumanoid.Health
            telemetry.After=targetHumanoid.Health;telemetry.Damage=math.max(0,telemetry.Before-telemetry.After)
            if os.clock()-old.LastDamage>5 then old.Height=options.FallbackHeight or 4;telemetry.Height=old.Height end
            if options.Mode=="below" and options.AdaptDepth and os.clock()-old.LastDamage>3
                and os.clock()-old.DepthStepAt>3 and old.Depth>(options.Depth or 5.5)then
                local previousDepth=old.Depth
                old.Depth=math.max(options.Depth or 5.5,old.Depth-.25)
                local candidate=pose()
                if not candidate or not overlaps(candidate)then old.Depth=previousDepth end
                old.DepthStepAt=os.clock();telemetry.Depth=old.Depth
            end
            if os.clock()-old.LastDamage>(options.NoDamageTimeout or 12) then telemetry.Result="no damage; released";retry[target]=os.clock()+30;C.Release();return end
            local at=pose()
            if not at then telemetry.Result="no supported underground attack position";C.Release();return end
            if options.ValidatePose and not options.ValidatePose(at,targetRoot)then telemetry.Result="unsafe target position";C.Release();return end
            if options.Mode=="behind" and options.AdaptDistance and not overlaps(at)then
                for distance=old.Distance-.25,3,-.25 do
                    old.Distance=distance
                    local candidate=pose()
                    if candidate and overlaps(candidate)and(not options.ValidatePose or options.ValidatePose(candidate,targetRoot))then
                        at=candidate;telemetry.Distance=distance;break
                    end
                end
            end
            if not overlaps(at) then telemetry.Result="target outside native hitbox";C.Release();return end
            for _,part in ipairs(character:GetDescendants()) do
                if part:IsA("BasePart") then
                    if old.Collisions[part]==nil then old.Collisions[part]=part.CanCollide end
                    part.CanCollide=false
                end
            end
            root.AssemblyLinearVelocity=Vector3.zero;root.AssemblyAngularVelocity=Vector3.zero;root.CFrame=at
        end
        local function safePulse()
            local owned=lock==old
            local ok,err=pcall(pulse)
            if not ok then C.Release();A.Error(options.Error or "phone cop lock",err) end
            if owned and lock~=old and type(C.OnLost)=="function"then
                local good,reason=pcall(C.OnLost)
                if not good then A.Error(options.Error or "target lock cleanup",reason)end
            end
        end
        old.Connections[#old.Connections+1]=Run.PreSimulation:Connect(safePulse)
        old.Connections[#old.Connections+1]=Run.PostSimulation:Connect(safePulse)
        safePulse()
        return lock==old
    end
    A.Cleanups[#A.Cleanups+1]=C.Release
    return C
end

end)()(A,B,Policy)
local ownedAttack
local Http=game:GetService("HttpService")
local RS=game:GetService("ReplicatedStorage")
local player=B.Player
local path="sharkwow-standout-phone-"..player.UserId..".json"
local ledger={Schema=1,UserId=player.UserId,Enabled=false}
if type(readfile)=="function" then
    local ok,data=pcall(function() return Http:JSONDecode(readfile(path)) end)
    if ok and type(data)=="table" and data.Schema==1 and data.UserId==player.UserId then ledger=data end
end
local generation,held,acquired=0,nil,false
local nextAction,stageAt,lastStage=0,os.clock(),nil
local paused={"AutoFarm","AutoQuest","QuestFarm","BountyFarm","QuestTravel","AutoDialogue","AutoRoll","ItemFarm","AutoHopArrows","AutoCraftBizarre","AutoPilot","AutoSkills","AutoSummon","AutoBlock","AutoParry","AutoDash"}
local function save()
    assert(type(writefile)=="function","phone resume storage unavailable")
    writefile(path,Http:JSONEncode(ledger))
end
local function current(token)
    return A.Current() and A.Get("AutoPhone") and token==generation
end
local function snapshot()
    local data=player:FindFirstChild("Data")
    local stats=data and data:FindFirstChild("Stats")
    local inventory=B.State.ReadInventory()
    local active={}
    if stats and stats:FindFirstChild("ActiveQuest") then
        for id in stats.ActiveQuest.Value:gmatch("[^,]+") do active[id]=true end
    end
    return {InventoryReady=inventory~=nil and stats~=nil,Phone=inventory and inventory.Phone or 0,
        Active=active,Finished=stats and stats:FindFirstChild("TutorialFinished") and stats.TutorialFinished.Value==true,
        Step=data and tonumber(data:GetAttribute("TutorialStep")) or stats and stats:FindFirstChild("TutorialProgress") and stats.TutorialProgress.Value or 1}
end
local function releaseHold()
    if held then pcall(held.InputHoldEnd,held);held=nil end
end
local function cleanup()
    generation+=1;releaseHold();B.State.PhoneBusy=false;acquired=false
    CopLock.Release()
    if ownedAttack then
        pcall(ownedAttack.cancelAttacksForStandReplacement,ownedAttack)
        pcall(ownedAttack.finishBasicAttack,ownedAttack,true)
        ownedAttack=nil
    end
    local menus=player.PlayerGui:FindFirstChild("Menus")
    if menus and menus:FindFirstChild("CloseRequested") then menus.CloseRequested:Fire() end
    local n=A.Native()
    if n then
        if n:getStates().Piloting then pcall(n.pilot,n,false) end
        if ledger.PreviousEX~=nil then pcall(n.setEXMode,n,ledger.PreviousEX) end
    end
end
local function finish()
    if snapshot().Phone<1 then return end
    ledger.Enabled=false;ledger.Handoff=true;ledger.Completed=true;ledger.CompletedAt=os.time();ledger.ArrowPending=nil
    save()
    A.Features.AutoPhone.Enabled=false
    cleanup()
    for _,id in ipairs({"AutoQuest","QuestFarm","BountyFarm","QuestTravel","AutoFarm","AutoDialogue"}) do
        if A.Features[id] and A.Get(id) then A.Set(id,false) end
    end
    local d=require(RS.Modules.Dialogue)
    if player.PlayerGui:FindFirstChild("Dialogue") and player.PlayerGui.Dialogue.Enabled and d.closeDialogue then d:closeDialogue() end
    local menus=player.PlayerGui:FindFirstChild("Menus")
    if menus and menus:FindFirstChild("CloseRequested") then menus.CloseRequested:Fire() end
    if ledger.Previous then
        B.State.SetAuto("rokaka",ledger.Previous.Rokaka==true)
        B.State.SetAuto("part",ledger.Previous.Parts==true)
        if ledger.Previous.Garden and not A.Get("GardenHarvest") then A.Set("GardenHarvest",true) end
    end
    B.State.SetAuto("arrow",true)
    ledger.Handoff=false;save()
    A.PhoneStatus="phone received / arrow farm on"
    A.Status=A.PhoneStatus
    A.Metrics.PhoneCompleted=true
    if B.State.OnPhoneReady then B.State.OnPhoneReady() end
    if A.Refresh then A.Refresh() end
end
A.Add({Id="AutoPhone",Name="get phone + farm arrows",Group="farm",
    Description="Completes the opening tutorial and Meryl's phone quest, then farms all arrow types. Uses one starter arrow and one health point for the tutorial. Progress resumes separately for each account.",
    Set=function(value)
        generation+=1;nextAction=0;lastStage=nil;stageAt=os.clock()
        if value then
            assert(game.PlaceId==128828638194450,"unsupported phone tutorial place")
            ledger.Enabled=true;ledger.Completed=false;save()
        else ledger.Enabled=false;save();cleanup();A.PhoneStatus="phone quest stopped" end
    end})
A.Cleanups[#A.Cleanups+1]=cleanup
local function status(value) A.PhoneStatus=value;A.Status=value end
local function readyToOwn()
    local s=B.State
    return not (s.AutoBusy or s.RouteBusy or s.TeleportBusy or s.CraftBusy or s.HopBusy or s.AutoHopPause or s.TransferPending or s.PlayerWarpBusy or A.GardenBusy())
end
local function acquire()
    if acquired then return true end
    if not readyToOwn() then status("phone quest waiting for current operation");return false end
    ledger.Previous=ledger.Previous or {Rokaka=B.State.AutoRokaka==true,Parts=B.State.AutoParts==true,Garden=A.Get("GardenHarvest")==true}
    local n=A.Native();if n and ledger.PreviousEX==nil then ledger.PreviousEX=n:getStates().EXToggle==true end
    save()
    B.State.PhoneBusy=true;acquired=true
    for _,id in ipairs(paused) do if A.Features[id] and A.Get(id) then A.Set(id,false) end end
    for _,kind in ipairs({"arrow","rokaka","part"}) do B.State.SetAuto(kind,false) end
    if A.Get("GardenHarvest") then A.Set("GardenHarvest",false) end
    B.SetFly(false)
    if B.State.ReleaseIdleHide then B.State.ReleaseIdleHide() end
    return true
end
local function travel(point,model,token)
    local c,r,h=A.Character();if not c then return false end
    if (r.Position-point).Magnitude<5 then return true end
    B.State.RequestStream(point,2)
    if not current(token) or player.Character~=c then return false end
    local params=RaycastParams.new();params.FilterType=Enum.RaycastFilterType.Exclude
    params.FilterDescendantsInstances=model and {c,model} or {c}
    local hit
    for _,height in ipairs({2,6,12}) do
        local candidate=workspace:Raycast(point+Vector3.new(0,height,3),Vector3.new(0,-20,0),params)
        if candidate and candidate.Normal.Y>0.5 then hit=candidate;break end
    end
    if not hit or hit.Normal.Y<0.5 then status("phone quest waiting for safe landing");return false end
    r.AssemblyLinearVelocity=Vector3.zero
    c:PivotTo(CFrame.lookAt(hit.Position+Vector3.new(0,h.HipHeight+r.Size.Y/2+0.2,0),point))
    task.wait(0.35)
    return current(token) and player.Character==c
end
local function interact(prompt,token)
    if not prompt or not prompt.Enabled or prompt.HoldDuration>4 then return end
    local part=prompt.Parent
    local point=part:IsA("Attachment") and part.WorldPosition or part:IsA("BasePart") and part.Position
    local _,r=A.Character()
    if not point or not r or (point-r.Position).Magnitude>prompt.MaxActivationDistance+0.5 then return end
    held=prompt;prompt:InputHoldBegin()
    local untilAt=os.clock()+prompt.HoldDuration+0.15
    repeat task.wait(0.05) until not current(token) or os.clock()>=untilAt
    releaseHold()
end
local function click(button)
    if button and button:IsA("GuiButton") and button.Visible and button.Active then
        A.PhoneLastButton=button:GetFullName();A.PhoneLastClick=os.clock()
        return A.ClickDialogue(button)
    end
    return false
end
local function menuCard(name,token)
    local menus=player.PlayerGui:FindFirstChild("Menus")
    local hand=menus and menus:FindFirstChild("HandContainer")
    local card=hand and hand:FindFirstChild(name)
    if card and hand:GetAttribute("NavigationOpen")==true then return click(card:FindFirstChild("CardImage",true)) end
    if not menus then return end
    if not current(token) then return end
    local identity=type(getthreadidentity)=="function" and getthreadidentity() or nil
    local ok,err=pcall(function()
        if identity and type(setthreadidentity)=="function" then setthreadidentity(8) end
        local input=game:GetService("VirtualInputManager")
        input:SendKeyEvent(true,Enum.KeyCode.M,false,game)
        input:SendKeyEvent(false,Enum.KeyCode.M,false,game)
    end)
    if identity and type(setthreadidentity)=="function" then setthreadidentity(identity) end
    assert(ok,"native menu input unavailable: "..tostring(err))
end
local function useEX(n)
    n:refreshEXSkills()
    local wanted=player.Data:GetAttribute("TutorialEXMove")
    local slot
    for key,name in pairs(n.EXModeSlots or {}) do if not wanted or name==wanted then slot=key;break end end
    if not slot then for key,name in pairs(n.EXOnlyBinds or {}) do if not wanted or name==wanted then slot=key;break end end end
    if not slot then status("waiting for tutorial ex skill slot");return end
    n:setEXMode(true)
    for _,fn in pairs(debug.getupvalues(n.processSkillInputQueue)) do
        if type(fn)=="function" and debug.info(fn,"n")=="useSkill" then fn(slot,nil,nil);return end
    end
    error("native tutorial skill input unavailable")
end
local function tick()
    if not A.Get("AutoPhone") then return end
    local token=generation
    local state=snapshot()
    local stage=Policy.stage(state)
    if stage~="cop" then CopLock.Release() end
    if stage=="complete" then finish();return end
    if stage=="loading" then status("waiting for account inventory");return end
    if not acquire() then return end
    if stage~=lastStage then
        if lastStage=="archive and stats" then
            local menus=player.PlayerGui:FindFirstChild("Menus")
            if menus and menus:FindFirstChild("CloseRequested") then menus.CloseRequested:Fire() end
        end
        lastStage=stage;stageAt=os.clock();nextAction=0
    end
    status("phone quest / "..stage)
    if os.clock()-stageAt>240 then
        A.Set("AutoPhone",false);A.Error("AutoPhone","no progress at "..stage.."; stopped for inspection");return
    end
    if os.clock()<nextAction then return end
    local c,r,h=A.Character();if not c then return end
    A.PhoneTrace={Stage=stage,At=os.clock(),Stunned=c:GetAttribute("Stunned"),Cinematic=player:GetAttribute("TutorialCinematic"),QTE=player:GetAttribute("QTEInputLocked")}
    if c:GetAttribute("Stunned") or player:GetAttribute("TutorialCinematic") or player:GetAttribute("QTEInputLocked") then return end
    nextAction=os.clock()+1.5
    local n=A.Native();if not n then return end
    local dialogue=player.PlayerGui:FindFirstChild("Dialogue")
    if dialogue and dialogue.Enabled then
        local title=dialogue.Holder.Title.Text:gsub("<[^>]+>",""):lower()
        for _,choice in ipairs(A.DialogueChoices()) do
            if Policy.choice(stage,title,choice.Text,state.Phone) then click(choice.Button);return end
        end
        return
    end
    if stage=="intro" or stage=="finish tutorial" then return end
    if stage=="movement" then n:runStart();n:startDash();return end
    if stage=="cop" then
        local target
        for _,m in ipairs(workspace.Game.Players:GetChildren()) do
            local mh=m:FindFirstChildOfClass("Humanoid")
            if mh and mh.Health>0 and m:FindFirstChild("HumanoidRootPart") and Policy.ownedCop(m:GetAttributes(),player.UserId,player.Name) then target=m;break end
        end
        if not target then
            local point=player:GetAttribute("VisibleQuestTrackerPosition")
            if typeof(point)=="Vector3" then travel(point,nil,token) end
            return
        end
        if h.Health<h.MaxHealth*0.25 then status("phone quest / recovering health");return end
        local tr=target.HumanoidRootPart
        if not current(token) then return end
        local states=n:getStates()
        if states.SwingCooldown or states.Swinging or states.HeavySwinging or states.Stunned then nextAction=os.clock()+.1;return end
        local locked=CopLock.Begin(target,n,function() return current(token) and lastStage=="cop" end)
        if not locked then
            r.AssemblyLinearVelocity=Vector3.zero
            c:PivotTo(CFrame.lookAt(tr.CFrame:PointToWorldSpace(Vector3.new(0,0,3)),tr.Position))
        end
        nextAction=os.clock()+0.2;ownedAttack=n
        local ok,err=pcall(n.lightSwing,n);ownedAttack=nil
        if not ok then CopLock.Release();error(err) end
        return
    end
    if stage=="jodio" or stage=="meryl" then
        local story=require(player.PlayerScripts.Core.StoryInteractions)
        local name=stage=="jodio" and "TutorialJodio" or "Meryl Mei Qi"
        local actor=story.GetDialogueActor(name) or workspace.Game.NPCs:FindFirstChild(name)
        local root=actor and actor:FindFirstChild("HumanoidRootPart")
        if not root then
            local point=stage=="jodio" and Vector3.new(-377.66,19.58,2227.25) or Vector3.new(-1312.37,20.02,839.98)
            B.State.RequestStream(point,2);return
        end
        if not travel(root.Position,actor,token) or not story.CanTalkToActor(actor) then return end
        for _,prompt in ipairs(actor:GetDescendants()) do
            if prompt:IsA("ProximityPrompt") and prompt.Enabled and
                (prompt.Name=="AmbientTalkPrompt" or prompt.ActionText=="Talk") and story.IsEligible(prompt) then interact(prompt,token);return end
        end
        status("phone quest / waiting for "..name.." talk prompt");return
    end
    if stage=="sand" then
        local sand=workspace.Game.QuestInteractables:FindFirstChild("TutorialArrowSand")
        if sand and travel(sand.Position,sand,token) then interact(sand:FindFirstChild("Prompt"),token) end
        return
    end
    if stage=="first stand" then
        if player.Data.Stand.Value~="" or c:GetAttribute("ArrowUseToken") then ledger.ArrowPending=nil;return end
        if ledger.ArrowPending then status("waiting for starter arrow result");return end
        if h.Health<h.MaxHealth*0.5 then return end
        local inventory=Http:JSONDecode(player.Data.Stats.Inventory.Value)
        for _,item in ipairs(inventory) do
            if type(item)=="table" and item.Name=="Mysterious Arrow" and (item.Amount or 1)>0 then
                ledger.ArrowPending=os.time();save()
                if current(token) then RS.Remotes.Item:FireServer("Use",item.Name,item.ID) end
                return
            end
        end
        status("phone quest / starter arrow missing");return
    end
    if stage=="summon" then
        if not n:getStates().Summoned then n:summonStand(true)
        elseif require(RS.Modules.Stands).stands[player.Data.Stand.Value].Pilot and not n:getStates().Piloting then n:pilot(true) end
        return
    end
    if stage=="ex skill" then
        if n:getStates().Piloting then n:pilot(false);return end
        if not n:getStates().Summoned then n:summonStand(true);return end
        useEX(n);nextAction=os.clock()+3;return
    end
    if stage=="archive and stats" then
        if n:getStates().Piloting then n:pilot(false) end
        n:setEXMode(false)
        local menus=player.PlayerGui:FindFirstChild("Menus");if not menus then return end
        if player.Data:GetAttribute("TutorialMenuTarget")=="Archive" then
            local canvas=menus:FindFirstChild("MainCanvas")
            if canvas and canvas.Visible then click(canvas:FindFirstChild("MyStand",true)) else menuCard("ARCHIVE",token) end
        else
            local stats=menus:FindFirstChild("Stats")
            if stats and stats.Visible then
                if not ledger.StatRequested then
                    ledger.StatRequested=true;save()
                    stats.Amount.TextLabel.Text="1"
                    click(stats:FindFirstChild("Health"))
                end
            else menuCard("STATS",token) end
        end
    end
end
A.Loop("phone quest",0.25,tick)
if ledger.Enabled or ledger.Handoff then A.Set("AutoPhone",true) end

    end)(advanced, bridge);
    (function(A, B)
local P=(function()
local P={}
function P.CanStartFresh(record,now,busy)
    if busy or type(record)~="table" or type(record.At)~="number" then return false end
    local age=now-record.At
    return age==age and age>=120 and age<math.huge
end
function P.Count(inv,name)
    local v=type(inv)=="table" and inv[name]
    return type(v)=="number" and v==v and v>=0 and v<math.huge and math.floor(v) or 0
end
function P.Next(inv,bizarreCap)
    if not inv then return nil end
    if P.Count(inv,"Bizarre Arrow")>=99 and bizarreCap==nil then return nil end
    if P.Count(inv,"Mysterious Arrow")>=9 and P.Count(inv,"Bizarre Arrow")<(bizarreCap or 99) then
        return {Name="Bizarre Arrow",Cost={["Mysterious Arrow"]=9}}
    end
    if P.Count(inv,"Arrow Part")>=3 and P.Count(inv,"Steel")>=2 and P.Count(inv,"Wood")>=1 then
        return {Name="Mysterious Arrow",Cost={["Arrow Part"]=3,Steel=2,Wood=1}}
    end
end
function P.Needs(inv,limits)
    local needs={}
    for _,name in ipairs({"Steel","Wood"}) do
        local cap=limits and limits[name] or 99
        if type(cap)~="number" or cap~=cap or cap==math.huge or cap<1 then cap=0 end
        needs[name]=math.max(0,math.min(99,math.floor(cap))-P.Count(inv,name))
    end
    return needs
end
function P.Confirmed(record,inv)
    if type(record)~="table" or type(inv)~="table" or type(record.Before)~="table" or type(record.Cost)~="table" then return false end
    if record.Recipe~="Mysterious Arrow" and record.Recipe~="Bizarre Arrow" then return false end
    local expected=record.Recipe=="Bizarre Arrow" and {["Mysterious Arrow"]=9} or {["Arrow Part"]=3,Steel=2,Wood=1}
    for name,amount in pairs(expected) do if record.Cost[name]~=amount then return false end end
    for name in pairs(record.Cost) do if not expected[name] then return false end end
    if P.Count(inv,record.Recipe)<P.Count(record.Before,record.Recipe)+1 then return false end
    for name,amount in pairs(record.Cost) do
        if type(amount)~="number" or amount<=0 or P.Count(inv,name)>P.Count(record.Before,name)-amount then return false end
    end
    return next(record.Cost)~=nil
end
function P.Owned(attrs,userId)
    for _,key in ipairs({"OwnerUserId","StoryOwnerUserId","DropOwnerUserId","PickupOwnerUserId","ReservedUserId"}) do
        local value=attrs[key]
        if value~=nil and value~="" and tonumber(value)~=0 and tonumber(value)~=userId then return false end
    end
    return true
end
return P

end)()
local id="FreeArrowMaterials"
local function nextCraft(inventory)
    return P.Next(inventory,B.State.BizarreStockCap)
end
B.State.MaterialCraftPolicyVersion=2
local Http=game:GetService("HttpService")
local CS=game:GetService("CollectionService")
local player=B.Player
local file="sharkwow-standout-materials-"..player.UserId..".json"
local config={Schema=1,UserId=player.UserId,Enabled=false}
local storageError
if type(readfile)=="function" then
    local exists=type(isfile)=="function" and isfile(file)
    local ok,data=pcall(function() return Http:JSONDecode(readfile(file)) end)
    if ok and type(data)=="table" and data.Schema==1 and data.UserId==player.UserId then config=data
    elseif exists then storageError="saved material configuration unreadable; automatic start stopped" end
end
local generation,nextAction=0,0
local suspendedForConfirmation=false
local held,attack,attackNative,attackCharacter,acquired,controller,ownedBrowser,ownedSession
local retry=setmetatable({},{__mode="k"})
local objectCooldown={}
local harvestHistory={}
B.State.MaterialHarvestHistory=harvestHistory
B.State.MaterialHarvestVersion=7
local gather=setmetatable({},{__mode="k"})
local function save()
    assert(type(writefile)=="function","material config storage unavailable")
    writefile(file,Http:JSONEncode(config))
end
local function blocked()
    if B.State.PhoneBusy or A.Get("AutoPhone") or B.State.TransferPending or B.State.AutoHopPause or B.State.HopBusy or B.State.Flying or A.GardenBusy() then return true end
    for _,other in ipairs({"AutoFarm","AutoQuest","QuestFarm","BountyFarm","QuestTravel","AutoRoll","AutoPilot","ItemFarm"}) do if A.Get(other) then return true end end
    return false
end
local function current(token,c)
    local humanoid=c and c:FindFirstChildOfClass("Humanoid")
    return A.Current() and A.Get(id) and generation==token and player.Character==c and c.Parent and humanoid and humanoid.Health>0 and not blocked()
end
local function status(value) B.State.MaterialStatus=value;A.Status=value end
local function cleanup()
    if held then pcall(held.InputHoldEnd,held);held=nil end
    if attack and coroutine.status(attack)~="dead" then
        if attackNative and player.Character==attackCharacter then
            if type(attackNative.cancelAttacksForStandReplacement)=="function" then pcall(attackNative.cancelAttacksForStandReplacement,attackNative) end
            if type(attackNative.finishBasicAttack)=="function" then pcall(attackNative.finishBasicAttack,attackNative,true) end
            local humanoid=attackCharacter:FindFirstChildOfClass("Humanoid")
            if humanoid and type(attackNative.getGroundWalkSpeed)=="function" then
                local ok,speed=pcall(attackNative.getGroundWalkSpeed,attackNative,false)
                if ok and type(speed)=="number" then humanoid.WalkSpeed=speed end
            end
        end
        pcall(task.cancel,attack)
    end
    attack=nil;attackNative=nil;attackCharacter=nil
    if controller and ownedSession and controller.Session==ownedSession then pcall(controller.Close,controller,true) end
    if controller and ownedBrowser and controller.Browser==ownedBrowser then pcall(controller.CloseBrowser,controller,true) end
    ownedSession=nil;ownedBrowser=nil
    if acquired then B.State.CraftBusy=false;B.State.ExtensionPause=false;B.State.MaterialBusy=false;acquired=false end
    if A.Underground then
        if A.Current() and A.Get(id) and not blocked() then A.Underground.Finish(id) else A.Underground.Release(id,true) end
    end
end
local function reconcile()
    local record=config.Pending
    if not record then B.State.MaterialReconciliationPending=false;return true end
    if P.Confirmed(record,B.State.ReadInventory()) then config.Pending=nil;save();B.State.MaterialReconciliationPending=false;return true end
    B.State.MaterialReconciliationPending=true
    return false
end
A.Add({Id=id,Name="free materials > bizarre",Group="farm",Description="Collects free Steel and Wood while locked below targets with noclip, then crafts Mysterious and Bizarre Arrows below the workbench. Waits underground between jobs. No purchases. Saves per account. Waits for phone quests and existing farms. Unconfirmed crafts stop instead of repeating."})
A.Features[id].Set=function(value)
    if not value then B.State.MaterialResumeRequested=false end
    if value then
        assert(not storageError,storageError)
        if not reconcile() then
            assert(P.CanStartFresh(config.Pending,os.time(),B.State.CraftBusy or B.State.MaterialBusy),"previous craft outcome unknown; wait for the active craft before enabling a fresh run")
            local native=require(player.PlayerScripts.Core.Crafting)
            assert(not native.Session and not native.Pending and not native.Browser,"close the active crafting interaction before enabling a fresh run")
            local inventory=B.State.ReadInventory();assert(inventory,"inventory unavailable; recovery postponed")
            local replacement=table.clone(config)
            replacement.LastUnconfirmed={Record=config.Pending,ArchivedAt=os.time(),InventoryAtRestart=inventory,
                Reason="user explicitly enabled a fresh run after the previous interaction ended; old outcome remains unknown"}
            replacement.Pending=nil
            writefile(file,Http:JSONEncode(replacement))
            config=replacement
            B.State.MaterialReconciliationPending=false
            B.State.MaterialRecoveryStatus="old outcome archived; fresh run uses current inventory"
        end
    end
    suspendedForConfirmation=false
    config.Enabled=value;save();generation+=1
    if not value then cleanup() end
end
A.Features[id].Enabled=config.Enabled==true and not storageError
if storageError then A.Error(id,storageError) end
A.Cleanups[#A.Cleanups+1]=function() generation+=1;cleanup() end
local function watch(instance)
    if instance:GetAttribute("GardenGatherable")=="Steel" or instance:GetAttribute("GardenGatherable")=="Wood" then gather[instance]=true end
end
local map=workspace.Game:FindFirstChild("Map")
if map then
    for _,v in ipairs(map:GetDescendants()) do watch(v) end
    A.Connect(map.DescendantAdded,watch)
end
local function owned(instance)
    local node=instance
    while node and node~=workspace do
        if not P.Owned(node:GetAttributes(),player.UserId) then return false end
        node=node.Parent
    end
    return true
end
local function position(instance)
    if instance:IsA("Attachment") then return instance.WorldPosition end
    if instance:IsA("BasePart") then return instance.Position end
    if instance:IsA("Model") then return instance:GetPivot().Position end
end
local function pickup(model)
    if not model:IsDescendantOf(workspace) or not owned(model) then return end
    local name=model:GetAttribute("ItemName") or model:GetAttribute("GardenGatherable") or model.Name
    if name~="Steel" and name~="Wood" then return end
    for _,prompt in ipairs(model:GetDescendants()) do
        if prompt:IsA("ProximityPrompt") and prompt.Enabled and prompt.HoldDuration<=5 then
            local action=prompt.ActionText:lower()
            if prompt.Name=="GardenGather" or action:find("collect",1,true) or action:find("pick",1,true) or action:find("gather",1,true) then
                local point=position(prompt.Parent)
                if point then return {Model=model,Prompt=prompt,Point=point,Name=name} end
            end
        end
    end
end
local function loose(needs,root)
    local best,distance=nil,math.huge
    local function consider(model)
        if (retry[model] or 0)>os.clock() then return end
        local item=pickup(model)
        if item and (needs[item.Name] or 0)>0 then
            local d=(root.Position-item.Point).Magnitude
            if d<distance then best=item;distance=d end
        end
    end
    for _,name in ipairs({"SpawnedItems","WorldEventDrops"}) do
        local folder=workspace.Game:FindFirstChild(name)
        if folder then for _,model in ipairs(folder:GetChildren()) do consider(model) end end
    end
    for model in pairs(gather) do consider(model) end
    return best
end
local function waitFor(predicate,seconds,token,c)
    local deadline=os.clock()+seconds
    repeat
        assert(current(token,c),"material operation cancelled")
        if predicate() then return true end
        task.wait(0.1)
    until os.clock()>=deadline
    assert(current(token,c),"material operation cancelled")
    return predicate()
end
local function travel(point,exclude,token,c,r,h,range,mode,shape)
    assert(current(token,c),"material operation cancelled")
    assert(A.Underground,"underground position module unavailable")
    A.Underground.Begin(id,c,r,h,point,exclude,range or A.Underground.AttackRange,mode or "attack",function() return current(token,c) end,shape)
    task.wait(0.5)
    assert(current(token,c),"material operation cancelled")
end
local function collect(item,token,c,r,h)
    local before=B.State.ReadInventory();assert(before,"inventory unavailable")
    if P.Count(before,item.Name)>=99 then return end
    travel(item.Point,item.Model,token,c,r,h,math.min(9.25,item.Prompt.MaxActivationDistance-.75),"pickup")
    local prompt=item.Prompt
    if P.Count(B.State.ReadInventory(),item.Name)>=99 then return end
    assert(prompt.Parent and prompt.Enabled and owned(item.Model),"material pickup changed")
    local point=position(prompt.Parent)
    assert(point and (point-r.Position).Magnitude<=prompt.MaxActivationDistance,"material pickup out of range")
    held=prompt;A.Underground.Prompt(id,prompt,function() return current(token,c) end);held=nil
    assert(current(token,c),"material pickup cancelled")
    local gained=waitFor(function() return P.Count(B.State.ReadInventory(),item.Name)>P.Count(before,item.Name) end,5,token,c)
    retry[item.Model]=os.clock()+(gained and 5 or 60)
    assert(gained,"material pickup inventory gain unconfirmed")
    A.Metrics.MaterialPickups=(A.Metrics.MaterialPickups or 0)+1
    status("collected "..item.Name)
end
local function target(needs,root)
    local best,distance=nil,math.huge
    for tag,name in pairs({DestructibleTree="Wood",DestructiblePole="Steel"}) do
        if needs[name]>0 then
            for _,model in ipairs(CS:GetTagged(tag)) do
                if (model:IsA("Model") or model:IsA("BasePart")) and model:IsDescendantOf(workspace.Game.Map) and not model:GetAttribute("Destroyed")
                    and not model:GetAttribute("NoDestruction") and not CS:HasTag(model,"Indestructible") and owned(model) and (retry[model] or 0)<=os.clock() then
                    local base=model:IsA("BasePart") and model or nil
                    local woodBase=false
                    for _,part in ipairs(model:GetDescendants()) do
                        if part:IsA("BasePart") and part.Transparency<1 then
                            local isWood=name=="Wood" and (part.Material==Enum.Material.Wood or part.Material==Enum.Material.WoodPlanks or part.Name:lower():find("trunk",1,true)~=nil)
                            if not base or (isWood and not woodBase) or (isWood==woodBase and part.Position.Y<base.Position.Y) then base=part;woodBase=isWood end
                        end
                    end
                    if base then
                        local d=(base.Position-root.Position).Magnitude
                        local score=d/math.max(1,needs[name])
                        local key=string.format("%s:%d:%d:%d",name,math.floor(base.Position.X/4),math.floor(base.Position.Y/4),math.floor(base.Position.Z/4))
                        if score<distance and d<2500 and (objectCooldown[key] or 0)<=os.clock() then best={Model=model,Part=base,Point=base.Position,Name=name,Key=key,Tag=tag};distance=score end
                    end
                end
            end
        end
    end
    return best
end
local function harvest(item,token,c,r,h)
    if P.Count(B.State.ReadInventory(),item.Name)>=99 then return end
    retry[item.Model]=os.clock()+180
    objectCooldown[item.Key]=os.clock()+600
    for key,untilTime in pairs(objectCooldown) do if untilTime<os.clock() then objectCooldown[key]=nil end end
    A.Metrics.MaterialAttempts=(A.Metrics.MaterialAttempts or 0)+1
    B.State.MaterialTarget={Name=item.Name,Point=item.Point,Model=item.Model}
    local before=B.State.ReadInventory();assert(before,"inventory unavailable")
    local sample={Name=item.Name,Tag=item.Tag,Key=item.Key,Requests=0,ObservedSwings=0,Gain=0,Started=os.clock(),Reason="running"}
    local beforeCount=P.Count(before,item.Name)
    harvestHistory[#harvestHistory+1]=sample
    if #harvestHistory>40 then table.remove(harvestHistory,1) end
    local function gained()
        sample.Gain=math.max(sample.Gain,P.Count(B.State.ReadInventory(),item.Name)-beforeCount)
        return sample.Gain>0
    end
    local native=A.Native();assert(native and type(native.heavySwing)=="function","native heavy attack unavailable")
    local shape=A.Underground and A.Underground.HeavyShape(native,item.Part)
    if A.Underground then assert(shape,"native heavy reach profile unavailable") end
    local preferred=A.Underground and (item.Name=="Steel" and A.Underground.SteelRange or A.Underground.AttackRange)
    local fallback=A.Underground and (item.Name=="Steel" and A.Underground.SteelFallback or A.Underground.FallbackRange)
    local moved,moveError=pcall(travel,item.Point,item.Model,token,c,r,h,preferred,"attack",shape)
    if not moved and current(token,c) and tostring(moveError):find("no covered underground position",1,true) then
        moved,moveError=pcall(travel,item.Point,item.Model,token,c,r,h,fallback,"attack",shape)
    end
    if not moved then
        if current(token,c) and tostring(moveError):find("no covered underground position",1,true) then
            sample.Reason="no covered strike position";sample.Elapsed=os.clock()-sample.Started
            status("skipped target outside underground strike reach");return
        end
        error(moveError)
    end
    sample.UndergroundRange=B.State.UndergroundLock and B.State.UndergroundLock.Range
    status("gathering free "..item.Name)
    for _=1,2 do
        if P.Count(B.State.ReadInventory(),item.Name)>=99 then sample.Reason="stock full";break end
        if gained() then sample.Reason="inventory gain";break end
        if not item.Model.Parent or item.Model:GetAttribute("Destroyed") then sample.Reason="destroyed";break end
        if os.clock()-sample.Started>=10 then sample.Reason="time budget";break end
        assert(current(token,c),"material harvest cancelled")
        assert(not (B.State.HasPriorityItems and B.State.HasPriorityItems()),"material harvest yielded to collectible item")
        if A.Underground then assert(A.Underground.Check(id),"underground harvest hold lost") end
        local ready=waitFor(function()
            local states=native:getStates()
            return not (states.HeavyCD or states.SwingCooldown or states.Swinging or states.HeavySwinging or states.Stunned or states.CombatDisabled or states.Swimming or states.Driving)
        end,1,token,c)
        if not ready then
            sample.Reason="native cooldown"
            break
        end
        if A.Underground then
            if not A.Underground.Overlaps(item.Model,r.CFrame,shape) then sample.Reason="target outside strike box";break end
            sample.AimChecks=(sample.AimChecks or 0)+1
        end
        local finished,attackError=false,nil
        local observed=false
        sample.Requests+=1
        attackNative=native;attackCharacter=c
        attack=task.spawn(function()
            local ok,err=pcall(function() if current(token,c) then native:heavySwing() end end)
            if not ok then attackError=tostring(err) end
            finished=true
        end)
        local ended=waitFor(function()
            gained()
            local states=native:getStates()
            if not observed and (states.HeavySwinging or states.HeavyHit) then observed=true;sample.ObservedSwings+=1 end
            return finished
        end,5,token,c)
        if not ended then sample.Reason="attack timeout";sample.Elapsed=os.clock()-sample.Started end
        assert(ended,"native heavy attack timed out")
        attack=nil;attackNative=nil;attackCharacter=nil;assert(not attackError,attackError)
        if waitFor(gained,0.8,token,c) then sample.Reason="inventory gain";break end
        if not observed then sample.Reason="attack not observed";break end
        sample.Reason="no inventory gain"
        if _==1 and A.Underground and item.Model.Parent and not item.Model:GetAttribute("Destroyed") then
            local moved=pcall(travel,item.Point,item.Model,token,c,r,h,fallback,"attack",shape)
            if moved then sample.FallbackRange=fallback end
        end
    end
    gained();sample.Elapsed=os.clock()-sample.Started
    if sample.Gain>0 then
        sample.Reason="inventory gain"
        retry[item.Model]=os.clock()+30
        objectCooldown[item.Key]=os.clock()+30
        A.Metrics.MaterialGains=(A.Metrics.MaterialGains or 0)+sample.Gain
        status("received "..item.Name)
    else
        status("skipped unproductive "..item.Name)
    end
end
local function craft(recipe,token,c,r,h)
    controller=require(player.PlayerScripts.Core.Crafting)
    assert(not controller.Session and not controller.Pending and not controller.Browser,"another crafting interaction is open")
    local function station()
        local garden=workspace.Game:FindFirstChild("Gardening")
        local stations=garden and garden:FindFirstChild("ProcessingStations")
        return stations and stations:FindFirstChild("Crafting")
    end
    local bench=station()
    if not bench then B.State.RequestStream(Vector3.new(-1777.389,28.126,851.942),3);bench=station() end
    assert(current(token,c),"material crafting cancelled")
    assert(bench and bench:GetAttribute("StationId")=="SpawnGarden_Crafting" and not bench:GetAttribute("InUse"),"crafting bench unavailable")
    local mat=bench:FindFirstChild("WorkMat")
    local prompt=mat and mat:FindFirstChild("GardenCraft")
    assert(prompt and prompt.Enabled and prompt.HoldDuration<=5,"crafting prompt unavailable")
    travel(mat.Position,bench,token,c,r,h,math.min(9.25,prompt.MaxActivationDistance-.75),"craft")
    assert((r.Position-mat.Position).Magnitude<=prompt.MaxActivationDistance,"crafting out of range")
    held=prompt;A.Underground.Prompt(id,prompt,function() return current(token,c) end);held=nil
    assert(waitFor(function() return controller.Browser and controller.Browser.Model==bench end,5,token,c),"craft browser did not open")
    ownedBrowser=controller.Browser
    local inventory=B.State.ReadInventory();assert(inventory,"inventory unavailable")
    local nextRecipe=nextCraft(inventory);assert(nextRecipe and nextRecipe.Name==recipe.Name,"craft materials changed")
    local definitions=require(game.ReplicatedStorage.Modules.Crafting.Recipes).crafting
    local nativeRecipe=definitions[recipe.Name]
    assert(nativeRecipe and nativeRecipe.Yields==1,"native recipe changed")
    local seen=0
    for _,ingredient in ipairs(nativeRecipe.Ingredients) do assert(recipe.Cost[ingredient.Name]==ingredient.Amount,"native ingredient changed");seen+=1 end
    assert(seen==(recipe.Name=="Bizarre Arrow" and 1 or 3),"native ingredient list changed")
    local record={Recipe=recipe.Name,Cost=recipe.Cost,Before=inventory,At=os.time(),Job=game.JobId,UserId=player.UserId}
    config.Pending=record;save()
    assert(current(token,c),"material crafting cancelled")
    if not controller:Request(recipe.Name,1) then config.Pending=nil;save();error("native recipe request rejected") end
    status("crafting "..recipe.Name)
    local deadline=os.clock()+45
    repeat
        if P.Confirmed(record,B.State.ReadInventory()) then
            config.Pending=nil;save()
            A.Metrics.MaterialCrafts=(A.Metrics.MaterialCrafts or 0)+1
            status("crafted "..recipe.Name)
            return
        end
        assert(current(token,c),"craft cancelled; inventory reconciliation required")
        assert(A.Underground.Check(id),"underground crafting hold lost")
        local session=controller.Session
        if session then
            if not ownedSession then assert(session.Payload.Recipe==recipe.Name and session.Payload.Model==bench,"unexpected crafting session");ownedSession=session end
            assert(session==ownedSession,"craft session changed")
            local phase=session.Payload.Phase
            assert(phase=="Place" or phase=="Ready" or phase=="Success","unexpected crafting phase")
            if not session.Pending and phase~="Success" then controller:Act() end
        end
        task.wait(0.3)
    until os.clock()>=deadline
    error("craft inventory outcome unconfirmed; automatic retry stopped")
end
A.Loop("free arrow materials",1,function()
    if suspendedForConfirmation and config.Pending then
        if reconcile() then
            suspendedForConfirmation=false
            config.Enabled=true;A.Features[id].Enabled=true;save()
            A.Errors[id]=nil;status("late craft confirmed; material work resumed")
        else status("craft confirmation pending; other farms continue") end
    end
    if not A.Get(id) or os.clock()<nextAction or blocked() then return end
    if os.clock()<(B.State.TransportPriorityUntil or 0) then return end
    if os.clock()<(B.State.LevelPriorityUntil or 0) then return end
    if config.Pending and not reconcile() then
        config.Enabled=false;save();A.Features[id].Enabled=false;A.Error(id,"previous craft outcome unknown; automatic retry stopped");return
    end
    if B.State.CraftBusy or B.State.ExtensionPause or B.State.AutoBusy or B.State.RouteBusy or B.State.TeleportBusy then return end
    if B.State.HasPriorityItems and B.State.HasPriorityItems() then
        status("collectible items first; materials resume afterward")
        return
    end
    local inv=B.State.ReadInventory();if not inv then return end
    local recipe=nextCraft(inv)
    B.State.MaterialStockFull=P.Count(inv,"Steel")>=99 and P.Count(inv,"Wood")>=99
    if B.State.MaterialStockFull and not recipe then
        B.State.MaterialNeeds={Steel=0,Wood=0};B.State.MaterialTarget=nil
        if A.Underground then A.Underground.Release(id,true) end
        status("STEEL 99 / WOOD 99 - GATHERING PAUSED")
        nextAction=os.clock()+2;return
    end
    local c,r,h=A.Character();if not c then return end
    if recipe and recipe.Name=="Bizarre Arrow" and A.Get("AutoCraftBizarre") then return end
    if not recipe and ((B.State.AutoArrow and B.State.Arrow>0) or (B.State.AutoRokaka and B.State.Rokaka>0) or (B.State.AutoParts and (B.State.Parts or 0)>0)) then return end
    local definitions=require(game.ReplicatedStorage.Modules.Items).items
    local needs=P.Needs(inv,{Steel=definitions.Steel.MaxStack,Wood=definitions.Wood.MaxStack})
    B.State.MaterialNeeds={Steel=needs.Steel,Wood=needs.Wood}
    if P.Count(inv,"Wood")>=1 and P.Count(inv,"Steel")<2 then needs.Wood=0 end
    if P.Count(inv,"Steel")>=2 and P.Count(inv,"Wood")<1 then needs.Steel=0 end
    local item=not recipe and loose(needs,r)
    if not recipe and not item then
        local native=A.Native()
        local states=native and native:getStates()
        if states and (states.HeavyCD or states.SwingCooldown or states.Swinging or states.HeavySwinging or states.Stunned) then
            status("waiting for native attack cooldown");nextAction=os.clock()+2;return
        end
    end
    local object=not recipe and not item and target(needs,r)
    if not recipe and not item and not object then
        status(needs.Steel==0 and needs.Wood==0 and "material stock full; waiting for arrow parts" or "waiting underground for available material targets")
        local token=generation
        if A.Underground then A.Underground.Park(id,function() return current(token,c) end) end
        nextAction=os.clock()+5;return
    end
    local token=generation
    acquired=true;B.State.CraftBusy=true;B.State.ExtensionPause=true;B.State.MaterialBusy=true
    local ok,err=pcall(function()
        if B.State.ReleaseIdleHide then B.State.ReleaseIdleHide() end
        if recipe then craft(recipe,token,c,r,h) elseif item then collect(item,token,c,r,h) else harvest(object,token,c,r,h) end
    end)
    cleanup();nextAction=os.clock()+(ok and (object and 0.3 or 3) or 10)
    if not ok then
        if item then retry[item.Model]=os.clock()+60 end
        if config.Pending and generation==token then
            suspendedForConfirmation=A.Get(id)==true
            config.Enabled=false;save();A.Features[id].Enabled=false
        end
        A.Error(id,err)
    else A.Errors[id]=nil end
end)

    end)(advanced, bridge);
    (function(A, B)
local P=(function()
local P={}
function P.Event(value)
    return type(value)=="table" and value.Id=="MoneyTransport"
        and type(value.EventId)=="string" and #value.EventId>0 and #value.EventId<=120
        and (value.Phase=="Driving" or value.Phase=="Loot" or value.Phase=="Cleanup")
end
function P.Vehicle(attrs,eventId,referenced)
    if type(attrs)~="table" or attrs.ItemName or attrs.Destroyed==true then return false end
    for _,key in ipairs({"OwnerUserId","StoryOwnerUserId","DriverUserId","PilotUserId","MechanicCar"}) do
        local value=attrs[key]
        if value~=nil and value~="" and tonumber(value)~=0 then return false end
    end
    return referenced==true or attrs.WorldEventId==eventId or attrs.EventId==eventId
end
function P.ShouldYield(s)
    return s.Phone or s.Craft or s.Garden or s.Pickup or s.Travel or s.Transfer or s.Flying
        or s.Parts>0 or s.Arrows>0 or s.Health<.3 or s.PartCount>=99
end
function P.Newer(prior,event)
    if not P.Event(event) then return false end
    if not prior then return true end
    if prior.Phase=="Cleanup" then return false end
    if type(prior.Revision)=="number" and type(event.Revision)=="number" then
        return event.Revision>prior.Revision
    end
    return prior.Phase~="Loot" or event.Phase~="Driving"
end
return P

end)()
local Http=game:GetService("HttpService")
local Players=game:GetService("Players")
local RS=game:GetService("ReplicatedStorage")
local Run=game:GetService("RunService")
local id="MoneyTransportFarm"
local file="sharkwow-standout-transport-"..B.Player.UserId..".json"
local config={Schema=1,UserId=B.Player.UserId,Enabled=false}
local readOK,data=pcall(function()return Http:JSONDecode(readfile(file))end)
if readOK and type(data)=="table" and data.Schema==1 and data.UserId==B.Player.UserId then config=data end
local events,retry,streamAfter,revisions,revisionOrder={},{},{},{},{}
local generation,acquired,hold,attack,attackNative,attackCharacter=0,false,nil,nil,nil,nil
local channel=RS.Remotes:FindFirstChild("WorldEvents")
local lastSnapshot=-math.huge
local probe=getgenv().SHARKWOWTransportProbe
if probe and probe.Connection then probe.Connection:Disconnect() end
getgenv().SHARKWOWTransportProbe=nil
local function save()writefile(file,Http:JSONEncode(config))end
local function status(message)B.State.TransportStatus=message end
local function current(token,character)
    return A.Current() and A.Get(id) and generation==token and B.Player.Character==character
        and not B.State.TransferPending and not B.State.HopBusy and not B.State.AutoHopPause
        and not B.State.PhoneBusy and not B.State.Flying
end
local function cleanup()
    if attack and coroutine.status(attack)~="dead" then
        if attackNative and B.Player.Character==attackCharacter then
            pcall(attackNative.cancelAttacksForStandReplacement,attackNative)
            pcall(attackNative.finishBasicAttack,attackNative,true)
            local humanoid=attackCharacter:FindFirstChildOfClass("Humanoid")
            if humanoid and type(attackNative.getGroundWalkSpeed)=="function" then
                local ok,speed=pcall(attackNative.getGroundWalkSpeed,attackNative,false)
                if ok and type(speed)=="number" then humanoid.WalkSpeed=speed end
            end
        end
        pcall(task.cancel,attack)
    end
    attack=nil;attackNative=nil;attackCharacter=nil
    if hold then
        local old=hold;hold=nil
        if old.Connection then old.Connection:Disconnect() end
        for _,object in ipairs(old.Objects)do object:Destroy()end
        if old.Humanoid.Parent then old.Humanoid.AutoRotate=old.AutoRotate end
        for part,value in pairs(old.Collisions)do if part.Parent and not B.State.Noclip and not B.State.FarmHideActive then part.CanCollide=value end end
        if old.Root.Parent then old.Root.AssemblyLinearVelocity=Vector3.zero;old.Root.AssemblyAngularVelocity=Vector3.zero end
    end
    if acquired then acquired=false;B.State.TransportBusy=false;B.State.CraftBusy=false;B.State.ExtensionPause=false end
    B.State.TransportPriorityUntil=0
end
local function apply(event)
    if not P.Event(event) then return end
    if not P.Newer(revisions[event.EventId],event) then return end
    if not revisions[event.EventId] then revisionOrder[#revisionOrder+1]=event.EventId end
    revisions[event.EventId]={Phase=event.Phase,Revision=event.Revision}
    while #revisionOrder>64 do
        local oldest=table.remove(revisionOrder,1)
        revisions[oldest]=nil;events[oldest]=nil;retry[oldest]=nil;streamAfter[oldest]=nil
    end
    if event.Phase=="Cleanup" then events[event.EventId]=nil;retry[event.EventId]=nil;streamAfter[event.EventId]=nil;return end
    events[event.EventId]={State=event,Received=os.clock()}
    if event.Phase=="Loot" then status("transport loot available; arrow part collector has priority") end
end
if channel then
    A.Connect(channel.OnClientEvent,function(kind,payload)
        if kind=="State" then apply(payload)
        elseif kind=="Snapshot" and type(payload)=="table" then
            for _,event in ipairs(payload)do apply(event)end
            B.State.TransportSnapshotReady=true
        end
    end)
end
local function snapshot()
    assert(channel,"world event channel unavailable")
    if os.clock()-lastSnapshot>=10 then lastSnapshot=os.clock();channel:FireServer("Snapshot") end
end
A.Add({Id=id,Name="money transport + meteor",Group="farm",Description="Watches actual money-transport events, attacks only an identified unowned event vehicle, then yields to Arrow Part collection. Meteor collection stays enabled. No shop purchases.",Set=function(value)
    if value then assert(channel,"world event channel unavailable");assert(A.Set("ArrowPartFarm",true));snapshot() end
    local previous=config.Enabled;config.Enabled=value
    local ok,err=pcall(save);if not ok then config.Enabled=previous;error(err) end
    generation+=1
    if value then status("waiting for money transport / collecting meteor parts")
    else cleanup();status("money transport stopped") end
end})
A.Features[id].Enabled=config.Enabled==true and not B.State.HoldForJoin
B.State.MoneyTransportVersion=1
B.State.TransportEvents=events
A.Cleanups[#A.Cleanups+1]=function()generation+=1;cleanup()end
local function payloadReferences(event)
    local models,points={},{}
    local seen={}
    local function visit(value,depth)
        if typeof(value)=="Instance" and value:IsA("Model") and value:IsDescendantOf(workspace) then models[value]=true
        elseif typeof(value)=="Vector3" and value.Magnitude<1e6 then if #points<4 then points[#points+1]=value end
        elseif type(value)=="table" and not seen[value] and depth<3 then
            seen[value]=true
            for _,child in pairs(value)do visit(child,depth+1)end
        end
    end
    visit(event,0)
    return models,points
end
local function vehicle(event)
    local referenced,points=payloadReferences(event)
    local candidates={}
    for model in pairs(referenced)do candidates[model]=true end
    local world=workspace:FindFirstChild("Game")
    local cars=world and world:FindFirstChild("Vehicles")
    if cars then for _,model in ipairs(cars:GetChildren())do candidates[model]=true end end
    for _,model in ipairs(workspace:GetChildren())do if model:IsA("Model") then candidates[model]=true end end
    for model in pairs(candidates)do
        if model:IsA("Model") and model.Parent and not Players:GetPlayerFromCharacter(model) and not model:FindFirstChildOfClass("Humanoid")
            and P.Vehicle(model:GetAttributes(),event.EventId,referenced[model]) then
            local part,volume=nil,0
            for _,child in ipairs(model:GetDescendants())do
                if child:IsA("BasePart") and child.CanQuery and child.CanCollide and child.Transparency<1 then
                    local size=child.Size.X*child.Size.Y*child.Size.Z
                    if size>volume then part=child;volume=size end
                end
            end
            if part then return model,part,points end
        end
    end
    return nil,nil,points
end
local function requestArea(event,points)
    if os.clock()<(streamAfter[event.EventId] or 0) or #points==0 then return end
    streamAfter[event.EventId]=os.clock()+15
    B.State.RequestStream(points[1],2)
end
local function attackVehicle(event,model,part,token,c,r,h)
    if not current(token,c) or not model.Parent or not part.Parent then return end
    local native=A.Native()
    assert(native and type(native.heavySwing)=="function","native heavy attack unavailable")
    local shape=A.Underground.HeavyShape(native,part)
    assert(shape,"native attack geometry unavailable")
    local params=RaycastParams.new();params.FilterType=Enum.RaycastFilterType.Exclude
    params.FilterDescendantsInstances={c,model,workspace.Game.Players};params.RespectCanCollide=true
    local function pose()
        for _,offset in ipairs({Vector3.new(part.Size.X/2+2,0,0),Vector3.new(-part.Size.X/2-2,0,0),Vector3.new(0,0,part.Size.Z/2+2),Vector3.new(0,0,-part.Size.Z/2-2)})do
            local point=part.CFrame:PointToWorldSpace(offset)
            local floor=workspace:Raycast(point+Vector3.new(0,12,0),Vector3.new(0,-40,0),params)
            if floor and floor.Normal.Y>=.65 and floor.Material~=Enum.Material.Water then
                local position=floor.Position+Vector3.new(0,h.HipHeight+r.Size.Y/2+.2,0)
                local at=CFrame.lookAt(position,Vector3.new(part.Position.X,position.Y,part.Position.Z))
                if A.Underground.Overlaps(model,at,shape) then return at end
            end
        end
    end
    local at=pose();assert(at,"no supported position within native vehicle hitbox")
    if not current(token,c) then return end
    acquired=true;B.State.TransportBusy=true;B.State.CraftBusy=true;B.State.ExtensionPause=true
    if B.State.ReleaseIdleHide then B.State.ReleaseIdleHide() end
    if B.ReleaseFarmHold then B.ReleaseFarmHold() end
    A.Underground.Release(nil,true)
    assert(not r.Anchored,"character movement is locked")
    local owner={Root=r,Humanoid=h,AutoRotate=h.AutoRotate,Objects={},Collisions={},Valid=true}
    hold=owner;h.AutoRotate=false
    local attachment=Instance.new("Attachment");attachment.Name="SHARKWOWTransportHold";attachment.Parent=r;owner.Objects[#owner.Objects+1]=attachment
    local velocity=Instance.new("LinearVelocity");velocity.Name="SHARKWOWTransportHold";velocity.Attachment0=attachment;velocity.MaxForce=math.huge;velocity.RelativeTo=Enum.ActuatorRelativeTo.World;velocity.VectorVelocity=Vector3.zero;velocity.Parent=r;owner.Objects[#owner.Objects+1]=velocity
    local nextFollow=0
    local function follow()
        if not current(token,c) or not model.Parent or not part.Parent or h.Health<h.MaxHealth*.3 then owner.Valid=false;return end
        local latest=events[event.EventId]
        local referenced=latest and payloadReferences(latest.State) or {}
        if not latest or latest.State.Phase~="Driving" or not P.Vehicle(model:GetAttributes(),event.EventId,referenced[model]) then owner.Valid=false;return end
        if os.clock()<nextFollow then return end
        nextFollow=os.clock()+.04
        local nextPose=pose();if not nextPose then owner.Valid=false;return end
        for _,piece in ipairs(c:GetDescendants())do if piece:IsA("BasePart")then if owner.Collisions[piece]==nil then owner.Collisions[piece]=piece.CanCollide end;piece.CanCollide=false end end
        r.CFrame=nextPose;r.AssemblyLinearVelocity=Vector3.zero;r.AssemblyAngularVelocity=Vector3.zero
    end
    owner.Connection=Run.PreSimulation:Connect(function()local ok=pcall(follow);if not ok then owner.Valid=false end end)
    follow()
    local report={EventId=event.EventId,BeforeHealth=model:GetAttribute("Health"),BeforeParts=(B.State.ReadInventory() or {})["Arrow Part"] or 0,Requests=0,Started=os.clock()}
    B.State.TransportAttempt=report
    local deadline=os.clock()+12
    while current(token,c) and owner.Valid and os.clock()<deadline and report.Requests<3 do
        if (B.State.Parts or 0)>0 then break end
        local state=native:getStates()
        if state.HeavyCD or state.SwingCooldown or state.Swinging or state.HeavySwinging or state.Stunned or state.CombatDisabled then task.wait(.15);continue end
        assert(A.Underground.Overlaps(model,r.CFrame,shape),"vehicle moved outside native hitbox")
        report.Requests+=1;attackNative=native;attackCharacter=c
        local done,attackError=false,nil
        attack=task.spawn(function()local ok,err=pcall(native.heavySwing,native);if not ok then attackError=err end;done=true end)
        local attackDeadline=os.clock()+4
        repeat task.wait(.05) until done or not current(token,c) or not owner.Valid or os.clock()>attackDeadline
        if not done then break end
        attack=nil;attackNative=nil;attackCharacter=nil
        assert(not attackError,attackError)
        task.wait(.25)
    end
    report.AfterParts=(B.State.ReadInventory() or {})["Arrow Part"] or 0
    report.AfterHealth=model:GetAttribute("Health")
    local latest=events[event.EventId]
    report.LootObserved=latest and latest.State.Phase=="Loot" or false
    report.Finished=os.clock()
end
if A.Get(id) then
    local ok,err=pcall(function()assert(A.Set("ArrowPartFarm",true));snapshot()end)
    if not ok then A.Features[id].Enabled=false;A.Error(id,err) end
end
A.Loop("money transport",1,function()
    if not A.Get(id) then return end
    local c,r,h=A.Character();if not c then return end
    B.State.TransportPriorityUntil=0
    local inv=B.State.ReadInventory() or {}
    if h.Health/h.MaxHealth>=.3 and (inv["Arrow Part"] or 0)<99 and not B.State.HoldForJoin then
        for eventId,record in pairs(events)do
            if record.State.Phase=="Driving" and os.clock()-record.Received<=450 and os.clock()>=(retry[eventId] or 0) and vehicle(record.State) then
                B.State.TransportPriorityUntil=os.clock()+2.5;break
            end
        end
    end
    if B.State.HoldForJoin then return end
    if P.ShouldYield({Phone=B.State.PhoneBusy,Craft=B.State.CraftBusy,Garden=A.GardenBusy(),Pickup=B.State.AutoBusy,
        Travel=B.State.RouteBusy or B.State.TeleportBusy or B.State.PlayerWarpBusy,Transfer=B.State.HopBusy or B.State.TransferPending or B.State.AutoHopPause,
        Flying=B.State.Flying,Parts=B.State.Parts or 0,Arrows=B.State.AutoArrow and B.State.Arrow or 0,Health=h.Health/h.MaxHealth,PartCount=inv["Arrow Part"] or 0}) then return end
    for _,feature in ipairs({"AutoFarm","AutoQuest","AutoPhone","QuestFarm","BountyFarm","AutoRoll"})do if A.Get(feature)then return end end
    for eventId,record in pairs(events)do
        if os.clock()-record.Received>450 then events[eventId]=nil;retry[eventId]=nil;streamAfter[eventId]=nil;continue end
        local event=record.State
        local model,part,points=vehicle(event)
        if event.Phase=="Loot" then requestArea(event,points);status("collecting transport drops with arrow part farm");continue end
        if os.clock()<(retry[eventId] or 0) then continue end
        if not model then requestArea(event,points);status("waiting for identified money transport vehicle");continue end
        retry[eventId]=os.clock()+30
        local token=generation
        status("attacking money transport")
        local ok,err=pcall(attackVehicle,event,model,part,token,c,r,h)
        cleanup()
        if generation==token and A.Current() then
            if not ok then A.Error(id,err) else A.Errors[id]=nil end
        end
        return
    end
    if not next(events) then status("waiting for money transport / collecting meteor parts") end
end)

    end)(advanced, bridge);
    (function(A, B)
local P=(function()
local P={}
function P.Goal(value)
    if type(value)~="number" or value~=value then return 20 end
    return math.clamp(math.floor(value),20,40)
end
function P.ownedCop(attrs,userId,name)
    return type(attrs)=="table" and attrs.FightableNPC==true and tonumber(attrs.PlayerBountyOwner)==userId
        and (not attrs.ForcedTargetName or attrs.ForcedTargetName==name)
end
function P.Target(state,modelName,attrs,userId,name)
    return type(state)=="table" and state.State=="Active" and state.Kind=="NPC" and state.UserId==0
        and type(state.CharacterName)=="string" and state.CharacterName==modelName and P.ownedCop(attrs,userId,name)
end
function P.Gained(before,level,xp)
    return before and type(level)=="number" and type(xp)=="number"
        and (level>before.Level or level==before.Level and xp>before.XP) or false
end
return P

end)()
local factory=(function()
return function(A,B,Policy,options)
    options=options or {}
    local prefix=options.Prefix or "PhoneCop"
    local Run=game:GetService("RunService")
    local lock
    local retry=setmetatable({},{__mode="k"})
    local C={Version=2}
    A[options.Store or "PhoneCopLock"]=C
    local function shape(native)
        if not debug or type(debug.getupvalues)~="function" then return end
        for _,profile in pairs(debug.getupvalues(native.lightSwing)) do
            if type(profile)=="table" and type(profile.M1Hitbox)=="table" and #profile.M1Hitbox>0 then
                local boxes={}
                for i,size in ipairs(profile.M1Hitbox) do
                    if typeof(size)~="Vector3" or size.X<=0 or size.Y<=0 or size.Z<=0 or size.Magnitude>100 then return end
                    local offset=profile.M1HitboxOffsets and profile.M1HitboxOffsets[i] or CFrame.new(0,0,-size.Z/2)
                    if typeof(offset)~="CFrame" then return end
                    boxes[#boxes+1]={Size=size,Offset=offset}
                end
                return boxes
            end
        end
    end
    function C.Release()
        local old=lock
        if not old then return end
        lock=nil
        for _,connection in ipairs(old.Connections) do connection:Disconnect() end
        for _,object in ipairs(old.Objects) do object:Destroy() end
        for part,value in pairs(old.Collisions) do if part.Parent then part.CanCollide=value end end
        if old.Root.Parent then
            old.Root.AssemblyLinearVelocity=Vector3.zero;old.Root.AssemblyAngularVelocity=Vector3.zero
            if B.Player.Character==old.Character then
                local position=old.Root.Position
                local look=old.TargetRoot.Parent and old.TargetRoot.CFrame.LookVector or Vector3.new(0,0,-1)
                old.Root.CFrame=CFrame.lookAt(position,position+Vector3.new(look.X,0,look.Z))
                old.Humanoid.AutoRotate=old.AutoRotate
            end
        end
        B.State[prefix.."LockActive"]=false
    end
    function C.Begin(target,native,current)
        if lock and lock.Target==target and lock.Character==B.Player.Character
            and target:FindFirstChild("HumanoidRootPart")==lock.TargetRoot
            and target:FindFirstChildOfClass("Humanoid")==lock.TargetHumanoid
            and lock.Character:FindFirstChild("HumanoidRootPart")==lock.Root
            and lock.Character:FindFirstChildOfClass("Humanoid")==lock.Humanoid
            and target.Parent and lock.TargetHumanoid.Health>0 and current()then lock.Valid=current;return true end
        C.Release()
        if not target.Parent or not current()then return false end
        if (retry[target] or 0)>os.clock() then return false end
        if not Policy.ownedCop(target:GetAttributes(),B.Player.UserId,B.Player.Name) then return false end
        local character,root,humanoid=A.Character()
        local targetRoot=target:FindFirstChild("HumanoidRootPart")
        local targetHumanoid=target:FindFirstChildOfClass("Humanoid")
        local boxes=shape(native)
        if not character or root.Anchored or not targetRoot or not targetHumanoid or targetHumanoid.Health<=0 or not boxes then return false end
        local params=OverlapParams.new();params.FilterType=Enum.RaycastFilterType.Include;params.FilterDescendantsInstances={targetRoot};params.MaxParts=1
        local old={Target=target,TargetRoot=targetRoot,TargetHumanoid=targetHumanoid,Character=character,Root=root,Humanoid=humanoid,AutoRotate=humanoid.AutoRotate,Collisions={},Objects={},Connections={},Valid=current,Height=options.Height or 4.75,Started=os.clock(),HP=targetHumanoid.Health,LastDamage=os.clock()}
        old.Offset=targetRoot.CFrame:VectorToWorldSpace(Vector3.new(0,0,options.Distance or 3))
        old.Distance=options.Distance or 3
        old.Depth=options.Depth or 5.5
        old.DepthStepAt=os.clock()
        old.PlayerHP=humanoid.Health
        local floorParams
        if options.Mode=="below"then
            floorParams=RaycastParams.new();floorParams.FilterType=Enum.RaycastFilterType.Include
            floorParams.FilterDescendantsInstances={workspace.Game.Map}
        end
        local function pose()
            if options.Mode=="below"then
                local position=targetRoot.Position-Vector3.new(0,old.Depth,0)
                local floor=workspace:Raycast(targetRoot.Position,Vector3.new(0,-32,0),floorParams)
                if not floor or floor.Position.Y-position.Y<1.25 then return nil end
                return CFrame.lookAt(position,targetRoot.Position,targetRoot.CFrame.RightVector)
            end
            if options.Mode=="behind" then
                if options.ResolveBehind then return options.ResolveBehind(targetRoot,old.Distance)end
                local offset=options.FollowFacing and targetRoot.CFrame:VectorToWorldSpace(Vector3.new(0,0,old.Distance))or old.Offset
                local position=targetRoot.Position+offset
                return CFrame.lookAt(position,targetRoot.Position)
            end
            local position=targetRoot.Position+Vector3.new(0,old.Height,0)
            return CFrame.lookAt(position,targetRoot.Position,targetRoot.CFrame.RightVector)
        end
        local function overlaps(at)
            for _,box in ipairs(boxes) do
                if options.Overlap then
                    if not options.Overlap(at*box.Offset,box.Size,targetRoot.CFrame,targetRoot.Size)then return false end
                elseif #workspace:GetPartBoundsInBox(at*box.Offset,box.Size,params)==0 then return false end
            end
            return true
        end
        local initialPose=pose()
        if options.Mode=="behind"and options.AdaptDistance then
            initialPose=nil
            for distance=old.Distance,3,-.25 do
                old.Distance=distance
                local candidate=pose()
                if candidate and overlaps(candidate)then
                    old.Distance=math.max(3,distance-.25);initialPose=pose();break
                end
            end
        end
        if options.Mode=="below" and options.MaxDepth then
            initialPose=nil
            for depth=options.MaxDepth,options.Depth or 5.5,-.25 do
                old.Depth=depth
                local candidate=pose()
                if candidate and overlaps(candidate)then
                    old.Depth=math.max(options.Depth or 5.5,depth-.35)
                    initialPose=pose();break
                end
            end
        end
        if not initialPose or not overlaps(initialPose)or(options.ValidatePose and not options.ValidatePose(initialPose,targetRoot))then return false end
        lock=old
        local attachment=Instance.new("Attachment");attachment.Name="SHARKWOW"..prefix.."Hold";attachment.Parent=root;old.Objects[#old.Objects+1]=attachment
        local velocity=Instance.new("LinearVelocity");velocity.Name="SHARKWOW"..prefix.."Hold";velocity.Attachment0=attachment;velocity.RelativeTo=Enum.ActuatorRelativeTo.World;velocity.MaxForce=math.huge;velocity.VectorVelocity=Vector3.zero;velocity.Parent=root;old.Objects[#old.Objects+1]=velocity
        humanoid.AutoRotate=false
        local telemetry={Version=2,Target=target.Name,Owner=B.Player.UserId,Mode=options.Mode or "above",Distance=options.Mode=="behind" and old.Distance or nil,Depth=options.Mode=="below" and old.Depth or nil,Height=old.Height,Before=old.HP,After=old.HP,Damage=0,IncomingDamage=0,PlayerBefore=humanoid.Health,PlayerAfter=humanoid.Health,Started=old.Started}
        B.State[prefix.."Result"]=telemetry;B.State[prefix.."LockActive"]=true
        local function pulse()
            if lock~=old then return end
            telemetry.PlayerAfter=humanoid.Health
            if humanoid.Health<old.PlayerHP then
                telemetry.IncomingDamage+=old.PlayerHP-humanoid.Health
                if options.RetreatOnDamage then
                    telemetry.Result="incoming damage; retreating";retry[target]=os.clock()+30;C.Release();return
                end
            end
            old.PlayerHP=humanoid.Health
            if not A.Current() or not old.Valid() or B.Player.Character~=character or not root.Parent or humanoid.Health<=0
                or not target.Parent or not targetRoot.Parent or targetHumanoid.Health<=0
                or target:FindFirstChild("HumanoidRootPart")~=targetRoot or target:FindFirstChildOfClass("Humanoid")~=targetHumanoid
                or character:FindFirstChild("HumanoidRootPart")~=root or character:FindFirstChildOfClass("Humanoid")~=humanoid
                or not Policy.ownedCop(target:GetAttributes(),B.Player.UserId,B.Player.Name) then
                telemetry.After=targetHumanoid.Health;telemetry.Damage=math.max(0,telemetry.Before-telemetry.After);C.Release();return
            end
            if targetHumanoid.Health<old.HP then old.LastDamage=os.clock() end
            old.HP=targetHumanoid.Health
            telemetry.After=targetHumanoid.Health;telemetry.Damage=math.max(0,telemetry.Before-telemetry.After)
            if os.clock()-old.LastDamage>5 then old.Height=options.FallbackHeight or 4;telemetry.Height=old.Height end
            if options.Mode=="below" and options.AdaptDepth and os.clock()-old.LastDamage>3
                and os.clock()-old.DepthStepAt>3 and old.Depth>(options.Depth or 5.5)then
                local previousDepth=old.Depth
                old.Depth=math.max(options.Depth or 5.5,old.Depth-.25)
                local candidate=pose()
                if not candidate or not overlaps(candidate)then old.Depth=previousDepth end
                old.DepthStepAt=os.clock();telemetry.Depth=old.Depth
            end
            if os.clock()-old.LastDamage>(options.NoDamageTimeout or 12) then telemetry.Result="no damage; released";retry[target]=os.clock()+30;C.Release();return end
            local at=pose()
            if not at then telemetry.Result="no supported underground attack position";C.Release();return end
            if options.ValidatePose and not options.ValidatePose(at,targetRoot)then telemetry.Result="unsafe target position";C.Release();return end
            if options.Mode=="behind" and options.AdaptDistance and not overlaps(at)then
                for distance=old.Distance-.25,3,-.25 do
                    old.Distance=distance
                    local candidate=pose()
                    if candidate and overlaps(candidate)and(not options.ValidatePose or options.ValidatePose(candidate,targetRoot))then
                        at=candidate;telemetry.Distance=distance;break
                    end
                end
            end
            if not overlaps(at) then telemetry.Result="target outside native hitbox";C.Release();return end
            for _,part in ipairs(character:GetDescendants()) do
                if part:IsA("BasePart") then
                    if old.Collisions[part]==nil then old.Collisions[part]=part.CanCollide end
                    part.CanCollide=false
                end
            end
            root.AssemblyLinearVelocity=Vector3.zero;root.AssemblyAngularVelocity=Vector3.zero;root.CFrame=at
        end
        local function safePulse()
            local owned=lock==old
            local ok,err=pcall(pulse)
            if not ok then C.Release();A.Error(options.Error or "phone cop lock",err) end
            if owned and lock~=old and type(C.OnLost)=="function"then
                local good,reason=pcall(C.OnLost)
                if not good then A.Error(options.Error or "target lock cleanup",reason)end
            end
        end
        old.Connections[#old.Connections+1]=Run.PreSimulation:Connect(safePulse)
        old.Connections[#old.Connections+1]=Run.PostSimulation:Connect(safePulse)
        safePulse()
        return lock==old
    end
    A.Cleanups[#A.Cleanups+1]=C.Release
    return C
end

end)()
local id="AutoLevel20"
local Http=game:GetService("HttpService")
local player=B.Player
local remote=game:GetService("ReplicatedStorage").Remotes:FindFirstChild("PlayerBounties")
local path="sharkwow-standout-level-"..player.UserId..".json"
local config={Schema=1,UserId=player.UserId,Enabled=false}
local ok,saved=pcall(function()return Http:JSONDecode(readfile(path))end)
if ok and type(saved)=="table" and saved.Schema==1 and saved.UserId==player.UserId then config=saved end
local function goal()return P.Goal(config.Goal)end
B.State.LevelTarget=goal()
local highway=player.Data.Stand.Value=="Highway Star"
local combatOptions={Prefix="Level",Store="LevelLock",Error="level target lock",Mode="below",Depth=4.5,MaxDepth=5.85,AdaptDepth=true,NoDamageTimeout=18,RetreatOnDamage=true}
if highway then
    combatOptions.Mode="behind";combatOptions.Distance=4;combatOptions.FollowFacing=true
    combatOptions.AdaptDistance=true;combatOptions.RetreatOnDamage=false
end
local lock=factory(A,B,P,combatOptions)
local levelSkills=highway and {["Footprint Flurry"]=true,["Nutrient Siphon"]=true} or nil
local generation,nextAction,nextSync=0,0,0
local state,acquired,attack,native,attackCharacter,returnPose,before=nil,false,nil,nil,nil,nil,nil
local startedByUs=false
local lastHeavy=false
local lastTarget,attemptStart,lastHP,lastDamage
local pendingReward
local guardNative,guardCharacter
local function releaseGuard()
    if guardNative and player.Character==guardCharacter then
        pcall(function()guardNative:getStates().HoldingBlock=false;guardNative:blockStop()end)
    end
    guardNative=nil;guardCharacter=nil;B.State.LevelGunGuard=false
end
local reports={}
B.State.LevelReports=reports
B.State.LevelFarmVersion=5
B.State.LevelM1Only=false
B.State.LevelCombatProfile=highway and "highway rear follow" or "default"
local function status(value)B.State.LevelStatus=value end
local function save()writefile(path,Http:JSONEncode(config))end
function B.State.SetLevelGoal(value)
    assert(type(value)=="number" and value==P.Goal(value),"level goal must be an integer from 20 to 40")
    local old=config.Goal;config.Goal=value
    local ok,err=pcall(save);if not ok then config.Goal=old;error(err)end
    B.State.LevelTarget=goal();B.State.LevelGoalReady=player.Data.Stats.Level.Value>=goal()
end
local function current(token,c)
    return A.Current() and A.Get(id) and generation==token and player.Character==c
        and not B.State.PhoneBusy and not B.State.TransferPending and not B.State.HopBusy and not B.State.AutoHopPause
        and not B.State.Flying and not B.State.HoldForJoin and player.Data.Stats.Level.Value<goal()
end
local function cleanup()
    if A.ReleaseFarmSkill then A.ReleaseFarmSkill("level")end
    releaseGuard()
    lock.Release()
    if attack and coroutine.status(attack)~="dead" then
        if native and player.Character==attackCharacter then
            if type(native.cancelAttacksForStandReplacement)=="function"then pcall(native.cancelAttacksForStandReplacement,native)end
            if type(native.finishBasicAttack)=="function"then pcall(native.finishBasicAttack,native,true)end
            local h=attackCharacter:FindFirstChildOfClass("Humanoid")
            if h and type(native.getGroundWalkSpeed)=="function"then local good,speed=pcall(native.getGroundWalkSpeed,native,false);if good then h.WalkSpeed=speed end end
        end
        pcall(task.cancel,attack)
    end
    attack=nil;native=nil;attackCharacter=nil
    if acquired then
        acquired=false;B.State.LevelBusy=false;B.State.CraftBusy=false;B.State.ExtensionPause=false
        local c,r=A.Character()
        if returnPose and c==returnPose.Character then r.CFrame=returnPose.CFrame;r.AssemblyLinearVelocity=Vector3.zero end
    end
    returnPose=nil;B.State.LevelPriorityUntil=0
end
lock.OnLost=function()
    cleanup();nextAction=os.clock()+3;status("attack position released; recovering")
end
local function observe(data)
    if type(data)~="table" or type(data.State)~="string"then return end
    state=data;B.State.LevelTargetState=data
    if data.State=="Completed" then
        if before then pendingReward={Before=before,At=os.clock(),Target=lastTarget,Started=attemptStart};before=nil end
        cleanup();nextAction=os.clock()+3;startedByUs=false
    elseif data.State=="Cancelled" then cleanup();nextAction=os.clock()+15;before=nil;startedByUs=false end
end
if remote then A.Connect(remote.OnClientEvent,observe)end
A.Add({Id=id,Name="auto level to target",Group="quests",Description="Repeats your assigned NPC elimination, checks real EXP gains and stops at the saved level target (20 to 40). Keeps map farming available between fights. No player targets or shop purchases.",Set=function(value)
    if value then assert(remote,"elimination channel unavailable");assert(player.Data.Stats.Level.Value<goal(),"level target already reached")end
    local old=config.Enabled;config.Enabled=value;local good,err=pcall(save);if not good then config.Enabled=old;error(err)end
    generation+=1;cleanup();nextAction=0;nextSync=0
    if value then status("checking NPC elimination")else status("level farm stopped")end
end})
A.Features[id].Enabled=config.Enabled==true and player.Data.Stats.Level.Value<goal() and not B.State.HoldForJoin
A.Cleanups[#A.Cleanups+1]=function()generation+=1;cleanup()end
local function tick()
    if pendingReward then
        local record=pendingReward
        local level,xp=player.Data.Stats.Level.Value,player.Data.Experience.Value
        if P.Gained(record.Before,level,xp) or os.clock()-record.At>8 then
            record.After={Level=level,XP=xp};record.Confirmed=P.Gained(record.Before,level,xp);record.Seconds=record.Started and os.clock()-record.Started or nil
            reports[#reports+1]=record;if #reports>20 then table.remove(reports,1)end
            pendingReward=nil
            if not record.Confirmed then A.Set(id,false);A.Error(id,"elimination completed without confirmed EXP gain");return end
        end
    end
    if not A.Get(id)then return end
    if player.Data.Stats.Level.Value>=goal() then A.Set(id,false);B.State.LevelGoalReady=true;status("level "..goal().." reached; level farm stopped");return end
    local c,r,h=A.Character()
    local token=generation
    if not c or not current(token,c)then cleanup();return end
    if os.clock()<nextAction then return end
    if not state or os.clock()>nextSync then
        nextSync=os.clock()+15;remote:FireServer("Sync")
        if not state then return end
    end
    if state.State=="Completed"or state.State=="Cancelled"then state={State="Idle"}end
    if state.State=="Idle"then
        if pendingReward or A.GardenBusy() or B.State.CraftBusy or B.State.AutoBusy then return end
        before={Level=player.Data.Stats.Level.Value,XP=player.Data.Experience.Value}
        attemptStart=os.clock();startedByUs=true;nextAction=os.clock()+5
        state={State="Searching"};remote:FireServer("Start");status("requesting NPC elimination");return
    end
    if state.State~="Active"then status(state.Message or "waiting for elimination assignment");return end
    if state.Kind~="NPC" or state.UserId~=0 then
        cleanup();status("skipping player elimination")
        nextAction=os.clock()+15;remote:FireServer("Cancel")
        return
    end
    if h.Health<h.MaxHealth*.35 then cleanup();nextAction=os.clock()+8;status("recovering before next attack");return end
    B.State.LevelPriorityUntil=os.clock()+2
    if not acquired then
        if not A.MovementFree() or B.State.ExtensionPause then return end
        if B.State.ReleaseIdleHide then B.State.ReleaseIdleHide()end
        if B.ReleaseFarmHold then B.ReleaseFarmHold()end
        A.Underground.Release(nil,true)
        returnPose={Character=c,CFrame=r.CFrame}
        acquired=true;B.State.LevelBusy=true;B.State.CraftBusy=true;B.State.ExtensionPause=true
    end
    local target=workspace.Game.Players:FindFirstChild(state.CharacterName)
    if not target then
        if typeof(state.Position)=="Vector3"then B.State.RequestStream(state.Position,2)end
        if not current(token,c)then cleanup();return end
        cleanup();nextAction=os.clock()+3;status("loading assigned NPC");return
    end
    if not P.Target(state,target.Name,target:GetAttributes(),player.UserId,player.Name)then cleanup();nextAction=os.clock()+10;status("assigned NPC ownership mismatch");return end
    local th=target:FindFirstChildOfClass("Humanoid")
    if not th or th.Health<=0 then cleanup();nextAction=os.clock()+1;status("waiting for elimination reward");return end
    if lastTarget~=target.Name then
        lastTarget=target.Name;lastHP=th.Health;lastDamage=os.clock()
        before=before or {Level=player.Data.Stats.Level.Value,XP=player.Data.Experience.Value}
        attemptStart=attemptStart or os.clock()
    end
    if th.Health<lastHP then lastDamage=os.clock()end
    lastHP=th.Health
    if os.clock()-lastDamage>18 then cleanup();lastDamage=os.clock();nextAction=os.clock()+15;status("no damage; retrying after recovery");return end
    if attack and coroutine.status(attack)~="dead"then return end
    native=A.Native();if not native then cleanup();return end
    local states=native:getStates()
    if states.Stunned or states.SwingCooldown or states.Swinging or states.HeavySwinging then return end
    if not states.Summoned and player.Data.Stand.Value~="" then native:summonStand(true);nextAction=os.clock()+1;return end
    local locked=lock.Begin(target,native,function()return current(token,c) and h.Health>=h.MaxHealth*.35 and state and P.Target(state,target.Name,target:GetAttributes(),player.UserId,player.Name)end)
    if not locked then cleanup();nextAction=os.clock()+3;status("waiting for native attack reach");return end
    attackCharacter=c
    status("level "..player.Data.Stats.Level.Value.." / "..goal().." - "..state.DisplayName)
    local controller=native
    local gun=target:GetAttribute("GloryDaysGunDrawn")==true
    local ammo=target:GetAttribute("GloryDaysAmmo")
    local reloading=target:GetAttribute("GloryDaysReloading")==true
    if gun and type(ammo)=="number" and ammo>0 and not reloading and not (B.State.LevelResult and B.State.LevelResult.Mode=="below")then
        if not guardNative then
            states.HoldingBlock=true;controller:blockStart();guardNative=controller;guardCharacter=c
            B.State.LevelGuardAttempts=(B.State.LevelGuardAttempts or 0)+1
        end
        B.State.LevelGunGuard=true;status("guarding gunfire; attack during reload")
        nextAction=os.clock()+.1;return
    end
    releaseGuard()
    if player.Data.SkillActive.Value then return end
    local swing=not lastHeavy and not states.HeavyCD and type(controller.heavySwing)=="function" and controller.heavySwing or controller.lightSwing
    lastHeavy=swing==controller.heavySwing
    B.State.LevelAttackKind=swing==controller.heavySwing and "M2" or "M1"
    attack=task.spawn(function()
        local good,err=pcall(swing,controller)
        if not good and current(token,c)then A.Error(id,err)end
    end)
    nextAction=os.clock()+.25
end
A.Loop("level to twenty",.2,function()
    local good,err=pcall(tick)
    if not good then cleanup();nextAction=os.clock()+10;A.Error(id,err)end
end)

    end)(advanced, bridge);
    (function(A, B)
-- Keep the feature id and filename so saved profiles cannot revive the old allocator.
local id="AutoStrength"
local Http=game:GetService("HttpService")
local player=B.Player
local stats=player.Data.Stats
local remote=game:GetService("ReplicatedStorage").Remotes.Data
local path="sharkwow-standout-strength-"..player.UserId..".json"
local config={Schema=2,UserId=player.UserId,Enabled=false,Target="Health"}
local loadError
local ok,saved=pcall(function()return Http:JSONDecode(readfile(path))end)
if not ok then
    local checked,exists=pcall(function()return isfile(path)end)
    if not checked or exists then loadError="stat settings unreadable; existing journal preserved"end
elseif saved~=nil and type(saved)~="table" then
    loadError="invalid stat settings; existing journal preserved"
end
if ok and type(saved)=="table" and saved.UserId==player.UserId then
    if saved.Schema==1 then
        config.Enabled=saved.Enabled==true
        if saved.Pending~=nil then
            local p=saved.Pending
            config.Pending=type(p)=="table" and {Stat="Damage",Before=p.Damage,Amount=p.Amount,At=p.At} or p
        end
    elseif saved.Schema==2 and (saved.Target=="Health"or saved.Target=="Balanced") then config=saved
    else loadError="unsupported stat settings; existing journal preserved"end
end
local generation,worker=0,nil
local function save()writefile(path,Http:JSONEncode(config))end
local function integer(value)
    return type(value)=="number" and value==value and math.abs(value)<math.huge and value==math.floor(value) and value>=0
end
local function statValue(name)
    local value=stats:FindFirstChild(name)
    if value and integer(value.Value) then return value.Value end
end
local function reconcile()
    local p=config.Pending
    if p==nil then return true end
    if type(p)~="table" or (p.Stat~="Health" and p.Stat~="Damage") or not integer(p.Before) or not integer(p.Amount) or p.Amount<1 or p.Amount>10000 then return false end
    local value=statValue(p.Stat)
    if value and value>=p.Before+p.Amount then
        B.State.HealthLast={Stat=p.Stat,Before=p.Before,After=value,Amount=p.Amount,Confirmed=true}
        if config.Target=="Balanced"then config.NextStat=p.Stat=="Health"and"Damage"or"Health"end
        config.Pending=nil;save();return true
    end
    return false
end
A.Add({Id=id,Name="auto health",Group="combat",Description="Spends unallocated points on Health, including points gained later. Never resets existing stats. Preserves pending requests when migrating old Strength settings.",Set=function(value)
    if value then
        assert(not loadError,loadError)
        assert(reconcile(),"previous stat allocation not confirmed")
        assert(statValue("Health")~=nil,"native Health stat unavailable; no points sent")
    end
    local old=config.Enabled;config.Enabled=value;local good,err=pcall(save);if not good then config.Enabled=old;error(err)end
    generation+=1
end})
local persisted,storageError=false,loadError
if not loadError then persisted,storageError=pcall(save)end
A.Features[id].Enabled=persisted and config.Enabled==true
if not persisted then A.Error(id,storageError)end
B.State.AutoHealthVersion=2
B.State.StatAllocationTarget="Health"
function B.State.SetStatAllocationTarget(target)
    assert(target=="Health"or target=="Balanced","unknown stat allocation target")
    assert(not worker and reconcile(),"pending allocation must finish first")
    config.Target=target;config.NextStat=config.NextStat or "Damage";save()
    B.State.StatAllocationTarget=target
end
B.State.StatAllocationTarget=config.Target
A.Cleanups[#A.Cleanups+1]=function()generation+=1;if worker then pcall(task.cancel,worker);worker=nil end end
A.Loop("auto health",1,function()
    if not A.Get(id) or worker then return end
    if not reconcile()then A.Set(id,false);A.Error(id,"pending stat allocation unresolved; stopped without repeating");return end
    local amount=statValue("Points")
    local stat=config.Target=="Balanced"and(config.NextStat=="Health"and"Health"or"Damage")or"Health"
    local before=statValue(stat)
    if not amount or amount>10000 or before==nil then
        A.Set(id,false);A.Error(id,"native Health/Points unavailable or invalid; no points sent");return
    end
    if amount<1 then B.State.HealthStatus="all points allocated";return end
    if config.Target=="Balanced"then amount=1 end
    local token=generation
    config.Pending={Stat=stat,Before=before,Amount=amount,At=os.time()};save()
    B.State.HealthStatus="allocating "..amount.." points to "..stat
    local done=false
    worker=task.spawn(function()
        if not A.Current()or generation~=token or not A.Get(id)then done=true;return end
        local success,err=pcall(remote.InvokeServer,remote,"Stats",stat,amount)
        if not success and A.Current()then A.Error(id,err)end
        done=true
    end)
    local deadline=os.clock()+10
    repeat task.wait(.1)until done or not A.Current()or generation~=token or os.clock()>deadline
    if not done then pcall(task.cancel,worker)end
    worker=nil
    if not A.Current()or generation~=token then return end
    local untilAt=os.clock()+2
    repeat if reconcile()then B.State.HealthStatus="health allocation confirmed";return end;task.wait(.1)until os.clock()>untilAt
    if A.Get(id)then A.Set(id,false)end
    A.Error(id,"health allocation outcome unconfirmed; automatic retry stopped")
end)

    end)(advanced, bridge);
    (function(A, B)
local P=(function()
local P={}
function P.SelectTarget(previous,models,valid,distance)
    if previous and valid(previous)then return previous end
    local target,score=nil,math.huge
    for _,model in ipairs(models)do
        if valid(model)then
            local value=distance(model)
            if value<score then target=model;score=value end
        end
    end
    return target
end
function P.Set(csv)
    local result={}
    for value in tostring(csv or ""):gmatch("[^,]+")do result[value]=true end
    return result
end
function P.Owned(attrs,userId)
    for _,key in ipairs({"StoryPromptOwnerId","StoryOwnerUserId","OwnerUserId","TutorialCopOwner","PlayerBountyOwner"})do
        local value=tonumber(attrs[key])
        if value and value~=0 and value~=userId then return false end
    end
    return true
end
function P.Target(quest,attrs,name,userId,playerName)
    if quest.Objectives and quest.Objectives["Defeat Diamotch Guard"] and attrs.DiamotchStoryGuard==true
        and attrs.Config=="Guard Taser" and type(playerName)=="string" and attrs.ForcedTargetName==playerName
        and P.Owned(attrs,userId) then return true end
    local storyEnemy=attrs.StoryEncounterCredit==true and (attrs.StoryBoss==true or attrs.Part9StoryNPC==true)
        and type(playerName)=="string" and attrs.ForcedTargetName==playerName
    if (attrs.FightableNPC~=true and not storyEnemy) or not P.Owned(attrs,userId)then return false end
    local config=attrs.Config or name
    for objective in pairs(quest.Objectives or {})do
        local target=objective:match("^Defeat (.+)$")
        if target and (config==target or name==target)then return true end
        if target=="Land Registry Guard"and attrs.LandRegistryGuard==true and config=="Guard Gun"then return true end
    end
    return false
end
function P.Prompt(questId,attrs,name,parentName,objectives)
    if type(attrs.ObjectiveTag)=="string" and type(objectives)=="table" and objectives["Interact_"..attrs.ObjectiveTag] then return true end
    if P.Set(attrs.StoryQuestIds)[questId]then return true end
    if(questId=="P9_23A_PICK_UP_USAGI"or questId=="P9_24_GO_TO_HOSPITAL"or questId=="P9_27_FIND_MRI_ROOM")and name=="UsagiPickupPrompt"and attrs.StoryAction=="Pickup"and attrs.QuestBound==true then return true end
    if questId=="P9_22C_DELIVER_JODIO_CROP"and name=="LandRegistryStoryPrompt"and attrs.StoryServerDialogue==true then return true end
    if questId=="P9_08_SIT_DIAMOTCH_BACK_ROOM" and name=="SeatSit"
        and type(parentName)=="string"and parentName:match("^DiamotchCouchSeat%d+$")then return true end
    return questId=="P9_02B_LOCATE_HIDDEN_VAULT" and attrs.StoryAction=="SecretBookshelf"
end
function P.Choice(text)
    text=text:lower()
    if text=="" or text=="no" or text=="bye" or text=="leave"then return false end
    for _,term in ipairs({"buy","purchase","robux","reset","reroll","trade","gift","never mind","nevermind","not now","goodbye","cancel"})do
        if text:find(term,1,true)then return false end
    end
    return true
end
function P.Advance(text)
    return ({["okay."]=true,["okay"]=true,["ok"]=true,["ok."]=true,["continue"]=true,["continue."]=true,["..."]=true})[text:lower()]==true
end
return P

end)()
local factory=(function()
return function(A,B,Policy,options)
    options=options or {}
    local prefix=options.Prefix or "PhoneCop"
    local Run=game:GetService("RunService")
    local lock
    local retry=setmetatable({},{__mode="k"})
    local C={Version=2}
    A[options.Store or "PhoneCopLock"]=C
    local function shape(native)
        if not debug or type(debug.getupvalues)~="function" then return end
        for _,profile in pairs(debug.getupvalues(native.lightSwing)) do
            if type(profile)=="table" and type(profile.M1Hitbox)=="table" and #profile.M1Hitbox>0 then
                local boxes={}
                for i,size in ipairs(profile.M1Hitbox) do
                    if typeof(size)~="Vector3" or size.X<=0 or size.Y<=0 or size.Z<=0 or size.Magnitude>100 then return end
                    local offset=profile.M1HitboxOffsets and profile.M1HitboxOffsets[i] or CFrame.new(0,0,-size.Z/2)
                    if typeof(offset)~="CFrame" then return end
                    boxes[#boxes+1]={Size=size,Offset=offset}
                end
                return boxes
            end
        end
    end
    function C.Release()
        local old=lock
        if not old then return end
        lock=nil
        for _,connection in ipairs(old.Connections) do connection:Disconnect() end
        for _,object in ipairs(old.Objects) do object:Destroy() end
        for part,value in pairs(old.Collisions) do if part.Parent then part.CanCollide=value end end
        if old.Root.Parent then
            old.Root.AssemblyLinearVelocity=Vector3.zero;old.Root.AssemblyAngularVelocity=Vector3.zero
            if B.Player.Character==old.Character then
                local position=old.Root.Position
                local look=old.TargetRoot.Parent and old.TargetRoot.CFrame.LookVector or Vector3.new(0,0,-1)
                old.Root.CFrame=CFrame.lookAt(position,position+Vector3.new(look.X,0,look.Z))
                old.Humanoid.AutoRotate=old.AutoRotate
            end
        end
        B.State[prefix.."LockActive"]=false
    end
    function C.Begin(target,native,current)
        if lock and lock.Target==target and lock.Character==B.Player.Character
            and target:FindFirstChild("HumanoidRootPart")==lock.TargetRoot
            and target:FindFirstChildOfClass("Humanoid")==lock.TargetHumanoid
            and lock.Character:FindFirstChild("HumanoidRootPart")==lock.Root
            and lock.Character:FindFirstChildOfClass("Humanoid")==lock.Humanoid
            and target.Parent and lock.TargetHumanoid.Health>0 and current()then lock.Valid=current;return true end
        C.Release()
        if not target.Parent or not current()then return false end
        if (retry[target] or 0)>os.clock() then return false end
        if not Policy.ownedCop(target:GetAttributes(),B.Player.UserId,B.Player.Name) then return false end
        local character,root,humanoid=A.Character()
        local targetRoot=target:FindFirstChild("HumanoidRootPart")
        local targetHumanoid=target:FindFirstChildOfClass("Humanoid")
        local boxes=shape(native)
        if not character or root.Anchored or not targetRoot or not targetHumanoid or targetHumanoid.Health<=0 or not boxes then return false end
        local params=OverlapParams.new();params.FilterType=Enum.RaycastFilterType.Include;params.FilterDescendantsInstances={targetRoot};params.MaxParts=1
        local old={Target=target,TargetRoot=targetRoot,TargetHumanoid=targetHumanoid,Character=character,Root=root,Humanoid=humanoid,AutoRotate=humanoid.AutoRotate,Collisions={},Objects={},Connections={},Valid=current,Height=options.Height or 4.75,Started=os.clock(),HP=targetHumanoid.Health,LastDamage=os.clock()}
        old.Offset=targetRoot.CFrame:VectorToWorldSpace(Vector3.new(0,0,options.Distance or 3))
        old.Distance=options.Distance or 3
        old.Depth=options.Depth or 5.5
        old.DepthStepAt=os.clock()
        old.PlayerHP=humanoid.Health
        local floorParams
        if options.Mode=="below"then
            floorParams=RaycastParams.new();floorParams.FilterType=Enum.RaycastFilterType.Include
            floorParams.FilterDescendantsInstances={workspace.Game.Map}
        end
        local function pose()
            if options.Mode=="below"then
                local position=targetRoot.Position-Vector3.new(0,old.Depth,0)
                local floor=workspace:Raycast(targetRoot.Position,Vector3.new(0,-32,0),floorParams)
                if not floor or floor.Position.Y-position.Y<1.25 then return nil end
                return CFrame.lookAt(position,targetRoot.Position,targetRoot.CFrame.RightVector)
            end
            if options.Mode=="behind" then
                if options.ResolveBehind then return options.ResolveBehind(targetRoot,old.Distance)end
                local offset=options.FollowFacing and targetRoot.CFrame:VectorToWorldSpace(Vector3.new(0,0,old.Distance))or old.Offset
                local position=targetRoot.Position+offset
                return CFrame.lookAt(position,targetRoot.Position)
            end
            local position=targetRoot.Position+Vector3.new(0,old.Height,0)
            return CFrame.lookAt(position,targetRoot.Position,targetRoot.CFrame.RightVector)
        end
        local function overlaps(at)
            for _,box in ipairs(boxes) do
                if options.Overlap then
                    if not options.Overlap(at*box.Offset,box.Size,targetRoot.CFrame,targetRoot.Size)then return false end
                elseif #workspace:GetPartBoundsInBox(at*box.Offset,box.Size,params)==0 then return false end
            end
            return true
        end
        local initialPose=pose()
        if options.Mode=="behind"and options.AdaptDistance then
            initialPose=nil
            for distance=old.Distance,3,-.25 do
                old.Distance=distance
                local candidate=pose()
                if candidate and overlaps(candidate)then
                    old.Distance=math.max(3,distance-.25);initialPose=pose();break
                end
            end
        end
        if options.Mode=="below" and options.MaxDepth then
            initialPose=nil
            for depth=options.MaxDepth,options.Depth or 5.5,-.25 do
                old.Depth=depth
                local candidate=pose()
                if candidate and overlaps(candidate)then
                    old.Depth=math.max(options.Depth or 5.5,depth-.35)
                    initialPose=pose();break
                end
            end
        end
        if not initialPose or not overlaps(initialPose)or(options.ValidatePose and not options.ValidatePose(initialPose,targetRoot))then return false end
        lock=old
        local attachment=Instance.new("Attachment");attachment.Name="SHARKWOW"..prefix.."Hold";attachment.Parent=root;old.Objects[#old.Objects+1]=attachment
        local velocity=Instance.new("LinearVelocity");velocity.Name="SHARKWOW"..prefix.."Hold";velocity.Attachment0=attachment;velocity.RelativeTo=Enum.ActuatorRelativeTo.World;velocity.MaxForce=math.huge;velocity.VectorVelocity=Vector3.zero;velocity.Parent=root;old.Objects[#old.Objects+1]=velocity
        humanoid.AutoRotate=false
        local telemetry={Version=2,Target=target.Name,Owner=B.Player.UserId,Mode=options.Mode or "above",Distance=options.Mode=="behind" and old.Distance or nil,Depth=options.Mode=="below" and old.Depth or nil,Height=old.Height,Before=old.HP,After=old.HP,Damage=0,IncomingDamage=0,PlayerBefore=humanoid.Health,PlayerAfter=humanoid.Health,Started=old.Started}
        B.State[prefix.."Result"]=telemetry;B.State[prefix.."LockActive"]=true
        local function pulse()
            if lock~=old then return end
            telemetry.PlayerAfter=humanoid.Health
            if humanoid.Health<old.PlayerHP then
                telemetry.IncomingDamage+=old.PlayerHP-humanoid.Health
                if options.RetreatOnDamage then
                    telemetry.Result="incoming damage; retreating";retry[target]=os.clock()+30;C.Release();return
                end
            end
            old.PlayerHP=humanoid.Health
            if not A.Current() or not old.Valid() or B.Player.Character~=character or not root.Parent or humanoid.Health<=0
                or not target.Parent or not targetRoot.Parent or targetHumanoid.Health<=0
                or target:FindFirstChild("HumanoidRootPart")~=targetRoot or target:FindFirstChildOfClass("Humanoid")~=targetHumanoid
                or character:FindFirstChild("HumanoidRootPart")~=root or character:FindFirstChildOfClass("Humanoid")~=humanoid
                or not Policy.ownedCop(target:GetAttributes(),B.Player.UserId,B.Player.Name) then
                telemetry.After=targetHumanoid.Health;telemetry.Damage=math.max(0,telemetry.Before-telemetry.After);C.Release();return
            end
            if targetHumanoid.Health<old.HP then old.LastDamage=os.clock() end
            old.HP=targetHumanoid.Health
            telemetry.After=targetHumanoid.Health;telemetry.Damage=math.max(0,telemetry.Before-telemetry.After)
            if os.clock()-old.LastDamage>5 then old.Height=options.FallbackHeight or 4;telemetry.Height=old.Height end
            if options.Mode=="below" and options.AdaptDepth and os.clock()-old.LastDamage>3
                and os.clock()-old.DepthStepAt>3 and old.Depth>(options.Depth or 5.5)then
                local previousDepth=old.Depth
                old.Depth=math.max(options.Depth or 5.5,old.Depth-.25)
                local candidate=pose()
                if not candidate or not overlaps(candidate)then old.Depth=previousDepth end
                old.DepthStepAt=os.clock();telemetry.Depth=old.Depth
            end
            if os.clock()-old.LastDamage>(options.NoDamageTimeout or 12) then telemetry.Result="no damage; released";retry[target]=os.clock()+30;C.Release();return end
            local at=pose()
            if not at then telemetry.Result="no supported underground attack position";C.Release();return end
            if options.ValidatePose and not options.ValidatePose(at,targetRoot)then telemetry.Result="unsafe target position";C.Release();return end
            if options.Mode=="behind" and options.AdaptDistance and not overlaps(at)then
                for distance=old.Distance-.25,3,-.25 do
                    old.Distance=distance
                    local candidate=pose()
                    if candidate and overlaps(candidate)and(not options.ValidatePose or options.ValidatePose(candidate,targetRoot))then
                        at=candidate;telemetry.Distance=distance;break
                    end
                end
            end
            if not overlaps(at) then telemetry.Result="target outside native hitbox";C.Release();return end
            for _,part in ipairs(character:GetDescendants()) do
                if part:IsA("BasePart") then
                    if old.Collisions[part]==nil then old.Collisions[part]=part.CanCollide end
                    part.CanCollide=false
                end
            end
            root.AssemblyLinearVelocity=Vector3.zero;root.AssemblyAngularVelocity=Vector3.zero;root.CFrame=at
        end
        local function safePulse()
            local owned=lock==old
            local ok,err=pcall(pulse)
            if not ok then C.Release();A.Error(options.Error or "phone cop lock",err) end
            if owned and lock~=old and type(C.OnLost)=="function"then
                local good,reason=pcall(C.OnLost)
                if not good then A.Error(options.Error or "target lock cleanup",reason)end
            end
        end
        old.Connections[#old.Connections+1]=Run.PreSimulation:Connect(safePulse)
        old.Connections[#old.Connections+1]=Run.PostSimulation:Connect(safePulse)
        safePulse()
        return lock==old
    end
    A.Cleanups[#A.Cleanups+1]=C.Release
    return C
end

end)()
local garden=(function()
return function(A,B)
    local player=B.Player
    local Http=game:GetService("HttpService")
    local remote=game:GetService("ReplicatedStorage").Remotes.Gardening
    local controller=require(player.PlayerScripts.Core.Gardening).GrowingController
    local nextAt,session,ownedSession,held=0,nil,nil,nil
    local attempts={}
    local function active()
        for _,value in pairs(debug.getupvalues(controller.Update))do
            if type(value)=="table"and value.Token and value.Payload then return value end
        end
    end
    local function send(a,action,args)
        for _,value in pairs(debug.getupvalues(controller.start))do
            if type(value)=="function"and debug.info(value,"n")=="send"then return value(a,action,args)end
        end
        error("native garden input unavailable")
    end
    local function resetDrag(a)
        if a then a.Dragging=false;a.PadDragging=false end
    end
    local G={}
    function G.Release()
        nextAt=0;session=nil;attempts={}
        if held then pcall(held.InputHoldEnd,held);held=nil end
        local old=ownedSession;ownedSession=nil
        resetDrag(old)
        if old and active()==old then pcall(controller.leave,controller)end
    end
    A.Cleanups[#A.Cleanups+1]=G.Release
    function G.Step(questId,current,travel)
        if questId~="P9_22A_JODIO_GOOD_STUFF"then return false end
        if not current()then G.Release();return true end
        local folder=workspace.Game:FindFirstChild("Gardening")
        if not folder then return true,"waiting for garden to load"end
        local mark=player:GetAttribute("JodioGardenTarget")
        if typeof(mark)~="Vector3"then return true,"waiting for garden marker"end
        if os.clock()<nextAt then return true,B.State.StoryGardenStatus end
        local pot,distance=nil,math.huge
        local pots=folder:FindFirstChild("Pots")
        for _,model in ipairs(pots and pots:GetChildren()or{})do
            if model:GetAttribute("OwnerUserId")==player.UserId then
                local d=(model:GetPivot().Position-mark).Magnitude
                if d<distance then pot=model;distance=d end
            end
        end
        local a=active()
        if a and not a.Closing then
            if not pot or a.Payload.Model~=pot or distance>6 then return true,"waiting for the marked personal pot"end
            ownedSession=a
            if session~=a then session=a;attempts={}end
            if a.Pending or a.PendingSeed or a.Payload.Paused then return true,"waiting for garden response"end
            local payload=a.Payload
            local signature=tostring(payload.Version)..":"..tostring(payload.Phase)
            local function input(action,args)
                local key=signature..":"..action..":"..tostring(args and args.Index or "")
                if (attempts[key]or 0)>=3 then return false end
                attempts[key]=(attempts[key]or 0)+1
                send(a,action,args);nextAt=os.clock()+.35
                return true
            end
            if payload.Kind=="Dirt"and payload.Phase=="Pour"then
                if not a.Bag or not a.BagPose then return true,"waiting for dirt bag"end
                if a.BagTween then a.BagTween:Cancel();a.BagTween=nil end
                a.BagPose.Value=CFrame.new(a.Goal);a.Bag:PivotTo(CFrame.new(a.Goal))
                a.Dragging=true;a.PadDragging=true;nextAt=os.clock()+.15
                return true,"filling personal pot"
            end
            resetDrag(a)
            if payload.Kind=="Seed"and payload.Phase=="Pour"then
                input("SeedDrop",{Offset=Vector2.zero});return true,"planting quest seed"
            end
            if payload.Phase=="Cover"or payload.Phase=="Clip"then
                local action=payload.Phase=="Cover"and"Cover"or"Clip"
                local flags=action=="Cover"and payload.Covered or payload.Clipped
                for index=1,payload.Count or 4 do
                    if not(flags and flags[index])and not(a.Targets[index]and a.Targets[index].Pending)then
                        input(action,{Index=index});break
                    end
                end
                return true,action=="Cover"and"covering quest seed"or"harvesting quest crop"
            end
            return true,"waiting for garden stage"
        end
        if a and a.Closing then resetDrag(a);return true,"finishing garden interaction"end
        ownedSession=nil;session=nil;attempts={}
        if pot and distance<6 then
            local stage=pot:GetAttribute("Stage")
            if stage=="Growing"then
                B.State.StoryGardenRemaining=pot:GetAttribute("GrowthRemaining")
                return true,"waiting for quest crop to grow",true
            end
            local inventory=B.State.ReadInventory()
            if not inventory then return true,"waiting for inventory"end
            if stage=="Empty"and(inventory["Dirt Bag"]or 0)<1 then return true,"quest needs one dirt bag"end
            if stage=="DirtReady"then
                local seedName=tostring(player:GetAttribute("JodioGardenInstruction")or""):match("^Pick (.+ Seed) in ")
                if not seedName then return true,"waiting for the quest seed instruction"end
                local chosen
                for _,item in ipairs(Http:JSONDecode(player.Data.Stats.Inventory.Value))do
                    if type(item)=="table"and item.Name==seedName and(item.Amount or 1)>0 then chosen=item;break end
                end
                if not chosen then return true,"quest seed is missing"end
                remote:FireServer("SelectSeed",{Name=chosen.Name,ID=chosen.ID})
            elseif stage~="Ready"and stage~="Empty"then return true,"waiting for personal pot"end
        else
            local inventory=B.State.ReadInventory()
            if not inventory or(inventory["Garden Pot"]or 0)<1 then return true,"quest needs one garden pot"end
        end
        local prompt
        if pot and distance<6 then prompt=pot:FindFirstChild("GardenWork",true)
        else
            for _,spot in ipairs(folder:GetChildren())do
                if spot:IsA("BasePart")and spot.Name=="GardenSpot"and(spot.Position-mark).Magnitude<2 then
                    prompt=spot:FindFirstChild("GardenPlace");break
                end
            end
        end
        if not prompt then return true,"waiting for garden interaction"end
        if not travel(mark)then return true,"waiting for garden floor"end
        task.wait(.2)
        if not current()or not prompt.Parent or not prompt.Enabled then return true end
        local _,root=A.Character()
        local parent=prompt.Parent
        local point=parent:IsA("Attachment")and parent.WorldPosition or parent:IsA("BasePart")and parent.Position
        if not point or not root or(root.Position-point).Magnitude>prompt.MaxActivationDistance or prompt.HoldDuration>5 then
            return true,"garden interaction out of reach"
        end
        held=prompt;prompt:InputHoldBegin()
        local deadline=os.clock()+prompt.HoldDuration+.15
        repeat task.wait(.05)until os.clock()>=deadline or not current()or not prompt.Parent
        if current()and prompt.Parent and prompt.Enabled then fireproximityprompt(prompt)end
        pcall(prompt.InputHoldEnd,prompt);held=nil
        nextAt=os.clock()+2
        return true,"opening personal garden interaction"
    end
    return G
end

end)()(A,B)
local carry=(function()
return function(A,B)
    local player=B.Player
    local active
    local C={}
    function C.Release()
        local run=active;if not run then return end
        active=nil
        for part,value in pairs(run.Collisions)do if part.Parent then part.CanCollide=value end end
    end
    A.Cleanups[#A.Cleanups+1]=C.Release
    function C.Move(goal,current)
        if player:GetAttribute("CarryingUsagi")~=true then return nil end
        local name=player:GetAttribute("CarryingPatient")
        local folder=workspace.Game:FindFirstChild("StoryActors")
        local patient=folder and name and folder:FindFirstChild(name)
        if not patient or patient:GetAttribute("StoryCarrierId")~=player.UserId then return false,"waiting for own patient"end
        local character,root,humanoid=A.Character()
        if not character or not current()then return false,"carry cancelled"end
        C.Release()
        local run={Character=character,Collisions={}}
        active=run
        local function valid()
            return active==run and current()and player.Character==character and patient.Parent
                and humanoid.Health>0 and player:GetAttribute("CarryingPatient")==name
                and patient:GetAttribute("StoryCarrierId")==player.UserId
        end
        local reason="carry route timed out"
        local good,err=pcall(function()
            for _,part in ipairs(character:GetDescendants())do
                if part:IsA("BasePart")then run.Collisions[part]=part.CanCollide;part.CanCollide=false end
            end
            if(patient:GetPivot().Position-root.Position).Magnitude>18 then
                root.CFrame=CFrame.new(patient:GetPivot().Position+Vector3.new(0,1,0));task.wait(.2)
            end
            local params=RaycastParams.new();params.FilterType=Enum.RaycastFilterType.Exclude
            params.FilterDescendantsInstances={character,patient,workspace.Game.Players,workspace.Game.NPCs}
            local deadline=os.clock()+40
            while valid()and os.clock()<deadline do
                local delta=Vector3.new(goal.X-root.Position.X,0,goal.Z-root.Position.Z)
                if delta.Magnitude<3 then reason="arrived";break end
                if(patient:GetPivot().Position-root.Position).Magnitude>18 then reason="patient did not follow";break end
                local nextPos=root.Position+delta.Unit*math.min(2.5,delta.Magnitude)
                local floor=workspace:Raycast(nextPos+Vector3.new(0,6,0),Vector3.new(0,-28,0),params)
                if not floor or floor.Normal.Y<.5 then reason="waiting for carry floor";break end
                local dest=floor.Position+Vector3.new(0,humanoid.HipHeight+root.Size.Y/2+.15,0)
                root.CFrame=CFrame.lookAt(dest,dest+delta.Unit);root.AssemblyLinearVelocity=Vector3.zero
                task.wait(.1)
            end
            if not valid()then reason="carry state changed"end
        end)
        if active==run then C.Release()end
        if not good then error(err)end
        return reason=="arrived",reason
    end
    return C
end

end)()(A,B)
local RS=game:GetService("ReplicatedStorage")
local Http=game:GetService("HttpService")
local Players=game:GetService("Players")
local player=B.Player
local stats=player.Data.Stats
local Quests=require(RS.Modules.Quests)
local nativeStory=require(player.PlayerScripts.Core.StoryInteractions)
local id="AutoStory"
local path="sharkwow-standout-story-"..player.UserId..".json"
local config={Schema=1,UserId=player.UserId,Enabled=false}
local good,saved=pcall(function()return Http:JSONDecode(readfile(path))end)
if good and type(saved)=="table"and saved.Schema==1 and saved.UserId==player.UserId then config=saved end
local generation,acquired,nextAction=0,false,0
local questId,quest,attack,attackNative,attackCharacter,held,ride,lastFingerprint,lastProgress,combatReturn
local lastQuest,beforeQuest,dialogueQuest,dialogueUntil,pending=nil,nil,nil,0,nil
local selectedTarget,selectedCharacter
local observedTarget,observedHealth
local rockCharacter,rockRequests=nil,0
local nextHeavy,lastHeavy=0,false
local fishFingerprint
local paused={"AutoFarm","AutoLevel20","AutoQuest","QuestFarm","BountyFarm","QuestTravel","AutoDialogue","AutoHopArrows","AutoCraftBizarre","FreeArrowMaterials","MoneyTransportFarm","AutoPilot","AutoSkills","AutoSummon","AutoBlock","AutoParry","AutoDash"}
local lock=factory(A,B,{ownedCop=function(attrs,userId)
    return quest~=nil and P.Target(quest,attrs,attrs.Config or "",userId,player.Name)
end},{Prefix="Story",Store="StoryLock",Error="story combat position",Mode=player.Data.Stand.Value=="Highway Star" and "behind" or nil,Distance=4,FollowFacing=true,AdaptDistance=true,Height=6,FallbackHeight=5,NoDamageTimeout=18})
local reports={}
local reportPath="sharkwow-standout-story-report-"..player.UserId..".json"
local reportOK,priorReports=pcall(function()return Http:JSONDecode(readfile(reportPath))end)
if reportOK and type(priorReports)=="table" and priorReports.UserId==player.UserId and type(priorReports.Reports)=="table"then reports=priorReports.Reports end
B.State.StoryVersion=4;B.State.StoryReports=reports
local function status(value)B.State.StoryStatus=value;A.Status=value end
local function save()writefile(path,Http:JSONEncode(config))end
function B.State.SetStoryLevelGoal(value)
    assert(type(value)=="number" and value%1==0 and value>=20 and value<=40,"story level goal must be 20 to 40")
    local old=config.LevelGoal;config.LevelGoal=value
    local ok,err=pcall(save);if not ok then config.LevelGoal=old;error(err)end
    B.State.StoryLevelGoal=value
end
B.State.StoryLevelGoal=config.LevelGoal
local function current(token,c)
    return A.Current() and A.Get(id) and generation==token and (not c or player.Character==c)
        and not B.State.HopBusy and not B.State.TransferPending and not B.State.AutoHopPause
end
local function stopAttack()
    lock.Release()
    if attackNative and player.Character==attackCharacter then
        pcall(function()attackNative:getStates().HoldingM1=false end)
        pcall(attackNative.cancelAttacksForStandReplacement,attackNative)
        pcall(attackNative.finishBasicAttack,attackNative,true)
    end
    if attack and coroutine.status(attack)~="dead"then pcall(task.cancel,attack)end
    attack=nil;attackNative=nil;attackCharacter=nil
    if combatReturn then
        local pose=combatReturn;combatReturn=nil
        local c,r=A.Character()
        if c==pose.Character then r.CFrame=pose.Pose;r.AssemblyLinearVelocity=Vector3.zero end
    end
end
local function release()
    stopAttack()
    garden.Release()
    carry.Release()
    selectedTarget=nil;selectedCharacter=nil;B.State.StoryTarget=nil
    if held then pcall(held.InputHoldEnd,held);held=nil end
    if acquired then acquired=false;B.State.CraftBusy=false;B.State.StoryBusy=false;B.State.ExtensionPause=false end
end
local function restore()
    if not config.Previous then return end
    local previous=config.Previous;config.Previous=nil
    for _,kind in ipairs({"arrow","rokaka","part"})do B.State.SetAuto(kind,previous[kind]==true)end
    for feature,enabled in pairs(previous.Features or {})do
        if enabled and feature~="AutoLevel20" and A.Features[feature]then A.Set(feature,true)end
    end
    if previous.Garden and not A.Get("GardenHarvest")then A.Set("GardenHarvest",true)end
    save()
end
lock.OnLost=function()
    stopAttack();nextAction=os.clock()+3
    status("story combat repositioning")
end
A.Add({Id=id,Name="auto story quests",Group="quests",Description="Follows available story objectives and checks native completion. Uses M1 and M2 against matching quest NPCs, without skills; stops on unavailable or unconfirmed steps. Saved per account.",Set=function(value)
    if value then assert(not B.State.PhoneBusy,"finish the phone tutorial first")end
    config.Enabled=value;save();generation+=1;release();nextAction=0;pending=nil
    if value then lastProgress=os.clock();lastFingerprint=nil end
    if not value then restore();status("story farm stopped")else status("reading current story quest")end
end})
A.Features[id].Enabled=config.Enabled==true and not B.State.HoldForJoin
A.Cleanups[#A.Cleanups+1]=function()generation+=1;release()end
local function acquire()
    if acquired then return true end
    if not A.MovementFree() or B.State.PhoneBusy then return false end
    config.Previous=config.Previous or {arrow=B.State.AutoArrow==true,rokaka=B.State.AutoRokaka==true,part=B.State.AutoParts==true,Garden=A.Get("GardenHarvest"),Features={}}
    for _,feature in ipairs(paused)do
        if A.Features[feature] and A.Get(feature)then config.Previous.Features[feature]=true;A.Set(feature,false)end
    end
    save()
    for _,kind in ipairs({"arrow","rokaka","part"})do B.State.SetAuto(kind,false)end
    if A.Get("GardenHarvest")then A.Set("GardenHarvest",false)end
    B.SetFly(false)
    if B.State.ReleaseIdleHide then B.State.ReleaseIdleHide()end
    if B.ReleaseFarmHold then B.ReleaseFarmHold()end
    A.Underground.Release(nil,true)
    acquired=true;B.State.CraftBusy=true;B.State.StoryBusy=true;B.State.ExtensionPause=true
    return true
end
local function pointOf(object)
    if object:IsA("BasePart")then return object.Position end
    if object:IsA("Attachment")then return object.WorldPosition end
    if object:IsA("Model")then return object:GetPivot().Position end
end
local function travel(point,token,c)
    local _,r,h=A.Character();if not r or not current(token,c)then return false end
    local carried,reason=carry.Move(point,function()return current(token,c)end)
    if carried~=nil then
        if not carried and reason then status(reason)end
        return carried
    end
    if (r.Position-point).Magnitude<5 then return true end
    if h.SeatPart then
        local seat=h.SeatPart
        local weld=seat:FindFirstChild("SeatWeld")
        h.Sit=false;h:ChangeState(Enum.HumanoidStateType.GettingUp)
        local deadline=os.clock()+2
        repeat task.wait(.1) until not current(token,c) or (not h.SeatPart and (not weld or not weld.Parent)) or os.clock()>=deadline
        if not current(token,c)then return false end
        if h.SeatPart or (weld and weld.Parent)then status("waiting to detach from seat before travel");return false end
    end
    B.State.RequestStream(point,2)
    if not current(token,c)then return false end
    local params=RaycastParams.new();params.FilterType=Enum.RaycastFilterType.Exclude
    params.FilterDescendantsInstances={c,workspace.Game.Players,workspace.Game.NPCs}
    local floor=workspace:Raycast(point+Vector3.new(0,6,0),Vector3.new(0,-32,0),params)
    if not floor or floor.Normal.Y<.5 then status("waiting for quest floor");return false end
    r.AssemblyLinearVelocity=Vector3.zero;r.AssemblyAngularVelocity=Vector3.zero
    r.CFrame=CFrame.new(floor.Position+Vector3.new(0,h.HipHeight+r.Size.Y/2+.15,0))
    return true
end
local function hold(prompt,token,c)
    local point=pointOf(prompt.Parent)
    if not point or not travel(point,token,c)then return false end
    task.wait(.2)
    if not current(token,c) or not prompt.Parent or not prompt.Enabled or not nativeStory.IsEligible(prompt)then return false end
    local r=c:FindFirstChild("HumanoidRootPart")
    if not r or (r.Position-point).Magnitude>prompt.MaxActivationDistance then return false end
    if prompt.HoldDuration>15 then status("quest interaction needs a longer native action");return false end
    held=prompt;prompt:InputHoldBegin()
    local deadline=os.clock()+prompt.HoldDuration+.15
    repeat task.wait(.05)until os.clock()>=deadline or not current(token,c) or not prompt.Parent
    if current(token,c) and prompt.Parent and prompt.Enabled then fireproximityprompt(prompt)end
    pcall(prompt.InputHoldEnd,prompt);held=nil
    return current(token,c)
end
A.Connect(RS.Remotes.Huber.OnClientEvent,function(action,data)
    if action=="Ride"then ride=data
    elseif action=="Ended"then if ride and ride.Id==data.Id then ride=nil end
    elseif action=="Notice"then B.State.StoryHuberNotice=type(data)=="table"and data.Text or tostring(data)end
end)
local lastHuber,hubRequests=nil,{}
local function huber(token,c)
    if lastHuber~=questId then lastHuber=questId;hubRequests={};RS.Remotes.Huber:FireServer("Sync");nextAction=os.clock()+1;return end
    local key=ride and ride.Id..":"..ride.State or "Call"
    if player.Data.CombatTagged.Value or player.Data.SkillActive.Value then
        status("waiting for combat to clear before huber");nextAction=os.clock()+2;return
    end
    if hubRequests[key] and os.clock()-hubRequests[key]<15 then return end
    if not ride then hubRequests[key]=os.clock();RS.Remotes.Huber:FireServer("Call")
    elseif ride.State=="AwaitingBoard"then
        local point=typeof(ride.Pickup)=="CFrame"and ride.Pickup.Position or ride.Pickup
        if typeof(point)=="Vector3"and travel(point,token,c)then hubRequests[key]=os.clock();RS.Remotes.Huber:FireServer("Board",{Id=ride.Id})end
    elseif ride.State=="ChoosingDestination"then
        hubRequests[key]=os.clock();RS.Remotes.Huber:FireServer("Choose",{Id=ride.Id,Stop="RohanTrail"})
    end
    status("story / huber ride");nextAction=os.clock()+.5
end
local function active()
    local set=P.Set(stats.ActiveQuest.Value)
    local tracked=stats.TrackedQuest.Value
    if set[tracked] and Quests.Quests[tracked]then return tracked,Quests.Quests[tracked]end
    for _,candidate in ipairs(Quests.Part9StoryChain)do if set[candidate]then return candidate,Quests.Quests[candidate]end end
    for candidate in pairs(set)do if Quests.Quests[candidate]then return candidate,Quests.Quests[candidate]end end
end
local function record(nextQuest)
    if lastQuest==nextQuest then return end
    stopAttack();garden.Release();pending=nil;selectedTarget=nil;B.State.StoryTarget=nil;rockCharacter=nil;rockRequests=0
    if dialogueQuest and Quests.Quests[dialogueQuest] and Quests.Quests[dialogueQuest].AutoStartNext==nextQuest then
        dialogueQuest=nextQuest;dialogueUntil=os.clock()+30
    end
    if lastQuest and P.Set(stats.CompletedQuests.Value)[lastQuest]then
        reports[#reports+1]={Quest=lastQuest,Before=beforeQuest,After={Level=stats.Level.Value,XP=player.Data.Experience.Value},Completed=true}
        if #reports>100 then table.remove(reports,1)end
        local ok,err=pcall(function()writefile(reportPath,Http:JSONEncode({UserId=player.UserId,Reports=reports}))end)
        if not ok then A.Error("story report",err)end
    end
    lastQuest=nextQuest;beforeQuest={Level=stats.Level.Value,XP=player.Data.Experience.Value}
    lastProgress=os.clock();lastFingerprint=nil
end
local function tick()
    if not A.Get(id)then return end
    if type(config.LevelGoal)=="number" and stats.Level.Value>=config.LevelGoal then
        A.Set(id,false);B.State.StoryLevelGoalReached=true;status("story level goal reached: "..config.LevelGoal);return
    end
    local token=generation
    local c,r,h=A.Character()
    if not c or not current(token,c)then release();return end
    if not acquire() or os.clock()<nextAction then return end
    questId,quest=active();record(questId)
    if not quest then
        local complete=P.Set(stats.CompletedQuests.Value)
        if complete[Quests.Part9StoryChain[#Quests.Part9StoryChain]]then A.Set(id,false);status("available story chain completed");return end
        status("waiting for an available quest");nextAction=os.clock()+3;return
    end
    local fingerprint=questId.."/"..stats.QuestObjectives.Value
    if fingerprint~=lastFingerprint then lastFingerprint=fingerprint;lastProgress=os.clock();pending=nil;A.Errors[id]=nil end
    if questId=="P9_33A_DARBY_WAGER"then
        local gui=player.PlayerGui:FindFirstChild("DarbyGoFish")
        local stage=gui and gui:FindFirstChild("Stage")
        local board=stage and stage:FindFirstChild("Board")
        if gui and gui.Enabled and board then
            stopAttack()
            local parts={}
            for _,label in ipairs(board.Log:GetChildren())do
                if label:IsA("TextLabel")then parts[#parts+1]=label.Name..":"..label.Text end
            end
            for _,button in ipairs(board.Hand.Stacks:GetChildren())do
                parts[#parts+1]=button.Name..":"..button.Badge.Count.Text
            end
            table.sort(parts)
            local signature=table.concat(parts,"|")
            if signature~=fishFingerprint then fishFingerprint=signature;lastProgress=os.clock()end
            if os.clock()-lastProgress>180 then A.Set(id,false);A.Error(id,"card game made no progress");return end
            if stage.Result.Visible then status("waiting for card game result");nextAction=os.clock()+1;return end
            local selected,count=nil,0
            if board.Pile.Visible and board.Pile.Active then selected=board.Pile
            else
                for _,button in ipairs(board.Hand.Stacks:GetChildren())do
                    local amount=tonumber(button.Badge.Count.Text:match("%d+"))or 0
                    if button:IsA("GuiButton")and button.Visible and button.Active and amount>count then selected=button;count=amount end
                end
            end
            if selected then
                assert(type(firesignal)=="function","native card input unavailable")
                firesignal(selected.Activated)
            end
            status("playing story card game");nextAction=os.clock()+2;return
        end
    end
    local handled,gardenStatus,growing=garden.Step(questId,function()return current(token,c)end,function(point)return travel(point,token,c)end)
    if handled then
        B.State.StoryGardenStatus=gardenStatus
        if gardenStatus then status(gardenStatus)end
        local marker=player:GetAttribute("JodioGardenInstruction")
        if growing or B.State.StoryGardenInstruction~=marker then
            B.State.StoryGardenInstruction=marker;lastProgress=os.clock()
        end
        if os.clock()-lastProgress>180 then A.Set(id,false);A.Error(id,"garden made no progress: "..tostring(gardenStatus))end
        return
    end
    if os.clock()-lastProgress>180 then A.Set(id,false);A.Error(id,"quest made no progress: "..questId);return end
    if stats.TrackedQuest.Value~=questId then RS.Remotes.Quest:FireServer("Track Quest",questId);nextAction=os.clock()+1;return end
    status("story / "..quest.Title)
    if questId=="P9_29_EXTRACT_BAGS_GROOVE"then
        stopAttack()
        local gui=player.PlayerGui:FindFirstChild("BagsGrooveMinigame")
        local root=gui and gui:FindFirstChild("Root")
        local panel=root and root:FindFirstChild("Panel")
        local veins=panel and panel:FindFirstChild("VeinPanel")
        local units=veins and veins:FindFirstChild("Units")
        if gui and gui.Enabled and root.Visible and units then
            for index=1,5 do
                local button=units:FindFirstChild("Unit"..index)
                if button and button:IsA("ImageButton")and button.Visible and button.Active then
                    assert(type(firesignal)=="function","native extraction input unavailable")
                    firesignal(button.Activated);nextAction=os.clock()+.65
                    status("extracting Bags' Groove unit "..index);return
                end
            end
        end
        status("waiting for extraction minigame response");nextAction=os.clock()+.5;return
    end
    if questId=="P9_20_COPY_LAND_DEEDS"and c:GetAttribute("LavaRockEquipped")~=true then
        if rockCharacter~=c then rockCharacter=c;rockRequests=0 end
        local inventory=B.State.ReadInventory()
        if not inventory or(inventory["Lava Rock"]or 0)<1 then status("waiting for the story lava rock");return end
        if rockRequests>=3 then status("lava rock equip awaiting confirmation");return end
        rockRequests+=1;RS.Remotes.Item:FireServer("Use","Lava Rock");nextAction=os.clock()+5
        status("equipping story lava rock");return
    end
    if questId=="P9_01B_TAKE_HUBER"then huber(token,c);return end
    if questId=="P9_08_SIT_DIAMOTCH_BACK_ROOM" and h.SeatPart and h.SeatPart.Name:match("^DiamotchCouchSeat%d+$")then
        local clerk=workspace.Game.NPCs:FindFirstChild("Diamotch Clerk")
        local clerkRoot=clerk and clerk:FindFirstChild("HumanoidRootPart")
        if clerkRoot and (clerkRoot.Position-r.Position).Magnitude<=25 then
            local response=require(RS.Modules.DialogueInfo).dialogues["Diamotch Clerk"].BackRoomShow.Responses[1]
            assert(response[1]=="Okay." and type(response[4])=="function","private showing dialogue changed")
            response[4](player)
            status("confirmed private showing dialogue; waiting for quest update");nextAction=os.clock()+10
        else status("seated; waiting for the clerk to reach the back room");nextAction=os.clock()+1 end
        return
    end
    if player:GetAttribute("StoryCinematic") or player:GetAttribute("TutorialCinematic") or player:GetAttribute("EndingCinematic") or player:GetAttribute("QTEInputLocked")then stopAttack();return end
    local dialogue=player.PlayerGui:FindFirstChild("Dialogue")
    if dialogue and dialogue.Enabled then
        stopAttack()
        local choices=A.DialogueChoices()
        if #choices==1 and P.Advance(choices[1].Text)then A.ClickDialogue(choices[1].Button);nextAction=os.clock()+.65;return end
        if dialogueQuest==questId and os.clock()<dialogueUntil then
            for _,choice in ipairs(choices)do
                if P.Choice(choice.Text)then A.ClickDialogue(choice.Button);nextAction=os.clock()+.65;return end
            end
        end
        status("waiting for quest dialogue");return
    end
    local combat=false
    for objective in pairs(quest.Objectives or {})do if objective:match("^Defeat ")then combat=true;break end end
    if combat then
        if selectedCharacter~=c then stopAttack();selectedTarget=nil;selectedCharacter=c end
        local targetQuest=questId
        local function validTarget(model)
            if model.Parent~=workspace.Game.Players then return false end
            local mh=model:FindFirstChildOfClass("Humanoid")local mr=model:FindFirstChild("HumanoidRootPart")
            return mh~=nil and mh.Health>0 and mr~=nil and not Players:GetPlayerFromCharacter(model)
                and P.Target(quest,model:GetAttributes(),model.Name,player.UserId,player.Name)
        end
        local target=P.SelectTarget(selectedTarget,workspace.Game.Players:GetChildren(),validTarget,function(model)
            return (model.HumanoidRootPart.Position-r.Position).Magnitude
        end)
        if target~=selectedTarget then
            stopAttack();selectedTarget=target
            B.State.StoryTargetChanges=(B.State.StoryTargetChanges or 0)+1
        end
        B.State.StoryTarget=target
        if target then
            local targetHealth=target:FindFirstChildOfClass("Humanoid").Health
            if observedTarget==target and observedHealth and targetHealth<observedHealth then lastProgress=os.clock()end
            observedTarget=target;observedHealth=targetHealth
            local n=A.Native();if not n then return end
            local states=n:getStates()
            if player.Data.Stand.Value~=""and not states.Summoned then n:summonStand(true);nextAction=os.clock()+.5;return end
            combatReturn=combatReturn or {Character=c,Pose=r.CFrame}
            local function combatCurrent()
                return current(token,c)and questId==targetQuest and stats.TrackedQuest.Value==targetQuest
                    and P.Set(stats.ActiveQuest.Value)[targetQuest]==true and selectedTarget==target and validTarget(target)
            end
            if not lock.Begin(target,n,combatCurrent)then stopAttack();status("finding quest M1 reach");return end
            if attack and coroutine.status(attack)~="dead"then return end
            if states.Stunned or states.SwingCooldown or states.Swinging or states.HeavySwinging or player.Data.SkillActive.Value then return end
            attackNative=n;attackCharacter=c
            local heavy=not lastHeavy and not states.HeavyCD and os.clock()>=nextHeavy and type(n.heavySwing)=="function"
            lastHeavy=heavy
            local swing=heavy and n.heavySwing or n.lightSwing
            if heavy then nextHeavy=os.clock()+1;B.State.StoryM2Requests=(B.State.StoryM2Requests or 0)+1
            else B.State.StoryM1Requests=(B.State.StoryM1Requests or 0)+1 end
            B.State.StoryAttackKind=heavy and "M2" or "M1"
            attack=task.spawn(function()
                if not combatCurrent()or not B.State.StoryLockActive then return end
                local ok,err=pcall(swing,n);if not ok and combatCurrent()then A.Error(id,err)end
            end)
            return
        end
    end
    stopAttack()
    if A.TryCollectDrop and A.TryCollectDrop({Owner="story",Current=function()return current(token,c)end})then nextAction=os.clock()+.25;return end
    local point=player:GetAttribute("VisibleQuestTrackerPosition")
    if typeof(point)~="Vector3"then status("waiting for quest marker");return end
    if not travel(point,token,c)then nextAction=os.clock()+2;return end
    task.wait(.15)
    if not current(token,c) or stats.TrackedQuest.Value~=questId then return end
    local selected,best=nil,math.huge
    for _,prompt in ipairs(workspace.Game:GetDescendants())do
        if prompt:IsA("ProximityPrompt")and prompt.Enabled then
            local pos=pointOf(prompt.Parent)
            if pos and (pos-point).Magnitude<85 and P.Owned(prompt:GetAttributes(),player.UserId)and nativeStory.IsEligible(prompt)then
                local match=P.Prompt(questId,prompt:GetAttributes(),prompt.Name,prompt.Parent.Name,quest.Objectives)
                local actor=prompt:FindFirstAncestorOfClass("Model")
                if not match and actor and P.Owned(actor:GetAttributes(),player.UserId)then
                    for objective in pairs(quest.Objectives or {})do
                        if objective:match("^Talked_") and (pos-point).Magnitude<12 and nativeStory.CanTalkToActor(actor)then match=true;break end
                    end
                end
                if match and (pos-point).Magnitude<best then best=(pos-point).Magnitude;selected=prompt end
            end
        end
    end
    if selected then
        if pending and pending.Prompt==selected and os.clock()-pending.At<8 then return end
        if pending and pending.Prompt==selected and pending.Count>=3 then status("quest interaction awaiting confirmation");nextAction=os.clock()+5;return end
        local count=pending and pending.Prompt==selected and pending.Count+1 or 1
        dialogueQuest=questId;dialogueUntil=os.clock()+30
        if hold(selected,token,c)then pending={Prompt=selected,At=os.clock(),Count=count}end
    end
    nextAction=os.clock()+1
end
A.Loop("story quests",.08,function()
    local ok,err=pcall(tick)
    if not ok then release();nextAction=os.clock()+3;A.Error(id,err)end
end)

    end)(advanced, bridge);
    (function(A, B)
local Http=game:GetService("HttpService")
local path="sharkwow-story40-workflow-"..B.Player.UserId..".json"
local config={Schema=1,UserId=B.Player.UserId,Enabled=false}
local ok,saved=pcall(function()return Http:JSONDecode(readfile(path))end)
if ok and type(saved)=="table" and saved.Schema==1 and saved.UserId==B.Player.UserId then config=saved end
local started=false
local function save()writefile(path,Http:JSONEncode(config))end
local function status(text)B.State.Story40Status=text end
local function block(reason)
    config.Blocked=tostring(reason);save();status("needs attention: "..config.Blocked)
end
function B.State.StartStory40()
    assert(B.Player.Data.Stats.Level.Value<40,"level 40 already reached")
    config.Enabled=true;config.Blocked=nil;started=false;save()
    assert(A.Set("AutoLevel20",false))
    B.State.SetStoryLevelGoal(40)
    status("preparing story leveling")
end
function B.State.StopStory40()
    config.Enabled=false;save();started=false
    if A.Get("AutoStory")then A.Set("AutoStory",false)end
    if A.Get("AutoPhone")then A.Set("AutoPhone",false)end
    status("stopped")
end
B.State.Story40WorkflowVersion=1
A.Loop("story40 workflow",2,function()
    if not config.Enabled then return end
    if config.Blocked then status("needs attention: "..config.Blocked);return end
    if B.State.HopBusy or B.State.TransferPending or B.State.PhoneBusy then return end
    if B.Player.Data.Stats.Level.Value>=40 then
        B.State.StopStory40();status("verified level 40 reached");return
    end
    local inventory=B.State.ReadInventory()
    if not inventory then return end
    local phase=(inventory.Phone or 0)>0 and "story" or "phone"
    if config.Phase~=phase then config.Phase=phase;started=false;save()end
    local id=phase=="phone" and "AutoPhone" or "AutoStory"
    if not started then
        if phase=="story" then B.State.SetStoryLevelGoal(40)end
        local enabled,reason=A.Set(id,true)
        if not enabled then block(reason or "feature failed to start");return end
        started=true
    end
    if not A.Get(id)then
        block(A.Errors[id] or (phase=="story" and "story stopped below level 40; inspect quest progress" or "phone tutorial stopped before Phone was received"));return
    end
    status(phase=="story" and (B.State.StoryStatus or "story running") or (B.State.PhoneStatus or "phone tutorial running"))
end)

    end)(advanced, bridge);
    (function(A, B)
-- Legacy goal automation cannot override the player raid switch.
local player=B.Player
local Http=game:GetService("HttpService")
local path="sharkwow-raid-cycle-"..player.UserId..".json"
B.State.RaidManualControlVersion=1
B.State.RaidCycleEnabled=false
B.State.RaidCycleStatus="manual Auto Raid control only"
function B.State.SetRaidCycle(value)
    assert(type(value)=="boolean","raid cycle requires boolean")
    if value then return false,"Use the Auto Raid switch for this player" end
    writefile(path,Http:JSONEncode({UserId=player.UserId,Enabled=false,Goal=40}))
    B.State.RaidCycleEnabled=false
    return true
end

    end)(advanced, bridge);
    (function(A, B)
local P=(function()
local P={Names={Scrap=true,["Bottle Cap"]=true,["Rusty Can"]=true,Seashell=true}}
function P.Candidate(item,definition,protected)
    return type(item)=="table" and P.Names[item.Name]==true and type(item.ID)=="string" and item.ID~=""
        and item.Bound~=true and not protected[item.Name] and type(definition)=="table"
        and definition.Type=="Beach Find" and definition.Rarity=="Common" and not definition.KeyItem
        and not definition.Wearable and not definition.UseFunc and not definition.GardenUse
end
return P

end)()
local Http=game:GetService("HttpService")
local RS=game:GetService("ReplicatedStorage")
local player=B.Player
local id="AutoDropJunk"
local path="sharkwow-standout-junk-"..player.UserId..".json"
local config={Schema=1,UserId=player.UserId,Enabled=false}
local storageError
if type(readfile)=="function" then
    local ok,data=pcall(function() return Http:JSONDecode(readfile(path)) end)
    if ok and type(data)=="table" and data.Schema==1 and data.UserId==player.UserId then config=data
    elseif type(isfile)=="function" and isfile(path) then storageError="junk settings unreadable" end
end
local function save()
    assert(type(writefile)=="function","junk configuration storage unavailable")
    writefile(path,Http:JSONEncode(config))
end
local function inventory()
    local data=player:FindFirstChild("Data")
    local stats=data and data:FindFirstChild("Stats")
    local value=stats and stats:FindFirstChild("Inventory")
    if not value then return end
    local ok,items=pcall(Http.JSONDecode,Http,value.Value)
    if ok and type(items)=="table" then return items end
end
local function amount(items,name,itemId)
    for _,item in pairs(items) do
        if type(item)=="table" and item.Name==name and item.ID==itemId then return tonumber(item.Amount) or 1 end
    end
    return 0
end
local function reconcile(items)
    local record=config.Pending
    if not record then return true end
    if items and amount(items,record.Name,record.ID)<record.Before then config.Pending=nil;save();return true end
    return false
end
A.Add({Id=id,Name="auto drop common junk",Group="utility",Description="Drops only Scrap, Bottle Cap, Rusty Can and Seashell. Keeps arrows, parts, Steel, Wood, fruit, seeds, Phone, equipment and unknown items. Recipe ingredients and bound items are protected. Saves per account.",Set=function(value)
    if value then assert(not storageError,storageError);assert(reconcile(inventory()),"previous drop unconfirmed; automatic retry stopped") end
    config.Enabled=value;save()
end})
A.Features[id].Enabled=config.Enabled==true and not storageError
if storageError then A.Error(id,storageError) end
local protected={}
local function protect(value,seen,depth)
    if type(value)~="table" or seen[value] or depth>12 then return end
    seen[value]=true
    for key,child in pairs(value) do
        if P.Names[key] then protected[key]=true end
        if type(child)=="string" and P.Names[child] then protected[child]=true end
        if type(child)=="table" then protect(child,seen,depth+1) end
    end
end
for _,module in ipairs({RS.Modules.Crafting.Recipes,RS.Modules.Processing,RS.Modules.Gardening}) do protect(require(module),{},0) end
local Items=require(RS.Modules.Items)
A.Loop("common junk cleanup",3,function()
    if not A.Get(id) or not A.MovementFree() or B.State.MaterialBusy or A.Get("AutoPhone") then return end
    local items=inventory();if not items then return end
    if not reconcile(items) then config.Enabled=false;save();A.Features[id].Enabled=false;A.Error(id,"previous drop unconfirmed; automatic retry stopped");return end
    for _,item in pairs(items) do
        if type(item)=="table" and P.Candidate(item,Items.items[item.Name],protected) then
            local before=amount(items,item.Name,item.ID)
            if before<=0 then continue end
            config.Pending={Name=item.Name,ID=item.ID,Before=before};save()
            RS.Remotes.Item:FireServer("Drop",item.Name,item.ID)
            local deadline=os.clock()+3
            repeat
                task.wait(.15)
                if not A.Current() then return end
                if reconcile(inventory()) then
                    A.Metrics.JunkDrops=(A.Metrics.JunkDrops or 0)+1
                    B.State.LastJunkDrop=item.Name;A.Errors[id]=nil
                    return
                end
            until os.clock()>=deadline
            config.Enabled=false;save();A.Features[id].Enabled=false;A.Error(id,"drop outcome unconfirmed; automatic retry stopped")
            return
        end
    end
end)

    end)(advanced, bridge);
    (function(A, B)
local Http=game:GetService("HttpService")
local remote=game:GetService("ReplicatedStorage").Remotes.Item
local id="DeleteNormalRokaka"
local pendingKey="SHARKWOW_NORMAL_ROKAKA_DELETE_PENDING_"..B.Player.UserId
local env=getgenv()
local function inventory()
    local data=B.Player:FindFirstChild("Data")
    local stats=data and data:FindFirstChild("Stats")
    local value=stats and stats:FindFirstChild("Inventory")
    if not value then return nil end
    local ok,result=pcall(Http.JSONDecode,Http,value.Value)
    return ok and type(result)=="table" and result or nil
end
local function count(items,itemId)
    for _,item in pairs(items) do
        if type(item)=="table" and item.Name=="Rokaka" and item.ID==itemId then return tonumber(item.Amount) or 1 end
    end
    return 0
end
local function reconciled(items)
    local pending=env[pendingKey]
    if not pending then return true end
    if items and count(items,pending.ID)<pending.Before then env[pendingKey]=nil;return true end
    return false
end
A.Add({Id=id,Name="delete normal rokaka",Group="farm",Description="Permanently deletes only unbound Rokaka. Keeps Opal Roka, other rare fruit and all seeds. Stops on an unconfirmed deletion. Your last enabled setting is saved for this account.",Set=function(value)
    if value then assert(reconciled(inventory()),"previous normal rokaka deletion is unconfirmed") end
end})
A.Loop("normal rokaka cleanup",3,function()
    if not A.Get(id) or not A.MovementFree() or B.State.MaterialBusy or B.State.CraftBusy or A.GardenBusy() then return end
    local items=inventory();if not items then return end
    if not reconciled(items) then A.Set(id,false);A.Error(id,"previous deletion unconfirmed; stopped");return end
    for _,item in pairs(items) do
        if type(item)=="table" and item.Name=="Rokaka" and item.Bound~=true
            and type(item.ID)=="string" and item.ID~="" and (tonumber(item.Amount) or 1)>0 then
            local token=Http:GenerateGUID(false)
            remote:FireServer("ArmDelete","Rokaka",item.ID,token)
            task.wait(.35)
            if not A.Current() or not A.Get(id) or not A.MovementFree() or A.GardenBusy() then return end
            local latest=inventory()
            if not latest or count(latest,item.ID)~=count(items,item.ID) then return end
            local current
            for _,entry in pairs(latest) do
                if type(entry)=="table" and entry.Name=="Rokaka" and entry.ID==item.ID then current=entry;break end
            end
            if not current or current.Bound==true then return end
            env[pendingKey]={ID=item.ID,Before=count(latest,item.ID),Token=token}
            remote:FireServer("ConfirmDelete","Rokaka",item.ID,token)
            local deadline=os.clock()+4
            repeat
                task.wait(.2)
                if not A.Current() then return end
                if reconciled(inventory()) then
                    A.Metrics.NormalRokakaDeleted=(A.Metrics.NormalRokakaDeleted or 0)+1
                    return
                end
            until os.clock()>=deadline
            A.Set(id,false);A.Error(id,"normal rokaka deletion unconfirmed; stopped")
            return
        end
    end
end)

    end)(advanced, bridge);
    (function(A, B)
local player=B.Player
local input=game:GetService("UserInputService")
function A.RepairNativeMenu()
    if not A.Current() or B.State.PhoneBusy or A.Get("AutoPhone") then return false end
    if player:GetAttribute("StandOutMenuGateReady")~=true or player:GetAttribute("StandOutCreationRequired")==true then return false end
    for _,key in ipairs({"TutorialCinematic","GameUIHidden","GuiNavigationLocked","ServerBrowserBusy","MobileLayoutEditing"}) do
        if player:GetAttribute(key)==true then return false end
    end
    local inv=B.State.ReadInventory()
    if not inv or (inv.Phone or 0)<1 then return false end
    local menus=player.PlayerGui:FindFirstChild("Menus")
    local handler=menus and menus:FindFirstChild("HandlerMenus")
    if menus and handler and handler.Enabled and menus:FindFirstChild("HandContainer") and not menus.Enabled then
        menus.Enabled=true
        A.Metrics.MenuRepairs=(A.Metrics.MenuRepairs or 0)+1
        return true
    end
    return false
end
A.Connect(input.InputBegan,function(event,processed)
    if not processed and event.KeyCode==Enum.KeyCode.M and not input:GetFocusedTextBox() then A.RepairNativeMenu() end
end)
local pending=true
A.Connect(player.CharacterAdded,function() pending=true end)
A.Loop("native menu recovery",2,function()
    if pending and A.RepairNativeMenu() then pending=false end
end)

    end)(advanced, bridge);
    (function(A, B)
local Http=game:GetService("HttpService")
local Policy=(function()
local P={}
function P.Entries(raw)
    assert(type(raw)=="table","inventory is unavailable")
    local entries={}
    for _,value in ipairs(raw)do
        local item=type(value)=="string"and{Name=value,Amount=1}or value
        if type(item)=="table"and type(item.Name)=="string"then entries[#entries+1]=item end
    end
    return entries
end
function P.Count(entries,resolve,isEquipped)
    local counts={}
    for _,item in ipairs(entries)do
        if (item.Name:lower():find("arrow",1,true) or item.Name=="Stone Mask") and item.Bound~=true then
            local definition=resolve(item)
            local amount=item.Amount==nil and 1 or item.Amount
            if type(definition)=="table"and not definition.KeyItem and not isEquipped(item)
                and type(amount)=="number"and amount==amount and amount>0 and amount<math.huge and amount%1==0 then
                counts[item.Name]=(counts[item.Name]or 0)+amount
            end
        end
    end
    return counts
end
return P

end)()
local Items=require(game:GetService("ReplicatedStorage").Modules.Items)
local Wearables=require(game:GetService("ReplicatedStorage").Modules.Items.Wearables)
local Input=game:GetService("UserInputService")
local configPath="sharkwow-standout-report-"..B.Player.UserId..".json"
local preferences={Enabled=true,Collapsed=false,X=1,Y=.24}
local function finite(v) return type(v)=="number" and v==v and math.abs(v)<math.huge end
if type(readfile)=="function" then
    local ok,value=pcall(function() return Http:JSONDecode(readfile(configPath)) end)
    if ok and type(value)=="table" and value.Schema==1 and value.UserId==B.Player.UserId then
        for _,key in ipairs({"Enabled","Collapsed"}) do if type(value[key])=="boolean" then preferences[key]=value[key] end end
        for _,key in ipairs({"X","Y"}) do if finite(value[key]) then preferences[key]=math.clamp(value[key],0,1) end end
    end
end
local function save()
    if type(writefile)~="function" then return end
    local data=table.clone(preferences);data.Schema=1;data.UserId=B.Player.UserId
    local ok,err=pcall(function() writefile(configPath,Http:JSONEncode(data)) end)
    if not ok then A.Error("inventory report settings",err) end
end
local function create(class,parent,properties)
    local object=Instance.new(class)
    for key,value in pairs(properties) do object[key]=value end
    object.Parent=parent;return object
end
local playerGui=B.Player:WaitForChild("PlayerGui")
local gui=create("ScreenGui",playerGui,{Name="SHARKWOW_ArrowReport",ResetOnSpawn=false,IgnoreGuiInset=false,DisplayOrder=B.Gui.DisplayOrder-1,ZIndexBehavior=Enum.ZIndexBehavior.Sibling,Enabled=preferences.Enabled})
local cyan=Color3.fromRGB(0,240,255)
local purple=Color3.fromRGB(65,151,255)
local ink=Color3.fromRGB(243,247,255)
local muted=Color3.fromRGB(166,177,204)
local font=Font.new("rbxasset://fonts/families/BuilderSans.json",Enum.FontWeight.Bold)
local panel=create("Frame",gui,{Name="Report",Size=UDim2.fromOffset(264,232),BackgroundColor3=Color3.fromRGB(9,17,24),BorderSizePixel=0,Active=true})
create("UICorner",panel,{CornerRadius=UDim.new(0,12)})
local stroke=create("UIStroke",panel,{Color=Color3.new(1,1,1),Thickness=1,Transparency=.25})
create("UIGradient",stroke,{Color=ColorSequence.new(cyan,purple),Rotation=20})
local function label(parent,name,text,size,color)
    return create("TextLabel",parent,{Name=name,Text=text,FontFace=font,TextSize=math.max(16,size),TextColor3=color or ink,BackgroundTransparency=1,TextXAlignment=Enum.TextXAlignment.Left,TextTruncate=Enum.TextTruncate.AtEnd})
end
local header=create("Frame",panel,{Name="DragHandle",Size=UDim2.new(1,-44,0,44),BackgroundTransparency=1,Active=true})
local brand=label(header,"Brand","SHARKWOW",11,cyan);brand.Position=UDim2.fromOffset(12,5);brand.Size=UDim2.new(1,-24,0,15)
local title=label(header,"Title","DROPPABLE ITEMS",14);title.Position=UDim2.fromOffset(12,20);title.Size=UDim2.new(1,-24,0,20)
local collapse=create("TextButton",panel,{Name="Collapse",Text=preferences.Collapsed and "+" or "-",FontFace=font,TextSize=24,TextColor3=cyan,BackgroundTransparency=1,Size=UDim2.fromOffset(44,44),Position=UDim2.new(1,-44,0,0),AutoButtonColor=false})
local content=create("Frame",panel,{Name="Counts",Position=UDim2.fromOffset(8,46),Size=UDim2.new(1,-16,0,208),BackgroundTransparency=1,Visible=not preferences.Collapsed})
local rows={}
for i,spec in ipairs({{"Mysterious Arrow","MYSTERIOUS ARROW",cyan},{"Bizarre Arrow","BIZARRE ARROW",purple},{"Arrow Part","ARROW PART",muted},{"Lucky Arrow","LUCKY ARROW",cyan},{"Stone Mask","STONE MASK",purple},{"Other","OTHER ARROWS",muted}}) do
    local row=create("Frame",content,{Name=spec[1],Position=UDim2.fromOffset(0,(i-1)*34),Size=UDim2.new(1,0,0,30),BackgroundColor3=Color3.fromRGB(22,30,40),BorderSizePixel=0,Visible=i<6})
    create("UICorner",row,{CornerRadius=UDim.new(0,7)})
    local name=label(row,"Item",spec[2],13,spec[3]);name.Position=UDim2.fromOffset(9,0);name.Size=UDim2.new(1,-68,1,0)
    local count=label(row,"Count","--",20);count.Position=UDim2.new(1,-61,0,0);count.Size=UDim2.new(0,52,1,0);count.TextXAlignment=Enum.TextXAlignment.Right
    rows[spec[1]]={Frame=row,Count=count}
end
local status=label(panel,"Status",string.upper(B.Player.Name),10,muted)
status.Position=UDim2.new(0,12,1,-17);status.Size=UDim2.new(1,-24,0,14)
local extra=false
local function bounds()
    local size=gui.AbsoluteSize
    return math.max(0,size.X-panel.AbsoluteSize.X-16),math.max(0,size.Y-panel.AbsoluteSize.Y-16)
end
local function position()
    local x,y=bounds()
    panel.Position=UDim2.fromOffset(8+x*preferences.X,8+y*preferences.Y)
end
local function layout()
    panel.Size=UDim2.fromOffset(math.min(264,math.max(140,gui.AbsoluteSize.X-16)),preferences.Collapsed and 44 or (extra and 266 or 232))
    content.Visible=not preferences.Collapsed;status.Visible=not preferences.Collapsed
    collapse.Text=preferences.Collapsed and "+" or "-"
    rows.Other.Frame.Visible=extra
    position()
end
local function update()
    local ready,counts=pcall(function()
        local stats=B.Player.Data.Stats
        local entries=Policy.Entries(Http:JSONDecode(stats.Inventory.Value))
        local equipment=Wearables.Read(stats.BodyEquipment.Value,entries,Items.Resolve)
        return Policy.Count(entries,Items.Resolve,function(item)return Wearables.Contains(equipment,item.Name,item.ID)end)
    end)
    if not ready then A.Error("inventory report",counts);counts={}else A.Errors["inventory report"]=nil end
    local other=0
    for name,amount in pairs(counts)do if not rows[name]then other+=amount end end
    for name,row in pairs(rows) do
        local amount=name=="Other" and other or (counts[name] or 0)
        row.Count.Text=ready and tostring(amount) or "--"
    end
    local nextExtra=other>0
    if extra~=nextExtra then extra=nextExtra;layout() end
    status.Text=ready and string.upper(B.Player.Name) or "WAITING FOR INVENTORY"
    B.State.InventoryReport={Version=3,Mode="droppable",Ready=ready,Counts=counts,Other=other,UpdatedAt=os.clock(),Visible=gui.Enabled}
end
local drag
A.Connect(header.InputBegan,function(input)
    if input.UserInputType==Enum.UserInputType.MouseButton1 or input.UserInputType==Enum.UserInputType.Touch then
        drag={Input=input,Start=input.Position,Position=panel.Position}
    end
end)
A.Connect(Input.InputChanged,function(input)
    if not drag then return end
    local touch=drag.Input.UserInputType==Enum.UserInputType.Touch
    if (touch and input~=drag.Input) or (not touch and input.UserInputType~=Enum.UserInputType.MouseMovement) then return end
    local delta=input.Position-drag.Start
    local x,y=bounds()
    local px=math.clamp(drag.Position.X.Offset+delta.X,8,8+x)
    local py=math.clamp(drag.Position.Y.Offset+delta.Y,8,8+y)
    preferences.X=x>0 and (px-8)/x or 0;preferences.Y=y>0 and (py-8)/y or 0
    position()
end)
A.Connect(Input.InputEnded,function(input)
    if drag and (input==drag.Input or input.UserInputType==Enum.UserInputType.MouseButton1) then drag=nil;save() end
end)
A.Connect(Input.WindowFocusReleased,function() if drag then drag=nil;save() end end)
A.Connect(collapse.Activated,function() preferences.Collapsed=not preferences.Collapsed;layout();save() end)
A.Connect(gui:GetPropertyChangedSignal("AbsoluteSize"),layout)
A.Add({Id="InventoryReport",Name="arrow inventory window",Group="visuals",Description="Counts droppable arrows, Arrow Parts and Stone Masks. Excludes bound, key and equipped items using native drop rules. Drag or collapse the window.",Get=function() return gui.Enabled end,Set=function(value) preferences.Enabled=value;gui.Enabled=value;update();save() end})
A.Cleanups[#A.Cleanups+1]=function() drag=nil;save();gui:Destroy() end
layout();update()
A.Loop("inventory report",.5,update)

    end)(advanced, bridge);
    (function(A, B)
local function create(class,parent,properties)
    local object=Instance.new(class)
    for key,value in pairs(properties) do object[key]=value end
    object.Parent=parent
    return object
end
local cyan=Color3.fromRGB(0,240,255)
local font=Font.new("rbxasset://fonts/families/BuilderSans.json",Enum.FontWeight.Bold)
local gui=create("ScreenGui",B.Player:WaitForChild("PlayerGui"),{Name="SHARKWOW_ServerInfo",ResetOnSpawn=false,IgnoreGuiInset=false,DisplayOrder=B.Gui.DisplayOrder-1,ZIndexBehavior=Enum.ZIndexBehavior.Sibling})
local panel=create("Frame",gui,{Name="Server",AnchorPoint=Vector2.new(1,1),Position=UDim2.new(1,-12,1,-80),Size=UDim2.fromOffset(316,102),BackgroundColor3=Color3.fromRGB(10,10,18),BorderSizePixel=0})
create("UICorner",panel,{CornerRadius=UDim.new(0,12)})
local stroke=create("UIStroke",panel,{Color=Color3.new(1,1,1),Thickness=1,Transparency=.25})
create("UIGradient",stroke,{Color=ColorSequence.new(cyan,Color3.fromRGB(168,85,247)),Rotation=20})
local function text(name,value,size,color,position,dimensions)
    return create("TextLabel",panel,{Name=name,Text=value,FontFace=font,TextSize=size,TextColor3=color,BackgroundTransparency=1,TextXAlignment=Enum.TextXAlignment.Left,Position=position,Size=dimensions})
end
text("Title","SERVER JOB ID",13,cyan,UDim2.fromOffset(12,8),UDim2.new(1,-100,0,22))
text("Account",string.upper(B.Player.Name),11,Color3.fromRGB(166,177,204),UDim2.fromOffset(12,30),UDim2.new(1,-24,0,18))
local value=create("TextBox",panel,{Name="JobId",Text=game.JobId,TextEditable=false,ClearTextOnFocus=false,FontFace=font,TextSize=12,TextColor3=Color3.fromRGB(243,247,255),BackgroundColor3=Color3.fromRGB(22,22,37),BorderSizePixel=0,Position=UDim2.fromOffset(8,54),Size=UDim2.new(1,-16,0,36),TextXAlignment=Enum.TextXAlignment.Center})
create("UICorner",value,{CornerRadius=UDim.new(0,7)})
local copy=create("TextButton",panel,{Name="Copy",Text="COPY",FontFace=font,TextSize=12,TextColor3=cyan,BackgroundColor3=Color3.fromRGB(22,22,37),BorderSizePixel=0,Position=UDim2.new(1,-86,0,6),Size=UDim2.fromOffset(78,40),AutoButtonColor=true})
create("UICorner",copy,{CornerRadius=UDim.new(0,7)})
local copiedAt=0
local function layout()
    panel.Size=UDim2.fromOffset(math.min(316,math.max(160,gui.AbsoluteSize.X-24)),102)
end
function A.CopyJobId()
    if not A.Current() then return false end
    local job=game.JobId
    if type(job)~="string" or job=="" then copy.Text="NO ID";return false end
    value.Text=job
    local writer=setclipboard or toclipboard
    local ok,err=false,"clipboard unavailable"
    if type(writer)=="function" then ok,err=pcall(writer,job) end
    copiedAt=os.clock()
    if ok then
        copy.Text="COPIED";B.State.LastCopiedJobId=job;A.Errors["copy job id"]=nil
    else
        copy.Text="SELECT ID";value:CaptureFocus();value.SelectionStart=1;value.CursorPosition=#job+1
        A.Error("copy job id",err)
    end
    return ok
end
A.Connect(copy.Activated,A.CopyJobId)
A.Connect(gui:GetPropertyChangedSignal("AbsoluteSize"),layout)
A.Add({Id="ServerInfo",Name="server job id",Group="visuals",Description="Your current server ID at the right of the screen. COPY puts the full ID on the clipboard.",Get=function()return gui.Enabled end,Set=function(on)gui.Enabled=on end})
B.State.ServerInfoVersion=1
A.Cleanups[#A.Cleanups+1]=function()gui:Destroy()end
A.Loop("server info",1,function()
    if value.Text~=game.JobId then value.Text=game.JobId end
    if copiedAt>0 and os.clock()-copiedAt>=2 then copy.Text="COPY";copiedAt=0 end
end)
layout()

    end)(advanced, bridge);
    (function(A, B)
local Http=game:GetService("HttpService")
local Teleports=game:GetService("TeleportService")
local origin=game.JobId
local ticket
B.State.TransferLifecycleVersion=1
function B.State.BeginTransfer()
    if isfile("sharkwow-standout-no-autorun.flag") then return end
    if ticket then return end
    local data=Http:JSONDecode(readfile(B.State.ResumeFile))
    assert(type(data)=="table" and data.Enabled and data.UserId==B.Player.UserId,"transfer resume record missing")
    local loader=data.Licensed and "sharkwow-license-loader.lua" or "sharkwow-standout-owner.lua"
    local source=readfile(loader)
    assert(type(source)=="string" and #source>100,"transfer loader missing")
    local record={Done=false,Data=data,Connection=nil}
    ticket=record
    local function recover(reason)
        if record.Done or game.JobId~=origin then return end
        record.Done=true
        if record.Connection then record.Connection:Disconnect() end
        local env=getgenv()
        local active=env.MT_ArrowRokakaFinder
        if active and active.Alive and active~=B.State then return end
        record.Data.Created=os.time()
        env.SHARKWOW_STANDOUT_RESUME=record.Data
        local ok,err=pcall(function()
            writefile(B.State.ResumeFile,Http:JSONEncode(record.Data))
            assert(loadstring(source,"@sharkwow-transfer-recovery"))()
        end)
        local nextHub=env.MT_ArrowRokakaFinder
        if nextHub then
            nextHub.HopNextRead=os.clock()+60
            nextHub.HopStatus="transfer failed; farming restored"
            nextHub.LastTransferError=tostring(reason):sub(1,180)
        end
        if not ok then warn("sharkwow transfer recovery: "..tostring(err)) end
    end
    B.State.RecoverTransfer=recover
    record.Connection=Teleports.TeleportInitFailed:Connect(function(who,result)
        if who==B.Player then recover(result) end
    end)
    task.delay(40,function() recover("transfer timeout") end)
    B.State.TransferPending=true
    B.State.Unload(true)
end
A.Connect(B.Player.OnTeleport,function(status)
    if status==Enum.TeleportState.InProgress and B.Alive() then
        local ok,err=pcall(B.State.BeginTransfer)
        if not ok then A.Error("transfer preparation",err) end
    end
end)

    end)(advanced, bridge);
    (function(A, B)
local P=(function()
local P={}
function P.Crowded(count) return type(count)=="number" and count>=10 end
function P.LowPopulation(server)
    return type(server.playing)=="number" and server.playing<=5
end
function P.AgeSeconds(text)
    if type(text)~="string" then return nil end
    local d,h,m=text:match("^%s*(%d+)d%s+(%d+)h%s+(%d+)m%s*$")
    if not d then return nil end
    d,h,m=tonumber(d),tonumber(h),tonumber(m)
    if h>=24 or m>=60 then return nil end
    return d*86400+h*3600+m*60
end
function P.EarlyDue(age,limit)
    return type(age)=="number" and type(limit)=="number" and limit==limit
        and limit>3600 and limit<math.huge and age>=limit-3600
end
function P.ValidJob(v) return type(v)=="string" and #v==36 and v:match("^[%x%-]+$")~=nil end
function P.Blocked(rows,userId,placeId,now)
    local blocked={}
    for _,r in ipairs(rows) do
        if type(r)=="table" and r.Schema==1 and r.Place==placeId then
            if r.UserId~=userId and type(r.At)=="number" and math.abs(now-r.At)<=60 then
                if P.ValidJob(r.Job) then blocked[r.Job]="another account" end
                if P.ValidJob(r.Target) then blocked[r.Target]="another account reservation" end
            end
            if type(r.Closing)=="table" then for job,at in pairs(r.Closing) do
                if P.ValidJob(job) and type(at)=="number" and now-at>=0 and now-at<3600 then blocked[job]="closing server" end
            end end
        end
    end
    return blocked
end
function P.Prune(closing,now)
    local rows={}
    for job,at in pairs(closing or {}) do
        if P.ValidJob(job) and type(at)=="number" and now-at>=0 and now-at<3600 then rows[#rows+1]={Job=job,At=at} end
    end
    table.sort(rows,function(a,b)return a.At>b.At end)
    local result={}
    for i=1,math.min(20,#rows) do result[rows[i].Job]=rows[i].At end
    return result
end
return P

end)()
local Http=game:GetService("HttpService")
local folder="sharkwow-standout-fleet"
local path=folder.."/"..B.Player.UserId..".json"
local closing={}
local target
local ready=type(listfiles)=="function" and type(readfile)=="function" and type(writefile)=="function" and type(isfolder)=="function" and type(makefolder)=="function"
if ready then
    local ok,err=pcall(function()
        if not isfolder(folder) then makefolder(folder) end
        local readOK,data=pcall(function()return Http:JSONDecode(readfile(path))end)
        if readOK and type(data)=="table" and data.UserId==B.Player.UserId and data.Place==game.PlaceId and type(data.Closing)=="table" then closing=P.Prune(data.Closing,os.time()) end
    end)
    if not ok then ready=false;A.Error("server coordination",err) end
else A.Error("server coordination","shared file APIs unavailable") end
local function write()
    if not ready then return end
    closing=P.Prune(closing,os.time())
    writefile(path,Http:JSONEncode({Schema=1,UserId=B.Player.UserId,Place=game.PlaceId,Job=game.JobId,Target=target,At=os.time(),Closing=closing}))
end
local function exclusions()
    local rows={{Schema=1,Place=game.PlaceId,UserId=B.Player.UserId,Closing=closing}}
    if ready then
        local files=listfiles(folder)
        for i,file in ipairs(files) do
            if i>200 then break end
            if type(file)=="string" and file:match("[%d]+%.json$") then
                local ok,data=pcall(function()return Http:JSONDecode(readfile(file))end)
                if ok then rows[#rows+1]=data end
            end
        end
    end
    return P.Blocked(rows,B.Player.UserId,game.PlaceId,os.time())
end
local hop=B.State.HopLowServer
function B.State.HopLowServer(options)
    options=table.clone(options or {})
    local blocked=exclusions()
    if options.Target and not options.PauseFarm and blocked[options.Target.id] then
        B.State.HopStatus="server excluded: "..blocked[options.Target.id];return false
    end
    local accept,before,failure=options.Accept,options.BeforeTransfer,options.OnFailure
    options.Accept=function(server) return not blocked[server.id] and (not accept or accept(server)) end
    options.BeforeTransfer=function(server)
        if before then before(server) end
        target=server.id;write()
        if not options.PauseFarm then assert(not exclusions()[server.id],"server reserved by another account") end
    end
    options.OnFailure=function(reason)
        target=nil
        local ok,err=pcall(write);if not ok then A.Error("server coordination",err) end
        if failure then failure(reason) end
    end
    return hop(options)
end
A.Features.Servers.Action=B.State.HopLowServer
local controls={ServerTransfers="allow server transfers",AvoidShutdown="leave before shutdown",EmergencyHop="leave closing server",AutoLowPopulation="move from crowded server"}
for id,name in pairs(controls) do
    A.Add({Id=id,Name=name,Group="utility",Description="Saved server transfer switch. Disabled means stay in the current server.",Get=function()return A.Options[id].ResumeEnabled==true end,Set=function(value)
        A.Options[id].ResumeEnabled=value==true
        if id=="ServerTransfers" then B.State.ServerTransfersEnabled=value==true end
        A.Save()
    end})
end
B.State.ServerTransfersEnabled=A.Get("ServerTransfers")
B.State.ServerSafetyVersion=4
local joinedAt,crowdedAt=os.clock(),nil
local nextTry,lastWrite=0,0
local function tick()
    if os.clock()-lastWrite>=10 then write();lastWrite=os.clock() end
    local playerGui=B.Player:FindFirstChild("PlayerGui")
    local top=playerGui and playerGui:FindFirstChild("Topbar")
    local container=top and top:FindFirstChild("TopbarContainer")
    local label=container and container:FindFirstChild("ServerAge")
    local age=P.AgeSeconds(label and label.Text)
    local limit=workspace:GetAttribute("ServerShutdownAgeSeconds")
    if not A.Get("ServerTransfers") then B.State.ShutdownStatus="server transfers disabled";return end
    local emergency=A.Get("EmergencyHop") and workspace:GetAttribute("ServerClosing")==true
    local early=A.Get("AvoidShutdown") and P.EarlyDue(age,limit)
    B.State.ServerAgeSeconds=age
    B.State.ServerShutdownLimit=limit
    B.State.ServerEarlyHopAt=type(limit)=="number" and limit-3600 or nil
    if not early and not emergency then
        B.State.ShutdownStatus=age and "age monitored; leaves one hour early" or "waiting for native Server Age"
        if not A.Get("AutoLowPopulation") then crowdedAt=nil;B.State.PopulationStatus="population hopping disabled";return end
        local players=game:GetService("Players")
        local crowded=P.Crowded(#players:GetPlayers())
        crowdedAt=crowded and (crowdedAt or os.clock()) or nil
        B.State.PopulationStatus=crowded and "crowded; waiting for safe departure" or "low population; staying"
        local gardening=workspace.Game:FindFirstChild("Gardening")
        local pots=gardening and gardening:FindFirstChild("Pots")
        local gardener=getgenv().MT_RokakaGardenRun
        if gardener and gardener.Alive then
            for _,pot in ipairs(pots and pots:GetChildren()or{})do
                if pot:GetAttribute("OwnerUserId")==B.Player.UserId
                    and (pot:GetAttribute("Stage")=="Growing" or pot:GetAttribute("Stage")=="Ready") then
                    B.State.PopulationStatus="staying for personal crop harvest"
                    return
                end
            end
        end
        if not crowdedAt or os.clock()-crowdedAt<30 or os.clock()-joinedAt<60 or os.clock()<nextTry then return end
        local s=B.State
        if s.HopBusy or s.TransferPending or s.RaidBusy or s.PhoneBusy or s.CraftBusy or s.MaterialBusy or s.AutoBusy or s.TeleportBusy or s.RouteBusy or A.GardenBusy() then return end
        local previousPause=s.AutoHopPause
        s.AutoHopPause=true
        nextTry=os.clock()+60
        local function allowed()
            return A.Current() and A.Get("ServerTransfers") and A.Get("AutoLowPopulation") and P.Crowded(#players:GetPlayers()) and not (s.RaidBusy or s.PhoneBusy or s.CraftBusy or s.MaterialBusy or A.GardenBusy())
        end
        local ok,started=pcall(s.HopLowServer,{
            Accept=P.LowPopulation,
            CanContinue=allowed,
            OnFailure=function(reason)
                s.AutoHopPause=previousPause
                nextTry=os.clock()+60
                s.PopulationStatus="population transfer retry: "..tostring(reason):sub(1,100)
            end,
        })
        if not ok or not started then
            s.AutoHopPause=previousPause
            s.PopulationStatus="waiting for low population server: "..tostring(ok and s.HopStatus or started)
        else s.PopulationStatus="moving to low population server" end
        return
    end
    closing[game.JobId]=os.time()
    B.State.ShutdownStatus=emergency and "server closing; moving to another server" or "server age reached early departure; moving"
    if not emergency and (B.State.RaidBusy or B.State.CraftBusy or B.State.PhoneBusy or B.State.AutoBusy or B.State.TeleportBusy or B.State.TransferPending) then
        B.State.ShutdownStatus="early departure pending; waiting for current operation"
        return
    end
    if B.State.HopBusy or os.clock()<nextTry then return end
    write();nextTry=os.clock()+15
    local previousPause=B.State.AutoHopPause
    B.State.AutoHopPause=true
    local ok,started=pcall(B.State.HopLowServer,{CanContinue=function()return A.Current() and A.Get("ServerTransfers") and ((emergency and A.Get("EmergencyHop")) or (early and A.Get("AvoidShutdown")))end,OnFailure=function(reason)
        B.State.AutoHopPause=previousPause;nextTry=os.clock()+30
        B.State.ShutdownStatus="shutdown transfer retry: "..tostring(reason):sub(1,100)
    end})
    if not ok or not started then
        B.State.AutoHopPause=previousPause
        B.State.ShutdownStatus="shutdown transfer waiting: "..tostring(ok and B.State.HopStatus or started)
    end
end
local ok,err=pcall(write);if not ok then A.Error("server coordination",err) end
A.Loop("server safety",2,tick)
A.Connect(workspace:GetAttributeChangedSignal("ServerClosing"),function() nextTry=0 end)

    end)(advanced, bridge);
    (function(A, B)
local S=B.State
if S.ServerCapacityVersion==1 then return end
local previous=S.HopLowServer
local rejected={}
local function room(server)
    return type(server)=="table"and type(server.playing)=="number"and type(server.maxPlayers)=="number"
        and server.playing>=0 and server.maxPlayers>0
        and server.maxPlayers-server.playing>=math.min(3,server.maxPlayers)
end
S.ServerHasRoom=room
S.ServerCapacityVersion=1
S.HopLowServer=function(options)
    options=table.clone(options or{})
    if options.Target then return previous(options)end
    local accept,before,failure=options.Accept,options.BeforeTransfer,options.OnFailure
    local chosen
    options.Accept=function(server)
        return room(server)and(not rejected[server.id]or rejected[server.id]<=os.clock())and(not accept or accept(server))
    end
    options.BeforeTransfer=function(server)
        chosen=server.id
        if options.FreshSelection then assert(room(server),"destination has no room");if before then before(server)end;return end
        local requester=request or http_request or(syn and syn.request)
        assert(type(requester)=="function","capacity recheck unavailable")
        local http=game:GetService("HttpService")
        local cursor,verified
        for _=1,2 do
            local url="https://games.roblox.com/v1/games/"..game.PlaceId.."/servers/Public?sortOrder=Asc&limit=100&excludeFullGames=true"
            if cursor then url..="&cursor="..http:UrlEncode(cursor)end
            local response=requester({Url=url,Method="GET",Timeout=8,Headers={["Cache-Control"]="no-cache"}})
            assert(A.Current(),"capacity check cancelled")
            assert(type(response)=="table"and tonumber(response.StatusCode or response.Status)==200,"capacity recheck failed; retry later")
            local data=http:JSONDecode(response.Body)
            for _,candidate in ipairs(data.data or{})do if candidate.id==chosen then verified=candidate;break end end
            if verified or type(data.nextPageCursor)~="string"or data.nextPageCursor==cursor then break end
            cursor=data.nextPageCursor
        end
        assert(verified and options.Accept(verified),"destination full, near capacity, or unavailable; selecting another server")
        assert(not options.CanContinue or options.CanContinue(),"capacity check cancelled")
        server.playing=verified.playing;server.maxPlayers=verified.maxPlayers
        S.ServerCapacityStatus=string.format("checked: %d/%d players; %d spaces",server.playing,server.maxPlayers,server.maxPlayers-server.playing)
        if before then before(server)end
    end
    options.OnFailure=function(reason)
        if chosen then rejected[chosen]=os.clock()+180 end
        S.ServerCapacityStatus="retry another destination: "..tostring(reason)
        if failure then failure(reason)end
    end
    return previous(options)
end
A.Features.Servers.Action=S.HopLowServer

    end)(advanced, bridge);
    (function(A, B)
local Http=game:GetService("HttpService")
local S=B.State
local began,nextTry,attempts=os.clock(),0,0
local recoverable={[256]=true,[266]=true,[276]=true,[277]=true,[279]=true}
A.Add({Id="SessionRecovery",Name="auto reconnect + separate accounts",Group="utility",Description="Reconnect after connection errors and move away from another local account. Does not retry duplicate-login, moderation or manual kick errors."})
A.Features.SessionRecovery.Enabled=true
S.SessionRecoveryVersion=1
local function errorCode()
    local identity=type(getthreadidentity)=="function"and getthreadidentity()
    local ok,result=pcall(function()
    if identity and type(setthreadidentity)=="function"then setthreadidentity(8)end
    local core=game:GetService("CoreGui")
    assert(core,"disconnect UI unavailable")
    local gui=core:FindFirstChild("RobloxPromptGui")
    local label=gui and gui:FindFirstChild("ErrorMessage",true)
    if not label or not label:IsA("TextLabel")then return end
    local p=label
    while p and p~=gui do if p:IsA("GuiObject")and not p.Visible then return end;p=p.Parent end
    return tonumber(label.Text:match("(%d%d%d)"))
    end)
    if identity and type(setthreadidentity)=="function"then setthreadidentity(identity)end
    if not ok then error("disconnect UI inspection unavailable")end
    return result
end
local function sharedServer()
    if type(listfiles)~="function"or type(isfolder)~="function"or not isfolder("sharkwow-standout-fleet")then return false end
    for i,path in ipairs(listfiles("sharkwow-standout-fleet"))do
        if i>200 then break end
        if path:match("%d+%.json$")then
            local ok,r=pcall(function()return Http:JSONDecode(readfile(path))end)
            if ok and type(r)=="table"and type(r.UserId)=="number"and r.UserId<B.Player.UserId
                and r.Place==game.PlaceId and r.Job==game.JobId and type(r.At)=="number"
                and math.abs(os.time()-r.At)<=35 then return true end
        end
    end
    return false
end
S.SessionRecoveryProbe=function()return errorCode(),sharedServer()end
A.Loop("session recovery",3,function()
    if not A.Get("SessionRecovery")or S.TransferPending or S.HopBusy or os.clock()<nextTry or os.clock()-began<30 then return end
    local code=errorCode()
    if code and not recoverable[code]then S.SessionRecoveryStatus="manual attention: "..code;return end
    local collision=not code and sharedServer()
    if not code and not collision then S.SessionRecoveryStatus="connected; separate server";attempts=0;return end
    if not code and (S.RaidBusy or S.CraftBusy or S.MaterialBusy or S.PhoneBusy or S.AutoBusy or S.RouteBusy or S.TeleportBusy or A.GardenBusy())then
        S.SessionRecoveryStatus="separation waiting for current operation";return
    end
    attempts+=1;nextTry=os.clock()+math.min(180,30*attempts)
    S.SessionRecoveryStatus=code and ("reconnecting: "..code)or"separating local accounts"
    S.HopLowServer({Manual=true,FreshSelection=true,CanContinue=function()return A.Current()and A.Get("SessionRecovery")end,
        Accept=function(server)return server.playing>=3 end})
end)

    end)(advanced, bridge);
    (function(A, B)
local P=(function()
local P={}
function P.MistAction(objective,inRoom,hasIce,spareIce,needsIce)
    if not tostring(objective):lower():find("survive the mist",1,true) then return end
    local refill=not hasIce or (needsIce and (tonumber(spareIce) or 0)<=0)
    if inRoom then return refill and "refill" or "leave" end
    if refill then return "enter" end
    return needsIce and "give" or "wait"
end
function P.ComboAction(lightCount, blocking, heavyReady, mode)
    if mode=="m1m2" then return heavyReady and "heavy" or "light" end
    if mode=="m1" then return "light" end
    if mode=="heavy"then return heavyReady and "heavy"or "wait" end
    if blocking and heavyReady then return "heavy" end
    if lightCount>=3 then return "skill" end
    return "light"
end
function P.StageKey(state)
    return state and tostring(state.Id)..":"..tostring(state.Car)..":"..tostring(state.Objective)
end
function P.ExitDoor(attrs,x,carX)
    return attrs.DoorLocked==true and attrs.TrainRaidCloset~=true and x>carX+35
end
function P.NeedsCombatReturn(dx,dy)
    return math.abs(dy)>100 or math.abs(dx)>350
end
function P.HealthRisk(health,maxHealth,previous,burst,reserve,detectBurst)
    if not health or not maxHealth or maxHealth<=0 or health<=maxHealth*(reserve or .75)then return "health reserve reached" end
    if detectBurst==false then return end
    if previous and previous-health>=maxHealth*.12 then return "heavy incoming hit" end
    if (burst or 0)>=maxHealth*.18 then return "rapid incoming damage" end
end
function P.Attacking(attrs,actionTrack)
    return attrs.Swinging==true or attrs.HeavySwinging==true or attrs.HitEnabled==true
        or attrs.Attacking==true or actionTrack==true
end
function P.CounterReady(now,lastThreat,nextStrike,states)
    return now-lastThreat>=.35 and now>=nextStrike and not
        (states.Stunned or states.Swinging or states.HeavySwinging or states.SwingCooldown or states.Blocking or states.BlockCooldown or states.Dashing)
end
function P.Prefer(candidate,target,nearest,distance,bestDistance)
    return distance<350 and (nearest==nil or candidate==target or(nearest~=target and distance<bestDistance))
end
function P.CombatObjective(objective)
    local text=string.lower(objective or "")
    return text:match("^defeat ")~=nil or text:match("^beat ")~=nil or text:match("^protect ")~=nil
        or text:match("^fight ")~=nil or text:match("^clear ")~=nil
end
function P.Mode(active,enabled,cooldown,level,health,maxHealth)
    if not enabled then return "off" end
    if not health or not maxHealth or maxHealth<=0 or health<=0 then return "waiting character" end
    if health<maxHealth*.99 then return "recover" end
    if active then return "raid" end
    if level<20 then return "level required" end
    if cooldown>0 then return "arrows" end
    return "enter"
end
function P.Enemy(attrs,raidId,isPlayer,hp)
    if isPlayer or not hp or hp<=0 or type(raidId)~="string" then return false end
    if attrs.TrainRaidAmbient or attrs.TrainRaidDormant or attrs.FightableNPC==false or attrs.Config=="TrainRaidPassenger" then return false end
    return attrs.Group=="TrainRaidEnemies_"..raidId
end
function P.Prompt(action,object,objective,promptName)
    action=string.lower(action or "");object=string.lower(object or "");objective=string.lower(objective or "")
    if action:find("buy",1,true) or action:find("purchase",1,true) or action:find("drop",1,true) then return false end
    if objective:find("enter the next car",1,true) then return false end
    if action=="investigate" then return objective=="find clues" end
    if action=="enter"and object=="coco jumbo"then return objective=="enter coco jumbo"or objective=="take ice from the fridge"end
    if action=="take ice"and object=="fridge"then return objective=="take ice from the fridge"end
    if action=="leave"and object=="coco jumbo"then return objective~="take ice from the fridge"end
    if action=="hide coco jumbo"and object=="under the seat"then return objective=="hide coco jumbo"end
    if action=="give ice"then return objective:find("survive the mist",1,true)~=nil end
    if action=="talk" and (object=="doris socks"or promptName=="OldLadyTalk")then return objective:find("old lady",1,true)~=nil or objective:match("^return ")~=nil end
    if action=="pick the lock" then return objective:find("lock",1,true)~=nil or(object=="compartment"and objective=="find the door key")end
    if action=="pick up" and object=="tea flask" then return objective:find("tea flask",1,true)~=nil end
    if action=="pick up"and promptName=="OldLadyItem"then return objective:match("^find ")~=nil and object~=""and objective:find(object,1,true)~=nil end
    if action=="search her purse" and (object=="doris socks"or promptName=="OldLadyTalk")then return objective=="find the paper clip" end
    if action=="unlock" then return objective:find("unlock",1,true)~=nil end
    if action=="pick up" and object:find("key",1,true) then return objective:find("key",1,true)~=nil end
    if action=="search" then return objective:find("search",1,true)~=nil or objective:find("find",1,true)~=nil end
    if action=="open" then return objective:find("open",1,true)~=nil end
    if object:find("ice",1,true) then return objective:find("ice",1,true)~=nil end
    if object:find("coco",1,true) then return objective:find("coco",1,true)~=nil end
    return false
end
function P.Delta(before,after)
    local result={}
    for name,amount in pairs(after)do
        local gain=amount-(before[name]or 0)
        if gain>0 then result[name]=gain end
    end
    return result
end
return P

end)()
local Geometry=(function()
local G={}
function G.SupportedFloor(raycast,point,radius)
    for _,offset in ipairs({Vector3.new(radius,0,radius),Vector3.new(radius,0,-radius),Vector3.new(-radius,0,radius),Vector3.new(-radius,0,-radius)})do
        local hit=raycast(point+offset+Vector3.new(0,1,0),Vector3.new(0,-2,0))
        if not hit or hit.Normal.Y<.7 or math.abs(hit.Position.Y-point.Y)>.5 then return false end
    end
    return true
end
function G.Overlap(a,as,b,bs)
    local aa={a.RightVector,a.UpVector,a.LookVector}
    local ba={b.RightVector,b.UpVector,b.LookVector}
    local ah={as.X/2,as.Y/2,as.Z/2}
    local bh={bs.X/2,bs.Y/2,bs.Z/2}
    local delta=b.Position-a.Position
    local axes={aa[1],aa[2],aa[3],ba[1],ba[2],ba[3]}
    for _,x in ipairs(aa)do for _,y in ipairs(ba)do axes[#axes+1]=x:Cross(y)end end
    for _,axis in ipairs(axes)do
        if axis.Magnitude>1e-6 then
            local ra,rb=0,0
            for i=1,3 do ra+=ah[i]*math.abs(aa[i]:Dot(axis));rb+=bh[i]*math.abs(ba[i]:Dot(axis))end
            if math.abs(delta:Dot(axis))>ra+rb+1e-6 then return false end
        end
    end
    return true
end
return G

end)()
local LockFactory=(function()
return function(A,B,Policy,options)
    options=options or {}
    local prefix=options.Prefix or "PhoneCop"
    local Run=game:GetService("RunService")
    local lock
    local retry=setmetatable({},{__mode="k"})
    local C={Version=2}
    A[options.Store or "PhoneCopLock"]=C
    local function shape(native)
        if not debug or type(debug.getupvalues)~="function" then return end
        for _,profile in pairs(debug.getupvalues(native.lightSwing)) do
            if type(profile)=="table" and type(profile.M1Hitbox)=="table" and #profile.M1Hitbox>0 then
                local boxes={}
                for i,size in ipairs(profile.M1Hitbox) do
                    if typeof(size)~="Vector3" or size.X<=0 or size.Y<=0 or size.Z<=0 or size.Magnitude>100 then return end
                    local offset=profile.M1HitboxOffsets and profile.M1HitboxOffsets[i] or CFrame.new(0,0,-size.Z/2)
                    if typeof(offset)~="CFrame" then return end
                    boxes[#boxes+1]={Size=size,Offset=offset}
                end
                return boxes
            end
        end
    end
    function C.Release()
        local old=lock
        if not old then return end
        lock=nil
        for _,connection in ipairs(old.Connections) do connection:Disconnect() end
        for _,object in ipairs(old.Objects) do object:Destroy() end
        for part,value in pairs(old.Collisions) do if part.Parent then part.CanCollide=value end end
        if old.Root.Parent then
            old.Root.AssemblyLinearVelocity=Vector3.zero;old.Root.AssemblyAngularVelocity=Vector3.zero
            if B.Player.Character==old.Character then
                local position=old.Root.Position
                local look=old.TargetRoot.Parent and old.TargetRoot.CFrame.LookVector or Vector3.new(0,0,-1)
                old.Root.CFrame=CFrame.lookAt(position,position+Vector3.new(look.X,0,look.Z))
                old.Humanoid.AutoRotate=old.AutoRotate
            end
        end
        B.State[prefix.."LockActive"]=false
    end
    function C.Begin(target,native,current)
        if lock and lock.Target==target and lock.Character==B.Player.Character
            and target:FindFirstChild("HumanoidRootPart")==lock.TargetRoot
            and target:FindFirstChildOfClass("Humanoid")==lock.TargetHumanoid
            and lock.Character:FindFirstChild("HumanoidRootPart")==lock.Root
            and lock.Character:FindFirstChildOfClass("Humanoid")==lock.Humanoid
            and target.Parent and lock.TargetHumanoid.Health>0 and current()then lock.Valid=current;return true end
        C.Release()
        if not target.Parent or not current()then return false end
        if (retry[target] or 0)>os.clock() then return false end
        if not Policy.ownedCop(target:GetAttributes(),B.Player.UserId,B.Player.Name) then return false end
        local character,root,humanoid=A.Character()
        local targetRoot=target:FindFirstChild("HumanoidRootPart")
        local targetHumanoid=target:FindFirstChildOfClass("Humanoid")
        local boxes=shape(native)
        if not character or root.Anchored or not targetRoot or not targetHumanoid or targetHumanoid.Health<=0 or not boxes then return false end
        local params=OverlapParams.new();params.FilterType=Enum.RaycastFilterType.Include;params.FilterDescendantsInstances={targetRoot};params.MaxParts=1
        local old={Target=target,TargetRoot=targetRoot,TargetHumanoid=targetHumanoid,Character=character,Root=root,Humanoid=humanoid,AutoRotate=humanoid.AutoRotate,Collisions={},Objects={},Connections={},Valid=current,Height=options.Height or 4.75,Started=os.clock(),HP=targetHumanoid.Health,LastDamage=os.clock()}
        old.Offset=targetRoot.CFrame:VectorToWorldSpace(Vector3.new(0,0,options.Distance or 3))
        old.Distance=options.Distance or 3
        old.Depth=options.Depth or 5.5
        old.DepthStepAt=os.clock()
        old.PlayerHP=humanoid.Health
        local floorParams
        if options.Mode=="below"then
            floorParams=RaycastParams.new();floorParams.FilterType=Enum.RaycastFilterType.Include
            floorParams.FilterDescendantsInstances={workspace.Game.Map}
        end
        local function pose()
            if options.Mode=="below"then
                local position=targetRoot.Position-Vector3.new(0,old.Depth,0)
                local floor=workspace:Raycast(targetRoot.Position,Vector3.new(0,-32,0),floorParams)
                if not floor or floor.Position.Y-position.Y<1.25 then return nil end
                return CFrame.lookAt(position,targetRoot.Position,targetRoot.CFrame.RightVector)
            end
            if options.Mode=="behind" then
                if options.ResolveBehind then return options.ResolveBehind(targetRoot,old.Distance)end
                local offset=options.FollowFacing and targetRoot.CFrame:VectorToWorldSpace(Vector3.new(0,0,old.Distance))or old.Offset
                local position=targetRoot.Position+offset
                return CFrame.lookAt(position,targetRoot.Position)
            end
            local position=targetRoot.Position+Vector3.new(0,old.Height,0)
            return CFrame.lookAt(position,targetRoot.Position,targetRoot.CFrame.RightVector)
        end
        local function overlaps(at)
            for _,box in ipairs(boxes) do
                if options.Overlap then
                    if not options.Overlap(at*box.Offset,box.Size,targetRoot.CFrame,targetRoot.Size)then return false end
                elseif #workspace:GetPartBoundsInBox(at*box.Offset,box.Size,params)==0 then return false end
            end
            return true
        end
        local initialPose=pose()
        if options.Mode=="behind"and options.AdaptDistance then
            initialPose=nil
            for distance=old.Distance,3,-.25 do
                old.Distance=distance
                local candidate=pose()
                if candidate and overlaps(candidate)then
                    old.Distance=math.max(3,distance-.25);initialPose=pose();break
                end
            end
        end
        if options.Mode=="below" and options.MaxDepth then
            initialPose=nil
            for depth=options.MaxDepth,options.Depth or 5.5,-.25 do
                old.Depth=depth
                local candidate=pose()
                if candidate and overlaps(candidate)then
                    old.Depth=math.max(options.Depth or 5.5,depth-.35)
                    initialPose=pose();break
                end
            end
        end
        if not initialPose or not overlaps(initialPose)or(options.ValidatePose and not options.ValidatePose(initialPose,targetRoot))then return false end
        lock=old
        local attachment=Instance.new("Attachment");attachment.Name="SHARKWOW"..prefix.."Hold";attachment.Parent=root;old.Objects[#old.Objects+1]=attachment
        local velocity=Instance.new("LinearVelocity");velocity.Name="SHARKWOW"..prefix.."Hold";velocity.Attachment0=attachment;velocity.RelativeTo=Enum.ActuatorRelativeTo.World;velocity.MaxForce=math.huge;velocity.VectorVelocity=Vector3.zero;velocity.Parent=root;old.Objects[#old.Objects+1]=velocity
        humanoid.AutoRotate=false
        local telemetry={Version=2,Target=target.Name,Owner=B.Player.UserId,Mode=options.Mode or "above",Distance=options.Mode=="behind" and old.Distance or nil,Depth=options.Mode=="below" and old.Depth or nil,Height=old.Height,Before=old.HP,After=old.HP,Damage=0,IncomingDamage=0,PlayerBefore=humanoid.Health,PlayerAfter=humanoid.Health,Started=old.Started}
        B.State[prefix.."Result"]=telemetry;B.State[prefix.."LockActive"]=true
        local function pulse()
            if lock~=old then return end
            telemetry.PlayerAfter=humanoid.Health
            if humanoid.Health<old.PlayerHP then
                telemetry.IncomingDamage+=old.PlayerHP-humanoid.Health
                if options.RetreatOnDamage then
                    telemetry.Result="incoming damage; retreating";retry[target]=os.clock()+30;C.Release();return
                end
            end
            old.PlayerHP=humanoid.Health
            if not A.Current() or not old.Valid() or B.Player.Character~=character or not root.Parent or humanoid.Health<=0
                or not target.Parent or not targetRoot.Parent or targetHumanoid.Health<=0
                or target:FindFirstChild("HumanoidRootPart")~=targetRoot or target:FindFirstChildOfClass("Humanoid")~=targetHumanoid
                or character:FindFirstChild("HumanoidRootPart")~=root or character:FindFirstChildOfClass("Humanoid")~=humanoid
                or not Policy.ownedCop(target:GetAttributes(),B.Player.UserId,B.Player.Name) then
                telemetry.After=targetHumanoid.Health;telemetry.Damage=math.max(0,telemetry.Before-telemetry.After);C.Release();return
            end
            if targetHumanoid.Health<old.HP then old.LastDamage=os.clock() end
            old.HP=targetHumanoid.Health
            telemetry.After=targetHumanoid.Health;telemetry.Damage=math.max(0,telemetry.Before-telemetry.After)
            if os.clock()-old.LastDamage>5 then old.Height=options.FallbackHeight or 4;telemetry.Height=old.Height end
            if options.Mode=="below" and options.AdaptDepth and os.clock()-old.LastDamage>3
                and os.clock()-old.DepthStepAt>3 and old.Depth>(options.Depth or 5.5)then
                local previousDepth=old.Depth
                old.Depth=math.max(options.Depth or 5.5,old.Depth-.25)
                local candidate=pose()
                if not candidate or not overlaps(candidate)then old.Depth=previousDepth end
                old.DepthStepAt=os.clock();telemetry.Depth=old.Depth
            end
            if os.clock()-old.LastDamage>(options.NoDamageTimeout or 12) then telemetry.Result="no damage; released";retry[target]=os.clock()+30;C.Release();return end
            local at=pose()
            if not at then telemetry.Result="no supported underground attack position";C.Release();return end
            if options.ValidatePose and not options.ValidatePose(at,targetRoot)then telemetry.Result="unsafe target position";C.Release();return end
            if options.Mode=="behind" and options.AdaptDistance and not overlaps(at)then
                for distance=old.Distance-.25,3,-.25 do
                    old.Distance=distance
                    local candidate=pose()
                    if candidate and overlaps(candidate)and(not options.ValidatePose or options.ValidatePose(candidate,targetRoot))then
                        at=candidate;telemetry.Distance=distance;break
                    end
                end
            end
            if not overlaps(at) then telemetry.Result="target outside native hitbox";C.Release();return end
            for _,part in ipairs(character:GetDescendants()) do
                if part:IsA("BasePart") then
                    if old.Collisions[part]==nil then old.Collisions[part]=part.CanCollide end
                    part.CanCollide=false
                end
            end
            root.AssemblyLinearVelocity=Vector3.zero;root.AssemblyAngularVelocity=Vector3.zero;root.CFrame=at
        end
        local function safePulse()
            local owned=lock==old
            local ok,err=pcall(pulse)
            if not ok then C.Release();A.Error(options.Error or "phone cop lock",err) end
            if owned and lock~=old and type(C.OnLost)=="function"then
                local good,reason=pcall(C.OnLost)
                if not good then A.Error(options.Error or "target lock cleanup",reason)end
            end
        end
        old.Connections[#old.Connections+1]=Run.PreSimulation:Connect(safePulse)
        old.Connections[#old.Connections+1]=Run.PostSimulation:Connect(safePulse)
        safePulse()
        return lock==old
    end
    A.Cleanups[#A.Cleanups+1]=C.Release
    return C
end

end)()
local Http=game:GetService("HttpService")
local Players=game:GetService("Players")
local RS=game:GetService("ReplicatedStorage")
local Run=game:GetService("RunService")
local Teleports=game:GetService("TeleportService")
local player=B.Player
local id="AutoRaid"
local path="sharkwow-standout-raid-"..player.UserId..".json"
local config={Schema=1,UserId=player.UserId,Enabled=false}
if type(readfile)=="function"then
    local ok,data=pcall(function()return Http:JSONDecode(readfile(path))end)
    if ok and type(data)=="table"and data.Schema==1 and data.UserId==player.UserId then config=data end
end
config.Enabled=false -- Fresh sessions require explicit player opt-in.
if config.StayInRaid==nil then config.StayInRaid=true end
config.CombatMode="m1m2"
local remote=RS.Remotes.TrainRaid
local referenceCombat=config.ReferenceCombat~=false
local nativeRaid=require(player.PlayerScripts.Core.TrainRaidClient)
local minigames=(function()
return function(A,B)
    local core=B.Player.PlayerScripts.Core
    local lock=require(core.QTE.Lockpicking)
    local rules=require(game.ReplicatedStorage.Modules.Lockpicking)
    local purse=require(core.TrainRaidClient.Purse)
    local inspect=require(core.ItemInspection)
    local remote=game.ReplicatedStorage.Remotes.Lockpicking
    local M={Revision=0}
    local session,attempt,stepAt,started,deadline,difficulty
    local angles,used={},{}
    local purseAt=0
    local sessionDifficulty={}
    A.Connect(remote.OnClientEvent,function(action,data)
        if action=="Start" and type(data)=="table" and data.Id then
            sessionDifficulty={[data.Id]=data.Difficulty}
            M.Revision+=1
        elseif action=="End" and type(data)=="table" then
            B.State.RaidLockOutcome={Success=data.Success==true,Reason=data.Reason,At=os.clock()}
            M.Revision+=1
        end
    end)
    local function named(fn,name,depth,seen)
        if depth<0 or seen[fn]then return end
        seen[fn]=true
        for _,v in pairs(debug.getupvalues(fn))do
            if type(v)=="function"then
                if debug.info(v,"n")==name then return v end
            end
        end
        for _,v in pairs(debug.getupvalues(fn))do
            if type(v)=="function"then local found=named(v,name,depth-1,seen);if found then return found end end
        end
    end
    local startTurn=named(lock.Start,"startTurn",2,{})
    local stopTurn=named(lock.Start,"stopTurn",3,{})
    local purseAction=named(purse.Open,"action",0,{})
    local function stop()
        if session and lock:GetSession()==session and session.Turning then
            if stopTurn then stopTurn(session)
            else session.Turning=false;session.Allowance=nil;remote:FireServer("Release",session.Id)end
        end
    end
    function M.Release()
        stop();session=nil;attempt=nil
    end
    function M.Step()
        local s=lock:GetSession()
        if s and not s.Ended then
            if not startTurn then return true,"native lock input unavailable",true end
            if session~=s then
                session=s;attempt=nil;stepAt=0;started=os.clock();deadline=started+45
                local _,cfg=rules.Resolve(sessionDifficulty[s.Id] or s.Difficulty)
                difficulty=cfg;angles={0,-55,55};used={}
            end
            if os.clock()>deadline or s.PicksLeft<2 then stop();return true,"lockpick safety limit reached",true end
            if s.Busy then return true,"waiting for lock animation"end
            if attempt and s.Allowance then
                if s.Allowance>=.999 then return true,"turning lock"end
                local allowance=s.Allowance
                stop();stepAt=os.clock()+.25
                if allowance>rules.MinAllowance+.001 and allowance<rules.MaxPartial then
                    local distance=difficulty.Window+difficulty.Partial*(1-allowance/rules.MaxPartial)
                    table.insert(angles,1,math.clamp(attempt-distance,-rules.PickRange,rules.PickRange))
                    table.insert(angles,1,math.clamp(attempt+distance,-rules.PickRange,rules.PickRange))
                end
                attempt=nil
            elseif attempt and os.clock()-s.TurnSent>.65 then
                stop();attempt=nil;stepAt=os.clock()+.35
            end
            if not attempt and not s.Turning and os.clock()>=stepAt and os.clock()>=(s.NextTurn or 0)then
                local angle
                while #angles>0 do
                    local candidate=table.remove(angles,1)
                    local key=math.floor(candidate*10+.5)
                    if not used[key]then used[key]=true;angle=candidate;break end
                end
                if not angle then
                    for value=-75,75,8 do if not used[math.floor(value*10+.5)]then angle=value;used[value*10]=true;break end end
                end
                if not angle then return true,"lockpick angle search exhausted",true end
                s.Angle=angle;startTurn(s)
                if s.Turning then attempt=angle
                else used[math.floor(angle*10+.5)]=nil;table.insert(angles,1,angle)end
                stepAt=os.clock()+.25
            end
            return true,"solving lock from native turn feedback"
        end
        session=nil;attempt=nil
        local bag
        for _,v in pairs(debug.getupvalues(purse.Close))do
            if type(v)=="table"and type(v.Token)=="string"and type(v.Items)=="table"then bag=v;break end
        end
        if bag and inspect.IsOpen(bag.Key)then
            if not purseAction then return true,"native purse input unavailable",true end
            if os.clock()-bag.Started>60 then return true,"purse interaction timed out",true end
            if os.clock()>=purseAt then purseAction(bag);purseAt=os.clock()+.4 end
            return true,"searching purse in native item order"
        end
        return false
    end
    A.Cleanups[#A.Cleanups+1]=M.Release
    return M
end

end)()(A,B)
local state,board,results
local generation,nextAction,nextSync,nextBoard=0,0,0,0
local acquired=false
local target,attack,attackNative,attackCharacter
local targetHealthConnection
local comboLights=0
local throwPending,throwUntil,throwNext=nil,0,0
local roofLock
local throwHeldItem,throwHeldAt,throwDropSent
local guardNative,guardCharacter,lastThreat,nextStrike=nil,nil,0,0
local damageWindow={}
local lastFingerprint,lastProgress=nil,os.clock()
local recoverAt=0
local recoveryReturn,recoveryCharacter,recoveryPlaced
local crouchNative,crouchCharacter
local function releaseCrouch()
    if crouchNative and player.Character==crouchCharacter then pcall(crouchNative.stopCrouching,crouchNative)end
    crouchNative=nil;crouchCharacter=nil
end
local held,safePose,lastHP,lastHumanoid,emergency
if type(config.SafePosition)=="table" and config.SafePosition.Job==game.JobId then
    local p=config.SafePosition
    if type(p.X)=="number"and type(p.Y)=="number"and type(p.Z)=="number"then
        safePose={Character=player.Character,Job=game.JobId,CFrame=CFrame.new(p.X,p.Y,p.Z)}
    end
end
local departUntil=0
if type(config.RecoveryReturn)=="table"and config.RecoveryReturn.Job==game.JobId then
    local p=config.RecoveryReturn
    if type(p.X)=="number"and type(p.Y)=="number"and type(p.Z)=="number"then
        recoveryReturn=CFrame.new(p.X,p.Y,p.Z);recoveryCharacter=player.Character;recoveryPlaced=true
    end
end
local exitRequested=false
local exitAttempts,exitNext,exitInFlight=0,0,false
local healthConnection
local promptAttempts={}
local objectiveRetries=0
local miniRevision=0
local function promptPoint(prompt)
    local parent=prompt.Parent
    if parent and parent:IsA("BasePart")then return parent.Position end
    if parent and parent:IsA("Attachment")then return parent.WorldPosition end
end
local function promptKey(prompt)
    local p=promptPoint(prompt)
    return prompt:GetFullName()..":"..prompt.ObjectText..(p and string.format(":%.1f:%.1f:%.1f",p.X,p.Y,p.Z)or "")
end
local paused={"AutoStory","AutoLevel20","AutoFarm","AutoQuest","QuestFarm","BountyFarm","QuestTravel","AutoDialogue","AutoHopArrows","AutoCraftBizarre","FreeArrowMaterials","MoneyTransportFarm","AutoPilot","AutoSkills","AutoSummon","AutoDropJunk"}
local function save()
    assert(type(writefile)=="function","raid config storage unavailable")
    writefile(path,Http:JSONEncode(config))
end
local function status(message)
    B.State.RaidStatus=message;A.Status=message
end
local function valid(token,character)
    return A.Current()and A.Get(id)and generation==token and not emergency
        and (not character or player.Character==character)and not B.State.TransferPending
end
local lock=LockFactory(A,B,{ownedCop=function(attrs)
    return state and P.Enemy(attrs,state.Id,false,1)
end},{Prefix="Raid",Store="RaidLock",Mode="behind",Distance=7.8,FollowFacing=true,AdaptDistance=true,NoDamageTimeout=30,RetreatOnDamage=false,Overlap=Geometry.Overlap,
ValidatePose=function(at,root)
    return state and typeof(state.Origin)=="Vector3" and at.Position.Y>=state.Origin.Y+1
        and root.AssemblyLinearVelocity.Y>-35
end,
ResolveBehind=function(root,distance)
    if not state or typeof(state.Origin)~="Vector3"then return nil end
    local origin=state.Origin
    for _,angle in ipairs({0,45,-45,90,-90,135,-135,180})do
        local offset=(root.CFrame*CFrame.Angles(0,math.rad(angle),0)):VectorToWorldSpace(Vector3.new(0,0,distance))
        local position=root.Position+offset
        if math.abs(position.Z-origin.Z)<=17 and position.X>=origin.X-65
            and position.X<=origin.X+(state.Cars-1)*156.2+65 and position.Y>=origin.Y+1 then
            return CFrame.lookAt(position,root.Position)
        end
    end
    return nil
end})
local function releaseGuard()
    if guardNative and player.Character==guardCharacter then
        pcall(function()guardNative:getStates().HoldingBlock=false;guardNative:blockStop()end)
    end
    guardNative=nil;guardCharacter=nil
end
local function stopStrike()
    if A.ReleaseFarmSkill then A.ReleaseFarmSkill("raid")end
    if attackNative and player.Character==attackCharacter then
        pcall(function()attackNative:getStates().HoldingM1=false end)
        pcall(attackNative.cancelAttacksForStandReplacement,attackNative)
        pcall(attackNative.finishBasicAttack,attackNative,true)
    end
    if attack and coroutine.status(attack)~="dead"then pcall(task.cancel,attack)end
    attack=nil;attackNative=nil;attackCharacter=nil
end
local function releaseRoof()
    local old=roofLock
    if not old then return end
    roofLock=nil
    old.Connection:Disconnect()
    if old.Humanoid.Parent then old.Humanoid.AutoRotate=old.AutoRotate end
    B.State.RaidRoofLocked=false
end
local function stopCombat()
    if targetHealthConnection then targetHealthConnection:Disconnect();targetHealthConnection=nil end
    releaseRoof()
    lock.Release();stopStrike();releaseGuard();target=nil;lastThreat=os.clock()
    comboLights=0
    throwPending=nil;throwUntil=0
end
local function release()
    stopCombat()
    releaseCrouch()
    minigames.Release()
    if held then pcall(held.InputHoldEnd,held);held=nil end
    if acquired or player:GetAttribute("TrainRaidActive")~=true then
        acquired=false;B.State.RaidBusy=false;B.State.ExtensionPause=false;B.State.CraftBusy=false
    end
end
local function restore()
    local prior=config.Previous
    if not prior then return end
    config.Previous=nil;save()
    for _,kind in ipairs({"arrow","rokaka","part"})do B.State.SetAuto(kind,prior[kind]==true)end
    for feature,enabled in pairs(prior.Features or {})do if enabled and A.Features[feature]then A.Set(feature,true)end end
end
local function acquire()
    if acquired then return true end
    if B.State.AutoBusy or B.State.TeleportBusy or B.State.HopBusy or A.GardenBusy()then return false end
    config.Previous=config.Previous or {arrow=B.State.AutoArrow==true,rokaka=B.State.AutoRokaka==true,part=B.State.AutoParts==true,Features={}}
    for _,feature in ipairs(paused)do
        if A.Get(feature)then config.Previous.Features[feature]=true;A.Set(feature,false)end
    end
    if A.Get("GardenHarvest")then config.Previous.Features.GardenHarvest=true;A.Set("GardenHarvest",false)end
    save()
    for _,kind in ipairs({"arrow","rokaka","part"})do B.State.SetAuto(kind,false)end
    B.SetFly(false)
    if B.State.ReleaseIdleHide then B.State.ReleaseIdleHide()end
    if B.ReleaseFarmHold then B.ReleaseFarmHold()end
    acquired=true;B.State.RaidBusy=true;B.State.ExtensionPause=true;B.State.CraftBusy=true
    return true
end
local function emergencyStop(reason)
    if emergency then return end
    emergency=reason;config.PausedReason=reason;generation+=1
    local stay=config.StayInRaid==true and player:GetAttribute("TrainRaidActive")==true
    config.ReturnToArrows=not stay or nil;recoverAt=os.clock()+3
    local currentCharacter=player.Character
    local currentHumanoid=currentCharacter and currentCharacter:FindFirstChildOfClass("Humanoid")
    local currentRoot=currentCharacter and currentCharacter:FindFirstChild("HumanoidRootPart")
    config.LastEmergency={Reason=reason,Job=game.JobId,At=os.time(),Health=currentHumanoid and currentHumanoid.Health,
        Lives=state and state.Lives,Car=state and state.Car,Objective=state and state.Objective,Combat=B.State.RaidResult,
        Position=currentRoot and {X=currentRoot.Position.X,Y=currentRoot.Position.Y,Z=currentRoot.Position.Z}}
    config.Enabled=stay;A.Features[id].Enabled=stay
    pcall(stopCombat);pcall(minigames.Release)
    local saved,saveError=pcall(save)
    if not saved then A.Error("raid emergency settings",saveError)end
    local c,r,h=A.Character()
    if c and safePose and safePose.Character==c and safePose.Job==game.JobId then
        r.CFrame=safePose.CFrame;r.AssemblyLinearVelocity=Vector3.zero;r.AssemblyAngularVelocity=Vector3.zero
    end
    recoveryReturn=c and r.CFrame or nil;recoveryCharacter=c;recoveryPlaced=false
    B.State.RaidEmergency=reason;status("raid paused: "..reason)
    if not stay and player:GetAttribute("TrainRaidActive")==true and not exitRequested then
        exitRequested=true
        local wrote,writeError=pcall(save)
        if not wrote then A.Error("raid emergency settings",writeError)end
        B.State.SetAuto("arrow",true)
        exitNext=0
    end
end
local function attemptExit()
    if config.StayInRaid==true or not emergency or exitInFlight or exitAttempts>=5 or os.clock()<exitNext
        or B.State.TransferPending or player:GetAttribute("TrainRaidActive")~=true then return end
    exitInFlight=true;exitAttempts+=1;exitNext=os.clock()+math.min(10,2*exitAttempts)
    B.State.RaidExitAttempts=exitAttempts
    task.spawn(function()
        if not A.Current() then exitInFlight=false;return end
        local prepared,resumeError=pcall(B.State.EnsureResumeReady)
        if not prepared or not resumeError then A.Error("raid emergency resume",resumeError or "unavailable")end
        local ok,err=pcall(Teleports.Teleport,Teleports,game.PlaceId,player)
        exitInFlight=false
        if not ok then A.Error("raid emergency return",err)end
    end)
end
function B.State.ReturnFromRaid()
    if player:GetAttribute("TrainRaidActive")~=true then return false end
    config.StayInRaid=false
    emergencyStop("raid exit requested; returning to arrow farm");attemptExit();return true
end
lock.OnLost=function()
    if target and target.Parent and target:FindFirstChildOfClass("Humanoid") and target.Humanoid.Health>0 then
        emergencyStop("combat position lost; review required")
    end
end
local function move(point,maxDistance)
    local c,r,h=A.Character();if not c or emergency then return false end
    local params=RaycastParams.new();params.FilterType=Enum.RaycastFilterType.Exclude
    params.RespectCanCollide=true
    params.FilterDescendantsInstances={c,workspace.Game.Players,workspace.Game.NPCs,workspace.Game.Stands}
    local landing,best
    for _,offset in ipairs({Vector3.zero,Vector3.new(2,0,0),Vector3.new(-2,0,0),Vector3.new(0,0,2),Vector3.new(0,0,-2),Vector3.new(3,0,0),Vector3.new(-3,0,0)})do
        local floor=workspace:Raycast(point+offset+Vector3.new(0,3,0),Vector3.new(0,-12,0),params)
        if floor and floor.Normal.Y>=.7 and floor.Instance.CanCollide
            and Geometry.SupportedFloor(function(from,direction)return workspace:Raycast(from,direction,params)end,floor.Position,1)then
            local candidate=floor.Position+Vector3.new(0,h.HipHeight+r.Size.Y/2+.1,0)
            local distance=(candidate-point).Magnitude
            if (not maxDistance or distance<maxDistance-.15)and(not best or distance<best)then landing=candidate;best=distance end
        end
    end
    if not landing then status("raid waiting for reachable solid floor");return false end
    stopCombat()
    r.AssemblyLinearVelocity=Vector3.zero;r.AssemblyAngularVelocity=Vector3.zero
    r.CFrame=CFrame.new(landing)
    return true
end
local function rememberSafe()
    local c,r=A.Character();if c then
        safePose={Character=c,Job=game.JobId,CFrame=r.CFrame}
        config.SafePosition={Job=game.JobId,X=r.Position.X,Y=r.Position.Y,Z=r.Position.Z};save()
    end
end
local function carModel(index)
    local arena=state and workspace.Game.Map:FindFirstChild("TrainRaid_"..state.Id)
    if not arena then return end
    for _,car in ipairs(arena:GetChildren())do if car:GetAttribute("TrainRaidCar")==index then return car end end
end
local function fingerprint()
    return state and tostring(state.Id)..":"..tostring(state.Car)..":"..tostring(state.Objective)..":"..tostring(state.Progress)
end
local function snapshot()
    local stats=player.Data.Stats
    return {Inventory=B.State.ReadInventory()or {},XP=player.Data.Experience.Value,Coins=stats:FindFirstChild("Coins")and stats.Coins.Value,Tokens=stats:FindFirstChild("RaidTokens")and stats.RaidTokens.Value}
end
A.Add({Id=id,Name="auto train raid",Group="quests",Description="Train objectives with continuous M1 and M2 whenever its native cooldown is ready. No combat skills or throwing. Retreat at 35% HP; resume at 85%. Saved per account.",Set=function(value)
    generation+=1;stopCombat();emergency=nil;exitRequested=false;exitAttempts=0;exitNext=0;config.PausedReason=nil;B.State.RaidEmergency=nil
    lastProgress=os.clock();lastFingerprint=nil;nextSync=0;promptAttempts={};objectiveRetries=0;B.State.RaidBlocked=nil
    if not value then
        minigames.Release();releaseCrouch()
        if held then pcall(held.InputHoldEnd,held);held=nil end
    end
    config.Enabled=value;save();nextAction=0
    if value then assert(B.State.EnsureResumeReady(),"raid teleport resume unavailable")
    elseif not player:GetAttribute("TrainRaidActive")then release();restore()end
end})
A.Features[id].Enabled=config.Enabled==true
B.State.RaidVersion=8
B.State.RaidReferenceCombat=referenceCombat
B.State.RaidStayInRaid=config.StayInRaid==true
B.State.RaidOwnerTest=config.OwnerTest==true
B.State.RaidReports={}
if config.PausedReason then emergency=config.PausedReason;B.State.RaidEmergency=emergency end
A.Connect(remote.OnClientEvent,function(action,data)
    if action=="State"and type(data)=="table"then
        if state and type(state.Lives)=="number"and type(data.Lives)=="number"and data.Lives<state.Lives then
            local c,r,h=A.Character()
            c=c or player.Character;r=r or(c and c:FindFirstChild("HumanoidRootPart"));h=h or(c and c:FindFirstChildOfClass("Humanoid"))
            config.LastLifeLoss={At=os.time(),Car=data.Car,Before=state.Lives,After=data.Lives,Health=h and h.Health,
                Position=r and {X=r.Position.X,Y=r.Position.Y,Z=r.Position.Z},Combat=B.State.RaidResult};save()
        end
        local before=P.StageKey(state);state=data;B.State.RaidState=data
        if before~=P.StageKey(state)then nextAction=0;promptAttempts={};objectiveRetries=0;stopCombat()end
    elseif action=="Board"and type(data)=="table"then board=data
    elseif action=="Depart"then departUntil=os.clock()+45;status("raid transferring")
    elseif action=="Suspect"and type(data)=="table"then
        B.State.RaidSuspect=data
        if data.NoAccuse and state then
            if not config.Evidence or config.Evidence.Raid~=state.Id then config.Evidence={Raid=state.Id,Clues={}}end
            config.Evidence.Clues[tostring(data.Title)]=tostring(data.Line);save()
            task.defer(function()
                if not A.Current()then return end
                local gui=player.PlayerGui:FindFirstChild("Dialogue")
                local module=gui and gui:FindFirstChild("DialogueHandler",true)
                if module then pcall(function()require(module):closeDialogue()end)end
            end)
        elseif state and typeof(data.Model)=="Instance" and data.Model:IsA("Model")
            and data.Model:GetAttribute("TrainRaidNPC")==state.Id
            and tostring(data.Model:GetAttribute("Config")):match("^TrainRaidHidden_")
            and data.Index==data.Model:GetAttribute("TrainRaidPassenger")and type(data.Token)=="string"then
            remote:FireServer("Accuse",{Index=data.Index,Token=data.Token})
            local gui=player.PlayerGui:FindFirstChild("Dialogue")
            local module=gui and gui:FindFirstChild("DialogueHandler",true)
            if module then task.defer(function()if A.Current()then pcall(function()require(module):closeDialogue()end)end end)end
        end
    elseif action=="Results"and type(data)=="table"then
        results=data;B.State.RaidResults=data;stopCombat();minigames.Release()
        config.PendingResult={Job=game.JobId,Result=data,ReceivedAt=os.time()};save()
    end
end)
local function observeHealth(h,value)
    local previous=lastHP;lastHP=value
    local now=os.clock()
    if previous and value<previous then damageWindow[#damageWindow+1]={At=now,Damage=previous-value};lastThreat=now end
    local burst=0
    for i=#damageWindow,1,-1 do
        if now-damageWindow[i].At>1.25 then table.remove(damageWindow,i)else burst+=damageWindow[i].Damage end
    end
    local reason=P.HealthRisk(value,h.MaxHealth,previous,burst,referenceCombat and .35 or .75,not referenceCombat)
    if reason then emergencyStop(reason..(config.StayInRaid and "; recovering in raid" or "; returning to arrow farm"));attemptExit()end
end
A.Connect(Run.Heartbeat,function()
    if emergency then
        if config.StayInRaid==true then
            local c,root,h=A.Character()
            if c and h.Health>=h.MaxHealth*(referenceCombat and .85 or .95)and os.clock()>=recoverAt then
                releaseGuard()
                if recoveryPlaced and recoveryCharacter==c and recoveryReturn then
                    root.AssemblyLinearVelocity=Vector3.zero;root.CFrame=recoveryReturn
                end
                recoveryReturn=nil;recoveryCharacter=nil;recoveryPlaced=false
                config.RecoveryReturn=nil
                emergency=nil;config.PausedReason=nil;B.State.RaidEmergency=nil
                lastHumanoid=nil;lastHP=nil;damageWindow={};lastFingerprint=nil;lastProgress=os.clock();nextSync=0;nextAction=0
                save();status("raid recovered / resuming objectives")
            else
                if c then
                    if not recoveryPlaced and state then
                        local arena=workspace.Game.Map:FindFirstChild("TrainRaid_"..state.Id)
                        local booth=arena and arena:FindFirstChild("SpectatorBooth")
                        local floor=booth and booth:FindFirstChild("Floor")
                        if floor and floor:IsA("BasePart")and floor.CanCollide then
                            recoveryReturn=safePose and safePose.Job==game.JobId and safePose.CFrame or root.CFrame
                            recoveryCharacter=c;recoveryPlaced=true
                            local rp=recoveryReturn.Position
                            config.RecoveryReturn={Job=game.JobId,X=rp.X,Y=rp.Y,Z=rp.Z};save()
                            root.AssemblyLinearVelocity=Vector3.zero;root.AssemblyAngularVelocity=Vector3.zero
                            root.CFrame=CFrame.new(floor.Position+Vector3.new(0,floor.Size.Y/2+h.HipHeight+root.Size.Y/2+.2,0))
                        end
                    end
                    local closest,distance
                    for _,m in ipairs(workspace.Game.Players:GetChildren())do
                        local mr=m:FindFirstChild("HumanoidRootPart");local mh=m:FindFirstChildOfClass("Humanoid")
                        if mr and state and P.Enemy(m:GetAttributes(),state.Id,Players:GetPlayerFromCharacter(m)~=nil,mh and mh.Health)then
                            local d=(mr.Position-root.Position).Magnitude
                            if not distance or d<distance then closest=mr;distance=d end
                        end
                    end
                    if closest then
                        local facing=Vector3.new(closest.Position.X,root.Position.Y,closest.Position.Z)
                        if (facing-root.Position).Magnitude>.1 then root.CFrame=CFrame.lookAt(root.Position,facing)end
                        local n=A.Native();local ns=n and n:getStates()
                        if ns and not ns.Blocking and not ns.BlockCooldown and not ns.Stunned and not ns.Swinging then
                            guardNative=n;guardCharacter=c;ns.HoldingBlock=true;pcall(n.blockStart,n)
                        end
                    end
                end
                status("raid recovering / guarding until health or respawn")
            end
        else attemptExit()end
        return
    end
    if not acquired or not A.Get(id)then return end
    local c,r,h=A.Character()
    if not c then emergencyStop("character lost; manual review required");return end
    if h~=lastHumanoid then
        if healthConnection then healthConnection:Disconnect()end
        lastHumanoid=h;lastHP=h.Health;damageWindow={}
        healthConnection=A.Connect(h.HealthChanged,function(value)
            if h~=lastHumanoid or not acquired or not A.Get(id)then return end
            observeHealth(h,value)
        end)
        if safePose and safePose.Character~=c then safePose=nil end
    else observeHealth(h,h.Health)end
end)
A.Cleanups[#A.Cleanups+1]=function()generation+=1;release()end
local function throwNearby(model,n,c)
    local api,utility
    for _,value in pairs(debug.getupvalues(n.useHeldThrowable))do
        if type(value)=="table"then
            if type(value.sendCombat)=="function"then api=value end
            if type(value.getHeldCharacterThrowable)=="function"then utility=value end
        end
    end
    if not api or not utility then return false end
    local heldItem=utility:getHeldCharacterThrowable(c)or utility:getHeldStandThrowable(c)
    if heldItem~=throwHeldItem then
        throwHeldItem=heldItem;throwHeldAt=os.clock();throwDropSent=false
    end
    if heldItem and os.clock()-throwHeldAt>8 then
        if not throwDropSent then
            api.sendCombat("DropItem");throwDropSent=true
            B.State.RaidThrowStatus="throw timed out / releasing item"
        elseif os.clock()-throwHeldAt>12 then emergencyStop("throwable release not confirmed")end
        return true
    end
    if os.clock()<throwNext then return heldItem~=nil end
    local ns=n:getStates()
    if not heldItem and throwPending then
        if os.clock()<throwUntil then status("raid waiting for throwable pickup");return true end
        throwPending=nil;throwNext=os.clock()+12
        B.State.RaidThrowStatus="pickup not confirmed";return false
    end
    if ns.Stunned or ns.Swinging or ns.HeavySwinging or ns.SwingCooldown or player.Data.SkillActive.Value then return heldItem~=nil end
    if not heldItem then
        local highlight=c:FindFirstChild("ThrowableHighlight")
        local item=highlight and not highlight:GetAttribute("Fading")and highlight.Adornee
        if not item or not item.Parent or not item:IsDescendantOf(workspace.Game.Map) then return false end
        if not utility:canStartAction(c,"GrabItem",item)then return false end
        lock.Release();stopStrike();releaseGuard()
        throwPending=item;throwUntil=os.clock()+3
        api.sendCombat("GrabItem",item)
        B.State.RaidThrowStatus="pickup requested";return true
    end
    lock.Release();stopStrike();releaseGuard()
    local root=c:FindFirstChild("HumanoidRootPart")
    local enemyRoot=model:FindFirstChild("HumanoidRootPart")
    if not root or not enemyRoot then return false end
    local function clearDistance(point)
        for _,enemy in ipairs(workspace.Game.Players:GetChildren())do
            local er=enemy:FindFirstChild("HumanoidRootPart")
            local eh=enemy:FindFirstChildOfClass("Humanoid")
            if er and P.Enemy(enemy:GetAttributes(),state.Id,Players:GetPlayerFromCharacter(enemy)~=nil,eh and eh.Health)
                and (er.Position-point).Magnitude<22 then return false end
        end
        return true
    end
    if not clearDistance(root.Position)then
        local car=carModel(state.Car)
        local center=car and car:GetPivot().Position
        if center then
            for _,direction in ipairs({-1,1})do
                local point=Vector3.new(enemyRoot.Position.X+direction*30,root.Position.Y,center.Z)
                if math.abs(point.X-center.X)<65 and clearDistance(point)and move(point)then break end
            end
        end
        if not clearDistance(root.Position)then
            B.State.RaidThrowStatus="waiting for throwing distance";nextAction=os.clock()+.3;return true
        end
    end
    local ray=RaycastParams.new();ray.FilterType=Enum.RaycastFilterType.Include
    ray.FilterDescendantsInstances={workspace.Game.Map};ray.RespectCanCollide=true
    if workspace:Raycast(root.Position,enemyRoot.Position-root.Position,ray)then
        B.State.RaidThrowStatus="throw path obstructed";nextAction=os.clock()+.5;return true
    end
    local before=model.Humanoid.Health
    root.CFrame=CFrame.lookAt(root.Position,Vector3.new(enemyRoot.Position.X,root.Position.Y,enemyRoot.Position.Z))
    api.sendCombat("UseItem",heldItem:GetAttribute("ThrowableType")=="ParkingSign"and "Light"or "Heavy",CFrame.new(enemyRoot.Position),ns.Shiftlocked,{})
    B.State.RaidThrowLast={Target=model.Name,Before=before,Distance=(root.Position-enemyRoot.Position).Magnitude,At=os.clock()}
    B.State.RaidThrowStatus="throw dispatched"
    throwPending=nil;throwNext=os.clock()+3;nextAction=os.clock()+2
    return true
end
local function breakRoof(token,c)
    local nextCar=carModel(state.Car+1)
    local effects=workspace.Game:FindFirstChild("Effects")
    local weak
    if nextCar and effects then
        local center=nextCar:GetPivot().Position
        for _,panel in ipairs(effects:GetChildren())do
            local point=panel.Name=="CrackedPanel"and panel:FindFirstChild("WeakPoint")
            local outline=panel:FindFirstChild("BreakTarget")
            if point and point:IsA("BasePart")and outline and outline.Adornee==point
                and math.abs(point.Position.X-center.X)<70 and math.abs(point.Position.Z-center.Z)<20
                and point.Position.Y>state.Origin.Y and point.Position.Y<state.Origin.Y+40 then weak=point;break end
        end
    end
    if not weak then status("raid waiting for marked roof panel");return end
    if not roofLock or roofLock.Point~=weak then
        stopCombat()
        local root=c:FindFirstChild("HumanoidRootPart")
        local h=c:FindFirstChildOfClass("Humanoid")
        if not root or not h then return end
        local stage=P.StageKey(state)
        local record={Point=weak,Humanoid=h,AutoRotate=h.AutoRotate}
        roofLock=record;h.AutoRotate=false
        record.Connection=Run.PreSimulation:Connect(function()
            if not valid(token,c)or P.StageKey(state)~=stage or not weak.Parent or h.Health<=0 then releaseRoof();return end
            root.CFrame=CFrame.lookAt(weak.Position+Vector3.new(0,3,0),weak.Position,Vector3.xAxis)
            root.AssemblyLinearVelocity=Vector3.zero;root.AssemblyAngularVelocity=Vector3.zero
        end)
        B.State.RaidRoofLocked=true
    end
    local n=A.Native();local ns=n and n:getStates()
    if not ns or ns.Stunned or ns.SwingCooldown or ns.HeavyCD or ns.Swinging or ns.HeavySwinging or player.Data.SkillActive.Value then return end
    if attack and coroutine.status(attack)~="dead"then return end
    attackNative=n;attackCharacter=c
    attack=task.spawn(function()
        if valid(token,c)and roofLock and roofLock.Point==weak then
            local ok,err=pcall(n.heavySwing,n)
            if not ok and valid(token,c)then emergencyStop("roof attack failed: "..tostring(err):sub(1,80))end
        end
    end)
    B.State.RaidRoofStrikes=(B.State.RaidRoofStrikes or 0)+1
    nextAction=os.clock()+.8;status("raid breaking marked roof / "..tostring(state.Progress))
end
local function fight(model,token,c)
    local n=A.Native();if not n then return end
    releaseCrouch()
    if target~=model then
        stopCombat();target=model
        if referenceCombat then lastThreat=os.clock()-.35;nextStrike=0 end
        B.State.RaidCurrentTarget=model.Name
        if B.State.RaidTargetEndedAt then
            B.State.RaidLastTargetSwitch={From=B.State.RaidEndedTarget,To=model.Name,Delay=os.clock()-B.State.RaidTargetEndedAt}
            B.State.RaidTargetEndedAt=nil
        end
        targetHealthConnection=model.Humanoid.HealthChanged:Connect(function(health)
            if health<=0 and target==model then
                B.State.RaidEndedTarget=model.Name;B.State.RaidTargetEndedAt=os.clock()
                stopCombat();nextAction=0;nextStrike=0;lastThreat=os.clock()-.35
            end
        end)
    end
    local function current()
        return valid(token,c)and state and state.Active and target==model and model.Parent~=nil
            and model:FindFirstChildOfClass("Humanoid")~=nil and model.Humanoid.Health>0
    end
    local s=n:getStates()
    if player.Data.Stand.Value~=""and not s.Summoned then n:summonStand(true);nextAction=os.clock()+.7;return end
    if config.CombatMode~="m1" and config.CombatMode~="m1m2" and referenceCombat and throwNearby(model,n,c)then return end
    if not lock.Begin(model,n,current)then emergencyStop("native M1 reach not confirmed");return end
    local danger=false
    local _,root=A.Character()
    for _,enemy in ipairs(workspace.Game.Players:GetChildren())do
        local eh=enemy:FindFirstChildOfClass("Humanoid");local er=enemy:FindFirstChild("HumanoidRootPart")
        if er and root and (er.Position-root.Position).Magnitude<18 and P.Enemy(enemy:GetAttributes(),state.Id,Players:GetPlayerFromCharacter(enemy)~=nil,eh and eh.Health)then
            local actionTrack=false
            local function playing(animator)
                if not animator then return end
                for _,track in ipairs(animator:GetPlayingAnimationTracks())do
                    if track.IsPlaying and track.Priority.Value>=Enum.AnimationPriority.Action.Value and track.WeightCurrent>.05 then actionTrack=true;break end
                end
            end
            playing(eh:FindFirstChildOfClass("Animator"))
            for _,stand in ipairs(workspace.Game.Stands:GetChildren())do
                if stand.Name==enemy.Name then playing(stand:FindFirstChildWhichIsA("Animator",true))end
            end
            if P.Attacking(enemy:GetAttributes(),actionTrack)then danger=true;break end
        end
    end
    if danger and not referenceCombat then
        lastThreat=os.clock();stopStrike()
        if not s.Stunned and not s.Swinging and not s.Blocking and not s.BlockCooldown then
            guardNative=n;guardCharacter=c;s.HoldingBlock=true;n:blockStart()
        end
        B.State.RaidCombatMode="guard";status("raid / waiting through enemy attack");return
    end
    if os.clock()-lastThreat<.35 then return end
    releaseGuard()
    if not P.CounterReady(os.clock(),lastThreat,nextStrike,s)then return end
    if attack and coroutine.status(attack)~="dead"then return end
    if s.Stunned or s.SwingCooldown or s.Swinging or player.Data.SkillActive.Value then return end
    local comboAction=P.ComboAction(comboLights,model:GetAttribute("Blocking")==true,not s.HeavyCD,config.CombatMode)
    if comboAction=="wait"then B.State.RaidCombatMode="heavy cooldown";return end
    if referenceCombat and comboAction=="skill" and A.UseSkill and A.UseSkill(n,"raid",{Barrage=true,["Hole Puncher"]=true,["Head Slam"]=true,["Ora Smash"]=true})then
        comboLights=0
        B.State.RaidCombatMode="combo skill";nextStrike=os.clock();return
    end
    attackNative=n;attackCharacter=c;nextStrike=os.clock()+(referenceCombat and .05 or .65)
    B.State.RaidCombatMode=config.CombatMode=="m1m2" and "m1 + m2" or(config.CombatMode=="m1" and "m1 only" or(config.CombatMode=="heavy"and "heavy"or(referenceCombat and "combo"or "counter")))
    B.State.RaidCounterAttempts=(B.State.RaidCounterAttempts or 0)+1
    local swing=referenceCombat and comboAction=="heavy" and type(n.heavySwing)=="function"and n.heavySwing or n.lightSwing
    if swing==n.lightSwing then comboLights=math.min(3,comboLights+1)else comboLights=0 end
    B.State.RaidComboLights=comboLights
    B.State.RaidAttackKind=swing==n.lightSwing and "M1"or "heavy"
    attack=task.spawn(function()
        if current()and B.State.RaidLockActive then
            local ok,err=pcall(swing,n)
            if not ok and current()then emergencyStop("native attack failed: "..tostring(err):sub(1,80))end
        end
    end)
end
local observedTarget,observedHP
A.Loop("auto raid",.05,function()
    local active=player:GetAttribute("TrainRaidActive")==true
    if not active and config.PendingResult then
        local after=snapshot()
        local before=config.Before
        local report={Job=config.PendingResult.Job,Result=config.PendingResult.Result,Before=before,After=after,
            InventoryGain=before and P.Delta(before.Inventory,after.Inventory)or {},VerifiedAt=os.time()}
        table.insert(B.State.RaidReports,report);config.LastReport=report
        config.PendingResult=nil;config.Before=nil;save();release()
        A.Set(id,false);restore()
        status("raid completed / previous item farming restored")
        return
    end
    if not active and config.ReturnToArrows then
        release()
        if config.Previous then restore()else B.State.SetAuto("arrow",true)end
        config.ReturnToArrows=nil;config.Before=nil
        B.State.RaidHandoffConfirmed=true
        local _,_,returnedHumanoid=A.Character()
        config.LastHandoff={Job=game.JobId,At=os.time(),Health=returnedHumanoid and returnedHumanoid.Health,Arrow=B.State.AutoArrow==true}
        save();status("raid stopped / arrow farm resumed")
    end
    if not A.Get(id)then return end
    if active and not acquired then acquire()end
    if emergency then status("raid paused: "..emergency);return end
    local c,r,h=A.Character();if not c then return end
    local token=generation
    if target and (not target.Parent or not target:FindFirstChildOfClass("Humanoid") or target.Humanoid.Health<=0) then
        B.State.RaidEndedTarget=target.Name;B.State.RaidTargetEndedAt=os.clock()
        stopCombat();nextAction=0;nextStrike=0;lastThreat=os.clock()-.35
    end
    if os.clock()>=nextSync then remote:FireServer("State");nextSync=os.clock()+10 end
    if os.clock()<nextAction then return end
    if active then
        if config.ExitPreflight then
            config.ExitPreflight=nil;save()
            B.State.ReturnFromRaid();return
        end
        if not state or not state.Active then status("waiting for raid state");return end
        if state.Raid~="Train"then emergencyStop("unsupported raid");return end
        if not config.Before then config.Before=snapshot();save()end
        if P.HealthRisk(h.Health,h.MaxHealth,nil,nil,referenceCombat and .35 or .75,not referenceCombat)then emergencyStop("health reserve reached; recovery required");return end
        local fp=fingerprint()
        if fp~=lastFingerprint then lastFingerprint=fp;lastProgress=os.clock()end
        if os.clock()-lastProgress>90 then
            if objectiveRetries>=2 then
                A.Set(id,false);B.State.RaidBlocked="objective made no confirmed progress after three interaction cycles"
                status("raid paused / "..B.State.RaidBlocked);return
            end
            objectiveRetries+=1;promptAttempts={};lastProgress=os.clock();nextSync=0
            B.State.RaidObjectiveRetries=objectiveRetries
        end
        status("raid "..tostring(state.Car).."/"..tostring(state.Cars).." / "..tostring(state.Objective))
        if results then return end
        if state.Objective=="Break through the roof"then breakRoof(token,c);return end
        local stageCar=carModel(state.Car)
        if stageCar and stageCar:GetAttribute("TrainRaidKind")=="Hooked"then
            stopCombat()
            local n=A.Native();local ns=n and n:getStates()
            if ns and ns.Summoned then n:summonStand(false);nextAction=os.clock()+.5;return end
            if ns and not ns.Crouching then
                if ns.Running and type(n.runStop)=="function"then n:runStop()end
                crouchNative=n;crouchCharacter=c;n:crouch();nextAction=os.clock()+.5;return
            end
        else releaseCrouch()end
        local mist=tostring(state.Objective):lower():find("survive the mist",1,true)
        if mist then
            stopCombat();releaseCrouch()
            local roomName=c:GetAttribute("PresidentRoom") or player:GetAttribute("PresidentRoom")
            local room=roomName and workspace.Game.Map:FindFirstChild(roomName)
            local inRoom=room and room:GetAttribute("TrainRaidCocoRoom")==state.Id
            local ice=c:FindFirstChild("IcePack")
            local passengerPrompt
            for _,passenger in ipairs(workspace.Game.Players:GetChildren()) do
                if passenger:GetAttribute("TrainRaidAmbient")==state.Id then
                    local prompt=passenger:FindFirstChild("GiveIce",true)
                    if prompt and prompt.Enabled then passengerPrompt=prompt;break end
                end
            end
            local action=P.MistAction(state.Objective,inRoom,ice~=nil,ice and ice:GetAttribute("SpareIce"),passengerPrompt~=nil)
            local prompt
            if action=="refill" then prompt=room:FindFirstChild("Take ice",true)
            elseif action=="leave" then
                local door=room:FindFirstChild("Teleport")
                prompt=door and door:FindFirstChild("Leave")
            elseif action=="enter" then
                local arena=workspace.Game.Map:FindFirstChild("TrainRaid_"..state.Id)
                if arena then for _,v in ipairs(arena:GetDescendants()) do
                    if v:IsA("ProximityPrompt") and v.Enabled and v.ObjectText=="Coco Jumbo" and v.ActionText:lower():match("^enter") then prompt=v;break end
                end end
            elseif action=="give" then prompt=passengerPrompt end
            if prompt and prompt.Parent and prompt.Enabled then
                if not move(promptPoint(prompt),prompt.MaxActivationDistance) then return end
                task.wait(.25)
                if not valid(token,c) or not prompt.Parent or not prompt.Enabled then return end
                if (r.Position-promptPoint(prompt)).Magnitude>prompt.MaxActivationDistance then return end
                assert(prompt.HoldDuration<=5,"unexpected mist prompt duration")
                held=prompt;prompt:InputHoldBegin()
                local finish=os.clock()+prompt.HoldDuration+.1
                repeat task.wait(.05) until os.clock()>=finish or not valid(token,c) or not prompt.Parent
                pcall(prompt.InputHoldEnd,prompt);held=nil
                nextAction=os.clock()+.6;nextSync=0;lastProgress=os.clock()
                status("raid mist / "..action);return
            end
            if action=="wait" and stageCar then
                local pivot=stageCar:GetPivot().Position
                if math.abs(r.Position.X-pivot.X)>45 or math.abs(r.Position.Y-pivot.Y)>20 then move(pivot+Vector3.new(0,1,0)) end
                status("raid mist / ice ready, waiting in active carriage")
            else status("raid mist / waiting for "..tostring(action).." prompt") end
            nextAction=os.clock()+.5;return
        end
        local handled,message,failed=minigames.Step()
        if minigames.Revision~=miniRevision then
            miniRevision=minigames.Revision;promptAttempts={};lastProgress=os.clock()
        end
        if handled then
            stopCombat();status("raid / "..message)
            if failed then emergencyStop(message)else lastProgress=os.clock()end
            return
        end
        local car=carModel(state.Car);if not car then status("waiting for raid carriage");return end
        local roomName=c:GetAttribute("PresidentRoom")or player:GetAttribute("PresidentRoom")
        if type(roomName)=="string"then
            local room=workspace.Game.Map:FindFirstChild(roomName)
            if room and room:GetAttribute("TrainRaidCocoRoom")==state.Id then
                if state.Objective=="Enter Coco Jumbo"then status("raid waiting for coco room objective");nextSync=0;return
                elseif state.Objective=="Take ice from the fridge"then car=room
                else
                    for _,prompt in ipairs(room:GetDescendants())do
                        if prompt:IsA("ProximityPrompt")and prompt.Enabled and prompt.ActionText=="Leave"and prompt.Parent:IsA("BasePart")then
                            if move(prompt.Parent.Position,prompt.MaxActivationDistance)then
                                task.wait(.7)
                                if valid(token,c)and prompt.Parent then fireproximityprompt(prompt)end
                            end
                            status("raid leaving coco room");nextAction=os.clock()+2;return
                        end
                    end
                    status("raid waiting for coco exit");return
                end
            end
        end
        if P.CombatObjective(state.Objective)then
            local pivot=car:GetPivot().Position
            if P.NeedsCombatReturn(r.Position.X-pivot.X,r.Position.Y-pivot.Y)then
                stopCombat()
                if B.State.RequestStream then B.State.RequestStream(pivot,2)end
                if not valid(token,c)then return end
                if move(pivot+Vector3.new(0,1,0))then rememberSafe();nextAction=os.clock()+1 end
                status("raid returning to active combat carriage");return
            end
        end
        if not safePose then rememberSafe()end
        if state.Objective=="Break down the exit door"then
            releaseCrouch()
            if target then stopCombat()end
            if attack and coroutine.status(attack)~="dead"then return end
            local door
            local center=car:GetPivot().Position
            for _,model in ipairs(car:GetDescendants())do
                if model:IsA("Model")and P.ExitDoor(model:GetAttributes(),model:GetPivot().Position.X,center.X)then door=model;break end
            end
            if not door then status("raid waiting for exit door geometry");return end
            local n=A.Native();local ns=n and n:getStates()
            if not ns or ns.Stunned or ns.SwingCooldown or ns.HeavyCD or ns.Swinging or ns.HeavySwinging or player.Data.SkillActive.Value then return end
            local point=door:GetPivot().Position
            if not move(point-Vector3.new(5,0,0))then return end
            r.CFrame=CFrame.lookAt(r.Position,Vector3.new(point.X,r.Position.Y,point.Z))
            if player.Data.Stand.Value~=""and not ns.Summoned then n:summonStand(true);nextAction=os.clock()+.7;return end
            attackNative=n;attackCharacter=c
            local stage=P.StageKey(state)
            attack=task.spawn(function()
                if valid(token,c)and P.StageKey(state)==stage and door.Parent then
                    local ok,err=pcall(n.heavySwing,n)
                    if not ok and valid(token,c)then emergencyStop("exit door attack failed: "..tostring(err):sub(1,80))end
                end
            end)
            B.State.RaidDoorStrikes=(B.State.RaidDoorStrikes or 0)+1
            nextAction=os.clock()+.8;status("raid breaking exit door / "..tostring(state.Progress));return
        end
        if state.Objective=="Question the passengers"then
            local gui=player.PlayerGui:FindFirstChild("Dialogue")
            local module=gui and gui:FindFirstChild("DialogueHandler",true)
            if gui and gui.Enabled and module then pcall(function()require(module):closeDialogue()end);nextAction=os.clock()+.5;return end
            for _,model in ipairs(workspace.Game.Players:GetChildren())do
                if model:GetAttribute("TrainRaidNPC")==state.Id and model:GetAttribute("TrainRaidDormant")
                    and tostring(model:GetAttribute("Config")):match("^TrainRaidHidden_")then
                    local prompt=model:FindFirstChildWhichIsA("ProximityPrompt",true)
                    if prompt and prompt.Enabled and prompt.Parent:IsA("BasePart")and move(prompt.Parent.Position,prompt.MaxActivationDistance)then
                        task.wait(.7)
                        if valid(token,c)and prompt.Parent and prompt.Enabled then fireproximityprompt(prompt)end
                        nextAction=os.clock()+3;return
                    end
                end
            end
            status("raid waiting for identified passenger");return
        end
        if tostring(state.Objective):lower():find("enter the next car",1,true)then
            rememberSafe()
            local floor=car:FindFirstChild("HullFloor",true)
            local pivot=car:GetPivot().Position
            if not floor and B.State.RequestStream then
                B.State.RequestStream(pivot,2)
                if not valid(token,c)then return end
                floor=car:FindFirstChild("HullFloor",true)
            end
            local y=floor and floor.Position.Y+floor.Size.Y/2+1 or pivot.Y+1
            if move(Vector3.new(pivot.X,y,pivot.Z))then nextAction=os.clock()+1 end
            return
        end
        local nearest,distance
        for _,model in ipairs(workspace.Game.Players:GetChildren())do
            local mh=model:FindFirstChildOfClass("Humanoid");local mr=model:FindFirstChild("HumanoidRootPart")
            if mr and P.CombatObjective(state.Objective)and P.Enemy(model:GetAttributes(),state.Id,Players:GetPlayerFromCharacter(model)~=nil,mh and mh.Health)then
                local d=(mr.Position-r.Position).Magnitude
                if P.Prefer(model,target,nearest,d,distance)then nearest=model;distance=d end
            end
        end
        if nearest then
            local hp=nearest:FindFirstChildOfClass("Humanoid").Health
            if observedTarget==nearest and observedHP and hp<observedHP then lastProgress=os.clock()end
            observedTarget=nearest;observedHP=hp
            fight(nearest,token,c);return
        end
        stopCombat()
        local interactions=car:GetDescendants()
        if tostring(state.Objective):find("Survive the mist",1,true)then
            for _,passenger in ipairs(workspace.Game.Players:GetChildren())do
                if passenger:GetAttribute("TrainRaidAmbient")==state.Id then
                    local prompt=passenger:FindFirstChild("GiveIce",true)
                    if prompt then interactions[#interactions+1]=prompt end
                end
            end
        end
        for _,prompt in ipairs(interactions)do
            if prompt:IsA("ProximityPrompt")and prompt.Enabled and promptPoint(prompt)
                and P.Prompt(prompt.ActionText,prompt.ObjectText,state.Objective,prompt.Name)and(promptAttempts[promptKey(prompt)]or 0)<5
                and not (prompt.ActionText=="Investigate"and config.Evidence and config.Evidence.Raid==state.Id and config.Evidence.Clues[prompt.ObjectText])then
                if not move(promptPoint(prompt),prompt.MaxActivationDistance)then return end
                task.wait(.7)
                if not valid(token,c)or not prompt.Parent or not prompt.Enabled then return end
                if not promptPoint(prompt)or(r.Position-promptPoint(prompt)).Magnitude>prompt.MaxActivationDistance then return end
                if prompt.HoldDuration>10 then emergencyStop("interaction hold exceeds ten seconds");return end
                held=prompt;prompt:InputHoldBegin()
                local finish=os.clock()+prompt.HoldDuration+.1
                repeat task.wait(.05)until os.clock()>=finish or not valid(token,c)or not prompt.Parent
                if valid(token,c)and prompt.Parent and prompt.Enabled then
                    local key=promptKey(prompt);promptAttempts[key]=(promptAttempts[key]or 0)+1;fireproximityprompt(prompt)
                end
                pcall(prompt.InputHoldEnd,prompt);held=nil;nextAction=os.clock()+2;return
            end
        end
        status("raid waiting for objective interaction / "..tostring(state.Objective));nextAction=os.clock()+1
        return
    end
    if os.clock()<departUntil then return end
    if results then results=nil;state=nil;config.Before=nil;save()end
    local cooldown=0
    local ok,data=pcall(function()return Http:JSONDecode(player.Data.Stats.TrainRaidCooldowns.Value)end)
    if not ok or type(data)~="table"then status("waiting for raid cooldown data");return end
    if board and board.Members then for _,m in ipairs(board.Members)do if m.UserId==player.UserId then cooldown=m.Cooldowns and m.Cooldowns.Train and m.Cooldowns.Train.Regular or 0 end end end
    if not board or os.clock()>=nextBoard then nativeRaid.RequestBoard();nextAction=os.clock()+1;nextBoard=os.clock()+10;board=nativeRaid.GetBoardData();return end
    local mode=P.Mode(false,true,cooldown,player.Data.Stats.Level.Value,h.Health,h.MaxHealth)
    if mode=="arrows"then
        release();B.State.SetAuto("arrow",true);status("raid cooldown / arrow farm");nextAction=os.clock()+3;return
    end
    if mode~="enter"then release();status("raid / "..mode);nextAction=os.clock()+3;return end
    if not acquire()then return end
    local npc=workspace.Game.NPCs:FindFirstChild("Donatello");local root=npc and npc:FindFirstChild("HumanoidRootPart")
    if not root then
        local tracking=require(player.PlayerScripts.Core.NpcTracking)
        local point=tracking.Position("Donatello")
        if typeof(point)=="Vector3"and B.State.RequestStream then B.State.RequestStream(point,3)end
        if not valid(token,c)then return end
        status("streaming donatello for train entry");nextAction=os.clock()+3;return
    end
    if not move((root.CFrame*CFrame.new(0,0,-5)).Position)then return end
    if not B.State.EnsureResumeReady()then emergencyStop("teleport resume unavailable");return end
    config.Before=snapshot();save();nativeRaid.Open(false,"Train");task.wait(.4)
    if not valid(token,c)then return end
    remote:FireServer("Start",{Raid="Train",Difficulty="Regular"});departUntil=os.clock()+45
    status("starting regular train raid");nextAction=os.clock()+3
end)

    end)(advanced, bridge);
    (function(A, B)
local resultAt,recoveryAt,nextExit=0,0,0
B.State.RaidAutopilotVersion=1
A.Loop("raid autopilot",2,function()
    local s=B.State
    if s.TransferPending or not A.Get("AutoRaid") then resultAt=0;recoveryAt=0;nextExit=0;return end
    if B.Player:GetAttribute("TrainRaidActive")~=true then
        resultAt=0;recoveryAt=0;nextExit=0
        return
    end
    local now=os.clock()
    if s.RaidResults then if resultAt==0 then resultAt=now end else resultAt=0 end
    if s.RaidEmergency then if recoveryAt==0 then recoveryAt=now end else recoveryAt=0 end
    local reason=s.RaidBlocked and "objective stalled"
        or(resultAt>0 and now-resultAt>=30 and "results received; returning to farm")
        or(recoveryAt>0 and now-recoveryAt>=180 and "recovery timeout; returning to farm")
    if not reason or now<nextExit then return end
    nextExit=now+60
    s.RaidAutopilotStatus=reason
    s.ReturnFromRaid()
end)

    end)(advanced, bridge);
    (function(A, B)
local pending={
    AutoQuest="quest acceptance and completion not verified",
    QuestFarm="quest progression and completion not verified",
    BountyFarm="field rewards unverified; incident minigames incomplete",
    QuestTravel="tracked objective travel and interaction not verified",
    AutoRoll="consumption and resulting stand not verified",
    ItemFarm="general non-arrow collection not verified",
    AutoParry="hostile attack timing not verified",
    AutoBlock="hostile attack timing not verified",
    AutoDash="hostile heavy attack response not verified",
    AttachStand="target attachment combat not verified",
    PilotRange="extended server distance not verified",
    NoDashCooldown="server cooldown bypass not verified",
    DashExtender="live dash distance not verified",
    NoStun="server stun recovery not verified",
    NoRagdoll="server ragdoll recovery not verified",
    InstantPrompts="generic prompt acceptance not verified",
    ESPWidget="replaced by the dedicated arrow inventory window",
}
local get,set,option=A.Get,A.Set,A.Option
if B.State.RaidOwnerTest then pending.AutoRaid=nil end
A.ReviewPending=pending
for id,reason in pairs(pending) do
    local feature=assert(A.Features[id],"review feature missing: "..id)
    if get(id) then set(id,false) end
    feature.Hidden=true;feature.HeldForReview=true;feature.ReviewReason=reason
end
A.Features.IgnoreFriends.Hidden=true
function A.IsFeatureAvailable(id)
    local f=A.Features[id]
    return f~=nil and not f.HeldForReview
end
function A.Get(id)
    if not A.IsFeatureAvailable(id) then return false end
    return get(id)
end
function A.Set(id,enabled)
    if enabled and not A.IsFeatureAvailable(id) then return false,"feature withheld from review build" end
    return set(id,enabled)
end
function A.Option(id,key,value)
    if not A.IsFeatureAvailable(id) then return false,"feature withheld from review build" end
    return option(id,key,value)
end
-- Skill controls are owner-requested; successful requests still require live damage verification.
B.State.ReviewMenuVersion=1

    end)(advanced, bridge);
    (function(A, B)
local S=B.State
S.FarmWorkflowVersion=6
local ids={"WaitForArrow","ArrowFarm","ArrowPartFarm","Rokaka","AutoCraftBizarre","FreeArrowMaterials","StoneMaskFarm","GardenHarvest"}
local selection={Arrow=true,["Lucky Arrow"]=true,["Rokaka / seeds"]=false,["Opal Roka"]=true,["Stone Mask"]=true,["Arrow Part"]=true}
local selectionFile=B.Player and "sharkwow-items-"..B.Player.UserId..".json"
if selectionFile and type(readfile)=="function" then
    local ok,data=pcall(function()return game.HttpService:JSONDecode(readfile(selectionFile))end)
    if ok and type(data)=="table" and data.UserId==B.Player.UserId and type(data.Selected)=="table" then
        for key in pairs(selection)do selection[key]=(key=="Opal Roka" and data.Schema~=2) or data.Selected[key]==true end
    end
end
S.ItemFarmSelection=selection
function S.ShouldCollectRokaka(name)
    if name=="Opal Roka" or name=="Opal Roka Seed" then return selection["Opal Roka"]==true end
    return selection["Rokaka / seeds"]==true
end
local function wanted(id,enabled)
    if not enabled then return false end
    if id=="ArrowFarm" then return selection.Arrow or selection["Lucky Arrow"] end
    if id=="Rokaka" or id=="GardenHarvest" then return selection["Rokaka / seeds"] or selection["Opal Roka"] end
    if id=="StoneMaskFarm" then return selection["Stone Mask"] end
    if id=="ArrowPartFarm" then return selection["Arrow Part"] end
    return true
end
local running=S.AutoArrow or S.AutoParts or S.AutoRokaka or A.Get("AutoCraftBizarre") or A.Get("FreeArrowMaterials") or false
if S.IsArrowSkipped and not S.ItemFilterInstalled then
    local original=S.IsArrowSkipped
    S.IsArrowSkipped=function(instance)
        local child=instance:FindFirstChildWhichIsA("Model")
        local name=tostring(instance:GetAttribute("ItemName")or(child and child.Name)or instance.Name):lower()
        if not selection[name:find("lucky",1,true)and "Lucky Arrow"or "Arrow"] then return true end
        return original(instance)
    end
    S.ItemFilterInstalled=true
end
local craft=A.Features.AutoCraftBizarre
local previous=craft.Set
craft.Name="auto craft arrows"
craft.Description="Crafts Bizarre Arrows when below capacity, otherwise stockpiles Mysterious Arrows from parts. Enables material collection automatically. Position is managed automatically."
craft.Set=function(enabled)
    local old=A.Options.AutoCraftBizarre.ResumeEnabled==true
    previous(enabled)
    if A.Get("FreeArrowMaterials")~=enabled then
        local ok,err=A.Set("FreeArrowMaterials",enabled)
        if not ok then
            previous(old)
            error(err)
        end
    end
end
A.Add({Id="FarmAndCraft",Name="start all farming + crafting",Group="farm",
    Description="One switch for quiet ground waiting, item pickup, materials, arrow crafting, masks and gardening. Items retain priority. Turning off stops these activities. Server transfer settings are separate.",
    Get=function()
        return running
    end,
    Set=function(enabled)
        if not enabled then
            S.MaterialResumeRequested=false;S.PhonePrerequisiteWaiting=false
            if A.Features.AutoPhone and A.Get('AutoPhone') then
                local ok,err=A.Set('AutoPhone',false);assert(ok,err)
            end
        end
        if not enabled and A.Options.AutoCraftBizarre.ResumeWhenConfirmed then
            local ok,err=A.Set("AutoCraftBizarre",false)
            assert(ok,err)
        end
        local original={}
        for _,id in ipairs(ids) do original[id]=A.Get(id) end
        local errors={}
        S.FarmCraftHold=nil
        local phoneFirst=false
        if enabled and A.Features.AutoPhone and S.ReadInventory then
            local inventory=S.ReadInventory()
            S.PhonePrerequisiteWaiting=inventory==nil
            phoneFirst=not inventory or (inventory.Phone or 0)<1
            if inventory and phoneFirst and not A.Get('AutoPhone') then
                local ok,err=A.Set('AutoPhone',true);assert(ok,err)
            end
        end
        if enabled then
            A.Option("ArrowPartFarm","MeteorLoot",false)
            local ok,err=A.Set("MoneyTransportFarm",false)
            assert(ok,err)
        end
        for _,id in ipairs(ids) do
            local was=A.Get(id)
            local desired=wanted(id,enabled and not phoneFirst)
            if was~=desired then
                local ok,err=A.Set(id,desired)
                if not ok then
                    if enabled and (id=='AutoCraftBizarre' or id=='FreeArrowMaterials') and S.MaterialReconciliationPending then
                        S.MaterialResumeRequested=true
                        S.FarmCraftHold='Material craft recovery waiting; item farming continues'
                    elseif enabled and id=="AutoCraftBizarre" and S.CraftReconciliationPending then
                        S.FarmCraftHold="Bizarre craft awaiting inventory reconciliation; other farms continue"
                    else table.insert(errors,id..": "..tostring(err)) end
                end
            end
        end
        if #errors>0 and enabled then
            for _,id in ipairs(ids) do
                if A.Get(id)~=original[id] then
                    local ok,err=A.Set(id,original[id])
                    if not ok then table.insert(errors,"rollback: "..tostring(err)) end
                end
            end
        end
        A.Save()
        assert(#errors==0,table.concat(errors,"; "))
        running=enabled
        if B.Player and type(writefile)=="function" then
            local pauseFile="sharkwow-farm-paused-"..B.Player.UserId..".flag"
            if enabled then
                if type(isfile)=="function" and isfile(pauseFile) then
                    assert(type(delfile)=="function","cannot clear manual farm pause")
                    delfile(pauseFile)
                end
                getgenv().SHARKWOW_FLEET_PAUSED=false
            else
                writefile(pauseFile,"manual pause")
                getgenv().SHARKWOW_FLEET_PAUSED=true
            end
        end
    end})
function S.SetFarmSelection(values)
    local previous=table.clone(selection)
    for key in pairs(selection)do selection[key]=values[key]==true end
    if running then
        local ok,err=A.Set("FarmAndCraft",true)
        if not ok then for key,value in pairs(previous)do selection[key]=value end;error(err)end
    end
    if selectionFile and type(writefile)=="function" then
        writefile(selectionFile,game.HttpService:JSONEncode({Schema=2,UserId=B.Player.UserId,Selected=selection}))
    end
end
S.OnPhoneReady=function()
    if running then
        local ok,err=A.Set('FarmAndCraft',true)
        if not ok then A.Error('FarmAndCraft',err) end
    end
end
if B.Player and type(isfile)=="function" and isfile("sharkwow-farm-paused-"..B.Player.UserId..".flag") then
    local ok,err=A.Set("FarmAndCraft",false)
    if not ok then A.Error("manual pause",err) end
end

-- Repair only recorded ON intent; manual OFF and unresolved resource actions win.
local nextRepair={}
S.CheckFarmHealth=function()
    if not running or getgenv().SHARKWOW_FLEET_PAUSED or not A.SettingsReady or A.RestoringSettings then return end
    if A.Features.AutoPhone and A.Get('AutoPhone') then return end
    if S.PhonePrerequisiteWaiting then
        if S.ReadInventory and S.ReadInventory() then S.OnPhoneReady() end
        return
    end
    if S.TransferPending or S.PhoneBusy or S.RaidBusy or S.CraftBusy or S.MaterialBusy or S.AutoBusy or S.RouteBusy or S.TeleportBusy then return end
    if S.MaterialResumeRequested and os.clock()>=(nextRepair.MaterialResume or 0) then
        nextRepair.MaterialResume=os.clock()+5
        local ok,err=A.Set('AutoCraftBizarre',true)
        if ok then
            S.MaterialResumeRequested=false;S.FarmCraftHold=nil
            S.FarmHealthStatus='interrupted craft recovery completed; crafting resumed'
        else S.FarmHealthStatus='waiting for material recovery: '..tostring(err) end
    end
    for _,id in ipairs(ids)do
        if A.FeatureStates[id]==true and not A.Get(id) and os.clock()>=(nextRepair[id] or 0) then
            local blocked=(id=="AutoCraftBizarre" and S.CraftReconciliationPending) or (A.Errors and A.Errors[id])
            if not blocked then
                nextRepair[id]=os.clock()+30
                local ok,err=A.Set(id,true)
                S.FarmHealthStatus=ok and ("restored stopped worker: "..id) or ("waiting for "..id..": "..tostring(err))
            else S.FarmHealthStatus="waiting for confirmation or error review: "..id end
        end
    end
end
A.Loop("farm health",2,S.CheckFarmHealth)

    end)(advanced, bridge);
    (function(A, B)
local S=B.State
if S.FarmCamera and S.FarmCamera.Destroy then S.FarmCamera:Destroy() end
local run=game:GetService('RunService')
local camera=workspace.CurrentCamera
local saved=A.Options.FarmCamera
if type(saved)~='table' or type(saved.Yaw)~='number' or saved.Yaw~=saved.Yaw or math.abs(saved.Yaw)>math.pi then
    local look=camera and camera.CFrame.LookVector or Vector3.new(0,-1,-.1)
    saved={Yaw=math.atan2(-look.X,-look.Z)}
    A.Options.FarmCamera=saved
    A.Save()
end
local rotation=CFrame.fromOrientation(math.rad(-80),saved.Yaw,0)
local controller={Alive=true,Active=false,Frames=0,Version=1}
S.FarmCamera=controller
local binding='SHARKWOW_Standout_FarmCamera'
local ownedCamera,oldFov
local function release()
    if ownedCamera and ownedCamera.FieldOfView==70 then ownedCamera.FieldOfView=oldFov end
    ownedCamera=nil;oldFov=nil;controller.Active=false
end
function controller:Destroy()
    self.Alive=false;run:UnbindFromRenderStep(binding);release()
end
function controller:Step()
    local enabled=not self.Suspended and A.Current() and A.SettingsReady
        and (A.Get('FarmAndCraft') or S.AutoArrow or S.AutoRokaka or S.AutoParts)
    local cam=workspace.CurrentCamera
    local character=B.Player.Character
    local root=character and character:FindFirstChild('HumanoidRootPart')
    local humanoid=character and character:FindFirstChildOfClass('Humanoid')
    if not enabled or not cam or not root or not humanoid or humanoid.Health<=0
        or cam.CameraType~=Enum.CameraType.Custom or S.RaidBusy
        or B.Player:GetAttribute('TrainRaidActive')==true then release();return end
    if ownedCamera~=cam then release();ownedCamera=cam;oldFov=cam.FieldOfView end
    local focus=root.Position+Vector3.new(0,1.5,0)
    cam.CFrame=CFrame.new(focus)*rotation*CFrame.new(0,0,12.5)
    cam.Focus=CFrame.new(focus);cam.FieldOfView=70
    self.Active=true;self.Frames+=1
end
run:BindToRenderStep(binding,Enum.RenderPriority.Camera.Value+1,function()
    if not controller.Alive then return end
    if not A.Current() then controller:Destroy();return end
    local ok,err=pcall(controller.Step,controller)
    if not ok then release();A.Error('farm camera',err) end
end)
A.Cleanups[#A.Cleanups+1]=function()controller:Destroy()end

    end)(advanced, bridge);
    (function(A, B)
local TweenService=game:GetService("TweenService")
local cyan=Color3.fromRGB(0,240,255)
local purple=Color3.fromRGB(168,85,247)
local ink=Color3.fromRGB(243,247,255)
local muted=Color3.fromRGB(166,177,204)
local surface=Color3.fromRGB(22,30,40)
local bold=Font.new("rbxasset://fonts/families/BuilderSans.json",Enum.FontWeight.Bold)
local pageConnections={}
local detailConnections={}
local categoryOrder={"favorites","farm","craft","quests","combat","move","visuals","settings"}
local categories={
    AutoFarm="combat",
    AutoPhone="quests",AutoQuest="quests",QuestFarm="quests",QuestTravel="quests",AutoDialogue="quests",BountyFarm="quests",
    FreeArrowMaterials="craft",AutoCraftBizarre="craft",AutoRoll="craft",AutoDropJunk="craft",
}
local categoryLabels={favorites="SAVED",farm="FARM",craft="CRAFT",quests="QUESTS",combat="COMBAT",move="TRAVEL",visuals="DISPLAY",settings="SETTINGS"}
local function category(f)
    return categories[f.Id] or ((f.Group=="utility" or f.Group=="notify") and "settings" or f.Group)
end
local priority={FarmAndCraft=0,AutoPhone=1,ArrowFarm=1,ArrowPartFarm=2,Rokaka=3,GardenHarvest=4,FreeArrowMaterials=1,AutoCraftBizarre=2,AutoHopArrows=5}
local function connect(signal,fn)
    local c=signal:Connect(function(...) if A.Current() then fn(...) end end)
    pageConnections[#pageConnections+1]=c;return c
end
local function create(class,parent,props)
    local obj=Instance.new(class)
    for key,value in pairs(props or {}) do obj[key]=value end
    obj.Parent=parent;return obj
end
local function text(parent,value,size)
    return create("TextLabel",parent,{BackgroundTransparency=1,Text=value,FontFace=bold,TextSize=size or 14,TextColor3=ink,TextXAlignment=Enum.TextXAlignment.Left,TextTruncate=Enum.TextTruncate.AtEnd})
end
local function button(parent,value,size)
    local b=create("TextButton",parent,{Text=value,FontFace=bold,TextSize=14,TextColor3=ink,BackgroundColor3=surface,BorderSizePixel=0,AutoButtonColor=true,Size=size or UDim2.fromOffset(100,36)})
    create("UICorner",b,{CornerRadius=UDim.new(0,7)});return b
end
local function icon(parent,kind,x,y)
    local holder=create("Frame",parent,{Name="CategoryIcon",Position=UDim2.fromOffset(x,y),Size=UDim2.fromOffset(18,18),BackgroundTransparency=1})
    local function line(x1,y1,x2,y2)
        local dx,dy=x2-x1,y2-y1
        create("Frame",holder,{AnchorPoint=Vector2.new(0.5,0.5),Position=UDim2.fromOffset((x1+x2)/2,(y1+y2)/2),Size=UDim2.fromOffset(math.sqrt(dx*dx+dy*dy),2),Rotation=math.deg(math.atan2(dy,dx)),BackgroundColor3=cyan,BorderSizePixel=0})
    end
    local paths={
        favorites={{9,1,11,6},{11,6,17,7},{17,7,13,11},{13,11,14,17},{14,17,9,14},{9,14,4,17},{4,17,5,11},{5,11,1,7},{1,7,7,6},{7,6,9,1}},
        farm={{9,17,9,7},{9,11,3,5},{3,5,3,10},{3,10,9,13},{9,8,15,2},{15,2,15,7},{15,7,9,10}},
        craft={{3,16,13,6},{8,3,12,1},{12,1,17,6},{17,6,14,9},{14,9,8,3}},
        quests={{4,3,14,3},{14,3,14,17},{14,17,4,17},{4,17,4,3},{7,1,11,1},{7,7,12,7},{7,11,12,11}},
        combat={{2,2,15,15},{12,14,16,10},{16,2,3,15},{2,10,6,14}},
        move={{2,9,16,9},{10,3,16,9},{10,15,16,9}},
        visuals={{1,9,5,4},{5,4,13,4},{13,4,17,9},{17,9,13,14},{13,14,5,14},{5,14,1,9},{9,6,9,12}},
        settings={{2,4,16,4},{2,9,16,9},{2,14,16,14},{6,2,6,6},{12,7,12,11},{5,12,5,16}},
    }
    for _,p in ipairs(paths[kind] or paths.settings) do line(p[1],p[2],p[3],p[4]) end
end
local tweens={}
local function animate(object,properties)
    if tweens[object] then tweens[object]:Cancel();tweens[object]=nil end
    local appearance=B.State.Appearance or {}
    if appearance.ReducedMotion or appearance.Effects==false then
        for key,value in pairs(properties) do object[key]=value end
        return
    end
    local tween=TweenService:Create(object,TweenInfo.new(.16,Enum.EasingStyle.Quart,Enum.EasingDirection.Out),properties)
    tweens[object]=tween;tween:Play()
end
local function switch(parent,position,callback,bind)
    local hit=button(parent,"",UDim2.fromOffset(64,44));hit.Name="Toggle";hit.Position=position;hit.BackgroundTransparency=1;hit.AutoButtonColor=false
    local track=create("Frame",hit,{Name="Track",Position=UDim2.fromOffset(4,8),Size=UDim2.fromOffset(56,28),BackgroundColor3=Color3.fromRGB(56,47,77),BorderSizePixel=0})
    create("UICorner",track,{CornerRadius=UDim.new(1,0)})
    local thumb=create("Frame",track,{Name="Thumb",Position=UDim2.fromOffset(3,3),Size=UDim2.fromOffset(22,22),BackgroundColor3=muted,BorderSizePixel=0})
    create("UICorner",thumb,{CornerRadius=UDim.new(1,0)})
    local last
    local function update(on,instant)
        if last==on then return end
        last=on;hit:SetAttribute("Enabled",on)
        local values={Position=UDim2.fromOffset(on and 31 or 3,3),BackgroundColor3=on and cyan or muted}
        local color=on and Color3.fromRGB(0,97,109) or Color3.fromRGB(56,47,77)
        if instant then for key,value in pairs(values) do thumb[key]=value end;track.BackgroundColor3=color
        else animate(thumb,values);animate(track,{BackgroundColor3=color}) end
    end
    bind(hit.Activated,callback)
    return {Button=hit,Update=update}
end
local function scroll(parent)
    return create("Frame",parent,{BackgroundTransparency=1,BorderSizePixel=0,ClipsDescendants=true})
end
local function paginate(container,pageNumber)
    local children={}
    for _,child in ipairs(container:GetChildren()) do if child:IsA("GuiObject") then children[#children+1]=child end end
    local columns=B.Panel.Size.X.Offset<600 and 1 or 2
    local capacity=columns*4
    local pages=math.max(1,math.ceil(#children/capacity))
    pageNumber=math.clamp(pageNumber,1,pages)
    for i,child in ipairs(children) do
        local slot=(i-1)%capacity
        child.Size=UDim2.new(1/columns,columns==1 and 0 or -4,0,68)
        child.Position=UDim2.new((slot%columns)/columns,(slot%columns)*4,0,math.floor(slot/columns)*76)
        child.Visible=math.floor((i-1)/capacity)+1==pageNumber
    end
    return pageNumber,pages
end
local page=create("Frame",B.Panel,{Name="ModulesPage",Position=UDim2.fromOffset(12,64),Size=UDim2.new(1,-24,1,-76),BackgroundColor3=Color3.fromRGB(9,17,24),BorderSizePixel=0,Visible=false,ZIndex=5})
local open=button(B.Panel,"modules >",UDim2.fromOffset(124,18));open.Name="Modules";open.Position=UDim2.new(1,-136,0,44);open.TextSize=12;open.TextColor3=cyan
A.Connect(open.Activated,function() B.State.ModulesOpen=not B.State.ModulesOpen;B.State.RefreshUI();page.Visible=B.State.ModulesOpen;open.Text=B.State.ModulesOpen and "< quick farm" or "modules >" end)
local sidebar=scroll(page);sidebar.Size=UDim2.new(0,100,1,-28)
create("UIListLayout",sidebar,{Padding=UDim.new(0,6),SortOrder=Enum.SortOrder.LayoutOrder})
local content=create("Frame",page,{Name="Content",Position=UDim2.fromOffset(110,0),Size=UDim2.new(1,-110,1,-28),BackgroundTransparency=1})
local search=create("TextBox",content,{Name="Search",Size=UDim2.new(1,0,0,34),BackgroundColor3=surface,BorderSizePixel=0,ClearTextOnFocus=false,Text="",PlaceholderText="search modules",PlaceholderColor3=muted,TextColor3=ink,FontFace=bold,TextSize=14})
create("UICorner",search,{CornerRadius=UDim.new(0,7)})
local list=scroll(content);list.Name="FeatureList";list.Position=UDim2.fromOffset(0,43);list.Size=UDim2.new(1,0,1,-82)
local footer=text(page,"",12);footer.Name="Status";footer.TextColor3=muted;footer.Position=UDim2.new(0,0,1,-24);footer.Size=UDim2.new(1,-10,0,20)
local details=create("Frame",content,{Name="Details",Size=UDim2.fromScale(1,1),BackgroundColor3=Color3.fromRGB(13,23,32),BorderSizePixel=0,Visible=false,ZIndex=10})
local detailTitle=text(details,"",18);detailTitle.Position=UDim2.fromOffset(10,4);detailTitle.Size=UDim2.new(1,-60,0,32)
local back=button(details,"x",UDim2.fromOffset(34,32));back.Position=UDim2.new(1,-38,0,3)
local detailList=scroll(details);detailList.Position=UDim2.fromOffset(10,42);detailList.Size=UDim2.new(1,-20,1,-84)
local mainIndex,detailIndex=1,1
local function pager(parent,name)
    local bar=create("Frame",parent,{Name=name,Position=UDim2.new(0,0,1,-36),Size=UDim2.new(1,0,0,36),BackgroundTransparency=1})
    local previous=button(bar,"<",UDim2.fromOffset(44,34));previous.Name="Previous"
    local nextButton=button(bar,">",UDim2.fromOffset(44,34));nextButton.Name="Next";nextButton.Position=UDim2.new(1,-44,0,0)
    local caption=text(bar,"1 / 1",12);caption.Name="Page";caption.Position=UDim2.fromOffset(50,0);caption.Size=UDim2.new(1,-100,1,0);caption.TextXAlignment=Enum.TextXAlignment.Center
    return {Bar=bar,Previous=previous,Next=nextButton,Caption=caption}
end
local mainPager=pager(content,"Pages")
local detailPager=pager(details,"Pages")
local function showPages(pager,index,total)
    pager.Caption.Text=index.." / "..total
    pager.Bar.Visible=total>1
    pager.Previous.Active=index>1;pager.Next.Active=index<total
    pager.Previous.TextTransparency=index>1 and 0 or .6;pager.Next.TextTransparency=index<total and 0 or .6
end
local group="farm"
local selected
local rows={}
local nav={}
local function clear(f)
    for _,child in ipairs(f:GetChildren()) do if child:IsA("GuiObject") then
            for object,tween in pairs(tweens) do if object==child or object:IsDescendantOf(child) then tween:Cancel();tweens[object]=nil end end
            child:Destroy()
        end end
end
local function safe(fn)
    local ok,err=pcall(fn);if not ok then A.Error("ui",err) end
end
local dropdown
local dropdownConnections={}
local function closeDropdown()
    for _,c in ipairs(dropdownConnections) do c:Disconnect() end;table.clear(dropdownConnections)
    if dropdown then dropdown:Destroy();dropdown=nil end
end
local function renderDetails()
    closeDropdown()
    for _,c in ipairs(detailConnections) do c:Disconnect() end;table.clear(detailConnections)
    clear(detailList)
    local function connect(signal,fn)
        local c=signal:Connect(function(...) if A.Current() then fn(...) end end)
        detailConnections[#detailConnections+1]=c;return c
    end
    local f=selected and A.Features[selected]
    if not f then details.Visible=false;return end
    detailTitle.Text=f.Name
    details.Visible=true
    local tools=create("Frame",detailList,{Size=UDim2.new(1,0,0,36),BackgroundTransparency=1})
    local favorite=button(tools,A.Favorites[f.Id] and "* favorite" or "+ favorite",UDim2.new(0.48,0,1,0))
    local bind=button(tools,"bind: "..tostring(A.Binds[f.Id] or "none"),UDim2.new(0.5,0,1,0));bind.Position=UDim2.fromScale(0.5,0)
    connect(favorite.Activated,function() A.Favorites[f.Id]=not A.Favorites[f.Id];A.Save();renderDetails();A.Refresh() end)
    connect(bind.Activated,function() if A.Binding==f.Id then A.Binding=nil;A.Binds[f.Id]=nil;A.Save();renderDetails() else A.Binding=f.Id;bind.Text="press key / click clears" end end)
    for _,field in ipairs(f.Fields) do
        local row=create("Frame",detailList,{Name=field.Key,Size=UDim2.new(1,0,0,type(field.Default)=="string" and not field.Choices and 66 or 40),BackgroundTransparency=1})
        local caption=text(row,field.Name,13);caption.Size=UDim2.new(0.58,-5,1,0);caption.TextWrapped=true;caption.TextTruncate=Enum.TextTruncate.None
        local value=A.Options[f.Id][field.Key]
        if type(field.Default)=="boolean" then
            caption.Size=UDim2.new(1,-72,1,0);caption.TextWrapped=true
            local control
            control=switch(row,UDim2.new(1,-66,0,7),function()
                safe(function() A.Option(f.Id,field.Key,not A.Options[f.Id][field.Key]) end)
                control.Update(A.Options[f.Id][field.Key])
            end,connect)
            control.Update(value,true)
        elseif field.Choices then
            local control=button(row,type(value)=="boolean" and (value and "on" or "off") or tostring(value),UDim2.new(0.42,0,1,0));control.Position=UDim2.fromScale(0.58,0);control.TextColor3=value==true and cyan or ink
            connect(control.Activated,function()
                if dropdown then closeDropdown();return end
                dropdown=create("ScrollingFrame",details,{Name="ChoiceMenu",Position=UDim2.fromOffset(8,42),Size=UDim2.new(1,-16,0,math.min(240,#field.Choices*44)),CanvasSize=UDim2.fromOffset(0,#field.Choices*44),ScrollBarThickness=3,BackgroundColor3=surface,BorderSizePixel=0,ZIndex=30})
                create("UICorner",dropdown,{CornerRadius=UDim.new(0,9)})
                for index,choice in ipairs(field.Choices) do
                    local option=button(dropdown,tostring(choice),UDim2.new(1,-8,0,42))
                    option.Position=UDim2.fromOffset(4,(index-1)*44);option.ZIndex=31
                    dropdownConnections[#dropdownConnections+1]=option.Activated:Connect(function() if A.Current() then safe(function() A.Option(f.Id,field.Key,choice) end);renderDetails() end end)
                end
            end)
        else
            local isString=type(field.Default)=="string"
            if isString then caption.Size=UDim2.new(1,0,0,24) end
            local box=create("TextBox",row,{Name="Value",Position=isString and UDim2.fromOffset(0,26) or UDim2.fromScale(0.6,0),Size=isString and UDim2.new(1,0,0,36) or UDim2.new(0.4,0,1,0),Text=tostring(value),ClearTextOnFocus=false,FontFace=bold,TextSize=13,TextColor3=ink,BackgroundColor3=surface,BorderSizePixel=0,TextTruncate=Enum.TextTruncate.AtEnd})
            create("UICorner",box,{CornerRadius=UDim.new(0,7)})
            connect(box.FocusLost,function()
                safe(function() A.Option(f.Id,field.Key,isString and box.Text or assert(tonumber(box.Text),"enter a number")) end)
                box.Text=tostring(A.Options[f.Id][field.Key])
            end)
            if not isString and field.Min and field.Max and field.Max>field.Min then
                caption.Size=UDim2.new(.58,-5,0,28);box.Size=UDim2.new(.4,0,0,28)
                local hit=button(row,"",UDim2.new(1,0,0,36));hit.Name="Slider";hit.Position=UDim2.fromOffset(0,30);hit.BackgroundTransparency=1;hit.AutoButtonColor=false
                local track=create("Frame",hit,{Position=UDim2.new(0,8,.5,-3),Size=UDim2.new(1,-16,0,6),BackgroundColor3=Color3.fromRGB(41,60,74),BorderSizePixel=0})
                create("UICorner",track,{CornerRadius=UDim.new(1,0)})
                local fill=create("Frame",track,{Size=UDim2.fromScale(0,1),BackgroundColor3=cyan,BorderSizePixel=0})
                create("UICorner",fill,{CornerRadius=UDim.new(1,0)})
                local thumb=create("Frame",track,{AnchorPoint=Vector2.new(.5,.5),Size=UDim2.fromOffset(16,16),BackgroundColor3=ink,BorderSizePixel=0})
                create("UICorner",thumb,{CornerRadius=UDim.new(1,0)})
                local drag,pending
                local function paint(n)
                    local alpha=math.clamp((n-field.Min)/(field.Max-field.Min),0,1)
                    fill.Size=UDim2.fromScale(alpha,1);thumb.Position=UDim2.fromScale(alpha,.5)
                end
                local function move(x)
                    local alpha=math.clamp((x-track.AbsolutePosition.X)/math.max(1,track.AbsoluteSize.X),0,1)
                    local step=field.Step or (field.Default%1~=0 and .1 or 1)
                    pending=math.clamp(math.floor((field.Min+alpha*(field.Max-field.Min))/step+.5)*step,field.Min,field.Max)
                    box.Text=tostring(pending);paint(pending)
                end
                connect(hit.InputBegan,function(e) if e.UserInputType==Enum.UserInputType.MouseButton1 or e.UserInputType==Enum.UserInputType.Touch then drag=e;move(e.Position.X) end end)
                connect(game:GetService("UserInputService").InputChanged,function(e)
                    if drag and (e==drag or drag.UserInputType==Enum.UserInputType.MouseButton1 and e.UserInputType==Enum.UserInputType.MouseMovement) then move(e.Position.X) end
                end)
                connect(game:GetService("UserInputService").InputEnded,function(e)
                    if e==drag then drag=nil;safe(function() A.Option(f.Id,field.Key,pending) end);paint(A.Options[f.Id][field.Key]) end
                end)
                connect(game:GetService("UserInputService").WindowFocusReleased,function()drag=nil;paint(A.Options[f.Id][field.Key]);box.Text=tostring(A.Options[f.Id][field.Key])end)
                connect(box.FocusLost,function()paint(A.Options[f.Id][field.Key])end)
                paint(value)
            end
        end
    end
    if f.Id=="AutoFarm" then
        local refresh=button(detailList,"use currently loaded mobs",UDim2.new(1,0,0,36))
        connect(refresh.Activated,function() A.Option("AutoFarm","Targets",table.concat(A.Mobs(),", "));renderDetails() end)
    end
    if f.Id=="ItemFarm" then
        local refresh=button(detailList,"use currently loaded items",UDim2.new(1,0,0,36))
        connect(refresh.Activated,function() A.Option("ItemFarm","Names",table.concat(A.WorldItemNames(),", "));renderDetails() end)
    end
    for _,action in ipairs(f.Actions or {}) do
        local b=button(detailList,action.Name,UDim2.new(1,0,0,36))
        connect(b.Activated,function() safe(action.Run) end)
    end
    if f.ListActions then
        local actions=f.ListActions()
        if #actions==0 then
            local empty=text(detailList,"no other players in this server",13)
            empty.Size=UDim2.new(1,0,0,36);empty.TextColor3=muted
        end
        for _,action in ipairs(actions) do
            local b=button(detailList,action.Name,UDim2.new(1,0,0,48))
            b.TextWrapped=true;b.TextSize=13
            connect(b.Activated,function() safe(action.Run) end)
        end
    end
    local total
    detailIndex,total=paginate(detailList,detailIndex);showPages(detailPager,detailIndex,total)
    B.State.MenuDetailPage={Id=f.Id,Page=detailIndex,Pages=total}
end
A.RefreshDetails=renderDetails
A.RefreshPlayerList=function() if selected=="WarpPlayer" and details.Visible then renderDetails() end end
A.Connect(back.Activated,function() selected=nil;A.Binding=nil;details.Visible=false;detailIndex=1 end)
A.Connect(detailPager.Previous.Activated,function()detailIndex-=1;renderDetails()end)
A.Connect(detailPager.Next.Activated,function()detailIndex+=1;renderDetails()end)
local function buildList()
    for _,c in ipairs(pageConnections) do c:Disconnect() end;table.clear(pageConnections)
    clear(list);table.clear(rows)
    local query=search.Text:lower()
    local ordered=table.clone(A.Order)
    table.sort(ordered,function(x,y)
        local a,b=priority[x] or 50,priority[y] or 50
        if a~=b then return a<b end
        return A.Features[x].Name<A.Features[y].Name
    end)
    for order,id in ipairs(ordered) do
        local f=A.Features[id]
        if not f.Hidden and (group=="favorites" and A.Favorites[id] or group==category(f) or query~="") and (query=="" or (f.Name.." "..f.Description):lower():find(query,1,true)) then
            local row=create("Frame",list,{Name=id,LayoutOrder=order,Size=UDim2.new(1,0,0,56),BackgroundColor3=surface,BorderSizePixel=0})
            create("UICorner",row,{CornerRadius=UDim.new(0,8)})
            icon(row,category(f),9,19)
            local name=button(row,f.Name,UDim2.new(1,-106,1,0));name.Name="DetailsButton";name.Position=UDim2.fromOffset(34,0);name.BackgroundTransparency=1;name.TextSize=13;name.TextXAlignment=Enum.TextXAlignment.Left;name.TextWrapped=true
            local control
            if f.Action then
                local action=button(row,"GO",UDim2.fromOffset(58,44));action.Name="Action";action.Position=UDim2.new(1,-66,0,7);action.TextColor3=cyan
                connect(action.Activated,function()safe(f.Action)end)
                control={Button=action}
            else
                control=switch(row,UDim2.new(1,-66,0,7),function()safe(function()A.Set(id,not A.Get(id))end)end,connect)
                control.Update(A.Get(id),true)
                if f.Locked then control.Button.Active=false end
            end
            connect(name.Activated,function()selected=id;detailIndex=1;renderDetails()end)
            rows[id]={Control=control,Name=name}
        end
    end
    local total
    mainIndex,total=paginate(list,mainIndex);showPages(mainPager,mainIndex,total)
    B.State.MenuPage={Category=group,Page=mainIndex,Pages=total}
    if selected then renderDetails() end
end
A.Connect(mainPager.Previous.Activated,function()mainIndex-=1;buildList();A.Refresh()end)
A.Connect(mainPager.Next.Activated,function()mainIndex+=1;buildList();A.Refresh()end)
function A.ShowCategory(name)
    assert(table.find(categoryOrder,name),"unknown category")
    closeDropdown()
    group=name;selected=nil;details.Visible=false;mainIndex=1;detailIndex=1;search.Text=""
    buildList();A.Refresh()
end
function A.OpenFeature(id)
    local feature=assert(A.Features[id],"unknown feature")
    if feature.Hidden then return false end
    B.State.ModulesOpen=true;group=category(feature);mainIndex=1;detailIndex=1;search.Text="";selected=id
    B.State.RefreshUI();buildList();A.Refresh()
end
for order,name in ipairs(categoryOrder) do
    local b=button(sidebar,"",UDim2.new(1,0,0,40));nav[name]=b;b.LayoutOrder=order
    icon(b,name,7,11)
    local caption=text(b,categoryLabels[name],11);caption.Name="Caption";caption.Position=UDim2.fromOffset(31,0);caption.Size=UDim2.new(1,-31,1,0)
    A.Connect(b.Activated,function()A.ShowCategory(name)end)
end
function A.Refresh()
    page.Visible=B.State.ModulesOpen==true
    open.Text=B.State.ModulesOpen and "< quick farm" or "modules >"
    local active=0
    for _,id in ipairs(A.Order) do if not A.Features[id].Hidden and A.Get(id) then active+=1 end end
    for id,row in pairs(rows) do
        local f=A.Features[id];local enabled=A.Get(id)
        if row.Control.Update then row.Control.Update(enabled) end
        row.Name.TextColor3=A.Errors[id] and Color3.fromRGB(255,160,120) or ink
    end
    for name,b in pairs(nav) do b.Caption.TextColor3=group==name and cyan or muted;b.BackgroundColor3=group==name and Color3.fromRGB(30,30,51) or surface end
    local status=B.State.AntiAFK:find("retrying:",1,true) and "anti-afk retrying" or A.Status
    footer.Text=string.format("%d active  |  %s",active,status)
end
A.Connect(search:GetPropertyChangedSignal("Text"),function() selected=nil;details.Visible=false;mainIndex=1;buildList();A.Refresh() end)
A.Loop("module ui",0.3,function() if B.Panel.Visible then A.Refresh() end end)
A.Cleanups[#A.Cleanups+1]=function() closeDropdown();for _,c in ipairs(pageConnections) do c:Disconnect() end;for _,c in ipairs(detailConnections) do c:Disconnect() end;table.clear(pageConnections);table.clear(detailConnections);for object,tween in pairs(tweens) do tween:Cancel();tweens[object]=nil end;page:Destroy();open:Destroy() end
buildList();A.Refresh()

B.State.MenuLayoutVersion=3
B.State.ModulesOpen=true
B.State.RefreshUI();A.Refresh()

    end)(advanced, bridge);
    (function(A, B)
local connections={}
local function upper(value)
    local result,offset={},1
    while true do
        local first,last=value:find("<[^>]*>",offset)
        if not first then result[#result+1]=value:sub(offset):upper();break end
        result[#result+1]=value:sub(offset,first-1):upper()
        result[#result+1]=value:sub(first,last)
        offset=last+1
    end
    return table.concat(result)
end
local function watch(object)
    if connections[object] then return end
    local property
    if object:IsA("TextLabel") or object:IsA("TextButton") then property="Text"
    elseif object:IsA("TextBox") then property="PlaceholderText" end
    if not property then return end
    local function update()
        if not A.Current() then return end
        local value=upper(object[property])
        if object[property]~=value then object[property]=value end
    end
    update()
    local changed=object:GetPropertyChangedSignal(property):Connect(update)
    local destroyed
    destroyed=object.Destroying:Connect(function()
        changed:Disconnect();destroyed:Disconnect();connections[object]=nil
    end)
    connections[object]={changed,destroyed}
end
for _,object in ipairs(B.Gui:GetDescendants()) do watch(object) end
A.Connect(B.Gui.DescendantAdded,watch)
A.Cleanups[#A.Cleanups+1]=function()
    for _,pair in pairs(connections) do for _,connection in ipairs(pair) do connection:Disconnect() end end
    table.clear(connections)
end

    end)(advanced, bridge);
end
do
local aster=assert(loadstring([======[
--[====[
Vendored Aster UI: 7638ffa1f294dc21e2e1b144a5b235e38e0a896b
MIT License

Copyright (c) 2026 Aster UI contributors

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.


MIT License

Copyright (c) 2025 Footages

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
]====]
-- Aster UI
-- Single-file Roblox UI library for executors.

local TweenService = game:GetService("TweenService")
local UserInputService = game:GetService("UserInputService")
local GuiService = game:GetService("GuiService")
local RunService = game:GetService("RunService")
local HttpService = game:GetService("HttpService")
local Players = game:GetService("Players")
local TeleportService = game:GetService("TeleportService")
local MarketplaceService = game:GetService("MarketplaceService")
local StatsService = game:GetService("Stats")

local LocalPlayer = Players.LocalPlayer

local Library = {}

Library.Flags = {}
Library.Windows = {}

Library.AutoTranslate = true

Library.ForceCheckbox = false

Library._toggleSkins = {}

Library._keybindMenus = {}

function Library:SetForceCheckbox(enabled)
    enabled = enabled == true
    Library.ForceCheckbox = enabled
    for button, rebuild in pairs(Library._toggleSkins) do
        if button:IsDescendantOf(game) then
            rebuild()
        else
            Library._toggleSkins[button] = nil
        end
    end
end

function Library._SetAlwaysOnTop(gui, enabled)
    if not gui then
        return
    end
    pcall(function()
        if sethiddenproperty then
            sethiddenproperty(gui, "OnTopOfCoreBlur", enabled)
        elseif setscriptable then
            setscriptable(gui, "OnTopOfCoreBlur", true)
            gui.OnTopOfCoreBlur = enabled
            setscriptable(gui, "OnTopOfCoreBlur", false)
        end
    end)
end

local function cleanIcon(icon)
    if type(icon) == "string" and icon:lower():gsub("^lucide:", "") == "none" then
        return false
    end
    return icon
end

local function normalize(source, map)
    local opts = {}
    if type(source) == "string" then
        opts.Name = source
    elseif type(source) == "table" then
        for key, value in pairs(source) do
            opts[key] = value
        end
    end
    for from, to in pairs(map or {}) do
        if opts[to] == nil and opts[from] ~= nil then
            opts[to] = opts[from]
        end
    end
    if opts.Icon ~= nil then
        opts.Icon = cleanIcon(opts.Icon)
    end
    if opts.Range then
        opts.Min = opts.Min or opts.Range[1]
        opts.Max = opts.Max or opts.Range[2]
    end
    return opts
end

local function finishElement(tab, opts, element, frame, kind)
    element._type = kind
    element._frame = frame
    element._listeners = element._listeners or {}
    local window = tab and tab.Window
    local searchText = opts.Name or opts.Text or opts.Title
    element._searchName = type(searchText) == "string" and searchText or ""
    element._searchKey = string.lower(element._searchName)
    if tab and tab._items then
        table.insert(tab._items, element)
    end
    if opts.Flag then
        Library.Flags[opts.Flag] = element
        if window then
            window:_flagCreated(opts.Flag, element)
        end
    end
    element._userVisible = opts.Visible ~= false
    function element:IsVisible()
        return element._userVisible
    end
    function element:_isShown()
        return element._userVisible and not (tab and tab._userVisible == false)
    end
    function element:SetVisible(visible)
        visible = visible and true or false
        if visible == element._userVisible or element._destroyed then
            return
        end
        element._userVisible = visible
        if not visible then
            if element._onHide then
                element._onHide()
            end
            if element.Open and type(element.SetOpen) == "function" then
                element:SetOpen(false)
            end
        end
        if frame then
            frame.Visible = visible
        end
        if window then
            window._controlsDirty = true
        end
    end
    if frame and not element._userVisible then
        frame.Visible = false
    end
    -- Tooltip: string or { Title, Text, Icon }.
    function element:SetTooltip(tip)
        element._tooltip = tip
        if frame and window and not element._tooltipBound then
            element._tooltipBound = true
            window:_attachTooltip(element, frame)
        end
    end
    function element:GetTooltip()
        return element._tooltip
    end
    if opts.Tooltip ~= nil and opts.Tooltip ~= false then
        element:SetTooltip(opts.Tooltip)
    end
    function element:Destroy()
        if element._destroyed then
            return
        end
        element._destroyed = true
        if window and window._tipOwner == element then
            window:_hideTooltip()
        end
        for _, disconnect in ipairs(element._listeners) do
            disconnect()
        end
        element._listeners = {}
        if tab and tab._items then
            local index = table.find(tab._items, element)
            if index then
                table.remove(tab._items, index)
            end
        end
        if opts.Flag and Library.Flags[opts.Flag] == element then
            Library.Flags[opts.Flag] = nil
        end
        if window then
            window._controlsDirty = true
        end
        if frame then
            frame:Destroy()
        end
    end
    return element
end

Library.Theme = {
    Background = Color3.fromRGB(12, 14, 12),
    Surface = Color3.fromRGB(16, 20, 17),
    Surface2 = Color3.fromRGB(22, 28, 23),
    Surface3 = Color3.fromRGB(32, 44, 34),
    Stroke = Color3.fromRGB(28, 44, 31),
    StrokeHover = Color3.fromRGB(50, 105, 65),
    Accent = Color3.fromRGB(50, 230, 150),
    AccentDark = Color3.fromRGB(12, 28, 18),
    Text = Color3.fromRGB(235, 248, 238),
    Muted = Color3.fromRGB(115, 145, 125),
    Warning = Color3.fromRGB(240, 190, 75),
    Success = Color3.fromRGB(50, 230, 150),
    Error = Color3.fromRGB(245, 85, 85),
}

-- tie-break for identical theme colors.
local THEME_KEYS = {
    "Accent", "AccentDark", "Background", "Surface", "Surface2", "Surface3",
    "Stroke", "StrokeHover", "Text", "Muted", "Warning", "Success", "Error",
}

local function rgb(r, g, b)
    return Color3.fromRGB(r, g, b)
end

local function preset(background, surface, surface2, surface3, strokeColor, strokeHover, accent, accentDark, text, muted)
    return {
        Background = rgb(table.unpack(background)),
        Surface = rgb(table.unpack(surface)),
        Surface2 = rgb(table.unpack(surface2)),
        Surface3 = rgb(table.unpack(surface3)),
        Stroke = rgb(table.unpack(strokeColor)),
        StrokeHover = rgb(table.unpack(strokeHover)),
        Accent = rgb(table.unpack(accent)),
        AccentDark = rgb(table.unpack(accentDark)),
        Text = rgb(table.unpack(text)),
        Muted = rgb(table.unpack(muted)),
    }
end

Library.ThemePresets = {
    Cybrion = preset({ 12, 14, 12 }, { 16, 20, 17 }, { 22, 28, 23 }, { 32, 44, 34 }, { 28, 44, 31 }, { 50, 105, 65 }, { 50, 230, 150 }, { 12, 28, 18 }, { 235, 248, 238 }, { 115, 145, 125 }),
    Midnight = preset({ 15, 18, 26 }, { 18, 22, 31 }, { 22, 26, 37 }, { 37, 44, 60 }, { 34, 40, 55 }, { 70, 84, 112 }, { 128, 160, 246 }, { 14, 18, 30 }, { 228, 232, 242 }, { 116, 126, 148 }),
    Ocean = preset({ 12, 20, 24 }, { 15, 24, 29 }, { 18, 29, 35 }, { 31, 48, 56 }, { 29, 44, 52 }, { 58, 92, 104 }, { 110, 214, 222 }, { 10, 24, 28 }, { 226, 238, 240 }, { 108, 134, 140 }),
    Rose = preset({ 22, 15, 18 }, { 27, 18, 22 }, { 32, 21, 26 }, { 48, 34, 40 }, { 45, 30, 37 }, { 98, 64, 78 }, { 246, 160, 186 }, { 30, 14, 20 }, { 240, 228, 232 }, { 138, 112, 120 }),
    Emerald = preset({ 13, 20, 17 }, { 16, 24, 20 }, { 20, 29, 24 }, { 33, 47, 40 }, { 30, 44, 37 }, { 62, 96, 78 }, { 132, 226, 170 }, { 12, 26, 18 }, { 228, 240, 233 }, { 110, 136, 122 }),
    Amber = preset({ 22, 18, 13 }, { 27, 22, 16 }, { 32, 26, 19 }, { 49, 41, 31 }, { 46, 38, 28 }, { 100, 82, 58 }, { 246, 196, 120 }, { 30, 22, 10 }, { 242, 236, 226 }, { 140, 126, 106 }),
    Mono = preset({ 16, 16, 17 }, { 20, 20, 21 }, { 25, 25, 26 }, { 40, 40, 42 }, { 38, 38, 40 }, { 84, 84, 88 }, { 236, 236, 240 }, { 20, 20, 22 }, { 234, 234, 236 }, { 122, 122, 128 }),
    Nebula = preset({ 14, 12, 28 }, { 18, 15, 35 }, { 23, 19, 43 }, { 39, 32, 68 }, { 35, 29, 62 }, { 84, 68, 140 }, { 199, 125, 255 }, { 22, 10, 40 }, { 236, 230, 252 }, { 124, 114, 160 }),
    Synthwave = preset({ 20, 12, 30 }, { 25, 15, 37 }, { 31, 18, 45 }, { 52, 30, 72 }, { 47, 27, 66 }, { 110, 58, 150 }, { 255, 94, 198 }, { 38, 8, 30 }, { 250, 232, 246 }, { 150, 118, 160 }),
    Sakura = preset({ 24, 14, 20 }, { 29, 17, 24 }, { 35, 20, 29 }, { 54, 32, 45 }, { 50, 29, 41 }, { 112, 66, 92 }, { 255, 158, 200 }, { 36, 12, 24 }, { 248, 232, 240 }, { 150, 112, 132 }),
    Velvet = preset({ 20, 10, 16 }, { 25, 12, 20 }, { 31, 15, 25 }, { 50, 25, 40 }, { 46, 23, 37 }, { 104, 52, 82 }, { 222, 110, 170 }, { 30, 8, 20 }, { 244, 228, 238 }, { 142, 106, 126 }),
    Crimson = preset({ 18, 10, 12 }, { 23, 12, 15 }, { 28, 14, 18 }, { 46, 24, 29 }, { 42, 22, 27 }, { 104, 46, 56 }, { 244, 74, 94 }, { 32, 8, 12 }, { 244, 230, 232 }, { 142, 106, 112 }),
    Sunset = preset({ 22, 13, 14 }, { 27, 16, 17 }, { 33, 19, 21 }, { 52, 31, 32 }, { 48, 28, 30 }, { 112, 62, 58 }, { 255, 138, 92 }, { 34, 14, 8 }, { 248, 234, 228 }, { 150, 118, 110 }),
    Gold = preset({ 14, 13, 11 }, { 18, 17, 14 }, { 23, 21, 17 }, { 38, 35, 28 }, { 35, 32, 26 }, { 92, 80, 54 }, { 232, 196, 122 }, { 30, 22, 8 }, { 240, 234, 222 }, { 136, 126, 106 }),
    Cyber = preset({ 13, 13, 15 }, { 17, 17, 19 }, { 21, 21, 24 }, { 36, 36, 40 }, { 33, 33, 37 }, { 86, 84, 70 }, { 250, 226, 72 }, { 30, 26, 4 }, { 240, 240, 232 }, { 126, 124, 118 }),
    Toxic = preset({ 11, 14, 11 }, { 14, 18, 14 }, { 18, 23, 18 }, { 31, 39, 30 }, { 28, 36, 28 }, { 74, 98, 60 }, { 184, 255, 74 }, { 18, 30, 6 }, { 232, 242, 228 }, { 116, 134, 110 }),
    Matcha = preset({ 16, 19, 14 }, { 20, 23, 17 }, { 24, 28, 21 }, { 40, 46, 34 }, { 37, 42, 31 }, { 84, 98, 70 }, { 176, 214, 140 }, { 18, 26, 10 }, { 236, 240, 228 }, { 128, 136, 116 }),
    Aurora = preset({ 10, 20, 22 }, { 12, 25, 27 }, { 15, 30, 33 }, { 26, 50, 53 }, { 24, 45, 48 }, { 50, 104, 104 }, { 94, 240, 180 }, { 6, 30, 22 }, { 224, 246, 240 }, { 102, 142, 134 }),
    Frost = preset({ 13, 17, 23 }, { 16, 21, 28 }, { 20, 26, 34 }, { 34, 43, 56 }, { 31, 40, 52 }, { 72, 92, 118 }, { 164, 214, 255 }, { 12, 22, 34 }, { 230, 238, 246 }, { 114, 128, 146 }),
    Abyss = preset({ 7, 11, 22 }, { 9, 14, 28 }, { 12, 18, 35 }, { 22, 31, 58 }, { 20, 28, 52 }, { 44, 64, 120 }, { 72, 148, 255 }, { 6, 14, 34 }, { 226, 234, 250 }, { 100, 116, 152 }),
    -- Seasonal and themed palettes.
    Halloween = preset({ 18, 12, 20 }, { 23, 15, 25 }, { 28, 18, 30 }, { 46, 30, 48 }, { 43, 28, 44 }, { 104, 62, 40 }, { 255, 138, 36 }, { 36, 16, 4 }, { 246, 234, 224 }, { 146, 120, 128 }),
    Haunted = preset({ 14, 12, 20 }, { 18, 15, 26 }, { 22, 18, 32 }, { 38, 31, 54 }, { 35, 29, 50 }, { 70, 96, 64 }, { 156, 255, 110 }, { 14, 30, 8 }, { 232, 240, 228 }, { 120, 116, 140 }),
    Christmas = preset({ 12, 20, 15 }, { 15, 25, 19 }, { 19, 30, 23 }, { 32, 50, 38 }, { 30, 46, 35 }, { 100, 54, 56 }, { 236, 72, 80 }, { 34, 8, 10 }, { 240, 244, 236 }, { 120, 142, 128 }),
    Valentine = preset({ 24, 12, 17 }, { 30, 14, 21 }, { 36, 17, 25 }, { 58, 27, 40 }, { 54, 25, 37 }, { 130, 56, 84 }, { 255, 92, 140 }, { 40, 8, 20 }, { 252, 232, 240 }, { 160, 112, 132 }),
    Lunar = preset({ 22, 10, 10 }, { 28, 12, 12 }, { 34, 15, 14 }, { 54, 24, 22 }, { 50, 22, 20 }, { 130, 92, 40 }, { 246, 196, 84 }, { 38, 16, 6 }, { 250, 236, 222 }, { 160, 120, 108 }),
    Tropical = preset({ 10, 22, 24 }, { 12, 27, 30 }, { 15, 33, 36 }, { 26, 54, 58 }, { 24, 50, 54 }, { 44, 110, 110 }, { 255, 170, 90 }, { 36, 18, 6 }, { 232, 246, 244 }, { 104, 144, 142 }),
    Dracula = preset({ 24, 25, 33 }, { 29, 30, 40 }, { 34, 36, 47 }, { 52, 55, 70 }, { 48, 50, 64 }, { 98, 114, 164 }, { 189, 147, 249 }, { 26, 18, 44 }, { 246, 246, 238 }, { 126, 132, 168 }),
    Coffee = preset({ 20, 16, 13 }, { 25, 20, 16 }, { 30, 24, 19 }, { 48, 39, 31 }, { 45, 36, 29 }, { 104, 82, 62 }, { 214, 170, 124 }, { 32, 22, 12 }, { 240, 230, 218 }, { 142, 124, 108 }),
}

Library.ThemeName = "Cybrion"
Library.DefaultTheme = "Cybrion"

Library.Assets = {
    Shadow = "rbxassetid://6014261993",
    Glow = "rbxassetid://8992230677",
    Logo = "rbxassetid://103859712365480",
}

local lucideSet = (function()
-- This file is automatically @generated by Tree Hub CLI.

return {
	["a-arrow-down"] = "rbxassetid://92867583610071",
	["a-arrow-up"] = "rbxassetid://132318504999733",
	["a-large-small"] = "rbxassetid://111491496660216",
	["accessibility"] = "rbxassetid://114029945302017",
	["activity"] = "rbxassetid://94212016861936",
	["air-vent"] = "rbxassetid://81517226012329",
	["airplay"] = "rbxassetid://115020759309179",
	["alarm-clock-check"] = "rbxassetid://76437352099157",
	["alarm-clock-minus"] = "rbxassetid://77364179863205",
	["alarm-clock-off"] = "rbxassetid://97904885874823",
	["alarm-clock-plus"] = "rbxassetid://80468822979214",
	["alarm-clock"] = "rbxassetid://126259032907535",
	["alarm-smoke"] = "rbxassetid://96965448419685",
	["album"] = "rbxassetid://127358331163602",
	["align-center-horizontal"] = "rbxassetid://81570549209434",
	["align-center-vertical"] = "rbxassetid://118470463752466",
	["align-end-horizontal"] = "rbxassetid://139502909745427",
	["align-end-vertical"] = "rbxassetid://96528869059554",
	["align-horizontal-distribute-center"] = "rbxassetid://97220086126656",
	["align-horizontal-distribute-end"] = "rbxassetid://106128590702022",
	["align-horizontal-distribute-start"] = "rbxassetid://76074660002997",
	["align-horizontal-justify-center"] = "rbxassetid://75732302772427",
	["align-horizontal-justify-end"] = "rbxassetid://129167626402283",
	["align-horizontal-justify-start"] = "rbxassetid://130161830325281",
	["align-horizontal-space-around"] = "rbxassetid://91646106782950",
	["align-horizontal-space-between"] = "rbxassetid://103886093046990",
	["align-start-horizontal"] = "rbxassetid://125674804697729",
	["align-start-vertical"] = "rbxassetid://105020230154823",
	["align-vertical-distribute-center"] = "rbxassetid://93791183635525",
	["align-vertical-distribute-end"] = "rbxassetid://139354223511433",
	["align-vertical-distribute-start"] = "rbxassetid://74961997822126",
	["align-vertical-justify-center"] = "rbxassetid://134754696166569",
	["align-vertical-justify-end"] = "rbxassetid://92569381441969",
	["align-vertical-justify-start"] = "rbxassetid://99692844572718",
	["align-vertical-space-around"] = "rbxassetid://96206012459190",
	["align-vertical-space-between"] = "rbxassetid://124998077349706",
	["ambulance"] = "rbxassetid://78599995190651",
	["ampersand"] = "rbxassetid://75272915739209",
	["ampersands"] = "rbxassetid://126947193455996",
	["amphora"] = "rbxassetid://137370389604364",
	["anchor"] = "rbxassetid://92181172123618",
	["angry"] = "rbxassetid://74237056000103",
	["annoyed"] = "rbxassetid://80064369052011",
	["antenna"] = "rbxassetid://99628923540956",
	["anvil"] = "rbxassetid://100203029845919",
	["aperture"] = "rbxassetid://83396154449972",
	["app-window-mac"] = "rbxassetid://79587216113811",
	["app-window"] = "rbxassetid://93142176757189",
	["apple"] = "rbxassetid://104349242902442",
	["archive-restore"] = "rbxassetid://78956681942188",
	["archive-x"] = "rbxassetid://75830115088395",
	["archive"] = "rbxassetid://122180020814574",
	["armchair"] = "rbxassetid://105384358373973",
	["arrow-big-down-dash"] = "rbxassetid://137987229582002",
	["arrow-big-down"] = "rbxassetid://81081164158885",
	["arrow-big-left-dash"] = "rbxassetid://97827621354677",
	["arrow-big-left"] = "rbxassetid://85973092492641",
	["arrow-big-right-dash"] = "rbxassetid://117825834972403",
	["arrow-big-right"] = "rbxassetid://82960676755590",
	["arrow-big-up-dash"] = "rbxassetid://99260194327483",
	["arrow-big-up"] = "rbxassetid://93136954756149",
	["arrow-down-0-1"] = "rbxassetid://120961896217875",
	["arrow-down-1-0"] = "rbxassetid://93474255891850",
	["arrow-down-a-z"] = "rbxassetid://99554596207900",
	["arrow-down-from-line"] = "rbxassetid://132045845807798",
	["arrow-down-left"] = "rbxassetid://102899325237364",
	["arrow-down-narrow-wide"] = "rbxassetid://129105261655061",
	["arrow-down-right"] = "rbxassetid://123109928624974",
	["arrow-down-to-dot"] = "rbxassetid://101675355931221",
	["arrow-down-to-line"] = "rbxassetid://87050478931254",
	["arrow-down-up"] = "rbxassetid://85780258549577",
	["arrow-down-wide-narrow"] = "rbxassetid://88461733425991",
	["arrow-down-z-a"] = "rbxassetid://76115279362232",
	["arrow-down"] = "rbxassetid://98764963621439",
	["arrow-left-from-line"] = "rbxassetid://87857914437603",
	["arrow-left-right"] = "rbxassetid://131324733048447",
	["arrow-left-to-line"] = "rbxassetid://118645136026970",
	["arrow-left"] = "rbxassetid://102531941843733",
	["arrow-right-from-line"] = "rbxassetid://74073639809355",
	["arrow-right-left"] = "rbxassetid://77015754304300",
	["arrow-right-to-line"] = "rbxassetid://78632510329852",
	["arrow-right"] = "rbxassetid://113692007244654",
	["arrow-up-0-1"] = "rbxassetid://105257823943016",
	["arrow-up-1-0"] = "rbxassetid://134175521693798",
	["arrow-up-a-z"] = "rbxassetid://77763416595160",
	["arrow-up-down"] = "rbxassetid://81019887641527",
	["arrow-up-from-dot"] = "rbxassetid://124408496673275",
	["arrow-up-from-line"] = "rbxassetid://95777664626453",
	["arrow-up-left"] = "rbxassetid://123490598231261",
	["arrow-up-narrow-wide"] = "rbxassetid://73006024672636",
	["arrow-up-right"] = "rbxassetid://129280608535523",
	["arrow-up-to-line"] = "rbxassetid://108818207813537",
	["arrow-up-wide-narrow"] = "rbxassetid://87437426951568",
	["arrow-up-z-a"] = "rbxassetid://107546173611884",
	["arrow-up"] = "rbxassetid://89282378235317",
	["arrows-up-from-line"] = "rbxassetid://133710016938621",
	["asterisk"] = "rbxassetid://88552752106723",
	["at-sign"] = "rbxassetid://79059152889146",
	["atom"] = "rbxassetid://73167696981648",
	["audio-lines"] = "rbxassetid://70930641819242",
	["audio-waveform"] = "rbxassetid://86462036665209",
	["award"] = "rbxassetid://132740088158419",
	["axe"] = "rbxassetid://132405197863294",
	["axis-3d"] = "rbxassetid://122438676546804",
	["baby"] = "rbxassetid://93472926933440",
	["backpack"] = "rbxassetid://140420225386018",
	["badge-alert"] = "rbxassetid://101829200081951",
	["badge-cent"] = "rbxassetid://133345018873154",
	["badge-check"] = "rbxassetid://76078495178149",
	["badge-dollar-sign"] = "rbxassetid://127139803581141",
	["badge-euro"] = "rbxassetid://120016477674659",
	["badge-indian-rupee"] = "rbxassetid://75659682309981",
	["badge-info"] = "rbxassetid://131995373201472",
	["badge-japanese-yen"] = "rbxassetid://99081574588615",
	["badge-minus"] = "rbxassetid://140321561183881",
	["badge-percent"] = "rbxassetid://121359224294885",
	["badge-plus"] = "rbxassetid://100325578561866",
	["badge-pound-sterling"] = "rbxassetid://119688217279444",
	["badge-question-mark"] = "rbxassetid://121464963737502",
	["badge-russian-ruble"] = "rbxassetid://108839463659864",
	["badge-swiss-franc"] = "rbxassetid://91447608372740",
	["badge-turkish-lira"] = "rbxassetid://137839965873529",
	["badge-x"] = "rbxassetid://122931434733842",
	["badge"] = "rbxassetid://116620312917084",
	["baggage-claim"] = "rbxassetid://86922213051957",
	["ban"] = "rbxassetid://90767043015246",
	["banana"] = "rbxassetid://140713420056179",
	["bandage"] = "rbxassetid://129660129590770",
	["banknote-arrow-down"] = "rbxassetid://139366449345199",
	["banknote-arrow-up"] = "rbxassetid://133758343082529",
	["banknote-x"] = "rbxassetid://95348701438065",
	["banknote"] = "rbxassetid://104840231536668",
	["barcode"] = "rbxassetid://118473018143689",
	["barrel"] = "rbxassetid://130647115622774",
	["baseline"] = "rbxassetid://124677132511270",
	["bath"] = "rbxassetid://76031400297942",
	["battery-charging"] = "rbxassetid://80139357470047",
	["battery-full"] = "rbxassetid://70906718268972",
	["battery-low"] = "rbxassetid://139659256984314",
	["battery-medium"] = "rbxassetid://105934079398915",
	["battery-plus"] = "rbxassetid://91931341486966",
	["battery-warning"] = "rbxassetid://115230083817257",
	["battery"] = "rbxassetid://70765800346189",
	["beaker"] = "rbxassetid://80902539995520",
	["bean-off"] = "rbxassetid://98164436608714",
	["bean"] = "rbxassetid://89491967076869",
	["bed-double"] = "rbxassetid://73820193212911",
	["bed-single"] = "rbxassetid://113423940880634",
	["bed"] = "rbxassetid://97726529032925",
	["beef"] = "rbxassetid://105850162318915",
	["beer-off"] = "rbxassetid://120333134736361",
	["beer"] = "rbxassetid://116404978807744",
	["bell-dot"] = "rbxassetid://93161277118810",
	["bell-electric"] = "rbxassetid://100277767266983",
	["bell-minus"] = "rbxassetid://126334890449727",
	["bell-off"] = "rbxassetid://78560046118930",
	["bell-plus"] = "rbxassetid://77014333795836",
	["bell-ring"] = "rbxassetid://94612128913941",
	["bell"] = "rbxassetid://97392696311902",
	["between-horizontal-end"] = "rbxassetid://81602774794322",
	["between-horizontal-start"] = "rbxassetid://76112384929846",
	["between-vertical-end"] = "rbxassetid://72817612571631",
	["between-vertical-start"] = "rbxassetid://85278312190301",
	["biceps-flexed"] = "rbxassetid://82004462003936",
	["bike"] = "rbxassetid://102930322246035",
	["binary"] = "rbxassetid://91751953950088",
	["binoculars"] = "rbxassetid://101460003267896",
	["biohazard"] = "rbxassetid://95956532900432",
	["bird"] = "rbxassetid://132284145117371",
	["birdhouse"] = "rbxassetid://83999157401433",
	["bitcoin"] = "rbxassetid://95459240442938",
	["blend"] = "rbxassetid://111679612185257",
	["blinds"] = "rbxassetid://71164165283925",
	["blocks"] = "rbxassetid://72212693357737",
	["bluetooth-connected"] = "rbxassetid://96315134002985",
	["bluetooth-off"] = "rbxassetid://80600044218117",
	["bluetooth-searching"] = "rbxassetid://100673019606426",
	["bluetooth"] = "rbxassetid://90506573139443",
	["bold"] = "rbxassetid://116141470019166",
	["bolt"] = "rbxassetid://102881251417484",
	["bomb"] = "rbxassetid://139223800924636",
	["bone"] = "rbxassetid://111242153474115",
	["book-a"] = "rbxassetid://104067275658465",
	["book-alert"] = "rbxassetid://124159928044853",
	["book-audio"] = "rbxassetid://109208148317037",
	["book-check"] = "rbxassetid://115999656081696",
	["book-copy"] = "rbxassetid://108543407492005",
	["book-dashed"] = "rbxassetid://127430784795958",
	["book-down"] = "rbxassetid://101011730128222",
	["book-headphones"] = "rbxassetid://108670200799574",
	["book-heart"] = "rbxassetid://112788845135284",
	["book-image"] = "rbxassetid://80808285757226",
	["book-key"] = "rbxassetid://116024426170705",
	["book-lock"] = "rbxassetid://118765061220571",
	["book-marked"] = "rbxassetid://73211024251780",
	["book-minus"] = "rbxassetid://112724962046282",
	["book-open-check"] = "rbxassetid://130848362492667",
	["book-open-text"] = "rbxassetid://100629528672195",
	["book-open"] = "rbxassetid://129845326810392",
	["book-plus"] = "rbxassetid://140267785051233",
	["book-text"] = "rbxassetid://94011772484232",
	["book-type"] = "rbxassetid://97817304725443",
	["book-up-2"] = "rbxassetid://130161620853665",
	["book-up"] = "rbxassetid://98640174079190",
	["book-user"] = "rbxassetid://128489189240523",
	["book-x"] = "rbxassetid://118754548186537",
	["book"] = "rbxassetid://125383279695672",
	["bookmark-check"] = "rbxassetid://93940443347986",
	["bookmark-minus"] = "rbxassetid://96807096039910",
	["bookmark-plus"] = "rbxassetid://121469724491615",
	["bookmark-x"] = "rbxassetid://112272342584706",
	["bookmark"] = "rbxassetid://121093149326239",
	["boom-box"] = "rbxassetid://99901322535868",
	["bot-message-square"] = "rbxassetid://96145330292478",
	["bot-off"] = "rbxassetid://140417690560013",
	["bot"] = "rbxassetid://80451686744860",
	["bottle-wine"] = "rbxassetid://131675403196921",
	["bow-arrow"] = "rbxassetid://124089655150375",
	["box"] = "rbxassetid://101768155599700",
	["boxes"] = "rbxassetid://136372617578355",
	["braces"] = "rbxassetid://117761094704041",
	["brackets"] = "rbxassetid://74368995728099",
	["brain-circuit"] = "rbxassetid://70547962410202",
	["brain-cog"] = "rbxassetid://132039205501538",
	["brain"] = "rbxassetid://92424107303177",
	["brick-wall-fire"] = "rbxassetid://92980588705520",
	["brick-wall-shield"] = "rbxassetid://75954432775071",
	["brick-wall"] = "rbxassetid://112878522258821",
	["briefcase-business"] = "rbxassetid://129135125207283",
	["briefcase-conveyor-belt"] = "rbxassetid://108665725653714",
	["briefcase-medical"] = "rbxassetid://119917756334087",
	["briefcase"] = "rbxassetid://96754188164225",
	["bring-to-front"] = "rbxassetid://132975903553748",
	["brush-cleaning"] = "rbxassetid://71728977448805",
	["brush"] = "rbxassetid://127035535799640",
	["bubbles"] = "rbxassetid://106183424168227",
	["bug-off"] = "rbxassetid://88020025049245",
	["bug-play"] = "rbxassetid://80107955888092",
	["bug"] = "rbxassetid://83626408925438",
	["building-2"] = "rbxassetid://77873775611951",
	["building"] = "rbxassetid://110616258983082",
	["bus-front"] = "rbxassetid://89863432456045",
	["bus"] = "rbxassetid://133798469717463",
	["cable-car"] = "rbxassetid://128643682205596",
	["cable"] = "rbxassetid://128449944504901",
	["cake-slice"] = "rbxassetid://136769828413242",
	["cake"] = "rbxassetid://103131590503275",
	["calculator"] = "rbxassetid://74915716529646",
	["calendar-1"] = "rbxassetid://98458364171044",
	["calendar-arrow-down"] = "rbxassetid://108415736543437",
	["calendar-arrow-up"] = "rbxassetid://70574654109118",
	["calendar-check-2"] = "rbxassetid://120231170248276",
	["calendar-check"] = "rbxassetid://71551019465748",
	["calendar-clock"] = "rbxassetid://119132152594595",
	["calendar-cog"] = "rbxassetid://122402172360287",
	["calendar-days"] = "rbxassetid://99072017568595",
	["calendar-fold"] = "rbxassetid://117368871270394",
	["calendar-heart"] = "rbxassetid://88839008103676",
	["calendar-minus-2"] = "rbxassetid://98846170279891",
	["calendar-minus"] = "rbxassetid://137354318924383",
	["calendar-off"] = "rbxassetid://109726151749217",
	["calendar-plus-2"] = "rbxassetid://112264562093883",
	["calendar-plus"] = "rbxassetid://125266115249843",
	["calendar-range"] = "rbxassetid://103641849247576",
	["calendar-search"] = "rbxassetid://92010083223634",
	["calendar-sync"] = "rbxassetid://78082218499697",
	["calendar-x-2"] = "rbxassetid://107518051061147",
	["calendar-x"] = "rbxassetid://106703374806500",
	["calendar"] = "rbxassetid://114792700814035",
	["camera-off"] = "rbxassetid://81057636835256",
	["camera"] = "rbxassetid://79950339943067",
	["candy-cane"] = "rbxassetid://71689468772492",
	["candy-off"] = "rbxassetid://110232752314832",
	["candy"] = "rbxassetid://107812129154678",
	["cannabis"] = "rbxassetid://98792006538601",
	["captions-off"] = "rbxassetid://105223545364193",
	["captions"] = "rbxassetid://104960225031445",
	["car-front"] = "rbxassetid://87380942739063",
	["car-taxi-front"] = "rbxassetid://122455403384057",
	["car"] = "rbxassetid://121065933462582",
	["caravan"] = "rbxassetid://120070979471783",
	["card-sim"] = "rbxassetid://134490550095771",
	["carrot"] = "rbxassetid://119118221444304",
	["case-lower"] = "rbxassetid://129303130603241",
	["case-sensitive"] = "rbxassetid://125410273293056",
	["case-upper"] = "rbxassetid://111633433531325",
	["cassette-tape"] = "rbxassetid://137065788934157",
	["cast"] = "rbxassetid://98202245922071",
	["castle"] = "rbxassetid://119275077187784",
	["cat"] = "rbxassetid://124252153404931",
	["cctv"] = "rbxassetid://99979894766624",
	["chart-area"] = "rbxassetid://123446436762366",
	["chart-bar-big"] = "rbxassetid://72336824986044",
	["chart-bar-decreasing"] = "rbxassetid://107217459044963",
	["chart-bar-increasing"] = "rbxassetid://88268905998571",
	["chart-bar-stacked"] = "rbxassetid://98478751113024",
	["chart-bar"] = "rbxassetid://105389816384108",
	["chart-candlestick"] = "rbxassetid://125676898615697",
	["chart-column-big"] = "rbxassetid://98598733210787",
	["chart-column-decreasing"] = "rbxassetid://73586137373563",
	["chart-column-increasing"] = "rbxassetid://120421615068601",
	["chart-column-stacked"] = "rbxassetid://86031449675105",
	["chart-column"] = "rbxassetid://97915995538580",
	["chart-gantt"] = "rbxassetid://88811660555940",
	["chart-line"] = "rbxassetid://101833156055618",
	["chart-network"] = "rbxassetid://104027882693561",
	["chart-no-axes-column-decreasing"] = "rbxassetid://123371717192542",
	["chart-no-axes-column-increasing"] = "rbxassetid://140383830943049",
	["chart-no-axes-column"] = "rbxassetid://94078751170351",
	["chart-no-axes-combined"] = "rbxassetid://121424233161912",
	["chart-no-axes-gantt"] = "rbxassetid://131936541106368",
	["chart-pie"] = "rbxassetid://113412261630136",
	["chart-scatter"] = "rbxassetid://108217585014571",
	["chart-spline"] = "rbxassetid://90307460742494",
	["check-check"] = "rbxassetid://95183312173858",
	["check-line"] = "rbxassetid://115122343485290",
	["check"] = "rbxassetid://93898873302694",
	["chef-hat"] = "rbxassetid://121744015002573",
	["cherry"] = "rbxassetid://139519182403183",
	["chess-bishop"] = "rbxassetid://121701705580238",
	["chess-king"] = "rbxassetid://90885687223462",
	["chess-knight"] = "rbxassetid://96467707042169",
	["chess-pawn"] = "rbxassetid://111318574652751",
	["chess-queen"] = "rbxassetid://98304702099749",
	["chess-rook"] = "rbxassetid://76223925830262",
	["chevron-down"] = "rbxassetid://134243273101015",
	["chevron-first"] = "rbxassetid://105243363790238",
	["chevron-last"] = "rbxassetid://89268452603731",
	["chevron-left"] = "rbxassetid://73780377692148",
	["chevron-right"] = "rbxassetid://92473583511724",
	["chevron-up"] = "rbxassetid://122444883127455",
	["chevrons-down-up"] = "rbxassetid://139404716013205",
	["chevrons-down"] = "rbxassetid://100524612205956",
	["chevrons-left-right-ellipsis"] = "rbxassetid://125035817741526",
	["chevrons-left-right"] = "rbxassetid://87910685945204",
	["chevrons-left"] = "rbxassetid://82617201744347",
	["chevrons-right-left"] = "rbxassetid://87149546686569",
	["chevrons-right"] = "rbxassetid://139121276490483",
	["chevrons-up-down"] = "rbxassetid://131833120209646",
	["chevrons-up"] = "rbxassetid://100467452364672",
	["chromium"] = "rbxassetid://128165143739006",
	["church"] = "rbxassetid://113714744350666",
	["cigarette-off"] = "rbxassetid://77797883078452",
	["circle-alert"] = "rbxassetid://83898160590116",
	["circle-arrow-down"] = "rbxassetid://95901860261344",
	["circle-arrow-left"] = "rbxassetid://102148876968988",
	["circle-arrow-out-down-left"] = "rbxassetid://140598097856694",
	["circle-arrow-out-down-right"] = "rbxassetid://119952801379305",
	["circle-arrow-out-up-left"] = "rbxassetid://132858212688303",
	["circle-arrow-out-up-right"] = "rbxassetid://81783743753173",
	["circle-arrow-right"] = "rbxassetid://70786767999559",
	["circle-arrow-up"] = "rbxassetid://84395128546494",
	["circle-check-big"] = "rbxassetid://93202927221730",
	["circle-check"] = "rbxassetid://85262178816537",
	["circle-chevron-down"] = "rbxassetid://137069490345718",
	["circle-chevron-left"] = "rbxassetid://130250009740827",
	["circle-chevron-right"] = "rbxassetid://125943696958495",
	["circle-chevron-up"] = "rbxassetid://111223574026321",
	["circle-dashed"] = "rbxassetid://126799443883746",
	["circle-divide"] = "rbxassetid://106398997754208",
	["circle-dollar-sign"] = "rbxassetid://91106238890387",
	["circle-dot-dashed"] = "rbxassetid://111451232827180",
	["circle-dot"] = "rbxassetid://82947033619201",
	["circle-ellipsis"] = "rbxassetid://91687150884779",
	["circle-equal"] = "rbxassetid://95133963751438",
	["circle-fading-arrow-up"] = "rbxassetid://104648212910336",
	["circle-fading-plus"] = "rbxassetid://91847890443490",
	["circle-gauge"] = "rbxassetid://108157549473765",
	["circle-minus"] = "rbxassetid://133556159576809",
	["circle-off"] = "rbxassetid://97923456918886",
	["circle-parking-off"] = "rbxassetid://128369410981252",
	["circle-parking"] = "rbxassetid://124034962915196",
	["circle-pause"] = "rbxassetid://139337739700879",
	["circle-percent"] = "rbxassetid://133311912860256",
	["circle-play"] = "rbxassetid://120408917249739",
	["circle-plus"] = "rbxassetid://113157136350384",
	["circle-pound-sterling"] = "rbxassetid://105476153083828",
	["circle-power"] = "rbxassetid://140676030155098",
	["circle-question-mark"] = "rbxassetid://97516698664325",
	["circle-slash-2"] = "rbxassetid://136766902186549",
	["circle-slash"] = "rbxassetid://125206439913049",
	["circle-small"] = "rbxassetid://73685402843600",
	["circle-star"] = "rbxassetid://120318414957104",
	["circle-stop"] = "rbxassetid://87400503942659",
	["circle-user-round"] = "rbxassetid://95489465399880",
	["circle-user"] = "rbxassetid://136220511671311",
	["circle-x"] = "rbxassetid://76821953846248",
	["circle"] = "rbxassetid://130359823580534",
	["circuit-board"] = "rbxassetid://107695264369312",
	["citrus"] = "rbxassetid://139018222976433",
	["clapperboard"] = "rbxassetid://132660667070200",
	["clipboard-check"] = "rbxassetid://92649798577170",
	["clipboard-clock"] = "rbxassetid://123957515687745",
	["clipboard-copy"] = "rbxassetid://125851897718493",
	["clipboard-list"] = "rbxassetid://96460215958908",
	["clipboard-minus"] = "rbxassetid://107968008485671",
	["clipboard-paste"] = "rbxassetid://74382068849983",
	["clipboard-pen-line"] = "rbxassetid://77711589791615",
	["clipboard-pen"] = "rbxassetid://75290966822953",
	["clipboard-plus"] = "rbxassetid://134285318675662",
	["clipboard-type"] = "rbxassetid://89949374318028",
	["clipboard-x"] = "rbxassetid://102222456890103",
	["clipboard"] = "rbxassetid://89601995828423",
	["clock-1"] = "rbxassetid://129363225422045",
	["clock-10"] = "rbxassetid://104332695855541",
	["clock-11"] = "rbxassetid://119023205186105",
	["clock-12"] = "rbxassetid://117789618723068",
	["clock-2"] = "rbxassetid://134710777209413",
	["clock-3"] = "rbxassetid://136385631189327",
	["clock-4"] = "rbxassetid://121808839832144",
	["clock-5"] = "rbxassetid://85082019959457",
	["clock-6"] = "rbxassetid://71009733505593",
	["clock-7"] = "rbxassetid://103111188546225",
	["clock-8"] = "rbxassetid://110059272125337",
	["clock-9"] = "rbxassetid://77610027126437",
	["clock-alert"] = "rbxassetid://97157344465162",
	["clock-arrow-down"] = "rbxassetid://92349314416042",
	["clock-arrow-up"] = "rbxassetid://111484286332629",
	["clock-check"] = "rbxassetid://85231630218857",
	["clock-fading"] = "rbxassetid://93205297285245",
	["clock-plus"] = "rbxassetid://93367709263150",
	["clock"] = "rbxassetid://121808839832144",
	["closed-caption"] = "rbxassetid://99832644030788",
	["cloud-alert"] = "rbxassetid://91967273658626",
	["cloud-check"] = "rbxassetid://97318598202432",
	["cloud-cog"] = "rbxassetid://96497764065749",
	["cloud-download"] = "rbxassetid://121435581993566",
	["cloud-drizzle"] = "rbxassetid://139525315752605",
	["cloud-fog"] = "rbxassetid://76650233148776",
	["cloud-hail"] = "rbxassetid://72320462748242",
	["cloud-lightning"] = "rbxassetid://133517088924849",
	["cloud-moon-rain"] = "rbxassetid://127667837827018",
	["cloud-moon"] = "rbxassetid://71938114737914",
	["cloud-off"] = "rbxassetid://131907154501444",
	["cloud-rain-wind"] = "rbxassetid://107414583736721",
	["cloud-rain"] = "rbxassetid://105547081967408",
	["cloud-snow"] = "rbxassetid://72307126270226",
	["cloud-sun-rain"] = "rbxassetid://99041604425705",
	["cloud-sun"] = "rbxassetid://86114208148727",
	["cloud-upload"] = "rbxassetid://93307473217005",
	["cloud"] = "rbxassetid://121226497050352",
	["cloudy"] = "rbxassetid://105360479023346",
	["clover"] = "rbxassetid://74925550436750",
	["club"] = "rbxassetid://108490365816628",
	["code-xml"] = "rbxassetid://130150477351734",
	["code"] = "rbxassetid://107380207681249",
	["codepen"] = "rbxassetid://135643965971885",
	["codesandbox"] = "rbxassetid://106911852964823",
	["coffee"] = "rbxassetid://106864403231093",
	["cog"] = "rbxassetid://116544501716299",
	["coins"] = "rbxassetid://116510979641930",
	["columns-2"] = "rbxassetid://113004100221850",
	["columns-3-cog"] = "rbxassetid://121589691981064",
	["columns-3"] = "rbxassetid://115223357399375",
	["columns-4"] = "rbxassetid://130807991968419",
	["combine"] = "rbxassetid://79908476334048",
	["command"] = "rbxassetid://93648221906330",
	["compass"] = "rbxassetid://115123411028382",
	["component"] = "rbxassetid://110027788875080",
	["computer"] = "rbxassetid://77480056459407",
	["concierge-bell"] = "rbxassetid://140384259310436",
	["cone"] = "rbxassetid://97759550688437",
	["construction"] = "rbxassetid://106539489968173",
	["contact-round"] = "rbxassetid://71907624112229",
	["contact"] = "rbxassetid://75868297719012",
	["container"] = "rbxassetid://91507237573499",
	["contrast"] = "rbxassetid://112796643981497",
	["cookie"] = "rbxassetid://73159504540002",
	["cooking-pot"] = "rbxassetid://94959783129799",
	["copy-check"] = "rbxassetid://91177247988892",
	["copy-minus"] = "rbxassetid://109524509933035",
	["copy-plus"] = "rbxassetid://113618379616952",
	["copy-slash"] = "rbxassetid://93805787810390",
	["copy-x"] = "rbxassetid://106557557978061",
	["copy"] = "rbxassetid://78979572434545",
	["copyleft"] = "rbxassetid://78559055698593",
	["copyright"] = "rbxassetid://129433635747111",
	["corner-down-left"] = "rbxassetid://90473561177832",
	["corner-down-right"] = "rbxassetid://86512767702085",
	["corner-left-down"] = "rbxassetid://139876989150630",
	["corner-left-up"] = "rbxassetid://126228268096099",
	["corner-right-down"] = "rbxassetid://89237035551302",
	["corner-right-up"] = "rbxassetid://112851237026705",
	["corner-up-left"] = "rbxassetid://84669279763024",
	["corner-up-right"] = "rbxassetid://115099889693145",
	["cpu"] = "rbxassetid://77549309870247",
	["creative-commons"] = "rbxassetid://90408210735312",
	["credit-card"] = "rbxassetid://99163352872346",
	["croissant"] = "rbxassetid://130710485559420",
	["crop"] = "rbxassetid://116344601101413",
	["cross"] = "rbxassetid://101833377863588",
	["crosshair"] = "rbxassetid://134242818164054",
	["crown"] = "rbxassetid://127843403295538",
	["cuboid"] = "rbxassetid://75618807946111",
	["cup-soda"] = "rbxassetid://121098640829562",
	["currency"] = "rbxassetid://90551250119972",
	["cylinder"] = "rbxassetid://90569677179169",
	["dam"] = "rbxassetid://76874486231393",
	["database-backup"] = "rbxassetid://103403210984699",
	["database-zap"] = "rbxassetid://131199921258418",
	["database"] = "rbxassetid://126791525623846",
	["decimals-arrow-left"] = "rbxassetid://120198500638749",
	["decimals-arrow-right"] = "rbxassetid://118263047146797",
	["delete"] = "rbxassetid://126279426372342",
	["dessert"] = "rbxassetid://71508133278830",
	["diameter"] = "rbxassetid://97429051503783",
	["diamond-minus"] = "rbxassetid://128989071438290",
	["diamond-percent"] = "rbxassetid://107717860105959",
	["diamond-plus"] = "rbxassetid://134701163723675",
	["diamond"] = "rbxassetid://105846996304890",
	["dice-1"] = "rbxassetid://112650149591038",
	["dice-2"] = "rbxassetid://112278274566793",
	["dice-3"] = "rbxassetid://118526270626312",
	["dice-4"] = "rbxassetid://113365650364004",
	["dice-5"] = "rbxassetid://72768312430593",
	["dice-6"] = "rbxassetid://85376239182543",
	["dices"] = "rbxassetid://81268120302865",
	["diff"] = "rbxassetid://135052708609715",
	["disc-2"] = "rbxassetid://91419420404185",
	["disc-3"] = "rbxassetid://135470554736048",
	["disc-album"] = "rbxassetid://74693460404344",
	["disc"] = "rbxassetid://101908120120777",
	["divide"] = "rbxassetid://136678191878278",
	["dna-off"] = "rbxassetid://89612426361540",
	["dna"] = "rbxassetid://74007982981741",
	["dock"] = "rbxassetid://121997427160252",
	["dog"] = "rbxassetid://71920105558570",
	["dollar-sign"] = "rbxassetid://127320961224019",
	["donut"] = "rbxassetid://72204922742657",
	["door-closed-locked"] = "rbxassetid://74027613267551",
	["door-closed"] = "rbxassetid://136249099949073",
	["door-open"] = "rbxassetid://91306356501736",
	["dot"] = "rbxassetid://137321056643916",
	["download"] = "rbxassetid://134814648082393",
	["drafting-compass"] = "rbxassetid://99701976182841",
	["drama"] = "rbxassetid://110297795801577",
	["dribbble"] = "rbxassetid://80231809663849",
	["drill"] = "rbxassetid://108644821412796",
	["drone"] = "rbxassetid://117299095794783",
	["droplet-off"] = "rbxassetid://119365002225172",
	["droplet"] = "rbxassetid://100597455015098",
	["droplets"] = "rbxassetid://140111846025180",
	["drum"] = "rbxassetid://136979060344890",
	["drumstick"] = "rbxassetid://104662462521709",
	["dumbbell"] = "rbxassetid://80277236776212",
	["ear-off"] = "rbxassetid://87421916192807",
	["ear"] = "rbxassetid://121894949934209",
	["earth-lock"] = "rbxassetid://88814147073745",
	["earth"] = "rbxassetid://76231597751076",
	["eclipse"] = "rbxassetid://114829622118222",
	["egg-fried"] = "rbxassetid://90622538210545",
	["egg-off"] = "rbxassetid://92288321309285",
	["egg"] = "rbxassetid://117851493400222",
	["ellipsis-vertical"] = "rbxassetid://117978708573781",
	["ellipsis"] = "rbxassetid://140019550645825",
	["equal-approximately"] = "rbxassetid://105382689698323",
	["equal-not"] = "rbxassetid://76864449458032",
	["equal"] = "rbxassetid://123467780715624",
	["eraser"] = "rbxassetid://133957773112410",
	["ethernet-port"] = "rbxassetid://75391715149314",
	["euro"] = "rbxassetid://72229646524456",
	["ev-charger"] = "rbxassetid://97906158859623",
	["expand"] = "rbxassetid://137492887754537",
	["external-link"] = "rbxassetid://129331830773832",
	["eye-closed"] = "rbxassetid://111063268625789",
	["eye-off"] = "rbxassetid://135928786788378",
	["eye"] = "rbxassetid://100033680381365",
	["facebook"] = "rbxassetid://72098528632192",
	["factory"] = "rbxassetid://102170024318039",
	["fan"] = "rbxassetid://78391400440696",
	["fast-forward"] = "rbxassetid://121615540167909",
	["feather"] = "rbxassetid://91872927606406",
	["fence"] = "rbxassetid://123451565578029",
	["ferris-wheel"] = "rbxassetid://79729205796176",
	["figma"] = "rbxassetid://134182122852301",
	["file-archive"] = "rbxassetid://77018106869967",
	["file-axis-3d"] = "rbxassetid://133912328009885",
	["file-badge"] = "rbxassetid://74564895394477",
	["file-box"] = "rbxassetid://119264004071690",
	["file-braces-corner"] = "rbxassetid://77253337986109",
	["file-braces"] = "rbxassetid://95314128621234",
	["file-chart-column-increasing"] = "rbxassetid://134449481172067",
	["file-chart-column"] = "rbxassetid://82048481252560",
	["file-chart-line"] = "rbxassetid://71954360551345",
	["file-chart-pie"] = "rbxassetid://81072193564497",
	["file-check-corner"] = "rbxassetid://76295552859171",
	["file-check"] = "rbxassetid://82604001452455",
	["file-clock"] = "rbxassetid://102325208830990",
	["file-code-corner"] = "rbxassetid://78293841184371",
	["file-code"] = "rbxassetid://130978036895504",
	["file-cog"] = "rbxassetid://101385347151368",
	["file-diff"] = "rbxassetid://96147216772241",
	["file-digit"] = "rbxassetid://89220220354580",
	["file-down"] = "rbxassetid://120650154178290",
	["file-exclamation-point"] = "rbxassetid://102821865889635",
	["file-headphone"] = "rbxassetid://100533735901986",
	["file-heart"] = "rbxassetid://132214916401696",
	["file-image"] = "rbxassetid://123334057511782",
	["file-input"] = "rbxassetid://124728604166044",
	["file-key"] = "rbxassetid://118790255921100",
	["file-lock"] = "rbxassetid://72170228691242",
	["file-minus-corner"] = "rbxassetid://119263271735124",
	["file-minus"] = "rbxassetid://111014798459222",
	["file-music"] = "rbxassetid://134948051536671",
	["file-output"] = "rbxassetid://92146832572911",
	["file-pen-line"] = "rbxassetid://104622936345006",
	["file-pen"] = "rbxassetid://79556179730240",
	["file-play"] = "rbxassetid://89006821567838",
	["file-plus-corner"] = "rbxassetid://76544604043974",
	["file-plus"] = "rbxassetid://78881710800060",
	["file-question-mark"] = "rbxassetid://127617422859576",
	["file-scan"] = "rbxassetid://129480105228213",
	["file-search-corner"] = "rbxassetid://90974165234008",
	["file-search"] = "rbxassetid://97780235974933",
	["file-signal"] = "rbxassetid://122070252538165",
	["file-sliders"] = "rbxassetid://85787771732439",
	["file-spreadsheet"] = "rbxassetid://134501869359270",
	["file-stack"] = "rbxassetid://138929929862605",
	["file-symlink"] = "rbxassetid://91865722036510",
	["file-terminal"] = "rbxassetid://116757454755476",
	["file-text"] = "rbxassetid://90496405707281",
	["file-type-corner"] = "rbxassetid://124902230275209",
	["file-type"] = "rbxassetid://115272552799361",
	["file-up"] = "rbxassetid://131173039312748",
	["file-user"] = "rbxassetid://99552018455009",
	["file-video-camera"] = "rbxassetid://81719056173960",
	["file-volume"] = "rbxassetid://111264764438958",
	["file-x-corner"] = "rbxassetid://87554136773609",
	["file-x"] = "rbxassetid://107333775515154",
	["file"] = "rbxassetid://74748492079329",
	["files"] = "rbxassetid://102806336233202",
	["film"] = "rbxassetid://120978945609706",
	["fingerprint"] = "rbxassetid://112173305232811",
	["fire-extinguisher"] = "rbxassetid://111643493006960",
	["fish-off"] = "rbxassetid://89756724887508",
	["fish-symbol"] = "rbxassetid://118475177681618",
	["fish"] = "rbxassetid://124360663785796",
	["flag-off"] = "rbxassetid://112944528856799",
	["flag-triangle-left"] = "rbxassetid://88045221285272",
	["flag-triangle-right"] = "rbxassetid://108292480304566",
	["flag"] = "rbxassetid://78183383236196",
	["flame-kindling"] = "rbxassetid://139728976917928",
	["flame"] = "rbxassetid://98218034436456",
	["flashlight-off"] = "rbxassetid://79780362871740",
	["flashlight"] = "rbxassetid://100286985600444",
	["flask-conical-off"] = "rbxassetid://112597970025298",
	["flask-conical"] = "rbxassetid://128406680901165",
	["flask-round"] = "rbxassetid://127508287324940",
	["flip-horizontal-2"] = "rbxassetid://103726993598186",
	["flip-horizontal"] = "rbxassetid://122937530107837",
	["flip-vertical-2"] = "rbxassetid://103836358956328",
	["flip-vertical"] = "rbxassetid://108003917346888",
	["flower-2"] = "rbxassetid://72934574245145",
	["flower"] = "rbxassetid://86129438272762",
	["focus"] = "rbxassetid://87493973153317",
	["fold-horizontal"] = "rbxassetid://92835712442240",
	["fold-vertical"] = "rbxassetid://108873727253656",
	["folder-archive"] = "rbxassetid://97312009460206",
	["folder-check"] = "rbxassetid://128492920904557",
	["folder-clock"] = "rbxassetid://111964836738545",
	["folder-closed"] = "rbxassetid://118286209350843",
	["folder-code"] = "rbxassetid://70624096349370",
	["folder-cog"] = "rbxassetid://85299519462846",
	["folder-dot"] = "rbxassetid://138687772725278",
	["folder-down"] = "rbxassetid://118044108459225",
	["folder-git-2"] = "rbxassetid://101394054141166",
	["folder-git"] = "rbxassetid://121885778095158",
	["folder-heart"] = "rbxassetid://79104747211105",
	["folder-input"] = "rbxassetid://90699920697871",
	["folder-kanban"] = "rbxassetid://78313285104072",
	["folder-key"] = "rbxassetid://85270407596791",
	["folder-lock"] = "rbxassetid://119201572260567",
	["folder-minus"] = "rbxassetid://85648718999010",
	["folder-open-dot"] = "rbxassetid://74741494767354",
	["folder-open"] = "rbxassetid://76018996254888",
	["folder-output"] = "rbxassetid://101532447937612",
	["folder-pen"] = "rbxassetid://112770491173911",
	["folder-plus"] = "rbxassetid://91865663406119",
	["folder-root"] = "rbxassetid://103333751154693",
	["folder-search-2"] = "rbxassetid://71276453442655",
	["folder-search"] = "rbxassetid://110568075123861",
	["folder-symlink"] = "rbxassetid://127485747227189",
	["folder-sync"] = "rbxassetid://91544602659796",
	["folder-tree"] = "rbxassetid://85577554337861",
	["folder-up"] = "rbxassetid://72008269765857",
	["folder-x"] = "rbxassetid://91699618247635",
	["folder"] = "rbxassetid://80846616596607",
	["folders"] = "rbxassetid://110351216219061",
	["footprints"] = "rbxassetid://139192589041315",
	["forklift"] = "rbxassetid://72030930983101",
	["forward"] = "rbxassetid://97545944739523",
	["frame"] = "rbxassetid://109080612832751",
	["framer"] = "rbxassetid://108384807262391",
	["frown"] = "rbxassetid://124407301067982",
	["fuel"] = "rbxassetid://106447647274511",
	["fullscreen"] = "rbxassetid://77793665526178",
	["funnel-plus"] = "rbxassetid://100780233821928",
	["funnel-x"] = "rbxassetid://70984385812555",
	["funnel"] = "rbxassetid://108829540827529",
	["gallery-horizontal-end"] = "rbxassetid://74672430161161",
	["gallery-horizontal"] = "rbxassetid://80004001442122",
	["gallery-thumbnails"] = "rbxassetid://136219289862706",
	["gallery-vertical-end"] = "rbxassetid://106461402088317",
	["gallery-vertical"] = "rbxassetid://119299431466725",
	["gamepad-2"] = "rbxassetid://92483947987410",
	["gamepad-directional"] = "rbxassetid://84342305212226",
	["gamepad"] = "rbxassetid://121607283959010",
	["gauge"] = "rbxassetid://110273524101447",
	["gavel"] = "rbxassetid://78952298198456",
	["gem"] = "rbxassetid://112904952151156",
	["georgian-lari"] = "rbxassetid://98084432591687",
	["ghost"] = "rbxassetid://113822048130017",
	["gift"] = "rbxassetid://109855212076373",
	["git-branch-minus"] = "rbxassetid://97385010649411",
	["git-branch-plus"] = "rbxassetid://125944221134316",
	["git-branch"] = "rbxassetid://90490195516649",
	["git-commit-horizontal"] = "rbxassetid://133646041800147",
	["git-commit-vertical"] = "rbxassetid://122098032990350",
	["git-compare-arrows"] = "rbxassetid://84874426520216",
	["git-compare"] = "rbxassetid://91945124438792",
	["git-fork"] = "rbxassetid://89954992404765",
	["git-graph"] = "rbxassetid://86166832019304",
	["git-merge"] = "rbxassetid://131833355158059",
	["git-pull-request-arrow"] = "rbxassetid://94507974577439",
	["git-pull-request-closed"] = "rbxassetid://78070600389091",
	["git-pull-request-create-arrow"] = "rbxassetid://127422677061091",
	["git-pull-request-create"] = "rbxassetid://105929577383926",
	["git-pull-request-draft"] = "rbxassetid://76173459869943",
	["git-pull-request"] = "rbxassetid://138463010991471",
	["github"] = "rbxassetid://120349554354380",
	["gitlab"] = "rbxassetid://114054627192933",
	["glass-water"] = "rbxassetid://115526102400988",
	["glasses"] = "rbxassetid://87936407455373",
	["globe-lock"] = "rbxassetid://134065526704402",
	["globe"] = "rbxassetid://114238209622913",
	["goal"] = "rbxassetid://120517954878160",
	["gpu"] = "rbxassetid://95577823614219",
	["graduation-cap"] = "rbxassetid://93771896340220",
	["grape"] = "rbxassetid://134760640415561",
	["grid-2x2-check"] = "rbxassetid://138468840220821",
	["grid-2x2-plus"] = "rbxassetid://91811610580247",
	["grid-2x2-x"] = "rbxassetid://72407303981388",
	["grid-2x2"] = "rbxassetid://99050491897640",
	["grid-3x2"] = "rbxassetid://95528684210010",
	["grid-3x3"] = "rbxassetid://70419024781206",
	["grip-horizontal"] = "rbxassetid://136255899715930",
	["grip-vertical"] = "rbxassetid://137183678565296",
	["grip"] = "rbxassetid://109058783556768",
	["group"] = "rbxassetid://107643418926671",
	["guitar"] = "rbxassetid://75915531867926",
	["ham"] = "rbxassetid://74465607934635",
	["hamburger"] = "rbxassetid://93086916815495",
	["hammer"] = "rbxassetid://83545120140895",
	["hand-coins"] = "rbxassetid://126990543175462",
	["hand-fist"] = "rbxassetid://83341608917591",
	["hand-grab"] = "rbxassetid://88867162163985",
	["hand-heart"] = "rbxassetid://117507367668412",
	["hand-helping"] = "rbxassetid://89897738419446",
	["hand-metal"] = "rbxassetid://113619498548713",
	["hand-platter"] = "rbxassetid://88594727743168",
	["hand"] = "rbxassetid://130703864968637",
	["handbag"] = "rbxassetid://135675846264061",
	["handshake"] = "rbxassetid://78442115255814",
	["hard-drive-download"] = "rbxassetid://73913801230614",
	["hard-drive-upload"] = "rbxassetid://85762133615118",
	["hard-drive"] = "rbxassetid://88183305858463",
	["hard-hat"] = "rbxassetid://128050846767382",
	["hash"] = "rbxassetid://82890331678520",
	["hat-glasses"] = "rbxassetid://101165538224815",
	["haze"] = "rbxassetid://108857561768901",
	["hdmi-port"] = "rbxassetid://103693661037020",
	["heading-1"] = "rbxassetid://118129315662110",
	["heading-2"] = "rbxassetid://110209069670094",
	["heading-3"] = "rbxassetid://90267885237062",
	["heading-4"] = "rbxassetid://129625620307602",
	["heading-5"] = "rbxassetid://120386663181267",
	["heading-6"] = "rbxassetid://90959079775093",
	["heading"] = "rbxassetid://129254312067735",
	["headphone-off"] = "rbxassetid://85038251615641",
	["headphones"] = "rbxassetid://118833729589183",
	["headset"] = "rbxassetid://129269236787694",
	["heart-crack"] = "rbxassetid://110987638564119",
	["heart-handshake"] = "rbxassetid://111483078692002",
	["heart-minus"] = "rbxassetid://96827380163326",
	["heart-off"] = "rbxassetid://89748414415617",
	["heart-plus"] = "rbxassetid://94877796283249",
	["heart-pulse"] = "rbxassetid://129352925579546",
	["heart"] = "rbxassetid://116559368303288",
	["heater"] = "rbxassetid://140478466880916",
	["helicopter"] = "rbxassetid://111557171735930",
	["hexagon"] = "rbxassetid://127592089339199",
	["highlighter"] = "rbxassetid://77411555641113",
	["history"] = "rbxassetid://123980022019922",
	["hop-off"] = "rbxassetid://103386036934034",
	["hop"] = "rbxassetid://82778923997672",
	["hospital"] = "rbxassetid://105868763850707",
	["hotel"] = "rbxassetid://132283390859718",
	["hourglass"] = "rbxassetid://86160434939203",
	["house-heart"] = "rbxassetid://136054771868597",
	["house-plug"] = "rbxassetid://71438263712075",
	["house-plus"] = "rbxassetid://118495165208309",
	["house-wifi"] = "rbxassetid://126495519725698",
	["house"] = "rbxassetid://98755624629571",
	["ice-cream-bowl"] = "rbxassetid://124867218454386",
	["ice-cream-cone"] = "rbxassetid://90751397288639",
	["id-card-lanyard"] = "rbxassetid://90761480469224",
	["id-card"] = "rbxassetid://75354294622640",
	["image-down"] = "rbxassetid://78972295741235",
	["image-minus"] = "rbxassetid://101066016918565",
	["image-off"] = "rbxassetid://81934811700938",
	["image-play"] = "rbxassetid://129501806784210",
	["image-plus"] = "rbxassetid://70391970623917",
	["image-up"] = "rbxassetid://126610009605241",
	["image-upscale"] = "rbxassetid://106963545024679",
	["images"] = "rbxassetid://79350649395557",
	["import"] = "rbxassetid://116545008906029",
	["inbox"] = "rbxassetid://112591360302868",
	["indian-rupee"] = "rbxassetid://113038778381805",
	["infinity"] = "rbxassetid://98083086936965",
	["info"] = "rbxassetid://124560466474914",
	["inspection-panel"] = "rbxassetid://70905313146088",
	["instagram"] = "rbxassetid://119864798614855",
	["italic"] = "rbxassetid://96220378864282",
	["iteration-ccw"] = "rbxassetid://140221832794083",
	["iteration-cw"] = "rbxassetid://95534489554662",
	["japanese-yen"] = "rbxassetid://106362863465813",
	["joystick"] = "rbxassetid://99416790224739",
	["kanban"] = "rbxassetid://125934100055431",
	["kayak"] = "rbxassetid://136107544609389",
	["key-round"] = "rbxassetid://83619031955390",
	["key-square"] = "rbxassetid://94621420033649",
	["key"] = "rbxassetid://96510194465420",
	["keyboard-music"] = "rbxassetid://121058541758636",
	["keyboard-off"] = "rbxassetid://92466375369772",
	["keyboard"] = "rbxassetid://121474456068237",
	["lamp-ceiling"] = "rbxassetid://80032758469141",
	["lamp-desk"] = "rbxassetid://85290686983238",
	["lamp-floor"] = "rbxassetid://104585881375892",
	["lamp-wall-down"] = "rbxassetid://91271394132073",
	["lamp-wall-up"] = "rbxassetid://132141464337445",
	["lamp"] = "rbxassetid://110730830653382",
	["land-plot"] = "rbxassetid://96449039620294",
	["landmark"] = "rbxassetid://76885079756393",
	["languages"] = "rbxassetid://90816903776498",
	["laptop-minimal-check"] = "rbxassetid://114352019833865",
	["laptop-minimal"] = "rbxassetid://136705765566068",
	["laptop"] = "rbxassetid://111387063244975",
	["lasso-select"] = "rbxassetid://105609719912753",
	["lasso"] = "rbxassetid://121072936884007",
	["laugh"] = "rbxassetid://104491311361166",
	["layers-2"] = "rbxassetid://70536710516357",
	["layers"] = "rbxassetid://81973586053257",
	["layout-dashboard"] = "rbxassetid://139929981863901",
	["layout-grid"] = "rbxassetid://81344910161871",
	["layout-list"] = "rbxassetid://87462136296578",
	["layout-panel-left"] = "rbxassetid://125092469751491",
	["layout-panel-top"] = "rbxassetid://91943941515944",
	["layout-template"] = "rbxassetid://115564446417985",
	["leaf"] = "rbxassetid://119951075637174",
	["leafy-green"] = "rbxassetid://105146290493154",
	["lectern"] = "rbxassetid://106166425183862",
	["library-big"] = "rbxassetid://106794530191412",
	["library"] = "rbxassetid://114334671982047",
	["life-buoy"] = "rbxassetid://81168450671956",
	["ligature"] = "rbxassetid://111397873269411",
	["lightbulb-off"] = "rbxassetid://83795722296178",
	["lightbulb"] = "rbxassetid://103871245626488",
	["line-squiggle"] = "rbxassetid://109555164424447",
	["link-2-off"] = "rbxassetid://76885956296867",
	["link-2"] = "rbxassetid://86072351557466",
	["link"] = "rbxassetid://131607023382430",
	["linkedin"] = "rbxassetid://132842789255788",
	["list-check"] = "rbxassetid://72374358471156",
	["list-checks"] = "rbxassetid://99809353635593",
	["list-chevrons-down-up"] = "rbxassetid://137409641500711",
	["list-chevrons-up-down"] = "rbxassetid://81825351389084",
	["list-collapse"] = "rbxassetid://124505247702401",
	["list-end"] = "rbxassetid://77650610048119",
	["list-filter-plus"] = "rbxassetid://96385120752336",
	["list-filter"] = "rbxassetid://103321376129527",
	["list-indent-decrease"] = "rbxassetid://137879979228193",
	["list-indent-increase"] = "rbxassetid://79051053161201",
	["list-minus"] = "rbxassetid://138507965142671",
	["list-music"] = "rbxassetid://126380635781840",
	["list-ordered"] = "rbxassetid://83212528113913",
	["list-plus"] = "rbxassetid://112384738137814",
	["list-restart"] = "rbxassetid://91703153577421",
	["list-start"] = "rbxassetid://84828348299727",
	["list-todo"] = "rbxassetid://132980603752108",
	["list-tree"] = "rbxassetid://97685396239010",
	["list-video"] = "rbxassetid://93648525452489",
	["list-x"] = "rbxassetid://113025303988861",
	["list"] = "rbxassetid://113179976918783",
	["loader-circle"] = "rbxassetid://116535712789945",
	["loader-pinwheel"] = "rbxassetid://108513357940900",
	["loader"] = "rbxassetid://78408734580845",
	["locate-fixed"] = "rbxassetid://137367361548433",
	["locate-off"] = "rbxassetid://73729216338137",
	["locate"] = "rbxassetid://84467676590391",
	["lock-keyhole-open"] = "rbxassetid://110863509313073",
	["lock-keyhole"] = "rbxassetid://78672912777756",
	["lock-open"] = "rbxassetid://93597915325122",
	["lock"] = "rbxassetid://134724289526879",
	["log-in"] = "rbxassetid://103768533135201",
	["log-out"] = "rbxassetid://84895399304975",
	["logs"] = "rbxassetid://89772091251787",
	["lollipop"] = "rbxassetid://84681611583044",
	["luggage"] = "rbxassetid://76619236486400",
	["magnet"] = "rbxassetid://135162361226972",
	["mail-check"] = "rbxassetid://86921536259917",
	["mail-minus"] = "rbxassetid://81989813236553",
	["mail-open"] = "rbxassetid://122785416858638",
	["mail-plus"] = "rbxassetid://104886401588341",
	["mail-question-mark"] = "rbxassetid://126540170949819",
	["mail-search"] = "rbxassetid://135616173775287",
	["mail-warning"] = "rbxassetid://81495303676089",
	["mail-x"] = "rbxassetid://74607841705644",
	["mail"] = "rbxassetid://103945161245599",
	["mailbox"] = "rbxassetid://82765503320335",
	["mails"] = "rbxassetid://90673453450080",
	["map-minus"] = "rbxassetid://129525760577747",
	["map-pin-check-inside"] = "rbxassetid://107130529843809",
	["map-pin-check"] = "rbxassetid://118110914690154",
	["map-pin-house"] = "rbxassetid://80546885029816",
	["map-pin-minus-inside"] = "rbxassetid://79005529692964",
	["map-pin-minus"] = "rbxassetid://74518762643623",
	["map-pin-off"] = "rbxassetid://82474689391020",
	["map-pin-pen"] = "rbxassetid://113515395277504",
	["map-pin-plus-inside"] = "rbxassetid://134639656514430",
	["map-pin-plus"] = "rbxassetid://91875228967029",
	["map-pin-x-inside"] = "rbxassetid://126235934252379",
	["map-pin-x"] = "rbxassetid://101085273547316",
	["map-pin"] = "rbxassetid://84279202219901",
	["map-pinned"] = "rbxassetid://103963788475034",
	["map-plus"] = "rbxassetid://129388826743495",
	["map"] = "rbxassetid://95107167260947",
	["mars-stroke"] = "rbxassetid://131973193186828",
	["mars"] = "rbxassetid://111287112372511",
	["martini"] = "rbxassetid://82977695401058",
	["maximize-2"] = "rbxassetid://73085922906397",
	["maximize"] = "rbxassetid://76045941763188",
	["medal"] = "rbxassetid://79016002264450",
	["megaphone-off"] = "rbxassetid://124280774193935",
	["megaphone"] = "rbxassetid://118759541854879",
	["meh"] = "rbxassetid://132197867028557",
	["memory-stick"] = "rbxassetid://93212591343119",
	["menu"] = "rbxassetid://77021539815611",
	["merge"] = "rbxassetid://126201866476775",
	["message-circle-code"] = "rbxassetid://112865244991651",
	["message-circle-dashed"] = "rbxassetid://81525157881897",
	["message-circle-heart"] = "rbxassetid://101990756073677",
	["message-circle-more"] = "rbxassetid://92856823884663",
	["message-circle-off"] = "rbxassetid://134955643890328",
	["message-circle-plus"] = "rbxassetid://106562979649273",
	["message-circle-question-mark"] = "rbxassetid://107700302759934",
	["message-circle-reply"] = "rbxassetid://137071749508334",
	["message-circle-warning"] = "rbxassetid://119020096067894",
	["message-circle-x"] = "rbxassetid://126843387725536",
	["message-circle"] = "rbxassetid://127255077587058",
	["message-square-code"] = "rbxassetid://110968863152123",
	["message-square-dashed"] = "rbxassetid://107653455516238",
	["message-square-diff"] = "rbxassetid://75472190472625",
	["message-square-dot"] = "rbxassetid://127806382463916",
	["message-square-heart"] = "rbxassetid://75612811742074",
	["message-square-lock"] = "rbxassetid://81268215619563",
	["message-square-more"] = "rbxassetid://120139782405970",
	["message-square-off"] = "rbxassetid://99961019005789",
	["message-square-plus"] = "rbxassetid://76934450256199",
	["message-square-quote"] = "rbxassetid://116670768629340",
	["message-square-reply"] = "rbxassetid://130985622754637",
	["message-square-share"] = "rbxassetid://131017005324026",
	["message-square-text"] = "rbxassetid://94899503194205",
	["message-square-warning"] = "rbxassetid://138432903962261",
	["message-square-x"] = "rbxassetid://137285463279462",
	["message-square"] = "rbxassetid://83881670383280",
	["messages-square"] = "rbxassetid://97532166733358",
	["mic-off"] = "rbxassetid://82123034444822",
	["mic-vocal"] = "rbxassetid://99082286164362",
	["mic"] = "rbxassetid://89640799126523",
	["microchip"] = "rbxassetid://73937907669903",
	["microscope"] = "rbxassetid://116875530102782",
	["microwave"] = "rbxassetid://108411735353008",
	["milestone"] = "rbxassetid://101618292325920",
	["milk-off"] = "rbxassetid://72388480962742",
	["milk"] = "rbxassetid://96221903896918",
	["minimize-2"] = "rbxassetid://116269596042539",
	["minimize"] = "rbxassetid://121304296213645",
	["minus"] = "rbxassetid://118026365011536",
	["monitor-check"] = "rbxassetid://86651948439229",
	["monitor-cloud"] = "rbxassetid://85931096038318",
	["monitor-cog"] = "rbxassetid://94345128715799",
	["monitor-dot"] = "rbxassetid://130394010063680",
	["monitor-down"] = "rbxassetid://97466933743423",
	["monitor-off"] = "rbxassetid://74395526657953",
	["monitor-pause"] = "rbxassetid://76002184067562",
	["monitor-play"] = "rbxassetid://133018824306217",
	["monitor-smartphone"] = "rbxassetid://84335680433378",
	["monitor-speaker"] = "rbxassetid://81744810060380",
	["monitor-stop"] = "rbxassetid://98708958984757",
	["monitor-up"] = "rbxassetid://96035360858377",
	["monitor-x"] = "rbxassetid://126265210441423",
	["monitor"] = "rbxassetid://72664649203050",
	["moon-star"] = "rbxassetid://82782200506348",
	["moon"] = "rbxassetid://83380517901735",
	["motorbike"] = "rbxassetid://94580787368233",
	["mountain-snow"] = "rbxassetid://105315495740588",
	["mountain"] = "rbxassetid://73269957566415",
	["mouse-off"] = "rbxassetid://75267871697595",
	["mouse-pointer-2-off"] = "rbxassetid://104701076865632",
	["mouse-pointer-2"] = "rbxassetid://117093892862228",
	["mouse-pointer-ban"] = "rbxassetid://106849413057133",
	["mouse-pointer-click"] = "rbxassetid://107150227368485",
	["mouse-pointer"] = "rbxassetid://72322454962935",
	["mouse"] = "rbxassetid://73096068864710",
	["move-3d"] = "rbxassetid://103365982054003",
	["move-diagonal-2"] = "rbxassetid://117298577948096",
	["move-diagonal"] = "rbxassetid://101433481954184",
	["move-down-left"] = "rbxassetid://102819433534567",
	["move-down-right"] = "rbxassetid://101479760041877",
	["move-down"] = "rbxassetid://70510115135583",
	["move-horizontal"] = "rbxassetid://88513523439149",
	["move-left"] = "rbxassetid://137614740247980",
	["move-right"] = "rbxassetid://132455779472989",
	["move-up-left"] = "rbxassetid://139079815540148",
	["move-up-right"] = "rbxassetid://105885140592646",
	["move-up"] = "rbxassetid://84505444262658",
	["move-vertical"] = "rbxassetid://86234730730899",
	["move"] = "rbxassetid://116138709011735",
	["music-2"] = "rbxassetid://134397426600888",
	["music-3"] = "rbxassetid://94466120066498",
	["music-4"] = "rbxassetid://132459323665838",
	["music"] = "rbxassetid://113343203848535",
	["navigation-2-off"] = "rbxassetid://116569611780763",
	["navigation-2"] = "rbxassetid://81889066747907",
	["navigation-off"] = "rbxassetid://87003270290777",
	["navigation"] = "rbxassetid://79308213542922",
	["network"] = "rbxassetid://127410729922644",
	["newspaper"] = "rbxassetid://123479530460544",
	["nfc"] = "rbxassetid://76822396542242",
	["non-binary"] = "rbxassetid://78442360386235",
	["notebook-pen"] = "rbxassetid://140380614761023",
	["notebook-tabs"] = "rbxassetid://127371085570083",
	["notebook-text"] = "rbxassetid://93061585217270",
	["notebook"] = "rbxassetid://136132108664987",
	["notepad-text-dashed"] = "rbxassetid://135793446376219",
	["notepad-text"] = "rbxassetid://93404682958966",
	["nut-off"] = "rbxassetid://78795397311573",
	["nut"] = "rbxassetid://127146410705656",
	["octagon-alert"] = "rbxassetid://140438367956051",
	["octagon-minus"] = "rbxassetid://74720436795421",
	["octagon-pause"] = "rbxassetid://103161463909039",
	["octagon-x"] = "rbxassetid://90498161006311",
	["octagon"] = "rbxassetid://120803515514852",
	["omega"] = "rbxassetid://70414080018786",
	["option"] = "rbxassetid://100776883894054",
	["orbit"] = "rbxassetid://108926136860562",
	["origami"] = "rbxassetid://136020626667101",
	["package-2"] = "rbxassetid://70394974762575",
	["package-check"] = "rbxassetid://102374216055130",
	["package-minus"] = "rbxassetid://114492858789692",
	["package-open"] = "rbxassetid://132890233237818",
	["package-plus"] = "rbxassetid://129261988138366",
	["package-search"] = "rbxassetid://95465120894145",
	["package-x"] = "rbxassetid://70818501607442",
	["package"] = "rbxassetid://97261141732706",
	["paint-bucket"] = "rbxassetid://124275586663284",
	["paint-roller"] = "rbxassetid://115248074358348",
	["paintbrush-vertical"] = "rbxassetid://105151296591292",
	["paintbrush"] = "rbxassetid://125572663700289",
	["palette"] = "rbxassetid://86350350950064",
	["panda"] = "rbxassetid://132509022802512",
	["panel-bottom-close"] = "rbxassetid://74287004071159",
	["panel-bottom-dashed"] = "rbxassetid://131084651621603",
	["panel-bottom-open"] = "rbxassetid://107768659586540",
	["panel-bottom"] = "rbxassetid://132127145048511",
	["panel-left-close"] = "rbxassetid://126579818823552",
	["panel-left-dashed"] = "rbxassetid://75536606374585",
	["panel-left-open"] = "rbxassetid://111075816195767",
	["panel-left-right-dashed"] = "rbxassetid://110100707973959",
	["panel-left"] = "rbxassetid://97419752870313",
	["panel-right-close"] = "rbxassetid://139528655524132",
	["panel-right-dashed"] = "rbxassetid://94959793877311",
	["panel-right-open"] = "rbxassetid://118114419142794",
	["panel-right"] = "rbxassetid://116365035443156",
	["panel-top-bottom-dashed"] = "rbxassetid://134737235653344",
	["panel-top-close"] = "rbxassetid://83578325777808",
	["panel-top-dashed"] = "rbxassetid://70522913169237",
	["panel-top-open"] = "rbxassetid://137959875507454",
	["panel-top"] = "rbxassetid://75838479462875",
	["panels-left-bottom"] = "rbxassetid://72996856149149",
	["panels-right-bottom"] = "rbxassetid://90659068960726",
	["panels-top-left"] = "rbxassetid://79858853850600",
	["paperclip"] = "rbxassetid://92088291163453",
	["parentheses"] = "rbxassetid://78950955173096",
	["parking-meter"] = "rbxassetid://84652733960568",
	["party-popper"] = "rbxassetid://111626795712193",
	["pause"] = "rbxassetid://74873705394436",
	["paw-print"] = "rbxassetid://112218825427601",
	["pc-case"] = "rbxassetid://122978648019101",
	["pen-line"] = "rbxassetid://109108135755303",
	["pen-off"] = "rbxassetid://84807123119438",
	["pen-tool"] = "rbxassetid://106145404953445",
	["pen"] = "rbxassetid://72037878096321",
	["pencil-line"] = "rbxassetid://88392917053533",
	["pencil-off"] = "rbxassetid://103330927652832",
	["pencil-ruler"] = "rbxassetid://110120288284597",
	["pencil"] = "rbxassetid://137986121120732",
	["pentagon"] = "rbxassetid://79184802179890",
	["percent"] = "rbxassetid://130155041032013",
	["person-standing"] = "rbxassetid://125020872044147",
	["philippine-peso"] = "rbxassetid://91173798254675",
	["phone-call"] = "rbxassetid://70555587592860",
	["phone-forwarded"] = "rbxassetid://113269614319737",
	["phone-incoming"] = "rbxassetid://82863576359288",
	["phone-missed"] = "rbxassetid://130156165198376",
	["phone-off"] = "rbxassetid://133318623553383",
	["phone-outgoing"] = "rbxassetid://104576478735825",
	["phone"] = "rbxassetid://128804946640049",
	["pi"] = "rbxassetid://74936036243146",
	["piano"] = "rbxassetid://85008880789520",
	["pickaxe"] = "rbxassetid://105888023317688",
	["picture-in-picture-2"] = "rbxassetid://112803319544468",
	["picture-in-picture"] = "rbxassetid://80579597835123",
	["piggy-bank"] = "rbxassetid://79498575790721",
	["pilcrow-left"] = "rbxassetid://103803000849583",
	["pilcrow-right"] = "rbxassetid://104881733911870",
	["pilcrow"] = "rbxassetid://139512780392871",
	["pill-bottle"] = "rbxassetid://118394692404597",
	["pill"] = "rbxassetid://73280534813448",
	["pin-off"] = "rbxassetid://127696372451750",
	["pin"] = "rbxassetid://120978111007514",
	["pipette"] = "rbxassetid://133167932934404",
	["pizza"] = "rbxassetid://126964453193501",
	["plane-landing"] = "rbxassetid://122555692211889",
	["plane-takeoff"] = "rbxassetid://117179478829575",
	["plane"] = "rbxassetid://126985561580989",
	["play"] = "rbxassetid://135609604299893",
	["plug-2"] = "rbxassetid://97912386476366",
	["plug-zap"] = "rbxassetid://74506269884055",
	["plug"] = "rbxassetid://99782373064495",
	["plus"] = "rbxassetid://111774323017047",
	["pocket-knife"] = "rbxassetid://134075428063965",
	["pocket"] = "rbxassetid://136686762542964",
	["podcast"] = "rbxassetid://109577075549215",
	["pointer-off"] = "rbxassetid://95488389312794",
	["pointer"] = "rbxassetid://92615117311099",
	["popcorn"] = "rbxassetid://139446511232750",
	["popsicle"] = "rbxassetid://112696318077073",
	["pound-sterling"] = "rbxassetid://127482649469130",
	["power-off"] = "rbxassetid://118768311012214",
	["power"] = "rbxassetid://96479131758775",
	["presentation"] = "rbxassetid://106134583757890",
	["printer-check"] = "rbxassetid://130273549443689",
	["printer"] = "rbxassetid://76080649734247",
	["projector"] = "rbxassetid://103281856385283",
	["proportions"] = "rbxassetid://130046855997237",
	["puzzle"] = "rbxassetid://136837798892463",
	["pyramid"] = "rbxassetid://107811442374127",
	["qr-code"] = "rbxassetid://105329945723350",
	["quote"] = "rbxassetid://103271711590001",
	["rabbit"] = "rbxassetid://98580518804206",
	["radar"] = "rbxassetid://138528222906635",
	["radiation"] = "rbxassetid://104499586848433",
	["radical"] = "rbxassetid://132758286926047",
	["radio-receiver"] = "rbxassetid://129598303378835",
	["radio-tower"] = "rbxassetid://93958663130054",
	["radio"] = "rbxassetid://85611589536956",
	["radius"] = "rbxassetid://89814505307129",
	["rail-symbol"] = "rbxassetid://134295386306962",
	["rainbow"] = "rbxassetid://132488862841895",
	["rat"] = "rbxassetid://127400975953159",
	["ratio"] = "rbxassetid://126369423897295",
	["receipt-cent"] = "rbxassetid://91557573925201",
	["receipt-euro"] = "rbxassetid://94015722210295",
	["receipt-indian-rupee"] = "rbxassetid://89718170439990",
	["receipt-japanese-yen"] = "rbxassetid://132472560758851",
	["receipt-pound-sterling"] = "rbxassetid://73934967569625",
	["receipt-russian-ruble"] = "rbxassetid://105164576936853",
	["receipt-swiss-franc"] = "rbxassetid://72503668620116",
	["receipt-text"] = "rbxassetid://138483536013737",
	["receipt-turkish-lira"] = "rbxassetid://91950765836342",
	["receipt"] = "rbxassetid://77877895901792",
	["rectangle-circle"] = "rbxassetid://100642423153903",
	["rectangle-ellipsis"] = "rbxassetid://112919953980965",
	["rectangle-goggles"] = "rbxassetid://98605436666727",
	["rectangle-horizontal"] = "rbxassetid://90224199814966",
	["rectangle-vertical"] = "rbxassetid://117277050590967",
	["recycle"] = "rbxassetid://140417023381961",
	["redo-2"] = "rbxassetid://70451039017914",
	["redo-dot"] = "rbxassetid://94252981719732",
	["redo"] = "rbxassetid://116150342119054",
	["refresh-ccw-dot"] = "rbxassetid://106702246753270",
	["refresh-ccw"] = "rbxassetid://117913330389477",
	["refresh-cw-off"] = "rbxassetid://140179498843054",
	["refresh-cw"] = "rbxassetid://138133190015277",
	["refrigerator"] = "rbxassetid://102614042652753",
	["regex"] = "rbxassetid://100727200791841",
	["remove-formatting"] = "rbxassetid://112833162022628",
	["repeat-1"] = "rbxassetid://130144534857095",
	["repeat-2"] = "rbxassetid://85927537182704",
	["repeat"] = "rbxassetid://121886242955173",
	["replace-all"] = "rbxassetid://127862728198635",
	["replace"] = "rbxassetid://128404082279430",
	["reply-all"] = "rbxassetid://71723137343562",
	["reply"] = "rbxassetid://109788633497028",
	["rewind"] = "rbxassetid://95205297521988",
	["ribbon"] = "rbxassetid://94265331526851",
	["rocket"] = "rbxassetid://87412317685854",
	["rocking-chair"] = "rbxassetid://110420269495360",
	["roller-coaster"] = "rbxassetid://112426178972099",
	["rose"] = "rbxassetid://126336840238769",
	["rotate-3d"] = "rbxassetid://76300551576392",
	["rotate-ccw-key"] = "rbxassetid://74976035240976",
	["rotate-ccw-square"] = "rbxassetid://90515853170424",
	["rotate-ccw"] = "rbxassetid://110116685948665",
	["rotate-cw-square"] = "rbxassetid://77095448159303",
	["rotate-cw"] = "rbxassetid://84183336178654",
	["route-off"] = "rbxassetid://106350402024079",
	["route"] = "rbxassetid://89968303228953",
	["router"] = "rbxassetid://102130331994471",
	["rows-2"] = "rbxassetid://112556185960101",
	["rows-3"] = "rbxassetid://117215586961375",
	["rows-4"] = "rbxassetid://125646021959055",
	["rss"] = "rbxassetid://131789058984793",
	["ruler-dimension-line"] = "rbxassetid://70673861371412",
	["ruler"] = "rbxassetid://81432445547423",
	["russian-ruble"] = "rbxassetid://126357936542156",
	["sailboat"] = "rbxassetid://87110567187540",
	["salad"] = "rbxassetid://128864507821603",
	["sandwich"] = "rbxassetid://104573187458917",
	["satellite-dish"] = "rbxassetid://136742443888305",
	["satellite"] = "rbxassetid://134967053164645",
	["saudi-riyal"] = "rbxassetid://102282769104635",
	["save-all"] = "rbxassetid://116946975799440",
	["save-off"] = "rbxassetid://87085435778560",
	["save"] = "rbxassetid://126116963775616",
	["scale-3d"] = "rbxassetid://72414199620352",
	["scale"] = "rbxassetid://108203682317477",
	["scaling"] = "rbxassetid://122360365318466",
	["scan-barcode"] = "rbxassetid://96889457154761",
	["scan-eye"] = "rbxassetid://99244790601968",
	["scan-face"] = "rbxassetid://109959345069668",
	["scan-heart"] = "rbxassetid://106280819776142",
	["scan-line"] = "rbxassetid://126544908146540",
	["scan-qr-code"] = "rbxassetid://105409149549927",
	["scan-search"] = "rbxassetid://80009010551347",
	["scan-text"] = "rbxassetid://73702396787766",
	["scan"] = "rbxassetid://123104789658180",
	["school"] = "rbxassetid://76351530290068",
	["scissors-line-dashed"] = "rbxassetid://122237447974173",
	["scissors"] = "rbxassetid://118665510911274",
	["screen-share-off"] = "rbxassetid://107677572669805",
	["screen-share"] = "rbxassetid://85137895705653",
	["scroll-text"] = "rbxassetid://97321022666868",
	["scroll"] = "rbxassetid://74072101474951",
	["search-check"] = "rbxassetid://75442076191356",
	["search-code"] = "rbxassetid://117114794592802",
	["search-slash"] = "rbxassetid://96483932261041",
	["search-x"] = "rbxassetid://137319957522951",
	["search"] = "rbxassetid://121018724060431",
	["section"] = "rbxassetid://91732188298948",
	["send-horizontal"] = "rbxassetid://111734392411664",
	["send-to-back"] = "rbxassetid://75340312862253",
	["send"] = "rbxassetid://127751956873796",
	["separator-horizontal"] = "rbxassetid://84864453699927",
	["separator-vertical"] = "rbxassetid://84031801478581",
	["server-cog"] = "rbxassetid://138470287250966",
	["server-crash"] = "rbxassetid://132810618000212",
	["server-off"] = "rbxassetid://114048751507723",
	["server"] = "rbxassetid://92188766517878",
	["settings-2"] = "rbxassetid://135684703553372",
	["settings"] = "rbxassetid://80758916183665",
	["shapes"] = "rbxassetid://129989433311409",
	["share-2"] = "rbxassetid://71210767962065",
	["share"] = "rbxassetid://87340985053299",
	["sheet"] = "rbxassetid://134902122480171",
	["shell"] = "rbxassetid://140212943563599",
	["shield-alert"] = "rbxassetid://114995877719925",
	["shield-ban"] = "rbxassetid://108765041044649",
	["shield-check"] = "rbxassetid://87354736164608",
	["shield-ellipsis"] = "rbxassetid://114794739892123",
	["shield-half"] = "rbxassetid://117842634172647",
	["shield-minus"] = "rbxassetid://89965059528921",
	["shield-off"] = "rbxassetid://133426959132690",
	["shield-plus"] = "rbxassetid://100664857995498",
	["shield-question-mark"] = "rbxassetid://135722075265150",
	["shield-user"] = "rbxassetid://124832775645347",
	["shield-x"] = "rbxassetid://73370117343811",
	["shield"] = "rbxassetid://110987169760162",
	["ship-wheel"] = "rbxassetid://130797795829448",
	["ship"] = "rbxassetid://83995100553930",
	["shirt"] = "rbxassetid://106579555405966",
	["shopping-bag"] = "rbxassetid://71885477293226",
	["shopping-basket"] = "rbxassetid://138646411956433",
	["shopping-cart"] = "rbxassetid://128420521375441",
	["shovel"] = "rbxassetid://102465000512056",
	["shower-head"] = "rbxassetid://75884944024117",
	["shredder"] = "rbxassetid://122125164414463",
	["shrimp"] = "rbxassetid://102625900815307",
	["shrink"] = "rbxassetid://90953687918880",
	["shrub"] = "rbxassetid://127326280714343",
	["shuffle"] = "rbxassetid://132382786975101",
	["sigma"] = "rbxassetid://126884244870899",
	["signal-high"] = "rbxassetid://130436670012270",
	["signal-low"] = "rbxassetid://73674683500458",
	["signal-medium"] = "rbxassetid://125003021367019",
	["signal-zero"] = "rbxassetid://130045332414754",
	["signal"] = "rbxassetid://78424889355261",
	["signature"] = "rbxassetid://114402748013000",
	["signpost-big"] = "rbxassetid://115780185675001",
	["signpost"] = "rbxassetid://106584743791433",
	["siren"] = "rbxassetid://134210267818039",
	["skip-back"] = "rbxassetid://70466132711334",
	["skip-forward"] = "rbxassetid://124844823753990",
	["skull"] = "rbxassetid://137726256442333",
	["slack"] = "rbxassetid://96089719516736",
	["slash"] = "rbxassetid://117792185664263",
	["slice"] = "rbxassetid://95810504278179",
	["sliders-horizontal"] = "rbxassetid://85538382643347",
	["sliders-vertical"] = "rbxassetid://101190569086853",
	["smartphone-charging"] = "rbxassetid://102837532613995",
	["smartphone-nfc"] = "rbxassetid://82326425754446",
	["smartphone"] = "rbxassetid://96623008834511",
	["smile-plus"] = "rbxassetid://131981881472144",
	["smile"] = "rbxassetid://105880397565283",
	["snail"] = "rbxassetid://70904536548363",
	["snowflake"] = "rbxassetid://101235206534566",
	["soap-dispenser-droplet"] = "rbxassetid://77258480479465",
	["sofa"] = "rbxassetid://114427687218324",
	["solar-panel"] = "rbxassetid://132448188047921",
	["soup"] = "rbxassetid://115092551871618",
	["space"] = "rbxassetid://87072088914178",
	["spade"] = "rbxassetid://131444449466462",
	["sparkle"] = "rbxassetid://111044800239623",
	["sparkles"] = "rbxassetid://138635884129147",
	["speaker"] = "rbxassetid://96227183003618",
	["speech"] = "rbxassetid://87013139446349",
	["spell-check-2"] = "rbxassetid://81556731785534",
	["spell-check"] = "rbxassetid://91913483031334",
	["spline-pointer"] = "rbxassetid://84842840956804",
	["spline"] = "rbxassetid://129406685807412",
	["split"] = "rbxassetid://105112438805988",
	["spool"] = "rbxassetid://124541981347743",
	["spotlight"] = "rbxassetid://77571742539344",
	["spray-can"] = "rbxassetid://128372039366326",
	["sprout"] = "rbxassetid://100091687832508",
	["square-activity"] = "rbxassetid://89496630185293",
	["square-arrow-down-left"] = "rbxassetid://108194680296901",
	["square-arrow-down-right"] = "rbxassetid://99403846801050",
	["square-arrow-down"] = "rbxassetid://135962519626588",
	["square-arrow-left"] = "rbxassetid://111671474549238",
	["square-arrow-out-down-left"] = "rbxassetid://125714881756353",
	["square-arrow-out-down-right"] = "rbxassetid://89971003001390",
	["square-arrow-out-up-left"] = "rbxassetid://103759986579087",
	["square-arrow-out-up-right"] = "rbxassetid://91221896066807",
	["square-arrow-right"] = "rbxassetid://113920471701361",
	["square-arrow-up-left"] = "rbxassetid://112424670290693",
	["square-arrow-up-right"] = "rbxassetid://76602291406940",
	["square-arrow-up"] = "rbxassetid://106998604646718",
	["square-asterisk"] = "rbxassetid://89186832353625",
	["square-bottom-dashed-scissors"] = "rbxassetid://79076980104803",
	["square-chart-gantt"] = "rbxassetid://104034017316411",
	["square-check-big"] = "rbxassetid://115320390907184",
	["square-check"] = "rbxassetid://134682053539509",
	["square-chevron-down"] = "rbxassetid://91032307924592",
	["square-chevron-left"] = "rbxassetid://73143404829510",
	["square-chevron-right"] = "rbxassetid://90612077729930",
	["square-chevron-up"] = "rbxassetid://85565910197337",
	["square-code"] = "rbxassetid://81604576616881",
	["square-dashed-bottom-code"] = "rbxassetid://100354801563230",
	["square-dashed-bottom"] = "rbxassetid://101102319625624",
	["square-dashed-kanban"] = "rbxassetid://90388067649847",
	["square-dashed-mouse-pointer"] = "rbxassetid://121016142178467",
	["square-dashed-top-solid"] = "rbxassetid://117157577548540",
	["square-dashed"] = "rbxassetid://136905537847606",
	["square-divide"] = "rbxassetid://99894657101970",
	["square-dot"] = "rbxassetid://116613421354866",
	["square-equal"] = "rbxassetid://110283363706707",
	["square-function"] = "rbxassetid://86075219551088",
	["square-kanban"] = "rbxassetid://114537101260131",
	["square-library"] = "rbxassetid://73810931222081",
	["square-m"] = "rbxassetid://117662700410577",
	["square-menu"] = "rbxassetid://104067089444415",
	["square-minus"] = "rbxassetid://116764432015770",
	["square-mouse-pointer"] = "rbxassetid://76141850603920",
	["square-parking-off"] = "rbxassetid://100857293535141",
	["square-parking"] = "rbxassetid://133116656122387",
	["square-pause"] = "rbxassetid://86608552787615",
	["square-pen"] = "rbxassetid://120239476110475",
	["square-percent"] = "rbxassetid://87111930314567",
	["square-pi"] = "rbxassetid://75383328781618",
	["square-pilcrow"] = "rbxassetid://131854284699367",
	["square-play"] = "rbxassetid://108186325238481",
	["square-plus"] = "rbxassetid://114713264461873",
	["square-power"] = "rbxassetid://129240437805187",
	["square-radical"] = "rbxassetid://132645931868292",
	["square-round-corner"] = "rbxassetid://104592745113567",
	["square-scissors"] = "rbxassetid://110601255612411",
	["square-sigma"] = "rbxassetid://113231244246816",
	["square-slash"] = "rbxassetid://105477013908757",
	["square-split-horizontal"] = "rbxassetid://76095370148660",
	["square-split-vertical"] = "rbxassetid://88589192032058",
	["square-square"] = "rbxassetid://136555087357875",
	["square-stack"] = "rbxassetid://100463396619394",
	["square-star"] = "rbxassetid://94506958703720",
	["square-stop"] = "rbxassetid://80018708472943",
	["square-terminal"] = "rbxassetid://83969264476798",
	["square-user-round"] = "rbxassetid://86484997229302",
	["square-user"] = "rbxassetid://70771214183445",
	["square-x"] = "rbxassetid://125136183850190",
	["square"] = "rbxassetid://86304921356806",
	["squares-exclude"] = "rbxassetid://102345385822324",
	["squares-intersect"] = "rbxassetid://120869602570119",
	["squares-subtract"] = "rbxassetid://131484650948795",
	["squares-unite"] = "rbxassetid://96673080107843",
	["squircle-dashed"] = "rbxassetid://129936702532522",
	["squircle"] = "rbxassetid://82426632573807",
	["squirrel"] = "rbxassetid://112864252085343",
	["stamp"] = "rbxassetid://92370779813368",
	["star-half"] = "rbxassetid://117449275562979",
	["star-off"] = "rbxassetid://75742832732503",
	["star"] = "rbxassetid://136141469398409",
	["step-back"] = "rbxassetid://108672750005121",
	["step-forward"] = "rbxassetid://126131872136145",
	["stethoscope"] = "rbxassetid://122331031702148",
	["sticker"] = "rbxassetid://79938203791608",
	["sticky-note"] = "rbxassetid://111894074643919",
	["store"] = "rbxassetid://90338129673705",
	["stretch-horizontal"] = "rbxassetid://87665042192343",
	["stretch-vertical"] = "rbxassetid://95265463417122",
	["strikethrough"] = "rbxassetid://103417324549613",
	["subscript"] = "rbxassetid://74553514785183",
	["sun-dim"] = "rbxassetid://129141645592715",
	["sun-medium"] = "rbxassetid://130278807964710",
	["sun-moon"] = "rbxassetid://75752898854559",
	["sun-snow"] = "rbxassetid://112791898014579",
	["sun"] = "rbxassetid://110150589884127",
	["sunrise"] = "rbxassetid://134705665494098",
	["sunset"] = "rbxassetid://75904872203588",
	["superscript"] = "rbxassetid://96887696590118",
	["swatch-book"] = "rbxassetid://126786244872453",
	["swiss-franc"] = "rbxassetid://113497920041625",
	["switch-camera"] = "rbxassetid://76841154349737",
	["sword"] = "rbxassetid://124448418211665",
	["swords"] = "rbxassetid://81872698913435",
	["syringe"] = "rbxassetid://123891270479254",
	["table-2"] = "rbxassetid://95751552281545",
	["table-cells-merge"] = "rbxassetid://95363715175258",
	["table-cells-split"] = "rbxassetid://114799086088649",
	["table-columns-split"] = "rbxassetid://111011625447949",
	["table-of-contents"] = "rbxassetid://135044763275414",
	["table-properties"] = "rbxassetid://125062886015372",
	["table-rows-split"] = "rbxassetid://96443733673997",
	["table"] = "rbxassetid://109109148250737",
	["tablet-smartphone"] = "rbxassetid://133680859813404",
	["tablet"] = "rbxassetid://128403991264386",
	["tablets"] = "rbxassetid://80835787970735",
	["tag"] = "rbxassetid://129104970103940",
	["tags"] = "rbxassetid://107179263080798",
	["tally-1"] = "rbxassetid://115301298241643",
	["tally-2"] = "rbxassetid://110363186864027",
	["tally-3"] = "rbxassetid://97655344572540",
	["tally-4"] = "rbxassetid://102633494371890",
	["tally-5"] = "rbxassetid://88031817475886",
	["tangent"] = "rbxassetid://123263132981724",
	["target"] = "rbxassetid://87563802520297",
	["telescope"] = "rbxassetid://91755049143647",
	["tent-tree"] = "rbxassetid://76698322463977",
	["tent"] = "rbxassetid://109779587826330",
	["terminal"] = "rbxassetid://106783148545356",
	["test-tube-diagonal"] = "rbxassetid://75662704378840",
	["test-tube"] = "rbxassetid://98801015650164",
	["test-tubes"] = "rbxassetid://92555361447433",
	["text-align-center"] = "rbxassetid://84051028246390",
	["text-align-end"] = "rbxassetid://130041738343555",
	["text-align-justify"] = "rbxassetid://80279880143030",
	["text-align-start"] = "rbxassetid://134489585487649",
	["text-cursor-input"] = "rbxassetid://107551944047171",
	["text-cursor"] = "rbxassetid://115984654447300",
	["text-initial"] = "rbxassetid://129458097472087",
	["text-quote"] = "rbxassetid://139278366448736",
	["text-search"] = "rbxassetid://92345384671606",
	["text-select"] = "rbxassetid://117087320884956",
	["text-wrap"] = "rbxassetid://114804318314018",
	["theater"] = "rbxassetid://108558145549163",
	["thermometer-snowflake"] = "rbxassetid://121876188028425",
	["thermometer-sun"] = "rbxassetid://106693240074310",
	["thermometer"] = "rbxassetid://106546011492311",
	["thumbs-down"] = "rbxassetid://87794009914015",
	["thumbs-up"] = "rbxassetid://111137070767020",
	["ticket-check"] = "rbxassetid://105428777212507",
	["ticket-minus"] = "rbxassetid://78966299769328",
	["ticket-percent"] = "rbxassetid://80834774406405",
	["ticket-plus"] = "rbxassetid://110086734392189",
	["ticket-slash"] = "rbxassetid://89045681172265",
	["ticket-x"] = "rbxassetid://88674114109926",
	["ticket"] = "rbxassetid://126527071492145",
	["tickets-plane"] = "rbxassetid://100367018248695",
	["tickets"] = "rbxassetid://135268612687833",
	["timer-off"] = "rbxassetid://110916370767271",
	["timer-reset"] = "rbxassetid://110052125369932",
	["timer"] = "rbxassetid://85473888890506",
	["toggle-left"] = "rbxassetid://85887872573050",
	["toggle-right"] = "rbxassetid://90411952142550",
	["toilet"] = "rbxassetid://80930782432931",
	["tool-case"] = "rbxassetid://87533537832522",
	["tornado"] = "rbxassetid://88358291515768",
	["torus"] = "rbxassetid://70855707283051",
	["touchpad-off"] = "rbxassetid://78784008075456",
	["touchpad"] = "rbxassetid://74882354908014",
	["tower-control"] = "rbxassetid://95937619060532",
	["toy-brick"] = "rbxassetid://86293483924633",
	["tractor"] = "rbxassetid://103376704722051",
	["traffic-cone"] = "rbxassetid://74110220470369",
	["train-front-tunnel"] = "rbxassetid://105194827005114",
	["train-front"] = "rbxassetid://125237934215370",
	["train-track"] = "rbxassetid://77451032453723",
	["tram-front"] = "rbxassetid://93315182364998",
	["transgender"] = "rbxassetid://135530817673639",
	["trash-2"] = "rbxassetid://109843431391323",
	["trash"] = "rbxassetid://106723740584310",
	["tree-deciduous"] = "rbxassetid://123124389219004",
	["tree-palm"] = "rbxassetid://103846705893963",
	["tree-pine"] = "rbxassetid://124662547202594",
	["trees"] = "rbxassetid://121203841375919",
	["trello"] = "rbxassetid://130987241149527",
	["trending-down"] = "rbxassetid://139309232226438",
	["trending-up-down"] = "rbxassetid://85083293981691",
	["trending-up"] = "rbxassetid://81819858538839",
	["triangle-alert"] = "rbxassetid://125920361880643",
	["triangle-dashed"] = "rbxassetid://124324079103935",
	["triangle-right"] = "rbxassetid://116930791412791",
	["triangle"] = "rbxassetid://126330486745540",
	["trophy"] = "rbxassetid://131545003268773",
	["truck-electric"] = "rbxassetid://111873446387359",
	["truck"] = "rbxassetid://86662707764771",
	["turkish-lira"] = "rbxassetid://114589876174070",
	["turntable"] = "rbxassetid://129870346487856",
	["turtle"] = "rbxassetid://118295081560334",
	["tv-minimal-play"] = "rbxassetid://99201833426972",
	["tv-minimal"] = "rbxassetid://100382201729427",
	["tv"] = "rbxassetid://135687724791776",
	["twitch"] = "rbxassetid://71383308134888",
	["twitter"] = "rbxassetid://88791703276842",
	["type-outline"] = "rbxassetid://80108627791690",
	["type"] = "rbxassetid://133543553793564",
	["umbrella-off"] = "rbxassetid://72395143739955",
	["umbrella"] = "rbxassetid://127502210274589",
	["underline"] = "rbxassetid://123709229216544",
	["undo-2"] = "rbxassetid://113885292059932",
	["undo-dot"] = "rbxassetid://132055277744844",
	["undo"] = "rbxassetid://111258459077271",
	["unfold-horizontal"] = "rbxassetid://117128358526398",
	["unfold-vertical"] = "rbxassetid://116593025265499",
	["ungroup"] = "rbxassetid://106674800451003",
	["university"] = "rbxassetid://84652528263642",
	["unlink-2"] = "rbxassetid://128131898892572",
	["unlink"] = "rbxassetid://139835795227752",
	["unplug"] = "rbxassetid://90171381619874",
	["upload"] = "rbxassetid://138212042425501",
	["usb"] = "rbxassetid://117230058949613",
	["user-check"] = "rbxassetid://81775205032725",
	["user-cog"] = "rbxassetid://92795491530865",
	["user-lock"] = "rbxassetid://78892639693821",
	["user-minus"] = "rbxassetid://126976941957511",
	["user-pen"] = "rbxassetid://87445472574836",
	["user-plus"] = "rbxassetid://118514469915884",
	["user-round-check"] = "rbxassetid://118794737621941",
	["user-round-cog"] = "rbxassetid://78239503290053",
	["user-round-minus"] = "rbxassetid://98944176636447",
	["user-round-pen"] = "rbxassetid://108155244324878",
	["user-round-plus"] = "rbxassetid://113301899567470",
	["user-round-search"] = "rbxassetid://71565774381870",
	["user-round-x"] = "rbxassetid://122367980560930",
	["user-round"] = "rbxassetid://136485052187963",
	["user-search"] = "rbxassetid://101335649828115",
	["user-star"] = "rbxassetid://98777846316000",
	["user-x"] = "rbxassetid://139748155894754",
	["user"] = "rbxassetid://81589895647169",
	["users-round"] = "rbxassetid://103005444008339",
	["users"] = "rbxassetid://115398113982385",
	["utensils-crossed"] = "rbxassetid://109520762270383",
	["utensils"] = "rbxassetid://139952569804235",
	["utility-pole"] = "rbxassetid://101965541238242",
	["variable"] = "rbxassetid://104743088438151",
	["vault"] = "rbxassetid://108049164599845",
	["vector-square"] = "rbxassetid://86713728565344",
	["vegan"] = "rbxassetid://119489190688082",
	["venetian-mask"] = "rbxassetid://102636443033920",
	["venus-and-mars"] = "rbxassetid://120227752103771",
	["venus"] = "rbxassetid://82891342220859",
	["vibrate-off"] = "rbxassetid://113446447326246",
	["vibrate"] = "rbxassetid://108330910738733",
	["video-off"] = "rbxassetid://132239189859305",
	["video"] = "rbxassetid://107587444636945",
	["videotape"] = "rbxassetid://114816894323398",
	["view"] = "rbxassetid://118717253976805",
	["voicemail"] = "rbxassetid://134313454010227",
	["volleyball"] = "rbxassetid://83889351124153",
	["volume-1"] = "rbxassetid://98514588731639",
	["volume-2"] = "rbxassetid://89344380902620",
	["volume-off"] = "rbxassetid://103047478058767",
	["volume-x"] = "rbxassetid://139252359189540",
	["volume"] = "rbxassetid://103236289817396",
	["vote"] = "rbxassetid://89409762851246",
	["wallet-cards"] = "rbxassetid://129728715308337",
	["wallet-minimal"] = "rbxassetid://137800448816116",
	["wallet"] = "rbxassetid://132331555762628",
	["wallpaper"] = "rbxassetid://74682121235494",
	["wand-sparkles"] = "rbxassetid://82546429942392",
	["wand"] = "rbxassetid://114580617777835",
	["warehouse"] = "rbxassetid://78388887451080",
	["washing-machine"] = "rbxassetid://104194127573858",
	["watch"] = "rbxassetid://130544621618405",
	["waves-ladder"] = "rbxassetid://101808619355514",
	["waves"] = "rbxassetid://96340135183647",
	["waypoints"] = "rbxassetid://102450133666017",
	["webcam"] = "rbxassetid://104148487911129",
	["webhook-off"] = "rbxassetid://96370548093471",
	["webhook"] = "rbxassetid://112812457747322",
	["weight"] = "rbxassetid://103860559844854",
	["wheat-off"] = "rbxassetid://133294844612307",
	["wheat"] = "rbxassetid://85261952080359",
	["whole-word"] = "rbxassetid://90111083954485",
	["wifi-cog"] = "rbxassetid://110500263326209",
	["wifi-high"] = "rbxassetid://81954601342139",
	["wifi-low"] = "rbxassetid://138217335635913",
	["wifi-off"] = "rbxassetid://74113634330106",
	["wifi-pen"] = "rbxassetid://91290205064712",
	["wifi-sync"] = "rbxassetid://84043971055177",
	["wifi-zero"] = "rbxassetid://124286465246123",
	["wifi"] = "rbxassetid://104669375183960",
	["wind-arrow-down"] = "rbxassetid://127753987414870",
	["wind"] = "rbxassetid://114551690399915",
	["wine-off"] = "rbxassetid://108294164302317",
	["wine"] = "rbxassetid://115743721332829",
	["workflow"] = "rbxassetid://99186544029189",
	["worm"] = "rbxassetid://115752311548091",
	["wrench"] = "rbxassetid://112148279212860",
	["x"] = "rbxassetid://110786993356448",
	["youtube"] = "rbxassetid://123663668456341",
	["zap-off"] = "rbxassetid://81385483183652",
	["zap"] = "rbxassetid://130551565616516",
	["zoom-in"] = "rbxassetid://127956924984803",
	["zoom-out"] = "rbxassetid://108334162607319",
	["balloon"] = "rbxassetid://97489111621526",
	["beef-off"] = "rbxassetid://99869959725200",
	["book-search"] = "rbxassetid://132585409504950",
	["calendars"] = "rbxassetid://130944763042289",
	["cannabis-off"] = "rbxassetid://101938500363812",
	["cctv-off"] = "rbxassetid://75925370187295",
	["cigarette"] = "rbxassetid://137149549886852",
	["circle-pile"] = "rbxassetid://116353155251541",
	["cloud-backup"] = "rbxassetid://111649579696132",
	["cloud-sync"] = "rbxassetid://79393911188593",
	["database-search"] = "rbxassetid://92017137080138",
	["ellipse"] = "rbxassetid://71559658267482",
	["fingerprint-pattern"] = "rbxassetid://80934710831288",
	["fishing-hook"] = "rbxassetid://121038780855899",
	["fishing-rod"] = "rbxassetid://71754848048049",
	["form"] = "rbxassetid://72999643971000",
	["git-merge-conflict"] = "rbxassetid://85677801675703",
	["globe-off"] = "rbxassetid://77775243585824",
	["globe-x"] = "rbxassetid://109268097029296",
	["hd"] = "rbxassetid://71682790698278",
	["image"] = "rbxassetid://112751259236831",
	["layers-plus"] = "rbxassetid://77587765623057",
	["lens-concave"] = "rbxassetid://94819631937027",
	["lens-convex"] = "rbxassetid://74736504195474",
	["line-dot-right-horizontal"] = "rbxassetid://104718593155221",
	["line-style"] = "rbxassetid://90176717785772",
	["map-pin-search"] = "rbxassetid://89065012915078",
	["message-circle-check"] = "rbxassetid://132772297689418",
	["message-square-check"] = "rbxassetid://125789987055668",
	["metronome"] = "rbxassetid://101991829345965",
	["mirror-rectangular"] = "rbxassetid://109046769760336",
	["mirror-round"] = "rbxassetid://121534049429097",
	["mouse-left"] = "rbxassetid://99144293708743",
	["mouse-right"] = "rbxassetid://88331710212594",
	["printer-x"] = "rbxassetid://103002721801548",
	["radio-off"] = "rbxassetid://80359258046586",
	["road"] = "rbxassetid://120251329173530",
	["scooter"] = "rbxassetid://100035452787934",
	["search-alert"] = "rbxassetid://127597984617505",
	["shelving-unit"] = "rbxassetid://80116568514793",
	["shield-cog-corner"] = "rbxassetid://111694066132698",
	["shield-cog"] = "rbxassetid://129235695057857",
	["sport-shoe"] = "rbxassetid://120495992692630",
	["square-arrow-right-enter"] = "rbxassetid://138867831495334",
	["square-arrow-right-exit"] = "rbxassetid://133688575845430",
	["square-centerline-dashed-horizontal"] = "rbxassetid://77780104374341",
	["square-centerline-dashed-vertical"] = "rbxassetid://107878435803525",
	["stone"] = "rbxassetid://135161057497830",
	["toolbox"] = "rbxassetid://85341033903792",
	["towel-rack"] = "rbxassetid://125223915620991",
	["user-key"] = "rbxassetid://105403041782190",
	["user-round-key"] = "rbxassetid://124547549008939",
	["van"] = "rbxassetid://122066377022942",
	["waves-arrow-down"] = "rbxassetid://129215220911792",
	["waves-arrow-up"] = "rbxassetid://102314705716217",
	["weight-tilde"] = "rbxassetid://112081212176951",
	["x-line-top"] = "rbxassetid://140592656289509",
	["zodiac-aquarius"] = "rbxassetid://74560047770362",
	["zodiac-aries"] = "rbxassetid://73255859670234",
	["zodiac-cancer"] = "rbxassetid://131985162532947",
	["zodiac-capricorn"] = "rbxassetid://97859568140652",
	["zodiac-gemini"] = "rbxassetid://80997588122992",
	["zodiac-leo"] = "rbxassetid://75509406718106",
	["zodiac-libra"] = "rbxassetid://113222735060218",
	["zodiac-ophiuchus"] = "rbxassetid://129180108892480",
	["zodiac-pisces"] = "rbxassetid://95845819440327",
	["zodiac-sagittarius"] = "rbxassetid://82651026742181",
	["zodiac-scorpio"] = "rbxassetid://113640924054631",
	["zodiac-taurus"] = "rbxassetid://123053219704400",
	["zodiac-virgo"] = "rbxassetid://99462994613661",
}

end)()
local function loadLucide() return lucideSet end

local FONT_PRESETS = {
    ValleySans = {
        Regular = "https://raw.githubusercontent.com/HelsinkiTypeStudio/valley-sans/main/fonts/ttf/ValleySans-Regular.ttf",
        Medium = "https://raw.githubusercontent.com/HelsinkiTypeStudio/valley-sans/main/fonts/ttf/ValleySans-Medium.ttf",
        SemiBold = "https://raw.githubusercontent.com/HelsinkiTypeStudio/valley-sans/main/fonts/ttf/ValleySans-SemiBold.ttf",
    },
}

local FONT_WEIGHTS = {
    Regular = { 400, Enum.FontWeight.Regular },
    Medium = { 500, Enum.FontWeight.Medium },
    SemiBold = { 600, Enum.FontWeight.SemiBold },
    Bold = { 700, Enum.FontWeight.Bold },
}

function Library:LoadFont(opts)
    opts = normalize(opts, {})
    if type(writefile) ~= "function" or type(isfile) ~= "function" or typeof(getcustomasset) ~= "function" then
        warn("[Aster UI] custom fonts need writefile, isfile and getcustomasset")
        return false
    end
    local name = opts.Name or "CustomFont"
    local weights = opts.Weights or FONT_PRESETS[name]
    if type(weights) ~= "table" then
        warn("[Aster UI] no font weights for " .. name)
        return false
    end
    local folder = opts.Folder or "AsterFonts"
    pcall(function()
        if type(isfolder) == "function" and type(makefolder) == "function" and not isfolder(folder) then
            makefolder(folder)
        end
    end)
    local faces = {}
    for weightName, url in pairs(weights) do
        local info = FONT_WEIGHTS[weightName]
        if info then
            local path = folder .. "/" .. name .. "-" .. weightName .. ".ttf"
            local ok = true
            if not isfile(path) then
                ok = pcall(function()
                    writefile(path, game:HttpGet(url))
                end)
            end
            if ok then
                table.insert(faces, { name = weightName, weight = info[1], style = "normal", assetId = getcustomasset(path) })
            else
                warn("[Aster UI] could not download " .. weightName .. " weight of " .. name)
            end
        end
    end
    if #faces == 0 then
        return false
    end
    local familyPath = folder .. "/" .. name .. ".json"
    local okWrite = pcall(function()
        writefile(familyPath, HttpService:JSONEncode({ name = name, faces = faces }))
    end)
    if not okWrite then
        return false
    end
    local family = getcustomasset(familyPath)
    local function face(weightName, fallback)
        local info = FONT_WEIGHTS[weightName]
        if info and weights[weightName] then
            return Font.new(family, info[2])
        end
        return fallback
    end
    Library.Fonts.Regular = face("Regular", Library.Fonts.Regular)
    Library.Fonts.Medium = face("Medium", face("Regular", Library.Fonts.Medium))
    Library.Fonts.Bold = face("SemiBold", face("Bold", Library.Fonts.Bold))
    return true
end

function Library:PreloadIcons()
    return loadLucide() ~= false
end

local function assetId(value)
    if type(value) == "number" then
        return "rbxassetid://" .. string.format("%.0f", value)
    end
    if type(value) == "string" then
        if value:match("^%d+$") then
            return "rbxassetid://" .. value
        end
        if value:find("^rbxassetid://") or value:find("^rbxasset://") or value:find("^rbxthumb://") or value:find("^http") or (Assets and value == Assets.Logo) then
            return value
        end
    end
    return nil
end

local function resolveIcon(icon)
    if typeof(icon) == "table" then
        return assetId(icon.Image) or icon.Image, icon.RectOffset, icon.RectSize, true, icon.Tint == true
    end
    local asset = assetId(icon)
    if asset then
        return asset, nil, nil, true, false
    end
    if type(icon) ~= "string" then
        return nil
    end
    local name = icon:gsub("^lucide:", "")
    local set = loadLucide()
    if not set then
        return nil
    end
    local entry = (set.Icons and set.Icons[name]) or set[name]
    if type(entry) == "table" then
        local image = entry.Image
        if type(image) == "number" then
            image = "rbxassetid://" .. tostring(image)
        end
        local sheet = (set.Spritesheets and set.Spritesheets[tostring(image)]) or image
        return sheet, entry.ImageRectPosition, entry.ImageRectSize
    elseif type(entry) == "string" then
        return entry
    end
    warn("[Aster UI] unknown lucide icon: " .. name)
    return nil
end

local BUTTON_HINT_ICON = "chevron-right"

local FONT_FAMILY = "rbxasset://fonts/families/BuilderSans.json"
Library.Fonts = {
    Regular = Font.new(FONT_FAMILY, Enum.FontWeight.Regular),
    Medium = Font.new(FONT_FAMILY, Enum.FontWeight.Medium),
    Bold = Font.new(FONT_FAMILY, Enum.FontWeight.SemiBold),
}

local Theme = Library.Theme
local Assets = Library.Assets

local EMBEDDED_LOGO = "iVBORw0KGgoAAAANSUhEUgAAAfQAAAH0CAYAAADL1t+KAAAQAElEQVR4Aex9B4AcR5X291X3hE1KlixLcpBlWXLONiYe3JEPuAMOjiOZZHI6cgZjMhgfxjlHguG4n+MCdz5yNtjgbMuyLduSbMlBeXdnpsP/vZ7t3dnZ2SRppd1Vtfrrqnr1Kn3dU69e9ezIwR+eAc+AZ8Az4BnwDEx5BrxBn/K30A/AM+AZ8Ax4BjwDwMQadM+wZ8Az4BnwDHgGPAO7hAFv0HcJzb4Rz4BnwDPgGfAMTCwDU9mgTywzvnbPgGfAM+AZ8AxMIQa8QZ9CN8t31TPgGfAMeAY8A8Mx4A36cMx4uWfAM+AZ8Ax4BqYQA96gT6Gb5bvqGfAMeAY8A56B4RjwBn04ZiZW7mv3D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nay+5ccuE37z/o0gvuOfDyi1YedMH59xx46Tn3Lr7ovFUHXnjeqqUXnr/q4IsuuO+QKy64d9nl592X4UrFL7rwnmUXKjRcdumqpZdcPIBLz7lv6fnn3btUdfXjwgvuWXrJ+SuXXnLR3Usvv2jF0ssuWXHwhefflWPp5Zdm8WUXXXBXhksuvHPpReffueSCc+9ccu7Zdy0555srllz8zRWq7+6DLrloheHgC867a9nFF9y5/Pxz7lh+wbm3Gw654Nw7DCY7+Lyz71h6zll3LP3mN+486IKz71xy/jfvXHLuWXdZfOmF59y57JLz7zjkwotuP/Sic28/7JLzbzv04vNuW37B2bcffPF5dxx04TkZllxw9h1W7uCLzr9z+cUX3Xno5Rfcfshl59++7JJzbzfZwZedf9eySy6849DLLr1j+WUX337wpedpXBfcffBll92z7PLL7znkkovvPvTyy1YccsmFdy+98jyN/8J7F198/r0HXnbJqsWXX3L/0isvX3XQJRfed+glV6485FtXrTzs6ivvOfSqS+495LJL7jv46stWLbnk4gcWX3ThA4svvOCBAy/owxXnP3igZAcpT7zdv/Qquz+X3nvIVVesPNRw9ZV3H3LF5Xcvu+zSu5defNHKJRdfuHLxheevPPCC81cuU3jYFeetOOLyi+887KrL71h21YV3LL308rsWn3/ZyiUX6N6ov8svveKuQ6656s5l37n0joO+ff6dB11x/oqDLj57pTjL6lp+zaUrll125R2HX3XFrUd964pbT7ri8tuedcV5t73krK/8YvHTnvIyPY2B4E/PwLAMeIM+LDU+wzMwTgaWLJnZ+aEXfWT5m177uZsCzL531kzc09GO+9racU+7wo42rGrvwH2dbVjZ1Ya7Fd7VUcbd7cNjpcqMCNWxsqMDKxvCu63OPpjc2lmhdI6Vit8r/TracW9nO1bO6MA9Cu/tqocr+9rN+7airQSDpVeqvznuyevpald5jUvpxvbvaivCsKK9BJObvuFe6d/b2Qnr+91qa4XqtDCDuMrDTJ6nxeXdwgrhrgxlWLhSba6c0Y5VGsN9szqz0NLWzgrjWeO1cEVnByy8u6sT987swCrTndmF+2Z21jFLceEepV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AIWga5FwHK3CMyPgFXo82NiYywCFgGLgEXAIrDMIWAV+jI3ZLbBFgGLgEWgaxGw3JdNBKxCXzbHzbbaImARsAhYBCwC8yBgFfo8cNiARcAiYBGwCHQtApZ7VyFgFXpXIWv5WgQsAhYBi4BFYCkiYBX6UgTbVmURsAhYBCwCXYtAT+ZuFXpPHn3bd4uARcAiYBFYbhD4fwAAAP//hA6cAAAAAAZJREFUAwA9gVnicalf7AAAAABJRU5ErkJggg=="

local function decodeBase64(data)
    local lookup = {}
    local alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
    for i = 1, #alphabet do
        lookup[alphabet:byte(i)] = i - 1
    end
    local out = {}
    for i = 1, #data, 4 do
        local a, b, c, d = data:byte(i, i + 3)
        local n = lookup[a] * 262144 + lookup[b] * 4096 + (lookup[c] or 0) * 64 + (lookup[d] or 0)
        local x, y, z = n // 65536, n // 256 % 256, n % 256
        if d ~= 61 then
            out[#out + 1] = string.char(x, y, z)
        elseif c ~= 61 then
            out[#out + 1] = string.char(x, y)
        else
            out[#out + 1] = string.char(x)
        end
    end
    return table.concat(out)
end

pcall(function()
    local getasset = (typeof(getcustomasset) == "function" and getcustomasset)
        or (typeof(getsynasset) == "function" and getsynasset)
    if type(writefile) ~= "function" or typeof(getasset) ~= "function" then
        return
    end
    local folder = "AsterAssets"
    if type(isfolder) == "function" and type(makefolder) == "function" and not isfolder(folder) then
        makefolder(folder)
    end
    local path = folder .. "/AsterLogo.png"
    local png = decodeBase64(EMBEDDED_LOGO)
    local fresh = type(isfile) == "function" and type(readfile) == "function" and isfile(path) and readfile(path) == png
    if not fresh then
        writefile(path, png)
    end
    local asset = getasset(path)
    if type(asset) == "string" and asset ~= "" then
        Assets.Logo = asset
    end
end)
local Fonts = Library.Fonts

local TOUCH = (getgenv().MT_ArrowRokakaFinder.Device or {}).Touch == true
Library.Touch = TOUCH

local SIDEBAR_WIDTH = 188
local HEADER_HEIGHT = 62
local TAB_TILE_HEIGHT = 34
local CARD_HEIGHT = TOUCH and 54 or 48
local CARD_HEIGHT_DESC = TOUCH and 70 or 64
local DROPDOWN_OPTION_HEIGHT = TOUCH and 40 or 34
local CHIP_HEIGHT = TOUCH and 34 or 28
local PROFILE_HEIGHT = 64
local SEARCH_WIDTH = 176
local STACK_BELOW = 440

local METRICS = {
    Card = {
        Compact = false,
        Height = math.max(56,CARD_HEIGHT),
        DescHeight = math.max(80,CARD_HEIGHT_DESC),
        Chip = CHIP_HEIGHT,
        Option = DROPDOWN_OPTION_HEIGHT,
        TextSize = 18,
        DescSize = 16,
        TitleHeight = 24,
        DescGap = 26,
        DescLine = 22,
        Slider = CARD_HEIGHT_DESC,
    },
    Row = {
        Compact = true,
        Height = 44,
        DescHeight = 68,
        Chip = 32,
        Option = 40,
        TextSize = 17,
        DescSize = 16,
        TitleHeight = 22,
        DescGap = 24,
        DescLine = 22,
        Slider = 68,
    },
}

local tweenInfoCache = {}

local themeBindings = {}
local themeHooks = {}
local themeLookup = {}
local orphanMarks = {}
local bindingCount = 0
local sweepAt = 4000

local function pruneTable(map, counted)
    for object in pairs(map) do
        if object.Parent == nil then
            if orphanMarks[object] then
                map[object] = nil
                orphanMarks[object] = nil
                if counted then
                    bindingCount -= 1
                end
            else
                orphanMarks[object] = true
            end
        else
            orphanMarks[object] = nil
        end
    end
end

local function sweepBindings()
    pruneTable(themeBindings, true)
    pruneTable(themeHooks, false)
    sweepAt = math.max(4000, bindingCount * 2)
end

local function colorKey(color)
    return math.floor(color.R * 255 + 0.5) .. "," .. math.floor(color.G * 255 + 0.5) .. "," .. math.floor(color.B * 255 + 0.5)
end

local function rebuildThemeLookup()
    table.clear(themeLookup)
    for index = #THEME_KEYS, 1, -1 do
        local name = THEME_KEYS[index]
        themeLookup[colorKey(Library.Theme[name])] = name
    end
end
rebuildThemeLookup()

local function bindColors(object, props)
    for property, value in pairs(props) do
        if typeof(value) == "Color3" then
            local name = themeLookup[colorKey(value)]
            local bound = themeBindings[object]
            if name then
                if not bound then
                    bound = {}
                    themeBindings[object] = bound
                    bindingCount += 1
                    if bindingCount >= sweepAt then
                        sweepBindings()
                    end
                end
                bound[property] = name
            elseif bound then
                bound[property] = nil
            end
        end
    end
end

local shownTheme = table.clone(Library.Theme)
local themeDriver = nil

local function paintBinding(object, bound, colors)
    for property, name in pairs(bound) do
        local color = colors[name]
        if color then
            object[property] = color
        end
    end
end

local function paintBindings(colors)
    for object, bound in pairs(themeBindings) do
        pcall(paintBinding, object, bound, colors)
    end
end

local function driveTheme(duration)
    if themeDriver then
        themeDriver:Disconnect()
        themeDriver = nil
    end
    local from, colors = {}, {}
    for _, name in ipairs(THEME_KEYS) do
        local target = Library.Theme[name]
        local current = shownTheme[name] or target
        if current ~= target then
            from[name] = current
            colors[name] = current
        end
    end
    local function finish()
        for _, name in ipairs(THEME_KEYS) do
            colors[name] = Library.Theme[name]
            shownTheme[name] = Library.Theme[name]
        end
        paintBindings(colors)
    end
    if duration <= 0 or next(from) == nil then
        finish()
        return
    end
    local elapsed = 0
    themeDriver = RunService.Heartbeat:Connect(function(deltaTime)
        elapsed += deltaTime
        if elapsed >= duration then
            themeDriver:Disconnect()
            themeDriver = nil
            finish()
            return
        end
        local alpha = 1 - (1 - elapsed / duration) ^ 5
        for name, start in pairs(from) do
            local color = start:Lerp(Library.Theme[name], alpha)
            colors[name] = color
            shownTheme[name] = color
        end
        paintBindings(colors)
    end)
end

-- run fn now and on each theme change while owner lives.
local function onTheme(owner, fn)
    themeHooks[owner] = fn
    fn()
end

local function tween(object, props, duration, style, direction, raw)
    duration=(duration or .2)/math.clamp(Library.AnimationSpeed or 1,.5,2)
    if Library.ReducedMotion then duration=0 end
    duration = duration or 0.2
    if not raw then
        bindColors(object, props)
    end
    if duration <= 0 then
        for key, value in pairs(props) do
            object[key] = value
        end
        return nil
    end
    style = style or Enum.EasingStyle.Quart
    direction = direction or Enum.EasingDirection.Out
    local key = duration .. style.Name .. direction.Name
    local info = tweenInfoCache[key]
    if not info then
        info = TweenInfo.new(duration, style, direction)
        tweenInfoCache[key] = info
    end
    local t = TweenService:Create(object, info, props)
    t:Play()
    return t
end

local function create(className, props, children)
    local inst = Instance.new(className)
    for key, value in pairs(props) do
        if key ~= "Parent" then
            inst[key] = value
        end
    end
    if not Library.AutoTranslate and (className == "TextLabel" or className == "TextButton" or className == "TextBox") then
        -- The UI opted out of Roblox's automatic translation.
        pcall(function()
            inst.AutoLocalize = false
        end)
    end
    if inst:IsA("TextLabel") or inst:IsA("TextButton") or inst:IsA("TextBox") then
        inst.TextSize=math.max(16,inst.TextSize)
        inst.TextScaled=false
        inst:GetPropertyChangedSignal("TextSize"):Connect(function()
            if inst.TextSize<16 then inst.TextSize=16 end
        end)
    end
    bindColors(inst, props)
    if children then
        for _, child in ipairs(children) do
            child.Parent = inst
        end
    end

    if props.Parent then
        inst.Parent = props.Parent
    end
    return inst
end

Library.Roundness = 1
Library._cornerBases = {}

local function corner(parent, radius)
    radius = radius or UDim.new(0, 8)
    local object = create("UICorner", {
        CornerRadius = radius.Scale == 0 and UDim.new(0, math.floor(radius.Offset * Library.Roundness + 0.5)) or radius,
        Parent = parent,
    })
    if radius.Scale == 0 then
        Library._cornerBases[object] = radius.Offset
    end
    return object
end

function Library._fixedCorner(parent, radius)
    return create("UICorner", { CornerRadius = radius, Parent = parent })
end

-- current window corner radius.
function Library._radius(pixels)
    return math.floor(pixels * Library.Roundness + 0.5)
end

local function stroke(parent, color, transparency, thickness)
    return create("UIStroke", {
        Color = color or Theme.Stroke,
        Transparency = transparency or 0,
        Thickness = thickness or 1,
        ApplyStrokeMode = Enum.ApplyStrokeMode.Border,
        Parent = parent,
    })
end

local function padding(parent, left, right, top, bottom)
    return create("UIPadding", {
        PaddingLeft = UDim.new(0, left or 0),
        PaddingRight = UDim.new(0, right or 0),
        PaddingTop = UDim.new(0, top or 0),
        PaddingBottom = UDim.new(0, bottom or 0),
        Parent = parent,
    })
end

local function label(props)
    local defaults = {
        BackgroundTransparency = 1,
        TextColor3 = Theme.Text,
        TextSize = 14,
        FontFace = Fonts.Medium,
        TextXAlignment = Enum.TextXAlignment.Left,
        TextYAlignment = Enum.TextYAlignment.Center,
        TextTruncate = Enum.TextTruncate.AtEnd,
    }
    for key, value in pairs(props) do
        defaults[key] = value
    end
    return create("TextLabel", defaults)
end

local function glow(parent, size, position, transparency, rotation)
    local image = create("ImageLabel", {
        AnchorPoint = Vector2.new(0.5, 0.5),
        Position = position,
        Size = size,
        BackgroundTransparency = 1,
        Image = Assets.Glow,
        ImageColor3 = Color3.fromRGB(226, 218, 230),
        ImageTransparency = 1,
        Visible = false,
        ZIndex = 0,
        Parent = parent,
    })
    local gradient = create("UIGradient", {
        Rotation = rotation or 90,
        Parent = image,
    })
    onTheme(gradient, function()
        gradient.Color = ColorSequence.new(Color3.fromRGB(255, 255, 255), Theme.Accent)
    end)
    return image
end

local function edgeHighlight(parent)
    return create("Frame", {
        Position = UDim2.fromOffset(0, 0),
        Size = UDim2.new(1, 0, 0, 1),
        BackgroundColor3 = Color3.new(1, 1, 1),
        BackgroundTransparency = 1,
        BorderSizePixel = 0,
        ZIndex = 0,
        Parent = parent,
    })
end

local CUSTOM_ICON_SCALE = 1.35

local function applyIcon(imageLabel, icon, fixedSize)
    if icon == "sharkwow" or icon == Assets.Logo then
        imageLabel.Image=""
        imageLabel:SetAttribute("CustomIcon",true)
        if imageLabel:FindFirstChild("SharkwowPixelLogo") then return end
        local logo=Instance.new("Frame")
        logo.Name="SharkwowPixelLogo";logo.BackgroundTransparency=1
        logo.Size=UDim2.fromScale(1,1);logo.Parent=imageLabel
        local rows={"............ss..........","...........ssss.........","ss........ssssss........",".sss..ssssssssssssss....","..ssssssssssssssssses...","...sssssssssssssssssss..","..ssswwwwwwwwwwwwwwww...",".sss...wwwwwwwwwwww.....","ss.......sss..ss........","..........ss............"}
        local colors={s=Color3.fromRGB(243,250,255),w=Color3.fromRGB(187,222,244),e=Color3.fromRGB(5,19,28)}
        for y,row in ipairs(rows)do
            local x=1
            while x<=#row do
                local symbol=row:sub(x,x);local last=x
                while last<#row and row:sub(last+1,last+1)==symbol do last+=1 end
                if colors[symbol]then
                    local p=Instance.new("Frame");p.BorderSizePixel=0;p.BackgroundColor3=colors[symbol]
                    p.Position=UDim2.fromScale((x-1)/24,.25+(y-1)/20)
                    p.Size=UDim2.fromScale((last-x+1)/24,1/20);p.ZIndex=imageLabel.ZIndex;p.Parent=logo
                end
                x=last+1
            end
        end
        return
    end
    if icon == false then
        imageLabel.Image = ""
        imageLabel.ImageRectOffset = Vector2.zero
        imageLabel.ImageRectSize = Vector2.zero
        imageLabel:SetAttribute("CustomIcon", nil)
        local stale = imageLabel:FindFirstChild("CustomIconScale")
        if stale then
            stale:Destroy()
        end
        return
    end
    local image, rectOffset, rectSize, custom, tint = resolveIcon(icon)
    if not image then
        return
    end
    imageLabel.Image = image
    imageLabel.ImageRectOffset = rectOffset or Vector2.zero
    imageLabel.ImageRectSize = rectSize or Vector2.zero
    -- keep the logo's gradient.
    if icon == Assets.Logo then
        tint = false
    end
    local keepColours = custom and not tint
    imageLabel:SetAttribute("CustomIcon", keepColours or nil)
    if keepColours then
        local bound = themeBindings[imageLabel]
        if bound then
            bound.ImageColor3 = nil
        end
        tween(imageLabel, { ImageColor3 = Color3.new(1, 1, 1) }, 0)
    end
    local scale = custom and not fixedSize and icon ~= Assets.Logo and (typeof(icon) == "table" and tonumber(icon.Scale) or CUSTOM_ICON_SCALE) or 1
    local scaler = imageLabel:FindFirstChild("CustomIconScale")
    if scale ~= 1 then
        scaler = scaler or create("UIScale", { Name = "CustomIconScale", Parent = imageLabel })
        scaler.Scale = scale
    elseif scaler then
        scaler:Destroy()
    end
end

local function tintIcon(imageLabel, color, active, duration)
    if imageLabel:GetAttribute("CustomIcon") then
        tween(imageLabel, { ImageTransparency = active and 0 or 0.4 }, duration)
    else
        tween(imageLabel, { ImageColor3 = color }, duration)
    end
end

local function defaultParent()
    local hidden
    pcall(function()
        if typeof(gethui) == "function" then
            hidden = gethui()
        end
    end)
    if typeof(hidden) == "Instance" then
        return hidden
    end
    local core
    pcall(function()
        core = game:GetService("CoreGui")
        local probe = Instance.new("Folder")
        probe.Parent = core
        probe:Destroy()
    end)
    if core then
        return core
    end
    return LocalPlayer:WaitForChild("PlayerGui")
end

local insetFrame, insetValue = nil, Vector2.zero
local function pointerPosition()
    local frame = time()
    if insetFrame ~= frame then
        insetFrame = frame
        insetValue = GuiService:GetGuiInset()
    end
    return UserInputService:GetMouseLocation() - insetValue
end

local function isPress(input)
    return input.UserInputType == Enum.UserInputType.MouseButton1 or input.UserInputType == Enum.UserInputType.Touch
end

local function usingTouch()
    return UserInputService:GetLastInputType() == Enum.UserInputType.Touch
end

local function tapGuard(button, getScroller)
    local startCanvas
    button.InputBegan:Connect(function(input)
        if isPress(input) then
            local frame = getScroller()
            startCanvas = frame and frame.CanvasPosition
        end
    end)
    return function()
        local frame = getScroller()
        return not (startCanvas and frame and (frame.CanvasPosition - startCanvas).Magnitude > 4)
    end
end

local function pointInside(point, object)
    local position, size = object.AbsolutePosition, object.AbsoluteSize
    return point.X >= position.X and point.X <= position.X + size.X
        and point.Y >= position.Y and point.Y <= position.Y + size.Y
end

local function isMove(input)
    return input.UserInputType == Enum.UserInputType.MouseMovement or input.UserInputType == Enum.UserInputType.Touch
end

local function glowIcon(parent, icon, color, position)
    local holder = create("Frame", {
        AnchorPoint = Vector2.new(0, 0.5),
        Position = position,
        Size = UDim2.fromOffset(16, 16),
        BackgroundTransparency = 1,
        Parent = parent,
    })
    local image = create("ImageLabel", {
        Size = UDim2.fromScale(1, 1),
        BackgroundTransparency = 1,
        ImageColor3 = color,
        ScaleType = Enum.ScaleType.Fit,
        Parent = holder,
    })
    applyIcon(image, icon)
    return holder, image
end

local function arrowIndicator(parent, anchorX, offsetX)
    local holder = create("Frame", {
        AnchorPoint = Vector2.new(anchorX, 0.5),
        Position = UDim2.new(anchorX, offsetX, 0.5, 0),
        Size = UDim2.fromOffset(18, 18),
        BackgroundTransparency = 1,
        Parent = parent,
    })
    local indicator = {}
    local image = create("ImageLabel", {
        AnchorPoint = Vector2.new(0.5, 0.5),
        Position = UDim2.fromScale(0.5, 0.5),
        Size = UDim2.fromOffset(16, 16),
        BackgroundTransparency = 1,
        ImageColor3 = Theme.Muted,
        ScaleType = Enum.ScaleType.Fit,
        Parent = holder,
    })
    applyIcon(image, "chevron-down")
    if image.Image ~= "" then
        function indicator:Set(open)
            tween(image, {
                Rotation = open and 180 or 0,
                ImageColor3 = open and Theme.Accent or Theme.Muted,
            }, 0.3, Enum.EasingStyle.Quint)
        end
        return indicator
    end
    image:Destroy()
    local function glyph(rotation, transparency)
        return label({
            AnchorPoint = Vector2.new(0.5, 0.5),
            Position = UDim2.fromScale(0.5, 0.5),
            Size = UDim2.fromOffset(18, 18),
            Text = "›",
            TextSize = 22,
            TextXAlignment = Enum.TextXAlignment.Center,
            TextColor3 = Theme.Muted,
            TextTransparency = transparency,
            Rotation = rotation,
            Parent = holder,
        })
    end
    local down = glyph(90, 0)
    local up = glyph(270, 1)
    function indicator:Set(open)
        tween(down, { TextTransparency = open and 1 or 0 }, 0.2)
        tween(up, { TextTransparency = open and 0 or 1, TextColor3 = open and Theme.Accent or Theme.Muted }, 0.2)
    end
    return indicator
end

local ripplePool = {}

local function ripple(button)
    local mouse = pointerPosition()
    local diameter = math.max(button.AbsoluteSize.X, button.AbsoluteSize.Y) * 2.2
    local circle = table.remove(ripplePool)
    -- skip destroyed pooled circles.
    if circle and not pcall(function()
        circle.Parent = nil
    end) then
        circle = nil
    end
    if not circle then
        circle = create("Frame", {
            AnchorPoint = Vector2.new(0.5, 0.5),
            BackgroundColor3 = Theme.Accent,
            BorderSizePixel = 0,
        })
        corner(circle, UDim.new(1, 0))
    end
    circle.Position = UDim2.fromOffset(mouse.X - button.AbsolutePosition.X, mouse.Y - button.AbsolutePosition.Y)
    circle.Size = UDim2.fromOffset(0, 0)
    circle.BackgroundColor3 = Theme.Accent
    circle.BackgroundTransparency = 0.82
    circle.ZIndex = button.ZIndex + 1
    circle.Parent = button
    tween(circle, { Size = UDim2.fromOffset(diameter, diameter), BackgroundTransparency = 1 }, 0.55)
    task.delay(0.55, function()
        -- button died mid-ripple: drop the circle.
        if circle.Parent ~= button or not button.Parent then
            pcall(circle.Destroy, circle)
            return
        end
        circle.Parent = nil
        if #ripplePool < 4 then
            table.insert(ripplePool, circle)
        else
            circle:Destroy()
        end
    end)
end

local function flashStroke(strokeObject)
    if not strokeObject or strokeObject:GetAttribute("Hidden") then
        return
    end
    tween(strokeObject, { Color = Theme.Accent, Transparency = 0.2 }, 0.08)
    task.delay(0.12, function()
        tween(strokeObject, { Color = Theme.Stroke, Transparency = 0 }, 0.35)
    end)
end

local function hoverStroke(target, strokeObject)
    target.MouseEnter:Connect(function()
        tween(strokeObject, { Color = Theme.StrokeHover }, 0.12)
    end)
    target.MouseLeave:Connect(function()
        tween(strokeObject, { Color = Theme.Stroke }, 0.25)
    end)
end

local KEY_NAMES = {
    [Enum.KeyCode.LeftControl] = "LCtrl",
    [Enum.KeyCode.RightControl] = "RCtrl",
    [Enum.KeyCode.LeftShift] = "LShift",
    [Enum.KeyCode.RightShift] = "RShift",
    [Enum.KeyCode.LeftAlt] = "LAlt",
    [Enum.KeyCode.RightAlt] = "RAlt",
    [Enum.KeyCode.Return] = "Enter",
    [Enum.KeyCode.Escape] = "Esc",
    [Enum.KeyCode.Backspace] = "Backspace",
    [Enum.UserInputType.MouseButton1] = "MB1",
    [Enum.UserInputType.MouseButton2] = "MB2",
    [Enum.UserInputType.MouseButton3] = "MB3",
}

local function keyName(keyCode)
    if typeof(keyCode) ~= "EnumItem" then
        return "None"
    end
    return KEY_NAMES[keyCode] or keyCode.Name
end

local Keybinds = {
    Mouse = {
        [Enum.UserInputType.MouseButton1] = true,
        [Enum.UserInputType.MouseButton2] = true,
        [Enum.UserInputType.MouseButton3] = true,
    },
    Aliases = {
        MB1 = Enum.UserInputType.MouseButton1,
        MB2 = Enum.UserInputType.MouseButton2,
        MB3 = Enum.UserInputType.MouseButton3,
    },
}

function Keybinds.FromInput(input)
    if input.UserInputType == Enum.UserInputType.Keyboard then
        return input.KeyCode
    end
    if Keybinds.Mouse[input.UserInputType] then
        return input.UserInputType
    end
    return nil
end

function Keybinds.Resolve(value)
    if typeof(value) == "EnumItem" then
        if value.EnumType == Enum.UserInputType and not Keybinds.Mouse[value] then
            return nil
        end
        return value
    end
    if type(value) ~= "string" then
        return nil
    end
    local key = Enum.KeyCode[value]
    if key then
        return key
    end
    local inputType = Enum.UserInputType[value]
    if inputType and Keybinds.Mouse[inputType] then
        return inputType
    end
    return Keybinds.Aliases[value] or Keybinds.Aliases[string.upper(value)]
end

local function safeCall(callback, ...)
    if type(callback) ~= "function" then
        return
    end
    local ok, err = pcall(callback, ...)
    if not ok then
        warn("[Aster UI] callback error: " .. tostring(err))
    end
end

local function isolatedCall(callback)
    local result = nil
    task.spawn(function()
        result = table.pack(pcall(callback))
    end)
    while result == nil do
        task.wait()
    end
    return table.unpack(result, 1, result.n)
end

local function numberFormat(min, max, step)
    local decimals = 0
    local text = tostring(step)
    local dot = text:find("%.")
    if dot then
        decimals = #text - dot
    end
    local pattern = "%." .. decimals .. "f"
    return {
        snap = function(value)
            value = math.floor(value / step + 0.5) * step
            return math.clamp(value, min, max)
        end,
        format = function(value)
            return string.format(pattern, value)
        end,
    }
end

local function metricsOf(tab)
    return tab._metrics or METRICS.Card
end

local function rowControlWidth(frame, window)
    local width = frame.AbsoluteSize.X / window.Scale.Scale
    return math.clamp(math.floor(width * 0.48), 90, 220)
end

local function card(tab, className, height, opts)
    local compact = metricsOf(tab).Compact
    local props = {
        Size = UDim2.new(1, 0, 0, height),
        BackgroundColor3 = Theme.Surface2,
        BackgroundTransparency = compact and 1 or 0,
        BorderSizePixel = 0,
        LayoutOrder = tab:_nextOrder(),
        Parent = tab.List,
    }
    if className == "TextButton" then
        props.AutoButtonColor = false
        props.Text = ""
    end
    local frame = create(className, props)
    frame:SetAttribute("NoDrag", true)
    corner(frame)
    local frameStroke = stroke(frame, Theme.Stroke, compact and 1 or 0)
    if compact then
        frameStroke:SetAttribute("Hidden", true)
    end
    return frame, frameStroke
end

local function titleDesc(parent, name, desc, rightReserve, metrics)
    metrics = metrics or METRICS.Card
    local title, descLabel
    if desc then
        local top = math.floor((metrics.DescHeight - (metrics.DescGap + metrics.DescLine)) / 2)
        title = label({
            Position = UDim2.fromOffset(14, top),
            Size = UDim2.new(1, -(14 + rightReserve), 0, metrics.TitleHeight),
            Text = name,
            TextSize = metrics.TextSize,
            Parent = parent,
        })
        descLabel = label({
            Position = UDim2.fromOffset(14, top + metrics.DescGap),
            Size = UDim2.new(1, -(14 + rightReserve), 0, metrics.DescLine),
            Text = desc,
            TextSize = metrics.DescSize,
            FontFace = Fonts.Regular,
            TextColor3 = Theme.Muted,
            Parent = parent,
        })
    else
        title = label({
            Position = UDim2.fromOffset(14, 0),
            Size = UDim2.new(1, -(14 + rightReserve), 1, 0),
            Text = name,
            TextSize = metrics.TextSize,
            Parent = parent,
        })
    end
    return title, descLabel
end

local function beginElement(tab, opts, map, className, rightReserve, fallbackName)
    opts = normalize(opts, map)
    local metrics = metricsOf(tab)
    local height = opts.Desc and metrics.DescHeight or metrics.Height
    local frame, frameStroke = card(tab, className or "Frame", height, opts)
    hoverStroke(frame, frameStroke)
    local title, descLabel
    if rightReserve then
        title, descLabel = titleDesc(frame, opts.Name or fallbackName, opts.Desc, rightReserve, metrics)
    end
    return opts, frame, frameStroke, height, title, descLabel
end

local function reserveRight(title, descLabel, width)
    if title then
        title.Size = UDim2.new(1, -(14 + width), title.Size.Y.Scale, title.Size.Y.Offset)
    end
    if descLabel then
        descLabel.Size = UDim2.new(1, -(14 + width), 0, descLabel.Size.Y.Offset)
    end
end

local Tab = {}
Tab.__index = Tab

function Tab:_nextOrder()
    self._order = self._order + 1
    return self._order
end

function Tab:Section(text)
    local visible = not (type(text) == "table" and text.Visible == false)
    if type(text) == "table" then
        text = text.Name or text.Title or ""
    end
    local inset = metricsOf(self).Compact and 14 or 2
    local holder = create("Frame", {
        Size = UDim2.new(1, 0, 0, 28),
        BackgroundTransparency = 1,
        LayoutOrder = self:_nextOrder(),
        Parent = self.List,
    })
    local text_ = label({
        Position = UDim2.fromOffset(inset, 8),
        Size = UDim2.new(0, 0, 0, 16),
        AutomaticSize = Enum.AutomaticSize.X,
        Text = string.upper(text),
        TextSize = 12,
        TextColor3 = Theme.Muted,
        TextTruncate = Enum.TextTruncate.None,
        Parent = holder,
    })
    local ruleInset = inset == 2 and 0 or inset
    local rule = create("Frame", {
        AnchorPoint = Vector2.new(1, 0.5),
        Position = UDim2.new(1, -ruleInset, 0, 16),
        Size = UDim2.new(1, -12, 0, 1),
        BackgroundColor3 = Theme.Stroke,
        BorderSizePixel = 0,
        Parent = holder,
    })
    local function fitRule()
        rule.Size = UDim2.new(1, -(text_.AbsoluteSize.X / self.Window.Scale.Scale + inset + 12 + ruleInset), 0, 1)
    end
    text_:GetPropertyChangedSignal("AbsoluteSize"):Connect(fitRule)
    task.defer(fitRule)
    return finishElement(self, { Visible = visible }, {
        Set = function(_, value)
            text_.Text = string.upper(value)
        end,
    }, holder, "Section")
end

function Tab:Divider(opts)
    local caption = type(opts) == "table" and (opts.Text or opts.Name) or type(opts) == "string" and opts or nil
    if caption then
        -- A centred caption with a rule on each side.
        local inset = metricsOf(self).Compact and 14 or 2
        local holder = create("Frame", {
            Size = UDim2.new(1, 0, 0, 18),
            BackgroundTransparency = 1,
            LayoutOrder = self:_nextOrder(),
            Parent = self.List,
        })
        local text_ = label({
            AnchorPoint = Vector2.new(0.5, 0.5),
            Position = UDim2.fromScale(0.5, 0.5),
            Size = UDim2.new(0, 0, 0, 14),
            AutomaticSize = Enum.AutomaticSize.X,
            Text = caption,
            TextSize = 11,
            FontFace = Fonts.Regular,
            TextColor3 = Theme.Muted,
            TextTruncate = Enum.TextTruncate.None,
            Parent = holder,
        })
        padding(text_, 8, 8)
        local rules = {}
        for index, anchor in ipairs({ 0, 1 }) do
            rules[index] = create("Frame", {
                AnchorPoint = Vector2.new(anchor, 0.5),
                Position = UDim2.new(anchor, anchor == 0 and inset or -inset, 0.5, 0),
                Size = UDim2.new(0.5, -inset, 0, 1),
                BackgroundColor3 = Theme.Stroke,
                BorderSizePixel = 0,
                Parent = holder,
            })
        end
        local function fitRules()
            local half = text_.AbsoluteSize.X / self.Window.Scale.Scale / 2
            for _, rule in ipairs(rules) do
                rule.Size = UDim2.new(0.5, -(inset + half), 0, 1)
            end
        end
        text_:GetPropertyChangedSignal("AbsoluteSize"):Connect(fitRules)
        task.defer(fitRules)
        return finishElement(self, { Visible = not (type(opts) == "table" and opts.Visible == false) }, {
            Set = function(_, value)
                text_.Text = tostring(value)
            end,
        }, holder, "Divider")
    end
    local line = create("Frame", {
        Size = UDim2.new(1, 0, 0, 1),
        BackgroundColor3 = Theme.Stroke,
        BorderSizePixel = 0,
        LayoutOrder = self:_nextOrder(),
        Parent = self.List,
    })
    if metricsOf(self).Compact then
        line.BackgroundTransparency = 1
        line.Size = UDim2.new(1, 0, 0, 9)
        create("Frame", {
            Position = UDim2.fromOffset(14, 4),
            Size = UDim2.new(1, -28, 0, 1),
            BackgroundColor3 = Theme.Stroke,
            BorderSizePixel = 0,
            Parent = line,
        })
    end
    return finishElement(self, { Visible = not (type(opts) == "table" and opts.Visible == false) }, {}, line, "Divider")
end

function Tab:Label(opts)
    opts = normalize(opts, { Name = "Text", Title = "Text" })
    local text_ = label({
        Size = UDim2.new(1, 0, 0, 18),
        Text = Library._rich(opts.Text or ""),
        TextSize = 13,
        FontFace = Fonts.Regular,
        TextColor3 = Library._color(opts.Color) or Theme.Muted,
        RichText = true,
        LayoutOrder = self:_nextOrder(),
        Parent = self.List,
    })
    if metricsOf(self).Compact then
        text_.TextSize = 12
        padding(text_, 14, 14)
    else
        padding(text_, 2)
    end
    local handle = {
        Set = function(_, value)
            text_.Text = Library._rich(value)
        end,
        Get = function()
            return text_.Text
        end,
        SetColor = function(_, color)
            tween(text_, { TextColor3 = Library._color(color) or Theme.Muted }, 0.25)
        end,
    }
    if type(opts.Update) == "function" then
        local rate = math.max(tonumber(opts.UpdateRate) or 1, 0.05)
        local running = true
        handle._listeners = handle._listeners or {}
        table.insert(handle._listeners, function()
            running = false
        end)
        task.spawn(function()
            while running and text_.Parent do
                local ok, value = isolatedCall(opts.Update)
                if ok and value ~= nil then
                    text_.Text = Library._rich(value)
                elseif not ok then
                    warn("[Aster UI] label update error: " .. tostring(value))
                end
                task.wait(rate)
            end
        end)
        function handle:SetUpdateRate(seconds)
            rate = math.max(tonumber(seconds) or rate, 0.05)
        end
    end
    return finishElement(self, opts, handle, text_, "Label")
end

function Tab:Paragraph(opts)
    opts = normalize(opts, { Title = "Name" })
    local frame = card(self, "Frame", 0, opts)
    frame.AutomaticSize = Enum.AutomaticSize.Y
    if metricsOf(self).Compact then
        padding(frame, 14, 14, 6, 8)
    else
        padding(frame, 14, 14, 11, 12)
    end
    create("UIListLayout", {
        SortOrder = Enum.SortOrder.LayoutOrder,
        Padding = UDim.new(0, 4),
        Parent = frame,
    })
    label({
        Size = UDim2.new(1, 0, 0, 14),
        Text = opts.Name or "",
        LayoutOrder = 1,
        Parent = frame,
    })
    local content = label({
        Size = UDim2.new(1, 0, 0, 0),
        AutomaticSize = Enum.AutomaticSize.Y,
        Text = Library._rich(opts.Content or ""),
        TextSize = 13,
        FontFace = Fonts.Regular,
        TextColor3 = Theme.Muted,
        TextWrapped = true,
        TextTruncate = Enum.TextTruncate.None,
        TextYAlignment = Enum.TextYAlignment.Top,
        RichText = true,
        LayoutOrder = 2,
        Parent = frame,
    })
    return finishElement(self, opts, {
        Set = function(_, value)
            content.Text = Library._rich(value)
        end,
    }, frame, "Paragraph")
end

local function rowButton(tab, opts)
    local primary = opts.Style == "Primary"
    local boxHeight = TOUCH and 34 or 28
    local height = boxHeight + 6 + (opts.Desc and 16 or 0)
    local button = card(tab, "TextButton", height, opts)

    local box = create("Frame", {
        Position = UDim2.fromOffset(14, 3),
        Size = UDim2.new(1, -28, 0, boxHeight),
        BackgroundColor3 = primary and Theme.Accent or Theme.Surface3,
        BackgroundTransparency = primary and 0.12 or 0.45,
        BorderSizePixel = 0,
        ClipsDescendants = true,
        Parent = button,
    })
    corner(box, UDim.new(0, 6))
    local boxStroke = stroke(box, primary and Theme.Accent or Theme.Stroke, primary and 0.4 or 0)

    local row = create("Frame", {
        AnchorPoint = Vector2.new(0.5, 0.5),
        Position = UDim2.fromScale(0.5, 0.5),
        Size = UDim2.new(0, 0, 1, 0),
        AutomaticSize = Enum.AutomaticSize.X,
        BackgroundTransparency = 1,
        Parent = box,
    })
    create("UIListLayout", {
        FillDirection = Enum.FillDirection.Horizontal,
        VerticalAlignment = Enum.VerticalAlignment.Center,
        SortOrder = Enum.SortOrder.LayoutOrder,
        Padding = UDim.new(0, 6),
        Parent = row,
    })
    local textColor = primary and Theme.AccentDark or Theme.Text
    if opts.Icon then
        local image = create("ImageLabel", {
            Size = UDim2.fromOffset(14, 14),
            BackgroundTransparency = 1,
            ImageColor3 = primary and Theme.AccentDark or Theme.Accent,
            ScaleType = Enum.ScaleType.Fit,
            LayoutOrder = 1,
            Parent = row,
        })
        applyIcon(image, opts.Icon)
    end
    local title = label({
        Size = UDim2.new(0, 0, 1, 0),
        AutomaticSize = Enum.AutomaticSize.X,
        Text = opts.Name or "Button",
        TextSize = 13,
        TextColor3 = textColor,
        TextTruncate = Enum.TextTruncate.None,
        LayoutOrder = 2,
        Parent = row,
    })
    if opts.Desc then
        label({
            Position = UDim2.fromOffset(14, boxHeight + 6),
            Size = UDim2.new(1, -28, 0, 14),
            Text = opts.Desc,
            TextSize = 12,
            FontFace = Fonts.Regular,
            TextColor3 = Theme.Muted,
            Parent = button,
        })
    end

    local restBg = primary and 0.12 or 0.45
    button.MouseEnter:Connect(function()
        tween(box, { BackgroundTransparency = primary and 0 or 0.2 }, 0.12)
        tween(boxStroke, primary and { Transparency = 0 } or { Color = Theme.StrokeHover }, 0.12)
    end)
    button.MouseLeave:Connect(function()
        tween(box, { BackgroundTransparency = restBg }, 0.25)
        tween(boxStroke, primary and { Transparency = 0.4 } or { Color = Theme.Stroke }, 0.25)
    end)
    button.MouseButton1Click:Connect(function()
        ripple(box)
        safeCall(opts.Callback)
    end)

    return finishElement(tab, opts, {
        SetText = function(_, value)
            title.Text = value
        end,
    }, button, "Button")
end

function Tab:Button(opts)
    opts = normalize(opts, { Title = "Name", Description = "Desc" })
    if metricsOf(self).Compact then
        return rowButton(self, opts)
    end
    local primary = opts.Style == "Primary"
    local height = opts.Desc and CARD_HEIGHT_DESC or CARD_HEIGHT
    local button, buttonStroke = card(self, "TextButton", height, opts)
    button.ClipsDescendants = true

    if primary then
        tween(button, { BackgroundColor3 = Theme.Accent, BackgroundTransparency = 0.12 }, 0)
        tween(buttonStroke, { Color = Theme.Accent }, 0)
        buttonStroke.Transparency = 0.4
        button.MouseEnter:Connect(function()
            tween(button, { BackgroundTransparency = 0 }, 0.12)
            tween(buttonStroke, { Transparency = 0 }, 0.12)
        end)
        button.MouseLeave:Connect(function()
            tween(button, { BackgroundTransparency = 0.12 }, 0.25)
            tween(buttonStroke, { Transparency = 0.4 }, 0.25)
        end)
    else
        hoverStroke(button, buttonStroke)
    end

    local textColor = primary and Theme.AccentDark or Theme.Text
    local iconOffset = 0
    if opts.Icon then
        glowIcon(button, opts.Icon, primary and Theme.AccentDark or Theme.Accent, UDim2.new(0, 14, 0.5, 0))
        iconOffset = 26
    end
    local title = titleDesc(button, opts.Name or "Button", opts.Desc, 30)
    if iconOffset > 0 then
        for _, child in ipairs(button:GetChildren()) do
            if child:IsA("TextLabel") then
                child.Position = child.Position + UDim2.fromOffset(iconOffset, 0)
                child.Size = child.Size - UDim2.fromOffset(iconOffset, 0)
            end
        end
    end
    if primary then
        for _, child in ipairs(button:GetChildren()) do
            if child:IsA("TextLabel") then
                tween(child, { TextColor3 = textColor }, 0)
            end
        end
    end

    glowIcon(button, BUTTON_HINT_ICON, primary and Theme.AccentDark or Theme.Muted, UDim2.new(1, -30, 0.5, 0))

    button.MouseButton1Click:Connect(function()
        ripple(button)
        safeCall(opts.Callback)
    end)

    return finishElement(self, opts, {
        SetText = function(_, value)
            title.Text = value
        end,
    }, button, "Button")
end

function Tab:Toggle(opts)
    local button, buttonStroke
    opts, button, buttonStroke = beginElement(self, opts, { Title = "Name", Description = "Desc", CurrentValue = "Default", Value = "Default" }, "TextButton", 56, "Toggle")

    local self_ = { Value = opts.Default == true }
    local skin

    local function buildSkin()
        if skin then
            skin.destroy()
            skin = nil
        end
        if Library.ForceCheckbox then
            -- checkbox skin
            local box = create("Frame", {
                AnchorPoint = Vector2.new(1, 0.5),
                Position = UDim2.new(1, -14, 0.5, 0),
                Size = TOUCH and UDim2.fromOffset(24, 24) or UDim2.fromOffset(20, 20),
                BackgroundColor3 = Theme.Surface2,
                BorderSizePixel = 0,
                Parent = button,
            })
            corner(box, UDim.new(0, 5))
            local boxStroke = stroke(box, Theme.Stroke)
            local check = create("ImageLabel", {
                AnchorPoint = Vector2.new(0.5, 0.5),
                Position = UDim2.fromScale(0.5, 0.5),
                Size = TOUCH and UDim2.fromOffset(14, 14) or UDim2.fromOffset(12, 12),
                BackgroundTransparency = 1,
                ImageColor3 = Theme.AccentDark,
                ImageTransparency = 1,
                ScaleType = Enum.ScaleType.Fit,
                Parent = box,
            })
            applyIcon(check, "check")
            local checkScale = create("UIScale", { Parent = check })
            skin = {
                destroy = function()
                    box:Destroy()
                end,
                render = function(animate)
                    local on = self_.Value
                    local duration = animate and 0.18 or 0
                    tween(box, { BackgroundColor3 = on and Theme.Accent or Theme.Surface2 }, duration)
                    tween(boxStroke, { Color = on and Theme.Accent or Theme.Stroke }, duration)
                    tween(check, { ImageTransparency = on and 0 or 1 }, duration)
                    if animate and on then
                        checkScale.Scale = 0.5
                        tween(checkScale, { Scale = 1 }, 0.3, Enum.EasingStyle.Back)
                    else
                        checkScale.Scale = 1
                    end
                end,
            }
        else
            -- switch skin
            local pill = create("Frame", {
                AnchorPoint = Vector2.new(1, 0.5),
                Position = UDim2.new(1, -14, 0.5, 0),
                Size = TOUCH and UDim2.fromOffset(44, 24) or UDim2.fromOffset(36, 20),
                BackgroundColor3 = Theme.Surface3,
                BorderSizePixel = 0,
                Parent = button,
            })
            corner(pill, UDim.new(1, 0))
            stroke(pill, Theme.Stroke)

            local knob = create("Frame", {
                AnchorPoint = Vector2.new(0, 0.5),
                Position = UDim2.new(0, 3, 0.5, 0),
                Size = TOUCH and UDim2.fromOffset(18, 18) or UDim2.fromOffset(14, 14),
                BackgroundColor3 = Theme.Muted,
                BorderSizePixel = 0,
                Parent = pill,
            })
            corner(knob, UDim.new(1, 0))
            local pillGlow = create("ImageLabel", {
                AnchorPoint = Vector2.new(0.5, 0.5),
                Position = UDim2.fromScale(0.5, 0.5),
                Size = UDim2.new(1, 24, 1, 24),
                BackgroundTransparency = 1,
                Image = Assets.Glow,
                ImageColor3 = Theme.Accent,
                ImageTransparency = 1,
                ZIndex = 0,
                Parent = pill,
            })
            skin = {
                destroy = function()
                    pill:Destroy()
                end,
                render = function(animate)
                    local on = self_.Value
                    local duration = animate and 0.25 or 0
                    tween(pill, { BackgroundColor3 = on and Theme.Accent or Theme.Surface3 }, duration)
                    tween(pillGlow, { ImageTransparency = on and 0.75 or 1 }, duration)
                    local knobSize = TOUCH and 18 or 14
                    tween(knob, {
                        Position = on and UDim2.new(0, (TOUCH and 44 or 36) - 3 - knobSize, 0.5, 0) or UDim2.new(0, 3, 0.5, 0),
                        BackgroundColor3 = on and Theme.AccentDark or Theme.Muted,
                    }, duration, Enum.EasingStyle.Back)
                    if animate then
                        tween(knob, { Size = UDim2.fromOffset(knobSize + 4, knobSize - 2) }, 0.08)
                        task.delay(0.08, function()
                            tween(knob, { Size = UDim2.fromOffset(knobSize, knobSize) }, 0.2, Enum.EasingStyle.Back)
                        end)
                    end
                end,
            }
        end
    end
    buildSkin()

    Library._toggleSkins[button] = function()
        if button:IsDescendantOf(game) then
            buildSkin()
            skin.render(false)
        end
    end

    local function render(animate)
        skin.render(animate)
    end

    local fromClick = false
    function self_:Set(value, silent)
        value = value == true
        if value == self_.Value then
            return
        end
        self_.Value = value
        render(true)
        if not fromClick then
            flashStroke(buttonStroke)
        end
        if not silent then
            safeCall(opts.Callback, value)
        end
    end

    function self_:Get()
        return self_.Value
    end

    render(false)
    button.MouseButton1Click:Connect(function()
        fromClick = true
        self_:Set(not self_.Value)
        fromClick = false
    end)

    local handle = finishElement(self, opts, self_, button, "Toggle")
    if self_.Value then
        safeCall(opts.Callback, true)
    end
    return handle
end

function Tab:Slider(opts)
    opts = normalize(opts, { Title = "Name", Description = "Desc", CurrentValue = "Default", Value = "Default", Increment = "Step" })
    local min = opts.Min or 0
    local max = opts.Max or 100
    local step = opts.Step or 1
    local suffix = opts.Suffix or ""
    local numbers = numberFormat(min, max, step)

    local metrics = metricsOf(self)
    local compact = metrics.Compact
    local height = metrics.Slider
    local frame, frameStroke = card(self, "Frame", height, opts)
    hoverStroke(frame, frameStroke)

    label({
        Position = UDim2.fromOffset(14, compact and 5 or 12),
        Size = UDim2.new(1, -120, 0, 18),
        Text = opts.Name or "Slider",
        TextSize = metrics.TextSize,
        Parent = frame,
    })

    local valueChip = create("Frame", {
        AnchorPoint = Vector2.new(1, 0),
        Position = UDim2.new(1, compact and -14 or -10, 0, compact and 2 or 9),
        Size = UDim2.fromOffset(40, 24),
        BackgroundColor3 = Theme.Surface,
        BorderSizePixel = 0,
        ClipsDescendants = true,
        Parent = frame,
    })
    corner(valueChip, UDim.new(0, 6))
    local chipStroke = stroke(valueChip)
    local valueLabel = label({
        Size = UDim2.new(1, 0, 1, 0),
        TextSize = 13,
        TextColor3 = Theme.Accent,
        TextXAlignment = Enum.TextXAlignment.Center,
        TextTruncate = Enum.TextTruncate.None,
        Parent = valueChip,
    })
    local valueBox = create("TextBox", {
        Position = UDim2.fromOffset(9, 0),
        Size = UDim2.new(0, 0, 1, 0),
        AutomaticSize = Enum.AutomaticSize.X,
        BackgroundTransparency = 1,
        Text = "",
        TextColor3 = Theme.Text,
        TextSize = 13,
        FontFace = Fonts.Medium,
        TextXAlignment = Enum.TextXAlignment.Left,
        ClearTextOnFocus = false,
        Visible = false,
        Parent = valueChip,
    })
    create("UISizeConstraint", { MinSize = Vector2.new(14, 0), Parent = valueBox })
    local suffixLabel = label({
        Size = UDim2.new(0, 0, 1, 0),
        AutomaticSize = Enum.AutomaticSize.X,
        Text = suffix,
        TextSize = 13,
        TextColor3 = Theme.Accent,
        TextTruncate = Enum.TextTruncate.None,
        Visible = false,
        Parent = valueChip,
    })
    local chipButton = create("TextButton", {
        Size = UDim2.fromScale(1, 1),
        BackgroundTransparency = 1,
        Text = "",
        AutoButtonColor = false,
        ZIndex = 2,
        Parent = valueChip,
    })
    local editing = false
    local function fitChip(instant)
        local width
        if editing then
            width = 9 + valueBox.AbsoluteSize.X / (self.Window.Scale.Scale) + suffixLabel.TextBounds.X + 9
            suffixLabel.Position = UDim2.fromOffset(9 + valueBox.AbsoluteSize.X / (self.Window.Scale.Scale), 0)
        else
            width = valueLabel.TextBounds.X + 18
        end
        width = math.max(width, 36)
        if instant then
            valueChip.Size = UDim2.fromOffset(width, 24)
        else
            tween(valueChip, { Size = UDim2.fromOffset(width, 24) }, 0.2)
        end
    end
    valueLabel:GetPropertyChangedSignal("TextBounds"):Connect(function()
        if not editing then
            fitChip(false)
        end
    end)
    valueBox:GetPropertyChangedSignal("AbsoluteSize"):Connect(function()
        if editing then
            fitChip(false)
        end
    end)

    local track = create("Frame", {
        Position = UDim2.new(0, 14, 0, height - (compact and 13 or 18)),
        Size = UDim2.new(1, -28, 0, 5),
        BackgroundColor3 = Theme.Surface3,
        BorderSizePixel = 0,
        Parent = frame,
    })
    corner(track, UDim.new(1, 0))
    local fill = create("Frame", {
        Size = UDim2.new(0, 0, 1, 0),
        BackgroundColor3 = Theme.Accent,
        BorderSizePixel = 0,
        Parent = track,
    })
    corner(fill, UDim.new(1, 0))

    local knobGlow = create("ImageLabel", {
        AnchorPoint = Vector2.new(0.5, 0.5),
        Position = UDim2.new(0, 0, 0.5, 0),
        Size = UDim2.fromOffset(28, 28),
        BackgroundTransparency = 1,
        Image = Assets.Glow,
        ImageColor3 = Theme.Accent,
        ImageTransparency = 0.85,
        ZIndex = 2,
        Parent = track,
    })
    local knob = create("Frame", {
        AnchorPoint = Vector2.new(0.5, 0.5),
        Position = UDim2.new(0, 0, 0.5, 0),
        Size = UDim2.fromOffset(12, 12),
        BackgroundColor3 = Theme.Accent,
        BorderSizePixel = 0,
        ZIndex = 3,
        Parent = track,
    })
    corner(knob, UDim.new(1, 0))

    local hit = create("TextButton", {
        Position = UDim2.new(0, 8, 0, height - (compact and 13 or 18) - (TOUCH and 19 or 13)),
        Size = UDim2.new(1, -16, 0, TOUCH and 40 or 28),
        BackgroundTransparency = 1,
        Text = "",
        AutoButtonColor = false,
        ZIndex = 4,
        Parent = frame,
    })

    local self_ = { Value = math.clamp(opts.Default or min, min, max) }
    local dragging = false
    chipButton.MouseEnter:Connect(function()
        tween(chipStroke, { Color = Theme.StrokeHover }, 0.12)
    end)
    chipButton.MouseLeave:Connect(function()
        if not valueBox:IsFocused() then
            tween(chipStroke, { Color = Theme.Stroke }, 0.2)
        end
    end)
    chipButton.MouseButton1Click:Connect(function()
        editing = true
        valueBox.Text = numbers.format(self_.Value)
        valueLabel.Visible = false
        valueBox.Visible = true
        suffixLabel.Visible = suffix ~= ""
        chipButton.Visible = false
        tween(chipStroke, { Color = Theme.StrokeHover }, 0.12)
        valueBox:CaptureFocus()
        task.defer(fitChip, false)
    end)
    valueBox.FocusLost:Connect(function()
        local typed = tonumber(valueBox.Text)
        editing = false
        valueBox.Visible = false
        suffixLabel.Visible = false
        valueLabel.Visible = true
        chipButton.Visible = true
        tween(chipStroke, { Color = Theme.Stroke }, 0.2)
        if typed then
            self_:Set(typed)
        end
        fitChip(false)
    end)
    hit.MouseEnter:Connect(function()
        if not dragging then
            tween(knobGlow, { ImageTransparency = 0.78, Size = UDim2.fromOffset(34, 34) }, 0.15)
        end
    end)
    hit.MouseLeave:Connect(function()
        if not dragging then
            tween(knobGlow, { ImageTransparency = 0.85, Size = UDim2.fromOffset(28, 28) }, 0.2)
        end
    end)

    local snap = numbers.snap

    local function fraction()
        return (max - min) == 0 and 0 or (self_.Value - min) / (max - min)
    end

    local function moveTo(frac, duration, style)
        style = style or Enum.EasingStyle.Linear
        tween(fill, { Size = UDim2.new(frac, 0, 1, 0) }, duration, style)
        tween(knob, { Position = UDim2.new(frac, 0, 0.5, 0) }, duration, style)
        tween(knobGlow, { Position = UDim2.new(frac, 0, 0.5, 0) }, duration, style)
    end

    local function render(duration, style)
        moveTo(fraction(), duration, style)
        valueLabel.Text = numbers.format(self_.Value) .. suffix
    end

    local function settleTo(previousFrac)
        local target = fraction()
        local width = math.max(track.AbsoluteSize.X, 1)
        local overshoot = (target >= previousFrac and 1 or -1) * (5 / width)
        moveTo(math.clamp(target + overshoot, 0, 1), 0.22, Enum.EasingStyle.Quint)
        task.delay(0.22, function()
            if not dragging then
                moveTo(fraction(), 0.18, Enum.EasingStyle.Quint)
            end
        end)
        valueLabel.Text = numbers.format(self_.Value) .. suffix
    end

    local function bounceKnob()
        tween(knob, { Size = UDim2.fromOffset(14, 12) }, 0.08)
        tween(knobGlow, { Size = UDim2.fromOffset(32, 32), ImageTransparency = 0.78 }, 0.12)
        task.delay(0.1, function()
            tween(knob, { Size = UDim2.fromOffset(12, 12) }, 0.25, Enum.EasingStyle.Quint)
            tween(knobGlow, { Size = UDim2.fromOffset(28, 28), ImageTransparency = 0.85 }, 0.25)
        end)
    end

    function self_:Set(value, silent)
        value = snap(tonumber(value) or min)
        if value == self_.Value then
            return
        end
        local previousFrac = fraction()
        self_.Value = value
        if dragging then
            render(0.05)
        else
            settleTo(previousFrac)
            bounceKnob()
            flashStroke(frameStroke)
        end
        if not silent then
            safeCall(opts.Callback, value)
        end
    end

    function self_:Get()
        return self_.Value
    end

    local function updateFromX(x)
        local frac = math.clamp((x - track.AbsolutePosition.X) / track.AbsoluteSize.X, 0, 1)
        self_:Set(min + (max - min) * frac)
    end

    hit.InputBegan:Connect(function(input)
        if isPress(input) then
            dragging = true
            self_.Dragging = true
            tween(knob, { Size = UDim2.fromOffset(16, 16) }, 0.15, Enum.EasingStyle.Back)
            tween(knobGlow, { Size = UDim2.fromOffset(44, 44), ImageTransparency = 0.7 }, 0.15)
            updateFromX(pointerPosition().X)
        end
    end)

    self.Window:_listen("Changed", function(input)
        if dragging and isMove(input) then
            updateFromX(pointerPosition().X)
        end
    end, self_)

    self.Window:_listen("Ended", function(input)
        if dragging and isPress(input) then
            dragging = false
            self_.Dragging = false
            tween(knob, { Size = UDim2.fromOffset(12, 12) }, 0.2)
            tween(knobGlow, { Size = UDim2.fromOffset(28, 28), ImageTransparency = 0.85 }, 0.2)
            safeCall(opts.OnRelease, self_.Value)
        end
    end, self_)

    self_.Value = snap(self_.Value)
    render(0)
    task.defer(fitChip, true)
    return finishElement(self, opts, self_, frame, "Slider")
end

function Tab:Dropdown(opts)
    opts = normalize(opts, { Title = "Name", Description = "Desc", CurrentOption = "Default", Value = "Default", MultipleOptions = "Multi", Values = "Options" })
    if opts.Multi and type(opts.Default) ~= "table" and opts.Default ~= nil then
        opts.Default = { opts.Default }
    elseif not opts.Multi and type(opts.Default) == "table" then
        opts.Default = opts.Default[1]
    end
    local multi = opts.Multi == true
    local options = opts.Options or {}
    local frame, frameStroke, height
    opts, frame, frameStroke, height = beginElement(self, opts, {}, "Frame")
    local metrics = metricsOf(self)
    local compact = metrics.Compact
    local chipHeight = metrics.Chip
    local window = self.Window
    local ROW = TOUCH and 40 or 30
    local MAX_ROWS = opts.MaxRows or 6
    -- stacked: chip spans the row, name above.
    local stacked = compact and opts.Stacked == true
    local stackTop = 2
    if stacked then
        stackTop = (opts.Name or "") ~= "" and 20 or 2
        chipHeight = TOUCH and 34 or 30
        height = stackTop + chipHeight + 4
        frame.Size = UDim2.new(1, 0, 0, height)
    end

    local header = create("TextButton", {
        Size = UDim2.new(1, 0, 0, height),
        BackgroundTransparency = 1,
        Text = "",
        AutoButtonColor = false,
        Parent = frame,
    })
    local titleLabel, descLabel
    if not stacked then
        titleLabel, descLabel = titleDesc(header, opts.Name or "Dropdown", opts.Desc, 180, metrics)
    elseif stackTop > 2 then
        titleLabel = label({
            Position = UDim2.fromOffset(14, 1),
            Size = UDim2.new(1, -28, 0, 16),
            Text = opts.Name,
            TextSize = metrics.TextSize,
            Parent = header,
        })
    end

    local chip = create("Frame", {
        AnchorPoint = stacked and Vector2.zero or Vector2.new(1, 0.5),
        Position = stacked and UDim2.fromOffset(14, stackTop) or UDim2.new(1, compact and -14 or -10, 0.5, 0),
        Size = UDim2.fromOffset(60, chipHeight),
        BackgroundColor3 = Theme.Surface,
        BorderSizePixel = 0,
        ClipsDescendants = true,
        Parent = header,
    })
    corner(chip, UDim.new(0, 6))
    local chipStroke = stroke(chip)
    local valueLabel = label({
        Position = UDim2.fromOffset(10, 0),
        Size = UDim2.new(1, -34, 1, 0),
        TextColor3 = Theme.Muted,
        TextSize = 13,
        TextTruncate = Enum.TextTruncate.None,
        ClipsDescendants = true,
        Parent = chip,
    })
    local arrow = arrowIndicator(chip, 1, -6)
    local measure = label({
        Size = UDim2.fromOffset(0, chipHeight),
        AutomaticSize = Enum.AutomaticSize.X,
        TextSize = 13,
        Visible = false,
        Parent = chip,
    })
    local fullText = ""
    local function trimmed()
        local maxText = (stacked and frame.AbsoluteSize.X / window.Scale.Scale - 28 or compact and rowControlWidth(frame, window) or 190) - 10 - 34
        measure.Text = fullText
        if measure.TextBounds.X <= maxText then
            return fullText
        end
        local text = fullText
        while #text > 1 do
            text = text:sub(1, -2)
            measure.Text = text .. ".."
            if measure.TextBounds.X <= maxText then
                return text .. ".."
            end
        end
        return ".."
    end
    local function fitChip(instant)
        if stacked then
            chip.Size = UDim2.new(1, -28, 0, chipHeight)
            return
        end
        local width
        if compact then
            width = rowControlWidth(frame, window)
        else
            width = math.clamp(valueLabel.TextBounds.X + 10 + 34, 60, 190)
        end
        reserveRight(titleLabel, descLabel, width + (compact and 24 or 20))
        if instant then
            chip.Size = UDim2.fromOffset(width, chipHeight)
        else
            tween(chip, { Size = UDim2.fromOffset(width, chipHeight) }, 0.2)
        end
    end
    valueLabel:GetPropertyChangedSignal("TextBounds"):Connect(function()
        if not compact then
            fitChip(false)
        end
    end)
    if compact then
        local lastWidth, pending = 0, false
        frame:GetPropertyChangedSignal("AbsoluteSize"):Connect(function()
            local width = frame.AbsoluteSize.X
            if width == lastWidth then
                return
            end
            lastWidth = width
            fitChip(true)
            if not pending then
                pending = true
                task.delay(0.12, function()
                    pending = false
                    valueLabel.Text = trimmed()
                end)
            end
        end)
    end

    local popup = create("Frame", {
        AnchorPoint = Vector2.new(1, 0),
        Size = UDim2.fromOffset(220, 0),
        BackgroundTransparency = 1,
        Visible = false,
        ZIndex = 45,
        Parent = window.Body,
    })
    popup:SetAttribute("NoDrag", true)
    local popupShadow = create("ImageLabel", {
        Position = UDim2.fromOffset(-18, -12),
        Size = UDim2.new(1, 36, 1, 36),
        BackgroundTransparency = 1,
        Image = Assets.Shadow,
        ImageColor3 = Color3.new(0, 0, 0),
        ImageTransparency = 1,
        ScaleType = Enum.ScaleType.Slice,
        SliceCenter = Rect.new(49, 49, 450, 450),
        Parent = popup,
    })
    local panel = create("Frame", {
        Size = UDim2.fromScale(1, 1),
        BackgroundColor3 = Theme.Background,
        BorderSizePixel = 0,
        ClipsDescendants = true,
        Parent = popup,
    })
    corner(panel, UDim.new(0, 10))
    local panelStroke = stroke(panel, Theme.Stroke, 1)
    edgeHighlight(panel)
    local inner = create("Frame", {
        Size = UDim2.new(1, 0, 0, 120),
        BackgroundTransparency = 1,
        Parent = panel,
    })
    padding(inner, 8, 8, 8, 8)

    local searchHolder = create("Frame", {
        Size = UDim2.new(1, 0, 0, 32),
        BackgroundColor3 = Theme.Surface,
        BorderSizePixel = 0,
        Parent = inner,
    })
    corner(searchHolder, UDim.new(0, 7))
    local searchStroke = stroke(searchHolder)
    local searchIconHolder, searchIcon = glowIcon(searchHolder, "search", Theme.Muted, UDim2.new(0, 10, 0.5, 0))
    searchIconHolder.Size = UDim2.fromOffset(14, 14)
    local searchBox = create("TextBox", {
        Position = UDim2.fromOffset(32, 0),
        Size = UDim2.new(1, -40, 1, 0),
        BackgroundTransparency = 1,
        Text = "",
        PlaceholderText = opts.SearchPlaceholder or "Search",
        PlaceholderColor3 = Theme.Muted,
        TextColor3 = Theme.Text,
        TextSize = 13,
        FontFace = Fonts.Regular,
        TextXAlignment = Enum.TextXAlignment.Left,
        TextTruncate = Enum.TextTruncate.AtEnd,
        ClearTextOnFocus = false,
        Parent = searchHolder,
    })
    searchBox.Focused:Connect(function()
        tween(searchStroke, { Color = Theme.StrokeHover }, 0.15)
        tween(searchIcon, { ImageColor3 = Theme.Accent }, 0.15)
    end)
    searchBox.FocusLost:Connect(function()
        tween(searchStroke, { Color = Theme.Stroke }, 0.2)
        tween(searchIcon, { ImageColor3 = Theme.Muted }, 0.2)
    end)

    local actions = create("Frame", {
        Size = UDim2.new(1, 0, 0, 28),
        BackgroundTransparency = 1,
        Visible = multi,
        Parent = inner,
    })
    local function actionButton(text, position)
        local button = create("TextButton", {
            Position = position,
            Size = UDim2.new(0.5, -3, 1, 0),
            BackgroundColor3 = Theme.Surface3,
            BackgroundTransparency = 0.35,
            BorderSizePixel = 0,
            Text = "",
            AutoButtonColor = false,
            ClipsDescendants = true,
            Parent = actions,
        })
        corner(button, UDim.new(0, 6))
        local buttonStroke = stroke(button)
        label({
            Size = UDim2.fromScale(1, 1),
            Text = text,
            TextSize = 12,
            TextXAlignment = Enum.TextXAlignment.Center,
            Parent = button,
        })
        button.MouseEnter:Connect(function()
            tween(button, { BackgroundTransparency = 0.05 }, 0.15)
            tween(buttonStroke, { Color = Theme.StrokeHover }, 0.15)
        end)
        button.MouseLeave:Connect(function()
            tween(button, { BackgroundTransparency = 0.35 }, 0.25)
            tween(buttonStroke, { Color = Theme.Stroke }, 0.25)
        end)
        button.MouseButton1Click:Connect(function()
            ripple(button)
        end)
        return button
    end
    local selectAll = actionButton(opts.SelectAllText or "Select all", UDim2.fromOffset(0, 0))
    local clearAll = actionButton(opts.ClearAllText or "Clear all", UDim2.new(0.5, 3, 0, 0))

    local list = create("ScrollingFrame", {
        Size = UDim2.new(1, 0, 0, 100),
        BackgroundTransparency = 1,
        BorderSizePixel = 0,
        ScrollBarThickness = TOUCH and 4 or 3,
        ScrollBarImageColor3 = Theme.Accent,
        ScrollBarImageTransparency = 0.4,
        ScrollingDirection = Enum.ScrollingDirection.Y,
        CanvasSize = UDim2.new(),
        Parent = inner,
    })
    create("UIListLayout", {
        SortOrder = Enum.SortOrder.LayoutOrder,
        Padding = UDim.new(0, 2),
        Parent = list,
    })
    local noResults = label({
        Size = UDim2.new(1, 0, 0, ROW),
        Text = opts.NoResultsText or "No results",
        TextSize = 13,
        FontFace = Fonts.Regular,
        TextColor3 = Theme.Muted,
        TextXAlignment = Enum.TextXAlignment.Center,
        LayoutOrder = 0,
        Visible = false,
        Parent = list,
    })

    local self_ = { Open = false }
    local selected = {}
    local optionButtons = {}
    local filter = ""

    local function matches(option)
        return filter == "" or string.find(string.lower(tostring(option)), filter, 1, true) ~= nil
    end

    -- rich text so search matches can highlight.
    local function escapeRich(text)
        return (text:gsub("&", "&amp;"):gsub("<", "&lt;"):gsub(">", "&gt;"))
    end
    local function optionText(option)
        local text = tostring(option)
        local at = filter ~= "" and string.find(string.lower(text), filter, 1, true)
        if not at then
            return escapeRich(text)
        end
        local stop = at + #filter - 1
        return escapeRich(text:sub(1, at - 1))
            .. '<font color="#' .. Theme.Accent:ToHex() .. '"><b>' .. escapeRich(text:sub(at, stop)) .. "</b></font>"
            .. escapeRich(text:sub(stop + 1))
    end

    if multi then
        for _, value in ipairs(opts.Default or {}) do
            selected[value] = true
        end
    elseif opts.Default ~= nil then
        selected[opts.Default] = true
    end

    local function currentValue()
        if multi then
            local picked = {}
            for _, option in ipairs(options) do
                if selected[option] then
                    table.insert(picked, option)
                end
            end
            return picked
        end
        for _, option in ipairs(options) do
            if selected[option] then
                return option
            end
        end
        return nil
    end

    -- picked rows get a faint accent tint.
    local function restRow(entry, duration)
        local on, hover = entry.On == true, entry.Hover == true
        tween(entry.Frame, {
            BackgroundColor3 = on and Theme.Accent or Theme.Surface3,
            BackgroundTransparency = on and (hover and 0.8 or 0.88) or (hover and 0.55 or 1),
        }, duration)
        tween(entry.Label, { TextColor3 = (on or hover) and Theme.Text or Theme.Muted }, duration)
    end

    local function paintOption(button, animate)
        local on = selected[button.Option] == true
        if button.On == on and animate then
            return
        end
        button.On = on
        local duration = animate and 0.18 or 0
        restRow(button, duration)
        if multi then
            tween(button.Box, { BackgroundColor3 = on and Theme.Accent or Theme.Surface2 }, duration)
            tween(button.BoxStroke, { Color = on and Theme.Accent or Theme.Stroke }, duration)
        else
            tween(button.Bar, {
                BackgroundTransparency = on and 0 or 1,
                Size = UDim2.fromOffset(3, on and ROW - 14 or 4),
            }, animate and 0.3 or 0, Enum.EasingStyle.Quint)
        end
        tween(button.Check, { ImageTransparency = on and 0 or 1 }, duration)
        if animate and on then
            button.CheckScale.Scale = 0.5
            tween(button.CheckScale, { Scale = 1 }, 0.3, Enum.EasingStyle.Back)
        else
            button.CheckScale.Scale = 1
        end
    end

    local function renderValue(animate)
        local value = currentValue()
        if #options == 0 then
            fullText = opts.EmptyText or "None"
        elseif multi then
            -- Two names at most, then a count, so a long pick stays readable.
            if #value > 2 then
                fullText = tostring(value[1]) .. ", " .. tostring(value[2]) .. "  +" .. (#value - 2)
            else
                fullText = #value > 0 and table.concat(value, ", ") or (opts.NoneText or "None")
            end
        else
            fullText = value ~= nil and tostring(value) or (opts.NoneText or "None")
        end
        valueLabel.Text = trimmed()
        -- A picked value reads in full colour; "None" stays muted.
        local picked = #options > 0 and (if multi then #value > 0 else value ~= nil)
        tween(valueLabel, { TextColor3 = picked and Theme.Text or Theme.Muted }, animate and 0.15 or 0)
        for _, button in pairs(optionButtons) do
            paintOption(button, animate)
        end
    end

    local function visibleCount()
        local count = 0
        for _, option in ipairs(options) do
            if matches(option) then
                count += 1
            end
        end
        return count
    end

    local searchShown = true
    local targetSize = Vector2.new(220, 120)
    local opened = false
    local function layoutPopup(instant)
        searchShown = opts.Searchable ~= false and #options > (opts.SearchAfter or 0)
        searchHolder.Visible = searchShown
        local top = 0
        if searchShown then
            top += 38
        end
        actions.Position = UDim2.fromOffset(0, top)
        if multi and #options > 0 then
            actions.Visible = true
            top += 34
        else
            actions.Visible = false
        end
        local count = visibleCount()
        noResults.Visible = count == 0
        local rows = math.clamp(count, 1, MAX_ROWS)
        local listHeight = rows * ROW + (rows - 1) * 2
        list.CanvasSize = UDim2.fromOffset(0, math.max(count, 1) * (ROW + 2) - 2)
        local scale = window.Scale.Scale
        local host = window:_popupHost(frame)
        local bodyHeight = host.AbsoluteSize.Y / scale
        local chipTop = (chip.AbsolutePosition.Y - host.AbsolutePosition.Y) / scale
        local room = math.max(bodyHeight - (chipTop + chip.AbsoluteSize.Y / scale) - 14, chipTop - 14) - top - 16
        if room >= ROW then
            listHeight = math.min(listHeight, room)
        end
        list.Position = UDim2.fromOffset(0, top)
        list.Size = UDim2.new(1, 0, 0, listHeight)
        local width = math.max(math.floor(chip.AbsoluteSize.X / scale), opts.PopupWidth or 210)
        local bodyWidth = host.AbsoluteSize.X / scale
        width = math.min(width, math.max(bodyWidth - 16, 120))
        targetSize = Vector2.new(width, top + listHeight + 16)
        inner.Size = UDim2.new(1, 0, 0, targetSize.Y)
        if not opened then
            return
        end
        if instant then
            popup.Size = UDim2.fromOffset(targetSize.X, targetSize.Y)
        else
            tween(popup, { Size = UDim2.fromOffset(targetSize.X, targetSize.Y) }, 0.22, Enum.EasingStyle.Quint)
        end
    end

    local function applyFilter()
        for option, button in pairs(optionButtons) do
            local shown = matches(option)
            button.Frame.Visible = shown
            if shown then
                button.Label.Text = optionText(option)
            end
        end
    end

    local scroller = nil
    local function place()
        local body = window:_popupHost(frame)
        local scale = window.Scale.Scale
        if scroller then
            local centre = chip.AbsolutePosition + chip.AbsoluteSize / 2
            if not pointInside(centre, scroller) then
                self_:SetOpen(false)
                return
            end
        end
        local bodySize = body.AbsoluteSize / scale
        local chipPosition = (chip.AbsolutePosition - body.AbsolutePosition) / scale
        local chipSize = chip.AbsoluteSize / scale
        local right = math.clamp(chipPosition.X + chipSize.X, targetSize.X + 8, math.max(bodySize.X - 8, targetSize.X + 8))
        local below = chipPosition.Y + chipSize.Y + 6
        -- opening upward pins content to the bottom edge.
        if below + targetSize.Y > bodySize.Y - 8 and chipPosition.Y - 6 - targetSize.Y >= 8 then
            popup.AnchorPoint = Vector2.new(1, 1)
            popup.Position = UDim2.fromOffset(right, chipPosition.Y - 6)
            inner.AnchorPoint = Vector2.new(0, 1)
            inner.Position = UDim2.fromScale(0, 1)
        else
            popup.AnchorPoint = Vector2.new(1, 0)
            popup.Position = UDim2.fromOffset(right, below)
            inner.AnchorPoint = Vector2.zero
            inner.Position = UDim2.fromScale(0, 0)
        end
    end

    local stopFollowing = nil
    local closeGeneration = 0
    local lockedScroller = nil
    local function unlockScroller()
        if lockedScroller then
            lockedScroller.ScrollingEnabled = true
            lockedScroller = nil
        end
    end
    local function scrollToSelected()
        list.CanvasPosition = Vector2.zero
        if multi then
            return
        end
        local value = currentValue()
        if value == nil then
            return
        end
        for index, option in ipairs(options) do
            if option == value then
                list.CanvasPosition = Vector2.new(0, math.max(0, (index - 2) * (ROW + 2)))
                return
            end
        end
    end
    local function setOpen(open)
        if open == self_.Open then
            return
        end
        self_.Open = open
        arrow:Set(open)
        tween(chipStroke, { Color = open and Theme.Accent or Theme.Stroke, Transparency = open and 0.35 or 0 }, 0.2)
        tween(chip, { BackgroundColor3 = open and Theme.Surface2 or Theme.Surface }, 0.2)
        closeGeneration += 1
        if open then
            if window._closePopup and window._closePopup ~= self_._close then
                window._closePopup()
            end
            window._closePopup = self_._close
            scroller = frame:FindFirstAncestorWhichIsA("ScrollingFrame")
            if scroller and scroller.ScrollingEnabled then
                lockedScroller = scroller
                scroller.ScrollingEnabled = false
            end
            -- Drawn over a floating panel when the dropdown lives in one.
            popup.Parent = window:_popupHost(frame)
            filter = ""
            searchBox.Text = ""
            searchBox.PlaceholderText = opts.SearchPlaceholder or (#options > 6 and ("Search " .. #options .. " options") or "Search")
            applyFilter()
            layoutPopup(true)
            renderValue(false)
            scrollToSelected()
            opened = true
            popup.Size = UDim2.fromOffset(targetSize.X, 0)
            place()
            popup.Visible = true
            tween(popup, { Size = UDim2.fromOffset(targetSize.X, targetSize.Y) }, 0.3, Enum.EasingStyle.Quint)
            tween(panelStroke, { Transparency = 0 }, 0.12)
            tween(popupShadow, { ImageTransparency = 0.4 }, 0.3)
            if not stopFollowing then
                stopFollowing = window:_listen("Render", place)
            end
        else
            if window._closePopup == self_._close then
                window._closePopup = nil
            end
            unlockScroller()
            if searchBox:IsFocused() then
                searchBox:ReleaseFocus()
            end
            opened = false
            tween(popup, { Size = UDim2.fromOffset(targetSize.X, 0) }, 0.2, Enum.EasingStyle.Quint)
            tween(popupShadow, { ImageTransparency = 1 }, 0.16)
            local generation = closeGeneration
            task.delay(0.14, function()
                if closeGeneration == generation and not self_.Open then
                    tween(panelStroke, { Transparency = 1 }, 0.06)
                end
            end)
            task.delay(0.21, function()
                if closeGeneration == generation and not self_.Open then
                    popup.Visible = false
                    if stopFollowing then
                        stopFollowing()
                        stopFollowing = nil
                    end
                end
            end)
        end
    end
    self_._close = function()
        setOpen(false)
    end

    local function commit()
        renderValue(true)
        safeCall(opts.Callback, currentValue())
    end

    local function buildOptions()
        local keep = {}
        for index, option in ipairs(options) do
            keep[option] = index
        end
        for option, button in pairs(optionButtons) do
            if not keep[option] then
                button.Frame:Destroy()
                optionButtons[option] = nil
            end
        end
        for index, option in ipairs(options) do
            local existing = optionButtons[option]
            if existing then
                existing.Frame.LayoutOrder = index
                continue
            end
            local row = create("TextButton", {
                Size = UDim2.new(1, -6, 0, ROW),
                BackgroundColor3 = Theme.Surface3,
                BackgroundTransparency = 1,
                BorderSizePixel = 0,
                Text = "",
                AutoButtonColor = false,
                LayoutOrder = index,
                Parent = list,
            })
            corner(row, UDim.new(0, 7))
            local box, boxStroke, bar, check
            if multi then
                box = create("Frame", {
                    AnchorPoint = Vector2.new(0, 0.5),
                    Position = UDim2.new(0, 8, 0.5, 0),
                    Size = UDim2.fromOffset(18, 18),
                    BackgroundColor3 = Theme.Surface2,
                    BorderSizePixel = 0,
                    Parent = row,
                })
                corner(box, UDim.new(0, 5))
                boxStroke = stroke(box, Theme.Stroke)
                check = create("ImageLabel", {
                    AnchorPoint = Vector2.new(0.5, 0.5),
                    Position = UDim2.fromScale(0.5, 0.5),
                    Size = UDim2.fromOffset(12, 12),
                    BackgroundTransparency = 1,
                    ImageColor3 = Theme.AccentDark,
                    ImageTransparency = 1,
                    ScaleType = Enum.ScaleType.Fit,
                    Parent = box,
                })
            else
                bar = create("Frame", {
                    AnchorPoint = Vector2.new(0, 0.5),
                    Position = UDim2.new(0, 3, 0.5, 0),
                    Size = UDim2.fromOffset(3, 4),
                    BackgroundColor3 = Theme.Accent,
                    BackgroundTransparency = 1,
                    BorderSizePixel = 0,
                    Parent = row,
                })
                corner(bar, UDim.new(1, 0))
                check = create("ImageLabel", {
                    AnchorPoint = Vector2.new(1, 0.5),
                    Position = UDim2.new(1, -10, 0.5, 0),
                    Size = UDim2.fromOffset(14, 14),
                    BackgroundTransparency = 1,
                    ImageColor3 = Theme.Accent,
                    ImageTransparency = 1,
                    ScaleType = Enum.ScaleType.Fit,
                    Parent = row,
                })
            end
            applyIcon(check, "check")
            local checkScale = create("UIScale", { Parent = check })
            local text_ = label({
                Position = UDim2.fromOffset(multi and 36 or 14, 0),
                Size = UDim2.new(1, multi and -44 or -46, 1, 0),
                Text = optionText(option),
                TextSize = 13,
                TextColor3 = Theme.Muted,
                RichText = true,
                Parent = row,
            })
            local entry = { Option = option, Frame = row, Box = box, BoxStroke = boxStroke, Bar = bar, Check = check, CheckScale = checkScale, Label = text_, On = nil, Hover = false }
            local isTap = tapGuard(row, function()
                return list
            end)
            row.MouseEnter:Connect(function()
                -- Touch fires enter without a matching leave; skip the hover.
                if usingTouch() then
                    return
                end
                entry.Hover = true
                restRow(entry, 0.15)
                if boxStroke and not selected[option] then
                    tween(boxStroke, { Color = Theme.StrokeHover }, 0.15)
                end
            end)
            row.MouseLeave:Connect(function()
                entry.Hover = false
                restRow(entry, 0.25)
                if boxStroke and not selected[option] then
                    tween(boxStroke, { Color = Theme.Stroke }, 0.25)
                end
            end)
            row.MouseButton1Click:Connect(function()
                if not isTap() then
                    return
                end
                if selected[option] then
                    if not multi and opts.AllowNone == false then
                        setOpen(false)
                        return
                    end
                    selected[option] = nil
                else
                    if not multi then
                        selected = {}
                    end
                    selected[option] = true
                end
                commit()
                if not multi then
                    setOpen(false)
                end
            end)
            optionButtons[option] = entry
            paintOption(entry, false)
        end
        applyFilter()
        if self_.Open then
            layoutPopup(false)
        end
    end

    selectAll.MouseButton1Click:Connect(function()
        for _, option in ipairs(options) do
            if matches(option) then
                selected[option] = true
            end
        end
        commit()
    end)
    clearAll.MouseButton1Click:Connect(function()
        selected = {}
        commit()
    end)

    function self_:Set(value, silent)
        selected = {}
        if multi then
            for _, item in ipairs(type(value) == "table" and value or { value }) do
                selected[item] = true
            end
        elseif value ~= nil then
            selected[value] = true
        end
        renderValue(self_.Open)
        flashStroke(frameStroke)
        if not silent then
            safeCall(opts.Callback, currentValue())
        end
    end

    function self_:Get()
        return currentValue()
    end

    local function sameValue(a, b)
        if type(a) ~= "table" or type(b) ~= "table" then
            return a == b
        end
        if #a ~= #b then
            return false
        end
        for index, item in ipairs(a) do
            if b[index] ~= item then
                return false
            end
        end
        return true
    end

    function self_:Refresh(newOptions, keepSelection, silent)
        local before = currentValue()
        options = newOptions or {}
        if not keepSelection then
            selected = {}
        end
        buildOptions()
        renderValue(false)
        if not silent and not sameValue(before, currentValue()) then
            safeCall(opts.Callback, currentValue())
        end
    end

    function self_:_saveValue()
        local picked = currentValue()
        if multi then
            local seen = {}
            for _, item in ipairs(picked) do
                seen[item] = true
            end
            for item in pairs(selected) do
                if not seen[item] then
                    table.insert(picked, item)
                end
            end
            return picked
        end
        if picked == nil then
            picked = next(selected)
        end
        return picked
    end

    function self_:SetOpen(open)
        setOpen(open == true)
    end

    local headerTap = tapGuard(header, function()
        return frame:FindFirstAncestorWhichIsA("ScrollingFrame")
    end)
    header.MouseButton1Click:Connect(function()
        if headerTap() then
            setOpen(not self_.Open)
        end
    end)
    header.MouseEnter:Connect(function()
        if not self_.Open and not usingTouch() then
            tween(chipStroke, { Color = Theme.StrokeHover }, 0.15)
            tween(chip, { BackgroundColor3 = Theme.Surface2 }, 0.15)
        end
    end)
    header.MouseLeave:Connect(function()
        if not self_.Open then
            tween(chipStroke, { Color = Theme.Stroke }, 0.25)
            tween(chip, { BackgroundColor3 = Theme.Surface }, 0.25)
        end
    end)
    searchBox:GetPropertyChangedSignal("Text"):Connect(function()
        filter = string.lower(searchBox.Text)
        applyFilter()
        if self_.Open then
            layoutPopup(false)
        end
    end)
    self_._listeners = {
        function()
            setOpen(false)
            unlockScroller()
            if stopFollowing then
                stopFollowing()
                stopFollowing = nil
            end
            popup:Destroy()
        end,
    }
    window:_listen("Began", function(input)
        if not self_.Open then
            return
        end
        if input.KeyCode == Enum.KeyCode.Escape then
            setOpen(false)
        elseif isPress(input) then
            local point = pointerPosition()
            if not pointInside(point, popup) and not pointInside(point, header) then
                setOpen(false)
            end
        end
    end, self_)

    buildOptions()
    renderValue(false)
    task.defer(fitChip, true)
    return finishElement(self, opts, self_, frame, "Dropdown")
end

Library._amountSuffixes = { k = 1e3, m = 1e6, b = 1e9, t = 1e12, qa = 1e15, qi = 1e18 }

function Library._parseAmount(text)
    text = string.lower(tostring(text)):gsub("[%s,_%$]", "")
    text = text:gsub("kg$", ""):gsub("/s$", "")
    local number = tonumber(text)
    if number then
        return number
    end
    local digits, suffix = text:match("^(.-)(%a+)$")
    local scale = suffix and Library._amountSuffixes[suffix]
    number = digits and tonumber(digits)
    if number and scale then
        return number * scale
    end
    return nil
end

function Tab:Input(opts)
    local frame, frameStroke, _, titleLabel, descLabel
    opts, frame, frameStroke, _, titleLabel, descLabel = beginElement(self, opts, { Title = "Name", Description = "Desc", PlaceholderText = "Placeholder", CurrentValue = "Default", Value = "Default" }, "Frame", 160, "Input")
    local compact = metricsOf(self).Compact
    local boxHeight = compact and metricsOf(self).Chip + 2 or 30

    local boxHolder = create("Frame", {
        AnchorPoint = Vector2.new(1, 0.5),
        Position = UDim2.new(1, compact and -14 or -10, 0.5, 0),
        Size = UDim2.fromOffset(170, boxHeight),
        BackgroundColor3 = Theme.Surface,
        BorderSizePixel = 0,
        Parent = frame,
    })
    corner(boxHolder, UDim.new(0, 6))
    local boxStroke = stroke(boxHolder)

    local boxIcon = opts.Icon
    if boxIcon then
        glowIcon(boxHolder, boxIcon, Theme.Muted, UDim2.new(0, 8, 0.5, 0))
    end
    local box = create("TextBox", {
        Position = UDim2.fromOffset(boxIcon and 30 or 8, 0),
        Size = UDim2.new(1, boxIcon and -38 or -16, 1, 0),
        BackgroundTransparency = 1,
        Text = opts.Default or "",
        PlaceholderText = opts.Placeholder or "",
        PlaceholderColor3 = Theme.Muted,
        TextColor3 = Theme.Text,
        TextSize = compact and 13 or 14,
        FontFace = Fonts.Regular,
        TextXAlignment = Enum.TextXAlignment.Left,
        ClearTextOnFocus = false,
        TextTruncate = Enum.TextTruncate.None,
        ClipsDescendants = true,
        Parent = boxHolder,
    })
    boxHolder.ClipsDescendants = true

    local lastText = box.Text
    local value = opts.Numeric and Library._parseAmount(lastText) or nil
    if opts.Numeric and not value then
        lastText = ""
    end
    local focused = false
    local textInset = (boxIcon and 30 or 8) + 8
    local function fitBox(instant)
        local width
        if compact then
            width = rowControlWidth(frame, self.Window)
        else
            local cardWidth = frame.AbsoluteSize.X / self.Window.Scale.Scale
            local maxWidth = math.clamp(cardWidth - 14 - 110 - 20, 100, 200)
            local measured = box.TextBounds.X
            if #box.Text == 0 then
                measured = math.min(box.TextBounds.X, 90)
            end
            width = math.clamp(measured + textInset + 12, 90, maxWidth) + (focused and 8 or 0)
            width = math.min(width, maxWidth + 8)
        end
        reserveRight(titleLabel, descLabel, width + (compact and 24 or 20))
        if instant then
            boxHolder.Size = UDim2.fromOffset(width, boxHeight)
        else
            tween(boxHolder, { Size = UDim2.fromOffset(width, boxHeight) }, 0.18)
        end
    end
    local lastWidth = 0
    frame:GetPropertyChangedSignal("AbsoluteSize"):Connect(function()
        if frame.AbsoluteSize.X ~= lastWidth then
            lastWidth = frame.AbsoluteSize.X
            fitBox(true)
        end
    end)
    box:GetPropertyChangedSignal("Text"):Connect(function()
        fitBox(false)
    end)
    box:GetPropertyChangedSignal("TextBounds"):Connect(function()
        fitBox(false)
    end)
    task.defer(fitBox, true)

    box.Focused:Connect(function()
        focused = true
        tween(boxStroke, { Color = Theme.StrokeHover }, 0.15)
        fitBox(false)
    end)
    box.FocusLost:Connect(function(enterPressed)
        focused = false
        tween(boxStroke, { Color = Theme.Stroke }, 0.15)
        fitBox(false)
        if opts.Numeric then
            local number = Library._parseAmount(box.Text)
            if not number then
                box.Text = lastText
                return
            end
            lastText, value = box.Text, number
            safeCall(opts.Callback, number, enterPressed)
            return
        end
        safeCall(opts.Callback, box.Text, enterPressed)
    end)

    return finishElement(self, opts, {
        Set = function(_, newValue)
            box.Text = tostring(newValue)
            if opts.Numeric then
                local number = Library._parseAmount(box.Text)
                if number then
                    lastText, value = box.Text, number
                else
                    box.Text = lastText
                end
            end
            flashStroke(frameStroke)
        end,
        Get = function()
            if opts.Numeric then
                return value
            end
            return box.Text
        end,
        _saveValue = opts.Numeric and function()
            return lastText
        end or nil,
    }, frame, "Input")
end

function Tab:Keybind(opts)
    local frame, frameStroke, _, titleLabel, descLabel
    opts, frame, frameStroke, _, titleLabel, descLabel = beginElement(self, opts, { Title = "Name", Description = "Desc", CurrentKeybind = "Default", Value = "Default" }, "Frame", 110, "Keybind")
    if opts.Default ~= nil then
        opts.Default = Keybinds.Resolve(opts.Default)
    end
    local compact = metricsOf(self).Compact
    local chipHeight = metricsOf(self).Chip

    local chip = create("TextButton", {
        AnchorPoint = Vector2.new(1, 0.5),
        Position = UDim2.new(1, compact and -14 or -10, 0.5, 0),
        Size = UDim2.fromOffset(44, chipHeight),
        BackgroundColor3 = Theme.Surface,
        BorderSizePixel = 0,
        Text = "",
        AutoButtonColor = false,
        ClipsDescendants = true,
        Parent = frame,
    })
    corner(chip, UDim.new(0, 6))
    local chipStroke = stroke(chip)
    local chipLabel = label({
        Size = UDim2.new(1, 0, 1, 0),
        TextSize = 13,
        TextColor3 = Theme.Muted,
        TextXAlignment = Enum.TextXAlignment.Center,
        TextTruncate = Enum.TextTruncate.None,
        Parent = chip,
    })

    local self_ = { Value = opts.Default, Listening = false }

    local function fitChip(instant)
        local width = math.max(chipLabel.TextBounds.X + 20, TOUCH and 44 or 36)
        reserveRight(titleLabel, descLabel, width + (compact and 24 or 20))
        if instant then
            chip.Size = UDim2.fromOffset(width, chipHeight)
        else
            tween(chip, { Size = UDim2.fromOffset(width, chipHeight) }, 0.2)
        end
    end
    chipLabel:GetPropertyChangedSignal("TextBounds"):Connect(function()
        fitChip(false)
    end)

    local function render()
        chipLabel.Text = self_.Listening and "..." or keyName(self_.Value)
        tween(chipStroke, { Color = self_.Listening and Theme.StrokeHover or Theme.Stroke }, 0.15)
        tween(chipLabel, { TextColor3 = self_.Listening and Theme.Accent or Theme.Muted }, 0.15)
    end

    function self_:Set(keyCode, silent)
        local wasListening = self_.Listening
        self_.Value = Keybinds.Resolve(keyCode)
        self_.Listening = false
        render()
        if not wasListening then
            flashStroke(frameStroke)
        end
        if not silent then
            safeCall(opts.OnChanged, self_.Value)
        end
        local keybindMenu = self_._keybindMenu
        if keybindMenu and not keybindMenu.Destroyed then
            keybindMenu:_updateRow(self_)
        end
    end

    chip.MouseButton1Click:Connect(function()
        local wasCapture = self_._capturedBind ~= nil
            or os.clock() - (self_._capturedAt or 0) < 0.4
        self_._capturedBind = nil
        if wasCapture and not self_.Listening then
            return
        end
        self_.Listening = not self_.Listening
        render()
    end)

    self.Window:_listen("Began", function(input, gameProcessed)
        local bind = Keybinds.FromInput(input)
        if bind == nil then
            return
        end
        if self_.Listening then
            self.Window._consumedKey = bind
            self.Window._consumedAt = os.clock()
            if bind == Enum.KeyCode.Escape then
                self_.Listening = false
                render()
            else
                if Keybinds.Mouse[bind] then
                    self_._capturedBind = bind
                    self_._capturedAt = os.clock()
                end
                self_:Set(bind)
            end
            return
        end
        if not gameProcessed and self_.Value ~= nil and bind == self_.Value
            and not (Keybinds.Mouse[bind] and self.Window.Open and not self.Window.Minimized) then
            safeCall(opts.Callback, bind)
        end
    end, self_)

    self.Window:_listen("Ended", function(input)
        if self_._capturedBind ~= nil and Keybinds.FromInput(input) == self_._capturedBind then
            self_._capturedBind = nil
        end
    end, self_)

    render()
    task.defer(fitChip, true)
    function self_:Get()
        return self_.Value
    end
    self_._onHide = function()
        if self_.Listening then
            self_.Listening = false
            render()
        end
    end
    local element = finishElement(self, opts, self_, frame, "Keybind")
    element._keybindName = element._searchName ~= "" and element._searchName or "Keybind"
    local keybindMenu = self.Window.KeybindMenu
    if keybindMenu and not keybindMenu.Destroyed then
        keybindMenu:AddRow(element)
    end
    local destroyElement = element.Destroy
    function element.Destroy(instance)
        local menu = element._keybindMenu
        destroyElement(instance)
        if menu and not menu.Destroyed then
            menu:RemoveRow(element)
        end
    end
    return element
end

function Tab:ColorPicker(opts)
    local PANEL_HEIGHT = 194
    local frame, frameStroke, height
    opts, frame, frameStroke, height = beginElement(self, opts, { Title = "Name", Description = "Desc", Color = "Default", CurrentValue = "Default", Value = "Default" }, "Frame")
    frame.ClipsDescendants = true
    local metrics = metricsOf(self)
    local compact = metrics.Compact

    local header = create("TextButton", {
        Size = UDim2.new(1, 0, 0, height),
        BackgroundTransparency = 1,
        Text = "",
        AutoButtonColor = false,
        Parent = frame,
    })
    titleDesc(header, opts.Name or "Color", opts.Desc, 140, metrics)

    -- Closed, the row shows the hex code beside a rounded swatch.
    local swatch = create("Frame", {
        AnchorPoint = Vector2.new(1, 0.5),
        Position = UDim2.new(1, compact and -38 or -34, 0.5, 0),
        Size = UDim2.fromOffset(22, 22),
        BorderSizePixel = 0,
        Parent = header,
    })
    corner(swatch, UDim.new(0, 6))
    stroke(swatch, Theme.Stroke)
    local swatchHex = label({
        AnchorPoint = Vector2.new(1, 0.5),
        Position = UDim2.new(1, compact and -68 or -64, 0.5, 0),
        Size = UDim2.fromOffset(64, 16),
        TextSize = 12,
        FontFace = Fonts.Regular,
        TextColor3 = Theme.Muted,
        TextXAlignment = Enum.TextXAlignment.Right,
        Parent = header,
    })
    local arrow = arrowIndicator(header, 1, compact and -14 or -12)

    local panel = create("Frame", {
        Position = UDim2.fromOffset(14, height + 2),
        Size = UDim2.new(1, -28, 0, PANEL_HEIGHT - 12),
        BackgroundTransparency = 1,
        Visible = false,
        Parent = frame,
    })

    -- Saturation runs left to right, brightness top to bottom.
    local svBox = create("TextButton", {
        Size = UDim2.new(1, 0, 0, 118),
        BackgroundColor3 = Color3.new(1, 1, 1),
        BorderSizePixel = 0,
        Text = "",
        AutoButtonColor = false,
        Parent = panel,
    })
    corner(svBox, UDim.new(0, 8))
    stroke(svBox, Theme.Stroke)
    local svHueGradient = create("UIGradient", {
        Color = ColorSequence.new(Color3.new(1, 1, 1), Color3.new(1, 0, 0)),
        Parent = svBox,
    })
    local svDark = create("Frame", {
        Size = UDim2.fromScale(1, 1),
        BackgroundColor3 = Color3.new(0, 0, 0),
        BorderSizePixel = 0,
        Parent = svBox,
    })
    corner(svDark, UDim.new(0, 8))
    create("UIGradient", {
        Transparency = NumberSequence.new({
            NumberSequenceKeypoint.new(0, 1),
            NumberSequenceKeypoint.new(1, 0),
        }),
        Rotation = 90,
        Parent = svDark,
    })

    local function knob(parent, size)
        local ring = create("Frame", {
            AnchorPoint = Vector2.new(0.5, 0.5),
            Size = UDim2.fromOffset(size, size),
            BackgroundColor3 = Color3.new(1, 1, 1),
            BorderSizePixel = 0,
            ZIndex = 3,
            Parent = parent,
        })
        corner(ring, UDim.new(1, 0))
        stroke(ring, Color3.new(0, 0, 0), 0.7)
        local fill = create("Frame", {
            AnchorPoint = Vector2.new(0.5, 0.5),
            Position = UDim2.fromScale(0.5, 0.5),
            Size = UDim2.new(1, -4, 1, -4),
            BorderSizePixel = 0,
            ZIndex = 3,
            Parent = ring,
        })
        corner(fill, UDim.new(1, 0))
        return ring, fill
    end
    local svCursor, svFill = knob(svBox, 14)

    -- Hue is a slim horizontal track under the square.
    local hueBar = create("TextButton", {
        Position = UDim2.fromOffset(0, 132),
        Size = UDim2.new(1, 0, 0, 10),
        BackgroundColor3 = Color3.new(1, 1, 1),
        BorderSizePixel = 0,
        Text = "",
        AutoButtonColor = false,
        Parent = panel,
    })
    corner(hueBar, UDim.new(1, 0))
    create("UIGradient", {
        Color = ColorSequence.new({
            ColorSequenceKeypoint.new(0, Color3.fromRGB(255, 0, 0)),
            ColorSequenceKeypoint.new(1 / 6, Color3.fromRGB(255, 255, 0)),
            ColorSequenceKeypoint.new(2 / 6, Color3.fromRGB(0, 255, 0)),
            ColorSequenceKeypoint.new(3 / 6, Color3.fromRGB(0, 255, 255)),
            ColorSequenceKeypoint.new(4 / 6, Color3.fromRGB(0, 0, 255)),
            ColorSequenceKeypoint.new(5 / 6, Color3.fromRGB(255, 0, 255)),
            ColorSequenceKeypoint.new(1, Color3.fromRGB(255, 0, 0)),
        }),
        Parent = hueBar,
    })
    local hueCursor, hueFill = knob(hueBar, 16)
    hueCursor.Position = UDim2.fromScale(0, 0.5)

    -- Bottom row: a preview chip and hex field on the left, RGB on the right.
    local hexHolder = create("Frame", {
        Position = UDim2.fromOffset(0, 154),
        Size = UDim2.fromOffset(compact and 110 or 124, 28),
        BackgroundColor3 = Theme.Surface,
        BorderSizePixel = 0,
        Parent = panel,
    })
    corner(hexHolder, UDim.new(0, 7))
    local hexStroke = stroke(hexHolder)
    local preview = create("Frame", {
        AnchorPoint = Vector2.new(0, 0.5),
        Position = UDim2.new(0, 6, 0.5, 0),
        Size = UDim2.fromOffset(16, 16),
        BorderSizePixel = 0,
        Parent = hexHolder,
    })
    corner(preview, UDim.new(0, 4))
    stroke(preview, Theme.Stroke)
    local hexBox = create("TextBox", {
        Position = UDim2.fromOffset(30, 0),
        Size = UDim2.new(1, -38, 1, 0),
        BackgroundTransparency = 1,
        Text = "",
        TextTruncate = Enum.TextTruncate.None,
        ClipsDescendants = false,
        TextColor3 = Theme.Text,
        TextSize = 13,
        FontFace = Fonts.Regular,
        TextXAlignment = Enum.TextXAlignment.Left,
        ClearTextOnFocus = false,
        Parent = hexHolder,
    })
    local rgbLabel = label({
        Position = UDim2.fromOffset(compact and 118 or 134, 154),
        Size = UDim2.new(1, compact and -118 or -134, 0, 28),
        TextXAlignment = Enum.TextXAlignment.Right,
        TextSize = 12,
        FontFace = Fonts.Regular,
        TextColor3 = Theme.Muted,
        Parent = panel,
    })

    local self_ = { Open = false }
    local hue, sat, val = Color3.toHSV(opts.Default or Theme.Accent)
    local dragTarget = nil

    local function toHex(color)
        return string.format("#%02X%02X%02X",
            math.floor(color.R * 255 + 0.5),
            math.floor(color.G * 255 + 0.5),
            math.floor(color.B * 255 + 0.5))
    end

    local function render(duration)
        local color = Color3.fromHSV(hue, sat, val)
        self_.Value = color
        swatch.BackgroundColor3 = color
        preview.BackgroundColor3 = color
        svFill.BackgroundColor3 = color
        hueFill.BackgroundColor3 = Color3.fromHSV(hue, 1, 1)
        swatchHex.Text = toHex(color)
        svHueGradient.Color = ColorSequence.new(Color3.new(1, 1, 1), Color3.fromHSV(hue, 1, 1))
        tween(svCursor, { Position = UDim2.fromScale(sat, 1 - val) }, duration, Enum.EasingStyle.Quint)
        tween(hueCursor, { Position = UDim2.fromScale(hue, 0.5) }, duration, Enum.EasingStyle.Quint)
        if not hexBox:IsFocused() then
            hexBox.Text = toHex(color)
        end
        rgbLabel.Text = string.format("%d  %d  %d",
            math.floor(color.R * 255 + 0.5),
            math.floor(color.G * 255 + 0.5),
            math.floor(color.B * 255 + 0.5))
    end

    local function commit(duration, silent)
        render(duration)
        if not silent then
            safeCall(opts.Callback, self_.Value)
        end
    end

    function self_:Set(color, silent)
        hue, sat, val = Color3.toHSV(color)
        commit(0.25, silent)
        flashStroke(frameStroke)
    end

    function self_:Get()
        return self_.Value
    end

    local function setOpen(open)
        self_.Open = open
        tween(frame, { Size = UDim2.new(1, 0, 0, open and (height + PANEL_HEIGHT) or height) }, 0.35, Enum.EasingStyle.Quint)
        arrow:Set(open)
        if open then
            panel.Visible = true
        else
            task.delay(0.35, function()
                if not self_.Open then
                    panel.Visible = false
                end
            end)
        end
    end

    function self_:SetOpen(open)
        setOpen(open == true)
    end

    header.MouseButton1Click:Connect(function()
        setOpen(not self_.Open)
    end)

    local function updateSV(position)
        sat = math.clamp((position.X - svBox.AbsolutePosition.X) / svBox.AbsoluteSize.X, 0, 1)
        val = 1 - math.clamp((position.Y - svBox.AbsolutePosition.Y) / svBox.AbsoluteSize.Y, 0, 1)
        commit(0.04)
    end
    local function updateHue(position)
        hue = math.clamp((position.X - hueBar.AbsolutePosition.X) / hueBar.AbsoluteSize.X, 0, 0.999)
        commit(0.04)
    end

    svBox.InputBegan:Connect(function(input)
        if isPress(input) then
            dragTarget = "sv"
            tween(svCursor, { Size = UDim2.fromOffset(18, 18) }, 0.2, Enum.EasingStyle.Quint)
            updateSV(pointerPosition())
        end
    end)
    hueBar.InputBegan:Connect(function(input)
        if isPress(input) then
            dragTarget = "hue"
            tween(hueCursor, { Size = UDim2.fromOffset(20, 20) }, 0.2, Enum.EasingStyle.Quint)
            updateHue(pointerPosition())
        end
    end)
    self.Window:_listen("Changed", function(input)
        if not dragTarget or not isMove(input) then
            return
        end
        local position = pointerPosition()
        if dragTarget == "sv" then
            updateSV(position)
        else
            updateHue(position)
        end
    end, self_)
    self.Window:_listen("Ended", function(input)
        if dragTarget and isPress(input) then
            dragTarget = nil
            tween(svCursor, { Size = UDim2.fromOffset(14, 14) }, 0.25, Enum.EasingStyle.Quint)
            tween(hueCursor, { Size = UDim2.fromOffset(16, 16) }, 0.25, Enum.EasingStyle.Quint)
        end
    end, self_)

    hexBox.Focused:Connect(function()
        tween(hexStroke, { Color = Theme.StrokeHover }, 0.15)
    end)
    hexBox.FocusLost:Connect(function()
        tween(hexStroke, { Color = Theme.Stroke }, 0.15)
        local r, g, b = hexBox.Text:match("^%s*#?(%x%x)(%x%x)(%x%x)%s*$")
        if r then
            self_:Set(Color3.fromRGB(tonumber(r, 16), tonumber(g, 16), tonumber(b, 16)))
        else
            hexBox.Text = toHex(self_.Value)
        end
    end)

    render(0)
    return finishElement(self, opts, self_, frame, "ColorPicker")
end

function Tab:Stepper(opts)
    local frame, frameStroke, _, titleLabel, descLabel
    opts, frame, frameStroke, _, titleLabel, descLabel = beginElement(self, opts, { Title = "Name", Description = "Desc", CurrentValue = "Default", Value = "Default", Increment = "Step" }, "Frame", 150, "Stepper")
    local min = opts.Min or 0
    local max = opts.Max or 100
    local step = opts.Step or 1
    local suffix = opts.Suffix or ""
    local numbers = numberFormat(min, max, step)
    local compact = metricsOf(self).Compact
    local chipHeight = metricsOf(self).Chip

    local group = create("Frame", {
        AnchorPoint = Vector2.new(1, 0.5),
        Position = UDim2.new(1, compact and -14 or -10, 0.5, 0),
        Size = UDim2.fromOffset(0, chipHeight),
        AutomaticSize = Enum.AutomaticSize.X,
        BackgroundColor3 = Theme.Surface,
        BorderSizePixel = 0,
        Parent = frame,
    })
    corner(group, UDim.new(0, 6))
    local groupStroke = stroke(group)
    create("UIListLayout", {
        FillDirection = Enum.FillDirection.Horizontal,
        SortOrder = Enum.SortOrder.LayoutOrder,
        VerticalAlignment = Enum.VerticalAlignment.Center,
        Parent = group,
    })

    local function stepButton(text, order)
        local button = create("TextButton", {
            Size = UDim2.fromOffset(chipHeight, chipHeight),
            BackgroundTransparency = 1,
            Text = text,
            TextColor3 = Theme.Muted,
            TextSize = 18,
            FontFace = Fonts.Medium,
            AutoButtonColor = false,
            LayoutOrder = order,
            Parent = group,
        })
        button.MouseEnter:Connect(function()
            tween(button, { TextColor3 = Theme.Accent }, 0.12)
        end)
        button.MouseLeave:Connect(function()
            tween(button, { TextColor3 = Theme.Muted }, 0.2)
        end)
        return button
    end
    local minus = stepButton("−", 1)
    local valueLabel = label({
        Size = UDim2.new(0, 30, 1, 0),
        TextSize = 13,
        TextColor3 = Theme.Accent,
        TextXAlignment = Enum.TextXAlignment.Center,
        TextTruncate = Enum.TextTruncate.None,
        LayoutOrder = 2,
        Parent = group,
    })
    local plus = stepButton("+", 3)
    local function fitValue(instant)
        local width = math.max(valueLabel.TextBounds.X + 12, 30)
        if instant then
            valueLabel.Size = UDim2.new(0, width, 1, 0)
        else
            tween(valueLabel, { Size = UDim2.new(0, width, 1, 0) }, 0.2)
        end
    end
    valueLabel:GetPropertyChangedSignal("TextBounds"):Connect(function()
        fitValue(false)
    end)
    group:GetPropertyChangedSignal("AbsoluteSize"):Connect(function()
        reserveRight(titleLabel, descLabel, group.AbsoluteSize.X / self.Window.Scale.Scale + (compact and 24 or 20))
    end)

    local self_ = { Value = math.clamp(opts.Default or min, min, max) }
    local snap = numbers.snap
    local fromButton = false
    local function render()
        valueLabel.Text = numbers.format(self_.Value) .. suffix
        tween(minus, { TextTransparency = self_.Value <= min and 0.6 or 0 }, 0.15)
        tween(plus, { TextTransparency = self_.Value >= max and 0.6 or 0 }, 0.15)
    end
    function self_:Set(value, silent)
        value = snap(tonumber(value) or min)
        if value == self_.Value then
            return
        end
        self_.Value = value
        render()
        if not fromButton then
            flashStroke(frameStroke)
        end
        if not silent then
            safeCall(opts.Callback, value)
        end
    end
    function self_:Get()
        return self_.Value
    end

    local function bump(direction)
        fromButton = true
        self_:Set(self_.Value + direction * step)
        fromButton = false
        tween(groupStroke, { Color = Theme.StrokeHover }, 0.08)
        task.delay(0.12, function()
            tween(groupStroke, { Color = Theme.Stroke }, 0.2)
        end)
    end
    local function holdRepeat(button, direction)
        local holding = false
        button.InputBegan:Connect(function(input)
            if not isPress(input) then
                return
            end
            holding = true
            bump(direction)
            task.delay(0.4, function()
                while holding do
                    bump(direction)
                    task.wait(0.07)
                end
            end)
        end)
        button.InputEnded:Connect(function(input)
            if isPress(input) then
                holding = false
            end
        end)
        button.MouseLeave:Connect(function()
            holding = false
        end)
    end
    holdRepeat(minus, -1)
    holdRepeat(plus, 1)

    render()
    task.defer(fitValue, true)
    return finishElement(self, opts, self_, frame, "Stepper")
end

function Tab:Progress(opts)
    opts = normalize(opts, { Title = "Name", Description = "Desc", CurrentValue = "Default", Value = "Default" })
    local metrics = metricsOf(self)
    local compact = metrics.Compact
    local extra = compact and 6 or 10
    local frame, frameStroke = card(self, "Frame", (opts.Desc and metrics.DescHeight or metrics.Height) + extra, opts)
    hoverStroke(frame, frameStroke)
    local top
    if opts.Desc then
        top = math.floor((metrics.DescHeight - (metrics.DescGap + metrics.DescLine)) / 2) - 2
    else
        top = compact and 5 or 12
    end

    label({
        Position = UDim2.fromOffset(14, top),
        Size = UDim2.new(1, -110, 0, 18),
        Text = opts.Name or "Progress",
        TextSize = metrics.TextSize,
        Parent = frame,
    })
    if opts.Desc then
        label({
            Position = UDim2.fromOffset(14, top + metrics.DescGap),
            Size = UDim2.new(1, -110, 0, metrics.DescLine),
            Text = opts.Desc,
            TextSize = metrics.DescSize,
            FontFace = Fonts.Regular,
            TextColor3 = Theme.Muted,
            Parent = frame,
        })
    end
    local valueLabel = label({
        AnchorPoint = Vector2.new(1, 0),
        Position = UDim2.new(1, -14, 0, top),
        Size = UDim2.fromOffset(90, 18),
        TextXAlignment = Enum.TextXAlignment.Right,
        TextSize = 13,
        TextColor3 = Library._color(opts.TextColor) or Theme.Accent,
        RichText = true,
        Parent = frame,
    })
    local track = create("Frame", {
        Position = UDim2.new(0, 14, 1, compact and -12 or -16),
        Size = UDim2.new(1, -28, 0, 5),
        BackgroundColor3 = Theme.Surface3,
        BorderSizePixel = 0,
        Parent = frame,
    })
    corner(track, UDim.new(1, 0))
    local fill = create("Frame", {
        Size = UDim2.new(0, 0, 1, 0),
        BackgroundColor3 = Library._color(opts.Color) or Theme.Accent,
        BorderSizePixel = 0,
        Parent = track,
    })
    corner(fill, UDim.new(1, 0))

    local self_ = { Value = math.clamp(opts.Default or 0, 0, 1) }
    local formatter = opts.Format
    local function render(duration)
        local frac = self_.Value
        tween(fill, { Size = UDim2.new(frac, 0, 1, 0) }, duration, Enum.EasingStyle.Quint)
        if type(formatter) == "function" then
            valueLabel.Text = Library._rich(formatter(frac))
        else
            valueLabel.Text = string.format("%d%%", math.floor(frac * 100 + 0.5))
        end
    end
    function self_:Set(value, silent)
        value = math.clamp(tonumber(value) or 0, 0, 1)
        if value == self_.Value then
            return
        end
        self_.Value = value
        render(0.35)
        if not silent then
            safeCall(opts.Callback, value)
        end
    end
    function self_:Get()
        return self_.Value
    end
    function self_:SetColor(color)
        tween(fill, { BackgroundColor3 = Library._color(color) or Theme.Accent }, 0.25)
    end
    -- The percentage's colour; nil goes back to the accent.
    function self_:SetTextColor(color)
        tween(valueLabel, { TextColor3 = Library._color(color) or Theme.Accent }, 0.25)
    end
    -- render now, and again on theme change.
    onTheme(valueLabel, function()
        render(0)
    end)
    return finishElement(self, opts, self_, frame, "Progress")
end

function Tab:OrderList(opts)
    opts = normalize(opts, { Title = "Name", Description = "Desc", Options = "Items", Values = "Items" })
    local metrics = metricsOf(self)
    local compact = metrics.Compact
    local window = self.Window
    local ROW = TOUCH and 40 or 32
    local GAP = 4
    local STEP = ROW + GAP
    local GRIP = TOUCH and 34 or 26
    local ARROW = TOUCH and 30 or 22
    local maxRows = math.max(math.floor(tonumber(opts.MaxRows) or 6), 1)
    local numbered = opts.Numbered ~= false
    local arrows = opts.Arrows ~= false

    local frame = card(self, "Frame", 0, opts)
    frame.AutomaticSize = Enum.AutomaticSize.Y
    if compact then
        padding(frame, 14, 14, 6, 8)
    else
        padding(frame, 14, 14, 11, 12)
    end
    create("UIListLayout", {
        SortOrder = Enum.SortOrder.LayoutOrder,
        Padding = UDim.new(0, 6),
        Parent = frame,
    })
    local name = tostring(opts.Name or "")
    label({
        Size = UDim2.new(1, 0, 0, 18),
        Text = name,
        TextSize = metrics.TextSize,
        Visible = name ~= "",
        LayoutOrder = 1,
        Parent = frame,
    })
    if opts.Desc then
        label({
            Size = UDim2.new(1, 0, 0, 0),
            AutomaticSize = Enum.AutomaticSize.Y,
            Text = opts.Desc,
            TextSize = metrics.DescSize,
            FontFace = Fonts.Regular,
            TextColor3 = Theme.Muted,
            TextWrapped = true,
            TextTruncate = Enum.TextTruncate.None,
            LayoutOrder = 2,
            Parent = frame,
        })
    end
    local scroller = create("ScrollingFrame", {
        Size = UDim2.new(1, 0, 0, ROW + 2),
        BackgroundTransparency = 1,
        BorderSizePixel = 0,
        ScrollBarThickness = TOUCH and 4 or 3,
        ScrollBarImageColor3 = Theme.Accent,
        ScrollBarImageTransparency = 0.4,
        ScrollingDirection = Enum.ScrollingDirection.Y,
        -- Sized by hand, like the dropdown list, so it scrolls under UIScale.
        CanvasSize = UDim2.new(),
        ScrollingEnabled = false,
        LayoutOrder = 3,
        Parent = frame,
    })
    scroller:SetAttribute("NoDrag", true)
    local content = create("Frame", {
        Size = UDim2.fromScale(1, 1),
        BackgroundTransparency = 1,
        Parent = scroller,
    })
    local empty = label({
        Size = UDim2.new(1, 0, 0, ROW),
        Text = tostring(opts.EmptyText or "Nothing to order"),
        TextSize = 13,
        FontFace = Fonts.Regular,
        TextColor3 = Theme.Muted,
        TextXAlignment = Enum.TextXAlignment.Center,
        Visible = false,
        Parent = content,
    })

    -- A lucide icon, or a text glyph when the icon set didn't load.
    local function iconButton(parent, icon, glyph, rotation, props)
        props.BackgroundTransparency = 1
        props.Text = ""
        props.AutoButtonColor = false
        props.Parent = parent
        local button = create("TextButton", props)
        local image = create("ImageLabel", {
            AnchorPoint = Vector2.new(0.5, 0.5),
            Position = UDim2.fromScale(0.5, 0.5),
            Size = TOUCH and UDim2.fromOffset(16, 16) or UDim2.fromOffset(14, 14),
            BackgroundTransparency = 1,
            ImageColor3 = Theme.Muted,
            ScaleType = Enum.ScaleType.Fit,
            Parent = button,
        })
        applyIcon(image, icon)
        if image.Image ~= "" then
            return button, { Object = image, Color = "ImageColor3", Fade = "ImageTransparency" }
        end
        image:Destroy()
        local text_ = label({
            Size = UDim2.fromScale(1, 1),
            Text = glyph,
            TextSize = 18,
            TextColor3 = Theme.Muted,
            TextXAlignment = Enum.TextXAlignment.Center,
            TextTruncate = Enum.TextTruncate.None,
            Rotation = rotation,
            Parent = button,
        })
        return button, { Object = text_, Color = "TextColor3", Fade = "TextTransparency" }
    end
    local function tint(icon, color, transparency, duration)
        tween(icon.Object, { [icon.Color] = color, [icon.Fade] = transparency }, duration)
    end

    local self_ = {}
    local entries = {}
    local remembered = {}
    local dragging = nil
    local nudge, beginDrag

    local function slotY(slot)
        return 1 + (slot - 1) * STEP
    end

    local function values()
        local list = {}
        for index, entry in ipairs(entries) do
            list[index] = entry.Value
        end
        return list
    end

    local function layout(instant)
        local count = #entries
        for slot, entry in ipairs(entries) do
            entry.Index.Text = tostring(slot)
            if entry ~= dragging then
                tween(entry.Frame, { Position = UDim2.fromOffset(3, slotY(slot)) }, instant and 0 or 0.22, Enum.EasingStyle.Quint)
            end
            if entry.UpIcon then
                tween(entry.UpIcon.Object, { [entry.UpIcon.Fade] = slot == 1 and 0.7 or 0 }, instant and 0 or 0.15)
                tween(entry.DownIcon.Object, { [entry.DownIcon.Fade] = slot == count and 0.7 or 0 }, instant and 0 or 0.15)
            end
        end
    end

    local function fit()
        local count = #entries
        local canvas = math.max(count, 1) * STEP - GAP + 2
        local shown = math.clamp(count, 1, maxRows)
        local height = shown * STEP - GAP + 2
        local scrolling = count > maxRows
        scroller.Size = UDim2.new(1, 0, 0, height)
        scroller.CanvasSize = UDim2.fromOffset(0, canvas)
        content.Size = UDim2.new(1, scrolling and -8 or 0, 0, canvas)
        if not dragging then
            scroller.ScrollingEnabled = scrolling
        end
        empty.Visible = count == 0
        local maxScroll = math.max(canvas - height, 0)
        if scroller.CanvasPosition.Y > maxScroll then
            scroller.CanvasPosition = Vector2.new(0, maxScroll)
        end
    end

    local function changed(silent)
        self_.Value = values()
        if not silent then
            safeCall(opts.Callback, values())
        end
    end

    local function listScroller()
        if scroller.ScrollingEnabled then
            return scroller
        end
        return frame:FindFirstAncestorWhichIsA("ScrollingFrame")
    end

    local function newEntry(value)
        local row = create("Frame", {
            Size = UDim2.new(1, -6, 0, ROW),
            BackgroundColor3 = Theme.Surface,
            BorderSizePixel = 0,
            Parent = content,
        })
        corner(row, UDim.new(0, 7))
        local entry = { Value = value, Frame = row }
        entry.Stroke = stroke(row)
        entry.Scale = create("UIScale", { Parent = row })
        local grip
        grip, entry.GripIcon = iconButton(row, "grip-vertical", "=", 0, {
            Size = UDim2.new(0, GRIP, 1, 0),
        })
        local x = GRIP
        entry.Index = label({
            Position = UDim2.fromOffset(x, 0),
            Size = UDim2.new(0, 22, 1, 0),
            TextSize = 12,
            TextColor3 = Theme.Accent,
            TextTruncate = Enum.TextTruncate.None,
            Visible = numbered,
            Parent = row,
        })
        if numbered then
            x += 22
        end
        local right = arrows and ARROW * 2 + 8 or 10
        entry.Text = label({
            Position = UDim2.fromOffset(x, 0),
            Size = UDim2.new(1, -(x + right), 1, 0),
            Text = tostring(value),
            TextSize = 13,
            Parent = row,
        })
        local buttons = {}
        if arrows then
            local up, down
            up, entry.UpIcon = iconButton(row, "chevron-up", "›", -90, {
                AnchorPoint = Vector2.new(1, 0),
                Position = UDim2.new(1, -(ARROW + 6), 0, 0),
                Size = UDim2.new(0, ARROW, 1, 0),
            })
            down, entry.DownIcon = iconButton(row, "chevron-down", "›", 90, {
                AnchorPoint = Vector2.new(1, 0),
                Position = UDim2.new(1, -4, 0, 0),
                Size = UDim2.new(0, ARROW, 1, 0),
            })
            for button, direction in pairs({ [up] = -1, [down] = 1 }) do
                local icon = direction < 0 and entry.UpIcon or entry.DownIcon
                local isTap = tapGuard(button, listScroller)
                button.MouseEnter:Connect(function()
                    if not usingTouch() then
                        tween(icon.Object, { [icon.Color] = Theme.Accent }, 0.12)
                    end
                end)
                button.MouseLeave:Connect(function()
                    tween(icon.Object, { [icon.Color] = Theme.Muted }, 0.2)
                end)
                button.MouseButton1Click:Connect(function()
                    if isTap() then
                        nudge(entry, direction)
                    end
                end)
                table.insert(buttons, button)
            end
        end
        grip.InputBegan:Connect(function(input)
            if isPress(input) then
                beginDrag(entry)
            end
        end)
        row.InputBegan:Connect(function(input)
            if input.UserInputType ~= Enum.UserInputType.MouseButton1 then
                return
            end
            local point = pointerPosition()
            for _, button in ipairs(buttons) do
                if pointInside(point, button) then
                    return
                end
            end
            beginDrag(entry)
        end)
        row.MouseEnter:Connect(function()
            if not usingTouch() and entry ~= dragging then
                tween(entry.Stroke, { Color = Theme.StrokeHover }, 0.12)
                tint(entry.GripIcon, Theme.Text, 0, 0.12)
            end
        end)
        row.MouseLeave:Connect(function()
            if entry ~= dragging then
                tween(entry.Stroke, { Color = Theme.Stroke }, 0.25)
                tint(entry.GripIcon, Theme.Muted, 0, 0.25)
            end
        end)
        return entry
    end

    local function build(list)
        local pool = {}
        for _, entry in ipairs(entries) do
            pool[entry.Value] = pool[entry.Value] or {}
            table.insert(pool[entry.Value], entry)
        end
        local nextEntries = {}
        for index, value in ipairs(list) do
            local bucket = pool[value]
            local entry = bucket and table.remove(bucket, 1)
            if not entry then
                entry = newEntry(value)
                entry.Frame.Position = UDim2.fromOffset(3, slotY(index))
            end
            nextEntries[index] = entry
        end
        for _, bucket in pairs(pool) do
            for _, entry in ipairs(bucket) do
                entry.Frame:Destroy()
            end
        end
        entries = nextEntries
    end

    -- ranked items first; the rest keep their order.
    local function arrange(items, ranking)
        local left = {}
        for _, value in ipairs(items) do
            left[value] = (left[value] or 0) + 1
        end
        local result = {}
        for _, pass in ipairs({ ranking, items }) do
            for _, value in ipairs(pass) do
                if (left[value] or 0) > 0 then
                    left[value] -= 1
                    table.insert(result, value)
                end
            end
        end
        return result
    end

    local function scrollIntoView(slot)
        local top = slotY(slot) - 1
        local view = scroller.AbsoluteWindowSize.Y / window.Scale.Scale
        local y = scroller.CanvasPosition.Y
        if top < y then
            y = top
        elseif top + ROW + 2 > y + view then
            y = top + ROW + 2 - view
        end
        if y ~= scroller.CanvasPosition.Y then
            tween(scroller, { CanvasPosition = Vector2.new(0, math.max(y, 0)) }, 0.2)
        end
    end

    function nudge(entry, direction)
        if dragging then
            return
        end
        local from = table.find(entries, entry)
        local to = from and from + direction
        if not to or to < 1 or to > #entries then
            return
        end
        entries[from], entries[to] = entries[to], entries[from]
        layout(false)
        tween(entry.Stroke, { Color = Theme.Accent }, 0.08)
        task.delay(0.18, function()
            if entry ~= dragging then
                tween(entry.Stroke, { Color = Theme.Stroke }, 0.3)
            end
        end)
        scrollIntoView(to)
        changed(false)
    end

    local grabOffset, lastPointer = 0, nil
    local startEntries, stopRender, lockedPage = nil, nil, nil

    local function follow(pointer)
        local scale = window.Scale.Scale
        local y = (pointer.Y - grabOffset - scroller.AbsolutePosition.Y) / scale + scroller.CanvasPosition.Y
        y = math.clamp(y, slotY(1), slotY(#entries))
        dragging.Frame.Position = UDim2.fromOffset(3, y)
        local slot = math.clamp(math.floor((y - 1) / STEP + 0.5) + 1, 1, #entries)
        local current = table.find(entries, dragging)
        if current ~= slot then
            table.remove(entries, current)
            table.insert(entries, slot, dragging)
            layout(false)
        end
    end

    local function autoScroll(deltaTime)
        if not dragging or not lastPointer then
            return
        end
        local scale = window.Scale.Scale
        local top = scroller.AbsolutePosition.Y
        local bottom = top + scroller.AbsoluteSize.Y
        local zone = ROW * scale
        local speed = 0
        if lastPointer.Y < top + zone then
            speed = -(top + zone - lastPointer.Y) / zone
        elseif lastPointer.Y > bottom - zone then
            speed = (lastPointer.Y - (bottom - zone)) / zone
        end
        if speed == 0 then
            return
        end
        local maxScroll = math.max(scroller.CanvasSize.Y.Offset - scroller.AbsoluteWindowSize.Y / scale, 0)
        local y = math.clamp(scroller.CanvasPosition.Y + math.clamp(speed, -1.5, 1.5) * 360 * deltaTime, 0, maxScroll)
        if y ~= scroller.CanvasPosition.Y then
            scroller.CanvasPosition = Vector2.new(0, y)
            follow(lastPointer)
        end
    end

    function beginDrag(entry)
        if dragging or #entries < 2 or self_._destroyed then
            return
        end
        dragging = entry
        startEntries = table.clone(entries)
        lastPointer = pointerPosition()
        grabOffset = lastPointer.Y - entry.Frame.AbsolutePosition.Y
        entry.Frame.ZIndex = 5
        tween(entry.Frame, { BackgroundColor3 = Theme.Surface3 }, 0.12)
        tween(entry.Stroke, { Color = Theme.Accent }, 0.12)
        tween(entry.Scale, { Scale = 1.02 }, 0.18, Enum.EasingStyle.Back)
        tint(entry.GripIcon, Theme.Accent, 0, 0.12)
        -- Neither the list nor the page scrolls under the finger while dragging.
        scroller.ScrollingEnabled = false
        local page = frame:FindFirstAncestorWhichIsA("ScrollingFrame")
        if page and page.ScrollingEnabled then
            lockedPage = page
            page.ScrollingEnabled = false
        end
        stopRender = window:_listen("Render", autoScroll)
    end

    local function endDrag(silent)
        local entry = dragging
        if not entry then
            return
        end
        dragging = nil
        lastPointer = nil
        if stopRender then
            stopRender()
            stopRender = nil
        end
        if lockedPage then
            lockedPage.ScrollingEnabled = true
            lockedPage = nil
        end
        tween(entry.Frame, { BackgroundColor3 = Theme.Surface }, 0.2)
        tween(entry.Stroke, { Color = Theme.Stroke }, 0.25)
        tween(entry.Scale, { Scale = 1 }, 0.2)
        tint(entry.GripIcon, Theme.Muted, 0, 0.25)
        task.delay(0.22, function()
            if entry ~= dragging then
                entry.Frame.ZIndex = 1
            end
        end)
        layout(false)
        fit()
        for index, other in ipairs(entries) do
            if startEntries[index] ~= other then
                changed(silent)
                break
            end
        end
    end

    window:_listen("Changed", function(input)
        if dragging and isMove(input) then
            lastPointer = pointerPosition()
            follow(lastPointer)
        end
    end, self_)
    window:_listen("Ended", function(input)
        if dragging and isPress(input) then
            endDrag(false)
        end
    end, self_)
    table.insert(self_._listeners, function()
        endDrag(true)
    end)
    self_._onHide = function()
        endDrag(false)
    end

    function self_:Set(list, silent)
        if type(list) ~= "table" then
            return
        end
        endDrag(true)
        remembered = table.clone(list)
        build(arrange(values(), remembered))
        layout(false)
        fit()
        changed(silent)
    end

    function self_:Get()
        return values()
    end

    function self_:Refresh(items, keepOrder, silent)
        endDrag(true)
        items = type(items) == "table" and table.clone(items) or {}
        if keepOrder ~= false then
            items = arrange(items, self_:_saveValue())
        else
            remembered = {}
        end
        build(items)
        layout(false)
        fit()
        changed(silent)
    end

    -- shown order, then remembered items not in the list.
    function self_:_saveValue()
        local list = values()
        local left = {}
        for _, value in ipairs(list) do
            left[value] = (left[value] or 0) + 1
        end
        for _, value in ipairs(remembered) do
            if (left[value] or 0) > 0 then
                left[value] -= 1
            else
                table.insert(list, value)
            end
        end
        return list
    end

    build(type(opts.Items) == "table" and opts.Items or {})
    layout(true)
    fit()
    self_.Value = values()
    return finishElement(self, opts, self_, frame, "OrderList")
end


for name, method in pairs(table.clone(Tab)) do
    if type(method) == "function" and name:sub(1, 1) ~= "_" and name:sub(1, 6) ~= "Create" then
        Tab["Create" .. name] = method
    end
end

local function detectExecutor()
    local name
    pcall(function()
        if typeof(identifyexecutor) == "function" then
            name = (identifyexecutor())
        elseif typeof(getexecutorname) == "function" then
            name = getexecutorname()
        end
    end)
    if type(name) == "string" and #name > 0 then
        return name
    end
    return RunService:IsStudio() and "Studio" or "Unknown"
end

local function executorReport(opts)
    local executor = detectExecutor()
    local supported = opts.SupportedExecutors
    if type(supported) == "table" then
        local lowered = string.lower(executor)
        for _, name in ipairs(supported) do
            if string.find(lowered, string.lower(tostring(name)), 1, true) then
                return executor, true, "Your executor is supported and fully compatible."
            end
        end
        return executor, false, "Not on the supported list. Some features may not work."
    end
    local capabilities = {
        { "writefile", writefile },
        { "readfile", readfile },
        { "getcustomasset", getcustomasset },
        { "setclipboard", setclipboard or toclipboard },
        { "request", request or http_request or (syn and syn.request) },
    }
    local missing = {}
    for _, entry in ipairs(capabilities) do
        if type(entry[2]) ~= "function" then
            table.insert(missing, entry[1])
        end
    end
    if #missing == 0 then
        return executor, true, "Your executor is supported and fully compatible."
    end
    return executor, false, "Missing " .. table.concat(missing, ", ") .. ". Some features may not work."
end

local function ensureFolder(folder)
    if type(isfolder) ~= "function" or type(makefolder) ~= "function" then
        return
    end
    pcall(function()
        local path = ""
        for segment in tostring(folder):gmatch("[^/\\]+") do
            path = path == "" and segment or path .. "/" .. segment
            if not isfolder(path) then
                makefolder(path)
            end
        end
    end)
end

local UnsupportedSkip = {}

function UnsupportedSkip.Path(folder)
    return tostring(folder) .. "/unsupported_skip.txt"
end

function UnsupportedSkip.Available()
    return type(writefile) == "function" and type(readfile) == "function" and type(isfile) == "function"
end

function UnsupportedSkip.Saved(folder, executor)
    if not UnsupportedSkip.Available() then
        return false
    end
    local path = UnsupportedSkip.Path(folder)
    local ok, saved = pcall(function()
        return isfile(path) and readfile(path) or nil
    end)
    return ok and saved == executor
end

function UnsupportedSkip.Write(folder, path, content)
    if not UnsupportedSkip.Available() then
        return false
    end
    return pcall(function()
        ensureFolder(folder)
        writefile(path, content)
    end)
end

function UnsupportedSkip.Save(folder, executor)
    return UnsupportedSkip.Write(folder, UnsupportedSkip.Path(folder), executor)
end

function UnsupportedSkip.DisclaimerKey(entry)
    if entry.Id ~= nil then
        return (tostring(entry.Id):gsub("[\r\n]", " "))
    end
    local source = tostring(entry.Title) .. "\0" .. tostring(entry.Text)
    local hash = 5381
    for index = 1, #source do
        hash = (hash * 33 + source:byte(index)) % 4294967296
    end
    return string.format("%08x", hash)
end

function UnsupportedSkip.DisclaimerAccepted(folder, key)
    if not UnsupportedSkip.Available() then
        return false
    end
    local path = tostring(folder) .. "/disclaimers.txt"
    local ok, saved = pcall(function()
        return isfile(path) and readfile(path) or ""
    end)
    if not ok or type(saved) ~= "string" then
        return false
    end
    for line in saved:gmatch("[^\r\n]+") do
        if line == key then
            return true
        end
    end
    return false
end

function UnsupportedSkip.AcceptDisclaimer(folder, key)
    if UnsupportedSkip.DisclaimerAccepted(folder, key) then
        return true
    end
    local path = tostring(folder) .. "/disclaimers.txt"
    local ok, saved = pcall(function()
        return isfile(path) and readfile(path) or ""
    end)
    saved = ok and type(saved) == "string" and saved or ""
    if saved ~= "" and not saved:match("\n$") then
        saved ..= "\n"
    end
    return UnsupportedSkip.Write(folder, path, saved .. key .. "\n")
end

local gameInfoCache = nil

local function fetchGameInfo()
    if gameInfoCache == nil then
        local ok, info = pcall(function()
            return MarketplaceService:GetProductInfo(game.PlaceId)
        end)
        gameInfoCache = ok and type(info) == "table" and info or false
    end
    return gameInfoCache or nil
end

local function detectGameName()
    local info = fetchGameInfo()
    if info and info.Name then
        return info.Name
    end
    return RunService:IsStudio() and "Studio" or "Unknown game"
end

-- Telemetry: off by default. CreateWindow opts.Telemetry turns it on.
Library.Telemetry = {
    Enabled = false,
    Url = "",
    Name = "Aster UI",
    Cooldown = 30, -- seconds
}

function Library:SetTelemetry(enabled)
    self.Telemetry.Enabled = enabled == true
end

local function configureTelemetry(opts)
    local value = opts.Telemetry
    if value == false then
        Library.Telemetry.Enabled = false
        return
    end
    if value == nil then
        return
    end
    if value == true then
        Library.Telemetry.Enabled = Library.Telemetry.Url ~= ""
        return
    end
    if type(value) == "string" then
        Library.Telemetry.Url = value
        Library.Telemetry.Enabled = true
        return
    end
    if type(value) ~= "table" then
        return
    end
    Library.Telemetry.Url = value.Url or value.Webhook or value.WebhookUrl or Library.Telemetry.Url
    Library.Telemetry.Name = value.Name or Library.Telemetry.Name
    Library.Telemetry.Cooldown = tonumber(value.Cooldown) or Library.Telemetry.Cooldown
    Library.Telemetry.Enabled = value.Enabled == true and Library.Telemetry.Url ~= ""
end

local lastTelemetry = 0

local function telemetryScriptName()
    local ok, name = pcall(function()
        if type(getscriptname) == "function" then
            return getscriptname()
        end
        return nil
    end)
    name = ok and name or nil
    if type(name) ~= "string" or name == "" then
        return "unknown"
    end
    return name:sub(1, 200)
end

function Library:_trackTelemetry(event)
    local settings = self.Telemetry
    if not settings or not settings.Enabled then
        return
    end
    if type(settings.Url) ~= "string" or settings.Url == "" then
        return
    end

    local now = os.clock()
    if now - lastTelemetry < (settings.Cooldown or 0) then
        return
    end
    lastTelemetry = now

    local httpRequest = (syn and syn.request) or http_request or request
    if type(httpRequest) ~= "function" then
        return
    end

    -- Payload building runs on the spawned thread: detectGameName can yield.
    task.spawn(function()
        pcall(function()
            local player = Players.LocalPlayer
            local payload = {
                username = settings.Name or "Aster UI",
                embeds = {{
                    title = "Aster UI — " .. tostring(event),
                    color = 0x5865F2,
                    timestamp = os.date("!%Y-%m-%dT%H:%M:%SZ"),
                    fields = {
                        {
                            name = "Jogador",
                            value = player and (player.Name .. " (" .. player.UserId .. ")") or "?",
                            inline = true,
                        },
                        { name = "Executor", value = tostring(detectExecutor()), inline = true },
                        {
                            name = "Jogo",
                            value = string.format("%s (%d)", detectGameName(), game.PlaceId),
                            inline = false,
                        },
                        {
                            name = "Servidor",
                            value = game.JobId ~= "" and game.JobId or "Studio",
                            inline = false,
                        },
                        { name = "Script", value = telemetryScriptName(), inline = false },
                    },
                }},
            }
            httpRequest({
                Url = settings.Url .. (settings.Url:find("?") and "&" or "?") .. "wait=true",
                Method = "POST",
                Headers = { ["Content-Type"] = "application/json" },
                Body = HttpService:JSONEncode(payload),
            })
        end)
    end)
end

local NOTIFY_COLORS = setmetatable({}, {
    __index = function(_, kind)
        if kind == "Success" or kind == "Warning" or kind == "Error" then
            return Theme[kind]
        end
        return nil
    end,
})

local Window = {}
Window.__index = Window

function Library.Window(_, opts)
    opts = normalize(opts, { Name = "Title", LoadingSubtitle = "Subtitle", ToggleUIKeybind = "Keybind" })
    configureTelemetry(opts)

    if type(opts.AutoTranslate) == "boolean" then
        Library.AutoTranslate = opts.AutoTranslate
    end

    if type(opts.ForceCheckbox) == "boolean" then
        Library:SetForceCheckbox(opts.ForceCheckbox)
    end

    opts.Keybind = Keybinds.Resolve(opts.Keybind)
    local size = opts.Size or UDim2.fromOffset(760, 520)
    local keybind = opts.Keybind or Enum.KeyCode.RightControl

    local logoIcon = opts.Icon
    if logoIcon == nil then
        logoIcon = Assets.Logo
    end
    local self = setmetatable({
        Tabs = {},
        CurrentTab = nil,
        Open = true,
        Keybind = keybind,
        _connections = {},
        _controls = {},
        _inputListeners = { Began = {}, Changed = {}, Ended = {}, Render = {} },
        _frameSteps = {},
        _destroyed = false,
        _identity = { Names = {}, Avatars = {} },
        _pinned = {},
        _islands = {},
        Minimized = false,
        _hideName = false,
        _hideAvatar = false,
        Title = opts.Title or opts.Name or "Aster UI",
        _logoIcon = logoIcon,
        _sessionStart = os.clock(),
        _islandLocked = opts.IslandDraggable == false,
    }, Window)
    local saving = type(opts.ConfigurationSaving) == "table" and opts.ConfigurationSaving or {}
    local folderName = type(saving.FolderName) == "string" and saving.FolderName or nil
    if folderName then
        folderName = folderName:gsub("\\", "/"):gsub("/+", "/"):gsub("^/", ""):gsub("/$", "")
    end
    if folderName and folderName ~= "" then
        self.ConfigFolder = folderName
        ensureFolder(folderName)
    else
        self.ConfigFolder = "AsterUI"
    end
    self.ConfigName = saving.FileName
    self._configListeners = {}
    self._pendingFlags = {}

    local startTheme = opts.DefaultTheme or opts.Theme
    if startTheme ~= nil then
        Library.DefaultTheme = startTheme
    end
    self:_applyDefaultTheme()
    self._uiScale = math.clamp(tonumber(opts.UIScale) or 1, 0.6, 1.5)
    self._adaptive = opts.AdaptiveSize ~= false
    self.UIScale = self._uiScale
    if opts.Density ~= nil then
        Library:SetDensity(opts.Density)
    end
    if opts.CornerRadius ~= nil then
        Library:SetCornerRadius(opts.CornerRadius, true)
    end
    local function dispatch(kind)
        return function(...)
            for _, handler in ipairs(self._inputListeners[kind]) do
                handler(...)
            end
        end
    end
    local renderDispatch = dispatch("Render")
    table.insert(self._connections, RunService.RenderStepped:Connect(function(deltaTime)
        renderDispatch(deltaTime)
        for _, step in ipairs(self._frameSteps) do
            step(deltaTime)
        end
    end))
    table.insert(self._connections, UserInputService.InputBegan:Connect(dispatch("Began")))
    table.insert(self._connections, UserInputService.InputChanged:Connect(dispatch("Changed")))
    table.insert(self._connections, UserInputService.InputEnded:Connect(dispatch("Ended")))

    local gui = create("ScreenGui", {
        Name = opts.Name or "AsterUI",
        IgnoreGuiInset = true,
        ResetOnSpawn = false,
        DisplayOrder = 999,
        ZIndexBehavior = Enum.ZIndexBehavior.Sibling,
    })
    self.Gui = gui
    self.AlwaysOnTop = opts.AlwaysOnTop == true
    Library._SetAlwaysOnTop(gui, self.AlwaysOnTop)

    self._modal = create("TextButton", {
        Name = "Modal",
        BackgroundTransparency = 1,
        Modal = false,
        Size = UDim2.fromScale(0, 0),
        Text = "",
        ZIndex = -999,
        Parent = gui,
    })

    local cursor = create("Frame", {
        Name = "Cursor",
        AnchorPoint = Vector2.new(0.5, 0.5),
        BackgroundTransparency = 1,
        Size = UDim2.fromOffset(1, 1),
        Visible = false,
        ZIndex = 11000,
        Parent = gui,
    })
    local cross = create("Frame", {
        AnchorPoint = Vector2.new(0.5, 0.5),
        BackgroundTransparency = 1,
        Position = UDim2.fromScale(0.5, 0.5),
        Size = UDim2.fromOffset(11, 11),
        Parent = cursor,
    })
    create("Frame", {
        AnchorPoint = Vector2.new(0.5, 0.5),
        BackgroundColor3 = Color3.new(0, 0, 0),
        Position = UDim2.fromScale(0.5, 0.5),
        Size = UDim2.new(1, 0, 0, 3),
        ZIndex = 1,
        Parent = cross,
    })
    create("Frame", {
        AnchorPoint = Vector2.new(0.5, 0.5),
        BackgroundColor3 = Color3.new(1, 1, 1),
        Position = UDim2.fromScale(0.5, 0.5),
        Size = UDim2.new(1, -2, 0, 1),
        ZIndex = 2,
        Parent = cross,
    })
    create("Frame", {
        AnchorPoint = Vector2.new(0.5, 0.5),
        BackgroundColor3 = Color3.new(0, 0, 0),
        Position = UDim2.fromScale(0.5, 0.5),
        Size = UDim2.new(0, 3, 1, 0),
        ZIndex = 1,
        Parent = cross,
    })
    create("Frame", {
        AnchorPoint = Vector2.new(0.5, 0.5),
        BackgroundColor3 = Color3.new(1, 1, 1),
        Position = UDim2.fromScale(0.5, 0.5),
        Size = UDim2.new(0, 1, 1, -2),
        ZIndex = 2,
        Parent = cross,
    })
    self._cursor = cursor
    self._cursorBinding = "AsterCursor_" .. string.sub(tostring({}), 10)
    self._originalMouseIconEnabled = UserInputService.MouseIconEnabled

    local root = create("Frame", {
        Name = "Window",
        AnchorPoint = Vector2.new(0.5, 0.5),
        Position = UDim2.fromScale(0.5, 0.5),
        Size = size,
        BackgroundTransparency = 1,
        Parent = gui,
    })
    self.Root = root
    local scale = create("UIScale", { Parent = root })
    self.Scale = scale

    local shadow = create("ImageLabel", {
        Position = UDim2.fromOffset(-25, -25),
        Size = UDim2.new(1, 50, 1, 50),
        BackgroundTransparency = 1,
        Image = Assets.Shadow,
        ImageColor3 = Color3.new(0, 0, 0),
        ImageTransparency = 0.6,
        ScaleType = Enum.ScaleType.Slice,
        SliceCenter = Rect.new(49, 49, 450, 450),
        Parent = root,
    })
    self.Shadow = shadow
    self._shadowRest = 0.6

    local fader = create("CanvasGroup", {
        Name = "Fader",
        Size = UDim2.fromScale(1, 1),
        BackgroundTransparency = 1,
        GroupTransparency = 1,
        ZIndex = 2,
        Parent = root,
    })
    self._fader = fader
    self._bodyAlpha = 1
    local body = create("Frame", {
        Name = "Body",
        Size = UDim2.fromScale(1, 1),
        BackgroundColor3 = Theme.Background,
        BorderSizePixel = 0,
        ClipsDescendants = true,
        ZIndex = 2,
        Parent = fader,
    })
    self.Body = body
    corner(body, UDim.new(0, 10))
    self.BodyStroke = stroke(body, Theme.Stroke)
    edgeHighlight(body)
    -- Background image: made first so everything else in the body draws over it.
    self._backgroundImage = create("ImageLabel", {
        Name = "BackgroundImage",
        Size = UDim2.fromScale(1, 1),
        BackgroundTransparency = 1,
        ScaleType = Enum.ScaleType.Crop,
        ImageTransparency = 1,
        Visible = false,
        ZIndex = 0,
        Parent = body,
    })
    corner(self._backgroundImage, UDim.new(0, 10))
    self.BackgroundTransparency = math.clamp(tonumber(opts.BackgroundTransparency) or 0.35, 0, 1)
    self._backgroundGeneration = 0

    local sidebar = create("Frame", {
        Name = "Sidebar",
        Size = UDim2.new(0, SIDEBAR_WIDTH, 1, 0),
        BackgroundTransparency = 1,
        BorderSizePixel = 0,
        ClipsDescendants = true,
        Parent = body,
    })
    self.Sidebar = sidebar
    local sidebarFill = create("Frame", {
        Name = "Fill",
        Size = UDim2.new(1, 24, 1, 0),
        BackgroundColor3 = Theme.Surface,
        BorderSizePixel = 0,
        ZIndex = 0,
        Parent = sidebar,
    })
    corner(sidebarFill, UDim.new(0, 10))
    self.SidebarFill = sidebarFill
    create("Frame", {
        Name = "Divider",
        AnchorPoint = Vector2.new(1, 0),
        Position = UDim2.fromScale(1, 0),
        Size = UDim2.new(0, 1, 1, 0),
        BackgroundColor3 = Theme.Stroke,
        BorderSizePixel = 0,
        ZIndex = 2,
        Parent = sidebar,
    })

    local header = create("Frame", {
        Name = "Header",
        Size = UDim2.new(1, 0, 0, HEADER_HEIGHT),
        BackgroundTransparency = 1,
        Parent = sidebar,
    })
    if opts.Icon ~= false then
        local logo = create("ImageLabel", {
            AnchorPoint = Vector2.new(0, 0.5),
            Position = UDim2.new(0, 14, 0.5, 0),
            Size = UDim2.fromOffset(32, 32),
            BackgroundTransparency = 1,
            Image = "",
            ImageColor3 = Color3.new(1, 1, 1),
            ScaleType = Enum.ScaleType.Fit,
            Parent = header,
        })
        applyIcon(logo, opts.Icon or Assets.Logo, true)
    end
    local TEXT_X = opts.Icon ~= false and 56 or 22
    local subtitle = opts.Version or opts.Subtitle
    label({
        Position = UDim2.new(0, TEXT_X, 0.5, subtitle and -15 or -9),
        Size = UDim2.new(1, -(TEXT_X + 12), 0, 18),
        Text = self.Title,
        TextSize = 14,
        FontFace = Fonts.Bold,
        Parent = header,
    })
    if subtitle then
        label({
            Position = UDim2.new(0, TEXT_X, 0.5, 3),
            Size = UDim2.new(1, -(TEXT_X + 12), 0, 14),
            Text = tostring(subtitle),
            TextSize = 11,
            FontFace = Fonts.Regular,
            TextColor3 = Theme.Muted,
            Parent = header,
        })
    end

    local profileEnabled = opts.Profile ~= false
    local tabList = create("ScrollingFrame", {
        Name = "Tabs",
        Position = UDim2.fromOffset(0, HEADER_HEIGHT),
        Size = UDim2.new(1, 0, 1, -(HEADER_HEIGHT + (profileEnabled and PROFILE_HEIGHT + 4 or 12))),
        BackgroundTransparency = 1,
        BorderSizePixel = 0,
        ScrollBarThickness = 0,
        ScrollingDirection = Enum.ScrollingDirection.Y,
        AutomaticCanvasSize = Enum.AutomaticSize.Y,
        CanvasSize = UDim2.new(),
        Parent = sidebar,
    })
    self.TabList = tabList
    local indicator = create("Frame", {
        Position = UDim2.fromOffset(8, 2),
        Size = UDim2.new(1, -16, 0, TAB_TILE_HEIGHT),
        BackgroundColor3 = Theme.Surface3,
        BackgroundTransparency = 0.35,
        BorderSizePixel = 0,
        Visible = false,
        Parent = tabList,
    })
    corner(indicator, UDim.new(0, 7))
    local pill = create("Frame", {
        AnchorPoint = Vector2.new(0, 0.5),
        Position = UDim2.new(0, 0, 0.5, 0),
        Size = UDim2.fromOffset(2, 14),
        BackgroundColor3 = Theme.Accent,
        Visible = false,
        BorderSizePixel = 0,
        Parent = indicator,
    })
    corner(pill, UDim.new(1, 0))
    self._indicatorPill = pill
    self.Indicator = indicator
    local stack = create("Frame", {
        Name = "Stack",
        Position = UDim2.fromOffset(8, 2),
        Size = UDim2.new(1, -16, 0, 0),
        AutomaticSize = Enum.AutomaticSize.Y,
        BackgroundTransparency = 1,
        ZIndex = 2,
        Parent = tabList,
    })
    create("UIListLayout", {
        SortOrder = Enum.SortOrder.LayoutOrder,
        Padding = UDim.new(0, 2),
        Parent = stack,
    })
    self._tabStack = stack

    -- More tabs than fit: a fade and a small "more" chip at the hidden end.
    self:_overflowHint(sidebar, tabList, stack, true, Theme.Surface)

    if profileEnabled then
        self:_buildProfile(sidebar)
    end

    local content = create("Frame", {
        Name = "Content",
        Position = UDim2.fromOffset(SIDEBAR_WIDTH + 1, 0),
        Size = UDim2.new(1, -(SIDEBAR_WIDTH + 1), 1, 0),
        BackgroundTransparency = 1,
        ClipsDescendants = true,
        Parent = body,
    })
    self.Content = content
    self:_sidebarResize(sidebar, tonumber(opts.SidebarWidth) or SIDEBAR_WIDTH)
    self._outLayer = create("CanvasGroup", {
        Name = "TransitionOut",
        Size = UDim2.fromScale(1, 1),
        BackgroundTransparency = 1,
        Visible = false,
        ZIndex = 2,
        Parent = content,
    })
    self._inLayer = create("CanvasGroup", {
        Name = "TransitionIn",
        Size = UDim2.fromScale(1, 1),
        BackgroundTransparency = 1,
        Visible = false,
        ZIndex = 3,
        Parent = content,
    })

    local minimizeButton = create("TextButton", {
        AnchorPoint = Vector2.new(1, 0),
        Position = UDim2.new(1, -14, 0, 14),
        Size = UDim2.fromOffset(34, 34),
        BackgroundColor3 = Theme.Surface2,
        BackgroundTransparency = 1,
        Text = "",
        AutoButtonColor = false,
        ZIndex = 5,
        Parent = content,
    })
    minimizeButton:SetAttribute("NoDrag", true)
    local minimizeGlyph = create("ImageLabel", {
        AnchorPoint = Vector2.new(0.5, 0.5),
        Position = UDim2.fromScale(0.5, 0.5),
        Size = UDim2.fromOffset(20, 20),
        BackgroundTransparency = 1,
        ImageColor3 = Theme.Muted,
        ScaleType = Enum.ScaleType.Fit,
        Parent = minimizeButton,
    })
    applyIcon(minimizeGlyph, "minimize-2")
    minimizeButton.MouseEnter:Connect(function()
        tween(minimizeGlyph, { ImageColor3 = Theme.Text, Size = UDim2.fromOffset(18, 18) }, 0.2, Enum.EasingStyle.Quint)
    end)
    minimizeButton.MouseLeave:Connect(function()
        tween(minimizeGlyph, { ImageColor3 = Theme.Muted, Size = UDim2.fromOffset(20, 20) }, 0.25, Enum.EasingStyle.Quint)
    end)
    minimizeButton.MouseButton1Click:Connect(function()
        self:Minimize()
    end)
    self.MinimizeButton = minimizeButton

    if opts.Search ~= false then
        self:_buildSearch(content)
    end

    local notifyHolder = create("Frame", {
        Name = "Notifications",
        AnchorPoint = Vector2.new(1, 1),
        Position = UDim2.new(1, -20, 1, -20),
        Size = UDim2.new(0, 280, 1, -40),
        BackgroundTransparency = 1,
        Parent = gui,
    })
    local function fitToasts()
        notifyHolder.Size = UDim2.new(0, math.min(280, gui.AbsoluteSize.X - 40), 1, -40)
    end
    table.insert(self._connections, gui:GetPropertyChangedSignal("AbsoluteSize"):Connect(fitToasts))
    create("UIListLayout", {
        SortOrder = Enum.SortOrder.LayoutOrder,
        VerticalAlignment = Enum.VerticalAlignment.Bottom,
        Padding = UDim.new(0, 4),
        Parent = notifyHolder,
    })
    self.NotifyHolder = notifyHolder
    self._notifyOrder = 0
    self._toasts = {}
    self.MaxNotifications = opts.MaxNotifications or 4

    self._controlsDirty = true
    table.insert(self._connections, body.DescendantAdded:Connect(function()
        self._controlsDirty = true
    end))
    table.insert(self._connections, body.DescendantRemoving:Connect(function()
        self._controlsDirty = true
    end))

    self:SetDragStyle(opts.DragStyle or (opts.DragSkeleton == false and "Off" or "Outline"))
    self:SetIslandStyle(opts.IslandStyle)
    if opts.Transparent then
        self:SetTransparent(true)
    end
    if opts.Background then
        task.spawn(self.SetBackground, self, opts.Background)
    end
    self:_enableDrag()
    self.MaxSize = opts.MaxSize
    self.KeepOnScreen = opts.KeepOnScreen ~= false
    self.UnlockMouseWhileOpen = opts.UnlockMouseWhileOpen ~= false
    self.ShowCustomCursor = opts.ShowCustomCursor ~= false
    self:_enableResize(opts.MinSize or Vector2.new(480, 360))
    -- window size is saved as a hidden flag.
    if opts.SaveSize ~= false then
        local window = self
        local sizeFlag = { _type = "WindowSize", _listeners = {} }
        function sizeFlag:Get()
            local current = window:GetSize()
            return { Width = current.X, Height = current.Y }
        end
        function sizeFlag:Set(value)
            if type(value) == "table" and tonumber(value.Width) and tonumber(value.Height) then
                window:SetSize(Vector2.new(tonumber(value.Width), tonumber(value.Height)))
            end
        end
        local flag = type(opts.SaveSize) == "string" and opts.SaveSize or "__WindowSize"
        Library.Flags[flag] = sizeFlag
        self:_flagCreated(flag, sizeFlag)
    end

    table.insert(self._connections, UserInputService.InputBegan:Connect(function(input, gameProcessed)
        if gameProcessed then
            return
        end
        local bind = Keybinds.FromInput(input)
        if bind ~= nil and bind == self.Keybind then
            task.defer(function()
                local consumed = self._consumedKey == bind and os.clock() - (self._consumedAt or 0) < 0.2
                self._consumedKey = nil
                if not consumed and not self._destroyed then
                    if self.Minimized then
                        self:Restore()
                    else
                        self:Toggle(not self.Open)
                    end
                end
            end)
        end
    end))

    pcall(function()
        if typeof(syn) == "table" and typeof(syn.protect_gui) == "function" then
            syn.protect_gui(gui)
        end
    end)
    gui.Parent = opts.Parent or defaultParent()

    scale.Scale = 0.9
    shadow.ImageTransparency = 1
    self.BodyStroke.Transparency = 1
    root.Visible = false
    self:_fitToScreen(true)
    table.insert(self._connections, gui:GetPropertyChangedSignal("AbsoluteSize"):Connect(function()
        self:_fitToScreen()
        self:_clampToScreen()
    end))
    local toggleOpts = opts.ToggleButton
    if toggleOpts == nil or toggleOpts == true then
        toggleOpts = {}
    end
    if type(toggleOpts) == "table" then
        self:_createToggleButton(toggleOpts)
    end
    local toggleShown = self.ToggleButton ~= nil and self:_toggleButtonAllowed()
    if (opts.OpenButton ~= nil and opts.OpenButton ~= false) or (opts.OpenButton == nil and TOUCH and not toggleShown) then
        self:_createOpenButton(type(opts.OpenButton) == "table" and opts.OpenButton or {})
    end
    if opts.Backdrop ~= false then
        local backdrop = type(opts.Backdrop) == "table" and opts.Backdrop or {}
        if opts.Weather ~= nil and backdrop.Weather == nil then
            local merged = {}
            for key, value in pairs(backdrop) do
                merged[key] = value
            end
            merged.Weather = opts.Weather
            backdrop = merged
        end
        self:_buildBackdrop(backdrop)
    end
    self._introDone = false

    table.insert(Library.Windows, self)

    Library:_trackTelemetry("Script executado")

    local keybindMenu = Library:_createKeybindMenu(self)
    if opts.KeybindMenu == true then
        keybindMenu:SetVisible(true)
    end

    if opts.Home ~= false then
        self:_buildHome(type(opts.Home) == "table" and opts.Home or {})
    end

    local loading = opts.Loading
    if type(loading) == "table" then
        opts.LoadingDuration = loading.Duration or opts.LoadingDuration
        opts.LoadingText = loading.Text or loading.Subtitle or opts.LoadingText
        opts.LoadingSteps = loading.Steps or opts.LoadingSteps
        opts.LoadingTitle = loading.Title or opts.LoadingTitle
        loading = loading.Enabled ~= false
    end
    local prompts = {}
    local gate = opts.UnsupportedExecutor
    if gate ~= false then
        gate = type(gate) == "table" and gate or {}
        local list = opts.SupportedExecutors or (type(opts.Home) == "table" and opts.Home.SupportedExecutors or nil)
        local executor, supported, message = executorReport({ SupportedExecutors = list })
        if not supported and not UnsupportedSkip.Saved(self.ConfigFolder, executor) then
            local block = gate.Block == true
            local folder = self.ConfigFolder
            table.insert(prompts, {
                Title = gate.Title or "Unsupported executor",
                Subtitle = executor,
                Text = block and ((gate.Text or message) .. " This script can't run here.") or (gate.Text or message),
                Icon = "shield-alert",
                Color = Theme.Warning,
                ContinueText = "Continue anyway",
                ExitText = "Exit",
                Block = block,
                RememberText = "Don't ask again on this executor",
                Remember = function()
                    UnsupportedSkip.Save(folder, executor)
                end,
            })
        end
    end
    local disclaimers = opts.Disclaimer or opts.Disclaimers
    if type(disclaimers) == "string" or (type(disclaimers) == "table" and (disclaimers.Title ~= nil or disclaimers.Text ~= nil)) then
        disclaimers = { disclaimers }
    end
    if type(disclaimers) == "table" then
        for _, entry in ipairs(disclaimers) do
            if type(entry) == "string" then
                entry = { Text = entry }
            end
            if type(entry) == "table" then
                local key = UnsupportedSkip.DisclaimerKey(entry)
                local folder = self.ConfigFolder
                local block = entry.Block == true
                local rememberable = entry.Remember ~= false and not block
                if not (rememberable and UnsupportedSkip.DisclaimerAccepted(folder, key)) then
                    local callback = entry.Callback
                    local entryIcon = cleanIcon(entry.Icon)
                    if entryIcon == nil then
                        entryIcon = "info"
                    end
                    table.insert(prompts, {
                        Title = entry.Title or "Disclaimer",
                        Subtitle = entry.Subtitle,
                        Text = entry.Text or "",
                        Icon = entryIcon,
                        Color = entry.Color or Theme.Accent,
                        ContinueText = entry.AcceptText or "I understand",
                        ExitText = entry.DeclineText == nil and "Exit" or entry.DeclineText,
                        RememberText = rememberable and (entry.RememberText or "Don't show again") or nil,
                        Remember = function()
                            UnsupportedSkip.AcceptDisclaimer(folder, key)
                        end,
                        Callback = type(callback) == "function" and callback or nil,
                        Block = block,
                    })
                end
            end
        end
    end
    if #prompts > 0 then
        opts._prompts = prompts
    end
    if loading == false and opts._prompts then
        opts.LoadingDuration = opts.LoadingDuration or 0.5
        loading = true
    end
    if loading == false then
        task.defer(function()
            self:_playIntro()
        end)
    else
        self:_showLoader(opts)
    end
    return self
end

Library.CreateWindow = Library.Window



function Library:Notify(opts)
    local window = Library.Windows[#Library.Windows]
    if window then
        return window:Notify(opts)
    end
end

function Library:Confirm(opts)
    local window = Library.Windows[#Library.Windows]
    if window then
        return window:Confirm(opts)
    end
end

function Library:Dialog(opts)
    local window = Library.Windows[#Library.Windows]
    if window then
        return window:Dialog(opts)
    end
end

Library._draggableLabels = {}
local OVERLAY_UI_SCALE = 1.1

function Library:AddDraggableLabel(...)
    local params = select(1, ...)
    local text, icon, iconPosition, startPosition, requestedWindow
    if typeof(params) == "table" then
        text = params.Text
        icon = params.Icon
        iconPosition = params.IconPosition
        startPosition = params.Position
        requestedWindow = params.Window
    elseif typeof(params) == "string" then
        text = params
        icon = select(2, ...)
        iconPosition = select(3, ...)
    end
    icon = cleanIcon(icon)
    if typeof(startPosition) == "table" then
        local x = tonumber(startPosition.X or startPosition[1])
        local y = tonumber(startPosition.Y or startPosition[2])
        startPosition = (x and y) and Vector2.new(x, y) or nil
    end
    if typeof(startPosition) ~= "Vector2" then
        startPosition = nil
    end
    if type(requestedWindow) ~= "table" then
        requestedWindow = nil
    end
    if typeof(iconPosition) ~= "string" then
        iconPosition = "left"
    end
    iconPosition = string.lower(iconPosition)
    if iconPosition ~= "right" then
        iconPosition = "left"
    end

    local window = requestedWindow or Library.Windows[#Library.Windows]
    if not window or not window.Gui or window._destroyed then
        warn("[Aster UI] AddDraggableLabel needs a window: create one first.")
        return nil
    end
    local gui = window.Gui
    local offset = Vector2.new(6, 6)

    local entry = {
        Connections = {},
        Destroyed = false,
    }

    local pill = create("TextButton", {
        Name = "DraggableLabel",
        Size = UDim2.fromOffset(0, 0),
        AutomaticSize = Enum.AutomaticSize.XY,
        BackgroundColor3 = Theme.Background,
        BorderSizePixel = 0,
        Text = "",
        AutoButtonColor = false,
        ZIndex = 5,
        Parent = gui,
    })
    entry.Label = pill

    corner(pill, UDim.new(0, 6))
    stroke(pill, Theme.Stroke)
    local pad = padding(pill, 12, 12, 6, 6)
    local scale = create("UIScale", { Scale = window:GetUIScale() * OVERLAY_UI_SCALE, Parent = pill })
    entry._scale = scale

    local textLabel = label({
        Size = UDim2.fromOffset(0, 0),
        AutomaticSize = Enum.AutomaticSize.XY,
        Text = text ~= nil and tostring(text) or "",
        TextSize = 13,
        TextTruncate = Enum.TextTruncate.None,
        ZIndex = 2,
        Parent = pill,
    })

    local iconImage
    local function hasIcon()
        return icon ~= nil and icon ~= false and tostring(icon):match("%S") ~= nil
    end

    local function updateIconLayout()
        local filled = hasIcon()
        pad.PaddingLeft = UDim.new(0, (filled and iconPosition == "left") and 34 or 12)
        pad.PaddingRight = UDim.new(0, (filled and iconPosition == "right") and 34 or 12)
        if iconImage then
            if iconPosition == "left" then
                iconImage.AnchorPoint = Vector2.new(0, 0.5)
                iconImage.Position = UDim2.new(0, -22, 0.5, 0)
            else
                iconImage.AnchorPoint = Vector2.new(1, 0.5)
                iconImage.Position = UDim2.new(1, 22, 0.5, 0)
            end
        end
    end

    local function applyCurrentIcon()
        if hasIcon() then
            iconImage = iconImage or create("ImageLabel", {
                Name = "Icon",
                BackgroundTransparency = 1,
                ImageColor3 = Theme.Text,
                Size = UDim2.fromOffset(16, 16),
                ZIndex = 2,
                Parent = pill,
            })
            applyIcon(iconImage, icon, true)
        end
        if iconImage then
            iconImage.Visible = hasIcon()
        end
        updateIconLayout()
    end

    local dragging = false
    local dragOrigin = Vector2.zero
    local dragStart = Vector2.zero

    local measureClampQueued = false
    local function placeAt(point)
        local viewport = gui.AbsoluteSize
        if viewport.X <= 0 or viewport.Y <= 0 then
            offset = Vector2.new(math.max(point.X, 0), math.max(point.Y, 0))
            if not measureClampQueued then
                measureClampQueued = true
                RunService.RenderStepped:Once(function()
                    measureClampQueued = false
                    if not entry.Destroyed and pill.Parent then
                        placeAt(offset)
                    end
                end)
            end
        else
            local bound = viewport - pill.AbsoluteSize
            offset = Vector2.new(
                math.clamp(point.X, 0, math.max(bound.X, 0)),
                math.clamp(point.Y, 0, math.max(bound.Y, 0))
            )
        end
        pill.Position = UDim2.fromOffset(offset.X, offset.Y)
    end

    table.insert(entry.Connections, pill.InputBegan:Connect(function(input)
        if entry.Destroyed or not isPress(input) then
            return
        end
        dragging = true
        dragOrigin = offset
        dragStart = pointerPosition()
    end))

    local dragChanged = UserInputService.InputChanged:Connect(function(input)
        if entry.Destroyed or not dragging or not isMove(input) then
            return
        end
        -- The pill's own scale does not move its offset: plain pixel delta.
        placeAt(dragOrigin + (pointerPosition() - dragStart))
    end)
    local dragEnded = UserInputService.InputEnded:Connect(function(input)
        if entry.Destroyed or not dragging then
            return
        end
        if isPress(input) then
            dragging = false
        end
    end)
    table.insert(entry.Connections, dragChanged)
    table.insert(entry.Connections, dragEnded)
    table.insert(window._connections, dragChanged)
    table.insert(window._connections, dragEnded)

    function entry:SetText(newText)
        textLabel.Text = newText ~= nil and tostring(newText) or ""
    end

    function entry:SetIcon(newIcon)
        icon = cleanIcon(newIcon)
        applyCurrentIcon()
    end

    function entry:SetIconPosition(newPosition)
        iconPosition = (typeof(newPosition) == "string" and string.lower(newPosition) == "right") and "right" or "left"
        updateIconLayout()
    end

    function entry:SetVisible(visible)
        pill.Visible = visible ~= false
    end

    function entry:Destroy()
        if entry.Destroyed then
            return
        end
        entry.Destroyed = true
        for _, connection in ipairs(entry.Connections) do
            pcall(function()
                connection:Disconnect()
            end)
        end
        table.clear(entry.Connections)
        for index, item in ipairs(Library._draggableLabels) do
            if item == entry then
                table.remove(Library._draggableLabels, index)
                break
            end
        end
        pill:Destroy()
    end

    applyCurrentIcon()
    table.insert(Library._draggableLabels, entry)

    -- One frame may pass first so the AutomaticSize has measured the pill.
    local function measurePill()
        if pill.AbsoluteSize.X <= 0 then
            pcall(function()
                RunService.RenderStepped:Wait()
            end)
        end
    end

    local function firstFreeSpot()
        measurePill()
        local size = pill.AbsoluteSize
        if size.X <= 0 then
            size = Vector2.new(150, 34) * scale.Scale
        end
        local bounds = gui.AbsoluteSize
        local margin = 6
        local x, y = margin, margin
        local column = size.X
        for _ = 1, 256 do
            local hitPosition, hitSize
            for _, other in ipairs(Library._draggableLabels) do
                local otherPill = other.Label
                if other ~= entry and otherPill and otherPill.Parent and otherPill.Visible then
                    local otherPosition = otherPill.AbsolutePosition - gui.AbsolutePosition
                    local otherSize = otherPill.AbsoluteSize
                    if x < otherPosition.X + otherSize.X and x + size.X > otherPosition.X
                        and y < otherPosition.Y + otherSize.Y and y + size.Y > otherPosition.Y then
                        hitPosition, hitSize = otherPosition, otherSize
                        break
                    end
                end
            end
            if not hitPosition then
                return Vector2.new(x, y)
            end
            column = math.max(column, hitSize.X)
            local nextY = hitPosition.Y + hitSize.Y + margin
            if nextY + size.Y > bounds.Y - margin then
                local nextX = x + column + margin
                if nextX + size.X > bounds.X - margin then
                    return Vector2.new(x, y)
                end
                x, y = nextX, margin
                column = size.X
            else
                y = nextY
            end
        end
        return Vector2.new(x, y)
    end

    if startPosition then
        measurePill()
        placeAt(startPosition)
    else
        placeAt(firstFreeSpot())
    end

    entry._reclamp = function()
        placeAt(offset)
    end

    return entry
end

function Library._syncDraggableLabels()
    local window = Library.Windows[#Library.Windows]
    local target = ((window and window:GetUIScale()) or 1) * OVERLAY_UI_SCALE
    for index = #Library._draggableLabels, 1, -1 do
        local entry = Library._draggableLabels[index]
        local pill = entry and entry.Label
        if not entry or entry.Destroyed or not pill or not pill.Parent then
            table.remove(Library._draggableLabels, index)
        else
            entry._scale.Scale = target
            if entry._reclamp then
                entry._reclamp()
            end
        end
    end
end

function Library:_createKeybindMenu(window)
    local gui = window.Gui
    local HEADER_H = 34
    local ROW_H = 16
    local ROW_GAP = 6
    local BODY_PAD_X = 12
    local BODY_PAD_Y = 8
    local MIN_WIDTH = 140

    local frame = create("Frame", {
        Name = "KeybindFrame",
        AnchorPoint = Vector2.new(0, 0.5),
        Position = UDim2.new(0, 6, 0.5, 0),
        AutomaticSize = Enum.AutomaticSize.XY,
        Size = UDim2.fromOffset(0, 0),
        BackgroundColor3 = Theme.Background,
        BorderSizePixel = 0,
        Visible = false,
        ZIndex = 6,
        Parent = gui,
    })
    corner(frame, UDim.new(0, 6))
    stroke(frame, Theme.Stroke)
    create("UISizeConstraint", {
        MinSize = Vector2.new(MIN_WIDTH, 0),
        MaxSize = Vector2.new(100000, 100000),
        Parent = frame,
    })
    local scaleObject = create("UIScale", {
        Scale = window:GetUIScale() * OVERLAY_UI_SCALE,
        Parent = frame,
    })

    local header = create("TextButton", {
        Name = "Header",
        Size = UDim2.new(1, 0, 0, HEADER_H),
        BackgroundTransparency = 1,
        Text = "",
        AutoButtonColor = false,
        ZIndex = 2,
        Parent = frame,
    })
    local title = label({
        Position = UDim2.fromOffset(BODY_PAD_X, 0),
        Size = UDim2.fromOffset(0, HEADER_H),
        AutomaticSize = Enum.AutomaticSize.X,
        Text = "Keybinds",
        TextSize = 13,
        FontFace = Fonts.Bold,
        TextTruncate = Enum.TextTruncate.None,
        ZIndex = 2,
        Parent = header,
    })

    local collapseButton = create("TextButton", {
        Name = "Collapse",
        AnchorPoint = Vector2.new(1, 0.5),
        Position = UDim2.new(1, -6, 0.5, 0),
        Size = UDim2.fromOffset(24, 24),
        BackgroundTransparency = 1,
        Text = "",
        AutoButtonColor = false,
        ZIndex = 3,
        Parent = header,
    })
    local chevron = create("ImageLabel", {
        AnchorPoint = Vector2.new(0.5, 0.5),
        Position = UDim2.fromScale(0.5, 0.5),
        Size = UDim2.fromOffset(14, 14),
        BackgroundTransparency = 1,
        ImageColor3 = Theme.Muted,
        ScaleType = Enum.ScaleType.Fit,
        ZIndex = 3,
        Parent = collapseButton,
    })
    applyIcon(chevron, "chevron-down")

    local rule = create("Frame", {
        Position = UDim2.fromOffset(0, HEADER_H),
        Size = UDim2.new(1, 0, 0, 1),
        BackgroundColor3 = Theme.Stroke,
        BorderSizePixel = 0,
        ZIndex = 1,
        Parent = frame,
    })
    local body = create("Frame", {
        Position = UDim2.fromOffset(0, HEADER_H + 1),
        AutomaticSize = Enum.AutomaticSize.XY,
        Size = UDim2.fromOffset(0, 0),
        BackgroundTransparency = 1,
        ZIndex = 1,
        Parent = frame,
    })
    padding(body, BODY_PAD_X, BODY_PAD_X, BODY_PAD_Y, BODY_PAD_Y)
    create("UIListLayout", {
        SortOrder = Enum.SortOrder.LayoutOrder,
        Padding = UDim.new(0, ROW_GAP),
        Parent = body,
    })

    local menu = {
        Window = window,
        Frame = frame,
        Container = body,
        Collapsed = false,
        Destroyed = false,
        Label = frame,
        _scale = scaleObject,
        _entries = {},
        _rowCount = 0,
        _nextRowOrder = 0,
        _emptyRow = nil,
        _connections = {},
    }

    function menu:_syncEmpty()
        if menu.Destroyed or not body.Parent then
            return
        end
        if menu._rowCount == 0 then
            if not menu._emptyRow then
                menu._emptyRow = label({
                    Size = UDim2.fromOffset(0, ROW_H),
                    AutomaticSize = Enum.AutomaticSize.X,
                    LayoutOrder = 0,
                    Text = "No keybinds yet",
                    TextSize = 13,
                    TextColor3 = Theme.Muted,
                    TextTruncate = Enum.TextTruncate.None,
                    ZIndex = 2,
                    Parent = body,
                })
            end
        elseif menu._emptyRow then
            menu._emptyRow:Destroy()
            menu._emptyRow = nil
        end
    end

    function menu:_updateRow(element)
        local row = element._keybindRow
        if not row or not row.Parent then
            return
        end
        local value = element.Value
        local text = "[" .. keyName(value) .. "] " .. (element._keybindName or "Keybind")
        if row.Text ~= text then
            row.Text = text
        end
        local bound = typeof(value) == "EnumItem"
        if element._keybindBound ~= bound then
            element._keybindBound = bound
            local color = bound and Theme.Text or Theme.Muted
            row.TextColor3 = color
            bindColors(row, { TextColor3 = color })
        end
    end

    function menu:AddRow(element)
        if menu.Destroyed or not body.Parent or element._keybindRow or menu._entries[element] then
            return
        end
        if menu._emptyRow then
            menu._emptyRow:Destroy()
            menu._emptyRow = nil
        end
        menu._nextRowOrder += 1
        local row = label({
            Size = UDim2.fromOffset(0, ROW_H),
            AutomaticSize = Enum.AutomaticSize.X,
            LayoutOrder = menu._nextRowOrder,
            Text = "",
            TextSize = 13,
            TextTruncate = Enum.TextTruncate.None,
            ZIndex = 2,
            Parent = body,
        })
        element._keybindRow = row
        element._keybindMenu = menu
        element._keybindBound = nil
        menu._entries[element] = row
        menu._rowCount += 1
        menu:_updateRow(element)
    end

    function menu:RemoveRow(element)
        local row = element._keybindRow
        element._keybindRow = nil
        element._keybindMenu = nil
        element._keybindBound = nil
        if menu._entries[element] then
            menu._entries[element] = nil
            menu._rowCount = math.max(menu._rowCount - 1, 0)
        end
        if row then
            row:Destroy()
        end
        menu:_syncEmpty()
    end

    function menu:Refresh()
        if menu.Destroyed then
            return
        end
        local stale
        for element, row in pairs(menu._entries) do
            if element._destroyed or not element._keybindRow or not row or not row.Parent then
                stale = stale or {}
                table.insert(stale, element)
            else
                menu:_updateRow(element)
            end
        end
        if stale then
            for _, element in ipairs(stale) do
                menu:RemoveRow(element)
            end
        end
        menu:_syncEmpty()
    end

    local function clampPosition(xOffset, yOffset)
        if menu.Destroyed then
            return
        end
        local view = gui.AbsoluteSize
        local position
        if view.X <= 0 or view.Y <= 0 then
            position = UDim2.new(0, math.max(xOffset, 0), 0.5, yOffset)
        else
            local size = frame.AbsoluteSize
            local x = math.clamp(xOffset, 0, math.max(view.X - size.X, 0))
            local top = view.Y * 0.5 + yOffset - size.Y * 0.5
            top = math.clamp(top, 0, math.max(view.Y - size.Y, 0))
            position = UDim2.new(0, x, 0.5, (top + size.Y * 0.5) - view.Y * 0.5)
        end
        if frame.Position ~= position then
            frame.Position = position
        end
    end

    menu._reclamp = function()
        if not menu.Destroyed then
            clampPosition(frame.Position.X.Offset, frame.Position.Y.Offset)
        end
    end

    local function renderCollapse()
        rule.Visible = not menu.Collapsed
        body.Visible = not menu.Collapsed
        tween(chevron, { Rotation = menu.Collapsed and 0 or 180 }, 0.18, Enum.EasingStyle.Quint)
    end

    function menu:SetCollapsed(collapsed)
        collapsed = collapsed == true
        if menu.Destroyed or collapsed == menu.Collapsed then
            return
        end
        local width
        if collapsed then
            width = frame.AbsoluteSize.X / math.max(scaleObject.Scale, 0.01)
        end
        menu.Collapsed = collapsed
        renderCollapse()
        if collapsed then
            frame.AutomaticSize = Enum.AutomaticSize.None
            frame.Size = UDim2.fromOffset(math.max(width, MIN_WIDTH), HEADER_H)
        else
            frame.AutomaticSize = Enum.AutomaticSize.XY
            frame.Size = UDim2.fromOffset(0, 0)
        end
        menu:_reclamp()
    end

    function menu:ToggleCollapsed()
        menu:SetCollapsed(not menu.Collapsed)
    end

    function menu:SetVisible(visible)
        if menu.Destroyed then
            return
        end
        frame.Visible = visible ~= false
    end

    function menu:ToggleVisible()
        menu:SetVisible(not frame.Visible)
    end

    function menu:Destroy()
        if menu.Destroyed then
            return
        end
        menu.Destroyed = true
        table.clear(menu._entries)
        menu._emptyRow = nil
        for index = #Library._keybindMenus, 1, -1 do
            if Library._keybindMenus[index] == menu then
                table.remove(Library._keybindMenus, index)
                break
            end
        end
        for index = #Library._draggableLabels, 1, -1 do
            if Library._draggableLabels[index] == menu then
                table.remove(Library._draggableLabels, index)
                break
            end
        end
        for _, connection in ipairs(menu._connections) do
            pcall(function()
                connection:Disconnect()
            end)
        end
        table.clear(menu._connections)
        if Library.KeybindMenu == menu then
            local newest = Library._keybindMenus[#Library._keybindMenus]
            Library.KeybindMenu = newest
            Library.KeybindFrame = newest and newest.Frame or nil
        end
        if window.KeybindMenu == menu then
            window.KeybindMenu = nil
            window.KeybindFrame = nil
        end
        pcall(function()
            frame:Destroy()
        end)
    end

    local function track(connection)
        table.insert(menu._connections, connection)
        table.insert(window._connections, connection)
        return connection
    end

    local dragging = false
    local dragOriginX, dragOriginY = 6, 0
    local dragStart = Vector2.zero

    track(header.InputBegan:Connect(function(input)
        if menu.Destroyed or not isPress(input) then
            return
        end
        -- The chevron is its own button; pressing it must not start a drag.
        if pointInside(pointerPosition(), collapseButton) then
            return
        end
        dragging = true
        dragOriginX = frame.Position.X.Offset
        dragOriginY = frame.Position.Y.Offset
        dragStart = pointerPosition()
    end))

    track(UserInputService.InputChanged:Connect(function(input)
        if menu.Destroyed or not dragging or not isMove(input) then
            return
        end
        local delta = pointerPosition() - dragStart
        clampPosition(dragOriginX + delta.X, dragOriginY + delta.Y)
    end))

    track(UserInputService.InputEnded:Connect(function(input)
        if menu.Destroyed or not dragging then
            return
        end
        if isPress(input) then
            dragging = false
        end
    end))

    track(gui:GetPropertyChangedSignal("AbsoluteSize"):Connect(function()
        if not menu.Destroyed then
            menu:_reclamp()
        end
    end))

    track(frame:GetPropertyChangedSignal("AbsoluteSize"):Connect(function()
        if not menu.Destroyed then
            menu:_reclamp()
        end
    end))

    track(frame:GetPropertyChangedSignal("Visible"):Connect(function()
        local toggle = window._keybindMenuToggle
        if toggle and not toggle._destroyed then
            toggle:Set(frame.Visible, true)
        end
    end))

    collapseButton.MouseButton1Click:Connect(function()
        menu:ToggleCollapsed()
    end)
    collapseButton.MouseEnter:Connect(function()
        tween(chevron, { ImageColor3 = Theme.Text }, 0.12)
    end)
    collapseButton.MouseLeave:Connect(function()
        tween(chevron, { ImageColor3 = Theme.Muted }, 0.2)
    end)

    table.insert(Library._keybindMenus, menu)
    table.insert(Library._draggableLabels, menu)
    window.KeybindFrame = frame
    window.KeybindMenu = menu
    Library.KeybindFrame = frame
    Library.KeybindMenu = menu
    renderCollapse()
    menu:_syncEmpty()
    return menu
end

local function isShown(object, stopAt, point)
    local child = object
    while child and child ~= stopAt and child:IsA("GuiObject") do
        if not child.Visible then
            return false
        end
        local parent = child.Parent
        if parent and parent ~= stopAt and parent:IsA("GuiObject") and (parent.ClipsDescendants or parent:IsA("ScrollingFrame")) and not pointInside(point, parent) then
            return false
        end
        child = parent
    end
    return true
end

function Window:_refreshControls()
    local controls = {}
    for _, object in ipairs(self.Body:GetDescendants()) do
        if object:IsA("GuiButton") or object:IsA("TextBox") or object:GetAttribute("NoDrag") then
            table.insert(controls, object)
        end
    end
    self._controls = controls
    self._controlsDirty = false
end

function Window:_overControl(point)
    if self._dialog or self:_overPopout(point) then
        return true
    end
    local keybindMenu = self.KeybindMenu
    if keybindMenu and not keybindMenu.Destroyed and keybindMenu.Frame
        and keybindMenu.Frame.Visible and pointInside(point, keybindMenu.Frame) then
        return true
    end
    if self._controlsDirty then
        self:_refreshControls()
    end
    for _, object in ipairs(self._controls) do
        if object.Parent and pointInside(point, object) and isShown(object, self.Body, point) then
            return true
        end
    end
    return false
end

function Window:_tooltipCard()
    if self._tip then
        return self._tip
    end
    local holder = create("CanvasGroup", {
        Name = "Tooltip",
        Size = UDim2.fromOffset(0, 0),
        BackgroundTransparency = 1,
        GroupTransparency = 1,
        Visible = false,
        ZIndex = 60,
        Parent = self.Gui,
    })
    local tipScale = create("UIScale", { Parent = holder })
    local PAD = 4
    local panel = create("Frame", {
        Position = UDim2.fromOffset(PAD, PAD),
        Size = UDim2.fromOffset(0, 0),
        AutomaticSize = Enum.AutomaticSize.XY,
        BackgroundTransparency = 1,
        Parent = holder,
    })
    create("UIListLayout", {
        SortOrder = Enum.SortOrder.LayoutOrder,
        Padding = UDim.new(0, 2),
        Parent = panel,
    })
    local function outline(object)
        create("UIStroke", {
            Color = Color3.new(0, 0, 0),
            Transparency = 0.35,
            Thickness = 1,
            ApplyStrokeMode = Enum.ApplyStrokeMode.Contextual,
            Parent = object,
        })
    end
    local head = create("Frame", {
        Size = UDim2.fromOffset(0, 18),
        AutomaticSize = Enum.AutomaticSize.X,
        BackgroundTransparency = 1,
        LayoutOrder = 1,
        Parent = panel,
    })
    create("UIListLayout", {
        FillDirection = Enum.FillDirection.Horizontal,
        VerticalAlignment = Enum.VerticalAlignment.Center,
        SortOrder = Enum.SortOrder.LayoutOrder,
        Padding = UDim.new(0, 6),
        Parent = head,
    })
    local icon = create("ImageLabel", {
        Size = UDim2.fromOffset(14, 14),
        BackgroundTransparency = 1,
        ImageColor3 = Theme.Accent,
        ScaleType = Enum.ScaleType.Fit,
        LayoutOrder = 1,
        Parent = head,
    })
    local title = label({
        Size = UDim2.fromOffset(0, 18),
        AutomaticSize = Enum.AutomaticSize.X,
        TextSize = 13,
        FontFace = Fonts.Bold,
        TextTruncate = Enum.TextTruncate.None,
        LayoutOrder = 2,
        Parent = head,
    })
    outline(title)
    local body = label({
        Size = UDim2.fromOffset(0, 0),
        AutomaticSize = Enum.AutomaticSize.XY,
        TextSize = 12,
        FontFace = Fonts.Medium,
        TextWrapped = true,
        TextTruncate = Enum.TextTruncate.None,
        TextYAlignment = Enum.TextYAlignment.Top,
        LineHeight = 1.1,
        LayoutOrder = 2,
        Parent = panel,
    })
    outline(body)
    create("UISizeConstraint", { MaxSize = Vector2.new(240, math.huge), Parent = body })
    local function fit()
        local scale = math.max(tipScale.Scale, 0.01)
        local size = panel.AbsoluteSize / scale
        holder.Size = UDim2.fromOffset(size.X + PAD * 2, size.Y + PAD * 2)
    end
    panel:GetPropertyChangedSignal("AbsoluteSize"):Connect(fit)
    local tip = {
        Holder = holder,
        Scale = tipScale,
        Pad = PAD,
        Head = head,
        Icon = icon,
        Title = title,
        Body = body,
        Shown = false,
        Fit = fit,
    }
    self._tip = tip
    self:_listen("Render", function(deltaTime)
        local owner = self._tipOwner
        if not owner then
            return
        end
        local frame = owner._frame
        if owner._destroyed or not self.Open or self.Minimized or not frame or not frame.Parent
            or (owner._isShown and not owner:_isShown()) or not isShown(frame, self.Body, frame.AbsolutePosition + frame.AbsoluteSize / 2) then
            self:_hideTooltip()
            return
        end
        local pointer = pointerPosition() - self.Gui.AbsolutePosition
        local pad = tip.Pad * tipScale.Scale
        local size = holder.AbsoluteSize - Vector2.one * pad * 2
        local view = self.Gui.AbsoluteSize
        local x, y
        if tip.Touch then
            x, y = pointer.X - size.X / 2, pointer.Y - size.Y - 30
        else
            x, y = pointer.X + 14, pointer.Y + 20
            if x + size.X > view.X - 8 then
                x = pointer.X - size.X - 10
            end
            if y + size.Y > view.Y - 8 then
                y = pointer.Y - size.Y - 12
            end
        end
        local target = Vector2.new(
            math.clamp(x, 8, math.max(8, view.X - size.X - 8)),
            math.clamp(y, 8, math.max(8, view.Y - size.Y - 8))
        )
        local current = tip.Position
        if not current or tip.Snap then
            current = target + Vector2.new(0, 6)
            tip.Snap = false
        else
            current = current:Lerp(target, math.min(deltaTime * 22, 1))
        end
        tip.Position = current
        holder.Position = UDim2.fromOffset(math.floor(current.X - pad + 0.5), math.floor(current.Y - pad + 0.5))
    end)
    -- A press anywhere (a dropdown chip inside the card, a key) hides it.
    self:_listen("Began", function(input)
        if self._tipOwner and not tip.Touch and (input.UserInputType == Enum.UserInputType.MouseButton1
            or input.UserInputType == Enum.UserInputType.MouseButton2 or input.UserInputType == Enum.UserInputType.Keyboard) then
            self:_hideTooltip()
        end
    end)
    return tip
end

function Window:_showTooltip(element, touch)
    local value = element._tooltip
    local text, titleText, iconName
    if type(value) == "table" then
        text, titleText, iconName = value.Text or value.Content or value.Desc, value.Title or value.Name, value.Icon
    elseif value ~= nil and value ~= false then
        text = tostring(value)
    end
    if (text == nil or text == "") and (titleText == nil or titleText == "") then
        return
    end
    local tip = self:_tooltipCard()
    tip.Title.Text = titleText or ""
    tip.Title.Visible = titleText ~= nil and titleText ~= ""
    tip.Icon.Visible = iconName ~= nil
    if iconName ~= nil then
        applyIcon(tip.Icon, iconName)
    end
    tip.Head.Visible = tip.Title.Visible or iconName ~= nil
    tip.Body.Text = text or ""
    tip.Body.Visible = text ~= nil and text ~= ""
    tip.Fit()
    tip.Body.TextColor3 = Theme.Text
    tip.Scale.Scale = math.max(self.Scale.Scale, 0.75)
    tip.Touch = touch == true
    local wasShown = tip.Shown
    self._tipOwner = element
    tip.Shown = true
    tip.Generation = (tip.Generation or 0) + 1
    local holder = tip.Holder
    if not wasShown then
        tip.Snap = true
        holder.Visible = true
        holder.GroupTransparency = 1
        tip.Scale.Scale = tip.Scale.Scale * 0.96
    end
    tween(holder, { GroupTransparency = 0 }, 0.14, Enum.EasingStyle.Quad)
    tween(tip.Scale, { Scale = math.max(self.Scale.Scale, 0.75) }, 0.18, Enum.EasingStyle.Back)
end

function Window:_hideTooltip(element)
    local tip = self._tip
    if not tip or not tip.Shown or (element and self._tipOwner ~= element) then
        return
    end
    self._tipOwner = nil
    self._tipHiddenAt = os.clock()
    tip.Shown = false
    tip.Generation = (tip.Generation or 0) + 1
    local generation = tip.Generation
    tween(tip.Holder, { GroupTransparency = 1 }, 0.1, Enum.EasingStyle.Quad)
    task.delay(0.1, function()
        if tip.Generation == generation then
            tip.Holder.Visible = false
        end
    end)
end

function Window:_attachTooltip(element, frame)
    local hovering, token, pressAt = false, 0, nil
    local function begin(delay, touch)
        token += 1
        local mine = token
        task.delay(delay, function()
            if token ~= mine or not hovering or element._destroyed or self._destroyed then
                return
            end
            -- A finger that moved was scrolling, not holding.
            if touch and pressAt and (pointerPosition() - pressAt).Magnitude > 10 then
                return
            end
            self:_showTooltip(element, touch)
        end)
    end
    table.insert(element._listeners, (function()
        local connections = {
            frame.MouseEnter:Connect(function()
                if usingTouch() then
                    return
                end
                hovering = true
                local recent = os.clock() - (self._tipHiddenAt or 0) < 0.35 or self._tipOwner ~= nil
                begin(recent and 0 or 0.45, false)
            end),
            frame.MouseLeave:Connect(function()
                hovering = false
                token += 1
                self:_hideTooltip(element)
            end),
            frame.InputBegan:Connect(function(input)
                if input.UserInputType == Enum.UserInputType.Touch then
                    hovering = true
                    pressAt = pointerPosition()
                    begin(0.5, true)
                end
            end),
            frame.InputEnded:Connect(function(input)
                if input.UserInputType == Enum.UserInputType.Touch then
                    hovering = false
                    token += 1
                    self:_hideTooltip(element)
                end
            end),
        }
        return function()
            for _, connection in ipairs(connections) do
                connection:Disconnect()
            end
        end
    end)())
end

Library.DragStyles = { "Outline", "Brackets", "Ghost", "Frame", "Off" }

local function makeSkeleton(window)
    local root = window.Root
    local style = window.DragStyle or "Outline"
    local skeleton = create("Frame", {
        AnchorPoint = root.AnchorPoint,
        Position = root.Position,
        Size = UDim2.fromOffset(root.AbsoluteSize.X, root.AbsoluteSize.Y),
        BackgroundColor3 = style == "Ghost" and Theme.Background or Theme.Accent,
        BackgroundTransparency = 1,
        BorderSizePixel = 0,
        ZIndex = 40,
        Parent = window.Gui,
    })
    corner(skeleton, UDim.new(0, 10))
    local parts = {}
    local function part(object, shown)
        local hidden = {}
        for key in pairs(shown) do
            hidden[key] = 1
        end
        table.insert(parts, { Object = object, Shown = shown, Hidden = hidden })
    end
    local function brackets(length, inset)
        for _, spot in ipairs({ Vector2.new(0, 0), Vector2.new(1, 0), Vector2.new(0, 1), Vector2.new(1, 1) }) do
            local at = UDim2.new(spot.X, spot.X == 0 and inset or -inset, spot.Y, spot.Y == 0 and inset or -inset)
            for _, size in ipairs({ UDim2.fromOffset(length, 2), UDim2.fromOffset(2, length) }) do
                local bracket = create("Frame", {
                    AnchorPoint = spot,
                    Position = at,
                    Size = size,
                    BackgroundColor3 = Theme.Accent,
                    BackgroundTransparency = 1,
                    BorderSizePixel = 0,
                    Parent = skeleton,
                })
                corner(bracket, UDim.new(1, 0))
                part(bracket, { BackgroundTransparency = 0 })
            end
        end
    end
    if style == "Brackets" then
        -- Just the four corners of the window, a little longer.
        brackets(22, 0)
    elseif style == "Ghost" then
        -- A see-through copy of the window's panel.
        part(skeleton, { BackgroundTransparency = 0.35 })
        part(stroke(skeleton, Theme.Stroke, 1, 1), { Transparency = 0 })
    elseif style == "Frame" then
        -- A single quiet line, nothing else.
        part(stroke(skeleton, Theme.StrokeHover, 1, 1), { Transparency = 0 })
    else
        -- Outline: a faint accent wash, an outline and corner brackets.
        part(skeleton, { BackgroundTransparency = 0.92 })
        part(stroke(skeleton, Theme.Accent, 1, 1.5), { Transparency = 0.2 })
        brackets(16, 6)
    end
    local scale = create("UIScale", { Scale = 1.02, Parent = skeleton })
    for _, item in ipairs(parts) do
        tween(item.Object, item.Shown, 0.15, Enum.EasingStyle.Quad)
    end
    tween(scale, { Scale = 1 }, 0.25, Enum.EasingStyle.Quint)
    local function fade()
        for _, item in ipairs(parts) do
            tween(item.Object, item.Hidden, 0.2, Enum.EasingStyle.Quad)
        end
        task.delay(0.22, function()
            skeleton:Destroy()
        end)
    end
    return skeleton, fade
end

function Window:_enableDrag()
    local dragging, moved = false, false
    local grabOffset, pressPoint = Vector2.zero, Vector2.zero
    local target = nil
    local skeleton, fadeSkeleton = nil, nil

    local function centre()
        local root = self.Root
        return root.AbsolutePosition + root.AbsoluteSize * root.AnchorPoint - self.Gui.AbsolutePosition
    end

    local function dropSkeleton()
        if not skeleton then
            return
        end
        local spot = Vector2.new(skeleton.Position.X.Offset, skeleton.Position.Y.Offset)
        if self.KeepOnScreen then
            spot = self:_clampedCentre(spot)
        end
        if self._clampTween then
            self._clampTween:Cancel()
        end
        self._clampTween = tween(self.Root, { Position = UDim2.fromOffset(spot.X, spot.Y) }, 0.3, Enum.EasingStyle.Quint)
        fadeSkeleton()
        skeleton, fadeSkeleton = nil, nil
    end

    table.insert(self._connections, UserInputService.InputBegan:Connect(function(input)
        if not isPress(input) then
            return
        end
        if not self.Open or not self.Root.Visible then
            return
        end
        local point = pointerPosition()
        if self._resizeActive or (self._grip and pointInside(point, self._grip)) then
            return
        end
        if not pointInside(point, self.Body) or self:_overControl(point) then
            return
        end
        if self._clampTween then
            self._clampTween:Cancel()
            self._clampTween = nil
        end
        dragging, moved = true, false
        pressPoint = point
        grabOffset = point - centre()
    end))

    table.insert(self._connections, UserInputService.InputEnded:Connect(function(input)
        if not dragging then
            return
        end
        if isPress(input) then
            dragging = false
            target = nil
            if skeleton then
                dropSkeleton()
            else
                self:_clampToScreen()
            end
        end
    end))

    table.insert(self._frameSteps, function(deltaTime)
        if not dragging then
            return
        end
        local point = pointerPosition()
        if not moved and (point - pressPoint).Magnitude > 3 then
            moved = true
            if self.DragSkeleton then
                skeleton, fadeSkeleton = makeSkeleton(self)
            end
        end
        if not moved then
            return
        end
        -- Hidden or minimized mid-drag: land it where the outline is.
        if skeleton and (not self.Open or not self.Root.Visible) then
            dragging = false
            dropSkeleton()
            return
        end
        target = point - grabOffset
        local alpha = 1 - math.exp(-deltaTime * 45)
        if skeleton then
            local current = Vector2.new(skeleton.Position.X.Offset, skeleton.Position.Y.Offset)
            local step = current:Lerp(target, alpha)
            skeleton.Position = UDim2.fromOffset(step.X, step.Y)
        else
            local step = centre():Lerp(target, alpha)
            self.Root.Position = UDim2.fromOffset(step.X, step.Y)
        end
    end)
end

function Window:SetDragStyle(style)
    style = table.find(Library.DragStyles, style) and style or "Outline"
    self.DragStyle = style
    self.DragSkeleton = style ~= "Off"
    return style
end

function Window:GetDragStyle()
    return self.DragStyle
end

Library.IslandStyles = { "Show on Hover", "Always Show" }

function Window:SetIslandStyle(style)
    style = table.find(Library.IslandStyles, style) and style or "Show on Hover"
    self.IslandStyle = style
    if self._islandSettle then
        self._islandSettle()
    end
    return style
end

function Window:GetIslandStyle()
    return self.IslandStyle
end

function Window:SetDragSkeleton(enabled)
    if enabled == false then
        self:SetDragStyle("Off")
    elseif self.DragStyle == "Off" or not self.DragStyle then
        self:SetDragStyle("Outline")
    end
end

function Window:_sidebarResize(sidebar, width)
    local divider = sidebar:FindFirstChild("Divider")
    local want = width
    local function apply(value, remember)
        if remember ~= false then
            want = value
        end
        local room = self.Body.AbsoluteSize.X / self.Scale.Scale - 300
        value = math.floor(math.clamp(value, 150, math.max(math.min(300, room), 150)))
        self.SidebarWidth = value
        sidebar.Size = UDim2.new(0, value, 1, 0)
        self.Content.Position = UDim2.fromOffset(value + 1, 0)
        self.Content.Size = UDim2.new(1, -(value + 1), 1, 0)
    end
    self.SetSidebarWidth = function(_, value)
        apply(tonumber(value) or SIDEBAR_WIDTH)
    end
    apply(width)
    local grip = create("TextButton", {
        AnchorPoint = Vector2.new(1, 0),
        Position = UDim2.new(1, 0, 0, 0),
        Size = UDim2.new(0, 6, 1, 0),
        BackgroundTransparency = 1,
        Text = "",
        AutoButtonColor = false,
        ZIndex = 6,
        Parent = sidebar,
    })
    grip:SetAttribute("NoDrag", true)
    local dragging, startX, startWidth = false, 0, width
    local function light(on)
        if divider then
            tween(divider, { BackgroundColor3 = on and Theme.Accent or Theme.Stroke }, 0.15)
        end
    end
    grip.MouseEnter:Connect(function()
        light(true)
    end)
    grip.MouseLeave:Connect(function()
        if not dragging then
            light(false)
        end
    end)
    grip.InputBegan:Connect(function(input)
        if input.UserInputType == Enum.UserInputType.MouseButton1 or input.UserInputType == Enum.UserInputType.Touch then
            dragging, startX, startWidth = true, input.Position.X, self.SidebarWidth
            want = startWidth
            light(true)
        end
    end)
    self:_listen("Changed", function(input)
        if dragging and isMove(input) then
            apply(startWidth + (input.Position.X - startX) / self.Scale.Scale)
        end
    end)
    self:_listen("Ended", function(input)
        if dragging and (input.UserInputType == Enum.UserInputType.MouseButton1 or input.UserInputType == Enum.UserInputType.Touch) then
            dragging = false
            light(false)
        end
    end)
    -- Shrinking the window pulls an over-wide rail back in.
    self.Body:GetPropertyChangedSignal("AbsoluteSize"):Connect(function()
        if not dragging then
            apply(want, false)
        end
    end)
end

function Window:SetTransparent(enabled)
    self.Transparent = enabled == true
    local on = self.Transparent
    self._shadowRest = on and 0.85 or 0.6
    tween(self.Body, { BackgroundTransparency = on and 0.35 or 0 }, 0.25)
    local railAlpha = on and 0.5 or (self.Background and 0.45 or 0)
    tween(self.SidebarFill, { BackgroundTransparency = railAlpha }, 0.25)
    if self.Open and not self.Minimized and self.Root.Visible then
        tween(self.Shadow, { ImageTransparency = self._shadowRest }, 0.25)
    end
end

function Window:SetAlwaysOnTop(enabled)
    self.AlwaysOnTop = enabled == true
    Library._SetAlwaysOnTop(self.Gui, self.AlwaysOnTop)
end

local function orderedChildren(parent)
    local children = {}
    for _, child in ipairs(parent:GetChildren()) do
        if child:IsA("GuiObject") then
            table.insert(children, child)
        end
    end
    table.sort(children, function(a, b)
        return a.LayoutOrder < b.LayoutOrder
    end)
    return children
end

local function popIn(object, delay, force)
    if not object.Visible and not force then
        return
    end
    object.Visible = false
    task.delay(delay, function()
        if not object.Parent then
            return
        end
        local scaleObject = create("UIScale", { Scale = 0.94, Parent = object })
        object.Visible = true
        tween(scaleObject, { Scale = 1 }, 0.4, Enum.EasingStyle.Back)
        task.delay(0.4, function()
            scaleObject:Destroy()
        end)
    end)
end

function Window:_revealCards(tab, baseDelay)
    local container = tab.CurrentSubTab or tab
    if container._revealed then
        return
    end
    container._revealed = true
    local index = 0
    local function reveal(object)
        popIn(object, (baseDelay or 0) + index * 0.035)
        index += 1
    end
    local columns = container._columnSet
    for _, child in ipairs(orderedChildren(container.List)) do
        if columns and child == columns.Holder then
            local left, right = orderedChildren(columns.Left), orderedChildren(columns.Right)
            for row = 1, math.max(#left, #right) do
                if left[row] then
                    reveal(left[row])
                end
                if right[row] then
                    reveal(right[row])
                end
            end
        else
            reveal(child)
        end
    end
end

function Window:_playIntro(morph)
    if self._introDone or self._destroyed then
        return
    end
    self._introDone = true
    self:_refreshModal()
    self:_refreshCursor()
    self:_refreshBackdrop(true)
    task.delay(0.4, function()
        self:_refreshToggleButton()
    end)
    task.delay(1.5, function()
        if not self._destroyed and not self.MiniBar then
            self:_buildMiniBar()
        end
    end)
    local root, shadow, scale = self.Root, self.Shadow, self.Scale
    if self.CurrentTab then
        self:_revealCards(self.CurrentTab, morph and 0.15 or 0.25)
    end
    root.Visible = true
    if morph then
        scale.Scale = self._fitScale or 1
        root.Position = UDim2.fromScale(0.5, 0.5)
        self:_fade(0, 0.3)
        tween(self.BodyStroke, { Transparency = 0 }, 0.3)
        tween(shadow, { ImageTransparency = 0.6 }, 0.3)
    else
        root.Position = UDim2.new(0.5, 0, 0.5, 24)
        tween(scale, { Scale = self._fitScale or 1 }, 0.5, Enum.EasingStyle.Back)
        tween(root, { Position = UDim2.fromScale(0.5, 0.5) }, 0.5, Enum.EasingStyle.Quint)
        self:_fade(0, 0.35)
        tween(self.BodyStroke, { Transparency = 0 }, 0.35)
    end
    if not morph then
        tween(shadow, { ImageTransparency = 0.6 }, 0.5)
    end

    for index, tab in ipairs(self.Tabs) do
        popIn(tab._button, 0.1 + index * 0.05, true)
    end
    self.Indicator.Visible = false
    task.delay(0.15 + #self.Tabs * 0.05, function()
        if self.CurrentTab then
            self:_placeIndicator(self.CurrentTab)
        end
    end)
end

function Window:_showLoader(opts)
    local duration = opts.LoadingDuration or 1.6
    local gui = self.Gui
    local steps = opts.LoadingSteps or { "Preparing interface", "Loading icons", "Almost there" }
    local WIDTH, PAD, STEP = 340, 22, 24
    local listTop = 80
    local height = listTop + #steps * STEP + 18
    local loader = create("CanvasGroup", {
        AnchorPoint = Vector2.new(0.5, 0.5),
        Position = UDim2.new(0.5, 0, 0.5, 10),
        Size = UDim2.fromOffset(WIDTH, height),
        BackgroundColor3 = Theme.Background,
        BorderSizePixel = 0,
        GroupTransparency = 1,
        ZIndex = 10,
        Parent = gui,
    })
    local loaderCorner = corner(loader, UDim.new(0, 12))
    local loaderStroke = stroke(loader, Theme.Stroke, 1)
    local loaderScale = create("UIScale", { Scale = 0.97, Parent = loader })
    local loaderShadow = create("ImageLabel", {
        Position = UDim2.fromOffset(-25, -25),
        Size = UDim2.new(1, 50, 1, 50),
        BackgroundTransparency = 1,
        Image = Assets.Shadow,
        ImageColor3 = Color3.new(0, 0, 0),
        ImageTransparency = 1,
        ScaleType = Enum.ScaleType.Slice,
        SliceCenter = Rect.new(49, 49, 450, 450),
        ZIndex = 0,
        Parent = loader,
    })
    local content = create("CanvasGroup", {
        Size = UDim2.fromScale(1, 1),
        BackgroundTransparency = 1,
        Parent = loader,
    })

    if opts.Icon ~= false then
        local logo = create("ImageLabel", {
            Position = UDim2.fromOffset(PAD, PAD),
            Size = UDim2.fromOffset(30, 30),
            BackgroundTransparency = 1,
            ImageColor3 = Color3.new(1, 1, 1),
            ScaleType = Enum.ScaleType.Fit,
            Parent = content,
        })
        applyIcon(logo, opts.Icon or Assets.Logo, true)
    end
    local TEXT_X = opts.Icon ~= false and (PAD + 42) or PAD
    local titleLabel = label({
        Position = UDim2.fromOffset(TEXT_X, PAD - 2),
        Size = UDim2.new(1, -(TEXT_X + 70), 0, 18),
        Text = opts.LoadingTitle or opts.Title or "Aster UI",
        TextSize = 15,
        FontFace = Fonts.Bold,
        Parent = content,
    })
    local statusLabel = label({
        Position = UDim2.fromOffset(TEXT_X, PAD + 17),
        Size = UDim2.new(1, -(TEXT_X + 70), 0, 15),
        Text = opts.LoadingText or opts.Subtitle or "Loading",
        TextSize = 12,
        FontFace = Fonts.Regular,
        TextColor3 = Theme.Muted,
        Parent = content,
    })
    local percentLabel = label({
        AnchorPoint = Vector2.new(1, 0),
        Position = UDim2.new(1, -PAD, 0, PAD + 6),
        Size = UDim2.fromOffset(56, 16),
        Text = "0%",
        TextSize = 13,
        FontFace = Fonts.Medium,
        TextColor3 = Theme.Muted,
        TextXAlignment = Enum.TextXAlignment.Right,
        Parent = content,
    })
    create("Frame", {
        Position = UDim2.fromOffset(PAD, listTop - 14),
        Size = UDim2.new(1, -PAD * 2, 0, 1),
        BackgroundColor3 = Theme.Stroke,
        BorderSizePixel = 0,
        Parent = content,
    })

    local rows = {}
    for index, text in ipairs(steps) do
        local row = create("Frame", {
            Position = UDim2.fromOffset(PAD, listTop + (index - 1) * STEP),
            Size = UDim2.new(1, -PAD * 2, 0, STEP),
            BackgroundTransparency = 1,
            Parent = content,
        })
        local dot = create("Frame", {
            AnchorPoint = Vector2.new(0.5, 0.5),
            Position = UDim2.new(0, 7, 0.5, 0),
            Size = UDim2.fromOffset(6, 6),
            BackgroundColor3 = Theme.Surface3,
            BorderSizePixel = 0,
            Parent = row,
        })
        corner(dot, UDim.new(1, 0))
        local spinner = create("Frame", {
            AnchorPoint = Vector2.new(0.5, 0.5),
            Position = UDim2.new(0, 7, 0.5, 0),
            Size = UDim2.fromOffset(12, 12),
            BackgroundTransparency = 1,
            Visible = false,
            Parent = row,
        })
        corner(spinner, UDim.new(1, 0))
        local spinnerStroke = create("UIStroke", {
            Color = Theme.Accent,
            Thickness = 2,
            Parent = spinner,
        })
        create("UIGradient", {
            Transparency = NumberSequence.new({
                NumberSequenceKeypoint.new(0, 0),
                NumberSequenceKeypoint.new(0.5, 0),
                NumberSequenceKeypoint.new(0.501, 1),
                NumberSequenceKeypoint.new(1, 1),
            }),
            Parent = spinnerStroke,
        })
        local check = create("ImageLabel", {
            AnchorPoint = Vector2.new(0.5, 0.5),
            Position = UDim2.new(0, 7, 0.5, 0),
            Size = UDim2.fromOffset(14, 14),
            BackgroundTransparency = 1,
            ImageColor3 = Theme.Accent,
            ImageTransparency = 1,
            ScaleType = Enum.ScaleType.Fit,
            Parent = row,
        })
        applyIcon(check, "check")
        local stepLabel = label({
            Position = UDim2.fromOffset(24, 0),
            Size = UDim2.new(1, -24, 1, 0),
            Text = tostring(text),
            TextSize = 13,
            FontFace = Fonts.Regular,
            TextColor3 = Theme.Muted,
            TextTransparency = 1,
            Parent = row,
        })
        rows[index] = { Dot = dot, Spinner = spinner, Check = check, Label = stepLabel, State = "pending" }
        task.delay(0.15 + index * 0.06, function()
            if loader.Parent and rows[index].State == "pending" then
                tween(stepLabel, { TextTransparency = 0.45 }, 0.3)
            end
        end)
    end
    local function setStep(index, state)
        local row = rows[index]
        if not row or row.State == state then
            return
        end
        row.State = state
        row.Dot.Visible = state == "pending"
        row.Spinner.Visible = state == "active"
        tween(row.Check, { ImageTransparency = state == "done" and 0 or 1 }, 0.2)
        tween(row.Label, {
            TextTransparency = state == "pending" and 0.45 or 0,
            TextColor3 = state == "active" and Theme.Text or Theme.Muted,
        }, 0.2)
    end

    local track = create("Frame", {
        AnchorPoint = Vector2.new(0, 1),
        Position = UDim2.fromScale(0, 1),
        Size = UDim2.new(1, 0, 0, 2),
        BackgroundColor3 = Theme.Surface3,
        BorderSizePixel = 0,
        Parent = content,
    })
    local fill = create("Frame", {
        Size = UDim2.fromScale(0, 1),
        BackgroundColor3 = Theme.Accent,
        BorderSizePixel = 0,
        Parent = track,
    })

    tween(loader, { GroupTransparency = 0, Position = UDim2.fromScale(0.5, 0.5) }, 0.45, Enum.EasingStyle.Quint)
    tween(loaderScale, { Scale = 1 }, 0.45, Enum.EasingStyle.Quint)
    tween(loaderShadow, { ImageTransparency = 0.55 }, 0.4)
    tween(fill, { Size = UDim2.fromScale(0.85, 1) }, duration * 0.8, Enum.EasingStyle.Quart)
    local percentStep
    percentStep = RunService.RenderStepped:Connect(function(deltaTime)
        if not loader.Parent then
            percentStep:Disconnect()
            return
        end
        percentLabel.Text = math.floor(fill.Size.X.Scale * 100 + 0.5) .. "%"
        for _, row in ipairs(rows) do
            if row.State == "active" then
                row.Spinner.Rotation = (row.Spinner.Rotation + deltaTime * 360) % 360
            end
        end
    end)

    task.spawn(loadLucide)

    for index in ipairs(steps) do
        task.delay(duration * (index - 1) / #steps, function()
            if not loader.Parent then
                return
            end
            if index > 1 then
                setStep(index - 1, "done")
            end
            setStep(index, "active")
        end)
    end
    local function completeSteps()
        for index in ipairs(rows) do
            setStep(index, "done")
        end
    end

    local function finish()
        completeSteps()
        tween(content, { GroupTransparency = 1 }, 0.18)

        local fit = self._fitScale or 1
        local target = self.Root.Size
        tween(loader, {
            Size = UDim2.fromOffset(target.X.Offset * fit, target.Y.Offset * fit),
            Position = UDim2.fromScale(0.5, 0.5),
        }, 0.5, Enum.EasingStyle.Quint)
        tween(loaderCorner, { CornerRadius = UDim.new(0, Library._radius(10)) }, 0.5, Enum.EasingStyle.Quint)
        tween(loaderScale, { Scale = 1 }, 0.5, Enum.EasingStyle.Quint)

        task.delay(0.28, function()
            self:_playIntro(true)
            tween(loader, { GroupTransparency = 1 }, 0.25)
            tween(loaderStroke, { Transparency = 1 }, 0.2)
            tween(loaderShadow, { ImageTransparency = 1 }, 0.2)
        end)
        task.delay(0.6, function()
            loader:Destroy()
        end)
    end

    local function hideBar()
        completeSteps()
        tween(content, { GroupTransparency = 1 }, 0.18)
    end

    local function showCard(info, onContinue)
        local WIDTH, PAD, MAX_BODY = 360, 24, 220
        local tone = info.Color or Theme.Accent
        local warnCard = create("CanvasGroup", {
            AnchorPoint = Vector2.new(0.5, 0),
            Position = UDim2.fromScale(0.5, 0),
            Size = UDim2.new(0, WIDTH, 1, 0),
            BackgroundTransparency = 1,
            GroupTransparency = 1,
            ZIndex = 5,
            Parent = loader,
        })
        local badge = create("Frame", {
            Position = UDim2.fromOffset(PAD, PAD),
            Size = UDim2.fromOffset(44, 44),
            BackgroundColor3 = tone,
            BackgroundTransparency = 0.86,
            BorderSizePixel = 0,
            Parent = warnCard,
        })
        corner(badge, UDim.new(0, 12))
        stroke(badge, tone, 1).Transparency = 0.6
        local badgeIcon = create("ImageLabel", {
            AnchorPoint = Vector2.new(0.5, 0.5),
            Position = UDim2.fromScale(0.5, 0.5),
            Size = UDim2.fromOffset(22, 22),
            BackgroundTransparency = 1,
            ImageColor3 = tone,
            ScaleType = Enum.ScaleType.Fit,
            Parent = badge,
        })
        if info.Icon ~= false then
            applyIcon(badgeIcon, info.Icon or "info")
        else
            badge.Visible = false
        end
        local headX = info.Icon ~= false and (PAD + 58) or PAD
        local headWidth = info.Icon ~= false and (PAD * 2 + 58) or (PAD * 2)
        label({
            Position = UDim2.fromOffset(headX, info.Subtitle and PAD + 3 or PAD + 12),
            Size = UDim2.new(1, -headWidth, 0, 20),
            Text = info.Title,
            TextSize = 17,
            Parent = warnCard,
        })
        if info.Subtitle then
            label({
                Position = UDim2.fromOffset(headX, PAD + 25),
                Size = UDim2.new(1, -headWidth, 0, 16),
                Text = tostring(info.Subtitle),
                TextSize = 13,
                TextColor3 = tone,
                Parent = warnCard,
            })
        end
        -- Long text scrolls past MAX_BODY instead of pushing the card off screen.
        local scroller = create("ScrollingFrame", {
            Position = UDim2.fromOffset(PAD, PAD + 60),
            Size = UDim2.new(1, -PAD * 2, 0, 16),
            BackgroundTransparency = 1,
            BorderSizePixel = 0,
            ScrollBarThickness = TOUCH and 4 or 3,
            ScrollBarImageColor3 = Theme.Accent,
            ScrollBarImageTransparency = 0.4,
            ScrollingDirection = Enum.ScrollingDirection.Y,
            CanvasSize = UDim2.new(),
            Parent = warnCard,
        })
        local body = label({
            Size = UDim2.new(1, -8, 0, 0),
            Text = tostring(info.Text),
            TextSize = 13,
            FontFace = Fonts.Regular,
            TextColor3 = Theme.Muted,
            TextWrapped = true,
            TextTruncate = Enum.TextTruncate.None,
            TextYAlignment = Enum.TextYAlignment.Top,
            Parent = scroller,
        })
        local row = create("Frame", {
            AnchorPoint = Vector2.new(0, 1),
            Position = UDim2.new(0, PAD, 1, -PAD + 4),
            Size = UDim2.new(1, -PAD * 2, 0, 34),
            BackgroundTransparency = 1,
            Parent = warnCard,
        })
        create("UIListLayout", {
            FillDirection = Enum.FillDirection.Horizontal,
            HorizontalAlignment = Enum.HorizontalAlignment.Right,
            SortOrder = Enum.SortOrder.LayoutOrder,
            Padding = UDim.new(0, 8),
            Parent = row,
        })

        local remember = false
        local rememberRow = nil
        if not info.Block and info.RememberText and UnsupportedSkip.Available() then
            local boxSize = TOUCH and 20 or 16
            rememberRow = create("TextButton", {
                AnchorPoint = Vector2.new(0, 1),
                Position = UDim2.new(0, PAD, 1, -PAD + 4 - 34 - 12),
                Size = UDim2.new(1, -PAD * 2, 0, TOUCH and 28 or 22),
                BackgroundTransparency = 1,
                Text = "",
                AutoButtonColor = false,
                Parent = warnCard,
            })
            local box = create("Frame", {
                AnchorPoint = Vector2.new(0, 0.5),
                Position = UDim2.fromScale(0, 0.5),
                Size = UDim2.fromOffset(boxSize, boxSize),
                BackgroundColor3 = Theme.Surface2,
                BorderSizePixel = 0,
                Parent = rememberRow,
            })
            corner(box, UDim.new(0, 4))
            local boxStroke = stroke(box, Theme.Stroke, 1)
            local check = create("ImageLabel", {
                AnchorPoint = Vector2.new(0.5, 0.5),
                Position = UDim2.fromScale(0.5, 0.5),
                Size = UDim2.fromOffset(boxSize - 4, boxSize - 4),
                BackgroundTransparency = 1,
                ImageColor3 = Theme.AccentDark,
                ImageTransparency = 1,
                ScaleType = Enum.ScaleType.Fit,
                Parent = box,
            })
            applyIcon(check, "check")
            local rememberLabel = label({
                Position = UDim2.fromOffset(boxSize + 8, 0),
                Size = UDim2.new(1, -(boxSize + 8), 1, 0),
                Text = info.RememberText,
                TextSize = 12,
                FontFace = Fonts.Regular,
                TextColor3 = Theme.Muted,
                Parent = rememberRow,
            })
            rememberRow.MouseEnter:Connect(function()
                tween(boxStroke, { Color = remember and Theme.Accent or Theme.StrokeHover }, 0.12)
                tween(rememberLabel, { TextColor3 = Theme.Text }, 0.12)
            end)
            rememberRow.MouseLeave:Connect(function()
                tween(boxStroke, { Color = remember and Theme.Accent or Theme.Stroke }, 0.2)
                tween(rememberLabel, { TextColor3 = remember and Theme.Text or Theme.Muted }, 0.2)
            end)
            rememberRow.MouseButton1Click:Connect(function()
                remember = not remember
                tween(box, { BackgroundColor3 = remember and Theme.Accent or Theme.Surface2 }, 0.15)
                tween(boxStroke, { Color = remember and Theme.Accent or Theme.Stroke }, 0.15)
                tween(check, { ImageTransparency = remember and 0 or 1 }, 0.15)
                tween(rememberLabel, { TextColor3 = remember and Theme.Text or Theme.Muted }, 0.15)
            end)
        end

        local chosen = false
        local function button(text, primary, order, callback)
            local frame = create("TextButton", {
                Size = UDim2.fromOffset(0, 34),
                AutomaticSize = Enum.AutomaticSize.X,
                BackgroundColor3 = primary and Theme.Accent or Theme.Surface2,
                BackgroundTransparency = primary and 0.12 or 0,
                BorderSizePixel = 0,
                Text = "",
                AutoButtonColor = false,
                LayoutOrder = order,
                Parent = row,
            })
            corner(frame, UDim.new(0, 7))
            local frameStroke = stroke(frame, primary and Theme.Accent or Theme.Stroke, 1)
            frameStroke.Transparency = primary and 0.4 or 0
            padding(frame, 14, 14)
            label({
                Size = UDim2.new(0, 0, 1, 0),
                AutomaticSize = Enum.AutomaticSize.X,
                Text = text,
                TextSize = 13,
                TextColor3 = primary and Theme.AccentDark or Theme.Text,
                TextXAlignment = Enum.TextXAlignment.Center,
                Parent = frame,
            })
            frame.MouseEnter:Connect(function()
                if primary then
                    tween(frame, { BackgroundTransparency = 0 }, 0.12)
                    tween(frameStroke, { Transparency = 0 }, 0.12)
                else
                    tween(frameStroke, { Color = Theme.StrokeHover }, 0.12)
                end
            end)
            frame.MouseLeave:Connect(function()
                if primary then
                    tween(frame, { BackgroundTransparency = 0.12 }, 0.2)
                    tween(frameStroke, { Transparency = 0.4 }, 0.2)
                else
                    tween(frameStroke, { Color = Theme.Stroke }, 0.2)
                end
            end)
            frame.MouseButton1Click:Connect(function()
                if chosen then
                    return
                end
                chosen = true
                callback()
            end)
        end
        if info.ExitText ~= false then
            button(info.ExitText or "Exit", info.Block, 1, function()
                if info.Callback then
                    task.spawn(info.Callback, false)
                end
                tween(loader, { GroupTransparency = 1, Position = UDim2.new(0.5, 0, 0.5, 12) }, 0.25, Enum.EasingStyle.Quint)
                tween(loaderShadow, { ImageTransparency = 1 }, 0.2)
                task.delay(0.25, function()
                    self:Destroy()
                end)
            end)
        end
        if not info.Block then
            button(info.ContinueText or "Continue", true, 2, function()
                if remember and info.Remember then
                    info.Remember()
                end
                if info.Callback then
                    task.spawn(info.Callback, true)
                end
                tween(warnCard, { GroupTransparency = 1 }, 0.15)
                task.delay(0.15, function()
                    warnCard:Destroy()
                    onContinue()
                end)
            end)
        end

        local laidOut = false
        local function measure()
            local ok, size = pcall(function()
                local params = Instance.new("GetTextBoundsParams")
                params.Text = body.Text
                params.Font = body.FontFace
                params.Size = body.TextSize
                params.Width = WIDTH - PAD * 2 - 8
                return game:GetService("TextService"):GetTextBoundsAsync(params)
            end)
            return ok and size and math.ceil(size.Y) + 2 or body.TextBounds.Y
        end
        local function fit(duration)
            local textHeight = math.max(measure(), 16)
            local bodyHeight = math.min(textHeight, MAX_BODY)
            body.Size = UDim2.new(1, -8, 0, textHeight)
            scroller.Size = UDim2.new(1, -PAD * 2, 0, bodyHeight)
            scroller.CanvasSize = UDim2.fromOffset(0, textHeight)
            local height = PAD + 60 + bodyHeight + 18 + 34 + PAD - 4
            if rememberRow then
                height += rememberRow.Size.Y.Offset + 10
            end
            tween(loader, { Size = UDim2.fromOffset(WIDTH, height) }, duration, Enum.EasingStyle.Quint)
        end
        body:GetPropertyChangedSignal("TextBounds"):Connect(function()
            if laidOut and loader.Parent and warnCard.Parent then
                fit(0.2)
            end
        end)
        task.delay(0.15, function()
            if not loader.Parent then
                return
            end
            laidOut = true
            fit(0.35)
            task.delay(0.12, function()
                tween(warnCard, { GroupTransparency = 0 }, 0.3)
                badge.Size = UDim2.fromOffset(34, 34)
                badge.Position = UDim2.fromOffset(PAD + 5, PAD + 5)
                tween(badge, { Size = UDim2.fromOffset(44, 44), Position = UDim2.fromOffset(PAD, PAD) }, 0.45, Enum.EasingStyle.Back)
            end)
        end)
    end

    local function runPrompts(queue, index)
        if not loader.Parent then
            return
        end
        local info = queue[index]
        if not info then
            finish()
            return
        end
        showCard(info, function()
            runPrompts(queue, index + 1)
        end)
    end

    task.delay(duration, function()
        tween(fill, { Size = UDim2.fromScale(1, 1) }, 0.25, Enum.EasingStyle.Quint)
        task.delay(0.25, function()
            if not loader.Parent then
                return
            end
            if opts._prompts then
                hideBar()
                runPrompts(opts._prompts, 1)
            else
                finish()
            end
        end)
    end)
end

function Window:_fitToScreen(instant)
    local viewport = self.Gui.AbsoluteSize
    if viewport.X == 0 or viewport.Y == 0 then
        return
    end
    local size = self.Root.Size
    local wanted = (self._uiScale or 1) * (self._adaptive ~= false and Library._adaptiveFactor(viewport) or 1)
    local scale = math.min(wanted, (viewport.X - 24) / math.max(size.X.Offset, 1), (viewport.Y - 24) / math.max(size.Y.Offset, 1))
    self._fitScale = math.max(scale, 0.45)
    if self._introDone and self.Open then
        if instant then
            self.Scale.Scale = self._fitScale
        else
            tween(self.Scale, { Scale = self._fitScale }, 0.2)
        end
    end
end

function Library._adaptiveFactor(viewport)
    if TOUCH then
        return 1
    end
    local factor = math.min(viewport.X / 1920, viewport.Y / 1020)
    if factor > 0.9 and factor < 1.15 then
        return 1
    end
    return math.clamp(math.floor(factor * 20 + 0.5) / 20, 0.85, 1.75)
end

function Window:SetAdaptiveSize(enabled)
    self._adaptive = enabled ~= false
    self:_fitToScreen()
    task.delay(0.22, function()
        if not self._destroyed then
            self:_clampToScreen()
        end
    end)
end

function Window:GetAdaptiveSize()
    return self._adaptive ~= false
end

-- UI scale: 0.6 to 1.5 on top of the automatic fit to small screens.
function Window:SetUIScale(value)
    value = math.clamp(tonumber(value) or 1, 0.6, 1.5)
    self.UIScale = value
    self._uiScale = value
    self:_fitToScreen()
    task.delay(0.22, function()
        if not self._destroyed then
            self:_clampToScreen()
        end
    end)
    Library._syncDraggableLabels()
end

function Window:GetUIScale()
    return self._uiScale or 1
end

Library.DensityModes = { Compact = 0.55, Default = 1, Comfortable = 1.45 }
Library.Density = "Default"

-- Small gaps (a groupbox's 2px rows) still move visibly between modes.
function Library._spaced(base, factor)
    if base <= 0 then
        return 0
    end
    return math.max(math.floor(base * factor + (factor - 1) * 4 + 0.5), 0)
end

function Library._space(object, base)
    local factor = Library.DensityModes[Library.Density] or 1
    if object:IsA("UIListLayout") or object:IsA("UIGridLayout") then
        object:SetAttribute("Space", base)
        object.Padding = UDim.new(0, Library._spaced(base, factor))
    elseif object:IsA("UIPadding") then
        -- base is { left, right, top, bottom }
        object:SetAttribute("SpaceL", base[1])
        object:SetAttribute("SpaceR", base[2])
        object:SetAttribute("SpaceT", base[3])
        object:SetAttribute("SpaceB", base[4])
        object.PaddingLeft = UDim.new(0, math.floor(base[1] * math.sqrt(factor) + 0.5))
        object.PaddingRight = UDim.new(0, math.floor(base[2] * math.sqrt(factor) + 0.5))
        object.PaddingTop = UDim.new(0, Library._spaced(base[3], factor))
        object.PaddingBottom = UDim.new(0, Library._spaced(base[4], factor))
    end
    return object
end

function Library:SetDensity(mode)
    if type(mode) == "string" then
        for name in pairs(Library.DensityModes) do
            if name:lower() == mode:lower() then
                mode = name
                break
            end
        end
    end
    if not Library.DensityModes[mode] then
        mode = "Default"
    end
    Library.Density = mode
    for _, window in ipairs(Library.Windows) do
        if window.Gui and window.Gui.Parent then
            for _, object in ipairs(window.Gui:GetDescendants()) do
                local base = object:GetAttribute("Space")
                if base then
                    Library._space(object, base)
                elseif object:GetAttribute("SpaceL") then
                    Library._space(object, {
                        object:GetAttribute("SpaceL"), object:GetAttribute("SpaceR"),
                        object:GetAttribute("SpaceT"), object:GetAttribute("SpaceB"),
                    })
                end
            end
        end
    end
    return mode
end

function Window:SetDensity(mode)
    return Library:SetDensity(mode)
end

function Window:GetDensity()
    return Library.Density
end

-- Nearest centre that keeps the whole window inside the viewport.
function Window:_clampedCentre(centre)
    local viewport = self.Gui.AbsoluteSize
    local half = self.Root.AbsoluteSize / 2
    return Vector2.new(
        math.clamp(centre.X, math.min(half.X, viewport.X / 2), math.max(viewport.X - half.X, viewport.X / 2)),
        math.clamp(centre.Y, math.min(half.Y, viewport.Y / 2), math.max(viewport.Y - half.Y, viewport.Y / 2))
    )
end

function Window:_clampToScreen()
    if not self.KeepOnScreen or self._resizeActive then
        return
    end
    local root = self.Root
    local centre = root.AbsolutePosition + root.AbsoluteSize / 2 - self.Gui.AbsolutePosition
    local clamped = self:_clampedCentre(centre)
    if (clamped - centre).Magnitude > 0.5 then
        self._clampTween = tween(root, { Position = UDim2.fromOffset(clamped.X, clamped.Y) }, 0.25, Enum.EasingStyle.Quint)
    end
end

function Window:_createOpenButton(opts)
    local gui = self.Gui
    local pill = create("TextButton", {
        AnchorPoint = Vector2.new(0.5, 0),
        Position = UDim2.new(0.5, 0, 0, 14),
        Size = UDim2.fromOffset(0, 40),
        AutomaticSize = Enum.AutomaticSize.X,
        BackgroundColor3 = Theme.Background,
        BorderSizePixel = 0,
        Text = "",
        AutoButtonColor = false,
        ZIndex = 30,
        Parent = gui,
    })
    corner(pill, UDim.new(1, 0))
    stroke(pill, Theme.Stroke)
    padding(pill, 12, 16)
    local openIcon = cleanIcon(opts.Icon)
    if openIcon == nil then
        openIcon = Assets.Logo
    end
    if openIcon ~= false then
        local icon = create("ImageLabel", {
            AnchorPoint = Vector2.new(0, 0.5),
            Position = UDim2.new(0, 0, 0.5, 0),
            Size = UDim2.fromOffset(20, 20),
            BackgroundTransparency = 1,
            ImageColor3 = Color3.new(1, 1, 1),
            ScaleType = Enum.ScaleType.Fit,
            ZIndex = 31,
            Parent = pill,
        })
        applyIcon(icon, openIcon, true)
    end
    label({
        Position = UDim2.fromOffset(openIcon ~= false and 28 or 0, 0),
        Size = UDim2.new(0, 0, 1, 0),
        AutomaticSize = Enum.AutomaticSize.X,
        Text = opts.Title or "Aster UI",
        TextSize = 13,
        TextTruncate = Enum.TextTruncate.None,
        ZIndex = 31,
        Parent = pill,
    })
    self.OpenButton = pill

    local dragging, moved = false, false
    local grab = Vector2.zero
    pill.InputBegan:Connect(function(input)
        if isPress(input) then
            dragging = true
            moved = false
            grab = pointerPosition() - pill.AbsolutePosition
        end
    end)
    table.insert(self._connections, UserInputService.InputChanged:Connect(function(input)
        if not dragging then
            return
        end
        if isMove(input) then
            local point = pointerPosition() - grab - gui.AbsolutePosition
            if (point - (pill.AbsolutePosition - gui.AbsolutePosition)).Magnitude > 3 then
                moved = true
            end
            pill.AnchorPoint = Vector2.new(0, 0)
            pill.Position = UDim2.fromOffset(
                math.clamp(point.X, 0, math.max(gui.AbsoluteSize.X - pill.AbsoluteSize.X, 0)),
                math.clamp(point.Y, 0, math.max(gui.AbsoluteSize.Y - pill.AbsoluteSize.Y, 0))
            )
        end
    end))
    table.insert(self._connections, UserInputService.InputEnded:Connect(function(input)
        if dragging and isPress(input) then
            dragging = false
            if not moved then
                self:Toggle()
            end
        end
    end))
end

function Window:_toggleButtonAllowed()
    return self._toggleEnabled and (TOUCH or self._togglePlatform == "Both")
end

function Window:_refreshToggleButton()
    local button = self.ToggleButton
    if not button then
        return
    end
    local shown = self._introDone and not self._destroyed and self:_toggleButtonAllowed()
    if shown and not button.Visible then
        button.Visible = true
        button.Size = UDim2.fromOffset(0, 0)
        tween(button, { Size = UDim2.fromOffset(self._toggleSize, self._toggleSize) }, 0.45, Enum.EasingStyle.Quint)
    elseif not shown then
        button.Visible = false
    end
    -- Folded (window minimized or hidden): the outline takes the accent.
    local folded = self.Minimized or not self.Open
    tween(self._toggleStroke, { Color = folded and Theme.Accent or Theme.Stroke, Transparency = folded and 0.3 or 0 }, 0.35)
    local icon = self._toggleIcon
    tween(icon, { Rotation = folded and 180 or 0 }, 0.5, Enum.EasingStyle.Quint)
    if not icon:GetAttribute("CustomIcon") then
        tween(icon, { ImageColor3 = folded and Theme.Text or Theme.Accent }, 0.35)
    end
end

function Window:_createToggleButton(opts)
    local gui = self.Gui
    local size = tonumber(opts.Size) or (TOUCH and 56 or 50)
    local iconSize = math.floor(size * 0.46)
    self._toggleEnabled = opts.Enabled ~= false
    self._togglePlatform = opts.Platform == "Both" and "Both" or "Mobile"
    self._toggleSize = size
    local button = create("TextButton", {
        AnchorPoint = Vector2.new(0.5, 0.5),
        Position = opts.Position or UDim2.new(0, 18 + size / 2, 0.5, 0),
        Size = UDim2.fromOffset(size, size),
        BackgroundColor3 = Theme.Background,
        BorderSizePixel = 0,
        Text = "",
        AutoButtonColor = false,
        ClipsDescendants = true,
        Visible = false,
        ZIndex = 30,
        Parent = gui,
    })
    corner(button, UDim.new(0, 12))
    local buttonStroke = stroke(button, Theme.Stroke)
    local icon = create("ImageLabel", {
        AnchorPoint = Vector2.new(0.5, 0.5),
        Position = UDim2.fromScale(0.5, 0.5),
        Size = UDim2.fromOffset(iconSize, iconSize),
        BackgroundTransparency = 1,
        ImageColor3 = Theme.Accent,
        ScaleType = Enum.ScaleType.Fit,
        ZIndex = 31,
        Parent = button,
    })
    local buttonScale = create("UIScale", { Parent = button })
    self.ToggleButton = button
    self._toggleStroke = buttonStroke
    self._toggleIcon = icon
    local toggleIcon = opts.Icon
    if toggleIcon == nil then
        toggleIcon = "layout-grid"
    end
    self:SetToggleButtonIcon(toggleIcon)

    local dragging, moved = false, false
    local grab = Vector2.zero
    button.InputBegan:Connect(function(input)
        if isPress(input) then
            dragging = true
            moved = false
            grab = pointerPosition() - button.AbsolutePosition
            tween(buttonScale, { Scale = 0.94 }, 0.18, Enum.EasingStyle.Quint)
        end
    end)
    table.insert(self._connections, UserInputService.InputChanged:Connect(function(input)
        if not dragging or not isMove(input) then
            return
        end
        local point = pointerPosition() - grab - gui.AbsolutePosition
        if (point - (button.AbsolutePosition - gui.AbsolutePosition)).Magnitude > 3 then
            moved = true
        end
        if moved then
            button.AnchorPoint = Vector2.zero
            button.Position = UDim2.fromOffset(
                math.clamp(point.X, 0, math.max(gui.AbsoluteSize.X - button.AbsoluteSize.X, 0)),
                math.clamp(point.Y, 0, math.max(gui.AbsoluteSize.Y - button.AbsoluteSize.Y, 0))
            )
        end
    end))
    table.insert(self._connections, UserInputService.InputEnded:Connect(function(input)
        if not dragging or not isPress(input) then
            return
        end
        dragging = false
        tween(buttonScale, { Scale = 1 }, 0.4, Enum.EasingStyle.Quint)
        if moved then
            return
        end
        ripple(button)
        if not self.Open then
            self:Toggle(true)
        elseif self.Minimized then
            self:Restore()
        else
            self:Minimize()
        end
    end))
end

function Window:SetToggleButton(enabled)
    self._toggleEnabled = enabled ~= false
    self:_refreshToggleButton()
end

function Window:SetToggleButtonPlatform(platform)
    self._togglePlatform = platform == "Both" and "Both" or "Mobile"
    self:_refreshToggleButton()
end

function Window:SetToggleButtonIcon(icon)
    local image = self._toggleIcon
    if not image then
        return
    end
    icon = cleanIcon(icon)
    image.Image = ""
    if icon ~= false then
        applyIcon(image, icon)
        if image.Image == "" then
            applyIcon(image, Assets.Logo)
        end
    end
    if not image:GetAttribute("CustomIcon") then
        tween(image, { ImageColor3 = (self.Minimized or not self.Open) and Theme.Text or Theme.Accent }, 0)
    end
end

function Window:_enableResize(minSize)
    local maxSize = self.MaxSize or Vector2.new(math.huge, math.huge)
    self._minSize = minSize
    local root = self.Root
    local grip = create("Frame", {
        AnchorPoint = Vector2.new(0.5, 0.5),
        Position = UDim2.new(1, 4, 1, 4),
        Size = UDim2.fromOffset(32, 32),
        BackgroundTransparency = 1,
        Active = true,
        ZIndex = 20,
        Parent = root,
    })
    self._grip = grip
    local gripArc = create("Frame", {
        AnchorPoint = Vector2.new(1, 1),
        Position = UDim2.fromOffset(12, 12),
        Size = UDim2.fromOffset(26, 26),
        BackgroundTransparency = 1,
        ZIndex = 20,
        Parent = grip,
    })
    corner(gripArc, UDim.new(0, 10))
    local gripStroke = create("UIStroke", {
        Color = Theme.Muted,
        Thickness = 2,
        Transparency = 0.55,
        Parent = gripArc,
    })
    create("UIGradient", {
        Rotation = 45,
        Transparency = NumberSequence.new({
            NumberSequenceKeypoint.new(0, 1),
            NumberSequenceKeypoint.new(0.55, 1),
            NumberSequenceKeypoint.new(0.85, 0),
            NumberSequenceKeypoint.new(1, 0),
        }),
        Parent = gripStroke,
    })
    local function lightGrip(on)
        tween(gripStroke, {
            Color = on and Theme.Accent or Theme.Muted,
            Transparency = on and 0 or 0.55,
        }, on and 0.15 or 0.3, Enum.EasingStyle.Quint)
    end

    local STIFFNESS = 20
    local resizing = false
    local startSize = Vector2.zero
    local startPointer = Vector2.zero
    local current = Vector2.zero
    local velocity = Vector2.zero
    local target = Vector2.zero
    local applied = Vector2.zero

    local function readSize()
        return Vector2.new(root.Size.X.Offset, root.Size.Y.Offset)
    end

    local function pin()
        if root.AnchorPoint == Vector2.zero then
            return
        end
        -- A clamp tween still writing centre coordinates would fight the new anchor.
        if self._clampTween then
            self._clampTween:Cancel()
            self._clampTween = nil
        end
        local topLeft = root.AbsolutePosition - self.Gui.AbsolutePosition
        root.AnchorPoint = Vector2.zero
        root.Position = UDim2.fromOffset(topLeft.X, topLeft.Y)
    end

    local function unpin()
        local topLeft = root.AbsolutePosition - self.Gui.AbsolutePosition
        local half = root.AbsoluteSize / 2
        root.AnchorPoint = Vector2.new(0.5, 0.5)
        root.Position = UDim2.fromOffset(topLeft.X + half.X, topLeft.Y + half.Y)
    end

    local function clampSize(size)
        return Vector2.new(
            math.floor(math.clamp(size.X, minSize.X, maxSize.X) + 0.5),
            math.floor(math.clamp(size.Y, minSize.Y, maxSize.Y) + 0.5)
        )
    end

    grip.InputBegan:Connect(function(input)
        if not isPress(input) or not self.Open then
            return
        end
        if not self._resizeActive then
            pin()
            current = readSize()
            velocity = Vector2.zero
            applied = current
        end
        self._resizeActive = true
        resizing = true
        startSize = current
        startPointer = pointerPosition()
        target = clampSize(startSize)
        lightGrip(true)
    end)
    grip.MouseEnter:Connect(function()
        if not resizing then
            lightGrip(true)
        end
    end)
    grip.MouseLeave:Connect(function()
        if not resizing then
            lightGrip(false)
        end
    end)
    table.insert(self._connections, UserInputService.InputEnded:Connect(function(input)
        if resizing and isPress(input) then
            resizing = false
            lightGrip(false)
        end
    end))

    table.insert(self._frameSteps, function(deltaTime)
        if not self._resizeActive then
            return
        end
        if resizing then
            local delta = (pointerPosition() - startPointer) / self.Scale.Scale
            target = clampSize(startSize + delta)
        end
        local dt = math.min(deltaTime, 1 / 30)
        local decay = math.exp(-STIFFNESS * dt)
        local offset = current - target
        local drift = (velocity + offset * STIFFNESS) * dt
        velocity = (velocity - drift * STIFFNESS) * decay
        current = target + (offset + drift) * decay

        local rounded = Vector2.new(math.floor(current.X + 0.5), math.floor(current.Y + 0.5))
        if rounded ~= applied then
            applied = rounded
            root.Size = UDim2.fromOffset(rounded.X, rounded.Y)
        end

        if not resizing and (current - target).Magnitude < 0.3 and velocity.Magnitude < 3 then
            current = target
            velocity = Vector2.zero
            applied = target
            root.Size = UDim2.fromOffset(target.X, target.Y)
            unpin()
            self._resizeActive = false
            self:_fitToScreen()
            self:_clampToScreen()
        end
    end)
end

-- The window's own size in pixels, before the UI scale and screen fit.
function Window:GetSize()
    return Vector2.new(self.Root.Size.X.Offset, self.Root.Size.Y.Offset)
end

function Window:SetSize(size, instant)
    if typeof(size) == "UDim2" then
        size = Vector2.new(size.X.Offset, size.Y.Offset)
    end
    if typeof(size) ~= "Vector2" or self._resizeActive then
        return
    end
    local minSize = self._minSize or Vector2.zero
    local maxSize = self.MaxSize or Vector2.new(math.huge, math.huge)
    size = Vector2.new(
        math.floor(math.clamp(size.X, minSize.X, maxSize.X) + 0.5),
        math.floor(math.clamp(size.Y, minSize.Y, maxSize.Y) + 0.5)
    )
    if size == self:GetSize() then
        return
    end
    local duration = (instant or not self.Root.Visible) and 0 or 0.3
    tween(self.Root, { Size = UDim2.fromOffset(size.X, size.Y) }, duration, Enum.EasingStyle.Quint)
    task.delay(duration + 0.02, function()
        if not self._destroyed then
            self:_fitToScreen()
            self:_clampToScreen()
        end
    end)
end

local CONFIG_VERSION = 1
local LEGACY_SHARE_PREFIX = "airflow:"

local function configPath(self, name)
    return self.ConfigFolder .. "/" .. name .. ".json"
end

local function fileApiAvailable()
    return type(writefile) == "function" and type(readfile) == "function" and type(isfile) == "function"
end

local function colorToHex(color)
    return string.format("%02x%02x%02x",
        math.floor(color.R * 255 + 0.5),
        math.floor(color.G * 255 + 0.5),
        math.floor(color.B * 255 + 0.5))
end

local function colorFromValue(value)
    if type(value) == "table" then
        if type(value.Hex) == "string" then
            value = value.Hex
        elseif type(value[1]) == "number" then
            -- Older configs stored { r, g, b } in 0-1.
            return Color3.new(value[1], value[2] or 0, value[3] or 0)
        end
    end
    if type(value) == "string" then
        local r, g, b = value:match("^%s*#?(%x%x)(%x%x)(%x%x)%s*$")
        if r then
            return Color3.fromRGB(tonumber(r, 16), tonumber(g, 16), tonumber(b, 16))
        end
    end
    return nil
end

local function serializeFlag(element)
    local kind = element._type
    local value = element:Get()
    if type(element._saveValue) == "function" then
        value = element:_saveValue()
    end
    if kind == "Keybind" then
        return { Type = kind, Value = value and value.Name or nil }
    elseif kind == "ColorPicker" then
        return { Type = kind, Value = typeof(value) == "Color3" and { Hex = colorToHex(value) } or nil }
    end
    return { Type = kind, Value = value }
end

local function deserializeFlag(element, entry, silent)
    local kind = element._type
    local value = entry.Value
    if kind == "Keybind" then
        element:Set(Keybinds.Resolve(value), silent)
    elseif kind == "ColorPicker" then
        local color = colorFromValue(value)
        if color then
            element:Set(color, silent)
        end
    elseif kind == "Dropdown" then
        -- A dropdown saved with nothing picked has no Value at all.
        element:Set(value, silent)
    elseif kind == "Toggle" then
        if type(value) == "boolean" then
            element:Set(value, silent)
        end
    elseif kind == "Slider" or kind == "Stepper" or kind == "Progress" then
        local number = tonumber(value)
        if number then
            element:Set(number, silent)
        end
    elseif value ~= nil then
        element:Set(value, silent)
    end
end

local function entryMatches(element, entry)
    return type(entry) == "table" and (entry.Type == nil or entry.Type == element._type)
end

local function collectFlags(self)
    local data = {}
    if self and self._pendingFlags then
        for flag, pending in pairs(self._pendingFlags) do
            data[flag] = pending.Entry
        end
    end
    for flag, element in pairs(Library.Flags) do
        if element._type and type(element.Get) == "function" then
            local ok, entry = pcall(serializeFlag, element)
            if ok then
                data[flag] = entry
            end
        end
    end
    return data
end

function Window:_applyFlags(data, silent)
    silent = silent == true
    self._pendingFlags = {}
    for flag, entry in pairs(data) do
        local element = Library.Flags[flag]
        if element and type(element.Set) == "function" then
            if entryMatches(element, entry) then
                pcall(deserializeFlag, element, entry, silent)
            end
        elseif type(entry) == "table" then
            self._pendingFlags[flag] = { Entry = entry, Silent = silent }
        end
    end
end

function Window:_flagCreated(flag, element)
    local ok, entry = pcall(serializeFlag, element)
    if ok then
        element._defaultEntry = entry
    end
    local pending = self._pendingFlags and self._pendingFlags[flag]
    if not pending then
        return
    end
    task.defer(function()
        if self._pendingFlags[flag] ~= pending or Library.Flags[flag] ~= element or element._destroyed then
            return
        end
        self._pendingFlags[flag] = nil
        if entryMatches(element, pending.Entry) then
            pcall(deserializeFlag, element, pending.Entry, pending.Silent)
        end
    end)
end

-- Anything listening for config changes (the config manager's status line).
function Window:_configChanged()
    for _, handler in ipairs(self._configListeners) do
        safeCall(handler)
    end
end

function Window:OnConfigChanged(handler)
    table.insert(self._configListeners, handler)
    return function()
        local index = table.find(self._configListeners, handler)
        if index then
            table.remove(self._configListeners, index)
        end
    end
end

local function validConfigName(name)
    return type(name) == "string" and name ~= "" and not name:find('[\\/:%*%?"<>|]')
end

local function encodeConfig(self, name, flags)
    return HttpService:JSONEncode({
        Folder = self.ConfigFolder,
        Name = name,
        Version = CONFIG_VERSION,
        Config = HttpService:JSONEncode(flags),
    })
end

local B64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
local B64_INDEX = {}
for index = 1, #B64 do
    B64_INDEX[B64:byte(index)] = index - 1
end

-- Only for reading the old "airflow:<base64>" share codes.
local function base64Decode(text)
    if #text % 4 ~= 0 then
        return nil
    end
    local out = {}
    for index = 1, #text, 4 do
        local n, pad = 0, 0
        for offset = 0, 3 do
            local byte = text:byte(index + offset)
            local value = B64_INDEX[byte]
            if byte == 61 and index + 3 >= #text then
                pad += 1
                value = 0
            elseif value == nil or pad > 0 then
                return nil
            end
            n = n * 64 + value
        end
        if pad > 2 then
            return nil
        end
        local chunk = string.char(bit32.extract(n, 16, 8), bit32.extract(n, 8, 8), bit32.extract(n, 0, 8))
        table.insert(out, chunk:sub(1, 3 - pad))
    end
    return table.concat(out)
end

local function decodeConfig(text)
    text = tostring(text or ""):match("^%s*(.-)%s*$")
    if text:sub(1, #LEGACY_SHARE_PREFIX) == LEGACY_SHARE_PREFIX then
        text = base64Decode((text:sub(#LEGACY_SHARE_PREFIX + 1):gsub("%s", "")))
        if not text then
            return nil, "invalid config code"
        end
    end
    local ok, data = pcall(function()
        return HttpService:JSONDecode(text)
    end)
    if not ok or type(data) ~= "table" then
        return nil, "invalid config code"
    end
    local info = {}
    -- A bare flag table could have a flag named Config, but its entry carries a Type.
    if type(data.Config) == "string" or (type(data.Config) == "table" and data.Config.Type == nil) then
        info.Folder = type(data.Folder) == "string" and data.Folder or nil
        info.Name = type(data.Name) == "string" and data.Name or nil
        info.Version = tonumber(data.Version)
        local flags = data.Config
        if type(flags) == "string" then
            ok, flags = pcall(function()
                return HttpService:JSONDecode(data.Config)
            end)
            if not ok then
                return nil, "invalid config code"
            end
        end
        if type(flags) ~= "table" then
            return nil, "invalid config code"
        end
        data = flags
    end
    for flag, entry in pairs(data) do
        if type(flag) ~= "string" or type(entry) ~= "table" then
            return nil, "invalid config code"
        end
    end
    return data, info
end

local function writeConfig(self, name, data)
    if not validConfigName(name) then
        return false, "invalid config name"
    end
    if not fileApiAvailable() then
        return false, "file API unavailable"
    end
    local encoded, text = pcall(encodeConfig, self, name, data)
    if not encoded then
        return false, "could not encode config"
    end
    ensureFolder(self.ConfigFolder)
    return pcall(writefile, configPath(self, name), text)
end

local function readConfig(self, name)
    if not fileApiAvailable() then
        return nil, "file API unavailable"
    end
    if not validConfigName(name) then
        return nil, "invalid config name"
    end
    local path = configPath(self, name)
    if not isfile(path) then
        return nil, "no config named " .. tostring(name)
    end
    local ok, text = pcall(readfile, path)
    if not ok or type(text) ~= "string" then
        return nil, "could not read " .. name
    end
    local data, info = decodeConfig(text)
    if not data then
        return nil, "config is not valid JSON"
    end
    return data, info
end

function Window:ConfigExists(name)
    return validConfigName(name) and fileApiAvailable() and isfile(configPath(self, name)) or false
end

function Window:SaveConfig(name)
    name = name or self.ConfigName
    if not name then
        return false, "no config name"
    end
    local ok, err = writeConfig(self, name, collectFlags(self))
    if ok then
        self.ConfigName = name
    end
    return ok, err
end

function Window:LoadConfig(name, silent)
    name = name or self.ConfigName
    if not name then
        return false, "no config name"
    end
    local data, err = readConfig(self, name)
    if not data then
        return false, err
    end
    self:_applyFlags(data, silent)
    self.ConfigName = name
    self.LoadedConfig = name
    self:_configChanged()
    return true
end

function Window:DeleteConfig(name)
    if not fileApiAvailable() or type(delfile) ~= "function" then
        return false, "file API unavailable"
    end
    if not validConfigName(name) then
        return false, "invalid config name"
    end
    local path = configPath(self, name)
    if not isfile(path) then
        return false, "no config named " .. name
    end
    local ok, err = pcall(delfile, path)
    if not ok then
        return false, err
    end
    if self.LoadedConfig == name then
        self.LoadedConfig = nil
    end
    self:_configChanged()
    return true
end

-- Moves the file and anything pointing at it: the loaded name and both autoloads.
function Window:RenameConfig(name, newName)
    if not validConfigName(newName) then
        return false, "invalid config name"
    end
    if name == newName then
        return true
    end
    if self:ConfigExists(newName) then
        return false, newName .. " already exists"
    end
    local data, err = readConfig(self, name)
    if not data then
        return false, err
    end
    local ok
    ok, err = writeConfig(self, newName, data)
    if not ok then
        return false, err
    end
    if type(delfile) == "function" then
        pcall(delfile, configPath(self, name))
    end
    if self.LoadedConfig == name then
        self.LoadedConfig = newName
    end
    if self.ConfigName == name then
        self.ConfigName = newName
    end
    for _, scope in ipairs({ "Global", "Account" }) do
        if self:GetAutoload(scope) == name then
            self:SetAutoload(newName, scope)
        end
    end
    self:_configChanged()
    return true
end

function Window:ListConfigs()
    local names = {}
    if type(listfiles) ~= "function" or type(isfolder) ~= "function" or not isfolder(self.ConfigFolder) then
        return names
    end
    local ok, paths = pcall(listfiles, self.ConfigFolder)
    if not ok or type(paths) ~= "table" then
        return names
    end
    for _, path in ipairs(paths) do
        local name = path:match("([^/\\]+)%.json$")
        if name then
            table.insert(names, name)
        end
    end
    table.sort(names, function(a, b)
        return a:lower() < b:lower()
    end)
    return names
end

-- Puts every flagged element back to the value it was created with.
function Window:ResetConfig(silent)
    self._pendingFlags = {}
    for _, element in pairs(Library.Flags) do
        if element._defaultEntry and type(element.Set) == "function" then
            pcall(deserializeFlag, element, element._defaultEntry, silent == true)
        end
    end
    self:_configChanged()
    return true
end

local function wipeFolder(path)
    if type(isfolder) ~= "function" or not isfolder(path) then
        return true
    end
    if type(delfolder) == "function" and pcall(delfolder, path) and not isfolder(path) then
        return true
    end
    if type(listfiles) == "function" then
        local ok, entries = pcall(listfiles, path)
        for _, entry in ipairs(ok and entries or {}) do
            if isfolder(entry) then
                wipeFolder(entry)
            elseif type(delfile) == "function" then
                pcall(delfile, entry)
            end
        end
    end
    if type(delfolder) == "function" then
        pcall(delfolder, path)
    end
    return not isfolder(path)
end

function Window:ClearWorkspace()
    local ok = wipeFolder(self.ConfigFolder)
    self.LoadedConfig = nil
    for _, handler in ipairs(self._workspaceListeners or {}) do
        safeCall(handler)
    end
    self:_configChanged()
    return ok
end

-- Share codes are the same JSON a config file holds.

function Window:ExportConfig(name)
    local data, err
    if name then
        data, err = readConfig(self, name)
        if not data then
            return nil, err
        end
    else
        data = collectFlags(self)
        name = self.LoadedConfig or self.ConfigName
    end
    local ok, code = pcall(encodeConfig, self, name, data)
    if not ok then
        return nil, "could not encode config"
    end
    return code
end

-- Reads a code without applying it. Returns flags and { Folder, Name, Version }.
function Window:DecodeConfig(code)
    return decodeConfig(code)
end

function Window:ImportConfig(code, saveAs, force)
    local data, info = decodeConfig(code)
    if not data then
        return false, info
    end
    if not force and info.Folder and info.Folder ~= self.ConfigFolder then
        return false, "config is for " .. info.Folder
    end
    if saveAs == true then
        saveAs = info.Name
        if not validConfigName(saveAs) then
            return false, "config has no usable name"
        end
    end
    if saveAs then
        local ok, err = writeConfig(self, saveAs, data)
        if not ok then
            return false, err
        end
    end
    self:_applyFlags(data)
    if saveAs then
        self.ConfigName = saveAs
        self.LoadedConfig = saveAs
    end
    self:_configChanged()
    return true, nil, saveAs
end

local function readText(path)
    if not fileApiAvailable() or not isfile(path) then
        return nil
    end
    local ok, text = pcall(readfile, path)
    if ok and type(text) == "string" and text ~= "" then
        return text
    end
    return nil
end

local function removeFile(path)
    if fileApiAvailable() and type(delfile) == "function" and isfile(path) then
        pcall(delfile, path)
    end
end

local function settingsPath(self)
    return self.ConfigFolder .. "/configsettings.txt"
end

function Window:_readConfigSettings()
    local text = readText(settingsPath(self))
    if text then
        local ok, data = pcall(function()
            return HttpService:JSONDecode(text)
        end)
        if ok and type(data) == "table" then
            return data
        end
    end
    return {}
end

function Window:_writeConfigSettings(changes)
    if not fileApiAvailable() then
        return false, "file API unavailable"
    end
    local data = self:_readConfigSettings()
    for key, value in pairs(changes) do
        data[key] = value
    end
    ensureFolder(self.ConfigFolder)
    return pcall(writefile, settingsPath(self), HttpService:JSONEncode(data))
end

local function autoloadPath(self, scope)
    if scope == "Account" then
        return self.ConfigFolder .. "/autoload_" .. tostring(LocalPlayer and LocalPlayer.UserId or 0) .. ".txt"
    end
    return self.ConfigFolder .. "/autoload.txt"
end

function Window:GetAutoloadMode()
    return self:_readConfigSettings().AutoloadMode == "Account" and "Account" or "Global"
end

function Window:GetAutoload(scope)
    if scope then
        return readText(autoloadPath(self, scope))
    end
    return readText(autoloadPath(self, "Account")) or readText(autoloadPath(self, "Global"))
end

function Window:SetAutoload(name, scope)
    if not fileApiAvailable() then
        return false, "file API unavailable"
    end
    scope = scope or self:GetAutoloadMode()
    local ok, err = true, nil
    if name == nil or name == "" then
        removeFile(autoloadPath(self, scope))
        if scope == "Global" then
            removeFile(autoloadPath(self, "Account"))
        end
    else
        ensureFolder(self.ConfigFolder)
        ok, err = pcall(writefile, autoloadPath(self, scope), tostring(name))
        if ok and scope == "Global" then
            removeFile(autoloadPath(self, "Account"))
        end
    end
    self:_configChanged()
    return ok, err
end

-- Switching the mode moves the current autoload so only one stays active.
function Window:SetAutoloadMode(mode)
    mode = mode == "Account" and "Account" or "Global"
    if mode == self:GetAutoloadMode() then
        return true
    end
    local current = self:GetAutoload()
    local ok, err = self:_writeConfigSettings({ AutoloadMode = mode })
    if not ok then
        return false, err
    end
    removeFile(autoloadPath(self, mode == "Account" and "Global" or "Account"))
    if current then
        return self:SetAutoload(current, mode)
    end
    self:_configChanged()
    return true
end

function Window:LoadAutoload(silent)
    local name = self:GetAutoload()
    if not name then
        return false, "no autoload config"
    end
    return self:LoadConfig(name, silent)
end

-- Themes

Library._themeListeners = {}

local function toColor(value)
    if typeof(value) == "Color3" then
        return value
    elseif type(value) == "string" then
        local r, g, b = value:match("^%s*#?(%x%x)(%x%x)(%x%x)%s*$")
        if r then
            return Color3.fromRGB(tonumber(r, 16), tonumber(g, 16), tonumber(b, 16))
        end
    elseif type(value) == "table" then
        local r, g, b = value[1] or value.R, value[2] or value.G, value[3] or value.B
        if tonumber(r) and tonumber(g) and tonumber(b) then
            return Color3.fromRGB(r, g, b)
        end
    end
    return nil
end

local function hexOf(color)
    return string.format("#%02X%02X%02X",
        math.floor(color.R * 255 + 0.5),
        math.floor(color.G * 255 + 0.5),
        math.floor(color.B * 255 + 0.5))
end

Library._toneTags = {}
for _, name in ipairs(THEME_KEYS) do
    Library._toneTags[string.lower(name)] = name
end

-- A theme key, a Color3, "#rrggbb" or { r, g, b } as a Color3.
function Library._color(value)
    if type(value) == "string" then
        local key = Library._toneTags[string.lower(value)]
        if key then
            return Theme[key]
        end
    end
    return toColor(value)
end

function Library._rich(text)
    text = tostring(text == nil and "" or text)
    if not string.find(text, "<", 1, true) then
        return text
    end
    return (string.gsub(text, "<(/?)(%a+%d*)>", function(slash, name)
        local key = Library._toneTags[string.lower(name)]
        if not key then
            return nil
        end
        if slash == "/" then
            return "</font>"
        end
        return '<font color="' .. hexOf(Theme[key]) .. '">'
    end))
end

-- Library.Colorize("12 ms", "Success") or Library:Colorize(text, Color3).
function Library.Colorize(...)
    local args = { ... }
    if args[1] == Library then
        table.remove(args, 1)
    end
    local text, color = tostring(args[1] == nil and "" or args[1]), args[2]
    local key = type(color) == "string" and Library._toneTags[string.lower(color)]
    if key then
        return "<" .. key .. ">" .. text .. "</" .. key .. ">"
    end
    local resolved = toColor(color)
    if not resolved then
        return text
    end
    return '<font color="' .. hexOf(resolved) .. '">' .. text .. "</font>"
end

function Library:SetCornerRadius(pixels, instant)
    pixels = math.clamp(math.floor((tonumber(pixels) or 10) + 0.5), 0, 20)
    Library.Roundness = pixels / 10
    for object, base in pairs(Library._cornerBases) do
        if not object.Parent then
            Library._cornerBases[object] = nil
        else
            local radius = UDim.new(0, math.floor(base * Library.Roundness + 0.5))
            if instant then
                object.CornerRadius = radius
            else
                tween(object, { CornerRadius = radius }, 0.25, Enum.EasingStyle.Quint)
            end
        end
    end
    return pixels
end

function Library:GetCornerRadius()
    return math.floor(Library.Roundness * 10 + 0.5)
end

function Library:SetTheme(theme, instant)
    if type(theme) == "string" then
        local found = Library.ThemePresets[theme]
        if not found then
            return false
        end
        Library.ThemeName = theme
        theme = found
    elseif type(theme) ~= "table" then
        return false
    end
    local changed = false
    for _, name in ipairs(THEME_KEYS) do
        local color = toColor(theme[name])
        if color and color ~= Theme[name] then
            Theme[name] = color
            changed = true
        end
    end
    if not changed then
        return true
    end
    rebuildThemeLookup()
    sweepBindings()
    driveTheme(instant and 0 or 0.3)
    for owner, fn in pairs(themeHooks) do
        if owner.Parent then
            pcall(fn)
        end
    end
    for _, fn in ipairs(Library._themeListeners) do
        pcall(fn)
    end
    return true
end

function Library:GetTheme()
    local copy = {}
    for _, name in ipairs(THEME_KEYS) do
        copy[name] = Theme[name]
    end
    return copy
end

function Library:SetDefaultTheme(theme)
    Library.DefaultTheme = theme
    if theme == nil then
        return true
    end
    local live = false
    for _, window in ipairs(Library.Windows) do
        if not window._destroyed then
            if window:GetDefaultTheme() then
                return true
            end
            live = true
        end
    end
    return Library:SetTheme(theme, not live)
end

function Library:GetDefaultTheme()
    return Library.DefaultTheme
end

local function themeFolder(self)
    return self.ConfigFolder .. "/themes"
end

function Window:SaveTheme(name)
    if not fileApiAvailable() then
        return false, "file API unavailable"
    end
    if type(name) ~= "string" or name == "" then
        return false, "theme needs a name"
    end
    ensureFolder(self.ConfigFolder)
    ensureFolder(themeFolder(self))
    local data = {}
    for _, key in ipairs(THEME_KEYS) do
        data[key] = hexOf(Theme[key])
    end
    return pcall(function()
        writefile(themeFolder(self) .. "/" .. name .. ".json", HttpService:JSONEncode(data))
    end)
end

function Window:LoadTheme(name, instant)
    if Library.ThemePresets[name] then
        return Library:SetTheme(name, instant)
    end
    local text = readText(themeFolder(self) .. "/" .. tostring(name) .. ".json")
    if not text then
        return false, "no theme named " .. tostring(name)
    end
    local ok, data = pcall(function()
        return HttpService:JSONDecode(text)
    end)
    if not ok or type(data) ~= "table" then
        return false, "theme is not valid JSON"
    end
    Library.ThemeName = name
    return Library:SetTheme(data, instant)
end

function Window:DeleteTheme(name)
    if not fileApiAvailable() or type(delfile) ~= "function" then
        return false, "file API unavailable"
    end
    local path = themeFolder(self) .. "/" .. tostring(name) .. ".json"
    if not isfile(path) then
        return false, "no theme named " .. tostring(name)
    end
    delfile(path)
    if self:GetDefaultTheme() == name then
        self:SetDefaultTheme(nil)
    end
    return true
end

function Window:ListThemes()
    local names = {}
    if type(listfiles) ~= "function" or type(isfolder) ~= "function" or not isfolder(themeFolder(self)) then
        return names
    end
    for _, path in ipairs(listfiles(themeFolder(self))) do
        local name = path:match("([^/\\]+)%.json$")
        if name then
            table.insert(names, name)
        end
    end
    table.sort(names)
    return names
end

function Window:GetDefaultTheme()
    return readText(themeFolder(self) .. "/default.txt")
end

function Window:SetDefaultTheme(name)
    if not fileApiAvailable() then
        return false, "file API unavailable"
    end
    ensureFolder(self.ConfigFolder)
    ensureFolder(themeFolder(self))
    local path = themeFolder(self) .. "/default.txt"
    if name == nil or name == "" then
        if isfile(path) and type(delfile) == "function" then
            pcall(delfile, path)
        end
        return true
    end
    return pcall(writefile, path, tostring(name))
end

function Window:_applyDefaultTheme()
    local name = self:GetDefaultTheme()
    if name then
        local ok, loaded = pcall(self.LoadTheme, self, name, true)
        if ok and loaded then
            return
        end
    end
    if Library.DefaultTheme ~= nil then
        pcall(Library.SetTheme, Library, Library.DefaultTheme, true)
    end
end

-- Background images

-- Image assets anyone can use, from Fluent-modded's themes.
Library.BackgroundPresets = {
    ["Deep Violet"] = "rbxassetid://136310484943077",
    ["Blood Red"] = "rbxassetid://121343473918667",
    ["Cyanic"] = "rbxassetid://95656189244173",
    ["Amber Glow"] = "rbxassetid://107795771598485",
    ["Bloomings"] = "rbxassetid://133541508207801",
    ["Lavender Pink"] = "rbxassetid://126107479485287",
}
Library.BackgroundPresetOrder = { "Deep Violet", "Blood Red", "Cyanic", "Amber Glow", "Bloomings", "Lavender Pink" }

-- Table fields, not locals: the library chunk is at Luau's 200 local limit.
Library._imageExtensions = { png = true, jpg = true, jpeg = true, webp = true, gif = true, bmp = true }

function Window:_backgroundFolder()
    return self.ConfigFolder .. "/backgrounds"
end

function Window:_trimBackground(source)
    return (tostring(source or ""):match("^%s*(.-)%s*$"))
end

function Window:_resolveBackground(source)
    source = self:_trimBackground(source)
    local preset = Library.BackgroundPresets[source]
    if preset then
        return preset
    end
    if source:match("^%d+$") then
        return "rbxassetid://" .. source
    end
    if source:match("^rbxassetid://%d+") or source:match("^rbxasset://") or source:match("^rbxthumb://")
        or source:match("^https?://www%.roblox%.com/asset") then
        return source
    end
    local canLoad = fileApiAvailable() and typeof(getcustomasset) == "function"
    if source:match("^https?://") then
        if not canLoad then
            return nil, "web images need writefile and getcustomasset"
        end
        local clean = source:match("^[^?#]+") or source
        local ext = (clean:match("%.(%w+)$") or "png"):lower()
        if not Library._imageExtensions[ext] then
            ext = "png"
        end
        local key = (clean:gsub("^https?://", ""):gsub("[^%w]", "_")):sub(-60)
        local folder = self:_backgroundFolder() .. "/cache"
        local path = folder .. "/" .. key .. "_" .. #source .. "." .. ext
        if not isfile(path) then
            local ok, body = pcall(function()
                local request = (syn and syn.request) or http_request or request
                if request then
                    local response = request({ Url = source, Method = "GET" })
                    return response and response.Body
                end
                return game:HttpGet(source, true)
            end)
            if not ok or type(body) ~= "string" or #body < 128 then
                return nil, "could not download the image"
            end
            local head = body:sub(1, 64):lower()
            if head:find("<!doctype") or head:find("<html") then
                return nil, "that link is a web page, not an image"
            end
            ensureFolder(folder)
            if not pcall(writefile, path, body) then
                return nil, "could not save the image"
            end
        end
        local ok, asset = pcall(getcustomasset, path)
        if ok and type(asset) == "string" and asset ~= "" then
            return asset
        end
        pcall(delfile, path)
        return nil, "the downloaded file is not an image"
    end
    -- A file in the backgrounds folder, or any path in the workspace.
    if canLoad then
        for _, path in ipairs({ self:_backgroundFolder() .. "/" .. source, source }) do
            if isfile(path) then
                local ok, asset = pcall(getcustomasset, path)
                if ok and type(asset) == "string" and asset ~= "" then
                    return asset
                end
                return nil, "could not load " .. source
            end
        end
    end
    return nil, "no image called " .. source
end

function Window:SetBackground(source)
    self._backgroundGeneration += 1
    local generation = self._backgroundGeneration
    local image = self._backgroundImage
    source = source ~= false and self:_trimBackground(source) or ""
    if source == "" or source == "None" then
        self.Background = nil
        tween(image, { ImageTransparency = 1 }, 0.25)
        task.delay(0.25, function()
            if self._backgroundGeneration == generation then
                image.Visible = false
                image.Image = ""
            end
        end)
        self:SetTransparent(self.Transparent)
        return true
    end
    local asset, err = self:_resolveBackground(source)
    if self._backgroundGeneration ~= generation or self._destroyed then
        return false, "replaced by a newer background"
    end
    if not asset then
        return false, err
    end
    self.Background = source
    image.Image = asset
    image.Visible = true
    tween(image, { ImageTransparency = self.BackgroundTransparency }, 0.3)
    self:SetTransparent(self.Transparent)
    return true
end

function Window:GetBackground()
    return self.Background
end

-- 0 shows the image fully, 1 hides it behind the theme background colour.
function Window:SetBackgroundTransparency(value)
    self.BackgroundTransparency = math.clamp(tonumber(value) or 0.35, 0, 1)
    if self.Background then
        tween(self._backgroundImage, { ImageTransparency = self.BackgroundTransparency }, 0.15)
    end
end

-- Preset names, then the image files in <ConfigFolder>/backgrounds.
function Window:ListBackgrounds()
    local names = table.clone(Library.BackgroundPresetOrder)
    local folder = self:_backgroundFolder()
    if type(listfiles) == "function" and type(isfolder) == "function" and isfolder(folder) then
        local files = {}
        for _, path in ipairs(listfiles(folder)) do
            local name = path:match("([^/\]+)$")
            local ext = name and name:match("%.(%w+)$")
            if ext and Library._imageExtensions[ext:lower()] then
                table.insert(files, name)
            end
        end
        table.sort(files)
        for _, name in ipairs(files) do
            table.insert(names, name)
        end
    end
    return names
end

local function emptyState(parent, icon, text)
    local holder = create("Frame", {
        AnchorPoint = Vector2.new(0.5, 0.5),
        Position = UDim2.new(0.5, 0, 0.5, -10),
        Size = UDim2.fromOffset(200, 70),
        BackgroundTransparency = 1,
        Parent = parent,
    })
    local image
    if icon then
        image = create("ImageLabel", {
            AnchorPoint = Vector2.new(0.5, 0),
            Position = UDim2.new(0.5, 0, 0, 0),
            Size = UDim2.fromOffset(26, 26),
            BackgroundTransparency = 1,
            ImageColor3 = Theme.Muted,
            ImageTransparency = 0.15,
            ScaleType = Enum.ScaleType.Fit,
            Parent = holder,
        })
        applyIcon(image, icon)
    end
    local caption = label({
        Position = UDim2.fromOffset(0, image and 36 or 27),
        Size = UDim2.new(1, 0, 0, 16),
        Text = text,
        TextSize = 13,
        FontFace = Fonts.Regular,
        TextColor3 = Theme.Muted,
        TextXAlignment = Enum.TextXAlignment.Center,
        Parent = holder,
    })
    return holder, caption, image
end

local function fadeSlideIn(group, restY)
    restY = restY or 0
    group.GroupTransparency = 1
    group.Position = UDim2.fromOffset(0, restY + 14)
    group.Visible = true
    tween(group, { GroupTransparency = 0, Position = UDim2.fromOffset(0, restY) }, 0.32, Enum.EasingStyle.Quint)
end

local function formatDuration(seconds)
    seconds = math.max(math.floor(seconds), 0)
    local days = math.floor(seconds / 86400)
    local hours = math.floor(seconds / 3600) % 24
    local minutes = math.floor(seconds / 60) % 60
    if days > 0 then
        return string.format("%dd %dh", days, hours)
    elseif hours > 0 then
        return string.format("%dh %dm", hours, minutes)
    elseif minutes > 0 then
        return string.format("%dm %ds", minutes, seconds % 60)
    end
    return string.format("%ds", seconds)
end

local function shortId(id)
    if type(id) ~= "string" or id == "" then
        return "Studio"
    end
    if #id > 16 then
        return id:sub(1, 8) .. "..." .. id:sub(-4)
    end
    return id
end

local function copyToClipboard(text)
    local setter = setclipboard or toclipboard or (Clipboard and Clipboard.set)
    if type(setter) ~= "function" then
        return false
    end
    return (pcall(setter, tostring(text)))
end

local function fetchServers(order)
    local url = string.format(
        "https://games.roblox.com/v1/games/%d/servers/Public?sortOrder=%s&limit=100&excludeFullGames=true",
        game.PlaceId,
        order
    )
    local ok, body = pcall(function()
        return game:HttpGet(url)
    end)
    if not ok or type(body) ~= "string" then
        return nil
    end
    local decoded, data = pcall(function()
        return HttpService:JSONDecode(body)
    end)
    if not decoded or type(data) ~= "table" or type(data.data) ~= "table" then
        return nil
    end
    return data.data
end

-- Small on/off pill used on the home card for the privacy switches.
local function miniSwitch(parent, initial, order, callback)
    local pill = create("TextButton", {
        Size = UDim2.fromOffset(30, 16),
        BackgroundColor3 = Theme.Surface3,
        BorderSizePixel = 0,
        Text = "",
        AutoButtonColor = false,
        LayoutOrder = order,
        Parent = parent,
    })
    corner(pill, UDim.new(1, 0))
    stroke(pill)
    local knob = create("Frame", {
        AnchorPoint = Vector2.new(0, 0.5),
        Position = UDim2.new(0, 2, 0.5, 0),
        Size = UDim2.fromOffset(12, 12),
        BackgroundColor3 = Theme.Muted,
        BorderSizePixel = 0,
        Parent = pill,
    })
    corner(knob, UDim.new(1, 0))
    local on = initial == true
    local function render(animate)
        local duration = animate and 0.22 or 0
        tween(pill, { BackgroundColor3 = on and Theme.Accent or Theme.Surface3 }, duration)
        tween(knob, {
            Position = on and UDim2.new(0, 16, 0.5, 0) or UDim2.new(0, 2, 0.5, 0),
            BackgroundColor3 = on and Theme.AccentDark or Theme.Muted,
        }, duration, Enum.EasingStyle.Back)
    end
    pill.MouseButton1Click:Connect(function()
        on = not on
        render(true)
        safeCall(callback, on)
    end)
    render(false)
    return pill
end

local function softButton(parent, text, props, callback)
    local button = create("TextButton", {
        BackgroundColor3 = Theme.Surface3,
        BackgroundTransparency = 0.45,
        BorderSizePixel = 0,
        Text = "",
        AutoButtonColor = false,
        ClipsDescendants = true,
        Parent = parent,
    })
    for key, value in pairs(props) do
        button[key] = value
    end
    corner(button, UDim.new(0, 6))
    local buttonStroke = stroke(button)
    local text_ = label({
        Size = UDim2.fromScale(1, 1),
        Text = text,
        TextSize = 12,
        TextXAlignment = Enum.TextXAlignment.Center,
        Parent = button,
    })
    if button.AutomaticSize == Enum.AutomaticSize.X then
        text_.Size = UDim2.new(0, 0, 1, 0)
        text_.AutomaticSize = Enum.AutomaticSize.X
        text_.TextTruncate = Enum.TextTruncate.None
        padding(button, 14, 14)
    end
    button.MouseEnter:Connect(function()
        tween(button, { BackgroundTransparency = 0.15 }, 0.12)
        tween(buttonStroke, { Color = Theme.StrokeHover }, 0.12)
    end)
    button.MouseLeave:Connect(function()
        tween(button, { BackgroundTransparency = 0.45 }, 0.25)
        tween(buttonStroke, { Color = Theme.Stroke }, 0.25)
    end)
    button.MouseButton1Click:Connect(function()
        ripple(button)
        safeCall(callback)
    end)
    return button, text_
end

local function panelCard(parent, height, order)
    local frame = create("Frame", {
        Size = UDim2.new(1, 0, 0, height),
        BackgroundColor3 = Theme.Surface2,
        BorderSizePixel = 0,
        LayoutOrder = order,
        Parent = parent,
    })
    frame:SetAttribute("NoDrag", true)
    corner(frame, UDim.new(0, 10))
    stroke(frame)
    return frame
end

local STAT_TYPES = {
    Players = { "users", "Players" },
    Friends = { "user-check", "Friends" },
    Execs = { "zap", "Execs" },
    Session = { "timer", "Session" },
    Uptime = { "timer", "Session" },
    FPS = { "gauge", "FPS" },
    Ping = { "wifi", "Ping" },
    Executor = { "terminal", "Executor" },
    Game = { "gamepad-2", "Game" },
    Time = { "clock", "Time" },
    ServerAge = { "server", "Server age" },
    Memory = { "cpu", "Memory" },
}

function Library._healthColor(value, good, bad, lowerIsBetter)
    if type(value) ~= "number" then
        return Theme.Text
    end
    if lowerIsBetter then
        return value <= good and Theme.Success or value <= bad and Theme.Warning or Theme.Error
    end
    return value >= good and Theme.Success or value >= bad and Theme.Warning or Theme.Error
end

local function bumpExecutions(folder)
    if not fileApiAvailable() then
        return nil
    end
    local path = folder .. "/executions.txt"
    local count = 0
    pcall(function()
        ensureFolder(folder)
        if isfile(path) then
            count = tonumber(readfile(path)) or 0
        end
    end)
    count += 1
    pcall(writefile, path, tostring(count))
    return count
end

local function buildContainer(owner, parent, top, emptyIcon, emptyText)
    local list = create("ScrollingFrame", {
        Position = UDim2.fromOffset(0, top),
        Size = UDim2.new(1, 0, 1, -top),
        BackgroundTransparency = 1,
        BorderSizePixel = 0,
        ScrollBarThickness = 2,
        ScrollBarImageColor3 = Theme.Accent,
        ScrollBarImageTransparency = 0.5,
        ScrollingDirection = Enum.ScrollingDirection.Y,
        AutomaticCanvasSize = Enum.AutomaticSize.Y,
        CanvasSize = UDim2.new(),
        Parent = parent,
    })
    Library._space(padding(list, 24, 24, 2, 24), { 24, 24, 2, 24 })
    Library._space(create("UIListLayout", {
        SortOrder = Enum.SortOrder.LayoutOrder,
        Padding = UDim.new(0, 8),
        Parent = list,
    }), 8)
    owner.List = list
    owner._items = {}
    owner._groupboxes = {}
    owner._childCount = 0
    owner._emptyText = emptyText
    owner._empty, owner._emptyCaption = emptyState(parent, emptyIcon, emptyText)
    list.ChildAdded:Connect(function(child)
        if child:IsA("GuiObject") then
            owner._childCount += 1
            owner:_refreshEmpty()
        end
    end)
    list.ChildRemoved:Connect(function(child)
        if child:IsA("GuiObject") then
            owner._childCount = math.max(owner._childCount - 1, 0)
            owner:_refreshEmpty()
        end
    end)
    owner:_refreshEmpty()
    return list
end

function Tab:_refreshEmpty()
    local empty = self._empty
    if not empty then
        return
    end
    if self._subTabs then
        empty.Visible = false
    else
        empty.Visible = self._childCount == 0
    end
end

function Tab:_columns()
    if self._columnSet then
        return self._columnSet
    end
    local holder = create("Frame", {
        Name = "Columns",
        Size = UDim2.new(1, 0, 0, 0),
        AutomaticSize = Enum.AutomaticSize.Y,
        BackgroundTransparency = 1,
        LayoutOrder = 100000,
        Parent = self.List,
    })
    local layout = Library._space(create("UIListLayout", {
        FillDirection = Enum.FillDirection.Horizontal,
        SortOrder = Enum.SortOrder.LayoutOrder,
        Padding = UDim.new(0, 10),
        Parent = holder,
    }), 10)
    local function column(order)
        local frame = create("Frame", {
            Size = UDim2.new(0.5, -5, 0, 0),
            AutomaticSize = Enum.AutomaticSize.Y,
            BackgroundTransparency = 1,
            LayoutOrder = order,
            Parent = holder,
        })
        Library._space(create("UIListLayout", {
            SortOrder = Enum.SortOrder.LayoutOrder,
            Padding = UDim.new(0, 10),
            Parent = frame,
        }), 10)
        return frame
    end
    local set = { Holder = holder, Left = column(1), Right = column(2), Counts = { 0, 0 }, Stacked = false }
    local window = self.Window
    -- Narrow windows stack the right column under the left one.
    local function relayout()
        local width = holder.AbsoluteSize.X / window.Scale.Scale
        if width <= 0 then
            return
        end
        local stacked = width < STACK_BELOW
        local gap = layout.Padding.Offset
        if stacked == set.Stacked and gap == set.Gap then
            return
        end
        set.Stacked = stacked
        set.Gap = gap
        layout.FillDirection = stacked and Enum.FillDirection.Vertical or Enum.FillDirection.Horizontal
        local size = stacked and UDim2.new(1, 0, 0, 0) or UDim2.new(0.5, -gap / 2, 0, 0)
        set.Left.Size = size
        set.Right.Size = size
    end
    holder:GetPropertyChangedSignal("AbsoluteSize"):Connect(relayout)
    layout:GetPropertyChangedSignal("Padding"):Connect(relayout)
    task.defer(relayout)
    self._columnSet = set
    return set
end

local function buildGroupPanel(opts, window, parent, config)
    config = config or {}
    local box = create("Frame", {
        Size = config.Size or UDim2.new(1, 0, 0, 0),
        AutomaticSize = Enum.AutomaticSize.Y,
        BackgroundColor3 = Theme.Surface2,
        BorderSizePixel = 0,
        LayoutOrder = config.LayoutOrder or 1,
        Parent = parent,
    })
    box:SetAttribute("NoDrag", true)
    corner(box, UDim.new(0, 10))
    stroke(box)
    create("UIListLayout", {
        SortOrder = Enum.SortOrder.LayoutOrder,
        Parent = box,
    })

    local header = create("TextButton", {
        Size = UDim2.new(1, 0, 0, 40),
        BackgroundColor3 = Theme.Surface3,
        BorderSizePixel = 0,
        Text = "",
        AutoButtonColor = false,
        LayoutOrder = 1,
        Parent = box,
    })
    corner(header, UDim.new(0, 10))
    -- Squares the strip's lower corners so it meets the body flat.
    local headerFill = create("Frame", {
        AnchorPoint = Vector2.new(0, 1),
        Position = UDim2.fromScale(0, 1),
        Size = UDim2.new(1, 0, 0, 10),
        BackgroundColor3 = Theme.Surface3,
        BorderSizePixel = 0,
        Parent = header,
    })
    local titleX = 14
    if opts.Icon then
        local headerIcon = create("ImageLabel", {
            AnchorPoint = Vector2.new(0, 0.5),
            Position = UDim2.new(0, 14, 0.5, 0),
            Size = UDim2.fromOffset(14, 14),
            BackgroundTransparency = 1,
            ImageColor3 = Theme.Accent,
            ScaleType = Enum.ScaleType.Fit,
            ZIndex = 2,
            Parent = header,
        })
        applyIcon(headerIcon, opts.Icon)
        titleX = 37
    end
    local collapseButton = create("ImageLabel", {
        AnchorPoint = Vector2.new(1, 0.5),
        Position = UDim2.new(1, -14, 0.5, 0),
        Size = UDim2.fromOffset(14, 14),
        BackgroundTransparency = 1,
        ImageColor3 = Theme.Muted,
        ScaleType = Enum.ScaleType.Fit,
        ZIndex = 2,
        Parent = header,
    })
    applyIcon(collapseButton, "chevron-down")
    local canPop = config.PopOut == true and opts.PopOut ~= false
    local popButton, popIcon
    if canPop then
        popButton = create("TextButton", {
            AnchorPoint = Vector2.new(1, 0.5),
            Position = UDim2.new(1, -34, 0.5, 0),
            Size = UDim2.fromOffset(24, 24),
            BackgroundColor3 = Theme.Surface2,
            BackgroundTransparency = 1,
            BorderSizePixel = 0,
            Text = "",
            AutoButtonColor = false,
            ZIndex = 3,
            Parent = header,
        })
        corner(popButton, UDim.new(0, 6))
        popIcon = create("ImageLabel", {
            AnchorPoint = Vector2.new(0.5, 0.5),
            Position = UDim2.fromScale(0.5, 0.5),
            Size = UDim2.fromOffset(13, 13),
            BackgroundTransparency = 1,
            ImageColor3 = Theme.Muted,
            ImageTransparency = TOUCH and 0 or 0.45,
            ScaleType = Enum.ScaleType.Fit,
            ZIndex = 3,
            Parent = popButton,
        })
        applyIcon(popIcon, "picture-in-picture-2")
    end
    local title = label({
        Position = UDim2.fromOffset(titleX, 0),
        Size = UDim2.new(1, -(titleX + (canPop and 66 or 40)), 1, 0),
        Text = opts.Name or "Groupbox",
        TextSize = 13,
        FontFace = Fonts.Bold,
        ZIndex = 2,
        Parent = header,
    })

    local rule = create("Frame", {
        Size = UDim2.new(1, 0, 0, 1),
        BackgroundColor3 = Theme.Stroke,
        BorderSizePixel = 0,
        LayoutOrder = 2,
        Parent = box,
    })
    local body = create("Frame", {
        Size = UDim2.new(1, 0, 0, 0),
        AutomaticSize = Enum.AutomaticSize.Y,
        BackgroundTransparency = 1,
        ClipsDescendants = true,
        LayoutOrder = 3,
        Parent = box,
    })
    local inner = create("Frame", {
        Size = UDim2.new(1, 0, 0, 0),
        AutomaticSize = Enum.AutomaticSize.Y,
        BackgroundTransparency = 1,
        Parent = body,
    })
    Library._space(padding(inner, 0, 0, 6, 8), { 0, 0, 6, 8 })
    Library._space(create("UIListLayout", {
        SortOrder = Enum.SortOrder.LayoutOrder,
        Padding = UDim.new(0, 2),
        Parent = inner,
    }), 2)

    local group
    local collapsed = false
    local generation = 0
    local function setCollapsed(value, instant)
        value = value == true
        if value == collapsed then
            return
        end
        collapsed = value
        generation += 1
        local current = generation
        local duration = instant and 0 or 0.32
        if value then
            for _, element in ipairs(group._items) do
                if element._onHide then
                    element._onHide()
                end
                if element.Open and type(element.SetOpen) == "function" then
                    element:SetOpen(false)
                end
            end
        end
        window._controlsDirty = true
        local scale = window.Scale.Scale
        if value then
            body.AutomaticSize = Enum.AutomaticSize.None
            body.Size = UDim2.new(1, 0, 0, body.AbsoluteSize.Y / scale)
            tween(body, { Size = UDim2.new(1, 0, 0, 0) }, duration, Enum.EasingStyle.Quint)
        else
            tween(body, { Size = UDim2.new(1, 0, 0, inner.AbsoluteSize.Y / scale) }, duration, Enum.EasingStyle.Quint)
            local function settle()
                if generation == current and not collapsed then
                    body.AutomaticSize = Enum.AutomaticSize.Y
                    body.Size = UDim2.new(1, 0, 0, 0)
                end
            end
            if duration > 0 then
                task.delay(duration, settle)
            else
                settle()
            end
        end
        local motion = instant and 0 or 0.3
        if value then
            local function fold()
                if generation == current and collapsed then
                    rule.Visible = false
                    headerFill.Visible = false
                end
            end
            if duration > 0 then
                task.delay(duration, fold)
            else
                fold()
            end
        else
            rule.Visible = true
            headerFill.Visible = true
        end
        tween(collapseButton, { Rotation = value and -90 or 0 }, motion, Enum.EasingStyle.Quint)
    end

    local function hover(on)
        local duration = on and 0.15 or 0.25
        tween(collapseButton, { ImageColor3 = on and Theme.Text or Theme.Muted }, duration)
        if popIcon and not TOUCH then
            tween(popIcon, { ImageTransparency = on and 0 or 0.45 }, duration)
        end
    end
    header.MouseEnter:Connect(function()
        hover(true)
    end)
    header.MouseLeave:Connect(function()
        hover(false)
    end)
    local isTap = tapGuard(header, function()
        return box:FindFirstAncestorWhichIsA("ScrollingFrame")
    end)

    return {
        Box = box,
        Header = header,
        HeaderFill = headerFill,
        Title = title,
        CollapseButton = collapseButton,
        Rule = rule,
        Body = body,
        Inner = inner,
        PopButton = popButton,
        PopIcon = popIcon,
        IsTap = isTap,
        SetCollapsed = setCollapsed,
        IsCollapsed = function()
            return collapsed
        end,
        SetGroup = function(value)
            group = value
        end,
    }
end

function Tab:Groupbox(opts, icon)
    if self._groupbox then
        return self.Parent:Groupbox(opts, icon)
    end
    opts = normalize(opts, { Title = "Name" })
    if icon ~= nil and opts.Icon == nil then
        opts.Icon = cleanIcon(icon)
    end
    local window = self.Window
    local set = self:_columns()
    local side = opts.Side
    if side == "Left" or side == 1 then
        side = 1
    elseif side == "Right" or side == 2 then
        side = 2
    else
        side = set.Counts[1] <= set.Counts[2] and 1 or 2
    end
    set.Counts[side] += 1

    local shell = buildGroupPanel(opts, window, side == 1 and set.Left or set.Right, {
        LayoutOrder = set.Counts[side],
        PopOut = true,
    })
    local box = shell.Box
    local header = shell.Header
    local title = shell.Title
    local setCollapsed = shell.SetCollapsed
    local isTap = shell.IsTap
    local popButton, popIcon = shell.PopButton, shell.PopIcon
    local canPop = popButton ~= nil

    local group = setmetatable({
        Name = opts.Name or "Groupbox",
        Window = window,
        Parent = self,
        List = shell.Inner,
        Frame = box,
        _frame = box,
        _order = 0,
        _groupbox = true,
        _metrics = METRICS.Row,
        _items = {},
    }, Tab)
    shell.SetGroup(group)
    table.insert(self._groupboxes, group)

    local popped, popGeneration = false, 0
    local panel, panelScale, panelShadow, slot, stopPanel
    local dragStart, dragOrigin, dragMoved, suppressClick = nil, nil, false, false
    local animating = false

    local function layerScale()
        return math.max(window.Scale.Scale, 0.05)
    end
    local function toLayer(point)
        return (point - window._popLayer.AbsolutePosition) / layerScale()
    end
    -- Keeps a panel's top-centre spot on screen, header always reachable.
    local function clampSpot(spot, width, height)
        local view = window._popLayer.AbsoluteSize / layerScale()
        local margin = 8
        local x = math.clamp(spot.X, width / 2 + margin, math.max(view.X - width / 2 - margin, width / 2 + margin))
        local y = math.clamp(spot.Y, margin, math.max(view.Y - math.min(height, 120) - margin, margin))
        return Vector2.new(x, y)
    end
    local function closeInner()
        for _, element in ipairs(group._items) do
            if element._onHide then
                element._onHide()
            end
            if element.Open and type(element.SetOpen) == "function" then
                element:SetOpen(false)
            end
        end
    end
    local function setPopIcon(out)
        if popIcon then
            applyIcon(popIcon, out and "minimize-2" or "picture-in-picture-2")
        end
    end

    local function popOut()
        if popped or not canPop or not box.Parent or group._destroyed then
            return
        end
        -- A dock still in flight lands first, so the box is back in its column.
        if group._settleDock then
            group._settleDock()
        end
        local layer = window:_popoutLayer()
        popped = true
        group._popped = true
        popGeneration += 1
        local current = popGeneration
        closeInner()
        window:_closePopups()
        local scale = layerScale()
        local column = box.Parent
        local from = toLayer(box.AbsolutePosition)
        local width = box.AbsoluteSize.X / scale
        local height = box.AbsoluteSize.Y / scale

        slot = create("TextButton", {
            Size = UDim2.new(1, 0, 0, height),
            BackgroundColor3 = Theme.Surface2,
            BackgroundTransparency = 0.6,
            BorderSizePixel = 0,
            Text = "",
            AutoButtonColor = false,
            ClipsDescendants = true,
            LayoutOrder = box.LayoutOrder,
            Parent = column,
        })
        slot:SetAttribute("NoDrag", true)
        corner(slot, UDim.new(0, 10))
        stroke(slot, Theme.Stroke, 1).Transparency = 0.3
        local slotLabel = label({
            Size = UDim2.new(1, -24, 0, 40),
            Position = UDim2.fromOffset(12, 0),
            Text = Library._rich(group.Name) .. '<font transparency="0.4">  ·  popped out, click to dock</font>',
            TextSize = 12,
            FontFace = Fonts.Regular,
            TextColor3 = Theme.Muted,
            TextXAlignment = Enum.TextXAlignment.Center,
            RichText = true,
            TextTransparency = 1,
            Parent = slot,
        })
        local thisSlot = slot
        slot.MouseEnter:Connect(function()
            tween(thisSlot, { BackgroundTransparency = 0.35 }, 0.15)
        end)
        slot.MouseLeave:Connect(function()
            tween(thisSlot, { BackgroundTransparency = 0.6 }, 0.25)
        end)
        slot.MouseButton1Click:Connect(function()
            if slot == thisSlot then
                group:Dock()
            end
        end)
        tween(slot, { Size = UDim2.new(1, 0, 0, 40) }, 0.42, Enum.EasingStyle.Quint)
        tween(slotLabel, { TextTransparency = 0 }, 0.3)
        slot.Visible = box.Visible

        panel = create("Frame", {
            Name = "PopOut",
            AnchorPoint = Vector2.new(0.5, 0),
            Position = UDim2.fromOffset(from.X + width / 2, from.Y),
            Size = UDim2.fromOffset(width, height),
            BackgroundTransparency = 1,
            Parent = layer,
        })
        panel:SetAttribute("NoDrag", true)
        panelScale = create("UIScale", { Parent = panel })
        panelShadow = create("ImageLabel", {
            Position = UDim2.fromOffset(-24, -18),
            Size = UDim2.new(1, 48, 1, 44),
            BackgroundTransparency = 1,
            Image = Assets.Shadow,
            ImageColor3 = Color3.new(0, 0, 0),
            ImageTransparency = 1,
            ScaleType = Enum.ScaleType.Slice,
            SliceCenter = Rect.new(49, 49, 450, 450),
            ZIndex = 0,
            Parent = panel,
        })
        table.insert(window._popPanels, panel)
        box.Parent = panel
        window._controlsDirty = true
        setPopIcon(true)

        local spot = clampSpot(group._popSpot or Vector2.new(from.X + width / 2 + 22, from.Y - 14), width, height)
        animating = true
        panelScale.Scale = 0.97
        tween(panel, { Position = UDim2.fromOffset(spot.X, spot.Y) }, 0.5, Enum.EasingStyle.Quint)
        tween(panelScale, { Scale = 1 }, 0.55, Enum.EasingStyle.Back)
        tween(panelShadow, { ImageTransparency = 0.35 }, 0.4)
        task.delay(0.5, function()
            if popGeneration == current then
                animating = false
            end
        end)

        local thisPanel = panel
        stopPanel = window:_listen("Render", function()
            if panel ~= thisPanel or not thisPanel.Parent then
                return
            end
            local boxHeight = box.AbsoluteSize.Y / layerScale()
            if math.abs(thisPanel.Size.Y.Offset - boxHeight) > 0.5 then
                thisPanel.Size = UDim2.fromOffset(thisPanel.Size.X.Offset, boxHeight)
            end
            thisPanel.Visible = box.Visible
            if slot then
                slot.Visible = box.Visible
            end
            if not animating and not dragStart then
                local position = Vector2.new(thisPanel.Position.X.Offset, thisPanel.Position.Y.Offset)
                local clamped = clampSpot(position, thisPanel.Size.X.Offset, boxHeight)
                if (clamped - position).Magnitude > 0.5 then
                    thisPanel.Position = UDim2.fromOffset(clamped.X, clamped.Y)
                end
            end
        end)
    end

    local function dock(instant)
        if not popped then
            return
        end
        popped = false
        group._popped = false
        popGeneration += 1
        dragStart, dragMoved, suppressClick = nil, false, false
        closeInner()
        window:_closePopups()
        local oldPanel, oldSlot, oldStop, oldScale, oldShadow = panel, slot, stopPanel, panelScale, panelShadow
        panel, slot, stopPanel = nil, nil, nil
        setPopIcon(false)
        group._popSpot = Vector2.new(oldPanel.Position.X.Offset, oldPanel.Position.Y.Offset)
        local settled = false
        local function settle()
            if settled then
                return
            end
            settled = true
            if group._settleDock == settle then
                group._settleDock = nil
            end
            if oldStop then
                oldStop()
            end
            local index = table.find(window._popPanels, oldPanel)
            if index then
                table.remove(window._popPanels, index)
            end
            -- Back into the column, unless it was popped again meanwhile.
            if box.Parent == oldPanel then
                if oldSlot and oldSlot.Parent and not group._destroyed then
                    box.Parent = oldSlot.Parent
                    box.LayoutOrder = oldSlot.LayoutOrder
                end
            end
            if oldSlot then
                oldSlot:Destroy()
            end
            if box.Parent ~= oldPanel then
                oldPanel:Destroy()
            end
            animating = false
            window._controlsDirty = true
        end
        group._settleDock = settle
        local canFly = not instant and oldSlot and oldSlot.Parent and window.Root.Visible and box.Visible
            and oldSlot.AbsoluteSize.X > 0 and isShown(oldSlot, window.Body, oldSlot.AbsolutePosition + oldSlot.AbsoluteSize / 2)
        if not canFly then
            settle()
            return
        end
        animating = true
        local scale = layerScale()
        local height = box.AbsoluteSize.Y / scale
        local width = oldSlot.AbsoluteSize.X / scale
        tween(oldSlot, { Size = UDim2.new(1, 0, 0, height) }, 0.36, Enum.EasingStyle.Quint)
        local oldLabel = oldSlot:FindFirstChildWhichIsA("TextLabel")
        if oldLabel then
            tween(oldLabel, { TextTransparency = 1 }, 0.12)
        end
        -- The slot's top stays put as it grows, so its spot is the landing.
        local target = toLayer(oldSlot.AbsolutePosition)
        tween(oldPanel, {
            Position = UDim2.fromOffset(target.X + width / 2, target.Y),
            Size = UDim2.fromOffset(width, height),
        }, 0.36, Enum.EasingStyle.Quint)
        tween(oldScale, { Scale = 1 }, 0.2)
        tween(oldShadow, { ImageTransparency = 1 }, 0.3)
        task.delay(0.37, settle)
    end

    -- Dragging the floating panel by its header.
    header.InputBegan:Connect(function(input)
        if not popped or not isPress(input) or not panel then
            return
        end
        dragStart = Vector2.new(input.Position.X, input.Position.Y)
        dragOrigin = Vector2.new(panel.Position.X.Offset, panel.Position.Y.Offset)
        dragMoved = false
        suppressClick = false
    end)
    window:_listen("Changed", function(input)
        if not dragStart or not panel or not isMove(input) then
            return
        end
        local delta = Vector2.new(input.Position.X, input.Position.Y) - dragStart
        if not dragMoved then
            if delta.Magnitude < (TOUCH and 8 or 5) then
                return
            end
            dragMoved, suppressClick = true, true
            animating = false
            closeInner()
            window:_closePopups()
            tween(panelScale, { Scale = 1.025 }, 0.18, Enum.EasingStyle.Quint)
            tween(panelShadow, { ImageTransparency = 0.15 }, 0.18)
        end
        local spot = clampSpot(dragOrigin + delta / layerScale(), panel.Size.X.Offset, panel.Size.Y.Offset)
        panel.Position = UDim2.fromOffset(spot.X, spot.Y)
    end, group)
    window:_listen("Ended", function(input)
        if not dragStart or not isPress(input) then
            return
        end
        dragStart = nil
        if dragMoved and panel then
            dragMoved = false
            tween(panelScale, { Scale = 1 }, 0.4, Enum.EasingStyle.Back)
            tween(panelShadow, { ImageTransparency = 0.35 }, 0.3)
            group._popSpot = Vector2.new(panel.Position.X.Offset, panel.Position.Y.Offset)
        end
    end, group)
    if popButton then
        popButton.MouseEnter:Connect(function()
            tween(popButton, { BackgroundTransparency = 0 }, 0.15)
            tween(popIcon, { ImageColor3 = Theme.Text }, 0.15)
        end)
        popButton.MouseLeave:Connect(function()
            tween(popButton, { BackgroundTransparency = 1 }, 0.25)
            tween(popIcon, { ImageColor3 = Theme.Muted }, 0.25)
        end)
        popButton.MouseButton1Click:Connect(function()
            if popped then
                dock()
            else
                popOut()
            end
        end)
    end

    header.MouseButton1Click:Connect(function()
        if suppressClick then
            suppressClick = false
            return
        end
        if isTap() then
            setCollapsed(not shell.IsCollapsed())
        end
    end)

    function group:PopOut()
        popOut()
    end
    function group:Dock()
        dock()
    end
    function group:IsPoppedOut()
        return popped
    end
    function group:SetCollapsed(value)
        setCollapsed(value)
    end
    function group:Collapse()
        setCollapsed(true)
    end
    function group:Expand()
        setCollapsed(false)
    end
    function group:IsCollapsed()
        return shell.IsCollapsed()
    end
    function group:SetTitle(text)
        group.Name = tostring(text)
        title.Text = group.Name
    end
    group._userVisible = opts.Visible ~= false
    function group:IsVisible()
        return group._userVisible
    end
    function group:SetVisible(visible)
        visible = visible and true or false
        if visible == group._userVisible then
            return
        end
        group._userVisible = visible
        if not visible then
            for _, element in ipairs(group._items) do
                if element._onHide then
                    element._onHide()
                end
                if element.Open and type(element.SetOpen) == "function" then
                    element:SetOpen(false)
                end
            end
        end
        box.Visible = visible
        window._controlsDirty = true
    end
    if not group._userVisible then
        box.Visible = false
    end
    function group:Destroy()
        for index = #group._items, 1, -1 do
            local element = group._items[index]
            if type(element.Destroy) == "function" then
                element:Destroy()
            end
        end
        local owner = group.Parent
        local index = table.find(owner._groupboxes, group)
        if index then
            table.remove(owner._groupboxes, index)
        end
        set.Counts[side] = math.max(set.Counts[side] - 1, 0)
        dock(true)
        group._destroyed = true
        window._controlsDirty = true
        box:Destroy()
    end

    if opts.Collapsed then
        setCollapsed(true, true)
    end
    if opts.PoppedOut then
        task.defer(popOut)
    end
    return group
end

local function sideGroupbox(side)
    return function(self, opts, icon)
        opts = normalize(opts, { Title = "Name" })
        opts.Side = side
        return self:Groupbox(opts, icon)
    end
end

Tab.CreateGroupbox = Tab.Groupbox
Tab.AddGroupbox = Tab.Groupbox
Tab.AddLeftGroupbox = sideGroupbox("Left")
Tab.AddRightGroupbox = sideGroupbox("Right")

local function islandFilterTarget(value)
    if type(value) ~= "table" then
        return nil
    end
    if value._isSubTab then
        return "SubTab"
    end
    if not value._groupbox and value.Window and (value._page or value._button or getmetatable(value) == Tab) then
        return "Tab"
    end
    return nil
end

function Window:IslandGroupbox(opts, icon)
    opts = normalize(opts, { Title = "Name" })
    if icon ~= nil and opts.Icon == nil then
        opts.Icon = cleanIcon(icon)
    end
    local window = self
    local layer = self:_popoutLayer()
    local width = math.clamp(tonumber(opts.Width) or 300, 180, 900)
    local gap = tonumber(opts.Offset) or tonumber(opts.Gap) or 12

    local shell = buildGroupPanel(opts, window, layer, {
        Size = UDim2.fromOffset(width, 0),
        PopOut = false,
    })
    local box = shell.Box
    box.Name = "IslandGroupbox"
    box.AnchorPoint = Vector2.new(0, 0.5)
    box.Position = UDim2.fromScale(0.5, 0.5)
    box.Visible = false

    local group = setmetatable({
        Name = opts.Name or "Groupbox",
        Window = window,
        Parent = window,
        List = shell.Inner,
        Frame = box,
        _frame = box,
        _order = 0,
        _groupbox = true,
        _island = true,
        _metrics = METRICS.Row,
        _items = {},
        _listeners = {},
        _userVisible = opts.Visible ~= false,
    }, Tab)
    shell.SetGroup(group)
    window._islands = window._islands or {}
    table.insert(window._islands, group)

    local tabHandles, subHandles = {}, {}
    local tabNames, subNames, pageNames = {}, {}, {}
    local filtered = false

    local function resetFilters()
        table.clear(tabHandles)
        table.clear(subHandles)
        table.clear(tabNames)
        table.clear(subNames)
        table.clear(pageNames)
        filtered = false
    end

    local function addFilter(value, kind)
        if value == nil or value == false then
            return
        end
        if type(value) == "string" then
            local name = string.lower(value)
            if kind == "Tab" then
                tabNames[name] = true
            elseif kind == "SubTab" then
                subNames[name] = true
            else
                pageNames[name] = true
            end
            filtered = true
            return
        end
        if type(value) ~= "table" or next(value) == nil then
            return
        end
        local target = islandFilterTarget(value) or kind
        if target == "SubTab" then
            subHandles[value] = true
        else
            tabHandles[value] = true
        end
        filtered = true
    end

    local function addMany(value, kind)
        if value == nil then
            return
        end
        if type(value) == "table" and #value > 0 and not islandFilterTarget(value) then
            for _, entry in ipairs(value) do
                addFilter(entry, kind)
            end
        else
            addFilter(value, kind)
        end
    end

    local function readFilters(source)
        if source == nil then
            return
        end
        if type(source) ~= "table" then
            addFilter(source, "Page")
            return
        end
        local target = islandFilterTarget(source)
        if target then
            addFilter(source, target)
            return
        end
        local named = false
        local tabs = source.Tabs
        if tabs == nil then
            tabs = source.Tab
        end
        if tabs ~= nil then
            named = true
            addMany(tabs, "Tab")
        end
        local subs = source.SubTabs
        if subs == nil then
            subs = source.Subtabs
        end
        if subs == nil then
            subs = source.SubTab
        end
        if subs ~= nil then
            named = true
            addMany(subs, "SubTab")
        end
        local pages = source.Pages
        if pages == nil then
            pages = source.On
        end
        if pages ~= nil then
            named = true
            addMany(pages, "Page")
        end
        if not named then
            for _, entry in ipairs(source) do
                addFilter(entry, "Page")
            end
        end
    end

    local function matches()
        local tab = window.CurrentTab
        if not tab then
            return false
        end
        if not filtered then
            return true
        end
        local tabName = type(tab.Name) == "string" and string.lower(tab.Name) or ""
        if tabHandles[tab] or tabNames[tabName] or pageNames[tabName] then
            return true
        end
        local sub = tab.CurrentSubTab
        if sub then
            local subName = type(sub.Name) == "string" and string.lower(sub.Name) or ""
            if subHandles[sub] or subNames[subName] or pageNames[subName] then
                return true
            end
        end
        return false
    end

    local function closeInner()
        for _, element in ipairs(group._items) do
            if element._onHide then
                element._onHide()
            end
            if element.Open and type(element.SetOpen) == "function" then
                element:SetOpen(false)
            end
        end
    end

    local function active()
        return window.Open == true
            and window._introDone == true
            and window.Root.Visible == true
            and not window.Minimized
            and not window._destroyed
            and group._userVisible
            and box.Parent ~= nil
            and matches()
    end

    local function updateVisibility()
        if group._destroyed then
            return
        end
        local shown = active()
        if shown ~= box.Visible then
            if not shown then
                closeInner()
                if window._hideTooltip then
                    window:_hideTooltip()
                end
            end
            box.Visible = shown
        end
    end

    readFilters(opts)

    local lastSpot = Vector2.new(-math.huge, -math.huge)
    window:_listen("Render", function()
        updateVisibility()
        if not box.Visible then
            return
        end
        local scale = math.max(window.Scale.Scale, 0.05)
        local view = layer.AbsoluteSize / scale
        local rootLeft = (window.Root.AbsolutePosition.X - layer.AbsolutePosition.X) / scale
        local rootTop = (window.Root.AbsolutePosition.Y - layer.AbsolutePosition.Y) / scale
        local rootWidth = window.Root.AbsoluteSize.X / scale
        local rootHeight = window.Root.AbsoluteSize.Y / scale
        local height = box.AbsoluteSize.Y / scale
        local margin = 8
        local actualWidth = width
        if view.X > 0 then
            actualWidth = math.min(width, math.max(view.X - margin * 2, 180))
        end
        if math.abs(box.Size.X.Offset - actualWidth) > 0.5 then
            box.Size = UDim2.fromOffset(actualWidth, 0)
        end
        local x = math.clamp(rootLeft + rootWidth + gap, margin, math.max(view.X - actualWidth - margin, margin))
        local centreY = rootTop + rootHeight / 2
        local minY = margin + height / 2
        local maxY = view.Y - margin - height / 2
        local y = maxY >= minY and math.clamp(centreY, minY, maxY) or minY
        local spot = Vector2.new(math.floor(x + 0.5), math.floor(y + 0.5))
        if (spot - lastSpot).Magnitude > 0.5 then
            lastSpot = spot
            box.Position = UDim2.fromOffset(spot.X, spot.Y)
        end
    end, group)

    shell.Header.MouseButton1Click:Connect(function()
        if shell.IsTap() then
            shell.SetCollapsed(not shell.IsCollapsed())
        end
    end)

    function group:SetCollapsed(value)
        shell.SetCollapsed(value)
    end
    function group:Collapse()
        shell.SetCollapsed(true)
    end
    function group:Expand()
        shell.SetCollapsed(false)
    end
    function group:IsCollapsed()
        return shell.IsCollapsed()
    end
    function group:SetTitle(text)
        group.Name = tostring(text)
        shell.Title.Text = group.Name
    end
    function group:IsVisible()
        return group._userVisible
    end
    function group:SetVisible(visible)
        visible = visible and true or false
        if visible == group._userVisible then
            return
        end
        group._userVisible = visible
        updateVisibility()
    end
    function group:Refresh()
        updateVisibility()
    end
    function group:SetPages(source)
        resetFilters()
        readFilters(source or {})
        updateVisibility()
    end
    group.SetShowOn = group.SetPages
    group.SetTabs = group.SetPages
    function group:AddPage(value)
        addFilter(value, islandFilterTarget(value) or "Page")
        updateVisibility()
    end
    function group:SetWidth(value)
        width = math.clamp(tonumber(value) or width, 180, 900)
        box.Size = UDim2.fromOffset(width, 0)
    end
    function group:GetWidth()
        return width
    end
    function group:SetOffset(value)
        gap = tonumber(value) or gap
    end
    function group:IsIsland()
        return true
    end
    function group:Destroy()
        if group._destroyed then
            return
        end
        for index = #group._items, 1, -1 do
            local element = group._items[index]
            if type(element.Destroy) == "function" then
                element:Destroy()
            end
        end
        for _, disconnect in ipairs(group._listeners) do
            disconnect()
        end
        group._listeners = {}
        local list = window._islands
        local index = list and table.find(list, group)
        if index then
            table.remove(list, index)
        end
        group._destroyed = true
        window._controlsDirty = true
        box:Destroy()
    end

    if opts.Collapsed then
        shell.SetCollapsed(true, true)
    end
    return group
end

Window.CreateIslandGroupbox = Window.IslandGroupbox
Window.AddIslandGroupbox = Window.IslandGroupbox
Window.FloatingGroupbox = Window.IslandGroupbox
Window.CreateFloatingGroupbox = Window.IslandGroupbox

-- Button rows: equal-width buttons side by side.

function Tab:ButtonRow(opts)
    local specs = type(opts) == "table" and (opts.Buttons or opts) or {}
    local compact = metricsOf(self).Compact
    local boxHeight = TOUCH and 34 or 30
    local frame = card(self, "Frame", boxHeight + (compact and 4 or 14), {})
    local inset = compact and 14 or 7
    local holder = create("Frame", {
        Position = UDim2.fromOffset(inset, compact and 2 or 7),
        Size = UDim2.new(1, -inset * 2, 0, boxHeight),
        BackgroundTransparency = 1,
        Parent = frame,
    })
    local count = math.max(#specs, 1)
    local handle = { Buttons = {} }
    local names = {}
    for index, spec in ipairs(specs) do
        if type(spec) == "string" then
            spec = { Name = spec }
        end
        local text = spec.Name or spec.Title or "Button"
        table.insert(names, text)
        local button, text_ = softButton(holder, text, {
            Position = UDim2.new((index - 1) / count, (index - 1) * 6 / count, 0, 0),
            Size = UDim2.new(1 / count, -6 * (count - 1) / count, 1, 0),
        }, function()
            safeCall(spec.Callback)
        end)
        text_.TextSize = 13
        if spec.Style == "Primary" then
            tween(button, { BackgroundColor3 = Theme.Accent, BackgroundTransparency = 0.12 }, 0)
            tween(text_, { TextColor3 = Theme.AccentDark }, 0)
        elseif spec.Style == "Danger" then
            tween(text_, { TextColor3 = Theme.Error }, 0)
        end
        handle.Buttons[index] = { Button = button, Label = text_ }
    end
    function handle:SetText(index, text)
        local entry = handle.Buttons[index]
        if entry then
            entry.Label.Text = tostring(text)
        end
    end
    return finishElement(self, { Name = table.concat(names, " "), Visible = not (type(opts) == "table" and opts.Visible == false) }, handle, frame, "ButtonRow")
end

local function actionInput(tab, placeholder, buttonText, callback)
    local boxHeight = TOUCH and 34 or 30
    local frame = card(tab, "Frame", boxHeight + 4, {})
    local inset = metricsOf(tab).Compact and 14 or 7
    local box
    local button = buttonText and softButton(frame, buttonText, {
        AnchorPoint = Vector2.new(1, 0),
        Position = UDim2.new(1, -inset, 0, 2),
        Size = UDim2.fromOffset(0, boxHeight),
        AutomaticSize = Enum.AutomaticSize.X,
    }, function()
        safeCall(callback, box.Text)
    end)
    local holder = create("Frame", {
        Position = UDim2.fromOffset(inset, 2),
        Size = UDim2.new(1, -(inset * 2 + (button and 70 or 0)), 0, boxHeight),
        BackgroundColor3 = Theme.Surface,
        BorderSizePixel = 0,
        Parent = frame,
    })
    corner(holder, UDim.new(0, 6))
    local holderStroke = stroke(holder)
    box = create("TextBox", {
        Position = UDim2.fromOffset(8, 0),
        Size = UDim2.new(1, -16, 1, 0),
        BackgroundTransparency = 1,
        Text = "",
        PlaceholderText = placeholder,
        PlaceholderColor3 = Theme.Muted,
        TextColor3 = Theme.Text,
        TextSize = 13,
        FontFace = Fonts.Regular,
        TextXAlignment = Enum.TextXAlignment.Center,
        TextTruncate = Enum.TextTruncate.AtEnd,
        ClearTextOnFocus = false,
        Parent = holder,
    })
    box.Focused:Connect(function()
        tween(holderStroke, { Color = Theme.StrokeHover }, 0.15)
    end)
    box.FocusLost:Connect(function(enterPressed)
        tween(holderStroke, { Color = Theme.Stroke }, 0.2)
        if enterPressed and box.Text ~= "" then
            safeCall(callback, box.Text)
        end
    end)
    if button then
        local function fit()
            local width = button.AbsoluteSize.X / tab.Window.Scale.Scale
            holder.Size = UDim2.new(1, -(inset * 2 + width + 6), 0, boxHeight)
        end
        button:GetPropertyChangedSignal("AbsoluteSize"):Connect(fit)
        task.defer(fit)
    end
    return finishElement(tab, { Name = placeholder }, {
        Get = function()
            return box.Text
        end,
        Set = function(_, value)
            box.Text = tostring(value or "")
        end,
    }, frame, "ActionInput")
end

local function trim(text)
    return (tostring(text or ""):match("^%s*(.-)%s*$"))
end

-- Managers go in their own groupbox when added straight to a tab.
local function managerHost(tab, opts, name, icon)
    if tab._groupbox then
        return tab
    end
    local hostIcon = opts.Icon
    if hostIcon == nil then
        hostIcon = icon
    end
    local host = tab:Groupbox({ Name = opts.Name or name, Icon = hostIcon, Side = opts.Side })
    -- Library chrome, not a script feature: the feature list skips it.
    host._manager = true
    return host
end

function Tab:ConfigManager(opts)
    opts = normalize(opts, { Title = "Name" })
    local host = managerHost(self, opts, "Configs", "folder")
    local window = self.Window
    local manager = {}
    local list, status, modeList

    local function notify(ok, title, detail)
        window:Notify({ Title = title, Content = detail, Type = ok and "Success" or "Error", Duration = 3 })
    end

    local function refreshStatus()
        status:Set(("loaded: %s   |   autoload: %s"):format(window.LoadedConfig or "none", window:GetAutoload() or "none"))
    end

    local function pickedName()
        local name = list:Get()
        if not name then
            notify(false, "No config selected", "Pick one from the list first")
        end
        return name
    end

    local nameInput = actionInput(host, opts.Placeholder or "config name", nil, function(text)
        manager:Create(text)
    end)
    local names = window:ListConfigs()
    local initial = window.LoadedConfig or window:GetAutoload()
    list = host:Dropdown({
        Stacked = true,
        Options = names,
        Default = table.find(names, initial) and initial or nil,
        EmptyText = "--",
        NoneText = "--",
    })
    host:ButtonRow({
        { Name = "Create", Callback = function() manager:Create(nameInput:Get()) end },
        { Name = "Save", Callback = function() manager:Save() end },
    })
    host:ButtonRow({
        { Name = "Load", Callback = function() manager:Load() end },
        { Name = "Delete", Style = "Danger", Callback = function() manager:Delete() end },
    })
    host:ButtonRow({
        { Name = "Set autoload", Callback = function() manager:SetAutoload() end },
        { Name = "Clear autoload", Callback = function() manager:ClearAutoload() end },
    })
    host:ButtonRow({
        { Name = "Rename", Callback = function() manager:Rename(nil, nameInput:Get()) end },
        { Name = "Reset", Style = "Danger", Callback = function() manager:Reset() end },
    })
    status = host:Label("loaded: none   |   autoload: none")
    modeList = host:Dropdown({
        Name = "Autoload mode",
        Stacked = true,
        Options = { "All accounts", "This account" },
        Default = window:GetAutoloadMode() == "Account" and "This account" or "All accounts",
        AllowNone = false,
        Callback = function(choice)
            manager:SetAutoloadMode(choice == "This account" and "Account" or "Global")
        end,
    })
    host:Button({ Name = "Refresh list", Callback = function() manager:Refresh() end })
    host:Divider({ Text = "share" })
    host:Button({ Name = "Copy code", Callback = function() manager:Export() end })
    local codeInput = actionInput(host, "paste a config code...", nil, function(text)
        manager:Import(text)
    end)
    host:Button({ Name = "Import code", Callback = function() manager:Import(codeInput:Get()) end })

    function manager:Refresh()
        local names = window:ListConfigs()
        local keep = list:Get()
        list:Refresh(names, true)
        if keep and not table.find(names, keep) then
            list:Set(window.LoadedConfig and table.find(names, window.LoadedConfig) and window.LoadedConfig or nil, true)
        end
        refreshStatus()
    end

    local function select(name)
        manager:Refresh()
        list:Set(name, true)
    end

    function manager:Create(name)
        name = trim(name)
        if name == "" then
            notify(false, "Name the config", "Type a name before creating it")
            return
        end
        if not validConfigName(name) then
            notify(false, "Invalid name", 'Names cannot contain \\ / : * ? " < > |')
            return
        end
        local ok, err = window:SaveConfig(name)
        if ok then
            window.LoadedConfig = name
            nameInput:Set("")
            select(name)
        end
        notify(ok, ok and "Config created" or "Create failed", ok and name or tostring(err))
    end

    function manager:Save(name)
        name = name or list:Get()
        if not name then
            local typed = trim(nameInput:Get())
            if typed == "" then
                notify(false, "No config selected", "Pick one from the list or type a name")
                return
            end
            return manager:Create(typed)
        end
        local ok, err = window:SaveConfig(name)
        if ok then
            window.LoadedConfig = name
            refreshStatus()
        end
        notify(ok, ok and "Config saved" or "Save failed", ok and name or tostring(err))
    end

    function manager:Load(name)
        name = name or pickedName()
        if not name then
            return
        end
        local ok, err = window:LoadConfig(name)
        notify(ok, ok and "Config loaded" or "Load failed", ok and name or tostring(err))
    end

    function manager:Delete(name)
        name = name or pickedName()
        if not name then
            return
        end
        window:Confirm({
            Title = "Delete config",
            Content = "Remove " .. name .. "? This cannot be undone.",
            Icon = "trash-2",
            ConfirmText = "Delete",
            Callback = function()
                local ok, err = window:DeleteConfig(name)
                if ok then
                    if window:GetAutoload("Account") == name then
                        window:SetAutoload(nil, "Account")
                    end
                    if window:GetAutoload("Global") == name then
                        window:SetAutoload(nil, "Global")
                    end
                    list:Set(nil, true)
                end
                manager:Refresh()
                notify(ok, ok and "Config deleted" or "Delete failed", ok and name or tostring(err))
            end,
        })
    end

    function manager:Rename(name, newName)
        name = name or pickedName()
        if not name then
            return
        end
        newName = trim(newName)
        if newName == "" then
            notify(false, "Name the config", "Type the new name in the name box")
            return
        end
        if not validConfigName(newName) then
            notify(false, "Invalid name", 'Names cannot contain \\ / : * ? " < > |')
            return
        end
        local ok, err = window:RenameConfig(name, newName)
        if ok then
            nameInput:Set("")
            select(newName)
        end
        notify(ok, ok and "Config renamed" or "Rename failed", ok and (name .. " -> " .. newName) or tostring(err))
    end

    function manager:Reset()
        window:Confirm({
            Title = "Reset settings",
            Content = "Put every setting back to its default and delete this script's folder? Saved configs, themes and autoload are removed for good.",
            Icon = "rotate-ccw",
            ConfirmText = "Reset",
            Callback = function()
                window:ResetConfig()
                local wiped = window:ClearWorkspace()
                window:_applyDefaultTheme()
                list:Set(nil, true)
                manager:Refresh()
                modeList:Set("All accounts", true)
                notify(wiped, wiped and "Settings reset" or "Reset incomplete",
                    wiped and "Everything is back to its default" or "Some files in " .. window.ConfigFolder .. " could not be deleted")
            end,
        })
    end

    function manager:SetAutoload(name)
        name = name or pickedName()
        if not name then
            return
        end
        local ok, err = window:SetAutoload(name)
        notify(ok, ok and "Autoload set" or "Autoload failed", ok and name or tostring(err))
    end

    function manager:ClearAutoload()
        local current = window:GetAutoload()
        if not current then
            notify(false, "No autoload", "Nothing is set to autoload")
            return
        end
        local ok, err = window:SetAutoload(nil)
        notify(ok, ok and "Autoload cleared" or "Clear failed", ok and current or tostring(err))
    end

    function manager:ToggleAutoload(name)
        name = name or pickedName()
        if not name then
            return
        end
        if window:GetAutoload() == name then
            manager:ClearAutoload()
        else
            manager:SetAutoload(name)
        end
    end

    function manager:SetAutoloadMode(mode)
        local ok, err = window:SetAutoloadMode(mode)
        local label_ = mode == "Account" and "This account" or "All accounts"
        if modeList:Get() ~= label_ then
            modeList:Set(label_, true)
        end
        notify(ok ~= false, ok ~= false and "Autoload mode" or "Mode change failed", ok ~= false and label_ or tostring(err))
    end

    function manager:Export(name)
        local code, err = window:ExportConfig(name)
        if not code then
            notify(false, "Export failed", tostring(err))
            return nil
        end
        window:CopyToClipboard(code, "Config code")
        return code
    end

    function manager:Import(code)
        code = trim(code)
        if code == "" then
            notify(false, "Nothing to import", "Paste a config code first")
            return
        end
        local data, info = window:DecodeConfig(code)
        if not data then
            notify(false, "Import failed", "Invalid config code")
            return
        end
        -- The typed name wins; otherwise the code's own name, never overwriting a config.
        local saveAs = trim(nameInput:Get())
        if saveAs == "" then
            saveAs = nil
            if validConfigName(info.Name) then
                saveAs = info.Name
                local index = 2
                while window:ConfigExists(saveAs) do
                    saveAs = ("%s (%d)"):format(info.Name, index)
                    index += 1
                end
            end
        elseif not validConfigName(saveAs) then
            notify(false, "Invalid name", 'Names cannot contain \\ / : * ? " < > |')
            return
        end
        local function run()
            local ok, err = window:ImportConfig(code, saveAs, true)
            if ok then
                codeInput:Set("")
                if saveAs then
                    nameInput:Set("")
                    select(saveAs)
                end
            end
            notify(ok, ok and "Config imported" or "Import failed", ok and (saveAs or "Applied to current settings") or tostring(err))
        end
        if info.Folder and info.Folder ~= window.ConfigFolder then
            window:Confirm({
                Title = "Different script",
                Content = ("This config was made for %s. Import it anyway? Only matching settings are applied."):format(info.Folder),
                Icon = "triangle-alert",
                ConfirmText = "Import",
                Callback = run,
            })
            return
        end
        run()
    end

    local disconnect = window:OnConfigChanged(function()
        -- Configs can arrive from elsewhere (a cloud install), so the list is reread.
        manager:Refresh()
        if window.LoadedConfig and list:Get() == nil then
            list:Set(window.LoadedConfig, true)
        end
    end)
    status._listeners = status._listeners or {}
    table.insert(status._listeners, disconnect)

    refreshStatus()
    return manager
end

local PRESET_ORDER = {
    "Cybrion", "Midnight", "Nebula", "Synthwave", "Sakura", "Velvet", "Rose", "Crimson", "Sunset", "Amber", "Gold",
    "Cyber", "Toxic", "Matcha", "Emerald", "Aurora", "Ocean", "Frost", "Abyss", "Mono",
    "Halloween", "Haunted", "Christmas", "Valentine", "Lunar", "Tropical", "Dracula", "Coffee",
}

local function presetNames()
    local names, seen = {}, {}
    for _, name in ipairs(PRESET_ORDER) do
        if Library.ThemePresets[name] then
            table.insert(names, name)
            seen[name] = true
        end
    end
    local extra = {}
    for name in pairs(Library.ThemePresets) do
        if not seen[name] then
            table.insert(extra, name)
        end
    end
    table.sort(extra)
    for _, name in ipairs(extra) do
        table.insert(names, name)
    end
    return names
end

function Tab:ThemeManager(opts)
    opts = normalize(opts, { Title = "Name" })
    local host = managerHost(self, opts, "Themes", "palette")
    local window = self.Window
    local manager = {}
    local themes, status, defaultRow, presets
    local weather, weatherMode, dim, transparent, dragSkeleton, islandStyle
    local background, backgroundInput, backgroundOpacity, backgroundLabel
    local uiScale, density, adaptive, cornerRadius

    local function notify(ok, title, detail)
        window:Notify({ Title = title, Content = detail, Type = ok and "Success" or "Error", Duration = 3 })
    end

    local function refreshStatus()
        local current = window:GetDefaultTheme()
        status:Set("Default theme: " .. (current or "none"))
        local picked = themes:Get() or presets:Get()
        defaultRow:SetText(2, (picked and picked == current) and "Clear Default" or "Set Default")
    end

    local function pickedTheme()
        local name = themes:Get()
        if not name then
            notify(false, "No theme selected", "Pick one from the list first")
        end
        return name
    end

    presets = host:Dropdown({
        Name = "Preset",
        Options = presetNames(),
        Default = Library.ThemePresets[Library.ThemeName or ""] and Library.ThemeName or nil,
        NoneText = "custom",
        AllowNone = false,
        Callback = function(name)
            if name then
                Library:SetTheme(name)
                themes:Set(nil, true)
                refreshStatus()
            end
        end,
    })
    local labels = { None = "None", Snow = "Snow", Rain = "Rain", Ember = "Hell Fire", Sakura = "Sakura", Fireflies = "Fireflies", Matrix = "Matrix" }
    if window._backdrop and opts.Weather ~= false then
        weather = host:Dropdown({
            Name = "Weather",
            Options = { "Snow", "Rain", "Hell Fire", "Sakura", "Fireflies", "Matrix", "None" },
            Default = labels[window.Weather] or "Matrix",
            AllowNone = false,
            Callback = function(name)
                if name then
                    window:SetWeather(name)
                end
            end,
        })
    end
    if window._backdrop and opts.Weather ~= false then
        weatherMode = host:Dropdown({
            Name = "Weather Mode",
            Options = { "Screen", "UI" },
            Default = window.WeatherMode,
            AllowNone = false,
            Callback = function(mode)
                if mode then
                    window:SetWeatherMode(mode)
                end
            end,
        })
    end
    if window._backdrop and opts.Dim ~= false then
        dim = host:Toggle({
            Name = "Dim",
            Default = window._backdropDim,
            Callback = function(value)
                window:SetDim(value)
            end,
        })
    end
    if opts.Transparent ~= false then
        transparent = host:Toggle({
            Name = "Transparent",
            Default = window.Transparent == true,
            Callback = function(value)
                window:SetTransparent(value)
            end,
        })
    end
    if opts.DragSkeleton ~= false and opts.DragStyle ~= false then
        dragSkeleton = host:Dropdown({
            Name = "Drag Style",
            Options = Library.DragStyles,
            Default = window.DragStyle,
            AllowNone = false,
            Callback = function(style)
                if style then
                    window:SetDragStyle(style)
                end
            end,
        })
    end
    if opts.IslandStyle ~= false then
        islandStyle = host:Dropdown({
            Name = "Dynamic Island",
            Options = Library.IslandStyles,
            Default = window.IslandStyle,
            AllowNone = false,
            Callback = function(style)
                if style then
                    window:SetIslandStyle(style)
                end
            end,
        })
    end
    if opts.AdaptiveSize ~= false then
        adaptive = host:Toggle({
            Name = "Adaptive Size",
            Default = window:GetAdaptiveSize(),
            Callback = function(value)
                window:SetAdaptiveSize(value)
            end,
        })
    end
    if opts.Scale ~= false then
        uiScale = host:Slider({
            Name = "UI Scale",
            Min = 60,
            Max = 150,
            Increment = 5,
            Default = math.floor(window:GetUIScale() * 100 + 0.5),
            Suffix = "%",
            Callback = function(value)
                if not (uiScale and uiScale.Dragging) then
                    window:SetUIScale(value / 100)
                end
            end,
            OnRelease = function(value)
                window:SetUIScale(value / 100)
            end,
        })
    end
    if opts.Density ~= false then
        density = host:Dropdown({
            Name = "Density",
            Options = { "Compact", "Default", "Comfortable" },
            Default = Library.Density,
            AllowNone = false,
            Callback = function(mode)
                if mode then
                    Library:SetDensity(mode)
                end
            end,
        })
    end
    if opts.CornerRadius ~= false then
        cornerRadius = host:Slider({
            Name = "Corner Radius",
            Min = 0,
            Max = 20,
            Increment = 1,
            Default = Library:GetCornerRadius(),
            Suffix = "px",
            Callback = function(value)
                Library:SetCornerRadius(value)
            end,
        })
    end
    if opts.Background ~= false then
        -- The dropdown shows listed images by name, "custom" for ids and links.
        backgroundLabel = function(source)
            if source == nil or source == "" then
                return "None"
            end
            return table.find(window:ListBackgrounds(), source) and source or nil
        end
        local function applyBackground(source, fromList)
            task.spawn(function()
                local ok, err = window:SetBackground(source)
                if ok and not fromList then
                    background:Set(backgroundLabel(window.Background), true)
                elseif not ok and err ~= "replaced by a newer background" then
                    notify(false, "Background failed", tostring(err))
                end
            end)
        end
        local options = window:ListBackgrounds()
        table.insert(options, 1, "None")
        background = host:Dropdown({
            Name = "Background",
            Options = options,
            Default = backgroundLabel(window.Background),
            NoneText = "custom",
            AllowNone = false,
            Callback = function(name)
                if name then
                    applyBackground(name, true)
                end
            end,
        })
        backgroundInput = actionInput(host, "image id or url", "Set", function(text)
            text = trim(text)
            if text == "" then
                notify(false, "No image", "Paste an image id or link first")
                return
            end
            applyBackground(text)
        end)
        backgroundOpacity = host:Slider({
            Name = "Background Opacity",
            Min = 0,
            Max = 100,
            Default = math.floor((1 - window.BackgroundTransparency) * 100 + 0.5),
            Suffix = "%",
            Callback = function(value)
                window:SetBackgroundTransparency(1 - value / 100)
            end,
        })
    end
    local nameInput = actionInput(host, opts.Placeholder or "theme name", "Create", function(text)
        manager:Create(text)
    end)
    themes = host:Dropdown({
        Name = "Theme",
        Options = window:ListThemes(),
        Default = (function()
            local current = window:GetDefaultTheme()
            return current and not Library.ThemePresets[current] and current or nil
        end)(),
        EmptyText = "no themes",
        NoneText = "select",
        Callback = function()
            refreshStatus()
        end,
    })
    host:ButtonRow({
        { Name = "Save", Callback = function() manager:Save() end },
        { Name = "Load", Callback = function() manager:Load() end },
    })
    defaultRow = host:ButtonRow({
        { Name = "Delete", Callback = function() manager:Delete() end },
        { Name = "Set Default", Callback = function() manager:ToggleDefault() end },
    })
    status = host:Label("Default theme: none")

    function manager:Refresh()
        themes:Refresh(window:ListThemes(), true)
        if background then
            local options = window:ListBackgrounds()
            table.insert(options, 1, "None")
            background:Refresh(options, true, true)
        end
        refreshStatus()
    end

    function manager:Create(name)
        name = trim(name)
        if name == "" then
            notify(false, "Name the theme", "Type a name before creating it")
            return
        end
        if Library.ThemePresets[name] then
            notify(false, "Name taken", name .. " is a built-in preset")
            return
        end
        local ok, err = window:SaveTheme(name)
        manager:Refresh()
        if ok then
            themes:Set(name, true)
            nameInput:Set("")
            refreshStatus()
        end
        notify(ok, ok and "Theme created" or "Create failed", ok and name or tostring(err))
    end

    function manager:Save(name)
        name = name or pickedTheme()
        if not name then
            return
        end
        local ok, err = window:SaveTheme(name)
        notify(ok, ok and "Theme saved" or "Save failed", ok and name or tostring(err))
    end

    function manager:Load(name)
        name = name or pickedTheme()
        if not name then
            return
        end
        local ok, err = window:LoadTheme(name)
        if ok then
            presets:Set(nil, true)
        end
        notify(ok ~= false, ok and "Theme loaded" or "Load failed", ok and name or tostring(err))
    end

    function manager:Delete(name)
        name = name or pickedTheme()
        if not name then
            return
        end
        window:Confirm({
            Title = "Delete theme",
            Content = "Remove " .. name .. "? This cannot be undone.",
            Icon = "trash-2",
            ConfirmText = "Delete",
            Callback = function()
                local ok, err = window:DeleteTheme(name)
                manager:Refresh()
                notify(ok, ok and "Theme deleted" or "Delete failed", ok and name or tostring(err))
            end,
        })
    end

    function manager:ToggleDefault(name)
        name = name or themes:Get() or presets:Get()
        if not name then
            notify(false, "Nothing selected", "Pick a theme or a preset first")
            return
        end
        local clearing = window:GetDefaultTheme() == name
        local ok, err = window:SetDefaultTheme(not clearing and name or nil)
        refreshStatus()
        notify(ok ~= false, clearing and "Default cleared" or "Default theme set", ok ~= false and name or tostring(err))
    end

    if opts.Customize ~= false then
        host:Divider()
        local fields = opts.Colors or {
            { "Accent", "Accent" },
            { "Background", "Background" },
            { "Surface2", "Surface" },
            { "Text", "Text" },
            { "Muted", "Muted text" },
        }
        for _, field in ipairs(fields) do
            local key, title = field[1], field[2] or field[1]
            local pending, scheduled = nil, false
            local picker
            picker = host:ColorPicker({
                Name = title,
                Default = Theme[key],
                Callback = function(color)
                    pending = color
                    if scheduled then
                        return
                    end
                    scheduled = true
                    task.delay(0.08, function()
                        scheduled = false
                        Library:SetTheme({ [key] = pending }, true)
                        presets:Set(nil, true)
                    end)
                end,
            })
            table.insert(Library._themeListeners, function()
                if picker.Value ~= Theme[key] then
                    picker:Set(Theme[key], true)
                end
            end)
        end
    end

    if opts.Flag ~= false then
        local flag = type(opts.Flag) == "string" and opts.Flag or "__Theme"
        local look = { _type = "Theme", _searchName = "Theme", _searchKey = "theme", _listeners = {} }

        function look:Get()
            local colors = {}
            for _, key in ipairs(THEME_KEYS) do
                colors[key] = colorToHex(Theme[key])
            end
            return {
                Name = presets:Get() or themes:Get(),
                Colors = colors,
                Weather = weather and window.Weather or nil,
                WeatherMode = weatherMode and window.WeatherMode or nil,
                -- if-expressions, not and/or: a switched-off value is false, not nil.
                Dim = if dim then window._backdropDim == true else nil,
                Transparent = if transparent then window.Transparent == true else nil,
                DragStyle = dragSkeleton and window.DragStyle or nil,
                IslandStyle = islandStyle and window.IslandStyle or nil,
                CornerRadius = cornerRadius and Library:GetCornerRadius() or nil,
                UIScale = uiScale and window:GetUIScale() or nil,
                AdaptiveSize = if adaptive then window:GetAdaptiveSize() else nil,
                Density = density and Library.Density or nil,
                -- "" is no background; a missing field leaves it alone on load.
                Background = background and (window.Background or "") or nil,
                BackgroundTransparency = background and window.BackgroundTransparency or nil,
            }
        end

        function look:Set(value)
            if type(value) ~= "table" then
                return
            end
            if type(value.Colors) == "table" then
                Library:SetTheme(value.Colors)
            end
            local name = type(value.Name) == "string" and value.Name or nil
            if name and Library.ThemePresets[name] then
                Library.ThemeName = name
                presets:Set(name, true)
                themes:Set(nil, true)
            else
                if name then
                    Library.ThemeName = name
                end
                presets:Set(nil, true)
                themes:Set(name and table.find(window:ListThemes(), name) and name or nil, true)
            end
            if weather and type(value.Weather) == "string" then
                window:SetWeather(value.Weather)
                weather:Set(labels[window.Weather] or "None", true)
            end
            if weatherMode and type(value.WeatherMode) == "string" then
                window:SetWeatherMode(value.WeatherMode)
                weatherMode:Set(window.WeatherMode, true)
            end
            if dim and type(value.Dim) == "boolean" then
                window:SetDim(value.Dim)
                dim:Set(value.Dim, true)
            end
            if transparent and type(value.Transparent) == "boolean" then
                window:SetTransparent(value.Transparent)
                transparent:Set(value.Transparent, true)
            end
            if dragSkeleton and type(value.DragStyle) == "string" then
                dragSkeleton:Set(window:SetDragStyle(value.DragStyle), true)
            elseif dragSkeleton and type(value.DragSkeleton) == "boolean" then
                -- legacy configs saved before drag styles.
                window:SetDragSkeleton(value.DragSkeleton)
                dragSkeleton:Set(window.DragStyle, true)
            end
            if islandStyle and type(value.IslandStyle) == "string" then
                islandStyle:Set(window:SetIslandStyle(value.IslandStyle), true)
            end
            if cornerRadius and tonumber(value.CornerRadius) then
                cornerRadius:Set(Library:SetCornerRadius(value.CornerRadius), true)
            end
            if adaptive and type(value.AdaptiveSize) == "boolean" then
                window:SetAdaptiveSize(value.AdaptiveSize)
                adaptive:Set(value.AdaptiveSize, true)
            end
            if uiScale and tonumber(value.UIScale) then
                window:SetUIScale(tonumber(value.UIScale))
                uiScale:Set(math.floor(window:GetUIScale() * 100 + 0.5), true)
            end
            if density and type(value.Density) == "string" then
                density:Set(Library:SetDensity(value.Density), true)
            end
            if value.ToggleStyle == "Toggle" or value.ToggleStyle == "Checkbox" then
                Library:SetForceCheckbox(value.ToggleStyle == "Checkbox")
                local style = window._interfaceToggleStyle
                if style and not style._destroyed then
                    style:Set(value.ToggleStyle, true)
                end
            end
            if type(value.KeybindMenu) == "boolean" then
                window:SetKeybindMenu(value.KeybindMenu)
            end
            if background and tonumber(value.BackgroundTransparency) then
                window:SetBackgroundTransparency(tonumber(value.BackgroundTransparency))
                backgroundOpacity:Set(math.floor((1 - window.BackgroundTransparency) * 100 + 0.5), true)
            end
            if background and type(value.Background) == "string" and value.Background ~= (window.Background or "") then
                local source = value.Background
                background:Set(backgroundLabel(source), true)
                -- A web image may download first; don't hold up the rest of the config.
                task.spawn(window.SetBackground, window, source)
            end
            refreshStatus()
        end

        Library.Flags[flag] = look
        window:_flagCreated(flag, look)
    end

    -- A reset wipes the themes folder, so drop the stale list.
    window._workspaceListeners = window._workspaceListeners or {}
    table.insert(window._workspaceListeners, function()
        themes:Set(nil, true)
        manager:Refresh()
    end)

    refreshStatus()
    return manager
end

function Tab:InterfaceManager(opts)
    opts = normalize(opts, { Title = "Name" })
    local host = managerHost(self, opts, "Interface", "monitor")
    local window = self.Window
    local manager = {}
    local keybind, backdropToggle, cursorToggle, watermarkToggle, toggleStyle, keybindMenuToggle
    local watermark = type(opts.Watermark) == "table" and type(opts.Watermark.SetVisible) == "function"
        and not opts.Watermark.Destroyed and opts.Watermark or nil
    local ownsWatermark = false
    local autoCreated = false

    if opts.Watermark ~= false and not watermark then
        watermark = window._interfaceWatermark
        if not watermark or watermark.Destroyed then
            watermark = Library:AddDraggableLabel({
                Window = window,
                Text = (opts.WatermarkName or window.Title or "Aster UI") .. " | -- FPS | -- ms",
                Position = opts.WatermarkPosition or Vector2.new(20, 70),
            })
            window._interfaceWatermark = watermark
            autoCreated = true
        end
        ownsWatermark = watermark ~= nil
    end

    if watermark and not watermark.Destroyed then
        if autoCreated then
            watermark:SetVisible(opts.WatermarkVisible == true)
        elseif opts.WatermarkVisible ~= nil then
            watermark:SetVisible(opts.WatermarkVisible == true)
        end
    end

    if ownsWatermark and watermark and window._interfaceWatermarkBound ~= watermark then
        window._interfaceWatermarkBound = watermark
        local frames, elapsed = 0, 0
        table.insert(window._connections, RunService.Heartbeat:Connect(function(deltaTime)
            if window._destroyed or not watermark or watermark.Destroyed then
                return
            end
            frames += 1
            elapsed += deltaTime
            if elapsed < 0.5 then
                return
            end
            local fps = math.floor(frames / elapsed + 0.5)
            frames, elapsed = 0, 0
            local ping = 0
            pcall(function()
                ping = math.floor(StatsService.Network.ServerStatsItem["Data Ping"]:GetValue() + 0.5)
            end)
            if ping <= 0 then
                pcall(function()
                    ping = math.floor(LocalPlayer:GetNetworkPing() * 1000 + 0.5)
                end)
            end
            watermark:SetText((opts.WatermarkName or window.Title or "Aster UI") .. " | " .. fps .. " FPS | " .. ping .. " ms")
        end))
    end
    manager.Watermark = watermark

    local function watermarkShown()
        local pill = watermark and watermark.Label
        return watermark ~= nil and not watermark.Destroyed and not (pill and pill.Visible == false)
    end

    if opts.MenuKeybind ~= false then
        keybind = host:Keybind({
            Name = "Menu Keybind",
            Default = window.Keybind or "LeftAlt",
            OnChanged = function(key)
                if key then
                    window:SetKeybind(key)
                end
            end,
        })
        window._interfaceKeybind = keybind
    end

    if window._backdrop and opts.Backdrop ~= false then
        backdropToggle = host:Toggle({
            Name = "Backdrop",
            Default = window._backdropEnabled ~= false,
            Callback = function(value)
                window:SetBackdrop(value)
            end,
        })
        window._interfaceBackdropToggle = backdropToggle
    end

    if opts.CustomCursor ~= false then
        cursorToggle = host:Toggle({
            Name = "Custom Cursor",
            Default = window.ShowCustomCursor == true,
            Callback = function(value)
                window:SetShowCustomCursor(value)
            end,
        })
        window._interfaceCursorToggle = cursorToggle
    end

    if watermark and not watermark.Destroyed and opts.Watermark ~= false then
        watermarkToggle = host:Toggle({
            Name = "Watermark",
            Default = watermarkShown(),
            Callback = function(value)
                if watermark and not watermark.Destroyed then
                    watermark:SetVisible(value)
                end
            end,
        })
        window._interfaceWatermarkToggle = watermarkToggle
    end

    if opts.KeybindMenu ~= false then
        keybindMenuToggle = host:Toggle({
            Name = "Keybind Menu",
            Default = window.KeybindFrame ~= nil and window.KeybindFrame.Visible == true,
            Callback = function(value)
                window:SetKeybindMenu(value)
            end,
        })
        window._keybindMenuToggle = keybindMenuToggle
    end

    if opts.ToggleStyle ~= false then
        toggleStyle = host:Dropdown({
            Name = "Toggle Style",
            Options = { "Toggle", "Checkbox" },
            Default = Library.ForceCheckbox and "Checkbox" or "Toggle",
            AllowNone = false,
            Callback = function(style)
                if style then
                    Library:SetForceCheckbox(style == "Checkbox")
                end
            end,
        })
        window._interfaceToggleStyle = toggleStyle
    end

    if opts.Unload ~= false then
        host:Button({
            Name = "Unload",
            Icon = "power",
            Style = "Danger",
            Callback = function()
                window:Confirm({
                    Title = "Unload " .. (window.Title or "Aster UI") .. "?",
                    Content = "Every feature is switched off and the menu closes.",
                    Icon = "power",
                    ConfirmText = "Unload",
                    Callback = function()
                        window:Destroy()
                    end,
                })
            end,
        })
    end

    function manager:Refresh()
        if keybind and not keybind._destroyed then
            keybind:Set(window.Keybind, true)
        end
        if backdropToggle and not backdropToggle._destroyed then
            backdropToggle:Set(window._backdropEnabled ~= false, true)
        end
        if cursorToggle and not cursorToggle._destroyed then
            cursorToggle:Set(window.ShowCustomCursor == true, true)
        end
        if watermarkToggle and not watermarkToggle._destroyed then
            watermarkToggle:Set(watermarkShown(), true)
        end
        if toggleStyle and not toggleStyle._destroyed then
            toggleStyle:Set(Library.ForceCheckbox and "Checkbox" or "Toggle", true)
        end
        if keybindMenuToggle and not keybindMenuToggle._destroyed then
            keybindMenuToggle:Set(window.KeybindFrame ~= nil and window.KeybindFrame.Visible == true, true)
        end
    end

    if opts.Flag ~= false then
        local flag = type(opts.Flag) == "string" and opts.Flag or "__Interface"
        local interface = { _type = "Interface", _searchName = "Interface", _searchKey = "interface", _listeners = {} }

        function interface:Get()
            local bind = keybind and keybind:Get() or nil
            return {
                MenuKey = bind and bind.Name or nil,
                Backdrop = if backdropToggle then backdropToggle:Get() else nil,
                CustomCursor = if cursorToggle then cursorToggle:Get() else nil,
                Watermark = if watermarkToggle then watermarkToggle:Get() else nil,
                ToggleStyle = toggleStyle and toggleStyle:Get() or nil,
                KeybindMenu = if keybindMenuToggle then keybindMenuToggle:Get() else nil,
            }
        end

        function interface:Set(value)
            if type(value) ~= "table" then
                return
            end
            if keybind and not keybind._destroyed and value.MenuKey ~= nil then
                local bind = Keybinds.Resolve(value.MenuKey)
                if bind then
                    keybind:Set(bind, true)
                    window:SetKeybind(bind)
                end
            end
            if backdropToggle and not backdropToggle._destroyed and type(value.Backdrop) == "boolean" then
                backdropToggle:Set(value.Backdrop, true)
                window:SetBackdrop(value.Backdrop)
            end
            if cursorToggle and not cursorToggle._destroyed and type(value.CustomCursor) == "boolean" then
                cursorToggle:Set(value.CustomCursor, true)
                window:SetShowCustomCursor(value.CustomCursor)
            end
            if watermarkToggle and not watermarkToggle._destroyed and type(value.Watermark) == "boolean" then
                watermarkToggle:Set(value.Watermark, true)
                if watermark and not watermark.Destroyed then
                    watermark:SetVisible(value.Watermark)
                end
            end
            if toggleStyle and not toggleStyle._destroyed
                and (value.ToggleStyle == "Toggle" or value.ToggleStyle == "Checkbox") then
                Library:SetForceCheckbox(value.ToggleStyle == "Checkbox")
                toggleStyle:Set(value.ToggleStyle, true)
            end
            if keybindMenuToggle and not keybindMenuToggle._destroyed and type(value.KeybindMenu) == "boolean" then
                keybindMenuToggle:Set(value.KeybindMenu, true)
                window:SetKeybindMenu(value.KeybindMenu)
            end
        end

        Library.Flags[flag] = interface
        window:_flagCreated(flag, interface)
    end

    return manager
end

Tab.CreateButtonRow = Tab.ButtonRow
Tab.CreateConfigManager = Tab.ConfigManager
Tab.CreateThemeManager = Tab.ThemeManager
Tab.CreateInterfaceManager = Tab.InterfaceManager

-- Status: read-only key/value lines, mostly for groupboxes, in several styles.

local STATUS_HEIGHT = { Plain = 22, Row = 24, Badge = 28, Dot = 24, Bar = 38, Stat = 46 }

-- Tone: a theme key, a Color3 or "#rrggbb".
local function toneColor(tone)
    return Library._color(tone) or Theme.Accent
end

local function formatNumber(value)
    if value == math.floor(value) then
        return tostring(math.floor(value))
    end
    return string.format("%.1f", value)
end

local function parseFraction(value, max)
    if type(value) == "number" and type(max) == "number" then
        return value, max
    end
    if type(value) == "string" then
        local cleaned = (value:gsub(",", ""))
        local current, total = cleaned:match("^%s*(%-?[%d%.]+)%s*/%s*(%-?[%d%.]+)")
        if current then
            return tonumber(current), tonumber(total)
        end
    end
    return nil, nil
end

function Tab:Status(opts)
    opts = normalize(opts, { Title = "Name", Text = "Value", Content = "Value", CurrentValue = "Value", Default = "Value" })
    local style = STATUS_HEIGHT[opts.Style] and opts.Style or "Plain"
    local compact = metricsOf(self).Compact
    local window = self.Window
    local height = STATUS_HEIGHT[style]
    local pad = compact and 0 or 8
    local frame = card(self, "Frame", height + pad * 2, opts)
    local holder = create("Frame", {
        Position = UDim2.fromOffset(14, pad),
        Size = UDim2.new(1, -28, 0, height),
        BackgroundTransparency = 1,
        Parent = frame,
    })

    local handle = { Value = opts.Value, Max = opts.Max, Tone = opts.Tone or "Accent", Name = opts.Name or "", Color = opts.Color or opts.ValueColor }
    local keyLabel, valueLabel, chip, chipStroke, dot, pulse, fill
    local tinted = false

    local function keyText()
        return style == "Plain" and (handle.Name .. ":") or handle.Name
    end

    if style == "Plain" then
        create("UIListLayout", {
            FillDirection = Enum.FillDirection.Horizontal,
            VerticalAlignment = Enum.VerticalAlignment.Center,
            SortOrder = Enum.SortOrder.LayoutOrder,
            Padding = UDim.new(0, 5),
            Parent = holder,
        })
        keyLabel = label({
            Size = UDim2.new(0, 0, 1, 0),
            AutomaticSize = Enum.AutomaticSize.X,
            TextSize = 12,
            FontFace = Fonts.Regular,
            TextColor3 = Theme.Muted,
            TextTruncate = Enum.TextTruncate.None,
            LayoutOrder = 1,
            Parent = holder,
        })
        valueLabel = label({
            Size = UDim2.new(0, 0, 1, 0),
            AutomaticSize = Enum.AutomaticSize.X,
            TextSize = 12,
            TextColor3 = Theme.Text,
            TextTruncate = Enum.TextTruncate.None,
            LayoutOrder = 2,
            Parent = holder,
        })
    elseif style == "Stat" then
        keyLabel = label({
            Position = UDim2.fromOffset(0, 3),
            Size = UDim2.new(1, 0, 0, 14),
            TextSize = 11,
            TextColor3 = Theme.Muted,
            Parent = holder,
        })
        valueLabel = label({
            Position = UDim2.fromOffset(0, 18),
            Size = UDim2.new(1, 0, 0, 24),
            TextSize = 20,
            FontFace = Fonts.Bold,
            TextColor3 = Theme.Text,
            Parent = holder,
        })
    else
        local keyX = 0
        if style == "Dot" then
            keyX = 18
            pulse = create("Frame", {
                AnchorPoint = Vector2.new(0.5, 0.5),
                Position = UDim2.new(0, 5, 0.5, 0),
                Size = UDim2.fromOffset(8, 8),
                BackgroundColor3 = toneColor(handle.Tone),
                BackgroundTransparency = 0.4,
                BorderSizePixel = 0,
                Parent = holder,
            })
            corner(pulse, UDim.new(1, 0))
            dot = create("Frame", {
                AnchorPoint = Vector2.new(0.5, 0.5),
                Position = UDim2.new(0, 5, 0.5, 0),
                Size = UDim2.fromOffset(8, 8),
                BackgroundColor3 = toneColor(handle.Tone),
                BorderSizePixel = 0,
                Parent = holder,
            })
            corner(dot, UDim.new(1, 0))
            if opts.Pulse ~= false then
                TweenService:Create(pulse, TweenInfo.new(1.4, Enum.EasingStyle.Quad, Enum.EasingDirection.Out, -1), {
                    Size = UDim2.fromOffset(20, 20),
                    BackgroundTransparency = 1,
                }):Play()
            else
                pulse.Visible = false
            end
        end
        local rowHeight = style == "Bar" and 18 or height
        keyLabel = label({
            Position = UDim2.fromOffset(keyX, 0),
            Size = UDim2.new(0.55, -keyX, 0, rowHeight),
            TextSize = 12,
            FontFace = Fonts.Regular,
            TextColor3 = Theme.Muted,
            Parent = holder,
        })
        if style == "Badge" then
            tinted = true
            chip = create("Frame", {
                AnchorPoint = Vector2.new(1, 0.5),
                Position = UDim2.new(1, 0, 0.5, 0),
                Size = UDim2.fromOffset(0, 22),
                AutomaticSize = Enum.AutomaticSize.X,
                BackgroundColor3 = toneColor(handle.Tone),
                BackgroundTransparency = 0.86,
                BorderSizePixel = 0,
                Parent = holder,
            })
            corner(chip, UDim.new(1, 0))
            chipStroke = stroke(chip, toneColor(handle.Tone), 0.6)
            padding(chip, 10, 10)
            valueLabel = label({
                Size = UDim2.new(0, 0, 1, 0),
                AutomaticSize = Enum.AutomaticSize.X,
                TextSize = 12,
                TextColor3 = toneColor(handle.Tone),
                TextTruncate = Enum.TextTruncate.None,
                Parent = chip,
            })
        else
            valueLabel = label({
                AnchorPoint = Vector2.new(1, 0),
                Position = UDim2.new(1, 0, 0, 0),
                Size = UDim2.new(0.45, 0, 0, rowHeight),
                TextSize = 12,
                TextColor3 = Theme.Text,
                TextXAlignment = Enum.TextXAlignment.Right,
                Parent = holder,
            })
        end
        if style == "Bar" then
            local track = create("Frame", {
                Position = UDim2.fromOffset(0, 25),
                Size = UDim2.new(1, 0, 0, 5),
                BackgroundColor3 = Theme.Surface3,
                BorderSizePixel = 0,
                ClipsDescendants = true,
                Parent = holder,
            })
            corner(track, UDim.new(1, 0))
            fill = create("Frame", {
                Size = UDim2.new(0, 0, 1, 0),
                BackgroundColor3 = toneColor(handle.Tone),
                BorderSizePixel = 0,
                Parent = track,
            })
            corner(fill, UDim.new(1, 0))
        end
    end

    local lastText = nil
    local function render(animate)
        keyLabel.Text = Library._rich(keyText())
        local value = handle.Value
        local text = value == nil and (opts.Placeholder or "-") or tostring(value)
        if style == "Bar" then
            local current, total = parseFraction(value, handle.Max)
            if current and total then
                handle.Max = total
                text = formatNumber(current) .. " / " .. formatNumber(total)
                local fraction = total > 0 and math.clamp(current / total, 0, 1) or 0
                tween(fill, { Size = UDim2.new(fraction, 0, 1, 0) }, animate and 0.4 or 0, Enum.EasingStyle.Quint)
            elseif type(value) == "number" and value <= 1 then
                text = string.format("%d%%", math.floor(value * 100 + 0.5))
                tween(fill, { Size = UDim2.new(math.clamp(value, 0, 1), 0, 1, 0) }, animate and 0.4 or 0, Enum.EasingStyle.Quint)
            end
        end
        text = Library._rich((opts.Prefix or "") .. text .. (opts.Suffix or ""))
        local changed = lastText ~= nil and text ~= lastText
        lastText = text
        valueLabel.Text = text
        local tone = toneColor(handle.Tone)
        local duration = animate and 0.25 or 0
        -- Color paints the whole value; inline tags still win over it.
        local valueColor = not tinted and Library._color(handle.Color) or Theme.Text
        if not tinted and not (changed and animate and opts.Flash ~= false) then
            tween(valueLabel, { TextColor3 = valueColor }, duration)
        end
        if chip then
            tween(chip, { BackgroundColor3 = tone }, duration)
            tween(chipStroke, { Color = tone }, duration)
            tween(valueLabel, { TextColor3 = tone }, duration)
        end
        if dot then
            tween(dot, { BackgroundColor3 = tone }, duration)
            tween(pulse, { BackgroundColor3 = tone }, 0)
        end
        if fill then
            tween(fill, { BackgroundColor3 = tone }, duration)
        end
        -- A brief accent flash marks a changed value.
        if changed and animate and not tinted and opts.Flash ~= false then
            tween(valueLabel, { TextColor3 = Theme.Accent }, 0.08)
            task.delay(0.1, function()
                if valueLabel.Parent then
                    tween(valueLabel, { TextColor3 = Library._color(handle.Color) or Theme.Text }, 0.45)
                end
            end)
        end
    end

    keyLabel.RichText = true
    valueLabel.RichText = true
    -- Theme tags in the text are baked to colours, so repaint on theme change.
    onTheme(holder, function()
        if lastText ~= nil then
            render(false)
        end
    end)

    function handle:Set(value, max)
        handle.Value = value
        if max ~= nil then
            handle.Max = max
        end
        render(true)
    end
    function handle:Get()
        return handle.Value
    end
    function handle:SetTone(tone)
        handle.Tone = tone
        render(true)
    end
    -- nil goes back to the normal text colour.
    function handle:SetColor(color)
        handle.Color = color
        render(true)
    end
    function handle:SetName(name)
        handle.Name = tostring(name)
        render(false)
    end
    function handle:Text()
        return valueLabel.Text
    end
    -- value colour on the island copy.
    function handle._shownColor()
        if handle.Color ~= nil then
            return Library._color(handle.Color) or Theme.Text
        end
        if style == "Badge" or style == "Dot" or style == "Bar" then
            return toneColor(handle.Tone)
        end
        return Theme.Text
    end

    handle._listeners = {}
    if type(opts.Update) == "function" then
        local rate = math.max(tonumber(opts.UpdateRate) or 1, 0.05)
        local running = true
        table.insert(handle._listeners, function()
            running = false
        end)
        task.spawn(function()
            while running and frame.Parent do
                local ok, value, extra = isolatedCall(opts.Update)
                if ok then
                    if value ~= nil then
                        handle.Value = value
                    end
                    if type(extra) == "number" then
                        handle.Max = extra
                    elseif type(extra) == "string" or typeof(extra) == "Color3" then
                        handle.Tone = extra
                    end
                    render(true)
                else
                    warn("[Aster UI] status update error: " .. tostring(value))
                end
                task.wait(rate)
            end
        end)
        function handle:SetUpdateRate(seconds)
            rate = math.max(tonumber(seconds) or rate, 0.05)
        end
    end
    if opts.Pin then
        table.insert(window._pinned, handle)
        table.insert(handle._listeners, function()
            local index = table.find(window._pinned, handle)
            if index then
                table.remove(window._pinned, index)
            end
        end)
    end

    render(false)
    return finishElement(self, opts, handle, frame, "Status")
end

function Tab:Statuses(entries, shared)
    local handles = {}
    for index, entry in ipairs(entries or {}) do
        local entryOpts = type(entry) == "table" and table.clone(entry) or { Name = tostring(entry) }
        for key, value in pairs(shared or {}) do
            if entryOpts[key] == nil then
                entryOpts[key] = value
            end
        end
        local handle = self:Status(entryOpts)
        handles[entryOpts.Name or entryOpts.Title or index] = handle
    end
    return handles
end

function Tab:StatusList(opts)
    opts = normalize(opts, { Title = "Name" })
    local compact = metricsOf(self).Compact
    local window = self.Window
    local maxRows = math.max(math.floor(tonumber(opts.MaxRows) or 5), 1)
    local frame = card(self, "Frame", 0, opts)
    frame.AutomaticSize = Enum.AutomaticSize.Y
    if compact then
        padding(frame, 14, 14, 6, 8)
    else
        padding(frame, 14, 14, 11, 12)
    end
    create("UIListLayout", {
        SortOrder = Enum.SortOrder.LayoutOrder,
        Padding = UDim.new(0, 4),
        Parent = frame,
    })
    local heading = label({
        Size = UDim2.new(1, 0, 0, 16),
        Text = string.upper(tostring(opts.Name or "")),
        TextSize = 11,
        TextColor3 = Theme.Muted,
        Visible = tostring(opts.Name or "") ~= "",
        LayoutOrder = 1,
        Parent = frame,
    })
    local scroller = create("ScrollingFrame", {
        Size = UDim2.new(1, 0, 0, 0),
        BackgroundTransparency = 1,
        BorderSizePixel = 0,
        ScrollBarThickness = 2,
        ScrollBarImageColor3 = Theme.Accent,
        ScrollBarImageTransparency = 0.4,
        ScrollingDirection = Enum.ScrollingDirection.Y,
        AutomaticCanvasSize = Enum.AutomaticSize.Y,
        CanvasSize = UDim2.new(),
        ScrollingEnabled = false,
        LayoutOrder = 2,
        Parent = frame,
    })
    scroller:SetAttribute("NoDrag", true)
    local content = create("Frame", {
        Size = UDim2.new(1, 0, 0, 0),
        AutomaticSize = Enum.AutomaticSize.Y,
        BackgroundTransparency = 1,
        Parent = scroller,
    })
    local contentPadding = padding(content, 0, 0, 0, 0)
    create("UIListLayout", {
        SortOrder = Enum.SortOrder.LayoutOrder,
        Padding = UDim.new(0, 2),
        Parent = content,
    })
    local empty = label({
        Size = UDim2.new(1, 0, 0, 24),
        AutomaticSize = Enum.AutomaticSize.Y,
        Text = tostring(opts.EmptyText or "Nothing yet"),
        TextSize = 13,
        LineHeight = 1.1,
        FontFace = Fonts.Regular,
        TextColor3 = Theme.Muted,
        TextWrapped = true,
        TextTruncate = Enum.TextTruncate.None,
        LayoutOrder = 0,
        Parent = content,
    })

    local rowObjects, rows, signature, raw = {}, {}, nil, {}
    local handle = { _listeners = {} }

    local function fit()
        if handle._destroyed then
            return
        end
        local scale = window.Scale.Scale
        local count = #rows
        local height = 0
        if count == 0 then
            height = empty.AbsoluteSize.Y / scale
        else
            local shown = math.min(count, maxRows)
            for index = 1, shown do
                height += rowObjects[index].Frame.AbsoluteSize.Y / scale
            end
            height += (shown - 1) * 2
        end
        height = math.ceil(height)
        local scrolling = count > maxRows
        scroller.ScrollingEnabled = scrolling
        contentPadding.PaddingRight = UDim.new(0, scrolling and 8 or 0)
        if scroller.Size.Y.Offset ~= height then
            scroller.Size = UDim2.new(1, 0, 0, height)
        end
        local maxScroll = math.max(scroller.AbsoluteCanvasSize.Y - scroller.AbsoluteWindowSize.Y, 0) / scale
        if scroller.CanvasPosition.Y > maxScroll then
            scroller.CanvasPosition = Vector2.new(0, maxScroll)
        end
    end

    local function fitText(row)
        if row.Value.Visible then
            row.Text.Size = UDim2.new(1, -(math.ceil(row.Value.AbsoluteSize.X / window.Scale.Scale) + 12), 0, 24)
        else
            row.Text.Size = UDim2.new(1, 0, 0, 24)
        end
    end

    local function newRow(order)
        local holder = create("Frame", {
            Size = UDim2.new(1, 0, 0, 0),
            AutomaticSize = Enum.AutomaticSize.Y,
            BackgroundTransparency = 1,
            LayoutOrder = order,
            Parent = content,
        })
        local row = {
            Frame = holder,
            Text = label({
                Size = UDim2.new(1, 0, 0, 24),
                AutomaticSize = Enum.AutomaticSize.Y,
                Text = "",
                TextSize = 13,
                LineHeight = 1.1,
                FontFace = Fonts.Regular,
                TextColor3 = Theme.Muted,
                TextWrapped = true,
                TextTruncate = Enum.TextTruncate.None,
                RichText = true,
                Parent = holder,
            }),
            Value = label({
                AnchorPoint = Vector2.new(1, 0),
                Position = UDim2.new(1, 0, 0, 0),
                Size = UDim2.new(0, 0, 0, 24),
                AutomaticSize = Enum.AutomaticSize.X,
                Text = "",
                TextSize = 12,
                FontFace = Fonts.Medium,
                TextColor3 = Theme.Text,
                RichText = true,
                TextXAlignment = Enum.TextXAlignment.Right,
                TextTruncate = Enum.TextTruncate.None,
                Visible = false,
                Parent = holder,
            }),
        }
        row.Connections = {
            holder:GetPropertyChangedSignal("AbsoluteSize"):Connect(fit),
            row.Value:GetPropertyChangedSignal("AbsoluteSize"):Connect(function()
                fitText(row)
            end),
        }
        return row
    end

    local function normalizeRow(entry)
        if type(entry) == "table" then
            local text = entry.Text or entry.Name or entry[1]
            local tone = entry.Tone or entry.Color
            return {
                Text = tostring(text == nil and "" or text),
                Value = entry.Value ~= nil and tostring(entry.Value) or nil,
                Tone = (type(tone) == "string" or typeof(tone) == "Color3") and tone or nil,
            }
        end
        return { Text = tostring(entry) }
    end

    local function rowKey(entry)
        return entry.Text .. "\0" .. (entry.Value or "\1") .. "\0" .. tostring(entry.Tone or "")
    end

    -- Tone tints the value, or the text when there is no value.
    local function paint(row, entry)
        local key = rowKey(entry)
        if row.Key == key then
            return
        end
        row.Key = key
        row.Text.Text = Library._rich(entry.Text)
        local tone = entry.Tone and Library._color(entry.Tone) or nil
        if entry.Value then
            row.Value.Text = Library._rich(entry.Value)
            row.Value.Visible = true
            tween(row.Value, { TextColor3 = tone or Theme.Text }, 0)
            tween(row.Text, { TextColor3 = Theme.Muted }, 0)
        else
            row.Value.Visible = false
            tween(row.Text, { TextColor3 = tone or Theme.Muted }, 0)
        end
        fitText(row)
    end

    local function dropRow(row)
        for _, connection in ipairs(row.Connections) do
            connection:Disconnect()
        end
        row.Frame:Destroy()
    end

    function handle:Set(list)
        if type(list) ~= "table" or handle._destroyed then
            return
        end
        local nextRows, keys = {}, {}
        raw = {}
        for index, entry in ipairs(list) do
            raw[index] = type(entry) == "table" and table.clone(entry) or entry
            local row = normalizeRow(entry)
            nextRows[index] = row
            keys[index] = rowKey(row)
        end
        local nextSignature = table.concat(keys, "\2") .. "#" .. #nextRows
        if nextSignature == signature then
            return
        end
        signature = nextSignature
        rows = nextRows
        for index, entry in ipairs(rows) do
            local row = rowObjects[index]
            if not row then
                row = newRow(index)
                rowObjects[index] = row
            end
            paint(row, entry)
        end
        for index = #rowObjects, #rows + 1, -1 do
            dropRow(rowObjects[index])
            rowObjects[index] = nil
        end
        empty.Visible = #rows == 0
        fit()
    end
    function handle:Get()
        local copy = {}
        for index, entry in ipairs(raw) do
            copy[index] = type(entry) == "table" and table.clone(entry) or entry
        end
        return copy
    end
    function handle:Clear()
        handle:Set({})
    end
    function handle:SetName(text)
        text = tostring(text or "")
        heading.Text = string.upper(text)
        heading.Visible = text ~= ""
        handle._searchName = text
        handle._searchKey = string.lower(text)
    end
    local rate = math.max(tonumber(opts.UpdateRate) or 1, 0.05)
    function handle:SetUpdateRate(seconds)
        rate = math.max(tonumber(seconds) or rate, 0.05)
    end

    -- Theme tags are baked into the text, so a theme change repaints the rows.
    onTheme(content, function()
        for index, row in ipairs(rowObjects) do
            if rows[index] then
                row.Key = nil
                paint(row, rows[index])
            end
        end
    end)

    local emptyConnection = empty:GetPropertyChangedSignal("AbsoluteSize"):Connect(fit)
    table.insert(handle._listeners, function()
        handle._destroyed = true
        emptyConnection:Disconnect()
        for _, row in ipairs(rowObjects) do
            for _, connection in ipairs(row.Connections) do
                connection:Disconnect()
            end
        end
    end)

    local function onScreen()
        if window._destroyed or not window.Open or window.Minimized or not handle._userVisible then
            return false
        end
        local page = self
        if page._groupbox then
            if page._userVisible == false then
                return false
            end
            page = page.Parent
        end
        if page._isSubTab then
            if page.Parent.CurrentSubTab ~= page then
                return false
            end
            page = page.Parent
        end
        return window.CurrentTab == page
    end

    if type(opts.Update) == "function" then
        local alive = true
        table.insert(handle._listeners, function()
            alive = false
        end)
        task.defer(function()
            local first = true
            while alive and frame.Parent do
                if first or onScreen() then
                    first = false
                    local ok, result = isolatedCall(opts.Update)
                    if ok then
                        if result ~= nil then
                            handle:Set(result)
                        end
                    else
                        warn("[Aster UI] status list update error: " .. tostring(result))
                    end
                end
                task.wait(rate)
            end
        end)
    end

    handle:Set(opts.Rows or {})
    return finishElement(self, opts, handle, frame, "StatusList")
end

Tab.CreateStatus = Tab.Status
Tab.AddStatus = Tab.Status
Tab.CreateStatuses = Tab.Statuses
Tab.CreateStatusList = Tab.StatusList
Tab.AddStatusList = Tab.StatusList

function Tab:_mediaCard(opts, defaultHeight)
    opts = normalize(opts, { Title = "Name", Description = "Desc" })
    local metrics = metricsOf(self)
    local compact = metrics.Compact
    local mediaHeight = math.clamp(tonumber(opts.Height) or defaultHeight, 40, 600)
    local inset = compact and 14 or 8
    local hasHead = type(opts.Name) == "string" and opts.Name ~= ""
    local titleTop = compact and 4 or 10
    local mediaTop = hasHead and (titleTop + (opts.Desc and 38 or 22)) or (compact and 4 or inset)
    local height = mediaTop + mediaHeight + (compact and 6 or inset)
    local frame, frameStroke = card(self, "Frame", height, opts)
    hoverStroke(frame, frameStroke)
    local title, descLabel
    if hasHead then
        title = label({
            Position = UDim2.fromOffset(14, titleTop),
            Size = UDim2.new(1, -28, 0, metrics.TitleHeight),
            Text = opts.Name,
            TextSize = metrics.TextSize,
            Parent = frame,
        })
        if opts.Desc then
            descLabel = label({
                Position = UDim2.fromOffset(14, titleTop + metrics.TitleHeight + 1),
                Size = UDim2.new(1, -28, 0, metrics.DescLine),
                Text = opts.Desc,
                TextSize = metrics.DescSize,
                FontFace = Fonts.Regular,
                TextColor3 = Theme.Muted,
                Parent = frame,
            })
        end
    end
    local media = create("Frame", {
        Position = UDim2.fromOffset(inset, mediaTop),
        Size = UDim2.new(1, -inset * 2, 0, mediaHeight),
        BackgroundColor3 = Theme.Surface3,
        BackgroundTransparency = 0.5,
        BorderSizePixel = 0,
        ClipsDescendants = true,
        Parent = frame,
    })
    corner(media, UDim.new(0, 6))
    stroke(media, Theme.Stroke)
    local placeholder = create("ImageLabel", {
        AnchorPoint = Vector2.new(0.5, 0.5),
        Position = UDim2.fromScale(0.5, 0.5),
        Size = UDim2.fromOffset(22, 22),
        BackgroundTransparency = 1,
        ImageColor3 = Theme.Muted,
        ImageTransparency = 0.3,
        ScaleType = Enum.ScaleType.Fit,
        Parent = media,
    })
    -- A caption over the bottom of the picture, on a dark fade.
    local captionHolder = create("Frame", {
        AnchorPoint = Vector2.new(0, 1),
        Position = UDim2.fromScale(0, 1),
        Size = UDim2.new(1, 0, 0, 30),
        BackgroundColor3 = Color3.new(0, 0, 0),
        BackgroundTransparency = 0.35,
        BorderSizePixel = 0,
        Visible = false,
        ZIndex = 3,
        Parent = media,
    })
    create("UIGradient", {
        Rotation = 90,
        Transparency = NumberSequence.new(1, 0),
        Parent = captionHolder,
    })
    local caption = label({
        Position = UDim2.fromOffset(10, 8),
        Size = UDim2.new(1, -20, 1, -10),
        TextSize = 12,
        TextColor3 = Color3.new(1, 1, 1),
        ZIndex = 4,
        Parent = captionHolder,
    })
    local function setCaption(text)
        text = text ~= nil and tostring(text) or ""
        caption.Text = text
        captionHolder.Visible = text ~= ""
    end
    setCaption(opts.Caption)
    return opts, {
        Frame = frame,
        Stroke = frameStroke,
        Media = media,
        Placeholder = placeholder,
        Title = title,
        Desc = descLabel,
        SetCaption = setCaption,
    }
end

function Tab:Image(opts)
    local parts
    opts, parts = self:_mediaCard(opts, 160)
    local window = self.Window
    local media = parts.Media
    applyIcon(parts.Placeholder, "image")
    -- Enum lookups throw on unknown names.
    local function scaleType(name, fallback)
        local ok, value = pcall(function()
            return Enum.ScaleType[tostring(name)]
        end)
        return ok and value or fallback
    end
    local image = create("ImageLabel", {
        Size = UDim2.fromScale(1, 1),
        BackgroundTransparency = 1,
        ImageTransparency = 1,
        ScaleType = scaleType(opts.ScaleType or "Crop", Enum.ScaleType.Crop),
        ZIndex = 2,
        Parent = media,
    })
    corner(image, UDim.new(0, 6))
    if opts.Color then
        image.ImageColor3 = opts.Color
    end

    local handle = { Value = nil }
    local generation = 0

    -- Yields while a web image downloads. Returns ok, err like SetBackground.
    function handle:SetImage(source)
        generation += 1
        local current = generation
        handle.Value = source
        if source == nil or source == "" or source == "None" then
            tween(image, { ImageTransparency = 1 }, 0.2)
            tween(parts.Placeholder, { ImageTransparency = 0.3 }, 0.2)
            return true
        end
        local asset, err
        if type(source) == "number" then
            asset = "rbxassetid://" .. math.floor(source)
        elseif type(source) == "string" and ({ avatar = true, headshot = true })[source:lower()] then
            asset = "rbxthumb://type=AvatarHeadShot&id=" .. LocalPlayer.UserId .. "&w=420&h=420"
        else
            local ok, result, message = pcall(window._resolveBackground, window, tostring(source))
            if ok then
                asset, err = result, message
            else
                err = tostring(result)
            end
        end
        if generation ~= current then
            return false, "replaced by a newer image"
        end
        if not asset then
            warn("[Aster UI] image: " .. tostring(err))
            return false, err
        end
        image.ImageTransparency = 1
        image.Image = asset
        -- Fade in once it has loaded, or after a few seconds regardless.
        task.spawn(function()
            local waited = 0
            while not image.IsLoaded and waited < 4 and generation == current and image.Parent do
                waited += task.wait(0.05)
            end
            if generation == current and image.Parent then
                tween(image, { ImageTransparency = 0 }, 0.35)
                tween(parts.Placeholder, { ImageTransparency = 1 }, 0.2)
            end
        end)
        return true
    end
    handle.Set = handle.SetImage

    function handle:Get()
        return handle.Value
    end

    function handle:SetCaption(text)
        parts.SetCaption(text)
    end

    function handle:SetScaleType(name)
        image.ScaleType = scaleType(name, image.ScaleType)
    end

    function handle:SetColor(color)
        image.ImageColor3 = typeof(color) == "Color3" and color or Color3.new(1, 1, 1)
    end

    function handle:SetTitle(text)
        if parts.Title then
            parts.Title.Text = tostring(text)
        end
    end

    if opts.Image ~= nil then
        task.spawn(handle.SetImage, handle, opts.Image)
    end
    return finishElement(self, opts, handle, parts.Frame, "Image")
end

function Tab:Viewport(opts)
    local parts
    opts, parts = self:_mediaCard(opts, 180)
    local window = self.Window
    local media = parts.Media
    applyIcon(parts.Placeholder, "box")

    local viewport = create("ViewportFrame", {
        Size = UDim2.fromScale(1, 1),
        BackgroundTransparency = 1,
        ImageTransparency = 1,
        Ambient = opts.Ambient or Color3.fromRGB(165, 160, 175),
        LightColor = opts.LightColor or Color3.fromRGB(255, 250, 245),
        LightDirection = Vector3.new(-0.6, -1, -0.8),
        ZIndex = 2,
        Parent = media,
    })
    local camera = Instance.new("Camera")
    camera.FieldOfView = math.clamp(tonumber(opts.FieldOfView) or 35, 10, 90)
    camera.Parent = viewport
    viewport.CurrentCamera = camera
    local world = Instance.new("WorldModel")
    world.Parent = viewport

    local handle = {
        Model = nil,
        Spin = opts.Spin ~= false,
        SpinSpeed = tonumber(opts.SpinSpeed) or 25,
    }
    local angle = math.rad(tonumber(opts.Angle) or 0)
    local pitch = math.rad(tonumber(opts.Pitch) or 10)
    local distanceScale = tonumber(opts.Distance) or 1
    local center, distance, basis = nil, 10, CFrame.new()
    local source = nil
    local generation = 0
    local dragging, lastX, resumeAt = false, 0, 0

    local function place()
        if not center then
            return
        end
        local direction = basis:VectorToWorldSpace(Vector3.new(
            math.sin(angle) * math.cos(pitch),
            math.sin(pitch),
            -math.cos(angle) * math.cos(pitch)
        ))
        camera.CFrame = CFrame.lookAt(center + direction * distance, center)
    end

    local function fit(model)
        local cf, size
        if model:IsA("Model") then
            cf, size = model:GetBoundingBox()
            basis = model:GetPivot().Rotation
        elseif model:IsA("BasePart") then
            cf, size = model.CFrame, model.Size
            basis = model.CFrame.Rotation
        else
            return false
        end
        center = cf.Position
        local radius = math.max(size.Magnitude / 2, 0.5)
        distance = radius / math.tan(math.rad(camera.FieldOfView / 2)) * distanceScale
        place()
        return true
    end

    -- A copy with its scripts and sounds stripped and every part anchored.
    local function prepare(instance)
        local copy = instance
        if opts.Clone ~= false then
            local archivable = instance.Archivable
            pcall(function()
                instance.Archivable = true
            end)
            local ok, result = pcall(instance.Clone, instance)
            pcall(function()
                instance.Archivable = archivable
            end)
            copy = ok and result or nil
        end
        if not copy then
            return nil
        end
        local function clean(object)
            if object:IsA("LuaSourceContainer") or object:IsA("Sound") or object:IsA("ForceField") then
                object:Destroy()
            elseif object:IsA("BasePart") then
                object.Anchored = true
                object.CanCollide = false
            end
        end
        for _, object in ipairs(copy:GetDescendants()) do
            pcall(clean, object)
        end
        if copy:IsA("BasePart") then
            copy.Anchored = true
        end
        local humanoid = copy:FindFirstChildOfClass("Humanoid")
        if humanoid then
            humanoid.DisplayDistanceType = Enum.HumanoidDisplayDistanceType.None
        end
        return copy
    end

    local function resolve(value)
        if type(value) == "function" then
            local ok, result = pcall(value)
            value = ok and result or nil
        end
        if type(value) == "string" and ({ avatar = true, player = true, character = true })[value:lower()] then
            value = LocalPlayer
        end
        if typeof(value) == "Instance" and value:IsA("Player") then
            local character = value.Character
            if not character then
                character = value.CharacterAdded:Wait()
                -- Let the body parts and accessories load in.
                task.wait(0.5)
            end
            value = character
        end
        return typeof(value) == "Instance" and value or nil
    end

    -- Yields while waiting for a character to spawn.
    function handle:SetModel(value)
        generation += 1
        local current = generation
        source = value
        if handle.Model then
            handle.Model:Destroy()
            handle.Model = nil
        end
        center = nil
        if value == nil then
            tween(viewport, { ImageTransparency = 1 }, 0.2)
            tween(parts.Placeholder, { ImageTransparency = 0.3 }, 0.2)
            return true
        end
        local instance = resolve(value)
        if generation ~= current then
            return false, "replaced by a newer model"
        end
        if not instance then
            return false, "no model to show"
        end
        local copy = prepare(instance)
        if not copy then
            return false, "could not copy the model"
        end
        copy.Parent = world
        handle.Model = copy
        if not fit(copy) then
            copy:Destroy()
            handle.Model = nil
            return false, "not a Model or a part"
        end
        viewport.ImageTransparency = 1
        tween(viewport, { ImageTransparency = 0 }, 0.35)
        tween(parts.Placeholder, { ImageTransparency = 1 }, 0.2)
        return true
    end
    handle.Set = handle.SetModel

    function handle:Get()
        return handle.Model
    end

    -- Copies the source again, e.g. after the character respawned or changed.
    function handle:Refresh()
        return handle:SetModel(source)
    end

    function handle:SetSpin(enabled)
        handle.Spin = enabled ~= false
    end

    function handle:SetSpinSpeed(degrees)
        handle.SpinSpeed = tonumber(degrees) or handle.SpinSpeed
    end

    function handle:SetAngle(degrees)
        angle = math.rad(tonumber(degrees) or 0)
        place()
    end

    function handle:SetCaption(text)
        parts.SetCaption(text)
    end

    function handle:SetTitle(text)
        if parts.Title then
            parts.Title.Text = tostring(text)
        end
    end

    media.InputBegan:Connect(function(input)
        if isPress(input) and handle.Model then
            dragging = true
            lastX = pointerPosition().X
        end
    end)
    window:_listen("Changed", function(input)
        if dragging and isMove(input) then
            local x = pointerPosition().X
            angle -= (x - lastX) * 0.012
            lastX = x
            place()
        end
    end, handle)
    window:_listen("Ended", function(input)
        if dragging and isPress(input) then
            dragging = false
            resumeAt = os.clock() + 1.5
        end
    end, handle)
    window:_listen("Render", function(deltaTime)
        if handle.Spin and center and not dragging and os.clock() >= resumeAt and window.Open and not window.Minimized
            and parts.Frame.Visible then
            angle += math.rad(handle.SpinSpeed) * deltaTime
            place()
        end
    end, handle)

    if opts.Model ~= nil then
        task.spawn(handle.SetModel, handle, opts.Model)
    end
    return finishElement(self, opts, handle, parts.Frame, "Viewport")
end

function Tab:Table(opts)
    opts = normalize(opts, { Title = "Name", Description = "Desc", Data = "Rows", OnRowClick = "Callback" })
    local window = self.Window
    local metrics = metricsOf(self)
    local compact = metrics.Compact
    local rowHeight = tonumber(opts.RowHeight) or (TOUCH and 32 or 26)
    local maxRows = math.max(math.floor(tonumber(opts.MaxRows) or 8), 1)
    local headerHeight = TOUCH and 28 or 24
    local textSize = compact and 12 or 13
    local inset = compact and 14 or 8
    local hasHead = type(opts.Name) == "string" and opts.Name ~= ""
    local titleTop = compact and 4 or 10
    local searchable = opts.Search ~= false
    local searchHeight = TOUCH and 30 or 26
    local searchTop = hasHead and (titleTop + (opts.Desc and 38 or 22)) or (compact and 4 or inset)
    local gridTop = searchTop + (searchable and searchHeight + 6 or 0)
    local bottom = compact and 6 or inset

    local frame, frameStroke = card(self, "Frame", gridTop + headerHeight + rowHeight + bottom, opts)
    hoverStroke(frame, frameStroke)
    local title
    if hasHead then
        title = label({
            Position = UDim2.fromOffset(14, titleTop),
            Size = UDim2.new(1, -28, 0, metrics.TitleHeight),
            Text = opts.Name,
            TextSize = metrics.TextSize,
            Parent = frame,
        })
        if opts.Desc then
            label({
                Position = UDim2.fromOffset(14, titleTop + metrics.TitleHeight + 1),
                Size = UDim2.new(1, -28, 0, metrics.DescLine),
                Text = opts.Desc,
                TextSize = metrics.DescSize,
                FontFace = Fonts.Regular,
                TextColor3 = Theme.Muted,
                Parent = frame,
            })
        end
    end
    local query = ""
    local searchBox, searchCount
    if searchable then
        local holder = create("Frame", {
            Position = UDim2.fromOffset(inset, searchTop),
            Size = UDim2.new(1, -inset * 2, 0, searchHeight),
            BackgroundColor3 = Theme.Surface,
            BorderSizePixel = 0,
            Parent = frame,
        })
        holder:SetAttribute("NoDrag", true)
        corner(holder, UDim.new(0, 6))
        local searchStroke = stroke(holder)
        local iconHolder, searchIcon = glowIcon(holder, "search", Theme.Muted, UDim2.new(0, 9, 0.5, 0))
        iconHolder.Size = UDim2.fromOffset(13, 13)
        searchCount = label({
            AnchorPoint = Vector2.new(1, 0),
            Position = UDim2.new(1, -9, 0, 0),
            Size = UDim2.new(0, 0, 1, 0),
            AutomaticSize = Enum.AutomaticSize.X,
            Text = "",
            TextSize = 11,
            FontFace = Fonts.Regular,
            TextColor3 = Theme.Muted,
            TextTruncate = Enum.TextTruncate.None,
            Visible = false,
            Parent = holder,
        })
        searchBox = create("TextBox", {
            Position = UDim2.fromOffset(29, 0),
            Size = UDim2.new(1, -90, 1, 0),
            BackgroundTransparency = 1,
            Text = "",
            PlaceholderText = opts.SearchPlaceholder or "Search",
            PlaceholderColor3 = Theme.Muted,
            TextColor3 = Theme.Text,
            TextSize = 12,
            FontFace = Fonts.Regular,
            TextXAlignment = Enum.TextXAlignment.Left,
            TextTruncate = Enum.TextTruncate.AtEnd,
            ClearTextOnFocus = false,
            Parent = holder,
        })
        searchBox.Focused:Connect(function()
            tween(searchStroke, { Color = Theme.StrokeHover }, 0.15)
            tween(searchIcon, { ImageColor3 = Theme.Accent }, 0.15)
        end)
        searchBox.FocusLost:Connect(function()
            tween(searchStroke, { Color = Theme.Stroke }, 0.2)
            tween(searchIcon, { ImageColor3 = Theme.Muted }, 0.2)
        end)
    end

    local grid = create("Frame", {
        Position = UDim2.fromOffset(inset, gridTop),
        Size = UDim2.new(1, -inset * 2, 0, headerHeight + rowHeight),
        BackgroundColor3 = Theme.Surface,
        BackgroundTransparency = 0.2,
        BorderSizePixel = 0,
        ClipsDescendants = true,
        Parent = frame,
    })
    corner(grid, UDim.new(0, 6))
    stroke(grid, Theme.Stroke)
    local header = create("Frame", {
        Size = UDim2.new(1, 0, 0, headerHeight),
        BackgroundColor3 = Theme.Surface3,
        BackgroundTransparency = 0.45,
        BorderSizePixel = 0,
        Parent = grid,
    })
    create("Frame", {
        AnchorPoint = Vector2.new(0, 1),
        Position = UDim2.fromScale(0, 1),
        Size = UDim2.new(1, 0, 0, 1),
        BackgroundColor3 = Theme.Stroke,
        BorderSizePixel = 0,
        Parent = header,
    })
    local body = create("ScrollingFrame", {
        Position = UDim2.fromOffset(0, headerHeight),
        Size = UDim2.new(1, 0, 1, -headerHeight),
        BackgroundTransparency = 1,
        BorderSizePixel = 0,
        ScrollBarThickness = 2,
        ScrollBarImageColor3 = Theme.Accent,
        ScrollBarImageTransparency = 0.4,
        ScrollingDirection = Enum.ScrollingDirection.Y,
        AutomaticCanvasSize = Enum.AutomaticSize.Y,
        CanvasSize = UDim2.new(),
        Parent = grid,
    })
    create("UIListLayout", {
        SortOrder = Enum.SortOrder.LayoutOrder,
        Parent = body,
    })
    local empty = label({
        Position = UDim2.fromOffset(0, headerHeight),
        Size = UDim2.new(1, 0, 0, rowHeight),
        Text = opts.EmptyText or "Nothing here yet",
        TextSize = 12,
        FontFace = Fonts.Regular,
        TextColor3 = Theme.Muted,
        TextXAlignment = Enum.TextXAlignment.Center,
        Parent = grid,
    })

    local handle = { Rows = {} }
    local shownCount = nil
    local columns, headerCells = {}, {}
    local pool = {}
    local sortKey, sortDescending = nil, false
    local shownHeight = nil
    local MEDALS = {
        Color3.fromRGB(245, 200, 90),
        Color3.fromRGB(200, 206, 218),
        Color3.fromRGB(214, 146, 96),
    }

    local function alignment(column)
        local align = type(column.Align) == "string" and column.Align:lower() or nil
        if align == "right" then
            return Enum.TextXAlignment.Right
        elseif align == "center" or align == "centre" then
            return Enum.TextXAlignment.Center
        end
        return Enum.TextXAlignment.Left
    end

    local function layoutColumns()
        local pixels, shares, autos = 0, 0, 0
        for _, column in ipairs(columns) do
            local width = tonumber(column.Width)
            if width and width > 1 then
                pixels += width
            elseif width and width > 0 then
                shares += width
            else
                autos += 1
            end
        end
        local left = math.max(1 - shares, 0)
        for _, column in ipairs(columns) do
            local width = tonumber(column.Width)
            local share
            if width and width > 1 then
                column.UDim = UDim.new(0, width)
            else
                share = (width and width > 0) and width or (autos > 0 and left / autos or 0)
                column.UDim = UDim.new(share, -pixels * share)
            end
        end
    end

    local function columnValue(row, column)
        if column.Rank then
            return nil
        end
        if row[1] ~= nil or column.Key == nil then
            return row[column.Index]
        end
        return row[column.Key]
    end

    local function display(value, column, row)
        if type(column.Format) == "function" then
            local ok, text = pcall(column.Format, value, row)
            if ok and text ~= nil then
                return tostring(text)
            end
        end
        if type(value) == "number" then
            local whole = value == math.floor(value)
            local text = whole and string.format("%d", value) or string.format("%.2f", value)
            -- Thousands separators on the whole part.
            local sign, int, rest = text:match("^(%-?)(%d+)(.*)$")
            if int then
                int = int:reverse():gsub("(%d%d%d)", "%1,"):reverse():gsub("^,", "")
                return sign .. int .. rest
            end
            return text
        end
        if value == nil then
            return ""
        end
        return tostring(value)
    end

    local function paintHeader()
        for _, cell in ipairs(headerCells) do
            local column = cell.Column
            local active = sortKey ~= nil and sortKey == column
            tween(cell.Label, { TextColor3 = active and Theme.Text or Theme.Muted }, 0.15)
            cell.Arrow.Visible = active
            if active then
                tween(cell.Arrow, { Rotation = sortDescending and 0 or 180 }, 0.2, Enum.EasingStyle.Quint)
            end
        end
    end

    local function sortedRows()
        local list = {}
        for index, row in ipairs(handle.Rows) do
            list[index] = { Row = row, Index = index }
        end
        if sortKey then
            local column = sortKey
            table.sort(list, function(a, b)
                local x, y = columnValue(a.Row, column), columnValue(b.Row, column)
                local nx, ny = tonumber(x), tonumber(y)
                if nx and ny then
                    if nx ~= ny then
                        if sortDescending then
                            return nx > ny
                        end
                        return nx < ny
                    end
                elseif x ~= nil and y ~= nil then
                    local sx, sy = string.lower(tostring(x)), string.lower(tostring(y))
                    if sx ~= sy then
                        if sortDescending then
                            return sx > sy
                        end
                        return sx < sy
                    end
                elseif x ~= y then
                    -- Empty cells sink to the bottom either way.
                    return x ~= nil
                end
                return a.Index < b.Index
            end)
        end
        -- Ranks come from the full order, so filtering never renumbers them.
        for position, item in ipairs(list) do
            item.Rank = position
        end
        if query == "" then
            return list
        end
        local shown = {}
        for _, item in ipairs(list) do
            for _, column in ipairs(columns) do
                if not column.Rank then
                    local text = display(columnValue(item.Row, column), column, item.Row)
                    text = string.lower((string.gsub(text, "<[^>]->", "")))
                    if string.find(text, query, 1, true) then
                        table.insert(shown, item)
                        break
                    end
                end
            end
        end
        return shown
    end

    local function newRow()
        local rowFrame = create("TextButton", {
            Size = UDim2.new(1, 0, 0, rowHeight),
            BackgroundColor3 = Theme.Surface3,
            BackgroundTransparency = 1,
            BorderSizePixel = 0,
            AutoButtonColor = false,
            Text = "",
            Parent = body,
        })
        local marker = create("Frame", {
            Position = UDim2.new(0, 3, 0.5, 0),
            AnchorPoint = Vector2.new(0, 0.5),
            Size = UDim2.new(0, 2, 1, -10),
            BackgroundColor3 = Theme.Accent,
            BackgroundTransparency = 1,
            BorderSizePixel = 0,
            Parent = rowFrame,
        })
        corner(marker, UDim.new(1, 0))
        local cellsFrame = create("Frame", {
            Size = UDim2.fromScale(1, 1),
            BackgroundTransparency = 1,
            Parent = rowFrame,
        })
        padding(cellsFrame, 10, 10)
        create("UIListLayout", {
            FillDirection = Enum.FillDirection.Horizontal,
            VerticalAlignment = Enum.VerticalAlignment.Center,
            SortOrder = Enum.SortOrder.LayoutOrder,
            Parent = cellsFrame,
        })
        local entry = { Frame = rowFrame, Marker = marker, Cells = {}, Hover = false }
        for order, column in ipairs(columns) do
            local cell = create("Frame", {
                Size = UDim2.new(column.UDim.Scale, column.UDim.Offset, 1, 0),
                BackgroundTransparency = 1,
                LayoutOrder = order,
                Parent = cellsFrame,
            })
            local text = label({
                Size = UDim2.new(1, -6, 1, 0),
                TextSize = textSize,
                FontFace = column.Rank and Fonts.Bold or Fonts.Regular,
                TextColor3 = Theme.Text,
                TextXAlignment = alignment(column),
                RichText = not column.Rank,
                Parent = cell,
            })
            local badge
            if column.Rank then
                text.Size = UDim2.fromScale(1, 1)
                text.TextXAlignment = Enum.TextXAlignment.Center
                badge = create("Frame", {
                    AnchorPoint = Vector2.new(0.5, 0.5),
                    Position = UDim2.fromScale(0.5, 0.5),
                    Size = UDim2.fromOffset(rowHeight - 8, rowHeight - 8),
                    BackgroundTransparency = 1,
                    BorderSizePixel = 0,
                    ZIndex = 0,
                    Parent = cell,
                })
                corner(badge, UDim.new(1, 0))
            end
            entry.Cells[order] = { Label = text, Badge = badge }
        end
        local canTap = tapGuard(rowFrame, function()
            return body
        end)
        rowFrame.MouseEnter:Connect(function()
            entry.Hover = true
            tween(rowFrame, { BackgroundTransparency = 0.35 }, 0.1)
        end)
        rowFrame.MouseLeave:Connect(function()
            entry.Hover = false
            tween(rowFrame, {
                BackgroundColor3 = entry.Highlighted and Theme.Accent or Theme.Surface3,
                BackgroundTransparency = entry.Rest or 1,
            }, 0.2)
        end)
        rowFrame.MouseButton1Click:Connect(function()
            if entry.Data and canTap() then
                safeCall(opts.Callback, entry.Data, entry.Index)
            end
        end)
        return entry
    end

    local function fitHeight(instant)
        local count = shownCount or #handle.Rows
        local visible = math.clamp(count, 1, maxRows)
        local gridHeight = headerHeight + visible * rowHeight
        local total = gridTop + gridHeight + bottom
        if shownHeight == total then
            return
        end
        local duration = (instant or shownHeight == nil) and 0 or 0.25
        shownHeight = total
        tween(grid, { Size = UDim2.new(1, -inset * 2, 0, gridHeight) }, duration, Enum.EasingStyle.Quint)
        tween(frame, { Size = UDim2.new(1, 0, 0, total) }, duration, Enum.EasingStyle.Quint)
    end

    local function render()
        local list = sortedRows()
        for position, item in ipairs(list) do
            local entry = pool[position]
            if not entry then
                entry = newRow()
                pool[position] = entry
            end
            local row = item.Row
            entry.Data = row
            entry.Index = item.Index
            entry.Frame.LayoutOrder = position
            entry.Frame.Visible = true
            local highlighted = row.Highlight == true
            if not highlighted and type(opts.Highlight) == "function" then
                local ok, result = pcall(opts.Highlight, row, item.Index)
                highlighted = ok and result == true
            end
            entry.Highlighted = highlighted
            entry.Rest = highlighted and 0.86 or (position % 2 == 0 and 0.78 or 1)
            if not entry.Hover then
                entry.Frame.BackgroundColor3 = highlighted and Theme.Accent or Theme.Surface3
                entry.Frame.BackgroundTransparency = entry.Rest
                bindColors(entry.Frame, { BackgroundColor3 = entry.Frame.BackgroundColor3 })
            end
            entry.Marker.BackgroundTransparency = highlighted and 0 or 1
            for order, column in ipairs(columns) do
                local cell = entry.Cells[order]
                if column.Rank then
                    local medal = MEDALS[item.Rank]
                    cell.Label.Text = tostring(item.Rank)
                    cell.Label.TextColor3 = medal and Color3.fromRGB(28, 22, 18) or Theme.Muted
                    bindColors(cell.Label, { TextColor3 = cell.Label.TextColor3 })
                    cell.Badge.BackgroundColor3 = medal or Theme.Surface3
                    cell.Badge.BackgroundTransparency = medal and 0.05 or 1
                else
                    local value = columnValue(row, column)
                    cell.Label.Text = Library._rich(display(value, column, row))
                    local wanted = column.Color
                    if type(wanted) == "function" then
                        local ok, result = pcall(wanted, value, row)
                        wanted = ok and result or nil
                    end
                    if type(row.Colors) == "table" then
                        local own = row.Colors[column.Key or column.Index]
                        if own == nil then
                            own = row.Colors[column.Index]
                        end
                        if own ~= nil then
                            wanted = own
                        end
                    end
                    local color = Library._color(wanted) or (highlighted and Theme.Accent or Theme.Text)
                    cell.Label.TextColor3 = color
                    bindColors(cell.Label, { TextColor3 = color })
                end
            end
        end
        for position = #list + 1, #pool do
            pool[position].Frame.Visible = false
            pool[position].Data = nil
        end
        shownCount = #list
        empty.Visible = #list == 0
        empty.Text = (#list == 0 and query ~= "" and #handle.Rows > 0) and (opts.NoMatchText or "No rows match")
            or (opts.EmptyText or "Nothing here yet")
        if searchCount then
            searchCount.Visible = query ~= ""
            searchCount.Text = #list .. " / " .. #handle.Rows
        end
        fitHeight()
    end

    local function buildHeader()
        for _, cell in ipairs(headerCells) do
            cell.Frame:Destroy()
        end
        table.clear(headerCells)
        for _, entry in ipairs(pool) do
            entry.Frame:Destroy()
        end
        table.clear(pool)
        local row = header:FindFirstChild("Cells") or create("Frame", {
            Name = "Cells",
            Size = UDim2.fromScale(1, 1),
            BackgroundTransparency = 1,
            Parent = header,
        })
        if not row:FindFirstChildOfClass("UIListLayout") then
            padding(row, 10, 10)
            create("UIListLayout", {
                FillDirection = Enum.FillDirection.Horizontal,
                VerticalAlignment = Enum.VerticalAlignment.Center,
                SortOrder = Enum.SortOrder.LayoutOrder,
                Parent = row,
            })
        end
        for order, column in ipairs(columns) do
            local cell = create("TextButton", {
                Size = UDim2.new(column.UDim.Scale, column.UDim.Offset, 1, 0),
                BackgroundTransparency = 1,
                AutoButtonColor = false,
                Text = "",
                LayoutOrder = order,
                Parent = row,
            })
            local align = column.Rank and Enum.TextXAlignment.Center or alignment(column)
            local right = align == Enum.TextXAlignment.Right
            local text = label({
                Size = UDim2.new(1, align == Enum.TextXAlignment.Center and 0 or -16, 1, 0),
                Position = UDim2.fromOffset(right and 16 or 0, 0),
                Text = string.upper(column.Name),
                TextSize = 11,
                FontFace = Fonts.Bold,
                TextColor3 = Theme.Muted,
                TextXAlignment = align,
                Parent = cell,
            })
            local arrow = create("ImageLabel", {
                AnchorPoint = Vector2.new(0, 0.5),
                Position = UDim2.new(0, 0, 0.5, 0),
                Size = UDim2.fromOffset(12, 12),
                BackgroundTransparency = 1,
                ImageColor3 = Theme.Accent,
                ScaleType = Enum.ScaleType.Fit,
                Visible = false,
                Parent = cell,
            })
            applyIcon(arrow, "chevron-down")
            local function placeArrow()
                local width = text.TextBounds.X
                if right then
                    arrow.Position = UDim2.new(1, -(width + 15), 0.5, 0)
                elseif align == Enum.TextXAlignment.Center then
                    arrow.Position = UDim2.new(0.5, width / 2 + 3, 0.5, 0)
                else
                    local cellWidth = cell.AbsoluteSize.X / math.max(window.Scale.Scale, 0.01)
                    arrow.Position = UDim2.new(0, math.clamp(width + 4, 0, math.max(cellWidth - 12, 0)), 0.5, 0)
                end
            end
            text:GetPropertyChangedSignal("TextBounds"):Connect(placeArrow)
            cell:GetPropertyChangedSignal("AbsoluteSize"):Connect(placeArrow)
            task.defer(placeArrow)
            local sortable = column.Sortable and not column.Rank
            if sortable then
                cell.MouseEnter:Connect(function()
                    if sortKey ~= column then
                        tween(text, { TextColor3 = Theme.Text }, 0.12)
                    end
                end)
                cell.MouseLeave:Connect(function()
                    if sortKey ~= column then
                        tween(text, { TextColor3 = Theme.Muted }, 0.2)
                    end
                end)
                cell.MouseButton1Click:Connect(function()
                    if sortKey ~= column then
                        local numeric = false
                        for _, data in ipairs(handle.Rows) do
                            local value = columnValue(data, column)
                            if value ~= nil then
                                numeric = tonumber(value) ~= nil
                                break
                            end
                        end
                        sortKey, sortDescending = column, numeric
                        column.FirstDescending = numeric
                    elseif sortDescending == column.FirstDescending then
                        sortDescending = not sortDescending
                    else
                        sortKey = nil
                    end
                    paintHeader()
                    render()
                end)
            end
            table.insert(headerCells, { Frame = cell, Label = text, Arrow = arrow, Column = column })
        end
        paintHeader()
    end

    function handle:SetColumns(list)
        table.clear(columns)
        if opts.Rank then
            table.insert(columns, { Name = "#", Rank = true, Width = TOUCH and 40 or 36, Sortable = false })
        end
        for index, column in ipairs(type(list) == "table" and list or {}) do
            if type(column) ~= "table" then
                column = { Name = tostring(column) }
            end
            local name = column.Name or column.Title or ("Column " .. index)
            table.insert(columns, {
                Name = name,
                Key = column.Key or name,
                Index = index,
                Width = column.Width,
                Align = column.Align,
                Format = column.Format,
                Color = column.Color,
                Sortable = column.Sortable ~= false and opts.Sortable ~= false,
            })
        end
        sortKey = nil
        layoutColumns()
        buildHeader()
        render()
    end

    local function findColumn(key)
        if type(key) == "number" then
            return columns[key + (opts.Rank and 1 or 0)]
        end
        for _, column in ipairs(columns) do
            if not column.Rank and (column.Key == key or column.Name == key) then
                return column
            end
        end
        return nil
    end

    function handle:SetRows(rows)
        handle.Rows = {}
        for index, row in ipairs(type(rows) == "table" and rows or {}) do
            handle.Rows[index] = type(row) == "table" and row or { row }
        end
        render()
    end
    handle.Set = handle.SetRows

    function handle:GetRows()
        return handle.Rows
    end
    handle.Get = handle.GetRows

    function handle:AddRow(row, position)
        row = type(row) == "table" and row or { row }
        if tonumber(position) then
            table.insert(handle.Rows, math.clamp(math.floor(position), 1, #handle.Rows + 1), row)
        else
            table.insert(handle.Rows, row)
        end
        render()
        return #handle.Rows
    end

    -- Replaces a row (by its index in the list you gave) and flashes it.
    function handle:UpdateRow(index, row)
        if not handle.Rows[index] then
            return false
        end
        handle.Rows[index] = type(row) == "table" and row or { row }
        render()
        for _, entry in ipairs(pool) do
            if entry.Index == index and entry.Frame.Visible then
                local restColor = entry.Highlighted and Theme.Accent or Theme.Surface3
                tween(entry.Frame, { BackgroundColor3 = Theme.Accent, BackgroundTransparency = 0.7 }, 0.08)
                task.delay(0.1, function()
                    if not entry.Hover then
                        tween(entry.Frame, { BackgroundColor3 = restColor, BackgroundTransparency = entry.Rest }, 0.5)
                    end
                end)
                break
            end
        end
        return true
    end

    function handle:RemoveRow(index)
        if not handle.Rows[index] then
            return false
        end
        table.remove(handle.Rows, index)
        render()
        return true
    end

    function handle:Clear()
        handle:SetRows({})
    end

    -- Sort(nil) goes back to the given order.
    function handle:Sort(key, descending)
        sortKey = key ~= nil and findColumn(key) or nil
        sortDescending = descending == true
        if sortKey then
            sortKey.FirstDescending = sortDescending
        end
        paintHeader()
        render()
    end

    function handle:SetTitle(text)
        if title then
            title.Text = tostring(text)
        end
    end

    function handle:SetMaxRows(count)
        maxRows = math.max(math.floor(tonumber(count) or maxRows), 1)
        fitHeight()
    end

    handle:SetColumns(opts.Columns or {})
    handle:SetRows(opts.Rows or {})
    if opts.SortBy ~= nil then
        handle:Sort(opts.SortBy, opts.SortDescending ~= false)
    end
    fitHeight(true)
    if searchBox then
        searchBox:GetPropertyChangedSignal("Text"):Connect(function()
            local text = string.lower(trim(searchBox.Text))
            if text ~= query then
                query = text
                body.CanvasPosition = Vector2.zero
                render()
            end
        end)
    end
    function handle:SetSearch(text)
        if searchBox then
            searchBox.Text = tostring(text or "")
        end
    end
    -- Theme tags in cells are baked to colours; repaint them on theme change.
    onTheme(grid, render)
    return finishElement(self, opts, handle, frame, "Table")
end

Tab.CreateImage = Tab.Image
Tab.AddImage = Tab.Image
Tab.CreateViewport = Tab.Viewport
Tab.AddViewport = Tab.Viewport
Tab.CreateTable = Tab.Table
Tab.AddTable = Tab.Table
Tab.CreateLeaderboard = Tab.Table

local function settleSubOut(ui)
    if ui.OutFrame then
        ui.OutFrame.Parent = ui.Area
        ui.OutFrame.Visible = false
        ui.OutFrame = nil
    end
    ui.Out.Visible = false
end

local function settleSubIn(ui)
    if ui.InFrame then
        ui.InFrame.Parent = ui.Area
        ui.InFrame.Position = UDim2.fromOffset(0, 0)
        ui.InFrame = nil
    end
    ui.In.Visible = false
end

function Tab:_setupSubTabs()
    local top = self._headerBottom
    local page = self._page
    local strip = create("ScrollingFrame", {
        Name = "SubTabs",
        Position = UDim2.fromOffset(24, top - 4),
        Size = UDim2.new(1, -48, 0, 32),
        BackgroundTransparency = 1,
        BorderSizePixel = 0,
        ScrollBarThickness = 0,
        ScrollingDirection = Enum.ScrollingDirection.X,
        AutomaticCanvasSize = Enum.AutomaticSize.X,
        CanvasSize = UDim2.new(),
        Parent = page,
    })
    strip:SetAttribute("NoDrag", true)
    local highlight = create("Frame", {
        Size = UDim2.fromOffset(0, 32),
        BackgroundColor3 = Theme.Surface3,
        BackgroundTransparency = 0.35,
        BorderSizePixel = 0,
        Visible = false,
        Parent = strip,
    })
    corner(highlight, UDim.new(0, 8))
    stroke(highlight, Theme.Stroke)
    local row = create("Frame", {
        Size = UDim2.new(0, 0, 1, 0),
        AutomaticSize = Enum.AutomaticSize.X,
        BackgroundTransparency = 1,
        ZIndex = 2,
        Parent = strip,
    })
    create("UIListLayout", {
        FillDirection = Enum.FillDirection.Horizontal,
        VerticalAlignment = Enum.VerticalAlignment.Center,
        SortOrder = Enum.SortOrder.LayoutOrder,
        Padding = UDim.new(0, 4),
        Parent = row,
    })
    self.Window:_overflowHint(page, strip, row, false, Theme.Background)
    local areaTop = top + 36
    local area = create("Frame", {
        Name = "SubPages",
        Position = UDim2.fromOffset(0, areaTop),
        Size = UDim2.new(1, 0, 1, -areaTop),
        BackgroundTransparency = 1,
        ClipsDescendants = true,
        Parent = page,
    })
    local ui = {
        Strip = strip,
        Row = row,
        Highlight = highlight,
        Area = area,
        Out = create("CanvasGroup", {
            Size = UDim2.fromScale(1, 1),
            BackgroundTransparency = 1,
            Visible = false,
            ZIndex = 2,
            Parent = area,
        }),
        In = create("CanvasGroup", {
            Size = UDim2.fromScale(1, 1),
            BackgroundTransparency = 1,
            Visible = false,
            ZIndex = 3,
            Parent = area,
        }),
        Generation = 0,
    }
    self._sub = ui
    self._subTabs = {}
    self.List.Visible = false
    self:_refreshEmpty()
    -- Keep the pill under the selected tab when widths change after layout.
    row:GetPropertyChangedSignal("AbsoluteSize"):Connect(function()
        if self.CurrentSubTab and not ui.Moving then
            self:_placeSubHighlight(self.CurrentSubTab, true)
        end
    end)
end

function Tab:_placeSubHighlight(sub, instant)
    local ui = self._sub
    local scale = self.Window.Scale.Scale
    local button = sub._button
    local width = button.AbsoluteSize.X / scale
    if width <= 0 then
        return
    end
    local x = (button.AbsolutePosition.X - ui.Row.AbsolutePosition.X) / scale
    local props = { Position = UDim2.fromOffset(x, 0), Size = UDim2.fromOffset(width, 32) }
    if instant or not ui.Highlight.Visible then
        ui.Highlight.Visible = true
        ui.Highlight.Position = props.Position
        ui.Highlight.Size = props.Size
    else
        ui.Moving = true
        tween(ui.Highlight, props, 0.35, Enum.EasingStyle.Quint)
        task.delay(0.36, function()
            ui.Moving = false
        end)
    end
    local view = ui.Strip.AbsoluteSize.X / scale
    local canvasX = ui.Strip.CanvasPosition.X
    if x < canvasX then
        tween(ui.Strip, { CanvasPosition = Vector2.new(math.max(x - 8, 0), 0) }, 0.3, Enum.EasingStyle.Quint)
    elseif x + width > canvasX + view then
        tween(ui.Strip, { CanvasPosition = Vector2.new(x + width - view + 8, 0) }, 0.3, Enum.EasingStyle.Quint)
    end
end

function Tab:SubTab(opts, icon)
    if self._groupbox or self._isSubTab then
        return self.Parent:SubTab(opts, icon)
    end
    opts = normalize(opts, { Title = "Name", Description = "Desc" })
    if icon ~= nil and opts.Icon == nil then
        opts.Icon = cleanIcon(icon)
    end
    if not self._subTabs then
        self:_setupSubTabs()
    end
    local ui = self._sub
    local index = #self._subTabs + 1
    local sub = setmetatable({
        Name = opts.Name or ("Page " .. index),
        Window = self.Window,
        Parent = self,
        _order = 0,
        _isSubTab = true,
        _index = index,
        _iconName = opts.Icon,
    }, Tab)
    local frame = create("Frame", {
        Name = sub.Name,
        Size = UDim2.fromScale(1, 1),
        BackgroundTransparency = 1,
        Visible = false,
        Parent = ui.Area,
    })
    sub._frame = frame
    local emptyIcon = opts.Icon
    if emptyIcon == nil then
        emptyIcon = self._iconName
    end
    if emptyIcon == nil then
        emptyIcon = "layout-grid"
    end
    buildContainer(sub, frame, 0, emptyIcon, opts.EmptyText or "Nothing here yet")

    local button = create("TextButton", {
        Size = UDim2.new(0, 0, 1, 0),
        AutomaticSize = Enum.AutomaticSize.X,
        BackgroundTransparency = 1,
        Text = "",
        AutoButtonColor = false,
        LayoutOrder = index,
        Parent = ui.Row,
    })
    padding(button, 14, 14)
    create("UIListLayout", {
        FillDirection = Enum.FillDirection.Horizontal,
        VerticalAlignment = Enum.VerticalAlignment.Center,
        SortOrder = Enum.SortOrder.LayoutOrder,
        Padding = UDim.new(0, 6),
        Parent = button,
    })
    if opts.Icon then
        local image = create("ImageLabel", {
            Size = UDim2.fromOffset(14, 14),
            BackgroundTransparency = 1,
            ImageColor3 = Theme.Muted,
            ScaleType = Enum.ScaleType.Fit,
            LayoutOrder = 1,
            Parent = button,
        })
        applyIcon(image, opts.Icon)
        if image:GetAttribute("CustomIcon") then
            image.ImageTransparency = 0.4
        end
        sub._iconImage = image
    end
    sub._label = label({
        Size = UDim2.new(0, 0, 1, 0),
        AutomaticSize = Enum.AutomaticSize.X,
        Text = sub.Name,
        TextSize = 13,
        TextColor3 = Theme.Muted,
        TextTruncate = Enum.TextTruncate.None,
        LayoutOrder = 2,
        Parent = button,
    })
    sub._button = button
    button.MouseEnter:Connect(function()
        if self.CurrentSubTab ~= sub then
            tween(sub._label, { TextColor3 = Theme.Text }, 0.12)
        end
    end)
    button.MouseLeave:Connect(function()
        if self.CurrentSubTab ~= sub then
            tween(sub._label, { TextColor3 = Theme.Muted }, 0.2)
        end
    end)
    button.MouseButton1Click:Connect(function()
        self:SelectSubTab(sub)
    end)

    table.insert(self._subTabs, sub)
    if index == 1 then
        self:SelectSubTab(sub, true)
    end
    return sub
end

Tab.CreateSubTab = Tab.SubTab
Tab.AddSubTab = Tab.SubTab

function Tab:SelectSubTab(sub, instant)
    if type(sub) ~= "table" then
        for index, entry in ipairs(self._subTabs or {}) do
            if entry.Name == sub or index == sub then
                sub = entry
                break
            end
        end
    end
    if type(sub) ~= "table" or not self._sub then
        return
    end
    local previous = self.CurrentSubTab
    if previous == sub then
        return
    end
    self.Window:_resetSearch()
    self.Window:_closePopups()
    self.CurrentSubTab = sub
    local ui = self._sub
    settleSubOut(ui)
    settleSubIn(ui)
    ui.Generation += 1
    local generation = ui.Generation

    local fade = instant and 0 or 0.2
    if previous then
        tween(previous._label, { TextColor3 = Theme.Muted }, fade)
        if previous._iconImage then
            tintIcon(previous._iconImage, Theme.Muted, false, fade)
        end
    end
    tween(sub._label, { TextColor3 = Theme.Text }, fade)
    if sub._iconImage then
        tintIcon(sub._iconImage, Theme.Accent, true, fade)
    end
    self:_placeSubHighlight(sub, instant)

    if instant or not previous then
        if previous then
            previous._frame.Visible = false
        end
        sub._frame.Visible = true
        return
    end

    local direction = sub._index > previous._index and 1 or -1
    ui.OutFrame = previous._frame
    previous._frame.Parent = ui.Out
    ui.Out.GroupTransparency = 0
    ui.Out.Position = UDim2.fromOffset(0, 0)
    ui.Out.Visible = true
    tween(ui.Out, { GroupTransparency = 1, Position = UDim2.fromOffset(-direction * 28, 0) }, 0.2)

    ui.InFrame = sub._frame
    sub._frame.Visible = true
    sub._frame.Parent = ui.In
    ui.In.GroupTransparency = 1
    ui.In.Position = UDim2.fromOffset(direction * 28, 0)
    ui.In.Visible = true
    tween(ui.In, { GroupTransparency = 0, Position = UDim2.fromOffset(0, 0) }, 0.34, Enum.EasingStyle.Quint)

    task.delay(0.2, function()
        if ui.Generation == generation then
            settleSubOut(ui)
        end
    end)
    task.delay(0.34, function()
        if ui.Generation == generation then
            settleSubIn(ui)
        end
    end)
end

Window._searchIcons = {
    Tab = "app-window",
    Page = "panels-top-left",
    Groupbox = "layout-grid",
    Button = "mouse-pointer-click",
    ButtonRow = "mouse-pointer-click",
    Toggle = "toggle-right",
    Slider = "sliders-horizontal",
    Dropdown = "list",
    Input = "text-cursor-input",
    Keybind = "keyboard",
    ColorPicker = "palette",
    Stepper = "chevrons-up-down",
    Progress = "activity",
    Status = "activity",
    StatusList = "activity",
    Label = "type",
    Paragraph = "type",
    OrderList = "list-ordered",
}

function Window:_searchResults(query)
    local results = {}
    local function consider(name, entry)
        if type(name) ~= "string" or name == "" then
            return
        end
        local at = string.find(string.lower(name), query, 1, true)
        if not at then
            return
        end
        entry.Name = name
        entry.At = at
        -- Name starts first, then word starts, then anywhere inside a word.
        entry.Rank = at == 1 and 0 or (string.find(string.sub(name, at - 1, at - 1), "[%s%p]") and 1 or 2)
        entry.Order = #results + 1
        table.insert(results, entry)
    end
    local function shown(element)
        return not element._destroyed
            and element._type ~= "Section" and element._type ~= "Divider"
            and (element._isShown == nil or element:_isShown())
    end
    for _, tab in ipairs(self.Tabs) do
        consider(tab.Name, { Kind = "Tab", Tab = tab, Icon = tab._iconName })
        for _, page in ipairs(tab._subTabs or { tab }) do
            local sub = page._isSubTab and page or nil
            local path = tab.Name
            if sub then
                consider(sub.Name, { Kind = "Page", Tab = tab, Sub = sub, Path = tab.Name })
                path = tab.Name .. "  ›  " .. sub.Name
            end
            if not page._noSearch then
                for _, element in ipairs(page._items or {}) do
                    if shown(element) then
                        consider(element._searchName, { Kind = element._type, Tab = tab, Sub = sub, Target = element, Path = path })
                    end
                end
                for _, group in ipairs(page._groupboxes or {}) do
                    if group._userVisible ~= false then
                        consider(group.Name, { Kind = "Groupbox", Tab = tab, Sub = sub, Target = group, Path = path })
                        local groupPath = path .. "  ›  " .. group.Name
                        for _, element in ipairs(group._items) do
                            if shown(element) then
                                consider(element._searchName, { Kind = element._type, Tab = tab, Sub = sub, Target = element, Group = group, Path = groupPath })
                            end
                        end
                    end
                end
            end
        end
    end
    table.sort(results, function(a, b)
        if a.Rank ~= b.Rank then
            return a.Rank < b.Rank
        end
        return a.Order < b.Order
    end)
    return results
end

function Window:_flash(frame, radius)
    for _, name in ipairs({ "SearchFlash", "SearchGlow" }) do
        local old = frame:FindFirstChild(name)
        if old then
            old:Destroy()
        end
    end
    radius = radius or 8
    local accent = Theme.Accent
    local bright = accent:Lerp(Color3.new(1, 1, 1), 0.65)

    -- Outer glow: a wide, faint stroke around a second outline.
    local halo = create("Frame", {
        Name = "SearchGlow",
        Size = UDim2.fromScale(1, 1),
        BackgroundTransparency = 1,
        ZIndex = 10,
        Parent = frame,
    })
    corner(halo, UDim.new(0, radius))
    local haloStroke = create("UIStroke", {
        Color = accent,
        Thickness = 1,
        Transparency = 1,
        ApplyStrokeMode = Enum.ApplyStrokeMode.Border,
        Parent = halo,
    })

    -- Wash with a moving sheen: a brighter diagonal band crosses it once.
    local wash = create("Frame", {
        Name = "SearchFlash",
        Size = UDim2.fromScale(1, 1),
        BackgroundColor3 = accent,
        BackgroundTransparency = 1,
        BorderSizePixel = 0,
        ZIndex = 10,
        Parent = frame,
    })
    corner(wash, UDim.new(0, radius))
    local sheen = create("UIGradient", {
        Transparency = NumberSequence.new({
            NumberSequenceKeypoint.new(0, 0.7),
            NumberSequenceKeypoint.new(0.4, 0.55),
            NumberSequenceKeypoint.new(0.5, 0),
            NumberSequenceKeypoint.new(0.6, 0.55),
            NumberSequenceKeypoint.new(1, 0.7),
        }),
        Rotation = 18,
        Offset = Vector2.new(-1, 0),
        Parent = wash,
    })

    -- Border light: the ring's gradient turns, so a bright spot runs round it.
    local ring = create("UIStroke", {
        Color = Color3.new(1, 1, 1),
        Thickness = 1.6,
        Transparency = 1,
        ApplyStrokeMode = Enum.ApplyStrokeMode.Border,
        Parent = wash,
    })
    local runner = create("UIGradient", {
        Color = ColorSequence.new({
            ColorSequenceKeypoint.new(0, accent),
            ColorSequenceKeypoint.new(0.5, bright),
            ColorSequenceKeypoint.new(1, accent),
        }),
        Transparency = NumberSequence.new({
            NumberSequenceKeypoint.new(0, 0.45),
            NumberSequenceKeypoint.new(0.5, 0),
            NumberSequenceKeypoint.new(1, 0.45),
        }),
        Parent = ring,
    })

    local inside = pcall(function()
        haloStroke.BorderStrokePosition = Enum.BorderStrokePosition.Inner
        ring.BorderStrokePosition = Enum.BorderStrokePosition.Inner
    end)
    local glowWidth = inside and 6 or 3
    if not inside then
        halo.Position = UDim2.fromOffset(glowWidth + 1, glowWidth + 1)
        halo.Size = UDim2.new(1, -(glowWidth + 1) * 2, 1, -(glowWidth + 1) * 2)
        wash.Position = UDim2.fromOffset(2, 2)
        wash.Size = UDim2.new(1, -4, 1, -4)
    end

    local pop
    if not frame:FindFirstChildOfClass("UIScale") then
        pop = create("UIScale", { Scale = 0.975, Parent = frame })
        tween(pop, { Scale = 1 }, 0.4, Enum.EasingStyle.Quint)
    end

    tween(wash, { BackgroundTransparency = 0.8 }, 0.2, Enum.EasingStyle.Quad)
    tween(ring, { Transparency = 0 }, 0.2, Enum.EasingStyle.Quad)
    tween(haloStroke, { Thickness = glowWidth, Transparency = 0.72 }, 0.35, Enum.EasingStyle.Quint)
    tween(sheen, { Offset = Vector2.new(1, 0) }, 0.8, Enum.EasingStyle.Quad, Enum.EasingDirection.InOut)
    tween(runner, { Rotation = 540 }, 2.2, Enum.EasingStyle.Quad)
    task.spawn(function()
        task.wait(0.75)
        tween(wash, { BackgroundTransparency = 0.9 }, 0.35, Enum.EasingStyle.Sine)
        tween(haloStroke, { Thickness = glowWidth / 2, Transparency = 0.85 }, 0.35, Enum.EasingStyle.Sine)
        task.wait(0.35)
        tween(wash, { BackgroundTransparency = 0.84 }, 0.3, Enum.EasingStyle.Sine)
        tween(haloStroke, { Thickness = glowWidth * 0.85, Transparency = 0.76 }, 0.3, Enum.EasingStyle.Sine)
        task.wait(0.4)
        tween(wash, { BackgroundTransparency = 1 }, 0.55, Enum.EasingStyle.Quad)
        tween(ring, { Transparency = 1 }, 0.65, Enum.EasingStyle.Quad)
        tween(haloStroke, { Thickness = glowWidth, Transparency = 1 }, 0.65, Enum.EasingStyle.Quad)
        task.wait(0.7)
        wash:Destroy()
        halo:Destroy()
        if pop then
            pop:Destroy()
        end
    end)
end

function Window:_revealResult(result)
    local tab, sub, target, group = result.Tab, result.Sub, result.Target, result.Group
    if self.CurrentTab ~= tab then
        self:SelectTab(tab)
    end
    if sub then
        tab:SelectSubTab(sub)
    end
    if not target then
        local button = sub and sub._button or tab._button
        task.delay(0.1, function()
            if button.Parent then
                self:_flash(button, sub and 8 or 10)
            end
        end)
        return
    end
    local expanding = group ~= nil and group:IsCollapsed()
    if expanding then
        group:Expand()
    end
    local list = (sub or tab).List
    task.spawn(function()
        -- Let the freshly shown page lay out before measuring it.
        task.wait()
        task.wait()
        if expanding then
            task.wait(0.3)
        end
        local frame = target._frame
        if self._destroyed or target._destroyed or not frame or not frame.Parent or not list then
            return
        end
        local scale = self.Scale.Scale
        local top = (frame.AbsolutePosition.Y - list.AbsolutePosition.Y) / scale + list.CanvasPosition.Y
        local height = frame.AbsoluteSize.Y / scale
        local view = list.AbsoluteWindowSize.Y / scale
        local limit = math.max(list.AbsoluteCanvasSize.Y / scale - view, 0)
        local y = math.clamp(top + height / 2 - view / 2, 0, limit)
        if math.abs(y - list.CanvasPosition.Y) > 2 then
            tween(list, { CanvasPosition = Vector2.new(0, y) }, 0.45, Enum.EasingStyle.Quint)
            task.wait(0.25)
        end
        if frame.Parent then
            self:_flash(frame, target._groupbox and 10 or 8)
        end
    end)
end

function Window:_resetSearch()
    if self.SearchBox and self.SearchBox.Text ~= "" then
        self.SearchBox.Text = ""
    end
end

-- Page titles stop short of the search box and close button.
function Window:_fitTitle(tab)
    local right = self.SearchBox and (self._searchWidth or SEARCH_WIDTH) + 72 or 56
    local reserve = tab._titleX + right
    tab._title.Size = UDim2.new(1, -reserve, 0, 24)
    if tab._desc then
        tab._desc.Size = UDim2.new(1, -reserve, 0, 16)
    end
end

function Window:_buildSearch(content)
    local holder = create("Frame", {
        AnchorPoint = Vector2.new(1, 0),
        Position = UDim2.new(1, -56, 0, 14),
        Size = UDim2.fromOffset(SEARCH_WIDTH, 34),
        BackgroundTransparency = 1,
        BorderSizePixel = 0,
        ZIndex = 5,
        Parent = content,
    })
    holder:SetAttribute("NoDrag", true)
    local baseline = create("Frame", {
        AnchorPoint = Vector2.new(0, 1),
        Position = UDim2.new(0, 0, 1, -2),
        Size = UDim2.new(1, 0, 0, 1),
        BackgroundColor3 = Theme.Stroke,
        BorderSizePixel = 0,
        Parent = holder,
    })
    local focusLine = create("Frame", {
        AnchorPoint = Vector2.new(0.5, 1),
        Position = UDim2.new(0.5, 0, 1, -1),
        Size = UDim2.new(0, 0, 0, 2),
        BackgroundColor3 = Theme.Accent,
        BorderSizePixel = 0,
        ZIndex = 2,
        Parent = holder,
    })
    corner(focusLine, UDim.new(1, 0))
    -- Kept for the focus handlers below, which recolour it.
    local _, icon = glowIcon(holder, "search", Theme.Muted, UDim2.new(0, 2, 0.5, -1))
    icon.Parent.Size = UDim2.fromOffset(15, 15)
    local box = create("TextBox", {
        Position = UDim2.fromOffset(26, 0),
        Size = UDim2.new(1, -28, 1, -2),
        BackgroundTransparency = 1,
        Text = "",
        PlaceholderText = "Search",
        PlaceholderColor3 = Theme.Muted,
        TextColor3 = Theme.Text,
        TextSize = 13,
        FontFace = Fonts.Regular,
        TextXAlignment = Enum.TextXAlignment.Left,
        TextTruncate = Enum.TextTruncate.AtEnd,
        ClearTextOnFocus = false,
        Parent = holder,
    })
    holder.MouseEnter:Connect(function()
        if not box:IsFocused() then
            tween(baseline, { BackgroundColor3 = Theme.StrokeHover }, 0.15)
        end
    end)
    holder.MouseLeave:Connect(function()
        tween(baseline, { BackgroundColor3 = Theme.Stroke }, 0.25)
    end)
    self.SearchBox = box

    -- Results float over the window under the box, like a dropdown popup.
    local rowHeight = TOUCH and 40 or 34
    local maxRows = 8
    local popup = create("Frame", {
        AnchorPoint = Vector2.new(1, 0),
        Size = UDim2.fromOffset(300, 0),
        BackgroundTransparency = 1,
        Visible = false,
        ZIndex = 45,
        Parent = self.Body,
    })
    popup:SetAttribute("NoDrag", true)
    local popupShadow = create("ImageLabel", {
        Position = UDim2.fromOffset(-18, -12),
        Size = UDim2.new(1, 36, 1, 36),
        BackgroundTransparency = 1,
        Image = Assets.Shadow,
        ImageColor3 = Color3.new(0, 0, 0),
        ImageTransparency = 1,
        ScaleType = Enum.ScaleType.Slice,
        SliceCenter = Rect.new(49, 49, 450, 450),
        Parent = popup,
    })
    local panel = create("Frame", {
        Size = UDim2.fromScale(1, 1),
        BackgroundColor3 = Theme.Background,
        BorderSizePixel = 0,
        ClipsDescendants = true,
        Parent = popup,
    })
    corner(panel, UDim.new(0, 10))
    local panelStroke = stroke(panel, Theme.Stroke, 1)
    edgeHighlight(panel)
    local list = create("ScrollingFrame", {
        Position = UDim2.fromOffset(6, 6),
        Size = UDim2.new(1, -12, 1, -12),
        BackgroundTransparency = 1,
        BorderSizePixel = 0,
        ScrollBarThickness = TOUCH and 4 or 3,
        ScrollBarImageColor3 = Theme.Accent,
        ScrollBarImageTransparency = 0.4,
        ScrollingDirection = Enum.ScrollingDirection.Y,
        CanvasSize = UDim2.new(),
        Parent = panel,
    })
    create("UIListLayout", {
        SortOrder = Enum.SortOrder.LayoutOrder,
        Padding = UDim.new(0, 2),
        Parent = list,
    })
    local noResults = label({
        Size = UDim2.new(1, 0, 0, rowHeight),
        Text = "No results",
        TextSize = 13,
        FontFace = Fonts.Regular,
        TextColor3 = Theme.Muted,
        TextXAlignment = Enum.TextXAlignment.Center,
        LayoutOrder = 0,
        Visible = false,
        Parent = list,
    })

    local rows = {}
    local results = {}
    local selected = 1
    local open = false
    local generation = 0
    local shownSize = Vector2.new(300, 0)
    local stopFollowing = nil
    local closeResults

    local function place()
        local scale = self.Scale.Scale
        local bodyPosition = self.Body.AbsolutePosition
        local bodyWidth = self.Body.AbsoluteSize.X / scale
        local right = (holder.AbsolutePosition.X + holder.AbsoluteSize.X - bodyPosition.X) / scale
        local top = (holder.AbsolutePosition.Y + holder.AbsoluteSize.Y - bodyPosition.Y) / scale + 6
        right = math.clamp(right, shownSize.X + 8, math.max(bodyWidth - 8, shownSize.X + 8))
        popup.Position = UDim2.fromOffset(right, top)
    end

    local function measure()
        local scale = self.Scale.Scale
        local bodySize = self.Body.AbsoluteSize / scale
        local below = (holder.AbsolutePosition.Y + holder.AbsoluteSize.Y - self.Body.AbsolutePosition.Y) / scale + 6
        local count = math.max(#rows, 1)
        local height = math.min(count, maxRows) * (rowHeight + 2) - 2 + 12
        height = math.max(math.min(height, bodySize.Y - below - 12), rowHeight + 12)
        local width = math.min(math.max(holder.AbsoluteSize.X / scale, 300), math.max(bodySize.X - 16, 160))
        shownSize = Vector2.new(width, height)
    end

    local function paintSelection()
        for index, row in ipairs(rows) do
            local on = index == selected
            tween(row.Button, { BackgroundTransparency = on and 0.35 or 1 }, 0.12)
            tintIcon(row.Icon, on and Theme.Accent or Theme.Muted, on, 0.12)
        end
    end

    local function keepSelectionInView()
        local rowTop = (selected - 1) * (rowHeight + 2)
        local view = list.AbsoluteWindowSize.Y / self.Scale.Scale
        local y = list.CanvasPosition.Y
        if rowTop < y then
            y = rowTop
        elseif rowTop + rowHeight > y + view then
            y = rowTop + rowHeight - view
        else
            return
        end
        list.CanvasPosition = Vector2.new(0, math.max(y, 0))
    end

    local function setOpen(value)
        if value == open then
            return
        end
        open = value
        generation += 1
        local current = generation
        if value then
            if self._closePopup and self._closePopup ~= closeResults then
                self._closePopup()
            end
            self._closePopup = closeResults
            place()
            popup.Size = UDim2.fromOffset(shownSize.X, 0)
            popup.Visible = true
            tween(popup, { Size = UDim2.fromOffset(shownSize.X, shownSize.Y) }, 0.26, Enum.EasingStyle.Quint)
            tween(panelStroke, { Transparency = 0 }, 0.12)
            tween(popupShadow, { ImageTransparency = 0.55 }, 0.26)
            if not stopFollowing then
                stopFollowing = self:_listen("Render", place)
            end
        else
            if self._closePopup == closeResults then
                self._closePopup = nil
            end
            tween(popup, { Size = UDim2.fromOffset(shownSize.X, 0) }, 0.18, Enum.EasingStyle.Quint)
            tween(popupShadow, { ImageTransparency = 1 }, 0.14)
            task.delay(0.19, function()
                if generation == current and not open then
                    popup.Visible = false
                    panelStroke.Transparency = 1
                    if stopFollowing then
                        stopFollowing()
                        stopFollowing = nil
                    end
                end
            end)
        end
    end
    closeResults = function()
        setOpen(false)
    end

    local function choose(result)
        if not result then
            return
        end
        setOpen(false)
        box.Text = ""
        if box:IsFocused() then
            box:ReleaseFocus()
        end
        self:_revealResult(result)
    end

    local function escape(text)
        return (string.gsub(string.gsub(string.gsub(text, "&", "&amp;"), "<", "&lt;"), ">", "&gt;"))
    end

    local function render(query)
        for _, row in ipairs(rows) do
            row.Button:Destroy()
        end
        table.clear(rows)
        results = self:_searchResults(query)
        selected = 1
        local accent = colorToHex(Theme.Accent)
        for index, result in ipairs(results) do
            if index > 50 then
                break
            end
            local button = create("TextButton", {
                Size = UDim2.new(1, 0, 0, rowHeight),
                BackgroundColor3 = Theme.Surface3,
                BackgroundTransparency = 1,
                Text = "",
                AutoButtonColor = false,
                LayoutOrder = index,
                Parent = list,
            })
            corner(button, UDim.new(0, 7))
            local crumbs = create("Frame", {
                Position = UDim2.fromOffset(10, 0),
                Size = UDim2.new(1, -20, 1, 0),
                BackgroundTransparency = 1,
                ClipsDescendants = true,
                Parent = button,
            })
            create("UIListLayout", {
                FillDirection = Enum.FillDirection.Horizontal,
                VerticalAlignment = Enum.VerticalAlignment.Center,
                SortOrder = Enum.SortOrder.LayoutOrder,
                Padding = UDim.new(0, 5),
                Parent = crumbs,
            })
            local part = 0
            local firstIcon = nil
            local function crumbIcon(icon)
                if not icon then
                    return
                end
                part += 1
                local image = create("ImageLabel", {
                    Size = UDim2.fromOffset(14, 14),
                    BackgroundTransparency = 1,
                    ImageColor3 = Theme.Muted,
                    ScaleType = Enum.ScaleType.Fit,
                    LayoutOrder = part,
                    Parent = crumbs,
                })
                applyIcon(image, icon)
                firstIcon = firstIcon or image
            end
            local function crumbText(text, color, rich)
                part += 1
                return label({
                    Size = UDim2.new(0, 0, 1, 0),
                    AutomaticSize = Enum.AutomaticSize.X,
                    Text = text,
                    RichText = rich == true,
                    TextSize = 13,
                    FontFace = color and Fonts.Medium or Fonts.Regular,
                    TextColor3 = color or Theme.Muted,
                    TextTruncate = Enum.TextTruncate.None,
                    LayoutOrder = part,
                    Parent = crumbs,
                })
            end
            local function chevron()
                crumbText(">")
            end
            local tab, sub, group = result.Tab, result.Sub, result.Group
            local onTab = result.Kind == "Tab"
            local onSub = result.Kind == "Page"
            local onGroup = result.Kind == "Groupbox"
            local tabIcon = tab._iconName
            if tabIcon == nil then
                tabIcon = "layout-grid"
            end
            crumbIcon(tabIcon)
            if not onTab then
                crumbText(tab.Name)
                if sub then
                    chevron()
                    local subIcon = sub._iconName
                    if subIcon == nil then
                        subIcon = "layers"
                    end
                    crumbIcon(subIcon)
                    if not onSub then
                        crumbText(sub.Name)
                    end
                end
                if group and not onGroup then
                    chevron()
                    crumbText(group.Name)
                end
                if not onSub then
                    chevron()
                end
            end
            -- The match itself: accent, with the typed part in bold.
            local name = result.Name
            local stop = result.At + #query
            local marked = escape(string.sub(name, 1, result.At - 1))
                .. "<b>" .. escape(string.sub(name, result.At, stop - 1)) .. "</b>"
                .. escape(string.sub(name, stop))
            crumbText(marked, Theme.Accent, true)
            local image = firstIcon
            local isTap = tapGuard(button, function()
                return list
            end)
            button.MouseEnter:Connect(function()
                if not usingTouch() then
                    selected = index
                    paintSelection()
                end
            end)
            button.MouseButton1Click:Connect(function()
                if isTap() then
                    choose(result)
                end
            end)
            table.insert(rows, { Button = button, Icon = image })
        end
        noResults.Visible = #rows == 0
        list.CanvasSize = UDim2.fromOffset(0, math.max(#rows, 1) * (rowHeight + 2) - 2)
        list.CanvasPosition = Vector2.zero
        paintSelection()
        measure()
        if open then
            place()
            tween(popup, { Size = UDim2.fromOffset(shownSize.X, shownSize.Y) }, 0.2, Enum.EasingStyle.Quint)
        end
    end

    local function update()
        local query = string.match(string.lower(box.Text), "^%s*(.-)%s*$")
        if query == "" then
            setOpen(false)
            return
        end
        render(query)
        setOpen(true)
    end

    box.Focused:Connect(function()
        tween(focusLine, { Size = UDim2.new(1, 0, 0, 2) }, 0.35, Enum.EasingStyle.Quint)
        tween(icon, { ImageColor3 = Theme.Accent }, 0.15)
        if box.Text ~= "" then
            update()
        end
    end)
    box.FocusLost:Connect(function(enterPressed)
        tween(focusLine, { Size = UDim2.new(0, 0, 0, 2) }, 0.3, Enum.EasingStyle.Quint)
        tween(icon, { ImageColor3 = Theme.Muted }, 0.2)
        if enterPressed and open then
            choose(results[selected])
        end
    end)
    box:GetPropertyChangedSignal("Text"):Connect(update)
    self:_listen("Began", function(input)
        if not open then
            return
        end
        if input.KeyCode == Enum.KeyCode.Up or input.KeyCode == Enum.KeyCode.Down then
            if #rows > 0 then
                local step = input.KeyCode == Enum.KeyCode.Up and -1 or 1
                selected = math.clamp(selected + step, 1, #rows)
                paintSelection()
                keepSelectionInView()
            end
        elseif input.KeyCode == Enum.KeyCode.Escape then
            setOpen(false)
        elseif isPress(input) then
            local point = pointerPosition()
            if not pointInside(point, popup) and not pointInside(point, holder) then
                setOpen(false)
            end
        end
    end)

    local function fit()
        local width = content.AbsoluteSize.X / self.Scale.Scale
        local searchWidth = math.clamp(math.floor(width * 0.32), 110, SEARCH_WIDTH)
        holder.Size = UDim2.fromOffset(searchWidth, 34)
        if searchWidth ~= self._searchWidth then
            self._searchWidth = searchWidth
            for _, tab in ipairs(self.Tabs) do
                self:_fitTitle(tab)
            end
        end
    end
    content:GetPropertyChangedSignal("AbsoluteSize"):Connect(fit)
    task.defer(fit)
end

function Window:_trackName(textLabel, kind)
    table.insert(self._identity.Names, { Label = textLabel, Kind = kind })
    self:_renderIdentity()
end

function Window:_trackAvatar(image, placeholder)
    table.insert(self._identity.Avatars, { Image = image, Placeholder = placeholder })
    self:_renderIdentity(true)
end

function Window:_renderIdentity(instant)
    for _, entry in ipairs(self._identity.Names) do
        if entry.Kind == "User" then
            entry.Label.Text = self._hideName and "@hidden" or ("@" .. LocalPlayer.Name)
        else
            entry.Label.Text = self._hideName and "Hidden" or LocalPlayer.DisplayName
        end
    end
    local duration = instant and 0 or 0.2
    for _, entry in ipairs(self._identity.Avatars) do
        tween(entry.Image, { ImageTransparency = self._hideAvatar and 1 or 0 }, duration)
        tween(entry.Placeholder, { ImageTransparency = self._hideAvatar and 0.2 or 1 }, duration)
    end
end

function Window:SetHideName(hidden)
    self._hideName = hidden == true
    self:_renderIdentity()
end

function Window:SetHideAvatar(hidden)
    self._hideAvatar = hidden == true
    self:_renderIdentity()
end

local function avatar(window, parent, props, ringColor, ringTransparency, ringThickness)
    local holder = create("Frame", {
        BackgroundColor3 = Theme.Surface3,
        BorderSizePixel = 0,
        Parent = parent,
    })
    for key, value in pairs(props) do
        holder[key] = value
    end
    corner(holder, UDim.new(1, 0))
    stroke(holder, ringColor or Theme.Stroke, ringTransparency or 0, ringThickness or 1)
    local image = create("ImageLabel", {
        Size = UDim2.fromScale(1, 1),
        BackgroundTransparency = 1,
        Image = "rbxthumb://type=AvatarHeadShot&id=" .. tostring(LocalPlayer.UserId) .. "&w=150&h=150",
        Parent = holder,
    })
    corner(image, UDim.new(1, 0))
    local placeholder = create("ImageLabel", {
        AnchorPoint = Vector2.new(0.5, 0.5),
        Position = UDim2.fromScale(0.5, 0.5),
        Size = UDim2.fromScale(0.45, 0.45),
        BackgroundTransparency = 1,
        ImageColor3 = Theme.Muted,
        ImageTransparency = 1,
        ScaleType = Enum.ScaleType.Fit,
        Parent = holder,
    })
    applyIcon(placeholder, "user")
    window:_trackAvatar(image, placeholder)
    return holder
end

function Window:_buildProfile(sidebar)
    create("Frame", {
        AnchorPoint = Vector2.new(0.5, 1),
        Position = UDim2.new(0.5, 0, 1, -PROFILE_HEIGHT),
        Size = UDim2.new(1, -20, 0, 1),
        BackgroundColor3 = Theme.Stroke,
        BorderSizePixel = 0,
        Parent = sidebar,
    })
    local card = create("TextButton", {
        AnchorPoint = Vector2.new(0.5, 1),
        Position = UDim2.new(0.5, 0, 1, -8),
        Size = UDim2.new(1, -16, 0, PROFILE_HEIGHT - 16),
        BackgroundColor3 = Theme.Surface2,
        BackgroundTransparency = 0,
        Text = "",
        AutoButtonColor = false,
        Parent = sidebar,
    })
    corner(card, UDim.new(0, 8))
    local cardStroke = stroke(card, Theme.Stroke, 0)
    local head = avatar(self, card, {
        AnchorPoint = Vector2.new(0, 0.5),
        Position = UDim2.new(0, 8, 0.5, 0),
        Size = UDim2.fromOffset(32, 32),
    })
    local online = create("Frame", {
        AnchorPoint = Vector2.new(1, 1),
        Position = UDim2.new(1, 1, 1, 1),
        Size = UDim2.fromOffset(9, 9),
        BackgroundColor3 = Theme.Success,
        BorderSizePixel = 0,
        ZIndex = 2,
        Parent = head,
    })
    corner(online, UDim.new(1, 0))
    stroke(online, Theme.Surface2, 0, 2)
    local name = label({
        Position = UDim2.new(0, 48, 0.5, -15),
        Size = UDim2.new(1, -74, 0, 15),
        TextSize = 12,
        FontFace = Fonts.Bold,
        Parent = card,
    })
    self:_trackName(name, "Display")
    local gameLabel = label({
        Position = UDim2.new(0, 48, 0.5, 1),
        Size = UDim2.new(1, -74, 0, 13),
        Text = "…",
        TextSize = 11,
        FontFace = Fonts.Regular,
        TextColor3 = Theme.Muted,
        Parent = card,
    })
    local chevron = create("ImageLabel", {
        AnchorPoint = Vector2.new(1, 0.5),
        Position = UDim2.new(1, -8, 0.5, 0),
        Size = UDim2.fromOffset(14, 14),
        BackgroundTransparency = 1,
        ImageColor3 = Theme.Muted,
        ScaleType = Enum.ScaleType.Fit,
        Parent = card,
    })
    applyIcon(chevron, "chevron-right")
    task.spawn(function()
        gameLabel.Text = detectGameName()
    end)
    card.MouseEnter:Connect(function()
        if usingTouch() then
            return
        end
        tween(cardStroke, { Color = Theme.StrokeHover }, 0.12)
        tween(chevron, { ImageColor3 = Theme.Text, Position = UDim2.new(1, -6, 0.5, 0) }, 0.15)
    end)
    card.MouseLeave:Connect(function()
        tween(cardStroke, { Color = Theme.Stroke }, 0.2)
        tween(chevron, { ImageColor3 = Theme.Muted, Position = UDim2.new(1, -8, 0.5, 0) }, 0.2)
    end)
    card.MouseButton1Click:Connect(function()
        if self.Home then
            self:SelectTab(self.Home)
        end
    end)
    self.Profile = card
end

-- Server actions

function Window:Rejoin()
    if not (getgenv().MT_ArrowRokakaFinder and getgenv().MT_ArrowRokakaFinder.ServerTransfersEnabled) then return end
    self:Notify({ Title = "Rejoining", Content = "Teleporting back into this server", Icon = "refresh-cw", Duration = 3 })
    task.spawn(function()
        local ok, err = pcall(function()
            if #Players:GetPlayers() <= 1 or game.JobId == "" then
                TeleportService:Teleport(game.PlaceId, LocalPlayer)
            else
                TeleportService:TeleportToPlaceInstance(game.PlaceId, game.JobId, LocalPlayer)
            end
        end)
        if not ok then
            self:Notify({ Title = "Rejoin failed", Content = tostring(err), Type = "Error", Duration = 4 })
        end
    end)
end

local function hopServers(window, order, pick, title)
    task.spawn(function()
        local servers = fetchServers(order)
        if not servers then
            window:Notify({ Title = title .. " failed", Content = "Could not load the server list", Type = "Error", Duration = 4 })
            return
        end
        local candidates = {}
        for _, server in ipairs(servers) do
            if type(server) == "table" and server.id ~= game.JobId then
                local playing, capacity = tonumber(server.playing), tonumber(server.maxPlayers)
                if playing and capacity and playing < capacity then
                    table.insert(candidates, server)
                end
            end
        end
        local target = #candidates > 0 and pick(candidates) or nil
        if not target then
            window:Notify({ Title = title .. " failed", Content = "No other open server found", Type = "Warning", Duration = 4 })
            return
        end
        window:Notify({
            Title = title,
            Content = string.format("Joining a server with %d/%d players", target.playing, target.maxPlayers),
            Icon = "server",
            Duration = 3,
        })
        local ok, err = pcall(function()
            assert(getgenv().MT_ArrowRokakaFinder.ServerTransfersEnabled,"server transfers disabled")
            TeleportService:TeleportToPlaceInstance(game.PlaceId, target.id, LocalPlayer)
        end)
        if not ok then
            window:Notify({ Title = title .. " failed", Content = tostring(err), Type = "Error", Duration = 4 })
        end
    end)
end

function Window:ServerHop()
    hopServers(self, "Desc", function(list)
        return list[math.random(1, #list)]
    end, "Server hop")
end

function Window:JoinLowestServer()
    hopServers(self, "Asc", function(list)
        table.sort(list, function(a, b)
            return a.playing < b.playing
        end)
        return list[1]
    end, "Lowest server")
end

function Window:CopyToClipboard(text, what)
    local ok = copyToClipboard(text)
    self:Notify({
        Title = ok and "Copied" or "Clipboard unavailable",
        Content = ok and (what or tostring(text)) or "Your executor has no setclipboard",
        Type = ok and "Success" or "Error",
        Icon = ok and "clipboard-check" or nil,
        Duration = 2.5,
    })
    return ok
end

-- Home

-- A Home card that grows with its stacked contents.
function Window:_homeCard(parent, order)
    local card = panelCard(parent, 0, order)
    card.AutomaticSize = Enum.AutomaticSize.Y
    padding(card, 16, 16, 14, 14)
    create("UIListLayout", { SortOrder = Enum.SortOrder.LayoutOrder, Parent = card })
    return card
end

-- A small caps heading at the top of a Home card.
function Window:_homeCaption(parent, text, order)
    return label({
        Size = UDim2.new(1, 0, 0, 22),
        Text = string.upper(text),
        TextSize = 10,
        TextColor3 = Theme.Muted,
        TextYAlignment = Enum.TextYAlignment.Top,
        LayoutOrder = order,
        Parent = parent,
    })
end

function Window:_homeChip(parent, order, icon, text, color)
    icon = cleanIcon(icon)
    local chip = create("TextButton", {
        Size = UDim2.fromOffset(0, 24),
        AutomaticSize = Enum.AutomaticSize.X,
        BackgroundColor3 = Theme.Surface3,
        BackgroundTransparency = 0.2,
        BorderSizePixel = 0,
        Text = "",
        AutoButtonColor = false,
        LayoutOrder = order,
        Parent = parent,
    })
    corner(chip, UDim.new(0, 6))
    local chipStroke = stroke(chip)
    padding(chip, 8, 9)
    create("UIListLayout", {
        FillDirection = Enum.FillDirection.Horizontal,
        VerticalAlignment = Enum.VerticalAlignment.Center,
        SortOrder = Enum.SortOrder.LayoutOrder,
        Padding = UDim.new(0, 6),
        Parent = chip,
    })
    local image
    if icon ~= false then
        image = create("ImageLabel", {
            Size = UDim2.fromOffset(12, 12),
            BackgroundTransparency = 1,
            ImageColor3 = color or Theme.Muted,
            ScaleType = Enum.ScaleType.Fit,
            LayoutOrder = 1,
            Parent = chip,
        })
        applyIcon(image, icon)
    end
    local text_ = label({
        Size = UDim2.new(0, 0, 1, 0),
        AutomaticSize = Enum.AutomaticSize.X,
        Text = text,
        TextSize = 12,
        TextColor3 = color or Theme.Muted,
        TextTruncate = Enum.TextTruncate.None,
        LayoutOrder = 2,
        Parent = chip,
    })
    return chip, text_, image, chipStroke
end

-- A chip that flips on press: on, it takes the accent; off, it sits muted.
function Window:_homeToggleChip(parent, order, icon, text, initial, callback)
    local chip, text_, image, chipStroke = self:_homeChip(parent, order, icon, text)
    local on = initial == true
    local function paint(duration)
        tween(chip, { BackgroundColor3 = on and Theme.Accent or Theme.Surface3, BackgroundTransparency = on and 0.85 or 0.2 }, duration)
        tween(chipStroke, { Color = on and Theme.Accent or Theme.Stroke, Transparency = on and 0.6 or 0 }, duration)
        tween(text_, { TextColor3 = on and Theme.Accent or Theme.Muted }, duration)
        if image then
            tween(image, { ImageColor3 = on and Theme.Accent or Theme.Muted }, duration)
        end
    end
    paint(0)
    chip.MouseButton1Click:Connect(function()
        on = not on
        paint(0.2)
        safeCall(callback, on)
    end)
    return chip
end

function Window:_homeProfile(list, opts, order)
    local banner = panelCard(list, 140, order)
    banner.ClipsDescendants = true

    local bust = create("ImageLabel", {
        AnchorPoint = Vector2.new(1, 1),
        Position = UDim2.new(1, -16, 1, 0),
        Size = UDim2.fromOffset(140, 140),
        BackgroundTransparency = 1,
        Image = "rbxthumb://type=AvatarBust&id=" .. tostring(LocalPlayer.UserId) .. "&w=420&h=420",
        ScaleType = Enum.ScaleType.Fit,
        Parent = banner,
    })
    create("UIGradient", {
        Transparency = NumberSequence.new({
            NumberSequenceKeypoint.new(0, 1),
            NumberSequenceKeypoint.new(0.45, 0),
            NumberSequenceKeypoint.new(1, 0),
        }),
        Parent = bust,
    })
    local bustPlaceholder = create("ImageLabel", {
        AnchorPoint = Vector2.new(0.5, 0.5),
        Position = UDim2.fromScale(0.6, 0.55),
        Size = UDim2.fromOffset(40, 40),
        BackgroundTransparency = 1,
        ImageColor3 = Theme.Muted,
        ImageTransparency = 1,
        ScaleType = Enum.ScaleType.Fit,
        Parent = bust,
    })
    applyIcon(bustPlaceholder, "user")
    self:_trackAvatar(bust, bustPlaceholder)

    local textWidth = UDim2.new(1, -190, 0, 0)
    label({
        Position = UDim2.fromOffset(22, 20),
        Size = textWidth + UDim2.fromOffset(0, 14),
        Text = string.upper(opts.Welcome or "Welcome back"),
        TextSize = 10,
        TextColor3 = Theme.Muted,
        Parent = banner,
    })
    local nameLabel = label({
        Position = UDim2.fromOffset(22, 35),
        Size = textWidth + UDim2.fromOffset(0, 32),
        TextSize = 26,
        FontFace = Fonts.Bold,
        Parent = banner,
    })
    self:_trackName(nameLabel, "Display")
    local userLabel = label({
        Position = UDim2.fromOffset(22, 67),
        Size = textWidth + UDim2.fromOffset(0, 16),
        TextSize = 13,
        FontFace = Fonts.Regular,
        TextColor3 = Theme.Muted,
        Parent = banner,
    })
    self:_trackName(userLabel, "User")

    -- Chips along the bottom: tier, time left, then the privacy toggles.
    local chips = create("Frame", {
        Position = UDim2.new(0, 22, 1, -40),
        Size = UDim2.new(1, -44, 0, 24),
        BackgroundTransparency = 1,
        Parent = banner,
    })
    create("UIListLayout", {
        FillDirection = Enum.FillDirection.Horizontal,
        VerticalAlignment = Enum.VerticalAlignment.Center,
        SortOrder = Enum.SortOrder.LayoutOrder,
        Padding = UDim.new(0, 6),
        Parent = chips,
    })
    local tier = opts.Tier
    if tier == nil then
        tier = "Free"
    end
    if tier then
        local tierIconValue = opts.TierIcon
        if tierIconValue == nil then
            tierIconValue = self._logoIcon
        end
        local tierChip, tierText, tierIcon = self:_homeChip(chips, 1, tierIconValue, tostring(tier), Theme.Accent)
        tierChip.Active = false
        tierText.FontFace = Fonts.Bold
        if tierIcon then
            tierIcon.Size = UDim2.fromOffset(13, 13)
        end
        self.TierLabel = tierText
    end
    local expiryChip, expiryText = self:_homeChip(chips, 2, "clock", "")
    expiryChip.Active = false
    expiryChip.Visible = false
    self:_homeToggleChip(chips, 3, "eye-off", "Name", self._hideName, function(on)
        self:SetHideName(on)
    end)
    self:_homeToggleChip(chips, 4, "user-x", "Avatar", self._hideAvatar, function(on)
        self:SetHideAvatar(on)
    end)

    return function()
        local value = opts.Expiry
        if type(value) == "function" then
            local ok, result = pcall(value)
            value = ok and result or nil
        end
        if type(value) == "number" then
            local left = value - os.time()
            expiryText.Text = left > 0 and (formatDuration(left) .. " left") or "Expired"
        elseif value ~= nil then
            expiryText.Text = tostring(value)
        end
        expiryChip.Visible = expiryText.Text ~= ""
    end
end

function Window:_homeGraph(parent, order, icon, title, ceiling)
    local cell = create("Frame", {
        BackgroundTransparency = 1,
        LayoutOrder = order,
        Parent = parent,
    })
    local holder = glowIcon(cell, icon, Theme.Muted, UDim2.new(0, 0, 0, 7))
    holder.Size = UDim2.fromOffset(12, 12)
    label({
        Position = UDim2.fromOffset(18, 0),
        Size = UDim2.new(1, -18, 0, 14),
        Text = string.upper(title),
        TextSize = 10,
        TextColor3 = Theme.Muted,
        Parent = cell,
    })
    local value = label({
        Position = UDim2.fromOffset(0, 16),
        Size = UDim2.new(1, 0, 0, 28),
        Text = "…",
        TextSize = 24,
        FontFace = Fonts.Bold,
        RichText = true,
        Parent = cell,
    })
    local track = create("Frame", {
        Position = UDim2.fromOffset(0, 50),
        Size = UDim2.new(1, 0, 0, 26),
        BackgroundTransparency = 1,
        Parent = cell,
    })
    create("UIListLayout", {
        FillDirection = Enum.FillDirection.Horizontal,
        VerticalAlignment = Enum.VerticalAlignment.Bottom,
        SortOrder = Enum.SortOrder.LayoutOrder,
        Padding = UDim.new(0, 2),
        Parent = track,
    })
    local COUNT = 24
    local bars, samples = {}, {}
    for index = 1, COUNT do
        local bar = create("Frame", {
            Size = UDim2.new(1 / COUNT, -2, 0, 2),
            BackgroundColor3 = Theme.Surface3,
            BorderSizePixel = 0,
            LayoutOrder = index,
            Parent = track,
        })
        corner(bar, UDim.new(0, 2))
        bars[index] = bar
    end
    local function push(sample, color)
        table.insert(samples, sample)
        if #samples > COUNT then
            table.remove(samples, 1)
        end
        local top = ceiling or 1
        for _, s in ipairs(samples) do
            top = math.max(top, s)
        end
        local offset = COUNT - #samples
        for index, bar in ipairs(bars) do
            local s = samples[index - offset]
            local latest = index == COUNT
            local height = s and math.max(s / top, 0.08) or 0
            tween(bar, {
                Size = UDim2.new(1 / COUNT, -2, height, s and 0 or 2),
                BackgroundColor3 = (latest and color) or (s and Theme.Muted or Theme.Surface3),
                BackgroundTransparency = latest and 0 or (s and 0.6 or 0),
            }, 0.35, Enum.EasingStyle.Quint)
        end
    end
    return value, push
end

-- A small figure: value over a caps caption.
function Window:_homeFigure(parent, order, title)
    local cell = create("Frame", {
        BackgroundTransparency = 1,
        LayoutOrder = order,
        Parent = parent,
    })
    local value = label({
        Size = UDim2.new(1, -8, 0, 20),
        Text = "…",
        TextSize = 15,
        FontFace = Fonts.Bold,
        RichText = true,
        Parent = cell,
    })
    label({
        Position = UDim2.fromOffset(0, 21),
        Size = UDim2.new(1, -8, 0, 14),
        Text = string.upper(title),
        TextSize = 10,
        TextColor3 = Theme.Muted,
        Parent = cell,
    })
    return value
end

-- A square tile button: an icon over a short label.
function Window:_homeAction(parent, order, icon, text, callback)
    local button = create("TextButton", {
        BackgroundColor3 = Theme.Surface3,
        BackgroundTransparency = 0.5,
        BorderSizePixel = 0,
        Text = "",
        AutoButtonColor = false,
        ClipsDescendants = true,
        LayoutOrder = order,
        Parent = parent,
    })
    corner(button, UDim.new(0, 8))
    local buttonStroke = stroke(button)
    local image = create("ImageLabel", {
        AnchorPoint = Vector2.new(0.5, 0),
        Position = UDim2.new(0.5, 0, 0, 11),
        Size = UDim2.fromOffset(16, 16),
        BackgroundTransparency = 1,
        ImageColor3 = Theme.Text,
        ScaleType = Enum.ScaleType.Fit,
        Parent = button,
    })
    applyIcon(image, icon)
    label({
        Position = UDim2.new(0, 4, 0, 32),
        Size = UDim2.new(1, -8, 0, 14),
        Text = text,
        TextSize = 11,
        TextColor3 = Theme.Muted,
        TextXAlignment = Enum.TextXAlignment.Center,
        Parent = button,
    })
    button.MouseEnter:Connect(function()
        tween(button, { BackgroundTransparency = 0 }, 0.15, Enum.EasingStyle.Quint)
        tween(buttonStroke, { Color = Theme.StrokeHover }, 0.15)
        tween(image, { ImageColor3 = Theme.Accent }, 0.15)
    end)
    button.MouseLeave:Connect(function()
        tween(button, { BackgroundTransparency = 0.5 }, 0.25, Enum.EasingStyle.Quint)
        tween(buttonStroke, { Color = Theme.Stroke }, 0.25)
        tween(image, { ImageColor3 = Theme.Text }, 0.25)
    end)
    button.MouseButton1Click:Connect(function()
        ripple(button)
        safeCall(callback)
    end)
    return button
end

function Window:_homeGame(parent, order)
    local card = self:_homeCard(parent, order)
    local head = create("Frame", {
        Size = UDim2.new(1, 0, 0, 46),
        BackgroundTransparency = 1,
        LayoutOrder = 1,
        Parent = card,
    })
    local icon = create("ImageLabel", {
        Size = UDim2.fromOffset(44, 44),
        BackgroundColor3 = Theme.Surface3,
        BorderSizePixel = 0,
        Image = "rbxthumb://type=GameIcon&id=" .. tostring(game.GameId) .. "&w=150&h=150",
        Parent = head,
    })
    corner(icon, UDim.new(0, 10))
    stroke(icon)
    local gameName = label({
        Position = UDim2.fromOffset(56, 3),
        Size = UDim2.new(1, -56, 0, 20),
        Text = "Loading",
        TextSize = 15,
        FontFace = Fonts.Bold,
        Parent = head,
    })
    local detail = label({
        Position = UDim2.fromOffset(56, 24),
        Size = UDim2.new(1, -56, 0, 16),
        Text = "",
        TextSize = 12,
        FontFace = Fonts.Regular,
        TextColor3 = Theme.Muted,
        Parent = head,
    })
    local owner = nil
    task.spawn(function()
        local info = fetchGameInfo()
        gameName.Text = info and info.Name or detectGameName()
        owner = info and type(info.Creator) == "table" and info.Creator.Name or nil
    end)

    local actions = create("Frame", {
        Size = UDim2.new(1, 0, 0, 0),
        AutomaticSize = Enum.AutomaticSize.Y,
        BackgroundTransparency = 1,
        LayoutOrder = 2,
        Parent = card,
    })
    padding(actions, 0, 0, 12, 0)
    create("UIGridLayout", {
        CellPadding = UDim2.fromOffset(6, 6),
        CellSize = UDim2.new(0.25, -5, 0, 54),
        SortOrder = Enum.SortOrder.LayoutOrder,
        Parent = actions,
    })
    self:_homeAction(actions, 1, "refresh-cw", "Rejoin", function()
        self:Rejoin()
    end)
    self:_homeAction(actions, 2, "shuffle", "Hop", function()
        self:ServerHop()
    end)
    self:_homeAction(actions, 3, "users", "Lowest", function()
        self:JoinLowestServer()
    end)
    self:_homeAction(actions, 4, "copy", "Job ID", function()
        self:CopyToClipboard(game.JobId, "Job ID")
    end)

    label({
        Size = UDim2.new(1, 0, 0, 26),
        Text = "Job " .. shortId(game.JobId) .. "  ·  Place " .. tostring(game.PlaceId),
        TextSize = 11,
        FontFace = Fonts.Regular,
        TextColor3 = Theme.Muted,
        TextYAlignment = Enum.TextYAlignment.Bottom,
        LayoutOrder = 3,
        Parent = card,
    })

    -- The detail line keeps the player count live.
    return function()
        local count = #Players:GetPlayers() .. "/" .. Players.MaxPlayers .. " players"
        detail.Text = owner and ("by " .. owner .. "  ·  " .. count) or count
    end
end

-- One row of the links card: icon, title and text, and a round icon button.
function Window:_homeLink(card, order, icon, title, text, buttonIcon, callback)
    local row = create("Frame", {
        Size = UDim2.new(1, 0, 0, 46),
        BackgroundTransparency = 1,
        LayoutOrder = order,
        Parent = card,
    })
    create("Frame", {
        Name = "Rule",
        Size = UDim2.new(1, 0, 0, 1),
        BackgroundColor3 = Theme.Stroke,
        BorderSizePixel = 0,
        Parent = row,
    })
    icon = cleanIcon(icon)
    local textX = 28
    if icon ~= false then
        local holder = glowIcon(row, icon, Theme.Accent, UDim2.new(0, 0, 0.5, 0))
        holder.Size = UDim2.fromOffset(16, 16)
    else
        textX = 0
    end
    local titleLabel = label({
        Position = UDim2.fromOffset(textX, 6),
        Size = UDim2.new(1, -(textX + 40), 0, 18),
        Text = title,
        TextSize = 13,
        Parent = row,
    })
    local textLabel = label({
        Position = UDim2.fromOffset(textX, 24),
        Size = UDim2.new(1, -(textX + 40), 0, 15),
        Text = text,
        TextSize = 12,
        FontFace = Fonts.Regular,
        TextColor3 = Theme.Muted,
        Parent = row,
    })
    local button = create("TextButton", {
        AnchorPoint = Vector2.new(1, 0.5),
        Position = UDim2.new(1, 0, 0.5, 0),
        Size = UDim2.fromOffset(30, 30),
        BackgroundColor3 = Theme.Surface3,
        BackgroundTransparency = 0.5,
        BorderSizePixel = 0,
        Text = "",
        AutoButtonColor = false,
        Parent = row,
    })
    corner(button, UDim.new(0, 8))
    local buttonStroke = stroke(button)
    local image = create("ImageLabel", {
        AnchorPoint = Vector2.new(0.5, 0.5),
        Position = UDim2.fromScale(0.5, 0.5),
        Size = UDim2.fromOffset(14, 14),
        BackgroundTransparency = 1,
        ImageColor3 = Theme.Muted,
        ScaleType = Enum.ScaleType.Fit,
        Parent = button,
    })
    applyIcon(image, buttonIcon)
    button.MouseEnter:Connect(function()
        tween(button, { BackgroundTransparency = 0 }, 0.15, Enum.EasingStyle.Quint)
        tween(buttonStroke, { Color = Theme.StrokeHover }, 0.15)
        tween(image, { ImageColor3 = Theme.Accent }, 0.15)
    end)
    button.MouseLeave:Connect(function()
        tween(button, { BackgroundTransparency = 0.5 }, 0.25, Enum.EasingStyle.Quint)
        tween(buttonStroke, { Color = Theme.Stroke }, 0.25)
        tween(image, { ImageColor3 = Theme.Muted }, 0.25)
    end)
    button.MouseButton1Click:Connect(function()
        safeCall(callback)
    end)
    return row, titleLabel, textLabel
end

function Window:_homeLinks(parent, opts, order)
    local links = {}
    if opts.Discord then
        local discordIcon = opts.DiscordIcon
        if discordIcon == nil then
            discordIcon = "message-circle"
        end
        table.insert(links, {
            Icon = discordIcon,
            Title = opts.DiscordTitle or "Community",
            Text = opts.Discord,
        })
    end
    if opts.Website then
        local websiteIcon = opts.WebsiteIcon
        if websiteIcon == nil then
            websiteIcon = "globe"
        end
        table.insert(links, {
            Icon = websiteIcon,
            Title = opts.WebsiteTitle or "Website",
            Text = opts.Website,
        })
    end
    for _, link in ipairs(opts.Links or {}) do
        table.insert(links, link)
    end
    local features = opts.Features
    if #links == 0 and features == false then
        return nil, function() end
    end
    local card = self:_homeCard(parent, order)
    self:_homeCaption(card, "Links", 0)
    for index, link in ipairs(links) do
        local action = type(link.Callback) == "function"
        local linkIcon = link.Icon
        if linkIcon == nil then
            linkIcon = "link"
        end
        self:_homeLink(card, index, linkIcon, link.Title or "", link.Text or "", action and "arrow-up-right" or "copy", function()
            if action then
                safeCall(link.Callback)
            else
                self:CopyToClipboard(link.Copy or link.Text, link.Title)
            end
        end)
    end
    local refresh = function() end
    if features ~= false then
        if type(features) == "table" then
            self._featuresTitle = features.Title
            self._features = features.List or (#features > 0 and features or nil)
        end
        local featuresIcon
        if type(features) == "table" then
            featuresIcon = features.Icon
        end
        if featuresIcon == nil then
            featuresIcon = "list-checks"
        end
        local _, _, text_ = self:_homeLink(card, 100,
            featuresIcon,
            type(features) == "table" and features.Title or "Feature list",
            "", "chevron-right", function()
                self:ShowFeatures()
            end)
        refresh = function()
            local desc = type(features) == "table" and features.Desc
            text_.Text = desc or (self:_featureSummary())
        end
        task.defer(refresh)
    end
    -- The first row needs no rule above it.
    local first = nil
    for _, child in ipairs(card:GetChildren()) do
        if child:IsA("Frame") and child:FindFirstChild("Rule") and (not first or child.LayoutOrder < first.LayoutOrder) then
            first = child
        end
    end
    if first then
        first.Rule.Visible = false
    end
    return card, refresh
end

function Window:_homeExecutor(list, opts, order)
    local line = create("Frame", {
        Size = UDim2.new(1, 0, 0, 26),
        BackgroundTransparency = 1,
        LayoutOrder = order,
        Parent = list,
    })
    local executor, supported, message = executorReport(opts)
    local dot = create("Frame", {
        AnchorPoint = Vector2.new(0, 0.5),
        Position = UDim2.new(0, 4, 0.5, 0),
        Size = UDim2.fromOffset(7, 7),
        BackgroundColor3 = supported and Theme.Success or Theme.Warning,
        BorderSizePixel = 0,
        Parent = line,
    })
    corner(dot, UDim.new(1, 0))
    local left = create("Frame", {
        Position = UDim2.fromOffset(18, 0),
        Size = UDim2.new(1, -170, 1, 0),
        BackgroundTransparency = 1,
        ClipsDescendants = true,
        Parent = line,
    })
    create("UIListLayout", {
        FillDirection = Enum.FillDirection.Horizontal,
        VerticalAlignment = Enum.VerticalAlignment.Center,
        SortOrder = Enum.SortOrder.LayoutOrder,
        Padding = UDim.new(0, 8),
        Parent = left,
    })
    label({
        Size = UDim2.new(0, 0, 1, 0),
        AutomaticSize = Enum.AutomaticSize.X,
        Text = executor,
        TextSize = 12,
        TextTruncate = Enum.TextTruncate.None,
        LayoutOrder = 1,
        Parent = left,
    })
    label({
        Size = UDim2.new(0, 0, 1, 0),
        AutomaticSize = Enum.AutomaticSize.X,
        Text = message,
        TextSize = 12,
        FontFace = Fonts.Regular,
        TextColor3 = supported and Theme.Muted or Theme.Warning,
        TextTruncate = Enum.TextTruncate.None,
        LayoutOrder = 2,
        Parent = left,
    })

    local hint = create("Frame", {
        AnchorPoint = Vector2.new(1, 0.5),
        Position = UDim2.new(1, -2, 0.5, 0),
        Size = UDim2.fromOffset(0, 22),
        AutomaticSize = Enum.AutomaticSize.X,
        BackgroundTransparency = 1,
        Parent = line,
    })
    create("UIListLayout", {
        FillDirection = Enum.FillDirection.Horizontal,
        VerticalAlignment = Enum.VerticalAlignment.Center,
        SortOrder = Enum.SortOrder.LayoutOrder,
        Padding = UDim.new(0, 6),
        Parent = hint,
    })
    label({
        Size = UDim2.new(0, 0, 1, 0),
        AutomaticSize = Enum.AutomaticSize.X,
        Text = TOUCH and "Tap the pill or" or "Hide with",
        TextSize = 12,
        FontFace = Fonts.Regular,
        TextColor3 = Theme.Muted,
        TextTruncate = Enum.TextTruncate.None,
        LayoutOrder = 1,
        Parent = hint,
    })
    local chip = create("Frame", {
        Size = UDim2.fromOffset(0, 20),
        AutomaticSize = Enum.AutomaticSize.X,
        BackgroundColor3 = Theme.Surface3,
        BorderSizePixel = 0,
        LayoutOrder = 2,
        Parent = hint,
    })
    corner(chip, UDim.new(0, 5))
    stroke(chip)
    padding(chip, 6, 6)
    self._keyChipLabel = label({
        Size = UDim2.new(0, 0, 1, 0),
        AutomaticSize = Enum.AutomaticSize.X,
        Text = keyName(self.Keybind),
        TextSize = 11,
        FontFace = Fonts.Bold,
        TextTruncate = Enum.TextTruncate.None,
        Parent = chip,
    })
end

Window._featureKinds = {
    Toggle = true,
    Slider = true,
    Dropdown = true,
    Input = true,
    Keybind = true,
    ColorPicker = true,
    Stepper = true,
    Button = true,
    ButtonRow = true,
    OrderList = true,
}

function Window:_featureGroups()
    local found, byName = {}, {}
    for _, tab in ipairs(self.Tabs) do
        if tab ~= self.Home and tab._userVisible ~= false then
            local group = { Name = tab.Name, Icon = tab._iconName, Items = {} }
            for _, page in ipairs(tab._subTabs or { tab }) do
                local sub = page._isSubTab and page or nil
                local function add(name, element, box, path)
                    if type(name) ~= "string" or name == "" then
                        return
                    end
                    local item = {
                        Name = name,
                        Kind = element._type == "ButtonRow" and "Button" or element._type,
                        Path = path,
                        Result = { Tab = tab, Sub = sub, Target = element, Group = box },
                    }
                    table.insert(group.Items, item)
                    byName[string.lower(name)] = byName[string.lower(name)] or item
                end
                local function addElement(element, box, path)
                    if element._destroyed or not self._featureKinds[element._type] or (element._isShown and not element:_isShown()) then
                        return
                    end
                    if element._type == "ButtonRow" and element.Buttons then
                        for _, button in ipairs(element.Buttons) do
                            add(button.Label.Text, element, box, path)
                        end
                    else
                        add(element._searchName, element, box, path)
                    end
                end
                if not page._noSearch then
                    for _, element in ipairs(page._items or {}) do
                        addElement(element, nil, sub and sub.Name or nil)
                    end
                    for _, box in ipairs(page._groupboxes or {}) do
                        if box._userVisible ~= false and not box._manager then
                            for _, element in ipairs(box._items) do
                                addElement(element, box, sub and (sub.Name .. "  ›  " .. box.Name) or box.Name)
                            end
                        end
                    end
                end
            end
            if #group.Items > 0 then
                table.insert(found, group)
            end
        end
    end
    local custom = self._features
    if type(custom) ~= "table" then
        return found
    end
    local function customItem(entry)
        if type(entry) ~= "table" then
            entry = { Name = entry }
        end
        local name = tostring(entry.Name or entry.Title or entry[1] or "")
        local link = byName[string.lower(name)]
        return {
            Name = name,
            Desc = entry.Desc or entry.Description,
            Tag = entry.Tag,
            Icon = entry.Icon,
            Kind = link and link.Kind,
            Path = link and link.Path,
            Result = link and link.Result,
            Callback = entry.Callback,
        }
    end
    local groups, loose = {}, nil
    for _, entry in ipairs(custom) do
        if type(entry) == "table" and type(entry.Items) == "table" then
            local group = { Name = tostring(entry.Name or entry.Title or "Features"), Icon = entry.Icon, Items = {} }
            for _, item in ipairs(entry.Items) do
                table.insert(group.Items, customItem(item))
            end
            table.insert(groups, group)
        else
            if not loose then
                loose = { Name = self._featuresTitle or "Features", Items = {} }
                table.insert(groups, loose)
            end
            table.insert(loose.Items, customItem(entry))
        end
    end
    return groups
end

function Window:_featureSummary()
    local groups = self:_featureGroups()
    local count = 0
    for _, group in ipairs(groups) do
        count += #group.Items
    end
    local text = count .. (count == 1 and " feature" or " features")
    if type(self._features) ~= "table" and #groups > 0 then
        text ..= " across " .. #groups .. (#groups == 1 and " tab" or " tabs")
    end
    return text, groups, count
end

function Window:ShowFeatures()
    if self._dialog then
        self._dialog.Close()
    end
    local summary, groups, total = self:_featureSummary()
    local PAD = 16
    local ROW = TOUCH and 44 or 38
    local body = self.Body

    local overlay = create("TextButton", {
        Size = UDim2.fromScale(1, 1),
        BackgroundColor3 = Color3.new(0, 0, 0),
        BackgroundTransparency = 1,
        Text = "",
        AutoButtonColor = false,
        ZIndex = 40,
        Parent = body,
    })
    -- A canvas group so the whole list fades as one on open and close.
    local card_ = create("CanvasGroup", {
        AnchorPoint = Vector2.new(0.5, 0.5),
        Position = UDim2.new(0.5, 0, 0.5, 10),
        Size = UDim2.fromOffset(420, 460),
        BackgroundColor3 = Theme.Background,
        BorderSizePixel = 0,
        GroupTransparency = 1,
        Active = true,
        Parent = overlay,
    })
    corner(card_, UDim.new(0, 12))
    local cardStroke = stroke(card_, Theme.Stroke, 1)
    local cardScale = create("UIScale", { Scale = 0.94, Parent = card_ })
    local function fit()
        local scale = self.Scale.Scale
        local size = body.AbsoluteSize / scale
        card_.Size = UDim2.fromOffset(math.min(440, size.X - 24), math.min(480, size.Y - 24))
    end
    fit()
    local fitConnection = body:GetPropertyChangedSignal("AbsoluteSize"):Connect(fit)

    local iconHolder = glowIcon(card_, "list-checks", Theme.Accent, UDim2.new(0, PAD, 0, PAD + 10))
    iconHolder.Size = UDim2.fromOffset(18, 18)
    label({
        Position = UDim2.fromOffset(PAD + 28, PAD),
        Size = UDim2.new(1, -(PAD * 2 + 28 + 36), 0, 18),
        Text = self._featuresTitle or "Features",
        TextSize = 15,
        Parent = card_,
    })
    label({
        Position = UDim2.fromOffset(PAD + 28, PAD + 19),
        Size = UDim2.new(1, -(PAD * 2 + 28 + 36), 0, 14),
        Text = summary,
        TextSize = 12,
        FontFace = Fonts.Regular,
        TextColor3 = Theme.Muted,
        Parent = card_,
    })
    local closeButton = create("TextButton", {
        AnchorPoint = Vector2.new(1, 0),
        Position = UDim2.new(1, -(PAD - 6), 0, PAD - 6),
        Size = TOUCH and UDim2.fromOffset(40, 40) or UDim2.fromOffset(32, 32),
        BackgroundColor3 = Theme.Surface3,
        BackgroundTransparency = 1,
        Text = "",
        AutoButtonColor = false,
        Parent = card_,
    })
    corner(closeButton, UDim.new(0, 8))
    local closeIcon = create("ImageLabel", {
        AnchorPoint = Vector2.new(0.5, 0.5),
        Position = UDim2.fromScale(0.5, 0.5),
        Size = UDim2.fromOffset(16, 16),
        BackgroundTransparency = 1,
        ImageColor3 = Theme.Muted,
        ScaleType = Enum.ScaleType.Fit,
        Parent = closeButton,
    })
    applyIcon(closeIcon, "x")
    if closeIcon.Image == "" then
        closeIcon:Destroy()
        label({ Size = UDim2.fromScale(1, 1), Text = "×", TextSize = 20, TextColor3 = Theme.Muted, TextXAlignment = Enum.TextXAlignment.Center, Parent = closeButton })
    end
    closeButton.MouseEnter:Connect(function()
        tween(closeButton, { BackgroundTransparency = 0.5 }, 0.12)
    end)
    closeButton.MouseLeave:Connect(function()
        tween(closeButton, { BackgroundTransparency = 1 }, 0.2)
    end)

    local top = PAD + 44
    local searchHolder = create("Frame", {
        Position = UDim2.fromOffset(PAD, top),
        Size = UDim2.new(1, -PAD * 2, 0, TOUCH and 36 or 32),
        BackgroundColor3 = Theme.Surface,
        BorderSizePixel = 0,
        Parent = card_,
    })
    corner(searchHolder, UDim.new(0, 7))
    local searchStroke = stroke(searchHolder)
    local _, searchIcon = glowIcon(searchHolder, "search", Theme.Muted, UDim2.new(0, 10, 0.5, 0))
    searchIcon.Parent.Size = UDim2.fromOffset(14, 14)
    local searchBox = create("TextBox", {
        Position = UDim2.fromOffset(32, 0),
        Size = UDim2.new(1, -40, 1, 0),
        BackgroundTransparency = 1,
        Text = "",
        PlaceholderText = "Search features",
        PlaceholderColor3 = Theme.Muted,
        TextColor3 = Theme.Text,
        TextSize = 13,
        FontFace = Fonts.Regular,
        TextXAlignment = Enum.TextXAlignment.Left,
        TextTruncate = Enum.TextTruncate.AtEnd,
        ClearTextOnFocus = false,
        Parent = searchHolder,
    })
    searchBox.Focused:Connect(function()
        tween(searchStroke, { Color = Theme.StrokeHover }, 0.15)
        tween(searchIcon, { ImageColor3 = Theme.Accent }, 0.15)
    end)
    searchBox.FocusLost:Connect(function()
        tween(searchStroke, { Color = Theme.Stroke }, 0.2)
        tween(searchIcon, { ImageColor3 = Theme.Muted }, 0.2)
    end)
    top += (TOUCH and 36 or 32) + 10

    local scroller = create("ScrollingFrame", {
        Position = UDim2.fromOffset(PAD, top),
        Size = UDim2.new(1, -PAD * 2 + 6, 1, -(top + PAD - 4)),
        BackgroundTransparency = 1,
        BorderSizePixel = 0,
        ScrollBarThickness = TOUCH and 4 or 3,
        ScrollBarImageColor3 = Theme.Accent,
        ScrollBarImageTransparency = 0.4,
        ScrollingDirection = Enum.ScrollingDirection.Y,
        CanvasSize = UDim2.new(),
        Parent = card_,
    })
    local content = create("Frame", {
        Size = UDim2.new(1, -10, 0, 0),
        AutomaticSize = Enum.AutomaticSize.Y,
        BackgroundTransparency = 1,
        Parent = scroller,
    })
    local layout = create("UIListLayout", {
        SortOrder = Enum.SortOrder.LayoutOrder,
        Padding = UDim.new(0, 2),
        Parent = content,
    })
    -- Canvas sized by hand, as elsewhere, so it scrolls under UIScale.
    layout:GetPropertyChangedSignal("AbsoluteContentSize"):Connect(function()
        scroller.CanvasSize = UDim2.fromOffset(0, layout.AbsoluteContentSize.Y / self.Scale.Scale + 4)
    end)
    local noResults = label({
        Size = UDim2.new(1, 0, 0, 60),
        Text = total == 0 and "No features yet" or "No matches",
        TextSize = 13,
        FontFace = Fonts.Regular,
        TextColor3 = Theme.Muted,
        TextXAlignment = Enum.TextXAlignment.Center,
        LayoutOrder = 0,
        Visible = total == 0,
        Parent = content,
    })

    local dialog = {}
    local closed = false
    local stopEscape = nil
    function dialog.Close()
        if closed then
            return
        end
        closed = true
        if self._dialog == dialog then
            self._dialog = nil
        end
        fitConnection:Disconnect()
        if stopEscape then
            -- Deferred: Close can run from inside the input dispatch loop.
            task.defer(stopEscape)
        end
        if searchBox:IsFocused() then
            searchBox:ReleaseFocus()
        end
        tween(overlay, { BackgroundTransparency = 1 }, 0.18)
        tween(card_, { Position = UDim2.new(0.5, 0, 0.5, 8), GroupTransparency = 1 }, 0.18, Enum.EasingStyle.Quint)
        tween(cardScale, { Scale = 0.96 }, 0.18, Enum.EasingStyle.Quint)
        tween(cardStroke, { Transparency = 1 }, 0.12)
        task.delay(0.2, function()
            overlay:Destroy()
        end)
    end

    local sections = {}
    local order = 0
    for _, group in ipairs(groups) do
        order += 1
        local header = create("Frame", {
            Size = UDim2.new(1, 0, 0, 30),
            BackgroundTransparency = 1,
            LayoutOrder = order,
            Parent = content,
        })
        local groupIcon = group.Icon
        if groupIcon == nil then
            groupIcon = "layout-grid"
        end
        local headX = 24
        if groupIcon ~= false then
            local headIcon = glowIcon(header, groupIcon, Theme.Accent, UDim2.new(0, 2, 0, 18))
            headIcon.Size = UDim2.fromOffset(14, 14)
        else
            headX = 2
        end
        label({
            Position = UDim2.fromOffset(headX, 10),
            Size = UDim2.new(1, -70, 0, 16),
            Text = string.upper(group.Name),
            TextSize = 11,
            TextColor3 = Theme.Muted,
            Parent = header,
        })
        local countLabel = label({
            AnchorPoint = Vector2.new(1, 0),
            Position = UDim2.new(1, -4, 0, 10),
            Size = UDim2.new(0, 40, 0, 16),
            Text = tostring(#group.Items),
            TextSize = 11,
            TextColor3 = Theme.Muted,
            TextXAlignment = Enum.TextXAlignment.Right,
            Parent = header,
        })
        local section = { Header = header, Count = countLabel, Rows = {} }
        for _, item in ipairs(group.Items) do
            order += 1
            local sub = item.Desc or item.Path
            local clickable = item.Result ~= nil or type(item.Callback) == "function"
            local row = create("TextButton", {
                Size = UDim2.new(1, 0, 0, sub and ROW + 4 or ROW - 4),
                BackgroundColor3 = Theme.Surface2,
                BackgroundTransparency = 1,
                BorderSizePixel = 0,
                Text = "",
                AutoButtonColor = false,
                LayoutOrder = order,
                Parent = content,
            })
            corner(row, UDim.new(0, 8))
            local rowIconValue = item.Icon
            if rowIconValue == nil then
                rowIconValue = self._searchIcons[item.Kind] or "check"
            end
            local rowIcon
            if rowIconValue ~= false then
                rowIcon = glowIcon(row, rowIconValue, Theme.Muted, UDim2.new(0, 10, 0.5, 0))
                rowIcon.Size = UDim2.fromOffset(14, 14)
            end
            local textX = rowIcon and 34 or 10
            local right = 12 + (clickable and 22 or 0)
            local tag
            if item.Tag then
                tag = create("Frame", {
                    AnchorPoint = Vector2.new(1, 0.5),
                    Position = UDim2.new(1, -(clickable and 30 or 10), 0.5, 0),
                    Size = UDim2.fromOffset(0, 20),
                    AutomaticSize = Enum.AutomaticSize.X,
                    BackgroundColor3 = Theme.Accent,
                    BackgroundTransparency = 0.85,
                    BorderSizePixel = 0,
                    Parent = row,
                })
                corner(tag, UDim.new(0, 5))
                padding(tag, 7, 7)
                label({
                    Size = UDim2.new(0, 0, 1, 0),
                    AutomaticSize = Enum.AutomaticSize.X,
                    Text = tostring(item.Tag),
                    TextSize = 11,
                    TextColor3 = Theme.Accent,
                    TextTruncate = Enum.TextTruncate.None,
                    Parent = tag,
                })
            end
            local nameLabel = label({
                Position = UDim2.fromOffset(textX, sub and 5 or 0),
                Size = UDim2.new(1, -(textX + right), 0, sub and 18 or ROW - 4),
                Text = item.Name,
                TextSize = 13,
                Parent = row,
            })
            local subLabel
            if sub then
                subLabel = label({
                    Position = UDim2.fromOffset(textX, 23),
                    Size = UDim2.new(1, -(textX + right), 0, 14),
                    Text = sub,
                    TextSize = 11,
                    FontFace = Fonts.Regular,
                    TextColor3 = Theme.Muted,
                    Parent = row,
                })
            end
            if tag then
                local function reserveTag()
                    local width = textX + right + tag.AbsoluteSize.X / self.Scale.Scale + 8
                    nameLabel.Size = UDim2.new(1, -width, 0, nameLabel.Size.Y.Offset)
                    if subLabel then
                        subLabel.Size = UDim2.new(1, -width, 0, 14)
                    end
                end
                tag:GetPropertyChangedSignal("AbsoluteSize"):Connect(reserveTag)
                task.defer(reserveTag)
            end
            if clickable then
                local go = create("ImageLabel", {
                    AnchorPoint = Vector2.new(1, 0.5),
                    Position = UDim2.new(1, -10, 0.5, 0),
                    Size = UDim2.fromOffset(14, 14),
                    BackgroundTransparency = 1,
                    ImageColor3 = Theme.Muted,
                    ImageTransparency = 0.4,
                    ScaleType = Enum.ScaleType.Fit,
                    Parent = row,
                })
                applyIcon(go, "arrow-up-right")
            end
            local isTap = tapGuard(row, function()
                return scroller
            end)
            row.MouseEnter:Connect(function()
                if not usingTouch() then
                    tween(row, { BackgroundTransparency = 0.3 }, 0.12)
                end
            end)
            row.MouseLeave:Connect(function()
                tween(row, { BackgroundTransparency = 1 }, 0.2)
            end)
            row.MouseButton1Click:Connect(function()
                if not clickable or not isTap() then
                    return
                end
                dialog.Close()
                if item.Result then
                    self:_revealResult(item.Result)
                end
                safeCall(item.Callback)
            end)
            table.insert(section.Rows, { Frame = row, Key = string.lower(item.Name .. " " .. (sub or "")) })
        end
        table.insert(sections, section)
    end

    searchBox:GetPropertyChangedSignal("Text"):Connect(function()
        local query = string.lower(searchBox.Text)
        local any = false
        for _, section in ipairs(sections) do
            local shown = 0
            for _, row in ipairs(section.Rows) do
                local match = query == "" or string.find(row.Key, query, 1, true) ~= nil
                row.Frame.Visible = match
                if match then
                    shown += 1
                end
            end
            section.Header.Visible = shown > 0
            section.Count.Text = tostring(shown)
            any = any or shown > 0
        end
        noResults.Visible = not any
        scroller.CanvasPosition = Vector2.zero
    end)
    closeButton.MouseButton1Click:Connect(dialog.Close)
    overlay.MouseButton1Click:Connect(dialog.Close)
    stopEscape = self:_listen("Began", function(input)
        if input.KeyCode == Enum.KeyCode.Escape then
            dialog.Close()
        end
    end)

    self._dialog = dialog
    tween(overlay, { BackgroundTransparency = 0.45 }, 0.25)
    tween(card_, { Position = UDim2.fromScale(0.5, 0.5), GroupTransparency = 0 }, 0.3, Enum.EasingStyle.Quint)
    tween(cardScale, { Scale = 1 }, 0.4, Enum.EasingStyle.Back)
    return dialog
end

function Window:_homeStats(list, opts, order, tab)
    local show = opts.Stats or { "Players", "Execs", "Session", "FPS", "Ping" }
    local card = self:_homeCard(list, order)
    local graphs = create("Frame", {
        Size = UDim2.new(1, 0, 0, 76),
        BackgroundTransparency = 1,
        LayoutOrder = 1,
        Parent = card,
    })
    create("UIGridLayout", {
        CellPadding = UDim2.fromOffset(24, 0),
        CellSize = UDim2.new(0.5, -12, 0, 76),
        SortOrder = Enum.SortOrder.LayoutOrder,
        Parent = graphs,
    })
    local rule = create("Frame", {
        Size = UDim2.new(1, 0, 0, 1),
        BackgroundColor3 = Theme.Stroke,
        BorderSizePixel = 0,
        LayoutOrder = 2,
        Parent = card,
    })
    local figures = create("Frame", {
        Size = UDim2.new(1, 0, 0, 0),
        AutomaticSize = Enum.AutomaticSize.Y,
        BackgroundTransparency = 1,
        LayoutOrder = 3,
        Parent = card,
    })
    padding(figures, 0, 0, 12, 0)
    local figureGrid = create("UIGridLayout", {
        CellPadding = UDim2.fromOffset(0, 8),
        CellSize = UDim2.new(0.25, 0, 0, 36),
        SortOrder = Enum.SortOrder.LayoutOrder,
        Parent = figures,
    })
    local values, sparks = {}, {}
    local graphCount, figureCount = 0, 0
    for index, name in ipairs(show) do
        local kind = STAT_TYPES[name]
        if kind and not values[name] then
            if name == "FPS" or name == "Ping" then
                graphCount += 1
                values[name], sparks[name] = self:_homeGraph(graphs, index, kind[1], kind[2], name == "FPS" and 60 or 100)
            else
                figureCount += 1
                values[name] = self:_homeFigure(figures, index, kind[2])
            end
        end
    end
    graphs.Visible = graphCount > 0
    figures.Visible = figureCount > 0
    rule.Visible = graphCount > 0 and figureCount > 0
    if graphCount == 0 then
        padding(figures, 0, 0, 0, 0)
    end
    local function fitFigures()
        local width = figures.AbsoluteSize.X / self.Scale.Scale
        local columns = math.clamp(figureCount, 1, width >= 440 and 5 or 3)
        figureGrid.CellSize = UDim2.new(1 / columns, 0, 0, 36)
    end
    figures:GetPropertyChangedSignal("AbsoluteSize"):Connect(fitFigures)
    task.defer(fitFigures)

    if values.Executor then
        values.Executor.Text = detectExecutor()
    end
    if values.Game then
        values.Game.Text = "Loading"
        task.spawn(function()
            values.Game.Text = detectGameName()
        end)
    end
    if values.Execs then
        local executions = bumpExecutions(opts.StatsFolder or self.ConfigFolder)
        values.Execs.Text = executions and tostring(executions) or "—"
    end
    if values.Friends then
        local friends = {}
        local function recount()
            local total = 0
            for _, player in ipairs(Players:GetPlayers()) do
                if player ~= LocalPlayer then
                    local known = friends[player.UserId]
                    if known == nil then
                        local ok, result = pcall(function()
                            return LocalPlayer:IsFriendsWith(player.UserId)
                        end)
                        known = ok and result == true
                        friends[player.UserId] = known
                    end
                    if known then
                        total += 1
                    end
                end
            end
            values.Friends.Text = tostring(total)
        end
        task.spawn(recount)
        table.insert(self._connections, Players.PlayerAdded:Connect(function()
            task.spawn(recount)
        end))
        table.insert(self._connections, Players.PlayerRemoving:Connect(function()
            task.defer(recount)
        end))
    end

    local session = values.Session or values.Uptime
    local started = os.clock()
    local frames = 0
    self:_listen("Render", function()
        frames += 1
    end)
    local tinted = opts.StatColors ~= false
    local function tint(valueLabel, color)
        if tinted and valueLabel.TextColor3 ~= color then
            tween(valueLabel, { TextColor3 = color }, 0.3)
        end
    end
    return function()
        if values.FPS then
            values.FPS.Text = tostring(frames)
            tint(values.FPS, Library._healthColor(frames, 50, 30))
            sparks.FPS(frames, Library._healthColor(frames, 50, 30))
        end
        frames = 0
        if values.Ping then
            local ok, ping = pcall(function()
                return math.floor(LocalPlayer:GetNetworkPing() * 1000)
            end)
            ping = ok and ping or 0
            values.Ping.Text = ping .. "ms"
            tint(values.Ping, Library._healthColor(ping, 90, 180, true))
            sparks.Ping(ping, Library._healthColor(ping, 90, 180, true))
        end
        if values.Players then
            values.Players.Text = #Players:GetPlayers() .. "/" .. Players.MaxPlayers
        end
        if session then
            session.Text = formatDuration(os.clock() - started)
        end
        if values.Time then
            values.Time.Text = os.date(opts.TimeFormat or "%H:%M")
        end
        if values.ServerAge then
            values.ServerAge.Text = formatDuration(workspace.DistributedGameTime)
        end
        if values.Memory then
            local ok, memory = pcall(function()
                return StatsService:GetTotalMemoryUsageMb()
            end)
            values.Memory.Text = ok and string.format("%d MB", memory) or "—"
            tint(values.Memory, ok and Library._healthColor(memory, 1500, 3000, true) or Theme.Text)
        end
    end, function()
        frames = 0
    end
end

local function changelogEntries(source)
    if type(source) ~= "table" then
        return nil
    end
    local entries = source.Entries or source.Updates or source.Versions
    if type(entries) ~= "table" then
        if source[1] ~= nil then
            entries = source
        elseif source.Version ~= nil or source.Changes ~= nil or source.Content ~= nil then
            entries = { source }
        end
    end
    if type(entries) ~= "table" or #entries == 0 then
        return nil
    end
    return entries
end

local function changelogTag(value)
    if type(value) == "number" then
        local ok, date = pcall(os.date, "%b %d", value)
        if ok then
            return (date:gsub(" 0", " "))
        end
        return tostring(value)
    end
    return value ~= nil and tostring(value) or nil
end

local function changelogPage(sub, entries, config)
    local list = sub.List
    local showLatest = config.Latest ~= false
    for index, entry in ipairs(entries) do
        if type(entry) == "string" then
            entry = { Content = entry }
        end
        if type(entry) == "table" then
            local card_ = panelCard(list, 0, index)
            card_.AutomaticSize = Enum.AutomaticSize.Y
            padding(card_, 16, 16, 14, 14)
            create("UIListLayout", {
                SortOrder = Enum.SortOrder.LayoutOrder,
                Padding = UDim.new(0, 10),
                Parent = card_,
            })
            local head = create("Frame", {
                Size = UDim2.new(1, 0, 0, 22),
                BackgroundTransparency = 1,
                LayoutOrder = 1,
                Parent = card_,
            })
            label({
                Size = UDim2.new(1, -100, 1, 0),
                Text = tostring(entry.Version or entry.Title or entry.Name or "Update"),
                TextSize = 15,
                FontFace = Fonts.Bold,
                Parent = head,
            })
            local tag = entry.Tag
            if tag == false then
                tag = nil
            else
                if tag == nil then
                    tag = changelogTag(entry.Date)
                end
                if tag == nil then
                    if entry.Latest == true or (entry.Latest ~= false and showLatest and index == 1) then
                        tag = "Latest"
                    end
                end
            end
            if tag ~= nil then
                local chip = create("Frame", {
                    AnchorPoint = Vector2.new(1, 0.5),
                    Position = UDim2.new(1, 0, 0.5, 0),
                    Size = UDim2.new(0, 0, 0, 20),
                    AutomaticSize = Enum.AutomaticSize.X,
                    BackgroundColor3 = Theme.Surface3,
                    BackgroundTransparency = 0.35,
                    BorderSizePixel = 0,
                    Parent = head,
                })
                corner(chip, UDim.new(0, 6))
                padding(chip, 9, 9)
                label({
                    Size = UDim2.new(0, 0, 1, 0),
                    AutomaticSize = Enum.AutomaticSize.X,
                    Text = tostring(tag),
                    TextSize = 11,
                    TextColor3 = Theme.Muted,
                    TextTruncate = Enum.TextTruncate.None,
                    Parent = chip,
                })
            end
            local changes = entry.Changes or entry.Items
            if type(changes) == "string" then
                changes = { changes }
            end
            if type(changes) == "table" and #changes > 0 then
                local body = create("Frame", {
                    Size = UDim2.new(1, 0, 0, 0),
                    AutomaticSize = Enum.AutomaticSize.Y,
                    BackgroundTransparency = 1,
                    LayoutOrder = 2,
                    Parent = card_,
                })
                create("UIListLayout", {
                    SortOrder = Enum.SortOrder.LayoutOrder,
                    Padding = UDim.new(0, 4),
                    Parent = body,
                })
                for changeIndex, change in ipairs(changes) do
                    local row = create("Frame", {
                        Size = UDim2.new(1, 0, 0, 0),
                        AutomaticSize = Enum.AutomaticSize.Y,
                        BackgroundTransparency = 1,
                        LayoutOrder = changeIndex,
                        Parent = body,
                    })
                    label({
                        Size = UDim2.fromOffset(12, 18),
                        Text = "•",
                        TextSize = 13,
                        FontFace = Fonts.Regular,
                        TextColor3 = Theme.Muted,
                        TextYAlignment = Enum.TextYAlignment.Top,
                        Parent = row,
                    })
                    label({
                        Position = UDim2.fromOffset(14, 0),
                        Size = UDim2.new(1, -14, 0, 0),
                        AutomaticSize = Enum.AutomaticSize.Y,
                        Text = tostring(change),
                        TextSize = 13,
                        FontFace = Fonts.Regular,
                        TextColor3 = Theme.Muted,
                        TextWrapped = true,
                        TextTruncate = Enum.TextTruncate.None,
                        TextYAlignment = Enum.TextYAlignment.Top,
                        Parent = row,
                    })
                end
            else
                local text = entry.Content or entry.Body
                if text then
                    label({
                        Size = UDim2.new(1, 0, 0, 0),
                        AutomaticSize = Enum.AutomaticSize.Y,
                        Text = tostring(text),
                        TextSize = 13,
                        FontFace = Fonts.Regular,
                        TextColor3 = Theme.Muted,
                        TextWrapped = true,
                        TextTruncate = Enum.TextTruncate.None,
                        TextYAlignment = Enum.TextYAlignment.Top,
                        LayoutOrder = 2,
                        Parent = card_,
                    })
                end
            end
        end
    end
    if type(config.Build) == "function" then
        safeCall(config.Build, sub, list)
    else
        sub._noSearch = true
    end
end

local function homePage(sub, page)
    local list = sub.List
    if type(page.Content) == "string" then
        local card_ = panelCard(list, 0, 1)
        card_.AutomaticSize = Enum.AutomaticSize.Y
        padding(card_, 16, 16, 14, 16)
        label({
            Size = UDim2.new(1, 0, 0, 0),
            AutomaticSize = Enum.AutomaticSize.Y,
            Text = page.Content,
            TextSize = 13,
            FontFace = Fonts.Regular,
            TextColor3 = Theme.Muted,
            TextWrapped = true,
            TextTruncate = Enum.TextTruncate.None,
            TextYAlignment = Enum.TextYAlignment.Top,
            Parent = card_,
        })
    end
    if type(page.Entries) == "table" then
        for index, entry in ipairs(page.Entries) do
            local card_ = panelCard(list, 0, index + 1)
            card_.AutomaticSize = Enum.AutomaticSize.Y
            padding(card_, 16, 16, 14, 16)
            create("UIListLayout", {
                SortOrder = Enum.SortOrder.LayoutOrder,
                Padding = UDim.new(0, 6),
                Parent = card_,
            })
            local head = create("Frame", {
                Size = UDim2.new(1, 0, 0, 20),
                BackgroundTransparency = 1,
                LayoutOrder = 1,
                Parent = card_,
            })
            label({
                Size = UDim2.new(1, -90, 1, 0),
                Text = entry.Title or entry.Version or "Update",
                TextSize = 15,
                Parent = head,
            })
            if entry.Date or entry.Tag then
                local chip = create("Frame", {
                    AnchorPoint = Vector2.new(1, 0.5),
                    Position = UDim2.new(1, 0, 0.5, 0),
                    Size = UDim2.fromOffset(0, 20),
                    AutomaticSize = Enum.AutomaticSize.X,
                    BackgroundColor3 = Theme.Surface,
                    BorderSizePixel = 0,
                    Parent = head,
                })
                corner(chip, UDim.new(0, 5))
                stroke(chip)
                padding(chip, 8, 8)
                label({
                    Size = UDim2.new(0, 0, 1, 0),
                    AutomaticSize = Enum.AutomaticSize.X,
                    Text = entry.Tag or entry.Date,
                    TextSize = 11,
                    TextColor3 = Theme.Muted,
                    TextTruncate = Enum.TextTruncate.None,
                    Parent = chip,
                })
            end
            local body = entry.Content or entry.Body
            if type(entry.Changes) == "table" then
                body = "• " .. table.concat(entry.Changes, "\n• ")
            end
            if body then
                label({
                    Size = UDim2.new(1, 0, 0, 0),
                    AutomaticSize = Enum.AutomaticSize.Y,
                    Text = body,
                    TextSize = 13,
                    FontFace = Fonts.Regular,
                    TextColor3 = Theme.Muted,
                    TextWrapped = true,
                    TextTruncate = Enum.TextTruncate.None,
                    TextYAlignment = Enum.TextYAlignment.Top,
                    LayoutOrder = 2,
                    Parent = card_,
                })
            end
        end
    end
    if type(page.Build) == "function" then
        safeCall(page.Build, sub, list)
    else
        sub._noSearch = true
    end
end

function Window:_buildHome(opts)
    self._hideName = opts.HideName == true
    self._hideAvatar = opts.HideAvatar == true
    self:_renderIdentity(true)
    local homeIcon = opts.Icon
    if homeIcon == nil then
        homeIcon = "house"
    end
    local tab = self:Tab({
        Name = opts.Name or "Home",
        Desc = opts.Desc,
        Icon = homeIcon,
        PageTitle = opts.Title or "Home",
    })
    tab._order = 100
    self.Home = tab

    local pages = opts.Pages or opts.Tabs
    local changelogConfig = type(opts.Changelog) == "table" and opts.Changelog or nil
    local changelogList = changelogEntries(changelogConfig)
    if not changelogList and changelogConfig and type(changelogConfig.Build) == "function" then
        changelogList = {}
    end

    local detailIcon = opts.DetailIcon or opts.TabIcon
    if detailIcon == nil then
        detailIcon = "layout-grid"
    end
    local detail = tab:SubTab({
        Name = opts.DetailName or opts.OverviewName or "Detail",
        Icon = detailIcon,
    })
    detail._noSearch = true
    detail._order = 100
    tab.Detail = detail
    self.Detail = detail
    local list = detail.List

    local refreshExpiry = self:_homeProfile(list, opts, 1)
    local refreshStats, resetStats = self:_homeStats(list, opts, 2, tab)

    -- Server and links side by side, stacked when narrow.
    local split = create("Frame", {
        Size = UDim2.new(1, 0, 0, 0),
        AutomaticSize = Enum.AutomaticSize.Y,
        BackgroundTransparency = 1,
        LayoutOrder = 3,
        Parent = list,
    })
    local splitLayout = create("UIListLayout", {
        SortOrder = Enum.SortOrder.LayoutOrder,
        Padding = UDim.new(0, 10),
        Parent = split,
    })
    local function column(order_)
        local frame = create("Frame", {
            Size = UDim2.new(1, 0, 0, 0),
            AutomaticSize = Enum.AutomaticSize.Y,
            BackgroundTransparency = 1,
            LayoutOrder = order_,
            Parent = split,
        })
        create("UIListLayout", { SortOrder = Enum.SortOrder.LayoutOrder, Parent = frame })
        return frame
    end
    local leftColumn, rightColumn = column(1), column(2)
    local refreshGame = self:_homeGame(leftColumn, 1)
    local linksCard, refreshFeatures = self:_homeLinks(rightColumn, opts, 1)
    if not linksCard then
        rightColumn:Destroy()
    end
    local function fitSplit()
        local wide = linksCard ~= nil and split.AbsoluteSize.X / self.Scale.Scale >= 540
        splitLayout.FillDirection = wide and Enum.FillDirection.Horizontal or Enum.FillDirection.Vertical
        local size = wide and UDim2.new(0.5, -5, 0, 0) or UDim2.new(1, 0, 0, 0)
        leftColumn.Size = size
        if linksCard then
            rightColumn.Size = size
        end
    end
    split:GetPropertyChangedSignal("AbsoluteSize"):Connect(fitSplit)
    task.defer(fitSplit)

    self:_homeExecutor(list, opts, 4)

    if changelogList then
        local changelogIcon = changelogConfig.Icon or opts.ChangelogIcon
        if changelogIcon == nil then
            changelogIcon = "history"
        end
        local changelogTab = tab:SubTab({
            Name = changelogConfig.Name or changelogConfig.Title or opts.ChangelogName or "Changelog",
            Icon = changelogIcon,
            EmptyText = changelogConfig.EmptyText or "No changes yet",
        })
        changelogTab._order = 101
        tab.Changelog = changelogTab
        self.Changelog = changelogTab
        changelogPage(changelogTab, changelogList, changelogConfig)
    end

    if type(pages) == "table" then
        for _, page in ipairs(pages) do
            homePage(tab:SubTab({ Name = page.Name or page.Title or "Page", Icon = page.Icon }), page)
        end
    end

    refreshExpiry()
    refreshStats()
    refreshGame()
    task.spawn(function()
        while not self._destroyed and tab._page.Parent do
            task.wait(1)
            if self.Open and self.CurrentTab == tab then
                refreshStats()
                refreshExpiry()
                refreshGame()
                refreshFeatures()
            else
                resetStats()
            end
        end
    end)
    return tab
end

function Window:Tab(opts, icon)
    opts = normalize(opts, { Title = "Name", Description = "Desc" })
    if icon ~= nil and opts.Icon == nil then
        opts.Icon = cleanIcon(icon)
    end
    local tab = setmetatable({
        Name = opts.Name or "Tab",
        Window = self,
        _order = 0,
    }, Tab)

    local button = create("TextButton", {
        Size = UDim2.new(1, 0, 0, TAB_TILE_HEIGHT),
        BackgroundColor3 = Theme.Surface3,
        BackgroundTransparency = 1,
        Text = "",
        AutoButtonColor = false,
        LayoutOrder = #self.Tabs + 1,
        Parent = self._tabStack,
    })
    corner(button, UDim.new(0, 7))
    local buttonStroke = stroke(button, Theme.Stroke, 1)
    buttonStroke.Enabled = false
    tab._button = button

    local hasIcon = opts.Icon ~= nil and opts.Icon ~= false
    if hasIcon then
        local iconImage = create("ImageLabel", {
            AnchorPoint = Vector2.new(0.5, 0.5),
            Position = UDim2.new(0, 20, 0.5, 0),
            Size = UDim2.fromOffset(16, 16),
            BackgroundTransparency = 1,
            ImageColor3 = Theme.Muted,
            ScaleType = Enum.ScaleType.Fit,
            Parent = button,
        })
        applyIcon(iconImage, opts.Icon)
        if iconImage:GetAttribute("CustomIcon") then
            iconImage.ImageTransparency = 0.4
        end
        tab._icon = iconImage
    end
    tab._label = label({
        Position = UDim2.fromOffset(hasIcon and 38 or 14, 0),
        Size = UDim2.new(1, hasIcon and -46 or -22, 1, 0),
        Text = tab.Name,
        TextSize = 13,
        TextColor3 = Theme.Muted,
        Parent = button,
    })

    local page = create("Frame", {
        Name = tab.Name,
        Size = UDim2.fromScale(1, 1),
        BackgroundTransparency = 1,
        Visible = false,
        Parent = self.Content,
    })
    tab._page = page
    local titleX = 24
    if hasIcon then
        local holder = glowIcon(page, opts.Icon, Theme.Accent, UDim2.new(0, 24, 0, 32))
        holder.Size = UDim2.fromOffset(20, 20)
        titleX = 54
    end
    tab._titleX = titleX
    tab._title = label({
        Position = UDim2.fromOffset(titleX, 20),
        Size = UDim2.new(1, -titleX, 0, 24),
        Text = opts.PageTitle or tab.Name,
        TextSize = 22,
        Parent = page,
    })
    if opts.Desc then
        tab._desc = label({
            Position = UDim2.fromOffset(titleX, 44),
            Size = UDim2.new(1, -titleX, 0, 16),
            Text = opts.Desc,
            TextSize = 13,
            FontFace = Fonts.Regular,
            TextColor3 = Theme.Muted,
            Parent = page,
        })
    end
    local listTop = opts.Desc and 70 or 58
    tab._headerBottom = listTop
    tab._iconName = opts.Icon
    local emptyIcon = opts.Icon
    if emptyIcon == nil then
        emptyIcon = "layout-grid"
    end
    buildContainer(tab, page, listTop, emptyIcon, opts.EmptyText or "Nothing here yet")

    local pressScale = create("UIScale", { Parent = button })
    local function release()
        tween(pressScale, { Scale = 1 }, 0.3, Enum.EasingStyle.Quint)
    end
    button.MouseEnter:Connect(function()
        if self.CurrentTab ~= tab and not usingTouch() then
            tween(button, { BackgroundTransparency = 0.75 }, 0.2, Enum.EasingStyle.Quint)
            tween(tab._label, { TextColor3 = Theme.Text }, 0.2)
            if tab._icon then
                tintIcon(tab._icon, Theme.Text, true, 0.2)
            end
        end
    end)
    button.MouseLeave:Connect(function()
        release()
        if self.CurrentTab ~= tab then
            tween(button, { BackgroundTransparency = 1 }, 0.3, Enum.EasingStyle.Quint)
            tween(tab._label, { TextColor3 = Theme.Muted }, 0.3)
            if tab._icon then
                tintIcon(tab._icon, Theme.Muted, false, 0.3)
            end
        end
    end)
    button.MouseButton1Down:Connect(function()
        tween(pressScale, { Scale = 0.97 }, 0.15, Enum.EasingStyle.Quint)
    end)
    button.MouseButton1Up:Connect(release)
    local isTap = tapGuard(button, function()
        return self.TabList
    end)
    button.MouseButton1Click:Connect(function()
        release()
        if isTap() then
            self:SelectTab(tab)
        end
    end)
    tab._stroke = buttonStroke
    self:_fitTitle(tab)

    if not self._introDone then
        button.Visible = false
    end
    table.insert(self.Tabs, tab)
    if #self.Tabs == 1 then
        task.defer(function()
            if not self.CurrentTab then
                self:SelectTab(tab)
            end
        end)
    end
    return tab
end

Window.CreateTab = Window.Tab

function Window:CloudConfigs(opts)
    opts = normalize(opts, { Title = "Name", Description = "Desc" })
    local window = self
    local tabIcon = opts.Icon
    if tabIcon == nil then
        tabIcon = "cloud"
    end
    local tab = self:Tab({
        Name = opts.Name or "Cloud",
        Desc = opts.Desc,
        Icon = tabIcon,
        PageTitle = opts.PageTitle,
    })
    tab._noSearch = true
    tab.List.Visible = false
    if tab._empty then
        tab._empty:Destroy()
        tab._empty = nil
    end

    local CARD = 116
    local ROW = TOUCH and 36 or 32
    local CHIP = TOUCH and 30 or 26
    local SORTS = { "Popular", "New", "Top", "Installs" }
    local SORT_NAMES = { Popular = "Popular", New = "Newest", Top = "Top rated", Installs = "Most installed" }
    local FILTERS = { "All", "Favorites", "Mine", "Installed" }
    local NAME_LIMIT = 40
    local DESC_LIMIT = math.max(math.floor(tonumber(opts.DescriptionLimit) or 300), 20)
    local pageSize = math.max(math.floor(tonumber(opts.PageSize) or 20), 1)
    local tagList = type(opts.Tags) == "table" and opts.Tags or {}
    local maxTags = math.max(math.floor(tonumber(opts.MaxTags) or 3), 0)
    local anonName = tostring(opts.StreamerName or "Ouroboros User")

    local cloud = { Tab = tab }
    local records, byId = {}, {}
    local cards = {}
    local hasMore, page, token = false, 0, 0
    local loading = false
    local query = { Search = "", Sort = "Popular", Filter = "All", Tag = nil }
    local views, currentView = {}, nil
    local detail, detailRecord, detailToken = {}, nil, 0

    local stored = window:_readConfigSettings()
    local favorites = type(stored.CloudFavorites) == "table" and stored.CloudFavorites or {}
    local installed = type(stored.CloudInstalled) == "table" and stored.CloudInstalled or {}
    if table.find(SORTS, stored.CloudSort) then
        query.Sort = stored.CloudSort
    elseif table.find(SORTS, opts.Sort) then
        query.Sort = opts.Sort
    end
    local function persist(key, value)
        window:_writeConfigSettings({ [key] = value })
    end

    local function notify(ok, title, detail_)
        window:Notify({ Title = title, Content = detail_, Type = ok and "Success" or "Error", Duration = 3 })
    end

    -- The Home tab's hide-name switch doubles as streamer mode.
    local function streamerOn()
        return window._hideName == true
    end

    -- Records

    local function countFlags(code)
        local data = type(code) == "string" and window:DecodeConfig(code)
        if not data then
            return nil
        end
        local count = 0
        for _ in pairs(data) do
            count += 1
        end
        return count
    end

    local function compact(number)
        number = math.max(math.floor(tonumber(number) or 0), 0)
        if number >= 1e6 then
            return (("%.1f"):format(number / 1e6):gsub("%.0$", "")) .. "m"
        elseif number >= 1e3 then
            return (("%.1f"):format(number / 1e3):gsub("%.0$", "")) .. "k"
        end
        return tostring(number)
    end

    local function ago(stamp)
        stamp = tonumber(stamp)
        if not stamp then
            return nil
        end
        local delta = os.time() - stamp
        if delta < 60 then
            return "just now"
        elseif delta < 3600 then
            return math.floor(delta / 60) .. "m ago"
        elseif delta < 86400 then
            return math.floor(delta / 3600) .. "h ago"
        elseif delta < 604800 then
            return math.floor(delta / 86400) .. "d ago"
        elseif delta < 2592000 then
            return math.floor(delta / 604800) .. "w ago"
        end
        return os.date("%d %b %Y", stamp)
    end

    local function escape(text)
        return (text:gsub("&", "&amp;"):gsub("<", "&lt;"):gsub(">", "&gt;"):gsub('"', "&quot;"):gsub("'", "&apos;"))
    end

    -- Rich text with every match of the search drawn in the accent.
    local function highlight(text)
        local needle = string.lower(query.Search)
        if needle == "" then
            return escape(text)
        end
        local lower = string.lower(text)
        local hex = colorToHex(Theme.Accent)
        local out, from = {}, 1
        while true do
            local first, last = string.find(lower, needle, from, true)
            if not first then
                break
            end
            table.insert(out, escape(text:sub(from, first - 1)))
            table.insert(out, ('<font color="#%s"><b>%s</b></font>'):format(hex, escape(text:sub(first, last))))
            from = last + 1
        end
        table.insert(out, escape(text:sub(from)))
        return table.concat(out)
    end

    local function normalizeRecord(raw)
        if type(raw) ~= "table" then
            return nil
        end
        local id = raw.Id ~= nil and tostring(raw.Id) or HttpService:GenerateGUID(false)
        local record = byId[id] or { Id = id }
        for key, value in pairs(raw) do
            if key ~= "Id" then
                record[key] = value
            end
        end
        record.Name = tostring(record.Name or "Untitled")
        record.Author = tostring(record.Author or "Unknown")
        record.Description = record.Description ~= nil and tostring(record.Description) or ""
        local tags = {}
        for _, tag in ipairs(type(record.Tags) == "table" and record.Tags or {}) do
            table.insert(tags, tostring(tag))
        end
        record.Tags = tags
        record.Installs = tonumber(record.Installs) or 0
        record.Likes = tonumber(record.Likes) or 0
        record.Updated = tonumber(record.Updated or record.Created)
        record.Liked = record.Liked == true
        if type(record.Code) ~= "string" or record.Code == "" then
            record.Code = nil
        end
        record.Count = tonumber(record.Count) or countFlags(record.Code)
        record.Mine = record.Mine == true or tonumber(record.AuthorId) == LocalPlayer.UserId or tonumber(record.OwnerId) == LocalPlayer.UserId
        byId[id] = record
        return record
    end

    local function publicRecord(record)
        return {
            Id = record.Id,
            Name = record.Name,
            Description = record.Description,
            Author = record.Author,
            AuthorId = record.AuthorId,
            Tags = table.clone(record.Tags),
            Installs = record.Installs,
            Likes = record.Likes,
            Liked = record.Liked,
            Updated = record.Updated,
            Code = record.Code,
            Count = record.Count,
            Folder = record.Folder,
            Mine = record.Mine,
        }
    end

    -- What is kept locally for favorites and installs: no code, it is refetched.
    local function summary(record)
        local kept = publicRecord(record)
        kept.Code = nil
        kept.Liked = nil
        return kept
    end

    local function installState(record)
        local mark = installed[record.Id]
        if type(mark) ~= "table" then
            return nil
        end
        if record.Updated and tonumber(mark.Updated) and record.Updated > tonumber(mark.Updated) then
            return "Update"
        end
        return "Installed"
    end

    local function otherScript(record)
        return type(record.Folder) == "string" and record.Folder ~= window.ConfigFolder
    end

    -- Small pieces

    local function iconButton(parent, icon, glyph, size, plain)
        local button = create("TextButton", {
            Size = UDim2.fromOffset(size, size),
            BackgroundColor3 = Theme.Surface2,
            BackgroundTransparency = plain and 1 or 0,
            Text = "",
            AutoButtonColor = false,
            Parent = parent,
        })
        corner(button, UDim.new(0, 8))
        if not plain then
            hoverStroke(button, stroke(button))
        end
        local image = create("ImageLabel", {
            AnchorPoint = Vector2.new(0.5, 0.5),
            Position = UDim2.fromScale(0.5, 0.5),
            Size = UDim2.fromOffset(15, 15),
            BackgroundTransparency = 1,
            ImageColor3 = Theme.Muted,
            ScaleType = Enum.ScaleType.Fit,
            Parent = button,
        })
        applyIcon(image, icon)
        if image.Image == "" then
            image:Destroy()
            image = label({
                Size = UDim2.fromScale(1, 1),
                Text = glyph,
                TextSize = 15,
                TextColor3 = Theme.Muted,
                TextXAlignment = Enum.TextXAlignment.Center,
                TextTruncate = Enum.TextTruncate.None,
                Parent = button,
            })
        end
        return button, image
    end

    local function primary(button, text_)
        tween(button, { BackgroundColor3 = Theme.Accent, BackgroundTransparency = 0.12 }, 0)
        tween(text_, { TextColor3 = Theme.AccentDark }, 0)
        text_.FontFace = Fonts.Bold
    end

    local function clear(parent)
        for _, child in ipairs(parent:GetChildren()) do
            if child:IsA("GuiObject") then
                child:Destroy()
            end
        end
    end

    local function chip(parent, text, order, onClick)
        local button = create("TextButton", {
            Size = UDim2.fromOffset(0, CHIP),
            AutomaticSize = Enum.AutomaticSize.X,
            BackgroundColor3 = Theme.Surface2,
            Text = "",
            AutoButtonColor = false,
            LayoutOrder = order,
            Parent = parent,
        })
        button:SetAttribute("NoDrag", true)
        corner(button, UDim.new(1, 0))
        local chipStroke = stroke(button)
        padding(button, 12, 12)
        local text_ = label({
            Size = UDim2.new(0, 0, 1, 0),
            AutomaticSize = Enum.AutomaticSize.X,
            Text = text,
            TextSize = 12,
            TextColor3 = Theme.Muted,
            TextTruncate = Enum.TextTruncate.None,
            Parent = button,
        })
        local object = { Button = button, Label = text_ }
        function object.Set(on, instant)
            local duration = instant and 0 or 0.15
            tween(button, { BackgroundColor3 = on and Theme.Accent or Theme.Surface2 }, duration)
            tween(text_, { TextColor3 = on and Theme.AccentDark or Theme.Muted }, duration)
            tween(chipStroke, { Transparency = on and 1 or 0 }, duration)
        end
        if onClick then
            button.MouseButton1Click:Connect(onClick)
        else
            button.Active = false
        end
        return object
    end

    local function tagPill(parent, text, order)
        local pill = label({
            Size = UDim2.fromOffset(0, 18),
            AutomaticSize = Enum.AutomaticSize.X,
            BackgroundColor3 = Theme.Surface3,
            BackgroundTransparency = 0.2,
            Text = text,
            TextSize = 11,
            TextColor3 = Theme.Muted,
            TextXAlignment = Enum.TextXAlignment.Center,
            TextTruncate = Enum.TextTruncate.None,
            LayoutOrder = order,
            Parent = parent,
        })
        corner(pill, UDim.new(0, 5))
        padding(pill, 7, 7)
        return pill
    end

    local function hlist(parent, gap, wraps)
        return create("UIListLayout", {
            FillDirection = Enum.FillDirection.Horizontal,
            VerticalAlignment = Enum.VerticalAlignment.Center,
            SortOrder = Enum.SortOrder.LayoutOrder,
            Padding = UDim.new(0, gap),
            Wraps = wraps == true,
            Parent = parent,
        })
    end

    local function vlist(parent, gap)
        return create("UIListLayout", {
            SortOrder = Enum.SortOrder.LayoutOrder,
            Padding = UDim.new(0, gap),
            Parent = parent,
        })
    end

    local function wrapped(parent, text, size, color, order, font)
        return label({
            Size = UDim2.new(1, 0, 0, 0),
            AutomaticSize = Enum.AutomaticSize.Y,
            Text = text,
            TextSize = size,
            FontFace = font or Fonts.Regular,
            TextColor3 = color or Theme.Text,
            TextWrapped = true,
            TextTruncate = Enum.TextTruncate.None,
            TextYAlignment = Enum.TextYAlignment.Top,
            LayoutOrder = order,
            Parent = parent,
        })
    end

    local function scroller(parent, visible)
        local frame = create("ScrollingFrame", {
            Size = UDim2.fromScale(1, 1),
            BackgroundTransparency = 1,
            BorderSizePixel = 0,
            ScrollBarThickness = 3,
            ScrollBarImageColor3 = Theme.Accent,
            ScrollBarImageTransparency = 0.4,
            ScrollingDirection = Enum.ScrollingDirection.Y,
            AutomaticCanvasSize = Enum.AutomaticSize.Y,
            CanvasSize = UDim2.new(),
            Visible = visible ~= false,
            Parent = parent,
        })
        frame:SetAttribute("NoDrag", true)
        return frame
    end

    -- A text box on the surface colour. Multi-line boxes show a counter.
    local function field(parent, order, placeholder, height, limit)
        local multi = height > ROW
        local holder = create("Frame", {
            Size = UDim2.new(1, 0, 0, height),
            BackgroundColor3 = Theme.Surface,
            BorderSizePixel = 0,
            ClipsDescendants = true,
            LayoutOrder = order,
            Parent = parent,
        })
        corner(holder, UDim.new(0, 8))
        local holderStroke = stroke(holder)
        local box = create("TextBox", {
            Position = UDim2.fromOffset(10, multi and 8 or 0),
            Size = UDim2.new(1, -20, 1, multi and -24 or 0),
            BackgroundTransparency = 1,
            Text = "",
            PlaceholderText = placeholder,
            PlaceholderColor3 = Theme.Muted,
            TextColor3 = Theme.Text,
            TextSize = 13,
            FontFace = Fonts.Regular,
            TextXAlignment = Enum.TextXAlignment.Left,
            TextYAlignment = multi and Enum.TextYAlignment.Top or Enum.TextYAlignment.Center,
            MultiLine = multi,
            TextWrapped = multi,
            ClearTextOnFocus = false,
            Parent = holder,
        })
        local counter = multi and label({
            AnchorPoint = Vector2.new(1, 1),
            Position = UDim2.new(1, -10, 1, -4),
            Size = UDim2.fromOffset(0, 14),
            AutomaticSize = Enum.AutomaticSize.X,
            Text = "",
            TextSize = 11,
            FontFace = Fonts.Regular,
            TextColor3 = Theme.Muted,
            TextTruncate = Enum.TextTruncate.None,
            Parent = holder,
        })
        box.Focused:Connect(function()
            tween(holderStroke, { Color = Theme.StrokeHover }, 0.15)
        end)
        box.FocusLost:Connect(function()
            tween(holderStroke, { Color = Theme.Stroke }, 0.2)
        end)
        box:GetPropertyChangedSignal("Text"):Connect(function()
            local text = box.Text
            local length = utf8.len(text) or #text
            if limit and length > limit then
                local cut = utf8.offset(text, limit + 1)
                box.Text = cut and text:sub(1, cut - 1) or text:sub(1, limit)
                return
            end
            if counter then
                counter.Text = limit and (length .. "/" .. limit) or ""
            end
        end)
        if counter and limit then
            counter.Text = "0/" .. limit
        end
        return box, holderStroke
    end

    local function uniqueName(base)
        base = trim((tostring(base or ""):gsub('[\\/:%*%?"<>|]', "")))
        if base == "" then
            base = "Cloud config"
        end
        local name, index = base, 2
        while window:ConfigExists(name) do
            name = ("%s (%d)"):format(base, index)
            index += 1
        end
        return name
    end

    -- Layout: the page holds three views that slide over each other.

    local top = tab._headerBottom
    local root = create("Frame", {
        Position = UDim2.fromOffset(23, top - 1),
        Size = UDim2.new(1, -46, 1, -(top + 14)),
        BackgroundTransparency = 1,
        ClipsDescendants = true,
        Parent = tab._page,
    })
    for _, name in ipairs({ "Browse", "Detail", "Publish" }) do
        views[name] = create("Frame", {
            Size = UDim2.fromScale(1, 1),
            BackgroundTransparency = 1,
            Visible = false,
            Parent = root,
        })
        padding(views[name], 1, 1, 1, 1)
    end

    local function showView(view)
        if currentView == view then
            return
        end
        local previous = currentView
        currentView = view
        if previous then
            previous.Visible = false
        end
        local fromX = view == views.Browse and -24 or 24
        view.Position = UDim2.fromOffset(fromX, 0)
        view.Visible = true
        tween(view, { Position = UDim2.fromOffset(0, 0) }, 0.3, Enum.EasingStyle.Quint)
    end

    -- Browse: search, publish and refresh, the filter strip, then results.

    local browse = views.Browse
    local toolbar = create("Frame", {
        Size = UDim2.new(1, 0, 0, ROW),
        BackgroundTransparency = 1,
        Parent = browse,
    })
    local publishButton, publishText = softButton(toolbar, "Publish", {
        AnchorPoint = Vector2.new(1, 0),
        Position = UDim2.fromScale(1, 0),
        Size = UDim2.new(0, 0, 1, 0),
        AutomaticSize = Enum.AutomaticSize.X,
    }, function()
        cloud:OpenPublish()
    end)
    primary(publishButton, publishText)
    publishButton.Visible = type(opts.OnPublish) == "function"
    local refreshButton, refreshIcon = iconButton(toolbar, "refresh-cw", "R", ROW)
    refreshButton.AnchorPoint = Vector2.new(1, 0)
    local searchHolder = create("Frame", {
        Size = UDim2.new(1, -(ROW + 8), 1, 0),
        BackgroundColor3 = Theme.Surface2,
        BorderSizePixel = 0,
        Parent = toolbar,
    })
    corner(searchHolder, UDim.new(0, 8))
    local searchStroke = stroke(searchHolder)
    local searchIcon, searchImage = glowIcon(searchHolder, "search", Theme.Muted, UDim2.new(0, 10, 0.5, 0))
    searchIcon.Size = UDim2.fromOffset(14, 14)
    local searchBox = create("TextBox", {
        Position = UDim2.fromOffset(32, 0),
        Size = UDim2.new(1, -62, 1, 0),
        BackgroundTransparency = 1,
        Text = "",
        PlaceholderText = opts.SearchPlaceholder or (TOUCH and "Search configs..." or "Search configs...   ( / )"),
        PlaceholderColor3 = Theme.Muted,
        TextColor3 = Theme.Text,
        TextSize = 13,
        FontFace = Fonts.Regular,
        TextXAlignment = Enum.TextXAlignment.Left,
        ClearTextOnFocus = false,
        ClipsDescendants = true,
        Parent = searchHolder,
    })
    local searchClear = iconButton(searchHolder, "x", "x", 24, true)
    searchClear.AnchorPoint = Vector2.new(1, 0.5)
    searchClear.Position = UDim2.new(1, -4, 0.5, 0)
    searchClear.Visible = false

    local fetch
    local searchToken = 0
    local recent = type(stored.CloudRecent) == "table" and stored.CloudRecent or {}
    local recentFrame = create("Frame", {
        Position = UDim2.fromOffset(0, ROW + 4),
        Size = UDim2.new(1, 0, 0, 0),
        AutomaticSize = Enum.AutomaticSize.Y,
        BackgroundColor3 = Theme.Surface2,
        BorderSizePixel = 0,
        Visible = false,
        ZIndex = 5,
        Parent = browse,
    })
    corner(recentFrame, UDim.new(0, 8))
    stroke(recentFrame)
    padding(recentFrame, 6, 6, 6, 6)
    vlist(recentFrame, 2)

    local function rememberSearch(text)
        text = trim(text)
        if #text < 2 then
            return
        end
        for index = #recent, 1, -1 do
            if string.lower(recent[index]) == string.lower(text) then
                table.remove(recent, index)
            end
        end
        table.insert(recent, 1, text)
        while #recent > 6 do
            table.remove(recent)
        end
        persist("CloudRecent", recent)
    end

    local function showRecent(show)
        show = show and #recent > 0 and searchBox.Text == ""
        if show == recentFrame.Visible then
            return
        end
        recentFrame.Visible = show
        if not show then
            return
        end
        clear(recentFrame)
        local header = create("Frame", {
            Size = UDim2.new(1, 0, 0, 20),
            BackgroundTransparency = 1,
            LayoutOrder = 0,
            Parent = recentFrame,
        })
        label({
            Position = UDim2.fromOffset(8, 0),
            Size = UDim2.new(1, -60, 1, 0),
            Text = "Recent searches",
            TextSize = 11,
            TextColor3 = Theme.Muted,
            Parent = header,
        })
        local wipe = create("TextButton", {
            AnchorPoint = Vector2.new(1, 0),
            Position = UDim2.new(1, -6, 0, 0),
            Size = UDim2.fromOffset(0, 20),
            AutomaticSize = Enum.AutomaticSize.X,
            BackgroundTransparency = 1,
            Text = "Clear",
            TextSize = 11,
            FontFace = Fonts.Medium,
            TextColor3 = Theme.Accent,
            AutoButtonColor = false,
            Parent = header,
        })
        wipe.MouseButton1Down:Connect(function()
            recent = {}
            persist("CloudRecent", recent)
            showRecent(false)
        end)
        for index, text in ipairs(recent) do
            local row = create("TextButton", {
                Size = UDim2.new(1, 0, 0, TOUCH and 32 or 28),
                BackgroundColor3 = Theme.Surface3,
                BackgroundTransparency = 1,
                Text = "",
                AutoButtonColor = false,
                LayoutOrder = index,
                Parent = recentFrame,
            })
            corner(row, UDim.new(0, 6))
            local icon = glowIcon(row, "history", Theme.Muted, UDim2.new(0, 8, 0.5, 0))
            icon.Size = UDim2.fromOffset(13, 13)
            label({
                Position = UDim2.fromOffset(28, 0),
                Size = UDim2.new(1, -34, 1, 0),
                Text = text,
                TextSize = 13,
                FontFace = Fonts.Regular,
                Parent = row,
            })
            row.MouseEnter:Connect(function()
                tween(row, { BackgroundTransparency = 0.5 }, 0.1)
            end)
            row.MouseLeave:Connect(function()
                tween(row, { BackgroundTransparency = 1 }, 0.15)
            end)
            row.MouseButton1Down:Connect(function()
                searchToken += 1
                searchBox.Text = text
                query.Search = text
                rememberSearch(text)
                showRecent(false)
                searchBox:ReleaseFocus()
                fetch(false)
            end)
        end
    end

    local function fitToolbar()
        local scale = window.Scale.Scale
        local publishWidth = publishButton.Visible and (publishButton.AbsoluteSize.X / scale + 8) or 0
        refreshButton.Position = UDim2.new(1, -publishWidth, 0, 0)
        searchHolder.Size = UDim2.new(1, -(publishWidth + ROW + 8), 1, 0)
        recentFrame.Size = UDim2.new(1, -(publishWidth + ROW + 8), 0, 0)
    end
    publishButton:GetPropertyChangedSignal("AbsoluteSize"):Connect(fitToolbar)
    task.defer(fitToolbar)

    -- A pixel taller than the chips on each side, so their strokes aren't clipped.
    local filterRow = create("Frame", {
        Position = UDim2.fromOffset(0, ROW + 7),
        Size = UDim2.new(1, 0, 0, CHIP + 2),
        BackgroundTransparency = 1,
        Parent = browse,
    })
    local sortButton = create("TextButton", {
        AnchorPoint = Vector2.new(1, 0),
        Position = UDim2.new(1, -1, 0, 1),
        Size = UDim2.fromOffset(0, CHIP),
        AutomaticSize = Enum.AutomaticSize.X,
        BackgroundColor3 = Theme.Surface2,
        Text = "",
        AutoButtonColor = false,
        Parent = filterRow,
    })
    corner(sortButton, UDim.new(1, 0))
    hoverStroke(sortButton, stroke(sortButton))
    padding(sortButton, 10, 12)
    hlist(sortButton, 6)
    local sortIcon = glowIcon(sortButton, "arrow-down-up", Theme.Accent, UDim2.new())
    sortIcon.Size = UDim2.fromOffset(13, 13)
    local sortLabel = label({
        Size = UDim2.new(0, 0, 1, 0),
        AutomaticSize = Enum.AutomaticSize.X,
        Text = SORT_NAMES[query.Sort],
        TextSize = 12,
        TextTruncate = Enum.TextTruncate.None,
        LayoutOrder = 2,
        Parent = sortButton,
    })
    local filterStrip = create("ScrollingFrame", {
        Size = UDim2.new(1, -120, 1, 0),
        BackgroundTransparency = 1,
        BorderSizePixel = 0,
        ScrollBarThickness = 0,
        ScrollingDirection = Enum.ScrollingDirection.X,
        AutomaticCanvasSize = Enum.AutomaticSize.X,
        CanvasSize = UDim2.new(),
        Parent = filterRow,
    })
    filterStrip:SetAttribute("NoDrag", true)
    hlist(filterStrip, 6)
    padding(filterStrip, 1, 1, 1, 1)
    local function fitFilters()
        local width = sortButton.AbsoluteSize.X / window.Scale.Scale
        filterStrip.Size = UDim2.new(1, -(width + 8), 1, 0)
    end
    sortButton:GetPropertyChangedSignal("AbsoluteSize"):Connect(fitFilters)
    task.defer(fitFilters)

    local resultsTop = ROW + 8 + CHIP + 10
    local results = scroller(browse)
    results.Position = UDim2.fromOffset(0, resultsTop)
    results.Size = UDim2.new(1, 0, 1, -resultsTop)
    padding(results, 1, 6, 1, 12)
    vlist(results, 10)
    local summaryRow = create("Frame", {
        Size = UDim2.new(1, 0, 0, 16),
        BackgroundTransparency = 1,
        LayoutOrder = 0,
        Parent = results,
    })
    local summaryLabel = label({
        Size = UDim2.new(1, -100, 1, 0),
        Text = "",
        RichText = true,
        TextSize = 12,
        FontFace = Fonts.Regular,
        TextColor3 = Theme.Muted,
        Parent = summaryRow,
    })
    local resetButton = create("TextButton", {
        AnchorPoint = Vector2.new(1, 0),
        Position = UDim2.fromScale(1, 0),
        Size = UDim2.fromOffset(0, 16),
        AutomaticSize = Enum.AutomaticSize.X,
        BackgroundTransparency = 1,
        Text = "Clear filters",
        TextSize = 12,
        FontFace = Fonts.Medium,
        TextColor3 = Theme.Accent,
        AutoButtonColor = false,
        Visible = false,
        Parent = summaryRow,
    })
    local resetFilters

    local function filtered()
        return query.Search ~= "" or query.Tag ~= nil or query.Filter ~= "All"
    end

    -- "12 configs in Favorites, tagged PvP, matching "boss"", or "Searching..."
    local function renderSummary(pending)
        local parts = {}
        if query.Filter ~= "All" then
            table.insert(parts, "in " .. query.Filter)
        end
        if query.Tag then
            table.insert(parts, "tagged " .. escape(query.Tag))
        end
        if query.Search ~= "" then
            table.insert(parts, ('matching <font color="#%s">"%s"</font>'):format(colorToHex(Theme.Accent), escape(query.Search)))
        end
        local context = #parts > 0 and (" " .. table.concat(parts, ", ")) or ""
        if pending or (loading and #records == 0) then
            summaryLabel.Text = "Searching" .. context .. "..."
        else
            local count = #records
            summaryLabel.Text = ("%d%s config%s%s"):format(count, hasMore and "+" or "", (count == 1 and not hasMore) and "" or "s", context)
        end
        resetButton.Visible = filtered()
    end

    local spin = nil
    local function busy(on)
        loading = on
        if on and not spin then
            refreshIcon.Rotation = 0
            spin = TweenService:Create(refreshIcon, TweenInfo.new(0.9, Enum.EasingStyle.Linear, Enum.EasingDirection.In, -1), { Rotation = 360 })
            spin:Play()
        elseif not on and spin then
            spin:Cancel()
            spin = nil
            tween(refreshIcon, { Rotation = 360 }, 0.35, Enum.EasingStyle.Quint)
        end
        renderSummary()
    end
    local grid = create("Frame", {
        Size = UDim2.new(1, 0, 0, 0),
        AutomaticSize = Enum.AutomaticSize.Y,
        BackgroundTransparency = 1,
        LayoutOrder = 1,
        Parent = results,
    })
    local gridLayout = create("UIGridLayout", {
        CellSize = UDim2.new(1, 0, 0, CARD),
        CellPadding = UDim2.fromOffset(8, 8),
        SortOrder = Enum.SortOrder.LayoutOrder,
        Parent = grid,
    })
    local function fitGrid()
        local width = results.AbsoluteSize.X / window.Scale.Scale
        local columns = width >= 620 and 2 or 1
        gridLayout.CellSize = UDim2.new(1 / columns, -(columns - 1) * 8 / columns, 0, CARD)
    end
    results:GetPropertyChangedSignal("AbsoluteSize"):Connect(fitGrid)
    task.defer(fitGrid)
    local moreButton = softButton(results, "Load more", {
        Size = UDim2.new(1, 0, 0, 32),
        LayoutOrder = 2,
        Visible = false,
    }, function()
        cloud:LoadMore()
    end)
    local stateFrame = create("Frame", {
        Size = UDim2.new(1, 0, 0, 180),
        BackgroundTransparency = 1,
        Visible = false,
        LayoutOrder = 3,
        Parent = results,
    })

    -- Loading placeholders that pulse where cards will land.
    local skeletons = {}
    local function addSkeletons(count)
        for _ = 1, count do
            local cell = create("Frame", {
                BackgroundColor3 = Theme.Surface2,
                BorderSizePixel = 0,
                LayoutOrder = 100000 + #skeletons,
                Parent = grid,
            })
            corner(cell, UDim.new(0, 10))
            stroke(cell)
            for index, spec in ipairs({ { 14, 0.45 }, { 36, 0.3 }, { 58, 0.8 }, { 76, 0.6 } }) do
                local bar = create("Frame", {
                    Position = UDim2.fromOffset(14, spec[1]),
                    Size = UDim2.new(spec[2], -14, 0, index == 1 and 14 or 10),
                    BackgroundColor3 = Theme.Surface3,
                    BorderSizePixel = 0,
                    Parent = cell,
                })
                corner(bar, UDim.new(0, 4))
                TweenService:Create(bar, TweenInfo.new(0.75, Enum.EasingStyle.Sine, Enum.EasingDirection.InOut, -1, true), {
                    BackgroundTransparency = 0.65,
                }):Play()
            end
            table.insert(skeletons, cell)
        end
    end
    local function clearSkeletons()
        for _, cell in ipairs(skeletons) do
            cell:Destroy()
        end
        skeletons = {}
    end

    -- kind: nil hides it, or "empty" / "error" with a message.
    local function setState(kind, text)
        clear(stateFrame)
        stateFrame.Visible = kind ~= nil
        if not kind then
            return
        end
        local holder, caption = emptyState(stateFrame, kind == "error" and "cloud-off" or "search-x", text)
        holder.Size = UDim2.fromOffset(280, 70)
        holder.Position = UDim2.new(0.5, 0, 0, 60)
        caption.TextWrapped = true
        caption.TextTruncate = Enum.TextTruncate.None
        caption.Size = UDim2.new(1, 0, 0, 32)
        if kind == "error" or filtered() then
            softButton(stateFrame, kind == "error" and "Try again" or "Clear filters", {
                AnchorPoint = Vector2.new(0.5, 0),
                Position = UDim2.new(0.5, 0, 0, 132),
                Size = UDim2.fromOffset(0, 30),
                AutomaticSize = Enum.AutomaticSize.X,
            }, function()
                if kind == "error" then
                    cloud:Refresh()
                else
                    resetFilters()
                end
            end)
        end
        renderSummary()
    end

    -- Cards

    local openDetail, installRecord, refreshRecord

    local function renderCard(card)
        local record = card.Record
        card.Title.Text = highlight(record.Name)
        local meta = { "by " .. record.Author }
        local when = ago(record.Updated)
        if when then
            table.insert(meta, when)
        end
        if record.Count then
            table.insert(meta, record.Count .. (record.Count == 1 and " setting" or " settings"))
        end
        card.Meta.Text = table.concat(meta, "  ·  ")
        card.Desc.Text = record.Description ~= "" and highlight(record.Description) or "No description"
        card.Desc.TextTransparency = record.Description ~= "" and 0.2 or 0.55
        card.Likes.Text = compact(record.Likes)
        card.Installs.Text = compact(record.Installs)
        tween(card.Heart, { ImageColor3 = record.Liked and Theme.Accent or Theme.Muted }, 0.15)
        local state = installState(record)
        local badge, color
        if state == "Update" then
            badge, color = "UPDATE", Theme.Accent
        elseif state == "Installed" then
            badge, color = "INSTALLED", Theme.Success
        elseif record.Mine then
            badge, color = "YOURS", Theme.Accent
        elseif otherScript(record) then
            badge, color = "OTHER SCRIPT", Theme.Warning
        end
        card.Badge.Visible = badge ~= nil
        if badge then
            card.Badge.Text = badge
            tween(card.Badge, { TextColor3 = color, BackgroundColor3 = color }, 0)
        end
        card.Star.Visible = favorites[record.Id] ~= nil
        card.InstallText.Text = state == "Update" and "Update" or (state == "Installed" and "Reinstall" or "Install")
        clear(card.TagRow)
        for index, tag in ipairs(record.Tags) do
            if index > 3 then
                tagPill(card.TagRow, "+" .. (#record.Tags - 3), index)
                break
            end
            tagPill(card.TagRow, tag, index)
        end
    end

    local function buildCard(record, order)
        local frame = create("TextButton", {
            BackgroundColor3 = Theme.Surface2,
            BorderSizePixel = 0,
            Text = "",
            AutoButtonColor = false,
            LayoutOrder = order,
            Parent = grid,
        })
        frame:SetAttribute("NoDrag", true)
        corner(frame, UDim.new(0, 10))
        hoverStroke(frame, stroke(frame))
        padding(frame, 14, 14, 12, 12)
        local card = { Record = record, Frame = frame }
        card.Title = label({
            Size = UDim2.new(1, -110, 0, 18),
            RichText = true,
            TextSize = 14,
            FontFace = Fonts.Bold,
            Parent = frame,
        })
        local corner_ = create("Frame", {
            AnchorPoint = Vector2.new(1, 0),
            Position = UDim2.fromScale(1, 0),
            Size = UDim2.fromOffset(0, 18),
            AutomaticSize = Enum.AutomaticSize.X,
            BackgroundTransparency = 1,
            Parent = frame,
        })
        local cornerLayout = hlist(corner_, 6)
        cornerLayout.HorizontalAlignment = Enum.HorizontalAlignment.Right
        card.Star = label({
            Size = UDim2.fromOffset(14, 18),
            Text = "★",
            TextSize = 13,
            TextColor3 = Theme.Accent,
            TextXAlignment = Enum.TextXAlignment.Center,
            TextTruncate = Enum.TextTruncate.None,
            LayoutOrder = 1,
            Parent = corner_,
        })
        card.Badge = label({
            Size = UDim2.fromOffset(0, 17),
            AutomaticSize = Enum.AutomaticSize.X,
            BackgroundTransparency = 0.85,
            TextSize = 10,
            FontFace = Fonts.Bold,
            TextXAlignment = Enum.TextXAlignment.Center,
            TextTruncate = Enum.TextTruncate.None,
            LayoutOrder = 2,
            Parent = corner_,
        })
        corner(card.Badge, UDim.new(0, 5))
        padding(card.Badge, 6, 6)
        card.Meta = label({
            Position = UDim2.fromOffset(0, 20),
            Size = UDim2.new(1, 0, 0, 16),
            TextSize = 12,
            FontFace = Fonts.Regular,
            TextColor3 = Theme.Muted,
            Parent = frame,
        })
        card.Desc = label({
            Position = UDim2.fromOffset(0, 41),
            RichText = true,
            Size = UDim2.new(1, 0, 0, 30),
            TextSize = 12,
            FontFace = Fonts.Regular,
            TextWrapped = true,
            TextYAlignment = Enum.TextYAlignment.Top,
            Parent = frame,
        })
        local bottom = create("Frame", {
            AnchorPoint = Vector2.new(0, 1),
            Position = UDim2.fromScale(0, 1),
            Size = UDim2.new(1, 0, 0, 26),
            BackgroundTransparency = 1,
            Parent = frame,
        })
        card.TagRow = create("Frame", {
            Size = UDim2.new(1, -190, 1, 0),
            BackgroundTransparency = 1,
            ClipsDescendants = true,
            Parent = bottom,
        })
        hlist(card.TagRow, 4)
        local install, installText = softButton(bottom, "Install", {
            AnchorPoint = Vector2.new(1, 0.5),
            Position = UDim2.new(1, 0, 0.5, 0),
            Size = UDim2.fromOffset(76, 26),
        }, function()
            installRecord(record)
        end)
        primary(install, installText)
        card.InstallText = installText
        local stats = create("Frame", {
            AnchorPoint = Vector2.new(1, 0.5),
            Position = UDim2.new(1, -86, 0.5, 0),
            Size = UDim2.fromOffset(0, 20),
            AutomaticSize = Enum.AutomaticSize.X,
            BackgroundTransparency = 1,
            Parent = bottom,
        })
        hlist(stats, 4)
        local function stat(icon, order_)
            local holder, image = glowIcon(stats, icon, Theme.Muted, UDim2.new())
            holder.Size = UDim2.fromOffset(12, 12)
            holder.LayoutOrder = order_
            local text_ = label({
                Size = UDim2.fromOffset(0, 20),
                AutomaticSize = Enum.AutomaticSize.X,
                TextSize = 12,
                TextColor3 = Theme.Muted,
                TextTruncate = Enum.TextTruncate.None,
                LayoutOrder = order_ + 1,
                Parent = stats,
            })
            return text_, image
        end
        card.Likes, card.Heart = stat("heart", 1)
        create("Frame", { Size = UDim2.fromOffset(4, 1), BackgroundTransparency = 1, LayoutOrder = 3, Parent = stats })
        card.Installs = stat("download", 4)
        local isTap = tapGuard(frame, function()
            return results
        end)
        frame.MouseButton1Click:Connect(function()
            if isTap() then
                if query.Search ~= "" then
                    rememberSearch(query.Search)
                end
                openDetail(record)
            end
        end)
        cards[record.Id] = card
        renderCard(card)
        return card
    end

    local function renderList()
        for _, card in pairs(cards) do
            card.Frame:Destroy()
        end
        cards = {}
        for index, record in ipairs(records) do
            buildCard(record, index)
        end
    end

    -- Favorites and Installed are kept on this device, so they filter locally.
    local function localRecords()
        local source = query.Filter == "Favorites" and favorites or installed
        local search = string.lower(query.Search)
        local list = {}
        for id, entry in pairs(source) do
            local kept = query.Filter == "Favorites" and entry or (type(entry) == "table" and entry.Record)
            if type(kept) == "table" then
                kept = table.clone(kept)
                kept.Id = id
                local record = normalizeRecord(kept)
                local matches = search == "" or string.find(string.lower(record.Name), search, 1, true)
                    or string.find(string.lower(record.Description), search, 1, true)
                if matches and query.Tag then
                    matches = table.find(record.Tags, query.Tag) ~= nil
                end
                if matches then
                    table.insert(list, record)
                end
            end
        end
        table.sort(list, function(a, b)
            if query.Sort == "New" then
                return (a.Updated or 0) > (b.Updated or 0)
            elseif query.Sort == "Installs" then
                return a.Installs > b.Installs
            end
            return a.Likes > b.Likes
        end)
        return list
    end

    local function emptyText()
        if query.Filter == "Favorites" then
            return "No favorites yet. Open a config and press Favorite to keep it here."
        elseif query.Filter == "Installed" then
            return "Nothing installed from the cloud yet"
        elseif query.Filter == "Mine" then
            return "You haven't published anything yet"
        elseif query.Search ~= "" or query.Tag then
            return "No configs match your search"
        end
        return tostring(opts.EmptyText or "No configs shared yet. Be the first!")
    end

    function fetch(more)
        token += 1
        local myToken = token
        if query.Filter == "Favorites" or query.Filter == "Installed" then
            busy(false)
            clearSkeletons()
            records = localRecords()
            hasMore = false
            renderList()
            moreButton.Visible = false
            setState(#records == 0 and "empty" or nil, emptyText())
            return
        end
        if type(opts.OnFetch) ~= "function" then
            renderList()
            setState(#records == 0 and "empty" or nil, emptyText())
            return
        end
        if more then
            if not hasMore then
                return
            end
            page += 1
        else
            page = 1
            records = {}
            renderList()
            results.CanvasPosition = Vector2.zero
        end
        busy(true)
        clearSkeletons()
        addSkeletons(more and 2 or 4)
        moreButton.Visible = false
        setState(nil)
        local fetchQuery = {
            Search = query.Search,
            Sort = query.Sort,
            Filter = query.Filter,
            Tag = query.Tag,
            Page = page,
            PageSize = pageSize,
            Folder = window.ConfigFolder,
            UserId = LocalPlayer.UserId,
        }
        task.spawn(function()
            local ok, list, extra = isolatedCall(function()
                return opts.OnFetch(fetchQuery)
            end)
            if myToken ~= token then
                return
            end
            busy(false)
            clearSkeletons()
            if not ok or type(list) ~= "table" then
                if more then
                    page -= 1
                end
                if not ok then
                    warn("[Aster UI] cloud OnFetch error: " .. tostring(list))
                end
                hasMore = more and hasMore or false
                moreButton.Visible = false
                setState("error", not ok and "Could not load configs" or tostring(extra or "Could not load configs"))
                return
            end
            hasMore = extra == true
            local seen = {}
            for _, record in ipairs(records) do
                seen[record] = true
            end
            for _, raw in ipairs(list) do
                local record = normalizeRecord(raw)
                if record and not seen[record] then
                    seen[record] = true
                    table.insert(records, record)
                    buildCard(record, #records)
                end
            end
            moreButton.Visible = hasMore
            setState(#records == 0 and "empty" or nil, emptyText())
        end)
    end

    -- Near the bottom, the next page loads by itself.
    results:GetPropertyChangedSignal("CanvasPosition"):Connect(function()
        if not hasMore or loading then
            return
        end
        local scale = window.Scale.Scale
        local remaining = results.AbsoluteCanvasSize.Y / scale - results.AbsoluteWindowSize.Y / scale - results.CanvasPosition.Y
        if remaining < 160 then
            fetch(true)
        end
    end)

    -- Filters and sorting

    local filterChips, tagChips = {}, {}
    local function renderFilters(instant)
        for name, object in pairs(filterChips) do
            object.Set(query.Filter == name, instant)
        end
        for name, object in pairs(tagChips) do
            object.Set(query.Tag == name, instant)
        end
        sortLabel.Text = SORT_NAMES[query.Sort]
    end
    for index, name in ipairs(FILTERS) do
        if not (name == "Mine" and opts.MineFilter == false) then
            filterChips[name] = chip(filterStrip, name, index, function()
                if query.Filter ~= name then
                    query.Filter = name
                    renderFilters()
                    fetch(false)
                end
            end)
        end
    end
    if #tagList > 0 then
        create("Frame", {
            Size = UDim2.fromOffset(1, 16),
            BackgroundColor3 = Theme.Stroke,
            BorderSizePixel = 0,
            LayoutOrder = 10,
            Parent = filterStrip,
        })
    end
    for index, tag in ipairs(tagList) do
        tag = tostring(tag)
        tagChips[tag] = chip(filterStrip, tag, 10 + index, function()
            query.Tag = query.Tag ~= tag and tag or nil
            renderFilters()
            fetch(false)
        end)
    end
    sortButton.MouseButton1Click:Connect(function()
        local index = table.find(SORTS, query.Sort) or 1
        query.Sort = SORTS[index % #SORTS + 1]
        persist("CloudSort", query.Sort)
        renderFilters()
        fetch(false)
    end)

    function resetFilters()
        searchToken += 1
        searchBox.Text = ""
        query.Search, query.Tag, query.Filter = "", nil, "All"
        renderFilters()
        fetch(false)
    end
    resetButton.MouseButton1Click:Connect(resetFilters)

    -- Typing searches after a short pause; Enter searches now.
    searchBox:GetPropertyChangedSignal("Text"):Connect(function()
        searchClear.Visible = searchBox.Text ~= ""
        showRecent(searchBox:IsFocused())
        searchToken += 1
        local mine = searchToken
        local text = trim(searchBox.Text)
        if text ~= query.Search then
            renderSummary(true)
        end
        task.delay(0.35, function()
            text = trim(searchBox.Text)
            if mine == searchToken and text ~= query.Search then
                query.Search = text
                fetch(false)
            end
        end)
    end)
    searchBox.Focused:Connect(function()
        tween(searchStroke, { Color = Theme.Accent }, 0.15)
        tween(searchImage, { ImageColor3 = Theme.Accent }, 0.15)
        showRecent(true)
    end)
    searchBox.FocusLost:Connect(function(enterPressed)
        tween(searchStroke, { Color = Theme.Stroke }, 0.2)
        tween(searchImage, { ImageColor3 = Theme.Muted }, 0.2)
        rememberSearch(searchBox.Text)
        -- Late enough for a press on a recent search to land first.
        task.delay(0.15, function()
            if not searchBox:IsFocused() then
                showRecent(false)
            end
        end)
        if enterPressed then
            searchToken += 1
            local text = trim(searchBox.Text)
            if text ~= query.Search then
                query.Search = text
                fetch(false)
            end
        end
    end)
    searchClear.MouseButton1Click:Connect(function()
        searchToken += 1
        searchBox.Text = ""
        if query.Search ~= "" then
            query.Search = ""
            fetch(false)
        end
    end)
    -- "/" jumps to the search box while the list is showing.
    window:_listen("Began", function(input, processed)
        if processed or input.KeyCode ~= Enum.KeyCode.Slash then
            return
        end
        if window.Open and window.CurrentTab == tab and currentView == views.Browse and not UserInputService:GetFocusedTextBox() then
            task.defer(function()
                searchBox:CaptureFocus()
                searchBox.Text = searchBox.Text:gsub("/$", "")
            end)
        end
    end, cloud)
    refreshButton.MouseButton1Click:Connect(function()
        cloud:Refresh()
    end)

    -- Actions on a record

    local function withCode(record, callback, onFail)
        if record.Code then
            callback(record.Code)
            return
        end
        local function fail(reason)
            if onFail then
                onFail(reason)
            else
                notify(false, "Could not load config", reason)
            end
        end
        if type(opts.OnFetchCode) ~= "function" then
            fail("This config has no code")
            return
        end
        task.spawn(function()
            local ok, code, reason = isolatedCall(function()
                return opts.OnFetchCode(publicRecord(record))
            end)
            if ok and type(code) == "string" and code ~= "" then
                record.Code = code
                record.Count = record.Count or countFlags(code)
                callback(code)
            else
                fail(tostring(reason or (not ok and "the request failed") or "no code came back"))
            end
        end)
    end

    function installRecord(record)
        if record._busy then
            return
        end
        record._busy = true
        withCode(record, function(code)
            record._busy = nil
            local data, info = window:DecodeConfig(code)
            if not data then
                notify(false, "Install failed", "The config code is invalid")
                return
            end
            local count = 0
            for _ in pairs(data) do
                count += 1
            end
            local mark = installed[record.Id]
            local saveAs = nil
            if fileApiAvailable() then
                -- An update overwrites the config it installed last time.
                saveAs = type(mark) == "table" and type(mark.Name) == "string" and window:ConfigExists(mark.Name) and mark.Name
                    or uniqueName(record.Name)
            end
            local other = info.Folder and info.Folder ~= window.ConfigFolder
            local function apply(save)
                local name = save and saveAs or nil
                local ok, err = window:ImportConfig(code, name, true)
                if not ok then
                    notify(false, "Install failed", tostring(err))
                    return
                end
                installed[record.Id] = { Updated = record.Updated or os.time(), Name = name, At = os.time(), Record = summary(record) }
                persist("CloudInstalled", installed)
                record.Installs += 1
                refreshRecord(record)
                notify(true, "Config installed", name and ("Saved as " .. name) or "Applied to your current settings")
                if opts.OnInstall then
                    task.spawn(safeCall, opts.OnInstall, publicRecord(record), name)
                end
            end
            local content = ("%s by %s changes %d setting%s."):format(record.Name, record.Author, count, count == 1 and "" or "s")
            if other then
                content ..= (" It was made for %s, so only matching settings apply."):format(info.Folder)
            end
            if saveAs then
                content ..= (" Install also saves it as %s; Apply only doesn't."):format(saveAs)
            end
            local buttons = { { Title = "Cancel" } }
            table.insert(buttons, { Title = "Apply only", Variant = not saveAs and "Primary" or nil, Callback = function()
                apply(false)
            end })
            if saveAs then
                table.insert(buttons, { Title = "Install", Variant = "Primary", Callback = function()
                    apply(true)
                end })
            end
            window:Dialog({
                Title = installState(record) == "Update" and "Update config" or "Install config",
                Content = content,
                Icon = other and "triangle-alert" or "download",
                Buttons = buttons,
            })
        end, function(reason)
            record._busy = nil
            notify(false, "Could not load config", reason)
        end)
    end

    local function toggleLike(record)
        if type(opts.OnLike) ~= "function" or record._liking then
            return
        end
        local liked = not record.Liked
        record.Liked = liked
        record.Likes = math.max(record.Likes + (liked and 1 or -1), 0)
        record._liking = true
        refreshRecord(record)
        task.spawn(function()
            local ok, result, reason = isolatedCall(function()
                return opts.OnLike(publicRecord(record), liked)
            end)
            record._liking = nil
            if not ok or result == false then
                record.Liked = not liked
                record.Likes = math.max(record.Likes + (liked and -1 or 1), 0)
                refreshRecord(record)
                notify(false, "Like not saved", tostring(reason or "Try again in a moment"))
            end
        end)
    end

    local function toggleFavorite(record)
        local on = favorites[record.Id] == nil
        favorites[record.Id] = on and summary(record) or nil
        persist("CloudFavorites", favorites)
        refreshRecord(record)
        window:Notify({
            Title = on and "Added to favorites" or "Removed from favorites",
            Content = record.Name,
            Icon = "star",
            Duration = 2,
        })
    end

    local function removeRecord(record)
        local index = table.find(records, record)
        if index then
            table.remove(records, index)
        end
        byId[record.Id] = nil
        local card = cards[record.Id]
        if card then
            card.Frame:Destroy()
            cards[record.Id] = nil
        end
        if #records == 0 and not loading then
            setState("empty", emptyText())
        end
    end

    local function deleteRecord(record)
        window:Confirm({
            Title = "Delete config",
            Content = ("Remove %s from the cloud? People who installed it keep their copy."):format(record.Name),
            Icon = "trash-2",
            ConfirmText = "Delete",
            Callback = function()
                task.spawn(function()
                    local ok, result, reason = isolatedCall(function()
                        return opts.OnDelete(publicRecord(record))
                    end)
                    if not ok or result == false then
                        notify(false, "Delete failed", tostring(reason or "Try again in a moment"))
                        return
                    end
                    favorites[record.Id] = nil
                    persist("CloudFavorites", favorites)
                    removeRecord(record)
                    showView(views.Browse)
                    notify(true, "Config deleted", record.Name)
                end)
            end,
        })
    end

    local function reportRecord(record)
        local reasons = type(opts.ReportReasons) == "table" and opts.ReportReasons or { "Broken", "Spam", "Inappropriate" }
        local buttons = { { Title = "Cancel" } }
        for _, reason in ipairs(reasons) do
            table.insert(buttons, { Title = tostring(reason), Callback = function()
                task.spawn(function()
                    local ok, result = isolatedCall(function()
                        return opts.OnReport(publicRecord(record), tostring(reason))
                    end)
                    local sent = ok and result ~= false
                    notify(sent, sent and "Report sent" or "Report failed", sent and "Thanks for letting us know" or "Try again in a moment")
                end)
            end })
        end
        window:Dialog({
            Title = "Report config",
            Content = ("What's wrong with %s?"):format(record.Name),
            Icon = "flag",
            Buttons = buttons,
        })
    end

    -- Detail view

    local detailList = scroller(views.Detail)
    padding(detailList, 1, 8, 1, 16)
    vlist(detailList, 10)

    local function valueText(entry)
        local value = type(entry) == "table" and entry.Value or nil
        if value == nil then
            return "None"
        elseif type(value) == "boolean" then
            return value and "On" or "Off"
        elseif type(value) == "number" then
            return (("%.2f"):format(value):gsub("%.?0+$", ""))
        elseif type(value) == "table" then
            if type(value.Hex) == "string" then
                return "#" .. string.upper(value.Hex)
            elseif type(value.Colors) == "table" then
                local text = type(value.Name) == "string" and value.Name or "Custom"
                if type(value.Background) == "string" and value.Background ~= "" then
                    text ..= ", image"
                end
                return text
            end
            local parts = {}
            for index, item in ipairs(value) do
                parts[index] = tostring(item)
            end
            return #parts > 0 and table.concat(parts, ", ") or "None"
        end
        return tostring(value)
    end

    local function encoded(entry)
        local ok, text = pcall(HttpService.JSONEncode, HttpService, type(entry) == "table" and entry.Value or nil)
        return ok and text or tostring(entry)
    end

    local function renderDetail()
        local record = detailRecord
        if not record or not detail.Meta then
            return
        end
        detail.Title.Text = record.Name
        local meta = { "by " .. record.Author }
        local when = ago(record.Updated)
        if when then
            table.insert(meta, "updated " .. when)
        end
        if otherScript(record) then
            table.insert(meta, "made for " .. record.Folder)
        end
        detail.Meta.Text = table.concat(meta, "  ·  ")
        detail.Stats.Text = ("%s like%s  ·  %s install%s"):format(
            compact(record.Likes), record.Likes == 1 and "" or "s",
            compact(record.Installs), record.Installs == 1 and "" or "s")
        if detail.BuiltFor ~= record or detail.BuiltMine ~= record.Mine then
            detail.BuiltFor, detail.BuiltMine = record, record.Mine
            local row = detail.Actions
            clear(row)
            local order = 0
            local function action(text, style, callback)
                order += 1
                local button, text_ = softButton(row, text, {
                    Size = UDim2.new(0, 0, 0, 30),
                    AutomaticSize = Enum.AutomaticSize.X,
                    LayoutOrder = order,
                }, callback)
                text_.TextSize = 13
                if style == "Primary" then
                    primary(button, text_)
                elseif style == "Danger" then
                    tween(text_, { TextColor3 = Theme.Error }, 0)
                end
                return text_
            end
            detail.InstallLabel = action("Install", "Primary", function()
                installRecord(record)
            end)
            if type(opts.OnLike) == "function" then
                detail.LikeLabel = action("Like", nil, function()
                    toggleLike(record)
                end)
            end
            detail.FavoriteLabel = action("Favorite", nil, function()
                toggleFavorite(record)
            end)
            action("Copy code", nil, function()
                withCode(record, function(code)
                    window:CopyToClipboard(code, "Config code")
                end)
            end)
            if record.Mine then
                if type(opts.OnUpdate) == "function" then
                    action("Edit", nil, function()
                        cloud:OpenPublish(record)
                    end)
                end
                if type(opts.OnDelete) == "function" then
                    action("Delete", "Danger", function()
                        deleteRecord(record)
                    end)
                end
            elseif type(opts.OnReport) == "function" then
                action("Report", "Danger", function()
                    reportRecord(record)
                end)
            end
        end
        local state = installState(record)
        detail.InstallLabel.Text = state == "Update" and "Update" or (state == "Installed" and "Reinstall" or "Install")
        if detail.LikeLabel then
            detail.LikeLabel.Text = (record.Liked and "Liked" or "Like") .. "  ·  " .. compact(record.Likes)
        end
        detail.FavoriteLabel.Text = favorites[record.Id] and "Favorited" or "Favorite"
    end

    local function fillPreview(record, myToken)
        local function mismatch(text)
            if detailToken == myToken then
                detail.Summary.Text = text
            end
        end
        withCode(record, function(code)
            if detailToken ~= myToken then
                return
            end
            local data = window:DecodeConfig(code)
            if not data then
                mismatch("The config code is invalid")
                return
            end
            local current = collectFlags(window)
            local rows = {}
            local changed = 0
            for flag, entry in pairs(data) do
                local element = Library.Flags[flag]
                local known = element ~= nil
                local differs = known and encoded(entry) ~= encoded(current[flag])
                if differs then
                    changed += 1
                end
                table.insert(rows, {
                    Name = element and element._searchName ~= "" and element._searchName or flag,
                    Value = valueText(entry),
                    Known = known,
                    Changed = differs,
                    Rank = differs and 0 or (known and 1 or 2),
                })
            end
            table.sort(rows, function(a, b)
                if a.Rank ~= b.Rank then
                    return a.Rank < b.Rank
                end
                return string.lower(a.Name) < string.lower(b.Name)
            end)
            record.Count = #rows
            detail.Summary.Text = changed == 0 and ("%d settings, all the same as yours"):format(#rows)
                or ("%d settings, %d different from yours"):format(#rows, changed)
            clear(detail.Rows)
            for index, item in ipairs(rows) do
                if index > 150 then
                    wrapped(detail.Rows, ("and %d more"):format(#rows - 150), 12, Theme.Muted, index)
                    break
                end
                local rowFrame = create("Frame", {
                    Size = UDim2.new(1, 0, 0, 30),
                    BackgroundColor3 = Theme.Surface2,
                    BackgroundTransparency = item.Changed and 0 or 0.5,
                    BorderSizePixel = 0,
                    LayoutOrder = index,
                    Parent = detail.Rows,
                })
                corner(rowFrame, UDim.new(0, 7))
                if item.Changed then
                    local dot = create("Frame", {
                        AnchorPoint = Vector2.new(0, 0.5),
                        Position = UDim2.new(0, 10, 0.5, 0),
                        Size = UDim2.fromOffset(6, 6),
                        BackgroundColor3 = Theme.Accent,
                        BorderSizePixel = 0,
                        Parent = rowFrame,
                    })
                    corner(dot, UDim.new(1, 0))
                end
                label({
                    Position = UDim2.fromOffset(24, 0),
                    Size = UDim2.new(0.55, -24, 1, 0),
                    Text = item.Known and item.Name or (item.Name .. "  (not in this script)"),
                    TextSize = 12,
                    TextColor3 = item.Known and Theme.Text or Theme.Muted,
                    Parent = rowFrame,
                })
                label({
                    AnchorPoint = Vector2.new(1, 0),
                    Position = UDim2.new(1, -10, 0, 0),
                    Size = UDim2.new(0.45, -10, 1, 0),
                    Text = item.Value,
                    TextSize = 12,
                    FontFace = Fonts.Regular,
                    TextColor3 = item.Changed and Theme.Accent or Theme.Muted,
                    TextXAlignment = Enum.TextXAlignment.Right,
                    Parent = rowFrame,
                })
            end
            if cards[record.Id] then
                renderCard(cards[record.Id])
            end
        end, mismatch)
    end

    function openDetail(record)
        detailRecord = record
        detailToken += 1
        local myToken = detailToken
        clear(detailList)
        detail = {}
        detailList.CanvasPosition = Vector2.zero
        softButton(detailList, "Back", {
            Size = UDim2.new(0, 0, 0, 28),
            AutomaticSize = Enum.AutomaticSize.X,
            LayoutOrder = 1,
        }, function()
            showView(views.Browse)
        end)
        detail.Title = wrapped(detailList, record.Name, 20, Theme.Text, 2, Fonts.Bold)
        detail.Meta = wrapped(detailList, "", 12, Theme.Muted, 3)
        if record.Description ~= "" then
            wrapped(detailList, record.Description, 13, Theme.Text, 4)
        end
        if #record.Tags > 0 then
            local tagsRow = create("Frame", {
                Size = UDim2.new(1, 0, 0, 0),
                AutomaticSize = Enum.AutomaticSize.Y,
                BackgroundTransparency = 1,
                LayoutOrder = 5,
                Parent = detailList,
            })
            hlist(tagsRow, 4, true)
            for index, tag in ipairs(record.Tags) do
                tagPill(tagsRow, tag, index)
            end
        end
        detail.Stats = wrapped(detailList, "", 12, Theme.Muted, 6)
        detail.Actions = create("Frame", {
            Size = UDim2.new(1, 0, 0, 0),
            AutomaticSize = Enum.AutomaticSize.Y,
            BackgroundTransparency = 1,
            LayoutOrder = 7,
            Parent = detailList,
        })
        hlist(detail.Actions, 6, true)
        create("Frame", {
            Size = UDim2.new(1, 0, 0, 1),
            BackgroundColor3 = Theme.Stroke,
            BorderSizePixel = 0,
            LayoutOrder = 8,
            Parent = detailList,
        })
        wrapped(detailList, "Settings", 14, Theme.Text, 9, Fonts.Bold)
        detail.Summary = wrapped(detailList, "Loading settings...", 12, Theme.Muted, 10)
        detail.Rows = create("Frame", {
            Size = UDim2.new(1, 0, 0, 0),
            AutomaticSize = Enum.AutomaticSize.Y,
            BackgroundTransparency = 1,
            LayoutOrder = 11,
            Parent = detailList,
        })
        vlist(detail.Rows, 4)
        renderDetail()
        showView(views.Detail)
        fillPreview(record, myToken)
    end

    function refreshRecord(record)
        local card = cards[record.Id]
        if card then
            renderCard(card)
        end
        if detailRecord == record and currentView == views.Detail then
            renderDetail()
        end
    end

    -- Publish view: also the edit form for the player's own configs.

    local form = { Mode = "Publish", Record = nil, Source = false, Tags = {}, Busy = false }
    local publishList = scroller(views.Publish)
    padding(publishList, 1, 8, 1, 16)
    vlist(publishList, 8)
    softButton(publishList, "Back", {
        Size = UDim2.new(0, 0, 0, 28),
        AutomaticSize = Enum.AutomaticSize.X,
        LayoutOrder = 1,
    }, function()
        showView(form.Mode == "Edit" and form.Record and views.Detail or views.Browse)
    end)
    local formTitle = wrapped(publishList, "Publish a config", 20, Theme.Text, 2, Fonts.Bold)
    wrapped(publishList, "Name", 12, Theme.Muted, 3)
    local nameBox = field(publishList, 4, "What is it for?", ROW, NAME_LIMIT)
    wrapped(publishList, "Description", 12, Theme.Muted, 5)
    local descBox = field(publishList, 6, "What does it do, and how should people use it?", 90, DESC_LIMIT)
    local tagsTitle = wrapped(publishList, "Tags", 12, Theme.Muted, 7)
    local tagsRow = create("Frame", {
        Size = UDim2.new(1, 0, 0, 0),
        AutomaticSize = Enum.AutomaticSize.Y,
        BackgroundTransparency = 1,
        LayoutOrder = 8,
        Parent = publishList,
    })
    hlist(tagsRow, 6, true)
    tagsTitle.Visible = #tagList > 0 and maxTags > 0
    tagsRow.Visible = tagsTitle.Visible
    wrapped(publishList, "Settings to share", 12, Theme.Muted, 9)
    local sourceRow = create("Frame", {
        Size = UDim2.new(1, 0, 0, 0),
        AutomaticSize = Enum.AutomaticSize.Y,
        BackgroundTransparency = 1,
        LayoutOrder = 10,
        Parent = publishList,
    })
    hlist(sourceRow, 6, true)
    local sourceSummary = wrapped(publishList, "", 12, Theme.Muted, 11)
    local identityNote = wrapped(publishList, "", 12, Theme.Muted, 12)
    local formError = wrapped(publishList, "", 12, Theme.Error, 13)
    formError.Visible = false
    local submitRow = create("Frame", {
        Size = UDim2.new(1, 0, 0, 32),
        BackgroundTransparency = 1,
        LayoutOrder = 14,
        Parent = publishList,
    })
    hlist(submitRow, 6)
    local submitButton, submitText = softButton(submitRow, "Publish", {
        Size = UDim2.new(0, 0, 1, 0),
        AutomaticSize = Enum.AutomaticSize.X,
        LayoutOrder = 1,
    }, function()
        cloud:_submit()
    end)
    primary(submitButton, submitText)
    softButton(submitRow, "Cancel", {
        Size = UDim2.new(0, 0, 1, 0),
        AutomaticSize = Enum.AutomaticSize.X,
        LayoutOrder = 2,
    }, function()
        showView(form.Mode == "Edit" and form.Record and views.Detail or views.Browse)
    end)

    local formTagChips = {}
    local function renderFormTags()
        for tag, object in pairs(formTagChips) do
            object.Set(table.find(form.Tags, tag) ~= nil)
        end
        tagsTitle.Text = maxTags > 0 and ("Tags  (%d/%d)"):format(#form.Tags, maxTags) or "Tags"
    end
    for index, tag in ipairs(tagList) do
        tag = tostring(tag)
        formTagChips[tag] = chip(tagsRow, tag, index, function()
            local at = table.find(form.Tags, tag)
            if at then
                table.remove(form.Tags, at)
            elseif #form.Tags < maxTags then
                table.insert(form.Tags, tag)
            else
                notify(false, "Too many tags", ("Pick up to %d"):format(maxTags))
            end
            renderFormTags()
        end)
    end

    -- The code and setting count for the picked source, or nil and why not.
    local function sourceCode(name)
        if form.Source == "Keep" then
            return nil, form.Record and form.Record.Count
        elseif form.Source then
            local code, err = window:ExportConfig(form.Source)
            if not code then
                return nil, nil, err
            end
            return code, countFlags(code)
        end
        local ok, code = pcall(encodeConfig, window, name ~= "" and name or "Cloud config", collectFlags(window))
        if not ok then
            return nil, nil, "could not encode your settings"
        end
        return code, countFlags(code)
    end

    local sourceChips = {}
    local function renderSource()
        for key, object in pairs(sourceChips) do
            object.Set(key == (form.Source or "*current"))
        end
        local _, count, err = sourceCode(trim(nameBox.Text))
        if err then
            sourceSummary.Text = tostring(err)
        elseif form.Source == "Keep" then
            sourceSummary.Text = "Keeps the settings already published" .. (count and (" (" .. count .. ")") or "")
        else
            sourceSummary.Text = ("%d setting%s from %s"):format(count or 0, count == 1 and "" or "s", form.Source or "your current settings")
        end
    end

    local function buildSources()
        clear(sourceRow)
        sourceChips = {}
        local order = 0
        local function add(key, text)
            order += 1
            sourceChips[key] = chip(sourceRow, text, order, function()
                form.Source = key ~= "*current" and key or false
                renderSource()
            end)
        end
        if form.Mode == "Edit" then
            add("Keep", "Keep published settings")
        end
        add("*current", "Current settings")
        for _, name in ipairs(window:ListConfigs()) do
            add(name, name)
        end
        renderSource()
    end

    local function showError(text)
        formError.Text = tostring(text)
        formError.Visible = true
    end

    function cloud:OpenPublish(record)
        local editing = type(record) == "table" and record.Id and byId[record.Id] or nil
        if editing then
            form.Mode, form.Record = "Edit", editing
            form.Source = "Keep"
            form.Tags = table.clone(editing.Tags)
            nameBox.Text = editing.Name
            descBox.Text = editing.Description
        elseif form.Mode == "Edit" then
            -- Leaving an edit starts a fresh draft; a publish draft is kept.
            form.Mode, form.Record, form.Source, form.Tags = "Publish", nil, false, {}
            nameBox.Text = ""
            descBox.Text = ""
        end
        formTitle.Text = editing and "Edit config" or "Publish a config"
        submitText.Text = editing and "Save changes" or "Publish"
        formError.Visible = false
        local streamer = streamerOn()
        identityNote.Text = streamer and ("Your name is hidden, so you publish as " .. anonName)
            or ("You publish as " .. LocalPlayer.DisplayName)
        renderFormTags()
        buildSources()
        publishList.CanvasPosition = Vector2.zero
        showView(views.Publish)
    end

    nameBox:GetPropertyChangedSignal("Text"):Connect(function()
        formError.Visible = false
    end)

    function cloud:_submit()
        if form.Busy then
            return
        end
        local name = trim(nameBox.Text)
        if name == "" then
            showError("Give your config a name")
            return
        end
        local code, count, err = sourceCode(name)
        if err then
            showError(err)
            return
        end
        if form.Source ~= "Keep" and (count or 0) == 0 then
            showError("There are no settings to share")
            return
        end
        local editing = form.Mode == "Edit" and form.Record or nil
        local callback = editing and opts.OnUpdate or opts.OnPublish
        if type(callback) ~= "function" then
            showError(editing and "Editing isn't available" or "Publishing isn't available")
            return
        end
        local streamer = streamerOn()
        local payload = {
            Name = name,
            Description = trim(descBox.Text),
            Tags = table.clone(form.Tags),
            Code = code,
            Count = count,
            Folder = window.ConfigFolder,
            Author = streamer and anonName or LocalPlayer.DisplayName,
            AuthorId = not streamer and LocalPlayer.UserId or nil,
            OwnerId = LocalPlayer.UserId,
            Streamer = streamer,
        }
        form.Busy = true
        submitText.Text = editing and "Saving..." or "Publishing..."
        formError.Visible = false
        task.spawn(function()
            local ok, result, reason = isolatedCall(function()
                if editing then
                    return callback(publicRecord(editing), payload)
                end
                return callback(payload)
            end)
            form.Busy = false
            submitText.Text = editing and "Save changes" or "Publish"
            if not ok or result == false then
                if not ok then
                    warn("[Aster UI] cloud publish error: " .. tostring(result))
                end
                showError(ok and reason and tostring(reason) or "Something went wrong, try again")
                return
            end
            local merged = table.clone(payload)
            merged.Code = code or (editing and editing.Code)
            merged.Updated = os.time()
            if type(result) == "table" then
                for key, value in pairs(result) do
                    merged[key] = value
                end
            end
            if editing then
                merged.Id = editing.Id
                normalizeRecord(merged)
                if favorites[editing.Id] then
                    favorites[editing.Id] = summary(editing)
                    persist("CloudFavorites", favorites)
                end
                refreshRecord(editing)
                notify(true, "Config updated", name)
                openDetail(editing)
            else
                nameBox.Text = ""
                descBox.Text = ""
                form.Tags = {}
                form.Source = false
                if type(result) == "table" then
                    merged.Mine = true
                    local record = normalizeRecord(merged)
                    if query.Filter == "All" or query.Filter == "Mine" then
                        table.insert(records, 1, record)
                        renderList()
                        setState(nil)
                    end
                    notify(true, "Config published", name)
                    openDetail(record)
                else
                    notify(true, "Config published", name)
                    showView(views.Browse)
                    fetch(false)
                end
            end
        end)
    end

    -- Handle

    function cloud:Refresh()
        fetch(false)
    end

    function cloud:LoadMore()
        if not loading then
            fetch(true)
        end
    end

    -- For backends that push results instead of answering OnFetch.
    function cloud:SetConfigs(list, more)
        token += 1
        busy(false)
        clearSkeletons()
        records = {}
        for _, raw in ipairs(type(list) == "table" and list or {}) do
            local record = normalizeRecord(raw)
            if record then
                table.insert(records, record)
            end
        end
        hasMore = more == true
        renderList()
        moreButton.Visible = hasMore
        setState(#records == 0 and "empty" or nil, emptyText())
    end

    function cloud:AddConfigs(list, more)
        token += 1
        busy(false)
        clearSkeletons()
        for _, raw in ipairs(type(list) == "table" and list or {}) do
            local record = normalizeRecord(raw)
            if record and not table.find(records, record) then
                table.insert(records, record)
                buildCard(record, #records)
            end
        end
        hasMore = more == true
        moreButton.Visible = hasMore
        setState(#records == 0 and "empty" or nil, emptyText())
    end

    function cloud:UpdateConfig(id, changes)
        local record = byId[tostring(id)]
        if record and type(changes) == "table" then
            local merged = table.clone(changes)
            merged.Id = record.Id
            normalizeRecord(merged)
            refreshRecord(record)
        end
    end

    function cloud:RemoveConfig(id)
        local record = byId[tostring(id)]
        if record then
            removeRecord(record)
            if detailRecord == record and currentView == views.Detail then
                showView(views.Browse)
            end
        end
    end

    function cloud:SetLoading(on)
        token += 1
        busy(on == true)
        clearSkeletons()
        if loading then
            addSkeletons(4)
            setState(nil)
        end
    end

    function cloud:SetError(text)
        token += 1
        busy(false)
        clearSkeletons()
        setState(text and "error" or nil, tostring(text or ""))
    end

    function cloud:Open(id)
        local record = byId[tostring(id)]
        if record then
            window:SelectTab(tab)
            openDetail(record)
        end
    end

    function cloud:Back()
        showView(views.Browse)
    end

    function cloud:GetQuery()
        return table.clone(query)
    end

    function cloud:GetFavorites()
        local list = {}
        for id, kept in pairs(favorites) do
            local copy = table.clone(kept)
            copy.Id = id
            table.insert(list, copy)
        end
        return list
    end

    function cloud:GetInstalled()
        local list = {}
        for id, mark in pairs(installed) do
            table.insert(list, { Id = id, Name = mark.Name, Updated = mark.Updated, Record = mark.Record })
        end
        return list
    end

    renderFilters(true)
    showView(views.Browse)
    -- The first fetch waits until the tab is opened, so a hidden tab costs nothing.
    local fetched = false
    local function firstFetch()
        if not fetched and tab._page.Visible then
            fetched = true
            fetch(false)
        end
    end
    tab._page:GetPropertyChangedSignal("Visible"):Connect(firstFetch)
    if type(opts.OnFetch) ~= "function" then
        fetched = true
        setState("empty", emptyText())
    else
        task.defer(firstFetch)
    end
    return cloud
end

Window.CreateCloudConfigs = Window.CloudConfigs
Window.CloudConfig = Window.CloudConfigs
Window.CreateCloudConfig = Window.CloudConfigs

function Tab:SetBadge() end

function Tab:GetBadge()
    return nil
end

function Window:Dialog(opts)
    opts = normalize(opts, { Text = "Content", Message = "Content" })
    if self._dialog then
        self._dialog.Close()
    end
    local WIDTH = 300
    local PAD = 18

    local overlay = create("TextButton", {
        Size = UDim2.fromScale(1, 1),
        BackgroundColor3 = Color3.new(0, 0, 0),
        BackgroundTransparency = 1,
        Text = "",
        AutoButtonColor = false,
        ZIndex = 40,
        Parent = self.Body,
    })
    local card = create("Frame", {
        AnchorPoint = Vector2.new(0.5, 0.5),
        Position = UDim2.new(0.5, 0, 0.5, 10),
        Size = UDim2.fromOffset(WIDTH, 120),
        BackgroundColor3 = Theme.Background,
        BackgroundTransparency = 1,
        BorderSizePixel = 0,
        ZIndex = 41,
        Parent = overlay,
    })
    corner(card, UDim.new(0, 10))
    local cardStroke = stroke(card, Theme.Stroke, 1)
    local cardScale = create("UIScale", { Scale = 0.94, Parent = card })
    local fading = {}

    local titleOffset = 0
    if opts.Icon then
        local holder, image = glowIcon(card, opts.Icon, Theme.Accent, UDim2.new(0, PAD, 0, PAD + 9))
        image.ImageTransparency = 1
        holder.ZIndex = 42
        image.ZIndex = 42
        table.insert(fading, { image, "ImageTransparency", 0 })
        titleOffset = 24
    end
    local title = label({
        Position = UDim2.fromOffset(PAD + titleOffset, PAD),
        Size = UDim2.new(1, -(PAD * 2 + titleOffset), 0, 18),
        Text = opts.Title or "Are you sure?",
        TextSize = 15,
        TextTransparency = 1,
        ZIndex = 42,
        Parent = card,
    })
    table.insert(fading, { title, "TextTransparency", 0 })

    local contentHeight = 0
    if opts.Content then
        local content = label({
            Position = UDim2.fromOffset(PAD, PAD + 24),
            Size = UDim2.new(1, -PAD * 2, 0, 0),
            AutomaticSize = Enum.AutomaticSize.Y,
            Text = opts.Content,
            TextSize = 13,
            FontFace = Fonts.Regular,
            TextColor3 = Theme.Muted,
            TextWrapped = true,
            TextTransparency = 1,
            TextTruncate = Enum.TextTruncate.None,
            TextYAlignment = Enum.TextYAlignment.Top,
            ZIndex = 42,
            Parent = card,
        })
        table.insert(fading, { content, "TextTransparency", 0 })
        contentHeight = math.max(content.TextBounds.Y, 16) + 6
        content:GetPropertyChangedSignal("TextBounds"):Connect(function()
            local newHeight = math.max(content.TextBounds.Y, 16) + 6
            if newHeight ~= contentHeight then
                contentHeight = newHeight
                card.Size = UDim2.fromOffset(WIDTH, PAD + 24 + contentHeight + 12 + 34 + PAD)
                local rowFrame = card:FindFirstChild("ButtonRow")
                if rowFrame then
                    rowFrame.Position = UDim2.fromOffset(PAD, PAD + 24 + contentHeight + 12)
                end
            end
        end)
    end

    local row = create("Frame", {
        Name = "ButtonRow",
        Position = UDim2.fromOffset(PAD, PAD + 24 + contentHeight + 12),
        Size = UDim2.new(1, -PAD * 2, 0, 34),
        BackgroundTransparency = 1,
        ZIndex = 42,
        Parent = card,
    })
    create("UIListLayout", {
        FillDirection = Enum.FillDirection.Horizontal,
        HorizontalAlignment = Enum.HorizontalAlignment.Right,
        SortOrder = Enum.SortOrder.LayoutOrder,
        Padding = UDim.new(0, 8),
        Parent = row,
    })
    card.Size = UDim2.fromOffset(WIDTH, PAD + 24 + contentHeight + 12 + 34 + PAD)

    local dialog = {}
    local closed = false
    function dialog.Close()
        if closed then
            return
        end
        closed = true
        if self._dialog == dialog then
            self._dialog = nil
        end
        tween(overlay, { BackgroundTransparency = 1 }, 0.18)
        tween(card, { BackgroundTransparency = 1, Position = UDim2.new(0.5, 0, 0.5, 8) }, 0.18, Enum.EasingStyle.Quint)
        tween(cardScale, { Scale = 0.96 }, 0.18, Enum.EasingStyle.Quint)
        tween(cardStroke, { Transparency = 1 }, 0.12)
        for _, entry in ipairs(fading) do
            tween(entry[1], { [entry[2]] = 1 }, 0.12)
        end
        task.delay(0.2, function()
            overlay:Destroy()
        end)
    end

    for index, spec in ipairs(opts.Buttons or {}) do
        local primary = spec.Variant == "Primary"
        local buttonFrame = create("TextButton", {
            Size = UDim2.fromOffset(0, 34),
            AutomaticSize = Enum.AutomaticSize.X,
            BackgroundColor3 = primary and Theme.Accent or Theme.Surface2,
            BackgroundTransparency = 1,
            BorderSizePixel = 0,
            Text = "",
            AutoButtonColor = false,
            ClipsDescendants = true,
            LayoutOrder = index,
            ZIndex = 43,
            Parent = row,
        })
        corner(buttonFrame, UDim.new(0, 7))
        local buttonStroke = stroke(buttonFrame, primary and Theme.Accent or Theme.Stroke, 1)
        padding(buttonFrame, 14, 14)
        local text = label({
            Size = UDim2.new(0, 0, 1, 0),
            AutomaticSize = Enum.AutomaticSize.X,
            Text = spec.Title or spec.Name or "OK",
            TextSize = 13,
            TextColor3 = primary and Theme.AccentDark or Theme.Text,
            TextXAlignment = Enum.TextXAlignment.Center,
            TextTransparency = 1,
            ZIndex = 44,
            Parent = buttonFrame,
        })
        local restBg = primary and 0.12 or 0
        local restStroke = primary and 0.4 or 0
        table.insert(fading, { buttonFrame, "BackgroundTransparency", restBg })
        table.insert(fading, { buttonStroke, "Transparency", restStroke })
        table.insert(fading, { text, "TextTransparency", 0 })
        buttonFrame.MouseEnter:Connect(function()
            if closed then
                return
            end
            if primary then
                tween(buttonFrame, { BackgroundTransparency = 0 }, 0.12)
                tween(buttonStroke, { Transparency = 0 }, 0.12)
            else
                tween(buttonStroke, { Color = Theme.StrokeHover }, 0.12)
            end
        end)
        buttonFrame.MouseLeave:Connect(function()
            if closed then
                return
            end
            if primary then
                tween(buttonFrame, { BackgroundTransparency = restBg }, 0.2)
                tween(buttonStroke, { Transparency = restStroke }, 0.2)
            else
                tween(buttonStroke, { Color = Theme.Stroke }, 0.2)
            end
        end)
        buttonFrame.MouseButton1Click:Connect(function()
            dialog.Close()
            safeCall(spec.Callback)
        end)
    end

    if opts.CloseOnBackdrop ~= false then
        overlay.MouseButton1Click:Connect(function()
            dialog.Close()
            safeCall(opts.OnCancel)
        end)
    end

    self._dialog = dialog
    tween(overlay, { BackgroundTransparency = 0.45 }, 0.25)
    tween(card, { BackgroundTransparency = 0, Position = UDim2.fromScale(0.5, 0.5) }, 0.3, Enum.EasingStyle.Quint)
    tween(cardStroke, { Transparency = 0 }, 0.25)
    tween(cardScale, { Scale = 1 }, 0.4, Enum.EasingStyle.Back)
    for _, entry in ipairs(fading) do
        tween(entry[1], { [entry[2]] = entry[3] }, 0.25)
    end
    return dialog
end

function Window:Confirm(opts)
    opts = normalize(opts, { Text = "Content", Message = "Content" })
    return self:Dialog({
        Title = opts.Title or "Are you sure?",
        Content = opts.Content,
        Icon = opts.Icon,
        OnCancel = opts.OnCancel,
        Buttons = {
            { Title = opts.CancelText or "Cancel", Callback = opts.OnCancel },
            { Title = opts.ConfirmText or "Confirm", Variant = "Primary", Callback = opts.Callback },
        },
    })
end

function Window:_listen(kind, handler, owner)
    local list = self._inputListeners[kind]
    table.insert(list, handler)
    local function disconnect()
        for index, entry in ipairs(list) do
            if entry == handler then
                table.remove(list, index)
                break
            end
        end
    end
    if owner then
        owner._listeners = owner._listeners or {}
        table.insert(owner._listeners, disconnect)
    end
    return disconnect
end

function Window:_indicatorY(tab)
    local stack = self._tabStack
    return (tab._button.AbsolutePosition.Y - stack.AbsolutePosition.Y) / self.Scale.Scale + stack.Position.Y.Offset
end

function Window:_placeIndicator(tab)
    local indicator = self.Indicator
    local targetY = self:_indicatorY(tab)
    if not indicator.Visible then
        indicator.Visible = true
        indicator.Position = UDim2.fromOffset(8, targetY)
        indicator.BackgroundTransparency = 1
        tween(indicator, { BackgroundTransparency = 0.35 }, 0.3)
    end
    tween(indicator, { Position = UDim2.fromOffset(8, targetY) }, 0.45, Enum.EasingStyle.Quint)
end

function Window:_overflowHint(host, scroller, items, vertical, fadeColor)
    local overlay = create("Frame", {
        AnchorPoint = scroller.AnchorPoint,
        Position = scroller.Position,
        Size = scroller.Size,
        BackgroundTransparency = 1,
        ZIndex = 3,
        Parent = host,
    })
    local function mirror()
        overlay.Position = scroller.Position
        overlay.Size = scroller.Size
        overlay.Visible = scroller.Visible
    end
    for _, property in ipairs({ "Position", "Size", "Visible" }) do
        scroller:GetPropertyChangedSignal(property):Connect(mirror)
    end

    local function axis(vector)
        return vertical and vector.Y or vector.X
    end
    local function scale()
        return self.Scale and self.Scale.Scale or 1
    end
    local function scrollBy(direction)
        local view = axis(scroller.AbsoluteWindowSize) / scale()
        local limit = math.max(axis(scroller.AbsoluteCanvasSize) / scale() - view, 0)
        local target = math.clamp(axis(scroller.CanvasPosition) + direction * view * 0.75, 0, limit)
        tween(scroller, { CanvasPosition = vertical and Vector2.new(0, target) or Vector2.new(target, 0) }, 0.35, Enum.EasingStyle.Quint)
    end

    local hints = {}
    for _, direction in ipairs({ -1, 1 }) do
        local far = direction > 0
        local fade = create("Frame", {
            AnchorPoint = vertical and Vector2.new(0, far and 1 or 0) or Vector2.new(far and 1 or 0, 0),
            Position = vertical and UDim2.fromScale(0, far and 1 or 0) or UDim2.fromScale(far and 1 or 0, 0),
            Size = vertical and UDim2.new(1, 0, 0, 34) or UDim2.new(0, 48, 1, 0),
            BackgroundColor3 = fadeColor,
            BackgroundTransparency = 1,
            BorderSizePixel = 0,
            Visible = false,
            Parent = overlay,
        })
        create("UIGradient", {
            Rotation = vertical and (far and 270 or 90) or (far and 180 or 0),
            Transparency = NumberSequence.new({
                NumberSequenceKeypoint.new(0, 0),
                NumberSequenceKeypoint.new(0.4, 0.2),
                NumberSequenceKeypoint.new(1, 1),
            }),
            Parent = fade,
        })
        local home = vertical and UDim2.new(0.5, 0, far and 1 or 0, far and -5 or 5) or UDim2.new(far and 1 or 0, far and -2 or 2, 0.5, 0)
        local chip = create("TextButton", {
            AnchorPoint = vertical and Vector2.new(0.5, far and 1 or 0) or Vector2.new(far and 1 or 0, 0.5),
            Position = home,
            Size = UDim2.fromOffset(0, 20),
            AutomaticSize = Enum.AutomaticSize.X,
            BackgroundColor3 = Theme.Surface3,
            BackgroundTransparency = 1,
            BorderSizePixel = 0,
            Text = "",
            AutoButtonColor = false,
            Visible = false,
            ZIndex = 2,
            Parent = overlay,
        })
        corner(chip, UDim.new(1, 0))
        local chipStroke = stroke(chip, Theme.Stroke, 1)
        padding(chip, 7, 7)
        create("UIListLayout", {
            FillDirection = Enum.FillDirection.Horizontal,
            VerticalAlignment = Enum.VerticalAlignment.Center,
            SortOrder = Enum.SortOrder.LayoutOrder,
            Padding = UDim.new(0, 3),
            Parent = chip,
        })
        local arrow = create("ImageLabel", {
            Size = UDim2.fromOffset(12, 12),
            BackgroundTransparency = 1,
            ImageColor3 = Theme.Accent,
            ImageTransparency = 1,
            ScaleType = Enum.ScaleType.Fit,
            LayoutOrder = 1,
            ZIndex = 2,
            Parent = chip,
        })
        applyIcon(arrow, vertical and (far and "chevron-down" or "chevron-up") or (far and "chevron-right" or "chevron-left"))
        local arrowFade = "ImageTransparency"
        if arrow.Image == "" then
            arrow:Destroy()
            arrow = label({
                Size = UDim2.fromOffset(10, 20),
                Text = "›",
                TextSize = 16,
                TextColor3 = Theme.Accent,
                TextTransparency = 1,
                TextXAlignment = Enum.TextXAlignment.Center,
                TextTruncate = Enum.TextTruncate.None,
                Rotation = vertical and (far and 90 or -90) or (far and 0 or 180),
                LayoutOrder = 1,
                ZIndex = 2,
                Parent = chip,
            })
            arrowFade = "TextTransparency"
        end
        local count = label({
            Size = UDim2.new(0, 0, 1, 0),
            AutomaticSize = Enum.AutomaticSize.X,
            Text = "",
            TextSize = 11,
            TextColor3 = Theme.Text,
            TextTransparency = 1,
            TextTruncate = Enum.TextTruncate.None,
            Visible = false,
            LayoutOrder = 2,
            ZIndex = 2,
            Parent = chip,
        })
        chip.MouseEnter:Connect(function()
            if not usingTouch() then
                tween(chipStroke, { Color = Theme.StrokeHover }, 0.12)
            end
        end)
        chip.MouseLeave:Connect(function()
            tween(chipStroke, { Color = Theme.Stroke }, 0.2)
        end)
        chip.MouseButton1Click:Connect(function()
            scrollBy(direction)
        end)
        hints[direction] = {
            Direction = direction,
            Fade = fade,
            Chip = chip,
            Stroke = chipStroke,
            Arrow = arrow,
            ArrowFade = arrowFade,
            Count = count,
            Home = home,
            Shown = false,
            Generation = 0,
        }
    end

    local function show(hint, on)
        if hint.Shown == on then
            return
        end
        hint.Shown = on
        hint.Generation += 1
        local away = hint.Home + (vertical and UDim2.fromOffset(0, hint.Direction * 6) or UDim2.fromOffset(hint.Direction * 6, 0))
        local value = on and 0 or 1
        if on then
            hint.Fade.Visible = true
            hint.Chip.Visible = true
            hint.Chip.Position = away
            tween(hint.Chip, { Position = hint.Home, BackgroundTransparency = 0.08 }, 0.3, Enum.EasingStyle.Quint)
        else
            tween(hint.Chip, { Position = away, BackgroundTransparency = 1 }, 0.2, Enum.EasingStyle.Quint)
            local generation = hint.Generation
            task.delay(0.21, function()
                if hint.Generation == generation then
                    hint.Fade.Visible = false
                    hint.Chip.Visible = false
                end
            end)
        end
        tween(hint.Fade, { BackgroundTransparency = value }, 0.2)
        tween(hint.Stroke, { Transparency = value }, 0.2)
        tween(hint.Arrow, { [hint.ArrowFade] = value }, 0.2)
        tween(hint.Count, { TextTransparency = value }, 0.2)
    end

    local function refresh()
        local view = axis(scroller.AbsoluteWindowSize)
        local overflow = (axis(scroller.AbsoluteCanvasSize) - view) / scale()
        local position = axis(scroller.CanvasPosition)
        local start = axis(scroller.AbsolutePosition)
        local before, after = 0, 0
        for _, item in ipairs(items:GetChildren()) do
            if item:IsA("GuiObject") and item.Visible and axis(item.AbsoluteSize) > 0 then
                local centre = axis(item.AbsolutePosition) + axis(item.AbsoluteSize) / 2 - start
                if centre < 0 then
                    before += 1
                elseif centre > view then
                    after += 1
                end
            end
        end
        for direction, hint in pairs(hints) do
            local hidden = direction < 0 and before or after
            hint.Count.Text = tostring(hidden)
            hint.Count.Visible = hidden > 0
            show(hint, overflow > 1 and (direction < 0 and position > 1 or direction > 0 and position < overflow - 1))
        end
    end
    for _, property in ipairs({ "CanvasPosition", "AbsoluteCanvasSize", "AbsoluteWindowSize" }) do
        scroller:GetPropertyChangedSignal(property):Connect(refresh)
    end
    task.defer(refresh)
end

function Window:_scrollTabIntoView(tab)
    local list = self.TabList
    local scale = self.Scale.Scale
    local top = (tab._button.AbsolutePosition.Y - list.AbsolutePosition.Y) / scale + list.CanvasPosition.Y
    local bottom = top + tab._button.AbsoluteSize.Y / scale
    local view = list.AbsoluteWindowSize.Y / scale
    local y = list.CanvasPosition.Y
    if top - 8 < y then
        y = top - 8
    elseif bottom + 8 > y + view then
        y = bottom + 8 - view
    else
        return
    end
    tween(list, { CanvasPosition = Vector2.new(0, math.max(0, y)) }, 0.35, Enum.EasingStyle.Quint)
end

function Window:_closePopups()
    if self._closePopup then
        self._closePopup()
    end
end

function Window:_popoutLayer()
    if self._popLayer then
        return self._popLayer
    end
    local layer = create("Frame", {
        Name = "PopOuts",
        Size = UDim2.fromScale(1, 1),
        BackgroundTransparency = 1,
        ZIndex = 20,
        Parent = self.Gui,
    })
    local layerScale = create("UIScale", { Parent = layer })
    self._popLayer = layer
    self._popPanels = {}
    self:_listen("Render", function()
        local scale = math.max(self.Scale.Scale, 0.05)
        if math.abs(layerScale.Scale - scale) > 1e-4 then
            layerScale.Scale = scale
            layer.Size = UDim2.fromScale(1 / scale, 1 / scale)
        end
        layer.Visible = self.Open == true and not self._destroyed
    end)
    return layer
end

function Window:_popupHost(object)
    local layer = self._popLayer
    if layer and object and object:IsDescendantOf(layer) then
        return layer
    end
    return self.Body
end

function Window:_overPopout(point)
    local layer = self._popLayer
    if not layer or not layer.Visible then
        return false
    end
    for _, panel in ipairs(self._popPanels) do
        if panel.Parent and panel.Visible and pointInside(point, panel) then
            return true
        end
    end
    -- Island groupboxes share the layer but are not dockable panels.
    for _, island in ipairs(self._islands or {}) do
        local frame = island.Frame
        if frame and frame.Parent and frame.Visible and pointInside(point, frame) then
            return true
        end
    end
    return false
end

function Window:_fade(target, duration)
    local fader, body = self._fader, self.Body
    self._fadeGeneration = (self._fadeGeneration or 0) + 1
    local generation = self._fadeGeneration
    if body.Parent ~= fader then
        fader.GroupTransparency = self._bodyAlpha
        body.Parent = fader
    end
    fader.Visible = true
    self._bodyAlpha = target
    tween(fader, { GroupTransparency = target }, duration)
    task.delay(duration + 0.03, function()
        if self._fadeGeneration == generation and target <= 0 and not self._destroyed then
            body.Parent = self.Root
            fader.Visible = false
        end
    end)
end

function Window:SelectTab(tab)
    if self.CurrentTab == tab then
        return
    end
    local previous = self.CurrentTab
    self:_resetSearch()
    self:_closePopups()
    self.CurrentTab = tab

    self:_settleTransition()
    local generation = (self._transitionGeneration or 0) + 1
    self._transitionGeneration = generation

    if previous then
        tween(previous._label, { TextColor3 = Theme.Muted }, 0.3)
        if previous._icon then
            tintIcon(previous._icon, Theme.Muted, false, 0.3)
        end
        local outLayer = self._outLayer
        previous._page.Parent = outLayer
        self._outPage = previous._page
        outLayer.GroupTransparency = 0
        outLayer.Position = UDim2.fromOffset(0, 0)
        outLayer.Visible = true
        tween(outLayer, { GroupTransparency = 1, Position = UDim2.fromOffset(0, -6) }, 0.2, Enum.EasingStyle.Quint)
        task.delay(0.18, function()
            if self._transitionGeneration == generation then
                self:_settleOut()
            end
        end)
    end

    tween(tab._button, { BackgroundTransparency = 1 }, 0.2)
    tween(tab._stroke, { Transparency = 1 }, 0.2)
    tween(tab._label, { TextColor3 = Theme.Text }, 0.3)
    if tab._icon then
        tintIcon(tab._icon, Theme.Text, true, 0.3)
    end

    self:_placeIndicator(tab)
    self:_scrollTabIntoView(tab)

    local page = tab._page
    page.Position = UDim2.fromOffset(0, 0)
    page.Visible = true
    page.Parent = self._inLayer
    self._inPage = page
    fadeSlideIn(self._inLayer)
    task.delay(0.32, function()
        if self._transitionGeneration == generation then
            self:_settleIn()
        end
    end)
end

function Window:_settleOut()
    local page = self._outPage
    if page then
        page.Parent = self.Content
        page.Visible = false
        self._outPage = nil
    end
    self._outLayer.Visible = false
end

function Window:_settleIn()
    local page = self._inPage
    if page then
        page.Parent = self.Content
        page.Position = UDim2.fromOffset(0, 0)
        self._inPage = nil
    end
    self._inLayer.Visible = false
end

function Window:_settleTransition()
    self:_settleOut()
    self:_settleIn()
end

local WEATHER = {
    Rain = { Image = "rbxassetid://241868005", Count = 90, Stretch = true },
    Snow = { Image = "rbxassetid://99851851", Count = 60 },
    Ember = { Image = "rbxassetid://242205518", Count = 55 },
    Sakura = { Petal = true, Count = 46, Glow = Color3.fromRGB(255, 150, 190), GlowAmount = 0.1 },
    Fireflies = { Image = Assets.Glow, Count = 34, Glow = Color3.fromRGB(70, 150, 60), GlowAmount = 0.16 },
    Matrix = {
        Text = true,
        Count = 38,
        Glow = Color3.fromRGB(30, 200, 90),
        GlowAmount = 0.07,
        Glyphs = "01234567890123456789アイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワン+-*=<>:",
    },
}
local WEATHER_NAMES = {
    rain = "Rain",
    snow = "Snow",
    ember = "Ember",
    embers = "Ember",
    fire = "Ember",
    hellfire = "Ember",
    sakura = "Sakura",
    petals = "Sakura",
    cherryblossom = "Sakura",
    firefly = "Fireflies",
    fireflies = "Fireflies",
    matrix = "Matrix",
    matrixrain = "Matrix",
    code = "Matrix",
}
local RAIN_STREAK = Vector2.new(7 / 420, 151 / 263)
local weatherRandom = Random.new()

local function weatherMode(mode)
    if type(mode) == "string" and ({ ui = true, window = true, inside = true })[mode:lower()] then
        return "UI"
    end
    return "Screen"
end

local function weatherName(name)
    if type(name) ~= "string" then
        return "None"
    end
    return WEATHER_NAMES[(name:lower():gsub("[%s_%-]", ""))] or "None"
end

local function roll(min, max)
    return weatherRandom:NextNumber(min, max)
end

local function seedParticle(kind, particle, width, height, anywhere)
    particle.Time = roll(0, 10)
    particle.Phase = roll(0, math.pi * 2)
    if kind == "Rain" then
        local w = roll(2, 3.5)
        particle.Size = Vector2.new(w, roll(26, 52))
        particle.VY = roll(950, 1400)
        particle.VX = particle.VY * 0.12
        particle.Sway, particle.Spin = 0, 0
        particle.Rotation = -math.deg(math.atan2(particle.VX, particle.VY))
        particle.Alpha = roll(0, 0.35)
        particle.X = roll(-0.15 * width, width)
        particle.Y = anywhere and roll(-40, height) or roll(-120, -particle.Size.Y)
    elseif kind == "Snow" then
        local s = roll(6, 17)
        particle.Size = Vector2.new(s, s)
        particle.VY = roll(30, 55) * (0.6 + s / 17)
        particle.VX = roll(-8, 14)
        particle.Sway = roll(12, 38)
        particle.Frequency = roll(0.5, 1.3)
        particle.Spin = roll(-60, 60)
        particle.Rotation = roll(0, 360)
        particle.Alpha = roll(0.05, 0.45)
        particle.X = roll(0, width)
        particle.Y = anywhere and roll(-20, height) or roll(-60, -s)
    elseif kind == "Sakura" then
        local s = roll(7, 14)
        particle.Size = Vector2.new(s, s * roll(0.55, 0.75))
        particle.VY = roll(35, 70)
        particle.VX = roll(18, 45)
        particle.Sway = roll(14, 34)
        particle.Frequency = roll(0.6, 1.4)
        particle.Flutter = roll(1.2, 2.6)
        particle.Spin = roll(-90, 90)
        particle.Rotation = roll(0, 360)
        particle.Alpha = roll(0.05, 0.35)
        particle.Color = Color3.fromRGB(255, 205, 220):Lerp(Color3.fromRGB(255, 140, 180), roll(0, 1))
        particle.X = roll(-0.25 * width, width)
        particle.Y = anywhere and roll(-20, height) or roll(-60, -s)
    elseif kind == "Fireflies" then
        local s = roll(14, 28)
        particle.Size = Vector2.new(s, s)
        particle.VY = roll(-14, 8)
        particle.VX = roll(-12, 12)
        particle.Sway = roll(10, 30)
        particle.SwayY = roll(8, 22)
        particle.Frequency = roll(0.3, 0.8)
        particle.Spin, particle.Rotation = 0, 0
        particle.Alpha = roll(0, 0.25)
        particle.Life = roll(5, 11)
        particle.Age = anywhere and roll(0, particle.Life) or 0
        particle.Pulse = roll(1.5, 3.5)
        particle.Color = Color3.fromRGB(200, 255, 120):Lerp(Color3.fromRGB(255, 230, 120), roll(0, 1))
        particle.X = roll(0, width)
        particle.Y = roll(height * 0.15, height)
    elseif kind == "Matrix" then
        local definition = WEATHER.Matrix
        if not definition.List then
            definition.List = {}
            for _, code in utf8.codes(definition.Glyphs) do
                table.insert(definition.List, utf8.char(code))
            end
        end
        local list = definition.List
        local s = math.floor(roll(12, 19))
        local length = math.floor(roll(8, 20))
        particle.TextSize = s
        particle.Size = Vector2.new(s + 6, s * length)
        particle.VY = roll(160, 360) * (s / 15)
        particle.VX, particle.Sway, particle.Spin, particle.Rotation = 0, 0, 0, 0
        -- Smaller columns read as further away: dimmer.
        particle.Alpha = roll(0, 0.25) + (19 - s) * 0.04
        particle.X = math.floor(roll(0, width) / 18) * 18 + 9
        particle.Y = anywhere and roll(-particle.Size.Y / 2, height) or -particle.Size.Y / 2 - roll(0, 240)
        particle.Chars = {}
        for index = 1, length do
            particle.Chars[index] = list[math.random(#list)]
        end
        particle.Shuffle = roll(0.05, 0.2)
    else
        local s = roll(4, 12)
        particle.Size = Vector2.new(s, s)
        particle.VY = -roll(60, 170)
        particle.VX = roll(-12, 12)
        particle.Sway = roll(8, 28)
        particle.Frequency = roll(1, 2.4)
        particle.Spin = roll(-140, 140)
        particle.Rotation = roll(0, 360)
        particle.Alpha = roll(0, 0.3)
        particle.Color = Color3.fromRGB(255, 70, 20):Lerp(Color3.fromRGB(255, 190, 70), roll(0, 1))
        particle.X = roll(0, width)
        particle.Y = anywhere and roll(height * 0.2, height + 10) or height + roll(10, 80)
    end
    local label = particle.Label
    if kind == "Rain" then
        label.Size = UDim2.fromOffset(particle.Size.X / RAIN_STREAK.X, particle.Size.Y / RAIN_STREAK.Y)
    else
        label.Size = UDim2.fromOffset(particle.Size.X, particle.Size.Y)
    end
    if kind == "Matrix" then
        label.TextSize = particle.TextSize
        label.Text = table.concat(particle.Chars, "\n")
    elseif kind == "Sakura" then
        label.BackgroundColor3 = particle.Color
    else
        label.ImageColor3 = particle.Color
            or (kind == "Rain" and Color3.fromRGB(190, 210, 245) or Color3.new(1, 1, 1))
    end
end

function Window:_buildBackdrop(opts)
    local layer = create("Frame", {
        Name = "Backdrop",
        Size = UDim2.fromScale(1, 1),
        BackgroundTransparency = 1,
        Visible = false,
        ZIndex = 0,
        Parent = self.Gui,
    })
    local tint = create("Frame", {
        Size = UDim2.fromScale(1, 1),
        BackgroundColor3 = Color3.new(0, 0, 0),
        BackgroundTransparency = 1,
        BorderSizePixel = 0,
        ZIndex = 0,
        Parent = layer,
    })
    -- Darker towards the top and bottom edges.
    create("UIGradient", {
        Rotation = 90,
        Transparency = NumberSequence.new({
            NumberSequenceKeypoint.new(0, 0),
            NumberSequenceKeypoint.new(0.5, 0.3),
            NumberSequenceKeypoint.new(1, 0),
        }),
        Parent = tint,
    })
    -- Heat rising from the bottom of the screen, hell fire only.
    local heat = create("Frame", {
        AnchorPoint = Vector2.new(0, 1),
        Position = UDim2.fromScale(0, 1),
        Size = UDim2.fromScale(1, 0.5),
        BackgroundColor3 = Color3.fromRGB(255, 60, 15),
        BackgroundTransparency = 1,
        BorderSizePixel = 0,
        ZIndex = 1,
        Parent = layer,
    })
    create("UIGradient", {
        Rotation = 90,
        Transparency = NumberSequence.new(1, 0),
        Parent = heat,
    })
    local field = create("Frame", {
        Size = UDim2.fromScale(1, 1),
        BackgroundTransparency = 1,
        ClipsDescendants = true,
        ZIndex = 2,
        Parent = layer,
    })
    heat.Parent = field
    self._backdrop = layer
    self._backdropTintFrame = tint
    self._backdropHeat = heat
    self._weatherField = field
    self._weatherParticles = {}
    self._backdropFade = 0
    self._weatherKick = 0
    self._backdropShown = false
    self._backdropEnabled = opts.Enabled ~= false
    self._backdropTint = math.clamp(tonumber(opts.Tint) or 0.45, 0, 1)
    self._backdropDim = opts.Dim ~= false
    self._dimLevel = self._backdropDim and 1 or 0
    self._weatherDensity = math.clamp(tonumber(opts.Density) or 1, 0, 3)
    self._weatherSpeed = math.clamp(tonumber(opts.Speed) or 1, 0.1, 3)
    self.Weather = weatherName(opts.Weather == nil and "Matrix" or opts.Weather)
    self.WeatherMode = "Screen"
    self:SetWeatherMode(opts.Mode)
    self:_rebuildWeather()
    table.insert(self._frameSteps, function(deltaTime)
        self:_stepBackdrop(deltaTime)
    end)
end

-- The area the particles cover, in the field's own (unscaled) units.
function Window:_weatherSize()
    if self.WeatherMode == "UI" then
        return Vector2.new(self.Root.Size.X.Offset, self.Root.Size.Y.Offset)
    end
    return self.Gui.AbsoluteSize
end

function Window:_rebuildWeather()
    for _, particle in ipairs(self._weatherParticles) do
        particle.Label:Destroy()
    end
    self._weatherParticles = {}
    local definition = WEATHER[self.Weather]
    if not definition then
        return
    end
    self._backdropHeat.BackgroundColor3 = definition.Glow or Color3.fromRGB(255, 60, 15)
    local size = self:_weatherSize()
    -- The window is a fraction of the screen, so it gets fewer particles.
    local count = definition.Count * self._weatherDensity * (self.WeatherMode == "UI" and 0.45 or 1)
    for _ = 1, math.floor(count + 0.5) do
        local instance, property
        if definition.Text then
            property = "TextTransparency"
            instance = create("TextLabel", {
                AnchorPoint = Vector2.new(0.5, 0.5),
                BackgroundTransparency = 1,
                Text = "",
                TextColor3 = Color3.fromRGB(90, 255, 140),
                TextTransparency = 1,
                FontFace = Font.fromEnum(Enum.Font.Code),
                TextXAlignment = Enum.TextXAlignment.Center,
                TextYAlignment = Enum.TextYAlignment.Top,
                LineHeight = 1,
                ZIndex = 2,
                Parent = self._weatherField,
            })
            -- A fading tail and a pale leading glyph.
            create("UIGradient", {
                Rotation = 90,
                Color = ColorSequence.new({
                    ColorSequenceKeypoint.new(0, Color3.new(1, 1, 1)),
                    ColorSequenceKeypoint.new(0.88, Color3.new(1, 1, 1)),
                    ColorSequenceKeypoint.new(1, Color3.fromRGB(235, 255, 240)),
                }),
                Transparency = NumberSequence.new({
                    NumberSequenceKeypoint.new(0, 1),
                    NumberSequenceKeypoint.new(0.6, 0.45),
                    NumberSequenceKeypoint.new(1, 0),
                }),
                Parent = instance,
            })
        elseif definition.Petal then
            property = "BackgroundTransparency"
            instance = create("Frame", {
                AnchorPoint = Vector2.new(0.5, 0.5),
                BackgroundColor3 = Color3.fromRGB(255, 190, 210),
                BackgroundTransparency = 1,
                BorderSizePixel = 0,
                ZIndex = 2,
                Parent = self._weatherField,
            })
            corner(instance, UDim.new(1, 0))
            create("UIGradient", {
                Rotation = 35,
                Color = ColorSequence.new(Color3.new(1, 1, 1), Color3.fromRGB(235, 200, 215)),
                Parent = instance,
            })
        else
            property = "ImageTransparency"
            instance = create("ImageLabel", {
                AnchorPoint = Vector2.new(0.5, 0.5),
                BackgroundTransparency = 1,
                Image = definition.Image,
                ImageTransparency = 1,
                ScaleType = definition.Stretch and Enum.ScaleType.Stretch or Enum.ScaleType.Fit,
                ZIndex = 2,
                Parent = self._weatherField,
            })
        end
        local particle = { Label = instance, Property = property }
        seedParticle(self.Weather, particle, size.X, size.Y, true)
        table.insert(self._weatherParticles, particle)
    end
end

function Window:_stepBackdrop(deltaTime)
    local target = self._backdropShown and 1 or 0
    local fade = self._backdropFade
    if fade == target and target == 0 then
        return
    end
    if fade < target then
        fade = math.min(fade + deltaTime / 0.45, target)
    elseif fade > target then
        fade = math.max(fade - deltaTime / 0.25, target)
    end
    self._backdropFade = fade
    if fade <= 0 then
        self._backdrop.Visible = false
        self._weatherField.Visible = false
        return
    end
    local eased = 1 - (1 - fade) ^ 3
    local kind = self.Weather
    -- The dim eases on its own so turning it off doesn't touch the weather.
    local dim = self._dimLevel
    if self._backdropDim then
        dim = math.min(dim + deltaTime / 0.3, 1)
    else
        dim = math.max(dim - deltaTime / 0.3, 0)
    end
    self._dimLevel = dim
    self._backdropTintFrame.BackgroundTransparency = 1 - self._backdropTint * eased * dim
    local definition = WEATHER[kind]
    self._backdropHeat.BackgroundTransparency = kind == "Ember"
        and 1 - (0.22 + math.sin(os.clock() * 2.1) * 0.05) * eased
        or definition and definition.GlowAmount and 1 - (definition.GlowAmount + math.sin(os.clock() * 0.8) * definition.GlowAmount * 0.25) * eased
        or 1

    -- The gust on restore: particles rush in fast and settle back.
    local kick = self._weatherKick
    self._weatherKick = math.max(kick - deltaTime * 1.3, 0)
    local speed = self._weatherSpeed * (1 + kick * kick * 2.5)
    local size = self:_weatherSize()
    local width, height = size.X, size.Y
    for _, particle in ipairs(self._weatherParticles) do
        particle.Time += deltaTime
        particle.X += particle.VX * deltaTime * speed
        particle.Y += particle.VY * deltaTime * speed
        particle.Rotation += particle.Spin * deltaTime * speed
        local margin = math.max(particle.Size.X, particle.Size.Y)
        if particle.Life then
            particle.Age += deltaTime
        end
        if (particle.Life and particle.Age > particle.Life)
            or (not particle.Life and ((particle.VY > 0 and particle.Y > height + margin) or (particle.VY < 0 and particle.Y < -margin))) then
            seedParticle(kind, particle, width, height, false)
        elseif particle.X > width + margin * 4 then
            particle.X -= width + margin * 6
        elseif particle.X < -margin * 4 then
            particle.X += width + margin * 6
        end
        local x = particle.X
        local alpha = 1 - particle.Alpha
        if particle.Sway ~= 0 then
            x += math.sin(particle.Time * particle.Frequency + particle.Phase) * particle.Sway
        end
        local y = particle.Y
        local label = particle.Label
        if kind == "Ember" then
            -- Flicker, and burn out on the way up.
            alpha *= math.clamp(particle.Y / (height * 0.85), 0, 1) ^ 0.6
            alpha *= 0.75 + math.sin(particle.Time * 9 + particle.Phase) * 0.25
        elseif kind == "Sakura" then
            -- Flip: the petal narrows and widens as it turns over.
            local turn = math.abs(math.cos(particle.Time * particle.Flutter + particle.Phase))
            label.Size = UDim2.fromOffset(particle.Size.X * (0.3 + turn * 0.7), particle.Size.Y)
        elseif kind == "Fireflies" then
            y += math.cos(particle.Time * particle.Frequency * 1.3 + particle.Phase) * particle.SwayY
            local age, life = particle.Age, particle.Life
            alpha *= math.clamp(math.min(age / 1.2, (life - age) / 1.2), 0, 1)
            alpha *= 0.5 + math.sin(particle.Time * particle.Pulse + particle.Phase) * 0.5
        elseif kind == "Matrix" then
            particle.Shuffle -= deltaTime * speed
            if particle.Shuffle <= 0 then
                particle.Shuffle = roll(0.05, 0.2)
                local list = WEATHER.Matrix.List
                local chars = particle.Chars
                chars[math.random(#chars)] = list[math.random(#list)]
                chars[#chars] = list[math.random(#list)]
                label.Text = table.concat(chars, "\n")
            end
        end
        label.Position = UDim2.fromOffset(x, y)
        label.Rotation = particle.Rotation
        label[particle.Property or "ImageTransparency"] = 1 - alpha * eased
    end
end

function Window:_refreshBackdrop(gust)
    if not self._backdrop then
        return
    end
    local shown = self._backdropEnabled and self._introDone and self.Open and not self.Minimized and not self._destroyed
    if shown and not self._backdropShown then
        self._backdrop.Visible = true
        self._weatherField.Visible = true
        if self._backdropFade <= 0 then
            local size = self:_weatherSize()
            for _, particle in ipairs(self._weatherParticles) do
                seedParticle(self.Weather, particle, size.X, size.Y, true)
            end
        end
        if gust then
            self._weatherKick = 1
        end
    end
    self._backdropShown = shown == true
end

function Window:SetBackdrop(enabled)
    if not self._backdrop then
        return
    end
    self._backdropEnabled = enabled ~= false
    local toggle = self._interfaceBackdropToggle
    if toggle and not toggle._destroyed then
        toggle:Set(self._backdropEnabled, true)
    end
    self:_refreshBackdrop(true)
end

function Window:SetBackdropTint(amount)
    if not self._backdrop then
        return
    end
    self._backdropTint = math.clamp(tonumber(amount) or 0.45, 0, 1)
end

-- Turns the black tint on or off, leaving the weather running.
function Window:SetDim(enabled)
    if not self._backdrop then
        return
    end
    self._backdropDim = enabled ~= false
end

function Window:SetWeatherMode(mode)
    if not self._backdrop then
        return
    end
    mode = weatherMode(mode)
    local field = self._weatherField
    if mode == "UI" then
        -- Under everything else in the body: sidebar, content and glows.
        field.ZIndex = 0
        field.Parent = self.Body
    else
        field.ZIndex = 2
        field.Parent = self._backdrop
    end
    if mode == self.WeatherMode then
        return
    end
    self.WeatherMode = mode
    self:_rebuildWeather()
    if self._backdropShown then
        self._weatherKick = 1
    end
end

function Window:SetWeather(name)
    if not self._backdrop then
        return
    end
    local kind = weatherName(name)
    if kind == self.Weather then
        return
    end
    self.Weather = kind
    self:_rebuildWeather()
    if self._backdropShown then
        self._weatherKick = 1
    end
end

function Window:SetWeatherDensity(density)
    if not self._backdrop then
        return
    end
    self._weatherDensity = math.clamp(tonumber(density) or 1, 0, 3)
    self:_rebuildWeather()
end

function Window:SetWeatherSpeed(speed)
    if not self._backdrop then
        return
    end
    self._weatherSpeed = math.clamp(tonumber(speed) or 1, 0.1, 3)
end

-- One table, not separate locals: the main chunk is at Luau's 200 local limit.
local Mini = {
    Top = 8, -- gap from the top of the screen
    Width = TOUCH and 176 or 168, -- compact
    Height = TOUCH and 36 or 32,
    Wide = 340, -- expanded and activity
    Radius = 34, -- corner of the expanded and activity cards
    Bars = 4,
    Pinned = 6,
}

local function makeGhost(window, position, size, radius)
    if window._ghost then
        window._ghost:Destroy()
    end
    local ghost = create("Frame", {
        Position = UDim2.fromOffset(position.X, position.Y),
        Size = UDim2.fromOffset(size.X, size.Y),
        BackgroundColor3 = Theme.Background,
        BackgroundTransparency = 1,
        BorderSizePixel = 0,
        ZIndex = 29,
        Parent = window.Gui,
    })
    local ghostCorner = Library._fixedCorner(ghost, UDim.new(0, radius))
    local ghostStroke = stroke(ghost, Theme.Stroke, 1)
    window._ghost = ghost
    return ghost, ghostStroke, ghostCorner
end

local function morphGhost(ghost, ghostCorner, position, size, radius, duration)
    tween(ghost, {
        Position = UDim2.fromOffset(position.X, position.Y),
        Size = UDim2.fromOffset(size.X, size.Y),
    }, duration, Enum.EasingStyle.Quint)
    tween(ghostCorner, { CornerRadius = UDim.new(0, radius) }, duration, Enum.EasingStyle.Quint)
end

local function dissolve(window, ghost, ghostStroke, duration)
    tween(ghost, { BackgroundTransparency = 1 }, duration, Enum.EasingStyle.Quad)
    tween(ghostStroke, { Transparency = 1 }, duration, Enum.EasingStyle.Quad)
    task.delay(duration + 0.02, function()
        if window._ghost == ghost then
            window._ghost = nil
        end
        ghost:Destroy()
    end)
end

function Window:_buildMiniBar()
    if self.MiniBar then
        return self.MiniBar
    end
    local gui = self.Gui

    local island = create("CanvasGroup", {
        Name = "Island",
        AnchorPoint = Vector2.new(0.5, 0),
        Position = UDim2.new(0.5, 0, 0, Mini.Top),
        Size = UDim2.fromOffset(Mini.Width, Mini.Height),
        BackgroundColor3 = Color3.new(0, 0, 0),
        BorderSizePixel = 0,
        GroupTransparency = 1,
        Visible = false,
        ZIndex = 30,
        Parent = gui,
    })
    local islandCorner = Library._fixedCorner(island, UDim.new(0, Mini.Height / 2))
    local islandScale = create("UIScale", { Parent = island })
    self._miniScale = islandScale
    local merge = create("NumberValue", { Value = 1 })
    local mergeTween
    self._miniOrb = island

    local function layer(name)
        return create("CanvasGroup", {
            Name = name,
            AnchorPoint = Vector2.new(0.5, 0),
            Position = UDim2.fromScale(0.5, 0),
            Size = UDim2.new(0, Mini.Wide, 0, 400),
            BackgroundTransparency = 1,
            GroupTransparency = 1,
            Parent = island,
        })
    end

    local compact = create("CanvasGroup", {
        Name = "Compact",
        Size = UDim2.fromScale(1, 1),
        BackgroundColor3 = Theme.Surface2,
        BorderSizePixel = 0,
        Parent = island,
    })
    create("UIGradient", {
        Rotation = 90,
        Color = ColorSequence.new(Color3.fromRGB(255, 255, 255), Color3.fromRGB(120, 120, 120)),
        Parent = compact,
    })
    local miniLogo = self._logoIcon
    if miniLogo ~= false then
        local logoDisc = create("Frame", {
            AnchorPoint = Vector2.new(0, 0.5),
            Position = UDim2.new(0, 5, 0.5, 0),
            Size = UDim2.fromOffset(Mini.Height - 10, Mini.Height - 10),
            BackgroundColor3 = Theme.Accent,
            BackgroundTransparency = 0.82,
            BorderSizePixel = 0,
            Parent = compact,
        })
        corner(logoDisc, UDim.new(1, 0))
        local logo = create("ImageLabel", {
            AnchorPoint = Vector2.new(0.5, 0.5),
            Position = UDim2.fromScale(0.5, 0.5),
            Size = UDim2.fromOffset(16, 16),
            BackgroundTransparency = 1,
            ImageColor3 = Theme.Accent,
            ScaleType = Enum.ScaleType.Fit,
            Parent = logoDisc,
        })
        applyIcon(logo, miniLogo, true)
    end
    -- The script's name beside the logo, so the pill reads at a glance.
    local titleX = miniLogo ~= false and (Mini.Height + 2) or 14
    local miniTitle = label({
        AnchorPoint = Vector2.new(0, 0.5),
        Position = UDim2.new(0, titleX, 0.5, 0),
        Size = UDim2.new(1, -titleX - 72, 0, 18),
        Text = self.Title,
        TextSize = 13,
        FontFace = Fonts.Bold,
        TextColor3 = Theme.Text,
        Parent = compact,
    })
    local meter = create("Frame", {
        AnchorPoint = Vector2.new(1, 0.5),
        Position = UDim2.new(1, -14, 0.5, 0),
        Size = UDim2.fromOffset(0, 18),
        AutomaticSize = Enum.AutomaticSize.X,
        BackgroundTransparency = 1,
        Parent = compact,
    })
    create("UIListLayout", {
        FillDirection = Enum.FillDirection.Horizontal,
        HorizontalAlignment = Enum.HorizontalAlignment.Right,
        VerticalAlignment = Enum.VerticalAlignment.Center,
        SortOrder = Enum.SortOrder.LayoutOrder,
        Padding = UDim.new(0, 7),
        Parent = meter,
    })
    local barsHolder = create("Frame", {
        Size = UDim2.fromOffset(Mini.Bars * 3 + (Mini.Bars - 1) * 2, 16),
        BackgroundTransparency = 1,
        Visible = false,
        LayoutOrder = 1,
        Parent = meter,
    })
    local bars = {}
    for index = 1, Mini.Bars do
        local bar = create("Frame", {
            AnchorPoint = Vector2.new(0, 0.5),
            Position = UDim2.new(0, (index - 1) * 5, 0.5, 0),
            Size = UDim2.fromOffset(3, 3),
            BackgroundColor3 = Theme.Muted,
            BorderSizePixel = 0,
            Parent = barsHolder,
        })
        corner(bar, UDim.new(1, 0))
        bars[index] = bar
    end
    local countLabel = label({
        Size = UDim2.fromOffset(0, 18),
        AutomaticSize = Enum.AutomaticSize.X,
        Text = "",
        TextSize = 13,
        FontFace = Fonts.Bold,
        TextTruncate = Enum.TextTruncate.None,
        Visible = false,
        LayoutOrder = 2,
        Parent = meter,
    })
    local idleDot = create("Frame", {
        Size = UDim2.fromOffset(6, 6),
        BackgroundColor3 = Theme.Accent,
        BorderSizePixel = 0,
        LayoutOrder = -1,
        Parent = meter,
    })
    corner(idleDot, UDim.new(1, 0))
    local idleLabel = label({
        Size = UDim2.fromOffset(0, 18),
        AutomaticSize = Enum.AutomaticSize.X,
        Text = "0s",
        TextSize = 12,
        FontFace = Fonts.Bold,
        TextColor3 = Theme.Text,
        TextTruncate = Enum.TextTruncate.None,
        LayoutOrder = 0,
        Parent = meter,
    })

    -- Expanded, on hover: the player's session.
    local expanded = layer("Expanded")
    local expandedList = create("Frame", {
        Position = UDim2.fromOffset(16, 14),
        Size = UDim2.new(1, -32, 0, 0),
        AutomaticSize = Enum.AutomaticSize.Y,
        BackgroundTransparency = 1,
        Parent = expanded,
    })
    create("UIListLayout", {
        SortOrder = Enum.SortOrder.LayoutOrder,
        Padding = UDim.new(0, 8),
        Parent = expandedList,
    })
    local top = create("Frame", {
        Size = UDim2.new(1, 0, 0, 48),
        BackgroundTransparency = 1,
        LayoutOrder = 1,
        Parent = expandedList,
    })
    local face = create("ImageLabel", {
        Size = UDim2.fromOffset(48, 48),
        BackgroundColor3 = Theme.Surface3,
        BorderSizePixel = 0,
        Image = "rbxthumb://type=AvatarHeadShot&id=" .. tostring(LocalPlayer.UserId) .. "&w=150&h=150",
        Parent = top,
    })
    corner(face, UDim.new(0, 12))
    local facePlaceholder = create("ImageLabel", {
        AnchorPoint = Vector2.new(0.5, 0.5),
        Position = UDim2.fromScale(0.5, 0.5),
        Size = UDim2.fromOffset(20, 20),
        BackgroundTransparency = 1,
        ImageColor3 = Theme.Muted,
        ImageTransparency = 1,
        ScaleType = Enum.ScaleType.Fit,
        Parent = face,
    })
    applyIcon(facePlaceholder, "user")
    self:_trackAvatar(face, facePlaceholder)
    local nameLabel = label({
        Position = UDim2.fromOffset(60, 5),
        Size = UDim2.new(1, -150, 0, 20),
        TextSize = 15,
        FontFace = Fonts.Bold,
        TextColor3 = Theme.Text,
        Parent = top,
    })
    self:_trackName(nameLabel, "Display")
    local tabLabel = label({
        Position = UDim2.fromOffset(60, 26),
        Size = UDim2.new(1, -150, 0, 15),
        Text = "",
        TextSize = 12,
        FontFace = Fonts.Regular,
        TextColor3 = Theme.Muted,
        Parent = top,
    })
    task.spawn(function()
        tabLabel.Text = detectGameName()
    end)
    local sessionLabel = label({
        AnchorPoint = Vector2.new(1, 0),
        Position = UDim2.new(1, 0, 0, 3),
        Size = UDim2.fromOffset(90, 24),
        Text = "0s",
        TextSize = 20,
        FontFace = Fonts.Bold,
        TextColor3 = Theme.Text,
        TextXAlignment = Enum.TextXAlignment.Right,
        Parent = top,
    })
    label({
        AnchorPoint = Vector2.new(1, 0),
        Position = UDim2.new(1, 0, 0, 27),
        Size = UDim2.fromOffset(90, 14),
        Text = "session",
        TextSize = 11,
        FontFace = Fonts.Regular,
        TextColor3 = Theme.Muted,
        TextXAlignment = Enum.TextXAlignment.Right,
        Parent = top,
    })

    local meters = create("Frame", {
        Size = UDim2.new(1, 0, 0, 42),
        BackgroundTransparency = 1,
        LayoutOrder = 2,
        Parent = expandedList,
    })
    local function meterPill(position, caption)
        local cell = create("Frame", {
            Position = position,
            Size = UDim2.new(0.5, -10, 1, 0),
            BackgroundTransparency = 1,
            Parent = meters,
        })
        local value = label({
            Size = UDim2.new(1, -70, 0, 24),
            Text = "",
            TextSize = 20,
            FontFace = Fonts.Bold,
            TextColor3 = Theme.Text,
            RichText = true,
            Parent = cell,
        })
        label({
            AnchorPoint = Vector2.new(1, 0),
            Position = UDim2.new(1, 0, 0, 6),
            Size = UDim2.fromOffset(70, 14),
            Text = caption,
            TextSize = 10,
            TextColor3 = Theme.Muted,
            TextXAlignment = Enum.TextXAlignment.Right,
            Parent = cell,
        })
        local track = create("Frame", {
            AnchorPoint = Vector2.new(0, 1),
            Position = UDim2.new(0, 0, 1, -4),
            Size = UDim2.new(1, 0, 0, 3),
            BackgroundColor3 = Theme.Surface3,
            BorderSizePixel = 0,
            Parent = cell,
        })
        corner(track, UDim.new(1, 0))
        local fill = create("Frame", {
            Size = UDim2.fromScale(0, 1),
            BackgroundColor3 = Theme.Success,
            BorderSizePixel = 0,
            Parent = track,
        })
        corner(fill, UDim.new(1, 0))
        return fill, value
    end
    local fpsFill, fpsValue = meterPill(UDim2.fromScale(0, 0), "FRAME RATE")
    local pingFill, pingValue = meterPill(UDim2.new(0.5, 10, 0, 0), "PING")

    -- Chips: a muted name and a bold value, the running count in accent.
    local chips = create("Frame", {
        Size = UDim2.new(1, 0, 0, 30),
        BackgroundTransparency = 1,
        LayoutOrder = 3,
        Parent = expandedList,
    })
    create("UIListLayout", {
        FillDirection = Enum.FillDirection.Horizontal,
        VerticalAlignment = Enum.VerticalAlignment.Center,
        SortOrder = Enum.SortOrder.LayoutOrder,
        Padding = UDim.new(0, 8),
        Parent = chips,
    })
    local function chipOf(order, name, color)
        local chipFrame = create("Frame", {
            Size = UDim2.fromOffset(0, 30),
            AutomaticSize = Enum.AutomaticSize.X,
            BackgroundColor3 = Theme.Surface3,
            BorderSizePixel = 0,
            LayoutOrder = order,
            Parent = chips,
        })
        corner(chipFrame, UDim.new(1, 0))
        padding(chipFrame, 14, 14)
        create("UIListLayout", {
            FillDirection = Enum.FillDirection.Horizontal,
            VerticalAlignment = Enum.VerticalAlignment.Center,
            SortOrder = Enum.SortOrder.LayoutOrder,
            Padding = UDim.new(0, 7),
            Parent = chipFrame,
        })
        label({
            Size = UDim2.new(0, 0, 1, 0),
            AutomaticSize = Enum.AutomaticSize.X,
            Text = name,
            TextSize = 12,
            FontFace = Fonts.Regular,
            TextColor3 = Theme.Muted,
            TextTruncate = Enum.TextTruncate.None,
            LayoutOrder = 1,
            Parent = chipFrame,
        })
        return label({
            Size = UDim2.new(0, 0, 1, 0),
            AutomaticSize = Enum.AutomaticSize.X,
            Text = "",
            TextSize = 12,
            FontFace = Fonts.Bold,
            TextColor3 = color or Theme.Text,
            TextTruncate = Enum.TextTruncate.None,
            LayoutOrder = 2,
            Parent = chipFrame,
        })
    end
    local playersValue = chipOf(1, "Players")
    local bigCount = chipOf(2, "Running", Theme.Accent)
    local tabValue = chipOf(3, "Tab")

    local rowsHolder = create("Frame", {
        Size = UDim2.new(1, 0, 0, 0),
        BackgroundTransparency = 1,
        Visible = false,
        LayoutOrder = 4,
        Parent = expandedList,
    })
    create("UIListLayout", {
        SortOrder = Enum.SortOrder.LayoutOrder,
        Padding = UDim.new(0, 2),
        Parent = rowsHolder,
    })
    -- What's running, by name, so the count above has something behind it.
    local runningNames = label({
        Size = UDim2.new(1, 0, 0, 15),
        Text = "",
        TextSize = 12,
        FontFace = Fonts.Regular,
        TextColor3 = Theme.Text,
        RichText = true,
        Visible = false,
        LayoutOrder = 4,
        Parent = expandedList,
    })
    local hint = label({
        Size = UDim2.new(1, 0, 0, 14),
        TextSize = 11,
        FontFace = Fonts.Regular,
        TextColor3 = Theme.Muted,
        LayoutOrder = 5,
        Parent = expandedList,
    })

    local sessionStart = self._sessionStart or os.clock()
    local frames, frameClock, fps = 0, os.clock(), 60
    self:_listen("Render", function()
        frames += 1
        local now = os.clock()
        if now - frameClock >= 0.5 then
            fps = math.floor(frames / (now - frameClock) + 0.5)
            frames, frameClock = 0, now
        end
    end)
    local function refreshSession()
        sessionLabel.Text = formatDuration(os.clock() - sessionStart)
        idleLabel.Text = sessionLabel.Text
        tween(idleDot, { BackgroundColor3 = Library._healthColor(fps, 50, 30) }, 0.4)
        local unit = '<font size="12" color="#8A8A93"> %s</font>'
        fpsValue.Text = fps .. string.format(unit, "fps")
        tween(fpsFill, {
            Size = UDim2.fromScale(math.clamp(fps / 60, 0.05, 1), 1),
            BackgroundColor3 = Library._healthColor(fps, 50, 30),
        }, 0.4, Enum.EasingStyle.Quint)
        local okPing, ping = pcall(function()
            return math.floor(LocalPlayer:GetNetworkPing() * 1000)
        end)
        ping = okPing and ping or 0
        pingValue.Text = ping .. string.format(unit, "ms")
        -- Lower ping fills more: 40ms or less is full, 400ms and up is low.
        tween(pingFill, {
            Size = UDim2.fromScale(math.clamp(1 - (ping - 40) / 360, 0.05, 1), 1),
            BackgroundColor3 = Library._healthColor(ping, 90, 180, true),
        }, 0.4, Enum.EasingStyle.Quint)
        playersValue.Text = #Players:GetPlayers() .. "/" .. Players.MaxPlayers
        local tab = self.CurrentTab
        tabValue.Text = tab and tab.Name or "-"
    end
    task.spawn(function()
        while island.Parent do
            if island.Visible and self.Minimized then
                refreshSession()
            end
            task.wait(0.5)
        end
    end)

    -- Activity: a notification that arrives while minimized drops in here.
    local activity = layer("Activity")
    local activityList = create("Frame", {
        Position = UDim2.fromOffset(16, 13),
        Size = UDim2.new(1, -32, 0, 0),
        AutomaticSize = Enum.AutomaticSize.Y,
        BackgroundTransparency = 1,
        Parent = activity,
    })
    local activityChip = create("Frame", {
        Size = UDim2.fromOffset(34, 34),
        BackgroundColor3 = Theme.Accent,
        BackgroundTransparency = 0.85,
        BorderSizePixel = 0,
        Parent = activityList,
    })
    corner(activityChip, UDim.new(1, 0))
    local activityIcon = create("ImageLabel", {
        AnchorPoint = Vector2.new(0.5, 0.5),
        Position = UDim2.fromScale(0.5, 0.5),
        Size = UDim2.fromOffset(17, 17),
        BackgroundTransparency = 1,
        ImageColor3 = Theme.Accent,
        ScaleType = Enum.ScaleType.Fit,
        Parent = activityChip,
    })
    local activityText = create("Frame", {
        Position = UDim2.fromOffset(46, 0),
        Size = UDim2.new(1, -46, 0, 0),
        AutomaticSize = Enum.AutomaticSize.Y,
        BackgroundTransparency = 1,
        Parent = activityList,
    })
    create("UIListLayout", {
        SortOrder = Enum.SortOrder.LayoutOrder,
        Padding = UDim.new(0, 1),
        Parent = activityText,
    })
    local activityTitle = label({
        Size = UDim2.new(1, 0, 0, 18),
        TextSize = 14,
        FontFace = Fonts.Bold,
        LayoutOrder = 1,
        Parent = activityText,
    })
    local activityBody = label({
        Size = UDim2.new(1, 0, 0, 0),
        AutomaticSize = Enum.AutomaticSize.Y,
        TextSize = 12,
        FontFace = Fonts.Regular,
        TextColor3 = Theme.Muted,
        TextWrapped = true,
        TextTruncate = Enum.TextTruncate.None,
        TextYAlignment = Enum.TextYAlignment.Top,
        MaxVisibleGraphemes = 140,
        LayoutOrder = 2,
        Parent = activityText,
    })

    local hit = create("TextButton", {
        Size = UDim2.fromScale(1, 1),
        BackgroundTransparency = 1,
        Text = "",
        AutoButtonColor = false,
        ZIndex = 10,
        Parent = island,
    })

    local layers = { Compact = compact, Expanded = expanded, Activity = activity }
    local mode = "Compact"
    local modeToken = 0
    local sizeTween, cornerTween
    local hovered, pressed = false, false
    local hoverToken = 0
    local dragFrom, dragAnchor, dragging, dragged = nil, nil, false, false
    local activityToken = 0
    local activityLive = false

    local function shapeFor(name)
        if name == "Expanded" then
            return Vector2.new(Mini.Wide, math.floor(expandedList.AbsoluteSize.Y + 28 + 0.5)), Mini.Radius
        elseif name == "Activity" then
            return Vector2.new(Mini.Wide, math.floor(math.max(activityList.AbsoluteSize.Y, 34) + 26 + 0.5)), Mini.Radius
        end
        return Vector2.new(Mini.Width, Mini.Height), Mini.Height / 2
    end

    local saved = self:_readConfigSettings().IslandPosition
    if type(saved) == "table" and tonumber(saved.X) and tonumber(saved.Y) then
        self._islandAnchor = Vector2.new(math.clamp(tonumber(saved.X), 0, 1), math.clamp(tonumber(saved.Y), 0, 1))
    end
    local positionTween
    local function anchorPixels()
        local view = gui.AbsoluteSize
        local anchor = self._islandAnchor
        if not anchor then
            return Vector2.new(view.X / 2, Mini.Top)
        end
        return Vector2.new(anchor.X * view.X, anchor.Y * view.Y)
    end
    local function islandSpot(size, from)
        local view = gui.AbsoluteSize
        local spot = from or anchorPixels()
        local margin = 6
        local x = math.clamp(spot.X, size.X / 2 + margin, math.max(view.X - size.X / 2 - margin, size.X / 2 + margin))
        local y = math.clamp(spot.Y, margin, math.max(view.Y - size.Y - margin, margin))
        return Vector2.new(x, y)
    end
    local function placeIsland(size, duration, style)
        local spot = islandSpot(size)
        if positionTween then
            positionTween:Cancel()
            positionTween = nil
        end
        if duration and duration > 0 then
            positionTween = tween(island, { Position = UDim2.fromOffset(spot.X, spot.Y) }, duration, style or Enum.EasingStyle.Quint)
        else
            island.Position = UDim2.fromOffset(spot.X, spot.Y)
        end
    end
    self._islandReset = function()
        self._islandAnchor = nil
        if island.Visible then
            placeIsland(Vector2.new(island.Size.X.Offset, island.Size.Y.Offset), 0.35)
        end
    end

    local function setMode(name, instant)
        local size, radius = shapeFor(name)
        local changed = name ~= mode
        mode = name
        modeToken += 1
        local token = modeToken
        local current = Vector2.new(island.Size.X.Offset, island.Size.Y.Offset)
        local growing = size.X > current.X + 1 or size.Y > current.Y + 1
        local duration = instant and 0 or (growing and 0.5 or 0.38)
        if sizeTween then
            sizeTween:Cancel()
        end
        if cornerTween then
            cornerTween:Cancel()
        end
        placeIsland(size, duration)
        sizeTween = tween(island, { Size = UDim2.fromOffset(size.X, size.Y) }, duration, growing and Enum.EasingStyle.Back or Enum.EasingStyle.Quint)
        cornerTween = tween(islandCorner, { CornerRadius = UDim.new(0, radius) }, duration, Enum.EasingStyle.Quint)
        if changed and not instant and not pressed and not dragging then
            islandScale.Scale = growing and 0.96 or 1.03
            tween(islandScale, { Scale = 1 }, growing and 0.55 or 0.4, Enum.EasingStyle.Back)
        end
        if changed or instant then
            if mergeTween then
                mergeTween:Cancel()
                mergeTween = nil
            end
            if instant then
                merge.Value = name == "Compact" and 1 or 0
            elseif name == "Compact" then
                -- Wait for the pill to shrink most of the way, then bud off.
                task.delay(duration * 0.55, function()
                    if modeToken == token then
                        mergeTween = tween(merge, { Value = 1 }, 0.6, Enum.EasingStyle.Back)
                    end
                end)
            else
                mergeTween = tween(merge, { Value = 0 }, 0.2, Enum.EasingStyle.Quint)
            end
        end
        if not changed and not instant then
            local target = layers[name]
            if target.GroupTransparency > 0 then
                tween(target, { GroupTransparency = 0 }, 0.22, Enum.EasingStyle.Quad)
            end
            if target ~= compact and target.Position ~= UDim2.fromScale(0.5, 0) then
                tween(target, { Position = UDim2.fromScale(0.5, 0) }, 0.32, Enum.EasingStyle.Quint)
            end
            return
        end
        for key, group in pairs(layers) do
            if key ~= name then
                tween(group, { GroupTransparency = 1 }, instant and 0 or 0.14, Enum.EasingStyle.Quad)
            end
        end
        local target = layers[name]
        if instant then
            target.GroupTransparency = 0
            if target ~= compact then
                target.Position = UDim2.fromScale(0.5, 0)
            end
        else
            if target ~= compact then
                target.Position = UDim2.new(0.5, 0, 0, 6)
            end
            task.delay(0.1, function()
                if modeToken == token then
                    tween(target, { GroupTransparency = 0 }, 0.22, Enum.EasingStyle.Quad)
                    if target ~= compact then
                        tween(target, { Position = UDim2.fromScale(0.5, 0) }, 0.32, Enum.EasingStyle.Quint)
                    end
                end
            end)
        end
    end

    local function settleMode()
        if hovered and not TOUCH and not dragging then
            setMode("Expanded")
        elseif activityLive then
            setMode("Activity")
        elseif self.IslandStyle == "Always Show" and not dragging then
            self:_refreshMini()
            refreshSession()
            setMode("Expanded")
        else
            setMode("Compact")
        end
    end

    self._islandSettle = function()
        if self.Minimized and island.Visible and not dragging then
            settleMode()
        end
    end

    function self:_miniLand()
        hovered, activityLive = false, false
        activityToken += 1
        islandScale.Scale = 1
        setMode("Compact", true)
        local size = Vector2.new(Mini.Width, Mini.Height)
        local spot = islandSpot(size)
        return Vector2.new(spot.X - size.X / 2, spot.Y), size
    end

    hit.MouseEnter:Connect(function()
        if usingTouch() or dragging then
            return
        end
        hovered = true
        hoverToken += 1
        local token = hoverToken
        if mode == "Expanded" then
            return
        end
        if not pressed then
            tween(islandScale, { Scale = 1.04 }, 0.18, Enum.EasingStyle.Quint)
        end
        task.delay(0.12, function()
            if hoverToken == token and hovered and self.Minimized and not dragging then
                self:_refreshMini()
                refreshSession()
                setMode("Expanded")
            end
        end)
    end)
    hit.MouseLeave:Connect(function()
        hovered = false
        hoverToken += 1
        local token = hoverToken
        if not pressed then
            tween(islandScale, { Scale = 1 }, 0.25, Enum.EasingStyle.Quint)
        end
        task.delay(mode == "Expanded" and 0.28 or 0.1, function()
            if hoverToken == token and not hovered and self.Minimized then
                settleMode()
            end
        end)
    end)
    hit.InputBegan:Connect(function(input)
        if not isPress(input) then
            return
        end
        pressed = true
        dragged = false
        tween(islandScale, { Scale = 0.95 }, 0.12, Enum.EasingStyle.Quad)
        if not self._islandLocked then
            dragFrom = Vector2.new(input.Position.X, input.Position.Y)
            dragAnchor = islandSpot(Vector2.new(Mini.Width, Mini.Height))
        end
    end)
    self:_listen("Changed", function(input)
        if not dragFrom or not isMove(input) or not self.Minimized then
            return
        end
        local delta = Vector2.new(input.Position.X, input.Position.Y) - dragFrom
        if not dragging then
            if delta.Magnitude < (TOUCH and 10 or 6) then
                return
            end
            dragging, dragged = true, true
            hovered = false
            setMode("Compact")
            tween(islandScale, { Scale = 1.06 }, 0.2, Enum.EasingStyle.Quint)
        end
        local spot = islandSpot(Vector2.new(Mini.Width, Mini.Height), dragAnchor + delta)
        local view = gui.AbsoluteSize
        self._islandAnchor = Vector2.new(spot.X / math.max(view.X, 1), spot.Y / math.max(view.Y, 1))
        if positionTween then
            positionTween:Cancel()
            positionTween = nil
        end
        island.Position = UDim2.fromOffset(spot.X, spot.Y)
    end)
    table.insert(self._connections, UserInputService.InputEnded:Connect(function(input)
        if not isPress(input) then
            return
        end
        dragFrom = nil
        if pressed then
            pressed = false
            tween(islandScale, { Scale = 1 }, 0.35, Enum.EasingStyle.Back)
        end
        if dragging then
            dragging = false
            local home = Vector2.new(gui.AbsoluteSize.X / 2, Mini.Top)
            local spot = islandSpot(Vector2.new(Mini.Width, Mini.Height))
            if (spot - home).Magnitude < 28 then
                self._islandAnchor = nil
                placeIsland(Vector2.new(Mini.Width, Mini.Height), 0.35, Enum.EasingStyle.Back)
            end
            local anchor = self._islandAnchor
            self:_writeConfigSettings({ IslandPosition = anchor and { X = anchor.X, Y = anchor.Y } or false })
            hovered = not usingTouch() and pointInside(pointerPosition(), island)
            task.delay(0.1, function()
                if self.Minimized and not dragging then
                    settleMode()
                end
            end)
        end
    end))
    -- Keeps the island on screen when the viewport changes size.
    table.insert(self._connections, gui:GetPropertyChangedSignal("AbsoluteSize"):Connect(function()
        if island.Visible and not dragging then
            placeIsland(Vector2.new(island.Size.X.Offset, island.Size.Y.Offset), 0)
        end
    end))
    hit.MouseButton1Click:Connect(function()
        if dragged then
            dragged = false
            return
        end
        if self.Minimized then
            self:Restore()
        end
    end)
    -- Restore hides the island under the pointer, so MouseLeave never fires.
    self._miniUnhover = function()
        hovered, pressed, activityLive = false, false, false
        dragFrom, dragging = nil, false
        activityToken += 1
        islandScale.Scale = 1
        task.delay(0.15, function()
            if not self.Minimized then
                setMode("Compact", true)
            end
        end)
    end

    self._islandActivity = function(opts)
        if not self.Minimized or not island.Visible then
            return
        end
        local color = NOTIFY_COLORS[opts.Type] or Theme.Accent
        activityTitle.Text = tostring(opts.Title or "Notification")
        activityTitle.TextColor3 = NOTIFY_COLORS[opts.Type] or Theme.Text
        activityBody.Text = tostring(opts.Content or "")
        activityBody.Visible = activityBody.Text ~= ""
        local icon = opts.Icon
        if icon == nil then
            icon = ({ Success = "circle-check", Warning = "triangle-alert", Error = "circle-x" })[opts.Type] or "bell"
        end
        local showIcon = icon ~= false
        activityChip.Visible = showIcon
        activityText.Position = UDim2.fromOffset(showIcon and 46 or 0, 0)
        applyIcon(activityIcon, icon)
        if not activityIcon:GetAttribute("CustomIcon") then
            activityIcon.ImageColor3 = color
        end
        activityChip.BackgroundColor3 = color
        activityLive = true
        activityToken += 1
        local token = activityToken
        task.defer(function()
            if activityToken == token and not hovered and not dragging then
                setMode("Activity")
                islandScale.Scale = 0.96
                tween(islandScale, { Scale = 1 }, 0.4, Enum.EasingStyle.Back)
            end
        end)
        task.delay(math.clamp(tonumber(opts.Duration) or 3, 1.5, 5), function()
            if activityToken == token then
                activityLive = false
                if self.Minimized and not hovered then
                    settleMode()
                end
            end
        end)
    end

    local running = 0
    self:_listen("Render", function()
        if island.Visible and running > 0 and mode == "Compact" then
            local now = os.clock()
            for index, bar in ipairs(bars) do
                local wave = 0.5 + 0.5 * math.sin(now * (6 + index * 1.4) + index * 1.9)
                bar.Size = UDim2.fromOffset(3, math.floor(4 + wave * 11 + 0.5))
            end
        end
    end)

    local pinValue = label({
        AnchorPoint = Vector2.new(1, 0.5),
        Position = UDim2.new(1, -14, 0.5, 0),
        Size = UDim2.new(1, -52, 0, 18),
        TextSize = 13,
        FontFace = Fonts.Bold,
        TextXAlignment = Enum.TextXAlignment.Right,
        RichText = true,
        TextTransparency = 1,
        Parent = compact,
    })
    local bubble = create("TextButton", {
        Name = "IslandBubble",
        AnchorPoint = Vector2.new(0.5, 0.5),
        Size = UDim2.fromOffset(0, 0),
        BackgroundColor3 = Theme.Surface3,
        BorderSizePixel = 0,
        Text = "",
        AutoButtonColor = false,
        Visible = false,
        ZIndex = 30,
        Parent = gui,
    })
    corner(bubble, UDim.new(1, 0))
    local split = create("NumberValue", { Value = 0 })
    local splitOn = false
    local pinnedLead = nil
    local function setSplit(on)
        if on == splitOn then
            return
        end
        splitOn = on
        barsHolder.Parent = on and bubble or meter
        barsHolder.AnchorPoint = on and Vector2.new(0.5, 0.5) or Vector2.new(0, 0)
        barsHolder.Position = on and UDim2.fromScale(0.5, 0.5) or UDim2.new()
        meter.Visible = not on
        tween(pinValue, { TextTransparency = on and 0 or 1 }, 0.2, Enum.EasingStyle.Quad)
        tween(split, { Value = on and 1 or 0 }, on and 0.55 or 0.3, on and Enum.EasingStyle.Back or Enum.EasingStyle.Quint)
        if on then
            islandScale.Scale = 0.96
            tween(islandScale, { Scale = 1 }, 0.45, Enum.EasingStyle.Back)
        end
    end
    self:_listen("Render", function()
        local t = split.Value * merge.Value
        local shown = island.Visible and t > 0.02 and island.GroupTransparency < 0.5
        bubble.Visible = shown
        if not shown then
            return
        end
        local origin = gui.AbsolutePosition
        local pos, size = island.AbsolutePosition - origin, island.AbsoluteSize
        local d = math.min(size.Y, Mini.Height)
        local gap = 6
        local right = pos.X + size.X + gap + d <= gui.AbsoluteSize.X
        local edge = right and pos.X + size.X or pos.X
        local dir = right and 1 or -1
        local inner = edge - dir * d * 0.6
        local outer = edge + dir * (gap + d / 2)
        local x = inner + (outer - inner) * t
        local scale = math.clamp(0.35 + 0.65 * t, 0, 1.2)
        local stretch = math.sin(math.clamp(t, 0, 1) * math.pi)
        bubble.Position = UDim2.fromOffset(x, pos.Y + d / 2)
        bubble.Size = UDim2.fromOffset(d * scale * (1 + 0.4 * stretch), d * scale * (1 - 0.18 * stretch))
        bubble.BackgroundTransparency = island.GroupTransparency
    end)
    bubble.MouseButton1Click:Connect(function()
        if self.Minimized then
            self:Restore()
        end
    end)

    local cardRows = {}
    function self:_refreshMini()
        local count = 0
        for _, element in pairs(Library.Flags) do
            if element._type == "Toggle" and element.Value == true then
                count += 1
            end
        end
        if count ~= running then
            local rising = count > running
            running = count
            countLabel.Text = tostring(count)
            for _, bar in ipairs(bars) do
                tween(bar, { BackgroundColor3 = count > 0 and Theme.Accent or Theme.Muted }, 0.25)
                if count == 0 then
                    tween(bar, { Size = UDim2.fromOffset(3, 3) }, 0.25)
                end
            end
            if rising and mode == "Compact" and island.Visible then
                islandScale.Scale = 1.06
                tween(islandScale, { Scale = 1 }, 0.4, Enum.EasingStyle.Back)
            end
        end
        bigCount.Text = tostring(count)
        local names = {}
        for _, element in pairs(Library.Flags) do
            if element._type == "Toggle" and element.Value == true and element._searchName ~= "" then
                table.insert(names, element._searchName)
            end
        end
        table.sort(names)
        local shownNames = {}
        for index = 1, math.min(#names, 3) do
            shownNames[index] = Library._rich(names[index])
        end
        local extra = #names - #shownNames
        runningNames.Text = '<font color="#8A8A93">Running </font>' .. table.concat(shownNames, '<font color="#8A8A93"> · </font>')
            .. (extra > 0 and string.format('<font color="#8A8A93">  +%d</font>', extra) or "")
        runningNames.Visible = #names > 0
        pinnedLead = nil
        for _, handle in ipairs(self._pinned) do
            if not handle._isShown or handle:_isShown() then
                pinnedLead = handle
                break
            end
        end
        if pinnedLead then
            local text = tostring(pinnedLead:Text() or "")
            -- A status with nothing to show yet doesn't take the pill.
            if text:gsub("<[^>]*>", ""):match("%S") then
                pinValue.Text = text
                local color = pinnedLead._shownColor and pinnedLead._shownColor() or Theme.Text
                -- Too dark to read on the black pill: fall back to text colour.
                local _, _, value = color:ToHSV()
                pinValue.TextColor3 = value < 0.35 and Theme.Text or color
            else
                pinnedLead = nil
            end
        end
        setSplit(running > 0 and pinnedLead ~= nil)
        local barsHere = running > 0 and not splitOn
        idleDot.Visible = not barsHere
        idleLabel.Visible = not barsHere
        countLabel.Visible = barsHere
        barsHolder.Visible = running > 0
        meter.Visible = not splitOn
        miniTitle.Visible = not splitOn
        local key = typeof(self.Keybind) == "EnumItem" and keyName(self.Keybind)
        hint.Text = TOUCH and "Tap to open" or (key and ("Click or press " .. key .. " to open") or "Click to open")

        local list = {}
        for _, handle in ipairs(self._pinned) do
            if (not handle._isShown or handle:_isShown()) and #list < Mini.Pinned then
                table.insert(list, handle)
            end
        end
        rowsHolder.Visible = false
        for index = 1, math.max(#list, #cardRows) do
            local handle = list[index]
            local row = cardRows[index]
            if handle then
                if not row then
                    local frame = create("Frame", {
                        Size = UDim2.new(1, 0, 0, 18),
                        BackgroundTransparency = 1,
                        LayoutOrder = index,
                        Parent = rowsHolder,
                    })
                    row = {
                        Frame = frame,
                        Key = label({
                            Size = UDim2.new(0.5, -4, 1, 0),
                            TextSize = 12,
                            FontFace = Fonts.Regular,
                            TextColor3 = Theme.Muted,
                            RichText = true,
                            Parent = frame,
                        }),
                        Value = label({
                            AnchorPoint = Vector2.new(1, 0),
                            Position = UDim2.fromScale(1, 0),
                            Size = UDim2.new(0.5, -4, 1, 0),
                            TextSize = 12,
                            TextXAlignment = Enum.TextXAlignment.Right,
                            RichText = true,
                            Parent = frame,
                        }),
                    }
                    cardRows[index] = row
                end
                row.Frame.Visible = true
                row.Key.Text = Library._rich(handle.Name)
                row.Value.Text = handle:Text()
                local color = handle._shownColor and handle._shownColor() or Theme.Text
                if row.Value.TextColor3 ~= color then
                    tween(row.Value, { TextColor3 = color }, 0.2)
                end
            elseif row then
                row.Frame.Visible = false
            end
        end
        -- Rows coming and going change the expanded height.
        if mode == "Expanded" and (hovered or self.IslandStyle == "Always Show") then
            task.defer(function()
                if mode == "Expanded" and (hovered or self.IslandStyle == "Always Show") and self.Minimized then
                    local size = shapeFor("Expanded")
                    if math.abs(size.Y - island.Size.Y.Offset) > 1 then
                        setMode("Expanded")
                    end
                end
            end)
        end
    end

    self.MiniBar = island
    self.Island = island
    return island
end

function Window:Minimize()
    if self.Minimized or not self._introDone or not self.Open or self._destroyed then
        return
    end
    self.Minimized = true
    self:_refreshModal()
    self:_refreshCursor()
    self._minimizeGeneration = (self._minimizeGeneration or 0) + 1
    local generation = self._minimizeGeneration
    self:_closePopups()
    self:_refreshToggleButton()
    self:_refreshBackdrop()
    local bar = self:_buildMiniBar()
    self:_refreshMini()
    local gui = self.Gui

    local fromPosition = self.Root.AbsolutePosition - gui.AbsolutePosition
    local fromSize = self.Root.AbsoluteSize
    local fromAlpha = 1
    if self._ghost then
        fromPosition = self._ghost.AbsolutePosition - gui.AbsolutePosition
        fromSize = self._ghost.AbsoluteSize
        fromAlpha = self._ghost.BackgroundTransparency
    end

    local ghost, ghostStroke, ghostCorner = makeGhost(self, fromPosition, fromSize, Library._radius(10))
    ghost.BackgroundTransparency = fromAlpha
    ghostStroke.Transparency = fromAlpha
    tween(ghost, { BackgroundTransparency = 0 }, 0.11, Enum.EasingStyle.Quad)
    tween(ghostStroke, { Transparency = 0 }, 0.11, Enum.EasingStyle.Quad)
    tween(self.Scale, { Scale = (self._fitScale or 1) * 0.985 }, 0.11, Enum.EasingStyle.Quad)
    tween(self.Shadow, { ImageTransparency = 1 }, 0.2)
    bar.Visible = true
    bar.GroupTransparency = 1

    task.delay(0.11, function()
        if self._minimizeGeneration ~= generation or self._destroyed then
            return
        end
        self.Root.Visible = false
        self.Scale.Scale = self._fitScale or 1
        local target, size = self:_miniLand(fromPosition + fromSize / 2)
        morphGhost(ghost, ghostCorner, target, size, math.floor(size.Y / 2), 0.36)
        task.delay(0.3, function()
            if self._minimizeGeneration ~= generation or self._destroyed then
                return
            end
            self._miniScale.Scale = 0.9
            tween(self._miniScale, { Scale = 1 }, 0.3, Enum.EasingStyle.Quint)
            tween(bar, { GroupTransparency = 0 }, 0.18, Enum.EasingStyle.Quad)
            dissolve(self, ghost, ghostStroke, 0.2)
            -- Always Show: once landed as the pill, swell open into the card.
            if self.IslandStyle == "Always Show" then
                task.delay(0.22, function()
                    if self._minimizeGeneration == generation and self._islandSettle then
                        self._islandSettle()
                    end
                end)
            end
        end)
    end)

    task.spawn(function()
        while self.Minimized and self._minimizeGeneration == generation and not self._destroyed do
            self:_refreshMini()
            task.wait(0.5)
        end
    end)
end

function Window:Restore()
    if not self.Minimized or self._destroyed then
        return
    end
    self.Minimized = false
    self:_refreshModal()
    self:_refreshCursor()
    self._minimizeGeneration = (self._minimizeGeneration or 0) + 1
    local generation = self._minimizeGeneration
    self:_refreshToggleButton()
    self:_refreshBackdrop(true)
    local gui = self.Gui
    local bar = self.MiniBar
    local fit = self._fitScale or 1
    local size = Vector2.new(self.Root.Size.X.Offset, self.Root.Size.Y.Offset) * fit
    local centre = self.Root.AbsolutePosition + self.Root.AbsoluteSize / 2 - gui.AbsolutePosition
    local target = centre - size / 2

    local fromPosition, fromSize = target, size
    local fromAlpha = 1
    if self._ghost then
        fromPosition = self._ghost.AbsolutePosition - gui.AbsolutePosition
        fromSize = self._ghost.AbsoluteSize
        fromAlpha = self._ghost.BackgroundTransparency
    elseif bar and bar.Visible then
        fromPosition = self._miniOrb.AbsolutePosition - gui.AbsolutePosition
        fromSize = self._miniOrb.AbsoluteSize
    end
    if bar and bar.Visible then
        if self._miniUnhover then
            self._miniUnhover()
        end
        tween(bar, { GroupTransparency = 1 }, 0.12, Enum.EasingStyle.Quad)
        task.delay(0.12, function()
            if self._minimizeGeneration == generation then
                bar.Visible = false
            end
        end)
    end

    local ghost, ghostStroke, ghostCorner = makeGhost(self, fromPosition, fromSize, math.floor(math.min(fromSize.X, fromSize.Y) / 2))
    ghost.BackgroundTransparency = fromAlpha
    ghostStroke.Transparency = fromAlpha
    tween(ghost, { BackgroundTransparency = 0 }, 0.1, Enum.EasingStyle.Quad)
    tween(ghostStroke, { Transparency = 0 }, 0.1, Enum.EasingStyle.Quad)
    morphGhost(ghost, ghostCorner, target, size, Library._radius(10), 0.4)
    tween(self.Shadow, { ImageTransparency = self._shadowRest }, 0.45)

    task.delay(0.3, function()
        if self._minimizeGeneration ~= generation or self._destroyed then
            return
        end
        self.Scale.Scale = fit
        self.BodyStroke.Transparency = 0
        self.Root.Visible = true
    end)
    task.delay(0.4, function()
        if self._ghost == ghost and self._minimizeGeneration == generation then
            dissolve(self, ghost, ghostStroke, 0.22)
        end
    end)
end

function Window:SetIslandDraggable(enabled)
    self._islandLocked = enabled == false
end

function Window:ResetIslandPosition()
    self._islandAnchor = nil
    if self._islandReset then
        self._islandReset()
    end
    self:_writeConfigSettings({ IslandPosition = false })
end

function Window:SetMinimized(minimized)
    if minimized then
        self:Minimize()
    else
        self:Restore()
    end
end

function Window:Toggle(open)
    if not self._introDone then
        return
    end
    if self.Minimized then
        if open ~= false then
            self:Restore()
        end
        return
    end
    if open == nil then
        open = not self.Open
    end
    if open == false then self:Minimize();return end
    if open == self.Open then
        return
    end
    self.Open = open
    self:_refreshModal()
    self:_refreshCursor()
    self:_refreshToggleButton()
    self:_refreshBackdrop(open)
    self._minimizeGeneration = (self._minimizeGeneration or 0) + 1
    local generation = self._minimizeGeneration
    local gui = self.Gui
    local fit = self._fitScale or 1
    local size = Vector2.new(self.Root.Size.X.Offset, self.Root.Size.Y.Offset) * fit
    local centre = self.Root.AbsolutePosition + self.Root.AbsoluteSize / 2 - gui.AbsolutePosition
    local shrunk = size * 0.94
    local fromPosition, fromSize, fromAlpha
    if self._ghost then
        fromPosition = self._ghost.AbsolutePosition - gui.AbsolutePosition
        fromSize = self._ghost.AbsoluteSize
        fromAlpha = self._ghost.BackgroundTransparency
    end
    if open then
        local ghost, ghostStroke, ghostCorner = makeGhost(self, fromPosition or centre - shrunk / 2, fromSize or shrunk, Library._radius(10))
        ghost.BackgroundTransparency = fromAlpha or 1
        ghostStroke.Transparency = fromAlpha or 1
        tween(ghost, { BackgroundTransparency = 0 }, 0.12, Enum.EasingStyle.Quad)
        tween(ghostStroke, { Transparency = 0 }, 0.12, Enum.EasingStyle.Quad)
        morphGhost(ghost, ghostCorner, centre - size / 2, size, Library._radius(10), 0.3)
        tween(self.Shadow, { ImageTransparency = self._shadowRest }, 0.3)
        -- Shown under the ghost once it covers the spot, then revealed.
        task.delay(0.2, function()
            if self._minimizeGeneration ~= generation or self._destroyed then
                return
            end
            self.Scale.Scale = fit
            self.BodyStroke.Transparency = 0
            self.Root.Visible = true
        end)
        task.delay(0.3, function()
            if self._ghost == ghost and self._minimizeGeneration == generation then
                dissolve(self, ghost, ghostStroke, 0.18)
            end
        end)
    else
        self:_closePopups()
        local position = fromPosition or self.Root.AbsolutePosition - gui.AbsolutePosition
        local current = fromSize or self.Root.AbsoluteSize
        local ghost, ghostStroke, ghostCorner = makeGhost(self, position, current, Library._radius(10))
        ghost.BackgroundTransparency = fromAlpha or 1
        ghostStroke.Transparency = fromAlpha or 1
        tween(ghost, { BackgroundTransparency = 0 }, 0.08, Enum.EasingStyle.Quad)
        tween(ghostStroke, { Transparency = 0 }, 0.08, Enum.EasingStyle.Quad)
        tween(self.Shadow, { ImageTransparency = 1 }, 0.16)
        task.delay(0.08, function()
            if self._minimizeGeneration ~= generation or self._destroyed then
                return
            end
            self.Root.Visible = false
            morphGhost(ghost, ghostCorner, centre - shrunk / 2, shrunk, Library._radius(10), 0.2)
            dissolve(self, ghost, ghostStroke, 0.16)
        end)
    end
end

function Window:SetKeepOnScreen(enabled)
    self.KeepOnScreen = enabled ~= false
    if self.KeepOnScreen then
        self:_clampToScreen()
    end
end

function Window:_refreshModal()
    if not self._modal then
        return
    end
    self._modal.Modal = self.UnlockMouseWhileOpen == true
        and self.Open == true
        and self._introDone == true
        and not self.Minimized
end

function Window:SetUnlockMouseWhileOpen(enabled)
    self.UnlockMouseWhileOpen = enabled ~= false
    self:_refreshModal()
end

function Window:SetShowCustomCursor(enabled)
    self.ShowCustomCursor = enabled ~= false
    local toggle = self._interfaceCursorToggle
    if toggle and not toggle._destroyed then
        toggle:Set(self.ShowCustomCursor, true)
    end
    self:_refreshCursor()
end

function Window:SetAutoTranslate(enabled)
    enabled = enabled ~= false
    Library.AutoTranslate = enabled
    for _, descendant in ipairs(self.Gui:GetDescendants()) do
        if descendant:IsA("TextLabel") or descendant:IsA("TextButton") or descendant:IsA("TextBox") then
            pcall(function()
                descendant.AutoLocalize = enabled
            end)
        end
    end
end

function Window:_refreshCursor()
    if not self._cursor then
        return
    end
    local active = not TOUCH and self._introDone and self.Open and not self.Minimized and not self._destroyed
    if active and not self._cursorBound then
        self._cursorBound = true
        self._originalMouseIconEnabled = UserInputService.MouseIconEnabled
        pcall(function()
            RunService:UnbindFromRenderStep(self._cursorBinding)
        end)
        RunService:BindToRenderStep(self._cursorBinding, Enum.RenderPriority.Last.Value, function()
            UserInputService.MouseIconEnabled = not self.ShowCustomCursor
            local pointer = pointerPosition() - self.Gui.AbsolutePosition
            self._cursor.Position = UDim2.fromOffset(pointer.X, pointer.Y)
            self._cursor.Visible = self.ShowCustomCursor
            if self._destroyed or not (self._introDone and self.Open and not self.Minimized and self.Gui.Parent) then
                self:_restoreMouseIcon()
            end
        end)
    elseif not active and self._cursorBound then
        self:_restoreMouseIcon()
    end
end

function Window:_restoreMouseIcon()
    self._cursorBound = false
    pcall(function()
        RunService:UnbindFromRenderStep(self._cursorBinding)
        RunService.RenderStepped:Wait()
    end)
    if self._originalMouseIconEnabled ~= nil then
        UserInputService.MouseIconEnabled = self._originalMouseIconEnabled
    end
    if self._cursor then
        self._cursor.Visible = false
    end
end

function Window:SetKeybind(key)
    self.Keybind = Keybinds.Resolve(key)
    if self._keyChipLabel then
        self._keyChipLabel.Text = keyName(self.Keybind)
    end
    local bind = self._interfaceKeybind
    if bind and not bind._destroyed and bind:Get() ~= self.Keybind then
        bind:Set(self.Keybind, true)
    end
end

function Window:SetKeybindMenu(enabled)
    local menu = self.KeybindMenu
    if menu and not menu.Destroyed then
        menu:SetVisible(enabled)
    end
end

function Window:ToggleKeybindMenu()
    local menu = self.KeybindMenu
    if menu and not menu.Destroyed then
        menu:ToggleVisible()
    end
end

function Window:Notify(opts)
    opts = normalize(opts, { Text = "Content", Message = "Content", Image = "Icon" })
    if self.Minimized and self._islandActivity then
        self._islandActivity(opts)
    end
    local duration = opts.Duration or 4
    local titleColor = NOTIFY_COLORS[opts.Type] or Theme.Text

    self._notifyOrder = self._notifyOrder + 1
    local outer = create("Frame", {
        Size = UDim2.new(1, 0, 0, 0),
        BackgroundTransparency = 1,
        LayoutOrder = self._notifyOrder,
        Parent = self.NotifyHolder,
    })
    local slide = create("Frame", {
        Position = UDim2.fromOffset(320, 0),
        Size = UDim2.new(1, 0, 0, 0),
        AutomaticSize = Enum.AutomaticSize.Y,
        BackgroundTransparency = 1,
        Parent = outer,
    })
    local shadow = create("ImageLabel", {
        Position = UDim2.fromOffset(-20, -20),
        Size = UDim2.new(1, 40, 1, 40),
        BackgroundTransparency = 1,
        Image = Assets.Shadow,
        ImageColor3 = Color3.new(0, 0, 0),
        ImageTransparency = 1,
        ScaleType = Enum.ScaleType.Slice,
        SliceCenter = Rect.new(49, 49, 450, 450),
        ZIndex = 0,
        Parent = slide,
    })
    local toast = create("CanvasGroup", {
        Size = UDim2.new(1, 0, 0, 0),
        AutomaticSize = Enum.AutomaticSize.Y,
        BackgroundColor3 = Theme.Background,
        BorderSizePixel = 0,
        GroupTransparency = 1,
        Parent = slide,
    })
    corner(toast, UDim.new(0, 10))
    local toastStroke = stroke(toast, Theme.Stroke)
    edgeHighlight(toast)
    glow(toast, UDim2.fromOffset(260, 120), UDim2.new(1, -10, 0, -10), 0.86, 90)

    local inner = create("Frame", {
        Size = UDim2.new(1, 0, 0, 0),
        AutomaticSize = Enum.AutomaticSize.Y,
        BackgroundTransparency = 1,
        Parent = toast,
    })
    padding(inner, 16, 16, 14, 24)

    local titleOffset = 0
    if opts.Icon then
        glowIcon(inner, opts.Icon, titleColor == Theme.Text and Theme.Accent or titleColor, UDim2.new(0, 0, 0, 8))
        titleOffset = 24
    end
    label({
        Position = UDim2.fromOffset(titleOffset, 0),
        Size = UDim2.new(1, -28 - titleOffset, 0, 16),
        Text = opts.Title or "Notification",
        TextSize = 14,
        TextColor3 = titleColor,
        Parent = inner,
    })
    local closeButton = create("TextButton", {
        AnchorPoint = Vector2.new(1, 0),
        Position = UDim2.new(1, 6, 0, -5),
        Size = UDim2.fromOffset(24, 24),
        BackgroundTransparency = 1,
        Text = "×",
        TextColor3 = Theme.Muted,
        TextSize = 22,
        FontFace = Fonts.Bold,
        AutoButtonColor = false,
        Parent = inner,
    })
    closeButton.MouseEnter:Connect(function()
        tween(closeButton, { TextColor3 = Theme.Text }, 0.15)
    end)
    closeButton.MouseLeave:Connect(function()
        tween(closeButton, { TextColor3 = Theme.Muted }, 0.2)
    end)
    if opts.Content then
        label({
            Position = UDim2.fromOffset(titleOffset, 21),
            Size = UDim2.new(1, -titleOffset, 0, 0),
            AutomaticSize = Enum.AutomaticSize.Y,
            Text = opts.Content,
            TextSize = 13,
            FontFace = Fonts.Regular,
            TextColor3 = Theme.Muted,
            TextWrapped = true,
            TextTruncate = Enum.TextTruncate.None,
            TextYAlignment = Enum.TextYAlignment.Top,
            Parent = inner,
        })
    end

    local track = create("Frame", {
        AnchorPoint = Vector2.new(0, 1),
        Position = UDim2.new(0, 16, 1, -8),
        Size = UDim2.new(1, -32, 0, 3),
        BackgroundColor3 = Theme.Surface3,
        BorderSizePixel = 0,
        Parent = toast,
    })
    corner(track, UDim.new(1, 0))
    local progress = create("Frame", {
        Size = UDim2.fromScale(1, 1),
        BackgroundColor3 = Theme.Accent,
        BorderSizePixel = 0,
        Parent = track,
    })
    corner(progress, UDim.new(1, 0))

    task.defer(function()
        if outer.Parent then
            tween(outer, { Size = UDim2.new(1, 0, 0, toast.AbsoluteSize.Y) }, 0.3, Enum.EasingStyle.Quint)
        end
    end)
    tween(slide, { Position = UDim2.fromOffset(0, 0) }, 0.5, Enum.EasingStyle.Back)
    tween(toast, { GroupTransparency = 0 }, 0.3)
    tween(shadow, { ImageTransparency = 0.6 }, 0.4)
    tween(progress, { Size = UDim2.fromScale(0, 1) }, duration, Enum.EasingStyle.Linear)

    local dismissed = false
    local function dismiss()
        if dismissed then
            return
        end
        dismissed = true
        for index, entry in ipairs(self._toasts) do
            if entry == dismiss then
                table.remove(self._toasts, index)
                break
            end
        end
        tween(slide, { Position = UDim2.fromOffset(320, 0) }, 0.3, Enum.EasingStyle.Quint)
        tween(toast, { GroupTransparency = 1 }, 0.2)
        tween(toastStroke, { Transparency = 1 }, 0.15)
        tween(shadow, { ImageTransparency = 1 }, 0.2)
        task.delay(0.22, function()
            outer.ClipsDescendants = true
            tween(outer, { Size = UDim2.new(1, 0, 0, -4) }, 0.22, Enum.EasingStyle.Quint)
            task.delay(0.24, function()
                outer:Destroy()
            end)
        end)
    end

    task.delay(duration, dismiss)
    closeButton.MouseButton1Click:Connect(dismiss)

    table.insert(self._toasts, dismiss)
    while #self._toasts > self.MaxNotifications do
        local oldest = table.remove(self._toasts, 1)
        oldest()
    end

    return { Dismiss = dismiss }
end

function Window:Destroy()
    if self._destroyed then
        return
    end
    self._destroyed = true
    if self._cursorBound then
        self:_restoreMouseIcon()
    end
    for index, entry in ipairs(Library.Windows) do
        if entry == self then
            table.remove(Library.Windows, index)
            break
        end
    end
    for _, connection in ipairs(self._connections) do
        pcall(function()
            connection:Disconnect()
        end)
    end
    self._connections = {}
    self._inputListeners = { Began = {}, Changed = {}, Ended = {}, Render = {} }
    self._frameSteps = {}

    local gui = self.Gui
    local removed = false
    local function remove()
        if removed then
            return
        end
        removed = true
        if self.KeybindMenu then
            self.KeybindMenu:Destroy()
        end
        for index = #self._islands, 1, -1 do
            local island = self._islands[index]
            if island and not island._destroyed then
                island:Destroy()
            end
        end
        if not pcall(gui.Destroy, gui) then
            pcall(function()
                gui.Enabled = false
            end)
        end
    end
    local ok, err = pcall(function()
        if self._dialog then
            self._dialog.Close()
        end
        self:_closePopups()
        local fit = self._fitScale or 1
        tween(self.Scale, { Scale = fit * 0.92 }, 0.22, Enum.EasingStyle.Quint)
        self:_fade(1, 0.2)
        tween(self.BodyStroke, { Transparency = 1 }, 0.12)
        tween(self.Shadow, { ImageTransparency = 1 }, 0.2)
        if self.MiniBar and self.MiniBar.Visible then
            tween(self.MiniBar, { GroupTransparency = 1 }, 0.18)
        end
        if self._backdrop then
            -- Frame steps are already cut, so the weather stops where it is.
            self._weatherField.Visible = false
            tween(self._backdropTintFrame, { BackgroundTransparency = 1 }, 0.2)
            tween(self._backdropHeat, { BackgroundTransparency = 1 }, 0.2)
        end
        for _, button in ipairs({ self.ToggleButton, self.OpenButton }) do
            if typeof(button) == "Instance" and button:IsA("GuiObject") then
                tween(button, { Size = UDim2.fromOffset(0, 0) }, 0.2, Enum.EasingStyle.Quint)
            end
        end
    end)
    if not ok then
        warn("[Aster UI] unload animation failed, removing the window directly: " .. tostring(err))
        remove()
        return
    end
    task.delay(0.24, remove)
end

Window.Unload = Window.Destroy

function Library:Destroy()
    if Library._trustedConnection then Library._trustedConnection:Disconnect(); Library._trustedConnection=nil end
    if themeDriver then themeDriver:Disconnect();themeDriver=nil end
    for index = #Library._draggableLabels, 1, -1 do
        local entry = Library._draggableLabels[index]
        if entry then
            pcall(function()
                entry:Destroy()
            end)
        end
    end
    for index = #Library.Windows, 1, -1 do
        local window = Library.Windows[index]
        if window then
            window:Destroy()
        end
    end
end

Library.Unload = Library.Destroy

local getIdentity = getthreadidentity or getidentity or get_thread_identity or (syn and syn.get_thread_identity)
local setIdentity = setthreadidentity or setidentity or set_thread_identity or (syn and syn.set_thread_identity)
local loadIdentity = nil
if getIdentity then
    local ok, identity = pcall(getIdentity)
    if ok and type(identity) == "number" then
        loadIdentity = identity
    end
end

local function threadLowered()
    local window = Library.Windows[#Library.Windows]
    local probe = window and window.Gui
    if typeof(probe) ~= "Instance" then
        return false
    end
    return not pcall(function()
        return probe.Name
    end)
end

local trustedQueue = {}
Library._trustedConnection = RunService.Heartbeat:Connect(function()
    if #trustedQueue == 0 then
        return
    end
    local queue = trustedQueue
    trustedQueue = {}
    for _, job in ipairs(queue) do
        job()
    end
end)

local function runTrusted(fn, ...)
    local args = table.pack(...)
    local result = nil
    table.insert(trustedQueue, function()
        result = table.pack(pcall(fn, table.unpack(args, 1, args.n)))
    end)
    while result == nil do
        task.wait()
    end
    if not result[1] then
        error(result[2], 0)
    end
    return table.unpack(result, 2, result.n)
end

local guardedObjects = setmetatable({}, { __mode = "k" })
local guardObject

local function guarded(fn)
    return function(...)
        if threadLowered() then
            if setIdentity then
                pcall(setIdentity, loadIdentity or 8)
            end
            if threadLowered() then
                return guardObject(runTrusted(fn, ...))
            end
        end
        return guardObject(fn(...))
    end
end

function guardObject(...)
    for index = 1, select("#", ...) do
        local object = select(index, ...)
        if type(object) == "table" and not guardedObjects[object] then
            local meta = getmetatable(object)
            if meta ~= Window and meta ~= Tab then
                guardedObjects[object] = true
                for key, value in pairs(object) do
                    if type(key) == "string" and type(value) == "function" and key:sub(1, 1) ~= "_" then
                        object[key] = guarded(value)
                    elseif type(key) == "number" and type(value) == "table" then
                        guardObject(value)
                    end
                end
            end
        end
    end
    return ...
end

for _, class in ipairs({ Library, Window, Tab }) do
    for key, value in pairs(class) do
        if type(key) == "string" and type(value) == "function" and key:sub(1, 1) ~= "_" then
            class[key] = guarded(value)
        end
    end
end

return Library

]======],"@sharkwow-aster"))()
local mount=assert(loadstring([======[
return function(S, Library)
    local A=assert(S.Advanced,"stand out modules unavailable")
    assert(#A.Order>=66,"stand out startup incomplete; original UI preserved")
    local player=game.Players.LocalPlayer
    local old=S.AsterUI
    if old then old:Destroy() end
    local palette={Background=Color3.fromRGB(9,17,24),Surface=Color3.fromRGB(13,23,32),Surface2=Color3.fromRGB(22,30,40),Surface3=Color3.fromRGB(30,30,51),Stroke=Color3.fromRGB(41,60,74),StrokeHover=Color3.fromRGB(65,151,255),Accent=Color3.fromRGB(0,240,255),AccentDark=Color3.fromRGB(0,97,109),Text=Color3.fromRGB(243,247,255),Muted=Color3.fromRGB(166,177,204),Success=Color3.fromRGB(81,236,177),Warning=Color3.fromRGB(255,190,80),Error=Color3.fromRGB(255,91,128)}
    Library.ThemePresets={SHARKWOW=palette}
    Library.ReducedMotion=S.Appearance and S.Appearance.ReducedMotion or false
    local W=Library:CreateWindow({Name="SHARKWOW_Aster_StandOut",Title="SHARKWOW HUB",Subtitle="STAND OUT",LoadingTitle="SHARKWOW HUB",LoadingSubtitle="STAND OUT",Icon="sharkwow",Theme="SHARKWOW",DefaultTheme="SHARKWOW",Parent=player.PlayerGui,ToggleUIKeybind="RightShift",ToggleButton=false,OpenButton=(S.Device and S.Device.Touch) and {Title="SHARKWOW HUB",Icon="sharkwow"} or false,IslandDraggable=true,AdaptiveSize=true,AlwaysOnTop=true,AutoTranslate=false,ShowCustomCursor=false,UnlockMouseWhileOpen=true,Weather="None",Home={Stats={"FPS","Ping","Game","Players","ServerAge","Session","Executor"}},ConfigurationSaving={FolderName="SHARKWOW/StandOut/"..player.UserId,FileName="interface"}})
    local self={Window=W,Library=Library,Alive=true,Controls={},Fields={},Connections={},Version="aster-7-selected",Palette=palette}
    S.AsterUI=self
    -- Keep the full-screen input shield below this window's controls.
    W.Gui.DisplayOrder=10000
    local refreshModal=W._refreshModal
    W._refreshModal=function(window)
        refreshModal(window)
        local shown=window.Open==true and window._introDone==true and not window.Minimized
        window._modal.Name="SHARKWOW_InputShield"
        window._modal.Size=UDim2.fromScale(1,1)
        window._modal.Active=shown
        window._modal.Visible=shown
        window._modal.Modal=shown
        window._modal.AutoButtonColor=false
    end
    W:_refreshModal()
    S.InputShieldVersion=1
    local ready=false
    if A.Options.JoinPlayer then A.Option("JoinPlayer",A.Options.JoinPlayer.UserId~=nil and "UserId"or"Username","")end
    local function safe(fn,...)
        if not ready or not self.Alive or not A.Current() then return end
        local ok,err=pcall(fn,...)
        if not ok then A.Error("aster ui",err);W:Notify({Title="SHARKWOW HUB",Content=tostring(err),Type="Error"}) end
    end
    local tabs={}
    local names={farm="Farm",craft="Craft",quests="Quests",combat="Combat",move="Travel",visuals="Display",utility="Settings",notify="Notifications",raid="Raids"}
    local icons={farm="sprout",craft="hammer",quests="scroll",combat="swords",move="navigation",visuals="eye",utility="settings",notify="bell",raid="swords"}
    for _,key in ipairs({"farm","combat","raid","move","visuals","utility"}) do tabs[key]=W:Tab({Name=names[key],Icon=icons[key]}) end
    local category={Webhook="farm",AutoFarm="combat",AutoRaid="raid",WarpPlayer="move",JoinPlayer="move"}
    local pages,main,advanced={},{},{}
    for key,tab in pairs(tabs)do
        main[key]=tab:SubTab({Name="Controls",Icon="toggle-right"})
        advanced[key]=tab:SubTab({Name="Options",Icon="sliders-horizontal"})
    end
    local visible={SessionRecovery=true,NoFall=true,DeleteNormalRokaka=true,Webhook=true,WaitForArrow=false,ServerTransfers=true,AvoidShutdown=true,EmergencyHop=true,AutoLowPopulation=true,Servers=true,AntiAFK=true,AutoFarm=true,AutoRaid=true,WarpPlayer=true,JoinPlayer=true,ItemESP=true,PlayerESP=true,MobESP=true,StandESP=true,NPCESP=true,ObjectiveESP=true}
    table.clear(A.Binds)
    A.Save()
    local items=main.farm
    if A.Features.FarmAndCraft then
        self.Controls.FarmAndCraft=items:Toggle({Name="Start All Farming + Crafting",Flag="workflow.enabled",Desc="Start item pickup, materials, arrow crafting and gardening together. Position is automatic. Turn off to stop the combined workflow.",Default=A.Get("FarmAndCraft"),Callback=function(v)
            safe(function()local ok,err=A.Set("FarmAndCraft",v);assert(ok,err)end)
        end})
    end
    local itemNames={"Arrow","Lucky Arrow","Rokaka / seeds","Opal Roka","Stone Mask","Arrow Part"}
    local selected={}
    for _,name in ipairs(itemNames)do if S.ItemFarmSelection[name]then selected[#selected+1]=name end end
    self.ItemSelection=items:Dropdown({Name="Items to collect",Options=itemNames,Multi=true,Default=selected,Callback=function(values)
        safe(function()local chosen={};for _,name in ipairs(values)do chosen[name]=true end;S.SetFarmSelection(chosen)end)
    end})
    items:Paragraph({Name="Farm workflow",Content="One switch handles items, arrow crafting, materials and gardening. Waits at one hiding spot between pickups. Money and meteor collection stay off."})
    for _,id in ipairs(A.Order) do
        local f=A.Features[id]
        if visible[id] and not f.Hidden then
            local group=category[id]or f.Group;if not tabs[group]then group="utility"end
            local primary=main[group]
            local page=(id=="Webhook"or id=="JoinPlayer"or id=="AutoFarm"or id=="WarpPlayer")and primary or advanced[group]:Groupbox({Name=f.Name,Icon=icons[group]or"circle",Collapsed=true,PopOut=false})
            pages[id]=page
            if id=="JoinPlayer"then
                primary:Section({Name="Follow to another server"})
                page:Input({Name="Username or user ID",Default="",Placeholder="Username or numeric ID",Callback=function(value)safe(A.Option,id,"UserId",value)end})
                self.Controls[id]=primary:Button({Name="Follow player",Callback=function()safe(f.Action)end})
                primary:Label({Text="Enter a username or user ID",Update=function()return tostring(S.JoinPlayerStatus or "Enter a username or user ID")end,UpdateRate=.5})
            elseif f.Action then
                self.Controls[id]=primary:Button({Name=f.Name,Tooltip=f.Description,Callback=function()safe(f.Action)end})
            elseif f.Locked then
                self.Controls[id]=primary:Label({Text=f.Name.." — always enabled"})
            else
                self.Controls[id]=primary:Toggle({Name=f.Name,Tooltip=f.Description,Default=A.Get(id),Flag="feature."..id,Callback=function(v)safe(function()local ok,err=A.Set(id,v);assert(ok,err)end)end})
            end
            self.Fields[id]={}
            for _,field in ipairs(id=="JoinPlayer" and {} or f.Fields) do
                if id=="AutoFarm" and field.Key=="Targets" then
                    local chosen={};for name in tostring(A.Options.AutoFarm.Targets):gmatch("[^,]+")do table.insert(chosen,name:match("^%s*(.-)%s*$"))end
                    local choices=A.Mobs();for _,name in ipairs(chosen)do if not table.find(choices,name)then table.insert(choices,name)end end
                    local dropdown=page:Dropdown({Name="Mobs to attack",Options=choices,Multi=true,Default=chosen,Callback=function(values)safe(A.Option,"AutoFarm","Targets",table.concat(values,", "))end})
                    page:Button({Name="Refresh mob list",Callback=function()safe(function()dropdown:Refresh(A.Mobs(),true,true)end)end})
                    continue
                end
                local opts={Name=field.Name,Default=A.Options[id][field.Key],Flag=id.."."..field.Key,Callback=function(v)safe(A.Option,id,field.Key,v)end}
                if id=="Webhook" and field.Key=="URL" then opts.Flag=nil end
                if id=="JoinPlayer"then opts.Default="";opts.Placeholder="Enter numeric Roblox user ID";opts.Flag=nil end
                local widget
                if type(field.Default)=="boolean" then widget=page:Toggle(opts)
                elseif field.Choices then opts.Options=field.Choices;widget=page:Dropdown(opts)
                elseif type(field.Default)=="number" and field.Min and field.Max then
                    opts.Min=field.Min;opts.Max=field.Max;opts.Step=field.Step or (field.Default%1~=0 and .1 or 1);widget=page:Slider(opts)
                else
                    opts.Numeric=type(field.Default)=="number"
                    opts.Callback=function(v)safe(A.Option,id,field.Key,opts.Numeric and assert(tonumber(v),"enter a number") or v)end
                    widget=page:Input(opts)
                    local originalSet=widget.Set
                    widget.Set=function(control,v,silent)originalSet(control,v);if not silent then opts.Callback(v)end end
                end
                self.Fields[id][field.Key]=widget
            end

            if id=="ItemFarm" then page:Button({Name="Use currently loaded items",Callback=function()safe(A.Option,id,"Names",table.concat(A.WorldItemNames(),", "))end}) end
            for _,action in ipairs(id=="JoinPlayer" and {} or f.Actions or {}) do page:Button({Name=action.Name,Callback=function()safe(action.Run)end}) end
            if f.ListActions then
                local buttons={}
                local function refresh()
                    for _,b in ipairs(buttons) do b:Destroy() end;table.clear(buttons)
                    for _,action in ipairs(f.ListActions()) do buttons[#buttons+1]=page:Button({Name=action.Name,Callback=function()safe(action.Run)end}) end
                end
                page:Button({Name="Refresh players",Callback=function()safe(refresh)end});refresh()
            end

        end
    end
    local settings=tabs.utility:SubTab({Name="Interface",Icon="sliders-horizontal"})
    settings:Toggle({Name="Reduced motion",Default=Library.ReducedMotion,Callback=function(v)Library.ReducedMotion=v;if S.Appearance then S.Appearance.ReducedMotion=v end end})
    settings:Button({Name="Minimize to island",Callback=function()W:Minimize()end})
    settings:Button({Name="Reset island position",Callback=function()W:ResetIslandPosition()end})
    settings:Button({Name="Unload hub",Callback=function()safe(S.Unload)end})
    local status=tabs.utility:SubTab({Name="Status",Icon="activity"})
    status:Label({Text="Session",Update=function()return "Server age: "..tostring(S.ServerAgeSeconds).."s | "..tostring(S.ShutdownStatus)end,UpdateRate=2})
    status:Label({Text="Farm",Update=function()return tostring(S.AutoStatus or A.Status).." | "..tostring(S.AntiAFK)end,UpdateRate=1})
    local inv=tabs.farm:SubTab({Name="Inventory",Icon="package"})
    for _,name in ipairs({"Mysterious Arrow","Lucky Arrow","Bizarre Arrow","Stone Mask","Arrow Part","Other"}) do
        inv:Label({Text=name,Update=function()local report=S.InventoryReport;local counts=report and report.Counts or{};return name..": "..tostring(name=="Other"and report and report.Other or counts[name]or 0)end,UpdateRate=2})
    end
    status:Paragraph({Name="Server ID",Content=game.JobId})
    status:Button({Name="Copy server ID",Callback=function()safe(A.CopyJobId)end})
    for _,name in ipairs({"SHARKWOW_ServerInfo"})do
        local report=player.PlayerGui:FindFirstChild(name)
        if report then report.Enabled=false;self.Connections[#self.Connections+1]=report:GetPropertyChangedSignal("Enabled"):Connect(function()if self.Alive and report.Enabled then report.Enabled=false end end)end
    end
    local arrowReport=player.PlayerGui:FindFirstChild("SHARKWOW_ArrowReport")
    if arrowReport then
        local itemColors={
            ["Mysterious Arrow"]=Color3.fromRGB(80,205,255),
            ["Lucky Arrow"]=Color3.fromRGB(255,213,79),
            ["Bizarre Arrow"]=Color3.fromRGB(206,153,255),
            ["Arrow Part"]=Color3.fromRGB(255,164,101),
            ["Stone Mask"]=Color3.fromRGB(104,229,173),
            Other=Color3.fromRGB(192,204,221),
        }
        for _,node in ipairs(arrowReport:GetDescendants())do
            if node:IsA("TextLabel")or node:IsA("TextButton")then
                node.TextSize=math.max(16,node.TextSize)
                node.TextColor3=itemColors[node.Parent.Name]or(node.Name=="Count"and palette.Text or palette.Accent)
                if node.Name=="Brand"then node.Text="SHARKWOW HUB";node.Size=UDim2.new(1,-24,0,18)end
                if node.Name=="Title"then node.Position=UDim2.fromOffset(12,23);node.Text="DROPPABLE ITEMS"end
                if node.Name=="Status"then node.TextColor3=palette.Muted;node.Size=UDim2.new(1,-24,0,19);node.Position=UDim2.new(0,12,1,-21)end
            elseif node:IsA("Frame")then
                node.BackgroundColor3=node.Name=="Report"and palette.Background or palette.Surface2
            elseif node:IsA("UIGradient")then
                node.Color=ColorSequence.new(palette.Accent,palette.StrokeHover)
            end
        end
        local rows=arrowReport:FindFirstChild("Counts",true)
        if rows then for name,color in pairs(itemColors)do
            local row=rows:FindFirstChild(name)
            if row then
                local stripe=row:FindFirstChild("ItemAccent")or Instance.new("Frame")
                stripe.Name="ItemAccent";stripe.BorderSizePixel=0
                stripe.BackgroundColor3=color;stripe.Size=UDim2.new(0,3,1,-10)
                stripe.Position=UDim2.fromOffset(0,5);stripe.Parent=row
            end
        end end
        if not S.AsterReportRestored then
            S.AsterReportRestored=true
            A.Set("InventoryReport",true)
        end
        self.ArrowReport=arrowReport
    end
    local legacy=player.PlayerGui:FindFirstChild("MT_ArrowRokakaFinder")
    local panel=legacy and legacy:FindFirstChild("Panel")
    local dock=legacy and legacy:FindFirstChild("SharkDock")
    local oldSet=S.SetWindowVisible
    if oldSet then oldSet(false) end
    if S.Hybrid then S.Hybrid:Destroy();S.Hybrid=nil end
    if panel then panel.Visible=false end
    if dock then dock.Visible=false end
    -- Old closures still capture this function, so disconnect only its input binding.
    if type(getconnections)=="function" and debug.getupvalues then
        for _,c in ipairs(getconnections(game:GetService("UserInputService").InputBegan)) do
            if c.Function then
                local ok,values=pcall(debug.getupvalues,c.Function)
                if ok then for _,v in pairs(values) do if v==oldSet then c:Disconnect();break end end end
            end
        end
    end
    S.SetWindowVisible=function(v)if v then if W.Minimized then W:Restore()else W:Toggle(true)end else W:Minimize()end end
    local priorRefresh=A.Refresh
    A.Refresh=function()
        if not self.Alive then return end
        local values={}
        for _,name in ipairs(itemNames)do if S.ItemFarmSelection[name]then values[#values+1]=name end end
        local fingerprint=table.concat(values,"|")
        if self.SelectionFingerprint~=fingerprint then self.SelectionFingerprint=fingerprint;self.ItemSelection:Set(values,true)end
        for id,c in pairs(self.Controls)do local f=A.Features[id];if not f.Action and not f.Locked then c:Set(A.Get(id),true)end end
        local focused=game:GetService("UserInputService"):GetFocusedTextBox()
        for id,fields in pairs(self.Fields)do for key,c in pairs(fields)do local value=A.Options[id][key];if not focused and c:Get()~=value then c:Set(value,true)end end end
    end
    local oldOpen=A.OpenFeature
    A.OpenFeature=function(id)local p=pages[id];if p then S.SetWindowVisible(true);if p._groupbox then W:SelectTab(p.Parent.Parent);p.Parent.Parent:SelectSubTab(p.Parent);p:SetCollapsed(false)else W:SelectTab(p.Parent);p.Parent:SelectSubTab(p)end;return true end return false end
    function self:Destroy()
        if not self.Alive then return end
        self.Alive=false
        if self.Cleanup then local index=table.find(A.Cleanups,self.Cleanup);if index then table.remove(A.Cleanups,index)end end
        if self.Worker then pcall(task.cancel,self.Worker)end
        for _,c in ipairs(self.Connections)do c:Disconnect()end
        Library:Destroy()
        if S.AsterUI==self then S.AsterUI=nil;S.SetWindowVisible=oldSet;A.Refresh=priorRefresh;A.OpenFeature=oldOpen end
    end
    if A.Workers["module ui"] then pcall(task.cancel,A.Workers["module ui"]);A.Workers["module ui"]=nil end
    self.Cleanup=function()self:Destroy()end
    A.Cleanups[#A.Cleanups+1]=self.Cleanup
    ready=true
    A.Errors["aster ui"]=nil
    W:SelectTab(tabs.farm);tabs.farm:SelectSubTab(main.farm)
    self.Worker=task.spawn(function()while self.Alive and A.Current()do A.Refresh();if panel then panel.Visible=false end;if dock then dock.Visible=false end;task.wait(.5)end end)
    return self
end

]======],"@sharkwow-aster-standout"))()
local ok,err=pcall(mount,state,aster)
if not ok then aster:Destroy();state.AsterMountError=tostring(err);warn(err)end
end
state.StartGarden = function()
local env = getgenv()
assert(game.PlaceId == 128828638194450, "wrong game")
local hub = assert(env.MT_ArrowRokakaFinder, "hub unavailable")
local player = game.Players.LocalPlayer
local remote = game.ReplicatedStorage.Remotes.Gardening
local controller = require(player.PlayerScripts.Core.Gardening).GrowingController
local existing = env.MT_RokakaGardenRun
if existing and existing.Alive then existing.Stop() end
local run = {Alive = true, Version = "0.1.6", Status = "waiting for rokaka seed", Started = existing and existing.Started or os.time(), Errors = {}, Operations = 0}
if existing then
    run.PlantedAt, run.SeedGrade, run.PotId = existing.PlantedAt, existing.SeedGrade, existing.PotId
end
run.Hub = hub
env.MT_RokakaGardenRun = run
local function current()
    return run.Alive and env.MT_RokakaGardenRun == run and env.MT_ArrowRokakaFinder == hub and hub.Alive
end
local function inventory()
    return game.HttpService:JSONDecode(player.Data.Stats.Inventory.Value)
end
local function fruits()
    local total, names = 0, {}
    for _, item in ipairs(inventory()) do
        local name = type(item) == "table" and item.Name or item
        if type(name) == "string" and name:lower():find("roka", 1, true) and not name:lower():find("seed", 1, true) then
            local amount = type(item) == "table" and (item.Amount or 1) or 1
            total += amount
            names[name] = (names[name] or 0) + amount
        end
    end
    return total, names
end
run.BeforeFruit = existing and not existing.Completed and existing.BeforeFruit or fruits()
local function seed()
    local items=inventory()
    for _,name in ipairs({"Opal Roka Seed","Rokaka Seed"}) do
        for _,item in ipairs(items) do
            if type(item)=="table" and item.Name==name and (item.Amount or 1)>0
                and (not hub.ShouldCollectRokaka or hub.ShouldCollectRokaka(name)) then
                run.NextSeed=name
                return item
            end
        end
    end
    run.NextSeed=nil
end
run.PreferredSeed="Opal Roka Seed"
local function ownedPot()
    local best,bestRank=nil,math.huge
    for _, pot in ipairs(workspace.Game.Gardening.Pots:GetChildren()) do
        if pot:GetAttribute("OwnerUserId") == player.UserId then
            local stage=pot:GetAttribute("Stage")
            local rank=stage=="Ready" and 0 or stage=="DirtReady" and 2 or stage=="Empty" and 3 or 4
            if stage=="Ready" and pot:GetAttribute("Contains")~="Opal Roka Seed" then rank=1 end
            if rank<bestRank then best,bestRank=pot,rank end
        end
    end
    return best
end
local function active()
    for _, value in pairs(debug.getupvalues(controller.Update)) do
        if type(value) == "table" and value.Token and value.Payload then return value end
    end
end
local function nativeSend()
    for _, value in pairs(debug.getupvalues(controller.start)) do
        if type(value) == "function" and debug.info(value, "n") == "send" then return value end
    end
    error("native gardening input unavailable")
end
local function waitUntil(predicate, seconds)
    local deadline = os.clock() + seconds
    repeat
        assert(current(), "garden operation cancelled")
        if predicate() then return true end
        task.wait(0.1)
    until os.clock() >= deadline
    return predicate()
end
local function completeMinigame(kind, pot)
    assert(waitUntil(function() local a = active() return a and not a.Closing and a.Payload.Kind == kind end, 5), "gardening minigame did not open")
    local a = active()
    assert(a.Payload.Model == pot, "unexpected gardening target")
    local send = nativeSend()
    local deadline = os.clock() + 20
    while current() and active() == a and not a.Closing and os.clock() < deadline do
        local phase = a.Payload.Phase
        if phase == "Complete" then break end
        if not a.Pending and not a.PendingSeed then
            if kind == "Seed" and phase == "Pour" then
                send(a, "SeedDrop", {Offset = Vector2.zero})
            elseif kind == "Seed" and phase == "Cover" then
                for index = 1, a.Payload.Count or 4 do
                    if not a.Payload.Covered[index] and not (a.Targets[index] and a.Targets[index].Pending) then
                        send(a, "Cover", {Index = index})
                        break
                    end
                end
            elseif kind == "Harvest" and phase == "Clip" then
                for index = 1, (a.Payload.Count or 1) do
                    if not a.Payload.Clipped[index] then send(a, "Clip", {Index = index}); task.wait(0.2) end
                end
            else error("unexpected minigame phase: " .. tostring(phase)) end
        end
        task.wait(0.35)
    end
    assert(current(), "garden operation cancelled")
end
local function prepareGarden()
    local function counts() return hub.ReadInventory() or {} end
    local function move(point)
        assert(current(),"garden cancelled")
        local character=assert(player.Character,"character unavailable")
        local root=assert(character:FindFirstChild("HumanoidRootPart"),"root unavailable")
        local humanoid=assert(character:FindFirstChildOfClass("Humanoid"),"humanoid unavailable")
        local filter=RaycastParams.new()
        filter.FilterType=Enum.RaycastFilterType.Exclude
        filter.FilterDescendantsInstances={character,workspace.Game.Gardening.Pots}
        local floor=workspace:Raycast(point+Vector3.new(0,8,3),Vector3.new(0,-25,0),filter)
        assert(floor and floor.Normal.Y>.5,"garden setup landing unavailable")
        root.AssemblyLinearVelocity=Vector3.zero
        character:PivotTo(CFrame.new(floor.Position+Vector3.new(0,humanoid.HipHeight+root.Size.Y/2+2.2,0)))
        task.wait(.8)
    end
    local function press(prompt)
        assert(current() and prompt:GetAttribute("StoryPromptAvailable")~=false,"garden prompt unavailable")
        assert(prompt.HoldDuration<=5,"garden hold changed")
        prompt:InputHoldBegin()
        task.wait(prompt.HoldDuration+.3)
        prompt:InputHoldEnd()
        task.wait(.5)
    end
    local pot=ownedPot()
    if pot and pot:GetAttribute("Stage")~="Empty" then return pot end
    local needPot=not pot and (counts()["Garden Pot"]or 0)<1
    local needDirt=(counts()["Dirt Bag"]or 0)<1
    if needPot or needDirt then
        local coins=player.Data.Stats:FindFirstChild("Coins")
        local cost=(needPot and 100 or 0)+(needDirt and 25 or 0)
        assert(coins and coins.Value>=cost,"garden needs coins for pot and dirt")
        run.Status="preparing personal garden supplies"
        hub.RequestStream(Vector3.new(-1759.7,31.5,805.6),5)
        move(Vector3.new(-1759.7,29,805.6))
        local shop=require(player.PlayerScripts.Core.Gardening.ShopController)
        local ok,err=pcall(function()
            shop:RequestOpen("Supply")
            assert(waitUntil(function()return shop.Token and shop.Root and shop.Root.Visible and next(shop.Rows)~=nil end,8),"garden shop unavailable")
            task.wait(1)
            for _,name in ipairs({"Garden Pot","Dirt Bag"}) do
                if (name=="Garden Pot" and needPot) or (name=="Dirt Bag" and needDirt) then
                    local row
                    for _,candidate in pairs(shop.Rows)do if candidate.Offer.Name==name then row=candidate;break end end
                    assert(row and row.Amount==1,"single garden supply unavailable")
                    assert(row.Offer.Coins==(name=="Garden Pot" and 100 or 25),"garden supply price changed")
                    assert(waitUntil(function()
                        return not shop.Pending and shop.Token and row.Card.BuyCoins.Active
                            and os.clock()>=(shop.ClickGuardUntil or 0)
                    end,8),"garden purchase controls not ready")
                    local before=counts()[name]or 0
                    local sent=false
                    for _,connection in ipairs(getconnections(row.Card.BuyCoins.Activated))do
                        if connection.Function then connection.Function();sent=true end
                    end
                    assert(sent,"garden buy callback unavailable")
                    assert(waitUntil(function()return (counts()[name]or 0)>before end,8),"garden purchase unconfirmed")
                    task.wait(1)
                end
            end
        end)
        shop:Close()
        assert(ok,err)
    end
    if not pot then
        local chosen,distance=nil,math.huge
        for _,spot in ipairs(workspace.Game.Gardening:GetChildren())do
            local prompt=spot:FindFirstChild("GardenPlace")
            if spot:IsA("BasePart") and prompt and prompt:GetAttribute("StoryPromptAvailable")==true then
                local d=(spot.Position-player.Character:GetPivot().Position).Magnitude
                if d<distance then chosen=spot;distance=d end
            end
        end
        assert(chosen,"no free personal garden spot")
        move(chosen.Position)
        press(chosen.GardenPlace)
        assert(waitUntil(function()pot=ownedPot();return pot~=nil end,5),"personal pot placement unconfirmed")
    end
    if pot:GetAttribute("Stage")=="Empty" then
        move(pot:GetPivot().Position)
        press(assert(pot:FindFirstChild("GardenWork",true),"garden work unavailable"))
        local deadline=os.clock()+25
        local session
        while current() and os.clock()<deadline and pot:GetAttribute("Stage")=="Empty" do
            local a=active()
            if a and a.Payload.Model==pot and a.Payload.Kind=="Dirt" and not a.Closing then
                session=a
                if a.Bag and a.BagPose and a.Goal then
                    if a.BagTween then a.BagTween:Cancel();a.BagTween=nil end
                    a.BagPose.Value=CFrame.new(a.Goal)
                    a.Bag:PivotTo(CFrame.new(a.Goal))
                    a.Dragging=true;a.PadDragging=true
                end
            end
            task.wait(.15)
        end
        if session then session.Dragging=false;session.PadDragging=false end
        assert(pot:GetAttribute("Stage")=="DirtReady","personal pot dirt unconfirmed")
        task.wait(.7)
    end
    return pot
end

local function operate(kind, chosenSeed)
    run.Busy = true
    if hub.ReleaseIdleHide then hub.ReleaseIdleHide() end
    local wantedRokaka = hub.AutoRokaka
    run.WantedRokaka = wantedRokaka
    local wantedArrow = hub.AutoArrow
    run.WantedArrow = wantedArrow
    run.Operations += 1
    local prompt
    local ok, err = pcall(function()
        assert(waitUntil(function() return not hub.AutoBusy and not hub.TeleportBusy end, 6), "farm did not yield")
        local pot = ownedPot()
        if not pot then
            hub.RequestStream(Vector3.new(-1755.824, 28.156, 814.510), 5)
            pot = ownedPot()
        end
        if not pot or pot:GetAttribute("Stage")=="Empty" then pot=prepareGarden() end
        assert(pot, "owned pot is not loaded")
        local expected = kind == "Seed" and "DirtReady" or "Ready"
        assert(pot:GetAttribute("Stage") == expected, "pot stage changed")
        local character = player.Character
        local root = character and character:FindFirstChild("HumanoidRootPart")
        local humanoid = character and character:FindFirstChildOfClass("Humanoid")
        assert(root and humanoid and humanoid.Health > 0, "character unavailable")
        local point = pot:GetPivot().Position
        local params = RaycastParams.new()
        params.FilterType = Enum.RaycastFilterType.Exclude
        params.FilterDescendantsInstances = {character, pot}
        local floor = workspace:Raycast(point + Vector3.new(0, 8, 3), Vector3.new(0, -16, 0), params)
        assert(floor and floor.Normal.Y > 0.5, "no supported garden landing")
        local position = floor.Position + Vector3.new(0, humanoid.HipHeight + root.Size.Y / 2 + 0.2, 0)
        root.AssemblyLinearVelocity = Vector3.zero
        character:PivotTo(CFrame.new(position, Vector3.new(point.X, position.Y, point.Z)))
        task.wait(0.7)
        assert(current() and player.Character == character, "character changed")
        if chosenSeed then
            remote:FireServer("SelectSeed", {Name = chosenSeed.Name, ID = chosenSeed.ID})
            task.wait(0.5)
        end
        prompt = assert(pot:FindFirstChild("GardenWork", true), "garden prompt missing")
        assert(prompt.HoldDuration <= 5, "unexpected garden hold")
        assert((root.Position - point).Magnitude <= 12, "garden out of range")
        local interactions=require(player.PlayerScripts.Core.StoryInteractions)
        assert(waitUntil(function()
            local camera=workspace.CurrentCamera
            if not camera then return false end
            local screen=camera:WorldToScreenPoint(point+Vector3.new(0,1,0))
            interactions.UpdateGardeningFocus(root,Vector2.new(screen.X,screen.Y))
            return prompt.Enabled and interactions.IsEligible(prompt)
        end,3),"garden target focus unavailable")
        if type(fireproximityprompt)=="function" then
            fireproximityprompt(prompt)
        else
            prompt:InputHoldBegin()
            task.wait(prompt.HoldDuration + 0.2)
            prompt:InputHoldEnd()
        end
        completeMinigame(kind, pot)
        if kind == "Seed" then
            assert(waitUntil(function() return pot:GetAttribute("Stage") == "Growing" and pot:GetAttribute("Contains") == chosenSeed.Name end, 5), "rokaka planting unconfirmed")
            run.PlantedAt = os.time()
            run.SeedGrade = chosenSeed.Quality
            run.PlantedSeed = chosenSeed.Name
            run.PotId = pot:GetAttribute("PotId")
            run.Status = "rokaka planted; arrows continue"
        else
            assert(waitUntil(function() return fruits() > run.BeforeFruit end, 5), "fruit inventory gain unconfirmed")
            run.FruitCount, run.FruitNames = fruits()
            run.Completed = os.time()
            run.Status = "rokaka fruit confirmed in inventory"
        end
    end)
    if prompt then pcall(function() prompt:InputHoldEnd() end) end
    pcall(function() controller:leave() end)
    if env.MT_RokakaGardenRun == run and env.MT_ArrowRokakaFinder == hub and hub.Alive then
        -- Busy owns the temporary pause; user toggles remain unchanged.
    end
    run.Busy = false
    if ok then run.LastError = nil end
    if not ok then
        run.LastError = tostring(err)
        table.insert(run.Errors, {time = os.time(), error = run.LastError})
        if #run.Errors > 10 then table.remove(run.Errors, 1) end
        run.RetryAt = os.clock() + 30
    end
end
run.Stop = function() run.Alive = false; run.Busy = false end
run.Worker = task.spawn(function()
    while current() do
        if hub.PhoneBusy or hub.CraftBusy or hub.AutoHopPause or hub.HopBusy then task.wait(0.2); continue end
        local count, names = fruits()
        if count > run.BeforeFruit then
            run.FruitCount, run.FruitNames, run.Completed = count, names, os.time()
            run.Status = "rokaka fruit confirmed in inventory"
            if not hub.AutoRokaka then break end
            run.BeforeFruit = count
            run.Completed = nil
        end
        local pot = ownedPot()
        local stage = pot and pot:GetAttribute("Stage")
        if stage == "Growing" then
            local endsAt = pot:GetAttribute("GrowthEndsAt")
            run.Remaining = type(endsAt) == "number" and math.max(0, endsAt - workspace:GetServerTimeNow()) or pot:GetAttribute("GrowthRemaining")
            run.Status = "rokaka growing; arrows continue"
        elseif not hub.AutoBusy and not hub.TeleportBusy and not hub.HasPriorityItems() and os.clock() >= (run.RetryAt or 0) then
            if stage == "Ready" and tostring(pot:GetAttribute("Contains")):lower():find("roka", 1, true)
                and (not hub.ShouldCollectRokaka or hub.ShouldCollectRokaka(pot:GetAttribute("Contains"))) then
                operate("Harvest")
            elseif stage == "DirtReady" or stage == "Empty" or not pot then
                local selected = seed()
                local collector = env.MT_RokakaSeedRun
                if selected and (not collector or not collector.Alive) then operate("Seed", selected)
                else run.Status = "waiting for rokaka seed; item farms continue" end
            end
        end
        if run.Completed then
            if not hub.AutoRokaka then break end
            run.BeforeFruit = fruits()
            run.Completed = nil
        end
        task.wait(5)
    end
    run.Alive = false
end)
return run

end
if not (resume and resume.HoldForJoin) and (not gardenBeforeReload or not gardenBeforeReload.Completed)
    and state.Advanced.FeatureStates.GardenHarvest == nil
    and not (type(isfile)=="function" and isfile("sharkwow-farm-paused-"..player.UserId..".flag")) then
    local gardenOK, gardenError = pcall(state.StartGarden)
    if not gardenOK then state.GardenError = tostring(gardenError); warn("stand out garden: " .. state.GardenError) end
end
savePreferences()
task.spawn(function()
    while alive do
        local ok, err = pcall(function()
            keepalive()
            readInventory()
            if state.ResumeStatus ~= "ready" and os.clock() >= resumeRetryAt then ensureResumeReady() end
            render(scan())
        end)
        if not ok then
            state.LastError = tostring(err)
            if alive then status.Text = "scan retry: " .. state.LastError:sub(1, 100) end
            warn("item finder: " .. tostring(err))
        else state.LastError = "" end
        task.wait(1)
    end
end)
local restored, restoreError = state.Advanced.RestoreSettings()
if not restored and restoreError then warn("stand out settings: "..tostring(restoreError)) end
if initialThreadIdentity and type(setthreadidentity) == "function" then setthreadidentity(initialThreadIdentity) end
return state
