text paste
--[[
    CHILLI HUB  //  STEAL AN EGG  //  v6.0 FINAL
    Execute while in Steal An Egg.
    Right Shift = menu.  End = panic.  Orb = reopen.

    Root parent is resolved once through a verified chain and
    asserted before any UI is built, so the menu always appears.
]]

local Players = game:GetService("Players")
local RunService = game:GetService("RunService")
local UserInputService = game:GetService("UserInputService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local TweenService = game:GetService("TweenService")
local TeleportService = game:GetService("TeleportService")
local VirtualUser = game:GetService("VirtualUser")
local HttpService = game:GetService("HttpService")
local StarterGui = game:GetService("StarterGui")
local Lighting = game:GetService("Lighting")
local CoreGui = game:GetService("CoreGui")

local env = getfenv()
local firetouchinterest = rawget(env, "firetouchinterest")
local gethui = rawget(env, "gethui")
local setclipboard = rawget(env, "setclipboard")
local writefile = rawget(env, "writefile")
local readfile = rawget(env, "readfile")
local isfile = rawget(env, "isfile")
local Drawing = rawget(env, "Drawing")

local player = Players.LocalPlayer
local camera = workspace.CurrentCamera
local playerGui = player:FindFirstChildOfClass("PlayerGui") or player:WaitForChild("PlayerGui")

-- ============================================================
-- CONFIG
-- ============================================================
local CFG = {
    accent = Color3.fromRGB(226, 62, 62),
    bg = Color3.fromRGB(15, 15, 17),
    panel = Color3.fromRGB(23, 23, 26),
    card = Color3.fromRGB(28, 28, 32),
    elem = Color3.fromRGB(37, 37, 42),
    text = Color3.fromRGB(240, 240, 244),
    dim = Color3.fromRGB(136, 136, 144),
    ok = Color3.fromRGB(92, 190, 122),
    warn = Color3.fromRGB(226, 176, 72),
    bad = Color3.fromRGB(226, 88, 88),
}

local State = {
    autoSteal = false, autoHatch = false, autoPlace = false,
    autoCollect = false, autoRift = false, autoSell = false,
    autoDeposit = false, autoBuy = false, autoMerge = false,
    autoRebirth = false, autoDaily = false, instantSteal = false,
    eggESP = false, playerESP = false, tracers = false,
    eggNotify = false, distLabels = false, fullbright = false,
    godMode = false, speedHack = false, fly = false,
    noclip = false, infJump = false, freeze = false,
    walkSpeed = 16, flySpeed = 90, stealRange = 400,
    minRarity = "Any", notifyRarity = "Legendary",
    priority = "Nearest", biome = "None",
    espMode = "Highlight", cacheTTL = 1.2, uiParent = "PlayerGui",
}

local AC = {
    rubberband = true, stateGuard = true, speedClamp = true,
    antiTrap = true, antiRagdoll = true, throttle = true,
    jitter = true, smoothTP = true, netOwner = true,
    antiAfk = true, randomNames = true, coreGui = false,
    throttleMs = 90, clampMax = 120,
    rbCount = 0, trapCount = 0, lastFire = 0,
}

local LAYERS = {
    "rubberband", "stateGuard", "speedClamp", "antiTrap",
    "antiRagdoll", "throttle", "jitter", "smoothTP",
    "netOwner", "antiAfk", "randomNames", "coreGui",
}

local RarityRank = {
    Any = 0, Common = 1, Uncommon = 2, Rare = 3, Epic = 4,
    Legendary = 5, Mythic = 6, Cosmic = 7, Secret = 8,
    Eternal = 9, Divine = 10,
}

local BIOMES = {
    "Forest", "Lake", "Desert", "Jungle", "Snow", "Volcano",
    "Abyss Ocean", "Prehistoric", "Cosmic", "Cherry Blossom",
    "Titan Temple", "Angel", "Demon", "Alien Planet", "Void",
}

local NAMES = { "Link", "Node", "Anchor", "Handler", "Relay", "Pivot", "Sync" }
local function pickName() return NAMES[math.random(#NAMES)] end

local gen = 0
local conns = {}
local flyAtt, flyLV, flyAO
local loopRunning = false
local guardBusy = false
local savedWalk = 16
local savedBrightness = Lighting.Brightness

local function track(c)
    conns[#conns + 1] = c
    return c
end

local function untrackAll()
    for _, c in ipairs(conns) do pcall(function() c:Disconnect() end) end
    table.clear(conns)
end

local function char() return player.Character end
local function hum()
    local c = char()
    return c and c:FindFirstChildOfClass("Humanoid")
end
local function root()
    local c = char()
    return c and c:FindFirstChild("HumanoidRootPart")
end

local function notify(t, b)
    pcall(function()
        StarterGui:SetCore("SendNotification", { Title = t, Text = b, Duration = 4 })
    end)
end

-- ============================================================
-- ROOT  (resolved once, verified, asserted)
-- ============================================================
local function resolveParent()
    if State.uiParent == "CoreGui" then
        if gethui then
            local ok, h = pcall(gethui)
            if ok and typeof(h) == "Instance" and h.Parent ~= nil then
                return h
            end
        end
        local ok, cg = pcall(function()
            return CoreGui:FindFirstChild("RobloxGui") or CoreGui
        end)
        if ok and cg then return cg end
    end
    return playerGui
end

local gui = Instance.new("ScreenGui")
gui.Name = pickName()
gui.ResetOnSpawn = false
gui.IgnoreGuiInset = true
gui.ZIndexBehavior = Enum.ZIndexBehavior.Sibling
gui.DisplayOrder = 2147483647
gui.Enabled = true

local okParent = pcall(function() gui.Parent = resolveParent() end)
if not okParent or not gui.Parent then
    gui.Parent = playerGui
end

assert(gui.Parent, "Chilli Hub: could not parent GUI")

-- re-parent only if the root is genuinely orphaned
task.spawn(function()
    while gui do
        task.wait(1.5)
        if not gui.Parent then
            pcall(function() gui.Parent = resolveParent() end)
            if not gui.Parent then gui.Parent = playerGui end
        end
    end
end)

local function corner(i, r)
    local c = Instance.new("UICorner")
    c.CornerRadius = UDim.new(0, r or 6)
    c.Parent = i
    return c
end

local function stroke(i, col, t)
    local s = Instance.new("UIStroke")
    s.Color = col or Color3.fromRGB(55, 55, 62)
    s.Thickness = 1
    s.Transparency = t or 0.35
    s.Parent = i
    return s
end

-- ============================================================
-- TOASTS
-- ============================================================
local toastHolder = Instance.new("Frame")
toastHolder.Size = UDim2.new(0, 250, 0, 320)
toastHolder.Position = UDim2.new(1, -266, 0, 20)
toastHolder.BackgroundTransparency = 1
toastHolder.ZIndex = 50
toastHolder.Parent = gui

local toastList = Instance.new("UIListLayout")
toastList.Padding = UDim.new(0, 6)
toastList.SortOrder = Enum.SortOrder.LayoutOrder
toastList.Parent = toastHolder

local toastOrder = 0
local function toast(text, color)
    toastOrder += 1
    local f = Instance.new("Frame")
    f.Size = UDim2.new(1, 0, 0, 30)
    f.BackgroundColor3 = CFG.card
    f.BorderSizePixel = 0
    f.LayoutOrder = toastOrder
    f.ZIndex = 50
    f.Parent = toastHolder
    corner(f, 6)
    stroke(f, color or CFG.accent, 0.2)

    local bar = Instance.new("Frame")
    bar.Size = UDim2.new(0, 3, 1, -8)
    bar.Position = UDim2.new(0, 5, 0, 4)
    bar.BackgroundColor3 = color or CFG.accent
    bar.BorderSizePixel = 0
    bar.Parent = f
    corner(bar, 2)

    local t = Instance.new("TextLabel")
    t.Size = UDim2.new(1, -22, 1, 0)
    t.Position = UDim2.new(0, 14, 0, 0)
    t.BackgroundTransparency = 1
    t.Text = text
    t.TextColor3 = CFG.text
    t.Font = Enum.Font.GothamMedium
    t.TextSize = 11
    t.TextXAlignment = Enum.TextXAlignment.Left
    t.TextTruncate = Enum.TextTruncate.AtEnd
    t.ZIndex = 51
    t.Parent = f

    task.delay(3.2, function()
        TweenService:Create(f, TweenInfo.new(0.25), { BackgroundTransparency = 1 }):Play()
        TweenService:Create(t, TweenInfo.new(0.25), { TextTransparency = 1 }):Play()
        task.wait(0.3)
        f:Destroy()
    end)
end

-- ============================================================
-- WINDOW
-- ============================================================
local main = Instance.new("Frame")
main.Name = "Window"
main.Size = UDim2.new(0, 600, 0, 460)
main.Position = UDim2.new(0.5, -300, 0.5, -230)
main.BackgroundColor3 = CFG.bg
main.BorderSizePixel = 0
main.Active = true
main.Visible = true
main.ZIndex = 10
main.Parent = gui
corner(main, 12)
stroke(main, Color3.fromRGB(58, 58, 64), 0.15)

local topBar = Instance.new("Frame")
topBar.Size = UDim2.new(1, 0, 0, 40)
topBar.BackgroundColor3 = CFG.panel
topBar.BorderSizePixel = 0
topBar.ZIndex = 11
topBar.Parent = main
corner(topBar, 12)

local topFix = Instance.new("Frame")
topFix.Size = UDim2.new(1, 0, 0, 16)
topFix.Position = UDim2.new(0, 0, 1, -16)
topFix.BackgroundColor3 = CFG.panel
topFix.BorderSizePixel = 0
topFix.ZIndex = 11
topFix.Parent = topBar

local logo = Instance.new("TextLabel")
logo.Size = UDim2.new(0, 200, 1, 0)
logo.Position = UDim2.new(0, 16, 0, 0)
logo.BackgroundTransparency = 1
logo.Text = "CHILLI HUB"
logo.TextColor3 = CFG.accent
logo.Font = Enum.Font.GothamBold
logo.TextSize = 15
logo.TextXAlignment = Enum.TextXAlignment.Left
logo.ZIndex = 12
logo.Parent = topBar

local ver = Instance.new("TextLabel")
ver.Size = UDim2.new(0, 140, 1, 0)
ver.Position = UDim2.new(0, 128, 0, 0)
ver.BackgroundTransparency = 1
ver.Text = "SAE v6.0 FINAL"
ver.TextColor3 = CFG.dim
ver.Font = Enum.Font.Gotham
ver.TextSize = 10
ver.TextXAlignment = Enum.TextXAlignment.Left
ver.ZIndex = 12
ver.Parent = topBar

local statusDot = Instance.new("TextLabel")
statusDot.Size = UDim2.new(0, 190, 1, 0)
statusDot.Position = UDim2.new(1, -270, 0, 0)
statusDot.BackgroundTransparency = 1
statusDot.Text = "STEALTH"
statusDot.TextColor3 = CFG.ok
statusDot.Font = Enum.Font.GothamBold
statusDot.TextSize = 10
statusDot.TextXAlignment = Enum.TextXAlignment.Right
statusDot.ZIndex = 12
statusDot.Parent = topBar

local minBtn = Instance.new("TextButton")
minBtn.Size = UDim2.new(0, 26, 0, 26)
minBtn.Position = UDim2.new(1, -66, 0, 7)
minBtn.BackgroundColor3 = CFG.elem
minBtn.Text = "-"
minBtn.TextColor3 = CFG.text
minBtn.Font = Enum.Font.GothamBold
minBtn.TextSize = 14
minBtn.ZIndex = 12
minBtn.Parent = topBar
corner(minBtn, 6)

local closeBtn = Instance.new("TextButton")
closeBtn.Size = UDim2.new(0, 26, 0, 26)
closeBtn.Position = UDim2.new(1, -36, 0, 7)
closeBtn.BackgroundColor3 = CFG.elem
closeBtn.Text = "X"
closeBtn.TextColor3 = CFG.text
closeBtn.Font = Enum.Font.GothamBold
closeBtn.TextSize = 12
closeBtn.ZIndex = 12
closeBtn.Parent = topBar
corner(closeBtn, 6)

local dragging, dragStart, startPos = false, nil, nil
topBar.InputBegan:Connect(function(i)
    if i.UserInputType == Enum.UserInputType.MouseButton1
        or i.UserInputType == Enum.UserInputType.Touch then
        dragging = true
        dragStart = i.Position
        startPos = main.Position
    end
end)
UserInputService.InputChanged:Connect(function(i)
    if not dragging then return end
    if i.UserInputType == Enum.UserInputType.MouseMovement
        or i.UserInputType == Enum.UserInputType.Touch then
        local d = i.Position - dragStart
        main.Position = UDim2.new(
            startPos.X.Scale, startPos.X.Offset + d.X,
            startPos.Y.Scale, startPos.Y.Offset + d.Y)
    end
end)
UserInputService.InputEnded:Connect(function(i)
    if i.UserInputType == Enum.UserInputType.MouseButton1
        or i.UserInputType == Enum.UserInputType.Touch then
        dragging = false
    end
end)

-- ============================================================
-- SIDEBAR + CONTENT
-- ============================================================
local sidebar = Instance.new("Frame")
sidebar.Size = UDim2.new(0, 124, 1, -58)
sidebar.Position = UDim2.new(0, 12, 0, 48)
sidebar.BackgroundTransparency = 1
sidebar.ZIndex = 11
sidebar.Parent = main

local sideList = Instance.new("UIListLayout")
sideList.Padding = UDim.new(0, 4)
sideList.SortOrder = Enum.SortOrder.LayoutOrder
sideList.Parent = sidebar

local content = Instance.new("Frame")
content.Size = UDim2.new(1, -150, 1, -58)
content.Position = UDim2.new(0, 138, 0, 48)
content.BackgroundTransparency = 1
content.ClipsDescendants = true
content.ZIndex = 11
content.Parent = main

local pages, tabButtons, pageOrder = {}, {}, {}

local function makePage(name)
    local scroll = Instance.new("ScrollingFrame")
    scroll.Name = name
    scroll.Size = UDim2.new(1, 0, 1, 0)
    scroll.BackgroundTransparency = 1
    scroll.BorderSizePixel = 0
    scroll.ScrollBarThickness = 3
    scroll.ScrollBarImageColor3 = CFG.accent
    scroll.CanvasSize = UDim2.new(0, 0, 0, 0)
    scroll.AutomaticCanvasSize = Enum.AutomaticSize.Y
    scroll.ScrollingDirection = Enum.ScrollingDirection.Y
    scroll.Visible = false
    scroll.ZIndex = 11
    scroll.Parent = content

    local list = Instance.new("UIListLayout")
    list.Padding = UDim.new(0, 6)
    list.SortOrder = Enum.SortOrder.LayoutOrder
    list.Parent = scroll

    local pad = Instance.new("UIPadding")
    pad.PaddingRight = UDim.new(0, 10)
    pad.PaddingBottom = UDim.new(0, 16)
    pad.Parent = scroll

    pageOrder[name] = 0
    pages[name] = scroll
    return scroll
end

local function ord(page)
    pageOrder[page.Name] += 1
    return pageOrder[page.Name]
end

local function selectTab(name)
    for n, pg in pairs(pages) do
        pg.Visible = (n == name)
        local b = tabButtons[n]
        b.BackgroundColor3 = (n == name) and CFG.accent or CFG.elem
        b.TextColor3 = (n == name) and Color3.new(1, 1, 1) or CFG.dim
    end
end

local function makeTab(name)
    local b = Instance.new("TextButton")
    b.Size = UDim2.new(1, 0, 0, 32)
    b.BackgroundColor3 = CFG.elem
    b.Text = name
    b.TextColor3 = CFG.dim
    b.Font = Enum.Font.GothamMedium
    b.TextSize = 12
    b.LayoutOrder = #tabButtons + 1
    b.ZIndex = 12
    b.Parent = sidebar
    corner(b, 7)
    tabButtons[name] = b
    makePage(name)
    b.MouseButton1Click:Connect(function() selectTab(name) end)
    return b
end

-- ============================================================
-- ELEMENTS
-- ============================================================
local renderers = {}

local function section(page, text)
    local l = Instance.new("TextLabel")
    l.Size = UDim2.new(1, 0, 0, 18)
    l.BackgroundTransparency = 1
    l.Text = string.upper(text)
    l.TextColor3 = CFG.accent
    l.Font = Enum.Font.GothamBold
    l.TextSize = 10
    l.TextXAlignment = Enum.TextXAlignment.Left
    l.LayoutOrder = ord(page)
    l.ZIndex = 12
    l.Parent = page
    return l
end

local function card(page)
    local c = Instance.new("Frame")
    c.Size = UDim2.new(1, 0, 0, 0)
    c.AutomaticSize = Enum.AutomaticSize.Y
    c.BackgroundColor3 = CFG.card
    c.BorderSizePixel = 0
    c.LayoutOrder = ord(page)
    c.ZIndex = 12
    c.Parent = page
    corner(c, 8)

    local pad = Instance.new("UIPadding")
    pad.PaddingTop = UDim.new(0, 5)
    pad.PaddingBottom = UDim.new(0, 5)
    pad.PaddingLeft = UDim.new(0, 5)
    pad.PaddingRight = UDim.new(0, 5)
    pad.Parent = c

    local list = Instance.new("UIListLayout")
    list.Padding = UDim.new(0, 4)
    list.SortOrder = Enum.SortOrder.LayoutOrder
    list.Parent = c

    return c
end

local function toggle(parent, label, key, cb, tbl)
    local store = tbl or State
    local row = Instance.new("Frame")
    row.Size = UDim2.new(1, 0, 0, 30)
    row.BackgroundColor3 = CFG.panel
    row.BorderSizePixel = 0
    row.LayoutOrder = ord(parent)
    row.ZIndex = 13
    row.Parent = parent
    corner(row, 6)

    local t = Instance.new("TextLabel")
    t.Size = UDim2.new(1, -62, 1, 0)
    t.Position = UDim2.new(0, 10, 0, 0)
    t.BackgroundTransparency = 1
    t.Text = label
    t.TextColor3 = CFG.text
    t.Font = Enum.Font.Gotham
    t.TextSize = 12
    t.TextXAlignment = Enum.TextXAlignment.Left
    t.TextTruncate = Enum.TextTruncate.AtEnd
    t.ZIndex = 14
    t.Parent = row

    local btn = Instance.new("TextButton")
    btn.Size = UDim2.new(0, 38, 0, 18)
    btn.Position = UDim2.new(1, -48, 0.5, -9)
    btn.BackgroundColor3 = CFG.elem
    btn.Text = ""
    btn.ZIndex = 14
    btn.Parent = row
    corner(btn, 9)

    local knob = Instance.new("Frame")
    knob.Size = UDim2.new(0, 14, 0, 14)
    knob.Position = UDim2.new(0, 2, 0.5, -7)
    knob.BackgroundColor3 = CFG.dim
    knob.BorderSizePixel = 0
    knob.ZIndex = 15
    knob.Parent = btn
    corner(knob, 7)

    local function render()
        local on = store[key]
        TweenService:Create(btn, TweenInfo.new(0.14), {
            BackgroundColor3 = on and CFG.accent or CFG.elem }):Play()
        TweenService:Create(knob, TweenInfo.new(0.14), {
            Position = on and UDim2.new(1, -16, 0.5, -7) or UDim2.new(0, 2, 0.5, -7),
            BackgroundColor3 = on and Color3.new(1, 1, 1) or CFG.dim }):Play()
    end

    btn.MouseButton1Click:Connect(function()
        store[key] = not store[key]
        render()
        if cb then pcall(cb, store[key]) end
    end)

    renderers[key] = render
    render()
    return row
end

local function slider(parent, label, key, min, max, suffix, tbl)
    local store = tbl or State
    local holder = Instance.new("Frame")
    holder.Size = UDim2.new(1, 0, 0, 46)
    holder.BackgroundColor3 = CFG.panel
    holder.BorderSizePixel = 0
    holder.LayoutOrder = ord(parent)
    holder.ZIndex = 13
    holder.Parent = parent
    corner(holder, 6)

    local t = Instance.new("TextLabel")
    t.Size = UDim2.new(1, -20, 0, 18)
    t.Position = UDim2.new(0, 10, 0, 4)
    t.BackgroundTransparency = 1
    t.Text = label .. ": " .. tostring(store[key]) .. (suffix or "")
    t.TextColor3 = CFG.text
    t.Font = Enum.Font.Gotham
    t.TextSize = 12
    t.TextXAlignment = Enum.TextXAlignment.Left
    t.ZIndex = 14
    t.Parent = holder

    local bar = Instance.new("Frame")
    bar.Size = UDim2.new(1, -20, 0, 5)
    bar.Position = UDim2.new(0, 10, 0, 30)
    bar.BackgroundColor3 = CFG.elem
    bar.BorderSizePixel = 0
    bar.ZIndex = 14
    bar.Parent = holder
    corner(bar, 3)

    local fill = Instance.new("Frame")
    fill.Size = UDim2.new((store[key] - min) / (max - min), 0, 1, 0)
    fill.BackgroundColor3 = CFG.accent
    fill.BorderSizePixel = 0
    fill.ZIndex = 15
    fill.Parent = bar
    corner(fill, 3)

    local function setX(x)
        local rel = math.clamp((x - bar.AbsolutePosition.X) / bar.AbsoluteSize.X, 0, 1)
        local v = math.floor(min + (max - min) * rel + 0.5)
        store[key] = v
        fill.Size = UDim2.new(rel, 0, 1, 0)
        t.Text = label .. ": " .. tostring(v) .. (suffix or "")
    end

    local held = false
    bar.InputBegan:Connect(function(i)
        if i.UserInputType == Enum.UserInputType.MouseButton1
            or i.UserInputType == Enum.UserInputType.Touch then
            held = true
            setX(i.Position.X)
        end
    end)
    UserInputService.InputChanged:Connect(function(i)
        if held and (i.UserInputType == Enum.UserInputType.MouseMovement
            or i.UserInputType == Enum.UserInputType.Touch) then
            setX(i.Position.X)
        end
    end)
    UserInputService.InputEnded:Connect(function(i)
        if i.UserInputType == Enum.UserInputType.MouseButton1
            or i.UserInputType == Enum.UserInputType.Touch then
            held = false
        end
    end)
    return holder
end

local function dropdown(parent, label, options, key, cb, tbl)
    local store = tbl or State
    local holder = Instance.new("Frame")
    holder.Size = UDim2.new(1, 0, 0, 30)
    holder.BackgroundColor3 = CFG.panel
    holder.BorderSizePixel = 0
    holder.ClipsDescendants = true
    holder.LayoutOrder = ord(parent)
    holder.ZIndex = 13
    holder.Parent = parent
    corner(holder, 6)

    local head = Instance.new("TextButton")
    head.Size = UDim2.new(1, 0, 0, 30)
    head.BackgroundTransparency = 1
    head.Text = ""
    head.ZIndex = 14
    head.Parent = holder

    local t = Instance.new("TextLabel")
    t.Size = UDim2.new(1, -20, 0, 30)
    t.Position = UDim2.new(0, 10, 0, 0)
    t.BackgroundTransparency = 1
    t.Text = label .. ": " .. tostring(store[key])
    t.TextColor3 = CFG.text
    t.Font = Enum.Font.Gotham
    t.TextSize = 12
    t.TextXAlignment = Enum.TextXAlignment.Left
    t.TextTruncate = Enum.TextTruncate.AtEnd
    t.ZIndex = 14
    t.Parent = holder

    local arrow = Instance.new("TextLabel")
    arrow.Size = UDim2.new(0, 20, 0, 30)
    arrow.Position = UDim2.new(1, -26, 0, 0)
    arrow.BackgroundTransparency = 1
    arrow.Text = "v"
    arrow.TextColor3 = CFG.dim
    arrow.Font = Enum.Font.GothamBold
    arrow.TextSize = 11
    arrow.ZIndex = 14
    arrow.Parent = holder

    local open = false
    local function rebuild()
        holder.Size = open and UDim2.new(1, 0, 0, 34 + #options * 24) or UDim2.new(1, 0, 0, 30)
        for _, c in ipairs(holder:GetChildren()) do
            if c:IsA("TextButton") and c ~= head then c:Destroy() end
        end
        if not open then return end
        for i, opt in ipairs(options) do
            local o = Instance.new("TextButton")
            o.Size = UDim2.new(1, -16, 0, 22)
            o.Position = UDim2.new(0, 8, 0, 32 + (i - 1) * 24)
            o.BackgroundColor3 = CFG.elem
            o.Text = opt
            o.TextColor3 = CFG.text
            o.Font = Enum.Font.Gotham
            o.TextSize = 11
            o.ZIndex = 15
            o.Parent = holder
            corner(o, 4)
            o.MouseButton1Click:Connect(function()
                store[key] = opt
                t.Text = label .. ": " .. opt
                open = false
                arrow.Text = "v"
                rebuild()
                if cb then pcall(cb, opt) end
            end)
        end
    end

    head.MouseButton1Click:Connect(function()
        open = not open
        arrow.Text = open and "^" or "v"
        rebuild()
    end)
    return holder
end

local function button(parent, text, cb, color)
    local b = Instance.new("TextButton")
    b.Size = UDim2.new(1, 0, 0, 30)
    b.BackgroundColor3 = color or CFG.elem
    b.Text = text
    b.TextColor3 = CFG.text
    b.Font = Enum.Font.GothamMedium
    b.TextSize = 12
    b.LayoutOrder = ord(parent)
    b.ZIndex = 14
    b.Parent = parent
    corner(b, 6)
    b.MouseButton1Click:Connect(function() pcall(cb) end)
    return b
end

local function label(parent, text, h)
    local l = Instance.new("TextLabel")
    l.Size = UDim2.new(1, 0, 0, h or 40)
    l.BackgroundTransparency = 1
    l.Text = text
    l.TextColor3 = CFG.dim
    l.Font = Enum.Font.Gotham
    l.TextSize = 11
    l.TextWrapped = true
    l.TextXAlignment = Enum.TextXAlignment.Left
    l.TextYAlignment = Enum.TextYAlignment.Top
    l.LayoutOrder = ord(parent)
    l.ZIndex = 14
    l.Parent = parent
    return l
end

-- ============================================================
-- REMOTE INDEX
-- ============================================================
local remoteIndex = {}
local remoteIndexAt = 0

local function buildRemoteIndex()
    table.clear(remoteIndex)
    for _, container in ipairs({ ReplicatedStorage, char() }) do
        if container then
            for _, obj in ipairs(container:GetDescendants()) do
                if obj:IsA("RemoteEvent") or obj:IsA("RemoteFunction") then
                    local k = obj.Name:lower()
                    local bucket = remoteIndex[k]
                    if not bucket then
                        bucket = {}
                        remoteIndex[k] = bucket
                    end
                    bucket[#bucket + 1] = obj
                end
            end
        end
    end
    remoteIndexAt = os.clock()
end

local function fire(names, ...)
    if AC.throttle then
        local now = os.clock() * 1000
        local gate = AC.throttleMs
        if AC.jitter then gate = gate * (0.7 + math.random() * 0.6) end
        if now - AC.lastFire < gate then return end
        AC.lastFire = now
    end
    if os.clock() - remoteIndexAt > 20 then buildRemoteIndex() end

    local args = table.pack(...)
    for _, n in ipairs(names) do
        local needle = n:lower()
        for k, bucket in pairs(remoteIndex) do
            if k:find(needle, 1, true) then
                for _, obj in ipairs(bucket) do
                    if obj.Parent then
                        pcall(function()
                            if obj:IsA("RemoteEvent") then
                                obj:FireServer(table.unpack(args, 1, args.n))
                            else
                                obj:InvokeServer(table.unpack(args, 1, args.n))
                            end
                        end)
                    end
                end
            end
        end
    end
end

-- ============================================================
-- EGG CACHE
-- ============================================================
local eggCache = {}
local eggCacheAt = 0

local function refreshEggs()
    local r = root()
    if not r then return eggCache end
    local now = os.clock()
    if now - eggCacheAt < State.cacheTTL then return eggCache end
    eggCacheAt = now

    table.clear(eggCache)
    local origin = r.Position
    local range = State.stealRange

    for _, obj in ipairs(workspace:GetDescendants()) do
        if obj:IsA("Model") or obj:IsA("BasePart") then
            local n = obj.Name:lower()
            if n:find("egg", 1, true) and not n:find("spawn", 1, true)
                and not n:find("config", 1, true) then
                local part = obj:IsA("BasePart") and obj
                    or obj:FindFirstChildWhichIsA("BasePart")
                if part and part.Parent then
                    local d = (part.Position - origin).Magnitude
                    if d <= range then
                        eggCache[#eggCache + 1] = { inst = obj, part = part, dist = d }
                    end
                end
            end
        end
    end
    if State.priority == "Nearest" then
        table.sort(eggCache, function(a, b) return a.dist < b.dist end)
    else
table.sort(eggCache, function(a, b) return a.dist > b.dist end)
    end
    return eggCache
end

local function eggRarity(egg)
    local hay = egg.inst.Name
    for _, m in ipairs(egg.inst:GetDescendants()) do
        if m:IsA("StringValue") then
            hay ..= " " .. m.Value .. " " .. m.Name
        elseif m:IsA("TextLabel") then
            hay ..= " " .. m.Text
        end
    end
    hay = hay:lower()
    for r in pairs(RarityRank) do
        if r ~= "Any" and hay:find(r:lower(), 1, true) then return r end
    end
    return "Common"
end

local function passes(egg)
    local min = RarityRank[State.minRarity] or 0
    if min == 0 then return true end
    return (RarityRank[eggRarity(egg)] or 1) >= min
end

local function touchEgg(part)
    local r = root()
    if not r or not part then return end
    if firetouchinterest then
        pcall(function()
            firetouchinterest(r, part, 0)
            task.wait(0.02)
            firetouchinterest(r, part, 1)
        end)
    end
end

local function smoothTP(target)
    local r = root()
    if not r or not target then return end
    if not AC.smoothTP then
        r.CFrame = target
        return
    end
    local dist = (r.Position - target.Position).Magnitude
    local dur = math.clamp(dist / 1100, 0.03, 0.28)
    local tw = TweenService:Create(r, TweenInfo.new(dur, Enum.EasingStyle.Linear), {
        CFrame = target })
    tw:Play()
    tw.Completed:Wait()
end

-- ============================================================
-- STATUS
-- ============================================================
local function setStatus()
    local n = 0
    for _, k in ipairs(LAYERS) do
        if AC[k] then n += 1
    end
    if n >= 9 then
        statusDot.Text = "STEALTH " .. n .. "/" .. #LAYERS
        statusDot.TextColor3 = CFG.ok
    elseif n >= 5 then
        statusDot.Text = "GUARDED " .. n .. "/" .. #LAYERS
        statusDot.TextColor3 = CFG.warn
    else
        statusDot.Text = "EXPOSED " .. n .. "/" .. #LAYERS
        statusDot.TextColor3 = CFG.bad
    end
end

-- ============================================================
-- STATE GUARD
-- ============================================================
local function startStateGuard()
    local h = hum()
    if not h then return end
    track(h.StateChanged:Connect(function(_, new)
        if not State.fly or guardBusy then return end
        if new == Enum.HumanoidStateType.Physics then return end
        if new == Enum.HumanoidStateType.Ragdoll and not AC.antiRagdoll then return end
        if not AC.stateGuard and new ~= Enum.HumanoidStateType.Ragdoll then return end
        guardBusy = true
        task.defer(function()
            local hh = hum()
            if hh and State.fly then
                pcall(function() hh:ChangeState(Enum.HumanoidStateType.Physics) end)
            end
            guardBusy = false
        end)
    end))
end

-- ============================================================
-- FEATURES
-- ============================================================
local function doSteal()
    local eggs = refreshEggs()
    for _, egg in ipairs(eggs) do
        if passes(egg) then
            local rank = RarityRank[eggRarity(egg)] or 0
            if State.eggNotify and rank >= (RarityRank[State.notifyRarity] or 99) then
                toast("Nearby: " .. egg.inst.Name, CFG.warn)
            end
            if State.instantSteal then
                smoothTP(egg.part.CFrame + Vector3.new(0, 3, 0))
            end
            touchEgg(egg.part)
            fire({ "Steal", "stealEgg", "Pickup", "CollectEgg", "Grab" }, egg.inst)
            if not State.instantSteal then break end
        end
    end
end

local function doHatch() fire({ "Hatch", "hatchEgg", "OpenEgg" }) end
local function doPlace() fire({ "Place", "placeEgg", "Equip", "Deploy" }) end
local function doCollect() fire({ "Collect", "collectReward", "ClaimReward" }) end
local function doRift() fire({ "Rift", "Sacrifice", "Void", "Offer" }) end
local function doSell() fire({ "Sell", "sellEgg", "SellAll" }) end
local function doDeposit() fire({ "Deposit", "Store", "Bank" }) end
local function doBuy() fire({ "Buy", "purchase", "BuyEgg" }) end
local function doMerge() fire({ "Merge", "Combine", "Fuse" }) end
local function doRebirth() fire({ "Rebirth", "Prestige", "Reset" }) end
local function doDaily() fire({ "Daily", "ClaimDaily", "Login" }) end

local function applyGod(on)
    local h = hum()
    if not h then return end
    if on then
        h.MaxHealth = math.huge
        h.Health = math.huge
    else
        h.MaxHealth = 100
        h.Health = 100
    end
end

local function applyFullbright(on)
    if on then
        savedBrightness = Lighting.Brightness
        Lighting.Brightness = 3
        Lighting.ClockTime = 14
        Lighting.FogEnd = 100000
        Lighting.GlobalShadows = false
    else
        Lighting.Brightness = savedBrightness
        Lighting.GlobalShadows = true
    end
end

-- ============================================================
-- FLY
-- ============================================================
local function startFly()
    local c, h, r = char(), hum(), root()
    if not c or not h or not r then return end

    savedWalk = h.WalkSpeed
    h.AutoRotate = false
    pcall(function() h:ChangeState(Enum.HumanoidStateType.Physics) end)

    if AC.netOwner then
        pcall(function() r:SetNetworkOwner(player) end)
    end

    local att = Instance.new("Attachment")
    att.Name = AC.randomNames and pickName() or "FlyAttach"
    att.Parent = r
    flyAtt = att

    local lv = Instance.new("LinearVelocity")
    lv.Name = AC.randomNames and pickName() or "FlyVelocity"
    lv.Attachment0 = att
    lv.RelativeTo = Enum.ActuatorRelativeTo.World
    lv.MaxForce = math.huge
    lv.VectorVelocity = Vector3.zero
    lv.Parent = r
    flyLV = lv

    local ao = Instance.new("AlignOrientation")
    ao.Name = AC.randomNames and pickName() or "FlyAlign"
    ao.Mode = Enum.OrientationAlignmentMode.OneAttachment
    ao.Attachment0 = att
    ao.MaxTorque = math.huge
    ao.RigidityEnabled = true
    ao.Parent = r
    flyAO = ao

    startStateGuard()

    local cam = camera
    local lastPos = r.Position
    local streak = 0
    local myGen = gen

    track(RunService.RenderStepped:Connect(function(dt)
        if not State.fly or myGen ~= gen or not r.Parent then return end

        att.CFrame = r.CFrame:ToObjectSpace(cam.CFrame)

        local mv = Vector3.zero
        if UserInputService:IsKeyDown(Enum.KeyCode.W) then mv += cam.CFrame.LookVector end
        if UserInputService:IsKeyDown(Enum.KeyCode.S) then mv -= cam.CFrame.LookVector end
        if UserInputService:IsKeyDown(Enum.KeyCode.A) then mv -= cam.CFrame.RightVector end
        if UserInputService:IsKeyDown(Enum.KeyCode.D) then mv += cam.CFrame.RightVector end
        if UserInputService:IsKeyDown(Enum.KeyCode.Space) then mv += Vector3.yAxis end
        if UserInputService:IsKeyDown(Enum.KeyCode.LeftShift) then mv -= Vector3.yAxis end
        if mv.Magnitude > 0 then mv = mv.Unit end

        local spd = State.flySpeed
        if AC.speedClamp then spd = math.min(spd, AC.clampMax) end
        local target = mv * spd
        lv.VectorVelocity = target

        if AC.rubberband then
            local moved = (r.Position - lastPos).Magnitude
            local expect = target.Magnitude * dt
            if expect > 5 and moved < expect * 0.25 then
                streak += 1
                if streak >= 3 then
                    r.CFrame = r.CFrame + target * dt
                    streak = 0
                    AC.rbCount += 1
                end
            else
                streak = 0
            end
            lastPos = r.Position
        end
    end))
end

local function stopFly()
    local h = hum()
    if h then
        h.AutoRotate = true
        h.WalkSpeed = savedWalk
        pcall(function() h:ChangeState(Enum.HumanoidStateType.Freefall) end)
    end
    if flyLV then flyLV:Destroy() flyLV = nil end
    if flyAO then flyAO:Destroy() flyAO = nil end
    if flyAtt then flyAtt:Destroy() flyAtt = nil end
end

-- ============================================================
-- ESP
-- ============================================================
local espLive = {}
local espGui = Instance.new("Folder")
espGui.Name = pickName()
espGui.Parent = gui

local tracerLines = {}

local function clearTracer(part)
    local d = tracerLines[part]
    if d then
        pcall(function() d:Remove() end)
        tracerLines[part] = nil
    end
end

local function clearOne(part)
    local e = espLive[part]
    if not e then return end
    pcall(function() e.obj:Destroy() end)
    pcall(function() e.bb:Destroy() end)
    clearTracer(part)
    espLive[part] = nil
end

local function addOne(part, color, text)
    if espLive[part] then return end
    local obj
    if State.espMode == "Highlight" then
        obj = Instance.new("Highlight")
        obj.Name = pickName()
        obj.Adornee = part
        obj.FillColor = color
        obj.OutlineColor = color
        obj.FillTransparency = 0.72
        obj.OutlineTransparency = 0.1
        obj.DepthMode = Enum.HighlightDepthMode.AlwaysOnTop
        obj.Parent = espGui
    else
        local box = Instance.new("BoxHandleAdornment")
        box.Size = part.Size + Vector3.new(0.4, 0.4, 0.4)
        box.Adornee = part
        box.AlwaysOnTop = true
        box.Transparency = 0.6
        box.Color3 = color
        box.ZIndex = 5
        box.Parent = espGui
        obj = box
    end

    local bb = Instance.new("BillboardGui")
    bb.Size = UDim2.new(0, 140, 0, 22)
    bb.StudsOffset = Vector3.new(0, part.Size.Y / 2 + 1.4, 0)
    bb.AlwaysOnTop = true
    bb.Parent = part

    local tl = Instance.new("TextLabel")
    tl.Size = UDim2.new(1, 0, 1, 0)
    tl.BackgroundTransparency = 1
    tl.Text = text
    tl.TextColor3 = color
    tl.Font = Enum.Font.GothamBold
    tl.TextSize = 12
    tl.TextStrokeTransparency = 0.35
    tl.Parent = bb

    espLive[part] = { obj = obj, bb = bb }

    if State.tracers and Drawing then
        local d = Drawing.new("Line")
        d.Thickness = 1
        d.Color = color
        d.Transparency = 0.7
        tracerLines[part] = d
    end
end

local function syncESP()
    local wanted = {}

    if State.eggESP then
        for _, egg in ipairs(refreshEggs()) do
            local txt = egg.inst.Name .. " [" .. eggRarity(egg) .. "]"
            if State.distLabels then
                txt ..= " " .. math.floor(egg.dist) .. "m"
            end
            wanted[egg.part] = { CFG.accent, txt }
        end
    end
    if State.playerESP then
        for _, p in ipairs(Players:GetPlayers()) do
            if p ~= player and p.Character then
                local pr = p.Character:FindFirstChild("HumanoidRootPart")
                if pr then
                    wanted[pr] = { Color3.fromRGB(90, 160, 240), p.Name }
                end
            end
        end
    end

    for part in pairs(espLive) do
        if not wanted[part] then clearOne(part) end
    end
    for part, info in pairs(wanted) do
        addOne(part, info[1], info[2])
    end
end

local function clearESP()
    for part in pairs(espLive) do clearOne(part) end
    table.clear(espLive)
    for part in pairs(tracerLines) do clearTracer(part) end
end

task.spawn(function()
    while gui.Parent do
        if State.tracers and Drawing then
            local r = root()
            if r then
                local vp = camera.ViewportSize
                for part, d in pairs(tracerLines) do
                    if part.Parent then
                        local sp, on = camera:WorldToViewportPoint(part.Position)
                        if on then
                            d.From = Vector2.new(vp.X / 2, vp.Y)
                            d.To = Vector2.new(sp.X, sp.Y)
                            d.Visible = true
                        else
                            d.Visible = false
                        end
                    else
                        pcall(function() d:Remove() end)
                        tracerLines[part] = nil
                    end
                end
            end
            task.wait(0.03)
        else
            task.wait(0.2)
        end
    end
end)

-- ============================================================
-- MAIN LOOP
-- ============================================================
local function startLoop()
    if loopRunning then return end
    loopRunning = true
    task.spawn(function()
        local beat = 0
        while loopRunning do
            beat += 1

            if State.autoSteal then pcall(doSteal) end
            if beat % 2 == 0 and State.autoHatch then pcall(doHatch) end
            if beat % 3 == 0 and State.autoPlace then pcall(doPlace) end
            if beat % 4 == 0 and State.autoCollect then pcall(doCollect) end
            if beat % 5 == 0 and State.autoSell then pcall(doSell) end
            if beat % 6 == 0 and State.autoDeposit then pcall(doDeposit) end
            if beat % 7 == 0 and State.autoBuy then pcall(doBuy) end
            if beat % 8 == 0 and State.autoMerge then pcall(doMerge) end
            if beat % 12 == 0 and State.autoRift then pcall(doRift) end
            if beat % 20 == 0 and State.autoRebirth then pcall(doRebirth) end
            if beat % 30 == 0 and State.autoDaily then pcall(doDaily) end

            if State.speedHack then
                local h = hum()
                if h then
                    local s = State.walkSpeed
                    if AC.speedClamp then s = math.min(s, AC.clampMax) end
                    h.WalkSpeed = s
                end
            end

            if AC.antiTrap then
                local r = root()
                if r and r.Position.Y < -400 then
                    AC.trapCount += 1
                    r.CFrame = CFrame.new(0, 80, 0)
                end
            end

            local wait = 0.12
            if AC.jitter then wait = wait * (0.75 + math.random() * 0.5) end
            task.wait(wait)
        end
    end)
end

track(player.Idled:Connect(function()
    if not AC.antiAfk then return end
    pcall(function()
        VirtualUser:CaptureController()
        VirtualUser:ClickButton2(Vector2.new())
    end)
end))

task.spawn(function()
    while gui.Parent do
        if State.noclip then
            local c = char()
            if c then
                for _, p in ipairs(c:GetDescendants()) do
                    if p:IsA("BasePart") and p.CanCollide then p.CanCollide = false end
                end
            end
        end
        if State.godMode then
            local h = hum()
            if h then h.MaxHealth = math.huge h.Health = math.huge end
        end
        task.wait(0.25)
    end
end)

-- ============================================================
-- BUILD UI
-- ============================================================
makeTab("Farm")
makeTab("Visuals")
makeTab("Movement")
makeTab("Stealth")
makeTab("Misc")

local farm = pages.Farm
local vis = pages.Visuals
local move = pages.Movement
local stl = pages.Stealth
local misc = pages.Misc

-- FARM
section(farm, "Egg Automation")
local c1 = card(farm)
toggle(c1, "Auto Steal Egg", "autoSteal", function(on)
    if on then startLoop() end
end)
toggle(c1, "Instant Steal (teleports)", "instantSteal")
toggle(c1, "Notify On Rare Egg", "eggNotify")

section(farm, "Filters")
local c2 = card(farm)
dropdown(c2, "Min Rarity To Steal", {
    "Any", "Common", "Uncommon", "Rare", "Epic", "Legendary",
    "Mythic", "Cosmic", "Secret", "Eternal", "Divine",
}, "minRarity")
dropdown(c2, "Notify At Rarity", {
    "Common", "Uncommon", "Rare", "Epic", "Legendary",
    "Mythic", "Cosmic", "Secret", "Eternal", "Divine",
}, "notifyRarity")
dropdown(c2, "Target Priority", { "Nearest", "Farthest" }, "priority")
slider(c2, "Steal Range", "stealRange", 50, 2000, " studs")

section(farm, "Other Automation")
local c3 = card(farm)
toggle(c3, "Auto Hatch", "autoHatch", function(on)
    if on then startLoop() end
end)
toggle(c3, "Auto Place", "autoPlace", function(on)
    if on then startLoop() end
end)
toggle(c3, "Auto Collect Reward", "autoCollect", function(on)
    if on then startLoop() end
end)
toggle(c3, "Auto Sell", "autoSell", function(on)
    if on then startLoop() end
end)
toggle(c3, "Auto Deposit", "autoDeposit", function(on)
    if on then startLoop() end
end)
toggle(c3, "Auto Buy", "autoBuy", function(on)
    if on then startLoop() end
end)
toggle(c3, "Auto Merge", "autoMerge", function(on)
    if on then startLoop() end
end)
toggle(c3, "Auto Rift Sacrifice", "autoRift", function(on)
    if on then startLoop() end
end)
toggle(c3, "Auto Rebirth", "autoRebirth", function(on)
    if on then startLoop() end
end)
toggle(c3, "Auto Daily Claim", "autoDaily", function(on)
    if on then startLoop() end
end)

section(farm, "One Shot")
local c4 = card(farm)
button(c4, "Steal Nearest Now", doSteal, CFG.accent)
button(c4, "Hatch All", doHatch)
button(c4, "Collect Rewards", doCollect)
button(c4, "Sell All", doSell)
button(c4, "Deposit All", doDeposit)

-- VISUALS
section(vis, "ESP")
local v1 = card(vis)
dropdown(v1, "Render Mode", { "Highlight", "Box" }, "espMode", function()
    clearESP()
    syncESP()
end)
toggle(v1, "Egg ESP", "eggESP", syncESP)
toggle(v1, "Player ESP", "playerESP", syncESP)
toggle(v1, "Tracer Lines", "tracers", function(on)
    if not on then
        for part in pairs(tracerLines) do clearTracer(part) end
    end
end)
toggle(v1, "Distance Labels", "distLabels", syncESP)
button(v1, "Refresh ESP", syncESP)
button(v1, "Clear ESP", clearESP)

section(vis, "World")
local v2 = card(vis)
toggle(v2, "Fullbright", "fullbright", applyFullbright)

section(vis, "Survival")
local v3 = card(vis)
toggle(v3, "God Mode", "godMode", applyGod)

-- MOVEMENT
section(move, "Speed")
local m1 = card(move)
toggle(m1, "Speed Hack", "speedHack", function(on)
    if on then startLoop() end
    local h = hum()
    if h and not on then h.WalkSpeed = 16 end
end)
slider(m1, "Walk Speed", "walkSpeed", 16, 500)

section(move, "Flight")
local m2 = card(move)
toggle(m2, "Fly", "fly", function(on)
    if on then startFly() else stopFly() end
end)
slider(m2, "Fly Speed", "flySpeed", 20, 500)
toggle(m2, "Noclip", "noclip", function(on)
    if not on then
        local c = char()
        if c then
            for _, p in ipairs(c:GetDescendants()) do
                if p:IsA("BasePart") then p.CanCollide = true end
            end
        end
    end
end)
toggle(m2, "Infinite Jump", "infJump")

section(move, "Teleport")
local m3 = card(move)
dropdown(m3, "Biome", BIOMES, "biome")
button(m3, "Go To Biome", function()
    if State.biome == "None" then return toast("Pick a biome first", CFG.warn) end
    local found
    for _, o in ipairs(workspace:GetDescendants()) do
        if (o:IsA("Model") or o:IsA("BasePart"))
            and o.Name:lower():find(State.biome:lower(), 1, true) then
            found = o:IsA("BasePart") and o or o:FindFirstChildWhichIsA("BasePart")
            if found then break end
        end
    end
    if found then
        smoothTP(found.CFrame + Vector3.new(0, 10, 0))
        toast("Moved to " .. State.biome, CFG.ok)
    else
        toast(State.biome .. " not found here", CFG.warn)
    end
end)
button(m3, "Go To Spawn", function()
    local sp = workspace:FindFirstChild("SpawnLocation")
    if sp then smoothTP(sp.CFrame + Vector3.new(0, 6, 0)) end
end)

-- STEALTH
section(stl, "Detection Layers")
local s1 = card(stl)
toggle(s1, "Anti Rubberband", "rubberband", setStatus, AC)
toggle(s1, "Humanoid State Guard", "stateGuard", setStatus, AC)
toggle(s1, "Speed Clamp", "speedClamp", setStatus, AC)
toggle(s1, "Anti Trap", "antiTrap", setStatus, AC)
toggle(s1, "Anti Ragdoll", "antiRagdoll", setStatus, AC)
toggle(s1, "Remote Throttle", "throttle", setStatus, AC)
toggle(s1, "Timing Jitter", "jitter", setStatus, AC)
toggle(s1, "Smooth Teleport", "smoothTP", setStatus, AC)
toggle(s1, "Network Ownership", "netOwner", setStatus, AC)
toggle(s1, "Anti AFK", "antiAfk", setStatus, AC)

section(stl, "Footprint")
local s2 = card(stl)
toggle(s2, "Random Instance Names", "randomNames", setStatus, AC)
toggle(s2, "CoreGui Parenting", "coreGui", function()
    pcall(function() gui.Parent = resolveParent() end)
    if not gui.Parent then gui.Parent = playerGui end
    setStatus()
end, AC)

section(stl, "Tuning")
local s3 = card(stl)
slider(s3, "Clamp Max Speed", "clampMax", 40, 500, "", AC)
slider(s3, "Throttle", "throttleMs", 20, 400, "ms", AC)
slider(s3, "Egg Cache TTL", "cacheTTL", 0.2, 4, "s")

section(stl, "Counters")
local s4 = card(stl)
local rbLabel = label(s4, "Rubberbands corrected: 0", 18)
local tpLabel = label(s4, "Trap rescues: 0", 18)

task.spawn(function()
    while gui.Parent do
        rbLabel.Text = "Rubberbands corrected: " .. AC.rbCount
        tpLabel.Text = "Trap rescues: " .. AC.trapCount
        task.wait(0.4)
    end
end)

section(stl, "Reading The Score")
local s5 = card(stl)
label(s5, "The header counts active layers. 9 or more reads STEALTH, 5 to 8 reads GUARDED, under 5 reads EXPOSED.\n\nOnly switch a layer off if it is actively fighting the game, then put it back once you move somewhere else.", 84)

-- MISC
section(misc, "Server")
local x1 = card(misc)
button(x1, "Server Hop (lowest ping)", function()
    local best, bestPing = nil, math.huge
    local ok, data = pcall(function()
        local url = "https://games.roblox.com/v1/games/" .. game.PlaceId
            .. "/servers/Public?sortOrder=Asc&limit=100"
        return HttpService:JSONDecode(game:HttpGet(url))
    end)
    if ok and data and data.data then
        for _, s in ipairs(data.data) do
            if s.playing < s.maxPlayers and s.id ~= game.JobId
                and (s.ping or 999) < bestPing then
                best, bestPing = s.id, s.ping or 999
            end
        end
    end
    if best then
        TeleportService:TeleportToPlaceInstance(game.PlaceId, best, player)
    else
        toast("No server found, rejoining", CFG.warn)
        TeleportService:Teleport(game.PlaceId, player)
    end
end)
button(x1, "Rejoin", function()
    TeleportService:Teleport(game.PlaceId, player)
end)
button(x1, "Copy Job ID", function()
    if setclipboard then
        pcall(function() setclipboard(game.JobId) end)
        toast("Job ID copied", CFG.ok)
    else
        toast(game.JobId, CFG.dim)
    end
end)

section(misc, "Interface")
local x2 = card(misc)
button(x2, "Reset Window", function()
    main.Position = UDim2.new(0.5, -300, 0.5, -230)
    main.Size = UDim2.new(0, 600, 0, 460)
    toast("Window reset", CFG.ok)
end)
button(x2, "Save Settings", function()
    if not writefile then return toast("No file API on this executor", CFG.warn) end
    local dump = HttpService:JSONEncode({ state = State, ac = AC })
    pcall(function() writefile("chilli_sae.json", dump) end)
    toast("Settings saved", CFG.ok)
end)
button(x2, "Load Settings", function()
    if not (readfile and isfile) then return toast("No file API on this executor", CFG.warn) end
    local ok, raw = pcall(function()
        if isfile("chilli_sae.json") then return readfile("chilli_sae.json") end
    end)
    if not ok or not raw then return toast("No saved file", CFG.warn) end
    local dec, data = pcall(function() return HttpService:JSONDecode(raw) end)
    if not dec or not data then return toast("File unreadable", CFG.bad) end
    for k, v in pairs(data.state or {}) do
        if State[k] ~= nil and type(v) == type(State[k]) then State[k] = v end
    end
    for k, v in pairs(data.ac or {}) do
        if AC[k] ~= nil and type(v) == type(AC[k]) then AC[k] = v end
    end
    for _, r in pairs(renderers) do pcall(r) end
    setStatus()
    toast("Settings loaded", CFG.ok)
end)

section(misc, "Maintenance")
local x3 = card(misc)
button(x3, "Rebuild Remote Index", function()
    buildRemoteIndex()
    local n = 0
    for _ in pairs(remoteIndex) do n += 1 end
    toast("Indexed " .. n .. " remote names", CFG.ok)
end)
button(x3, "Drop Egg Cache", function()
    table.clear(eggCache)
    eggCacheAt = 0
    toast("Egg cache cleared", CFG.ok)
end)

section(misc, "Panic")
local x4 = card(misc)
button(x4, "Disable Everything", function()
    for k, v in pairs(State) do
        if type(v) == "boolean" and v then
            State[k] = false
            local r = renderers[k]
            if r then pcall(r) end
        end
    end
    loopRunning = false
    stopFly()
    clearESP()
    local h = hum()
    if h then
        h.WalkSpeed = 16
        h.MaxHealth = 100
        h.Health = 100
    end
    toast("All features off, layers kept", CFG.warn)
end, CFG.warn)

section(misc, "Info")
local x5 = card(misc)
label(x5, "Right Shift toggles the menu. End is panic.\nWASD plus Space and Left Shift while flying.\nThe orb reopens the menu if you close it.", 60)

selectTab("Farm")

-- ============================================================
-- ORB
-- ============================================================
local orb = Instance.new("TextButton")
orb.Size = UDim2.new(0, 44, 0, 44)
orb.Position = UDim2.new(0, 20, 0.5, -22)
orb.BackgroundColor3 = CFG.accent
orb.Text = "C"
orb.TextColor3 = Color3.new(1, 1, 1)
orb.Font = Enum.Font.GothamBold
orb.TextSize = 16
orb.Visible = false
orb.ZIndex = 40
orb.Parent = gui
corner(orb, 22)
stroke(orb, Color3.new(1, 1, 1), 0.6)

local orbDrag, orbStart, orbPos = false, nil, nil
orb.InputBegan:Connect(function(i)
    if i.UserInputType == Enum.UserInputType.MouseButton1
        or i.UserInputType == Enum.UserInputType.Touch then
        orbDrag = true
        orbStart = i.Position
        orbPos = orb.Position
    end
end)
UserInputService.InputChanged:Connect(function(i)
    if not orbDrag then return end
    if i.UserInputType == Enum.UserInputType.MouseMovement
        or i.UserInputType == Enum.UserInputType.Touch then
        local d = i.Position - orbStart
        if d.Magnitude > 4 then
            orb.Position = UDim2.new(
                orbPos.X.Scale, orbPos.X.Offset + d.X,
                orbPos.Y.Scale, orbPos.Y.Offset + d.Y)
        end
    end
end)
UserInputService.InputEnded:Connect(function(i)
    if i.UserInputType == Enum.UserInputType.MouseButton1
        or i.UserInputType == Enum.UserInputType.Touch then
        orbDrag = false
    end
end)

-- ============================================================
-- VISIBILITY  (single owner)
-- ============================================================
local function showMenu()
    gui.Enabled = true
    main.Visible = true
    orb.Visible = false
end

local function hideMenu()
    main.Visible = false
    orb.Visible = true
end

orb.MouseButton1Click:Connect(showMenu)
minBtn.MouseButton1Click:Connect(hideMenu)
closeBtn.MouseButton1Click:Connect(hideMenu)

local function panic()
    for k, v in pairs(State) do
        if type(v) == "boolean" and v then
            State[k] = false
            local r = renderers[k]
            if r then pcall(r) end
        end
    end
    loopRunning = false
    stopFly()
    clearESP()
    local h = hum()
    if h then
        h.WalkSpeed = 16
        h.MaxHealth = 100
        h.Health = 100
    end
    toast("Panic: everything off", CFG.bad)
end

UserInputService.InputBegan:Connect(function(input, processed)
    if processed then return end
    if input.KeyCode == Enum.KeyCode.RightShift then
        if main.Visible then hideMenu() else showMenu() end
    elseif input.KeyCode == Enum.KeyCode.End then
        panic()
    end
end)

UserInputService.JumpRequest:Connect(function()
    if not State.infJump then return end
    local h = hum()
    if h then
        h:ChangeState(Enum.HumanoidStateType.Jumping)
    end
end)

-- ============================================================
-- LOOPS
-- ============================================================
task.spawn(function()
    while gui.Parent do
        if State.eggESP or State.playerESP then
            syncESP()
            task.wait(0.6)
        else
            task.wait(0.8)
        end
    end
end)

task.spawn(function()
    while gui.Parent do
        if State.freeze then
            local r = root()
            if r then r.Anchored = true end
        else
            local r = root()
            if r and r.Anchored and not State.fly then r.Anchored = false end
        end
        task.wait(0.2)
    end
end)

-- ============================================================
-- LIFECYCLE
-- ============================================================
player.CharacterAdded:Connect(function()
    gen += 1
    untrackAll()
    if State.fly then
        State.fly = false
        local r = renderers.fly
        if r then pcall(r) end
    end
    stopFly()
    clearESP()
    table.clear(eggCache)
    eggCacheAt = 0
    task.wait(1.2)
    buildRemoteIndex()
    if State.autoSteal then startLoop() end
    setStatus()
end)

player.CharacterRemoving:Connect(function()
    gen += 1
    untrackAll()
    stopFly()
    clearESP()
end)

-- ============================================================
-- BOOT
-- ============================================================
buildRemoteIndex()
setStatus()
showMenu()
toast("Chilli Hub loaded", CFG.accent)
notify("Chilli Hub", "Right Shift toggles the menu.")