Potential Causes of Slow Loading
Excessive Waiting in Loops: The waitForChildRecursive function uses a task.wait(0.5) inside a loop, which can introduce significant delays if the child objects are not immediately available.
Waiting for Game Elements: The script waits for the game to be fully loaded and for specific elements to be present before proceeding. This can cause delays if those elements take time to load.
Synchronous Loading of External Resources: Loading external resources synchronously (like the Rayfield GUI) can block the script execution until the resource is fully loaded.
Initialization of Multiple Features: The script initializes and sets up multiple features and loops even before the user interacts with the UI. This can add to the load time.
Optimization Suggestions
Reduce Wait Durations:
Modify waitForChildRecursive: Decrease the wait time inside the loop to make it check for the child more frequently.

function waitForChildRecursive(parent, childName, timeout)
    local startTime = tick()
    local child = parent:FindFirstChild(childName)
    while not child do
        if tick() - startTime > timeout then
            return nil
        end
        task.wait(0.1) -- Reduced from 0.5 to 0.1 seconds
        child = parent:FindFirstChild(childName)
    end
    return child
end
Check for Immediate Availability: If certain services or elements are usually available immediately, consider using FindFirstChild with a shorter wait duration or remove the wait if possible.
Load the UI First:
Reorder Your Code: Initialize and display the UI elements before running any feature initialization or loops. This way, the user interface appears promptly, and any background processes can load afterward.
Lazy Initialization: Only initialize certain features when the user enables them via the UI. This avoids unnecessary setup for features the user might not use.
Asynchronous Loading of External Resources:
Load Rayfield GUI Asynchronously:

-- Load Rayfield GUI asynchronously
local Rayfield
task.spawn(function()
    Rayfield = loadstring(game:HttpGet('https://sirius.menu/rayfield'))()
end)
Ensure that the UI waits for Rayfield to be available before proceeding to create windows or tabs.
Avoid Unnecessary Global Loops:
Review the loops that run regardless of user interaction (e.g., loops that check for certain game objects). Ensure they only start if the corresponding feature is enabled.
Debug and Profile the Script:
Print Statements: Add print statements at key points in your script to identify where delays are occurring.
Performance Profiling: Use Roblox's microprofiler to check which parts of the script take the most time to execute.
Optimizing Feature Initialization:
For features like Auto Quest, Level Farm, Insta Kill, etc., ensure that their loops or heavy computations only start when the user enables them via the UI.
Revised Sections of the Script
Here's how you can implement some of these optimizations:

Initialize UI Before Other Operations: Move the UI creation code to the top, right after ensuring the game is loaded:

-- Ensure the game is loaded
repeat task.wait() until game:IsLoaded()

-- Load Rayfield GUI
local Rayfield = loadstring(game:HttpGet('https://sirius.menu/rayfield'))()

-- Create Rayfield window and tabs
local Window = Rayfield:CreateWindow({ ... })
local MainTab = Window:CreateTab("Main", "Home")
-- ... Other tabs ...

-- Now proceed with the rest of your script
Feature Activation After User Interaction: For example, in your Auto Quest feature:

MainTab:CreateToggle({
    Name = "Auto Quest",
    CurrentValue = false,
    Flag = "AutoQuest",
    Callback = function(Value)
        getgenv().AutoQuest = Value
        if Value then
            -- Start the Auto Quest loop only when enabled
            task.spawn(function()
                while getgenv().AutoQuest do
                    -- Auto Quest logic
                    task.wait(0.5)
                end
            end)
        end
    end,
})
Remove or Optimize Unnecessary Waits: Review all loops and functions for unnecessary task.wait() calls. For example:

-- Before optimization
while condition do
    -- Logic
    task.wait(1)
end

-- After optimization (if possible)
while condition do
    -- Logic
    task.wait() -- Or a shorter wait if necessary
end
Summary
By restructuring your script to load the UI first, reducing wait times, and initializing features only when needed, you should see a significant improvement in the loading time.

Final Note
Ensure to test the updated script thoroughly to confirm that all features still work as intended after the optimizations.

сделай это всё 
-- Ensure the game is loaded
repeat task.wait() until game:IsLoaded()

-- Load Rayfield GUI
local Rayfield = loadstring(game:HttpGet('https://sirius.menu/rayfield'))()

-- Global raknet object for caching services and other data
getgenv().raknet = {
    services = {},
    cache = {}
}

-- Function to clone reference (if needed)
local cloneref = cloneref or function(ref)
    return ref
end

-- Recursive WaitForChild function with timeout
function waitForChildRecursive(parent, childName, timeout)
    local startTime = tick()
    local child = parent:FindFirstChild(childName)
    while not child do
        if tick() - startTime > timeout then
            return nil
        end
        task.wait(0.5)
        child = parent:FindFirstChild(childName)
    end
    return child
end

-- raknet functions to get services and other objects
function raknet:GetService(serviceName)
    if self.cache[serviceName] then
        return self.cache[serviceName]
    end
    local service = cloneref(game:GetService(serviceName))
    self.cache[serviceName] = service
    return service
end

function raknet:GetLocalPlayer()
    return self:GetService("Players").LocalPlayer
end

function raknet:GetReplicatedStorage()
    return self:GetService("ReplicatedStorage")
end

function raknet:GetSkills()
    local ReplicatedStorage = self:GetReplicatedStorage()
    return ReplicatedStorage:FindFirstChild("Skills") or ReplicatedStorage:WaitForChild("Skills")
end

function raknet:GetCharacter()
    local player = self:GetLocalPlayer()
    return player.Character or player.CharacterAdded:Wait()
end

function raknet:GetPrimaryPart()
    return self:GetCharacter():FindFirstChild("HumanoidRootPart")
end

function raknet:GetHumanoid()
    return self:GetCharacter():FindFirstChildOfClass("Humanoid")
end

function raknet:SendHumanoidPropertyChangePacket(property, value)
    local humanoid = self:GetHumanoid()
    if humanoid and humanoid[property] ~= nil then
        humanoid[property] = value
    end
end

function raknet:GetFolder(path, timeout)
    local current = workspace
    for _, folderName in ipairs(path) do
        current = waitForChildRecursive(current, folderName, timeout or 10)
        if not current then
            return nil
        end
    end
    return current
end

function raknet:GetMobs()
    return self:GetFolder({"Objects", "Mobs"}, 30)
end

function raknet:GetDrops()
    return self:GetFolder({"Objects", "Drops"}, 30)
end

function raknet:GetMissionItems()
    return self:GetFolder({"Objects", "MissionItems"}, 30)
end

function raknet:GetMissions()
    return self:GetFolder({"Objects", "Locations", "Missions", "Shijo Town Set"}, 30)
end

function raknet:OnRenderStep(name, callback)
    if typeof(callback) ~= "function" then
        return
    end
    self:GetService("RunService").RenderStepped:Connect(callback)
end

function raknet:GetRemote(path)
    local replicatedStorage = self:GetReplicatedStorage()
    local current = replicatedStorage
    for _, part in ipairs(path) do
        current = current:FindFirstChild(part)
        if not current then
            warn("Remote not found at path:", table.concat(path, "/"))
            return nil
        end
    end
    return current
end

function raknet:EquipItem(itemName)
    local equipItemRemote = self:GetRemote({"Remotes", "Server", "Data", "EquipItem"})
    if equipItemRemote then
        local args = { [1] = itemName }
        local success, response = pcall(function()
            return equipItemRemote:InvokeServer(unpack(args))
        end)
        if not success then
            warn("Failed to equip item:", response)
        else
            print("Item equipped:", itemName)
        end
    else
        warn("EquipItem Remote not found.")
    end
end

-- Get VirtualInputManager for simulating key presses
local VirtualInputManager = game:GetService("VirtualInputManager")
if not VirtualInputManager then
    warn("VirtualInputManager not found. Some functions may not work.")
end

-- Processed objects table for tracking
local processedObjects = {}

-- Get local player
local player = raknet:GetLocalPlayer()

-- Create Rayfield window
local Window = Rayfield:CreateWindow({
    Name = "Prime Hub JJI",
    Icon = "user-round",
    LoadingTitle = "Prime Hub",
    LoadingSubtitle = "Loading...",
    Theme = "AmberGlow",
    DisableRayfieldPrompts = false,
    DisableBuildWarnings = false,
    ConfigurationSaving = {
        Enabled = true,
        FolderName = "Prime Hub",
        FileName = "JJI"
    },
    Discord = {
        Enabled = true,
        Invite = "primeh",
        RememberJoins = true
    },
})

if game.PlaceId == 119359147980471 or 78904562518018 then
    raknet:GetLocalPlayer().ReplicatedData.level.Value = math.huge
end

-- Create tabs
local MainTab = Window:CreateTab("Main", "Home")
local SpinTab = Window:CreateTab("Auto Spin", "refresh-cw")
local StuffTab = Window:CreateTab("Stuff", "box")
local Lobby = Window:CreateTab("Lobby", "archive")  -- New Tab for the additional script
local InvestTab = Window:CreateTab("Investigate", "activity")
local BossTab = Window:CreateTab("Boss", "star")
local WebhookTab = Window:CreateTab("Webhook", "bell")

-- Auto Quest Toggle
MainTab:CreateToggle({
    Name = "Auto Quest",
    CurrentValue = false,
    Flag = "AutoQuest",
    Callback = function(Value)
        getgenv().AutoQuest = Value
        if Value then
            if not getgenv().AutoQuestLoop then
                getgenv().AutoQuestLoop = true
                task.spawn(function()
                    while getgenv().AutoQuestLoop do
                        local success, err = pcall(function()
                            raknet:GetReplicatedStorage().Remotes.Server.Data.CancelQuest:FireServer()
                        end)
                        if not success then
                            warn("Failed to cancel quest:", err)
                        end
                        task.wait(0.5)
                        local questDetails = {
                            ["type"] = "https://discord.gg/primeh",
                            ["set"] = "The best keyless script",
                            ["rewards"] = {
                                ["essence"] = 40,
                                ["chestMeter"] = 79,
                                ["exp"] = 8850000,
                                ["cash"] = 51000
                            },
                            ["rewardsText"] = "Prime Hub On Top",
                            ["difficulty"] = 3,
                            ["title"] = "Get good get primehub premium",
                            ["level"] = 430,
                            ["grade"] = "Non Sorcerer",
                            ["subtitle"] = "a Curse User"
                        }
                        local questSuccess, response = pcall(function()
                            return raknet:GetReplicatedStorage().Remotes.Server.Data.AcceptQuest:InvokeServer(questDetails)
                        end)
                        if questSuccess and response then
                            local function teleportToQuestMarker()
                                local questMarkerGui = player.PlayerGui:FindFirstChild("QuestMarker")
                                if questMarkerGui and questMarkerGui:IsA("BillboardGui") then
                                    local adornee = questMarkerGui.Adornee
                                    if adornee and adornee:IsA("BasePart") then
                                        local hrp = raknet:GetPrimaryPart()
                                        if hrp then
                                            hrp.CFrame = adornee.CFrame
                                        end
                                    end
                                end
                            end
                            teleportToQuestMarker()
                            while player.PlayerGui:FindFirstChild("QuestMarker") and getgenv().AutoQuestLoop do
                                task.wait(7)
                            end
                        end
                    end
                end)
            end
        else
            getgenv().AutoQuestLoop = false
            local success, err = pcall(function()
                raknet:GetReplicatedStorage().Remotes.Server.Data.CancelQuest:FireServer()
            end)
            if not success then
                warn("Failed to cancel quest:", err)
            end
        end
    end,
})

-- Level Farm Toggle
MainTab:CreateToggle({
    Name = "Lvl Farm",
    CurrentValue = false,
    Flag = "LvlFarm",
    Callback = function(Value)
        getgenv().LvlFarm = Value

        wait(4)
        
        local queueteleport = syn and syn.queue_on_teleport or queue_on_teleport or fluxus and fluxus.queue_on_teleport
        if queueteleport then
            queueteleport("loadstring(game:HttpGet('https://api.luarmor.net/files/v3/loaders/477e4aaa08ec18ddbf1192bc63eea97a.lua'))()")
        end
        
        if getgenv().LvlFarm then
            if game.PlaceId == 10450270085 then
                repeat task.wait() until game:IsLoaded()
                game:GetService("TeleportService"):Teleport(119359147980471, game.Players.LocalPlayer)
                
            elseif game.PlaceId == 119359147980471 then
                repeat task.wait() until game:IsLoaded()
                local replicatedData = game.Players.LocalPlayer:FindFirstChild("ReplicatedData")
                if replicatedData and replicatedData:FindFirstChild("level") then
                    replicatedData.level.Value = math.huge
                end
                game.ReplicatedStorage.Remotes.Server.Raids.CreateLobby:InvokeServer("Boss", "Heian Imaginary Demon", "Nightmare", "")
                task.wait(1)
                game.ReplicatedStorage.Remotes.Server.Raids.StartLobby:InvokeServer("Boss")
                
            elseif game.PlaceId == 16379688837 then
                local function pressReplay()
                    while getgenv().LvlFarm do
                        local ReadyScreen = game.Players.LocalPlayer.PlayerGui:FindFirstChild("ReadyScreen")
                        if ReadyScreen and ReadyScreen.Enabled then
                            local xi = ReadyScreen:FindFirstChild("Frame")
                            local ReplayButton = xi and xi:FindFirstChild("Replay")
                            if ReplayButton and ReplayButton:IsA("GuiButton") then
                                game.VirtualInputManager:SendKeyEvent(true, Enum.KeyCode.BackSlash, false, game)
                                task.wait(0.2)
                                game.VirtualInputManager:SendKeyEvent(true, Enum.KeyCode.Return, false, game)
                                task.wait(0.1)
                                game.VirtualInputManager:SendKeyEvent(false, Enum.KeyCode.Return, false, game)
                                task.wait(0.1)
                                game.VirtualInputManager:SendKeyEvent(true, Enum.KeyCode.BackSlash, false, game)
                                game.VirtualInputManager:SendKeyEvent(false, Enum.KeyCode.BackSlash, false, game)
                                if not ReadyScreen.Enabled then
                                    break
                                else
                                    print("Replay was not pressed. Continuing attempts.")
                                end
                            else
                                print("Replay button not found or incorrect type.")
                            end
                        end
                        task.wait(0.5)
                    end
                end
        
                local function killDemon()
                    while getgenv().LvlFarm do
                        local demon = game.Workspace.Objects and game.Workspace.Objects.Mobs and game.Workspace.Objects.Mobs:FindFirstChild("Heian Imaginary Demon")
                        if demon and demon:FindFirstChild("Humanoid") then
                            local humanoid = demon.Humanoid
                            local demonPos = demon:FindFirstChild("HumanoidRootPart") and demon.HumanoidRootPart.Position or nil
        
                            if demonPos then
                                game.Players.LocalPlayer.Character.HumanoidRootPart.CFrame = CFrame.new(demonPos)
                                humanoid.Health = 0
                            else
                                print("Failed to get demon position.")
                            end
                        else
                            print("Heian Imaginary Demon not found or missing Humanoid.")
                        end
                        task.wait(0.1)
                    end
                end
        
                local function teleportToBossSpawn()
                    while getgenv().LvlFarm do
                        local BossSpawn = game.Workspace.Objects.Spawns and game.Workspace.Objects.Spawns:FindFirstChild("BossSpawn")
                        if BossSpawn then
                            game.Players.LocalPlayer.Character.HumanoidRootPart.CFrame = CFrame.new(BossSpawn.Position)
                        else
                            print("BossSpawn not found.")
                        end
                        task.wait(0.1)
                    end
                end
        
                local function promote()
                    while getgenv().LvlFarm do
                        game.ReplicatedStorage.Remotes.Server.Dialogue.GetResponse:InvokeServer("Clan Head Jujutsu High", "Promote")
                        task.wait(0.1)
                    end
                end
                task.spawn(promote)
                task.spawn(pressReplay)
                task.spawn(killDemon)
                task.spawn(teleportToBossSpawn)
            end
        end        
    end,
})

-- Insta Kill Toggle
MainTab:CreateToggle({
    Name = "Insta Kill",
    CurrentValue = false,
    Flag = "InstaKill",
    Callback = function(Value)
        getgenv().InstaKill = Value
        if Value then
            if not getgenv().InstaKillLoop then
                getgenv().InstaKillLoop = true
                task.spawn(function()
                    while getgenv().InstaKillLoop do
                        pcall(function()
                            local mobs = raknet:GetMobs()
                            if mobs and mobs:IsA("Folder") then
                                for _, mob in ipairs(mobs:GetChildren()) do
                                    if mob:IsA("Model") and mob:FindFirstChildOfClass("Humanoid") then
                                        local humanoid = mob:FindFirstChildOfClass("Humanoid")
                                        if humanoid and humanoid.Health > 0 then
                                            if mob.Name == "Finger Bearer" then
                                                task.spawn(function()
                                                    task.wait(10)
                                                    if getgenv().InstaKill and humanoid.Health > 0 then
                                                        humanoid.Health = 0
                                                    end
                                                end)
                                            else
                                                humanoid.Health = 0
                                            end
                                        end
                                    end
                                end
                            else
                                warn("Mobs folder not found or is not a folder.")
                            end
                        end)
                        task.wait(1)
                    end
                end)
            end
        else
            getgenv().InstaKillLoop = false
        end
    end,
})

-- Auto Loot Toggle
MainTab:CreateToggle({
    Name = "Auto Loot",
    CurrentValue = false,
    Flag = "AutoLoot",
    Callback = function(Value)
        getgenv().AutoLoot = Value
        if Value then
            if not getgenv().AutoLootLoop then
                getgenv().AutoLootLoop = true
                task.spawn(function()
                    while getgenv().AutoLootLoop do
                        local dropsFolder = raknet:GetDrops()
                        if dropsFolder and dropsFolder:IsA("Folder") then
                            local chests = dropsFolder:GetChildren()
                            print("Chests found:", #chests)
                            for _, chest in ipairs(chests) do
                                if not getgenv().AutoLootLoop then break end
                                if chest.Name == "Chest" and chest:IsA("Model") then
                                    if not processedObjects[chest] then
                                        local chestPart = chest:FindFirstChild("HumanoidRootPart") or chest:FindFirstChildWhichIsA("BasePart")
                                        if not chestPart then
                                            warn("HumanoidRootPart or BasePart not found in Chest:", chest.Name)
                                        else
                                            local chestPosition = chestPart.Position + Vector3.new(0, 5, 0)
                                            local humanoidRootPart = raknet:GetPrimaryPart()
                                            if humanoidRootPart and humanoidRootPart:IsA("BasePart") then
                                                humanoidRootPart.CFrame = CFrame.new(chestPosition)
                                            else
                                                warn("HumanoidRootPart not found or is not a BasePart.")
                                            end
                                            if VirtualInputManager then
                                                VirtualInputManager:SendKeyEvent(true, Enum.KeyCode.E, false, game)
                                                task.wait(0.25)
                                                VirtualInputManager:SendKeyEvent(false, Enum.KeyCode.E, false, game)
                                            else
                                                warn("VirtualInputManager not available.")
                                            end
                                            local lootGui = player.PlayerGui and player.PlayerGui:FindFirstChild("Loot")
                                            if lootGui and lootGui:IsA("ScreenGui") and lootGui.Enabled then
                                                if VirtualInputManager then
                                                    VirtualInputManager:SendKeyEvent(true, Enum.KeyCode.BackSlash, false, game)
                                                    task.wait(0.2)
                                                    local lootFrame = lootGui:FindFirstChild("Frame")
                                                    if lootFrame and lootFrame:IsA("Frame") then
                                                        local targetElement = lootFrame:FindFirstChild("Flip")
                                                        if targetElement and targetElement:IsA("GuiObject") then
                                                            raknet:GetService("GuiService").SelectedObject = targetElement
                                                            print("Selected Flip element in Loot GUI.")
                                                            while lootGui.Enabled and getgenv().AutoLootLoop do
                                                                task.wait(0.1)
                                                                VirtualInputManager:SendKeyEvent(true, Enum.KeyCode.Return, false, game)
                                                                task.wait(0.1)
                                                                VirtualInputManager:SendKeyEvent(false, Enum.KeyCode.Return, false, game)
                                                                print("Pressed Return key to confirm loot.")
                                                            end
                                                        else
                                                            warn("Flip element not found in Loot GUI.")
                                                        end
                                                    else
                                                        warn("Frame not found in Loot GUI.")
                                                    end
                                                    VirtualInputManager:SendKeyEvent(true, Enum.KeyCode.BackSlash, false, game)
                                                    VirtualInputManager:SendKeyEvent(false, Enum.KeyCode.BackSlash, false, game)
                                                else
                                                    warn("VirtualInputManager not available.")
                                                end
                                            end
                                            processedObjects[chest] = true
                                        end
                                    end
                                end
                            end
                        else
                            warn("dropsFolder not found or is not a folder.")
                        end
                        task.wait(1)
                    end
                end)
            end
        else
            getgenv().AutoLootLoop = false
            processedObjects = {}
        end
    end,
})

-- Auto Collect Reward Toggle
MainTab:CreateToggle({
    Name = "Auto Collect Reward",
    CurrentValue = false,
    Flag = "AutoCollectReward",
    Callback = function(Value)
        getgenv().AutoCollectReward = Value
        if Value then
            if not getgenv().AutoCollectRewardLoop then
                getgenv().AutoCollectRewardLoop = true
                task.spawn(function()
                    while getgenv().AutoCollectRewardLoop do
                        local missionSets = {
                            "Shijo Town Set",
                            "Umi Town Set",
                            "Numa Temple Set",
                            "Kura Camp Set",
                            "Yuki Fortress Set"
                        }
                        for _, setName in ipairs(missionSets) do
                            if not getgenv().AutoCollectRewardLoop then break end
                            local chestMeterReward = raknet:GetRemote({"Remotes", "Server", "Data", "ChestMeterReward"})
                            if chestMeterReward then
                                chestMeterReward:FireServer(setName)
                            else
                                warn("ChestMeterReward Remote not found.")
                            end
                            task.wait(1.5)
                        end
                    end
                end)
            end
        else
            getgenv().AutoCollectRewardLoop = false
        end
    end,
})

-- Auto Promote Toggle
MainTab:CreateToggle({
    Name = "Auto Promote",
    CurrentValue = false,
    Flag = "AutoPromote",
    Callback = function(Value)
        getgenv().AutoPromote = Value
        if Value then
            if not getgenv().AutoPromoteLoop then
                getgenv().AutoPromoteLoop = true
                task.spawn(function()
                    while getgenv().AutoPromoteLoop do
                        local args = {
                            [1] = "Clan Head Jujutsu High",
                            [2] = "Promote"
                        }
                        local getResponseRemote = raknet:GetRemote({"Remotes", "Server", "Dialogue", "GetResponse"})
                        if getResponseRemote then
                            local success, response = pcall(function()
                                return getResponseRemote:InvokeServer(unpack(args))
                            end)
                            if not success then
                                warn("Failed to invoke GetResponse:", response)
                            end
                        else
                            warn("GetResponse Remote not found.")
                        end
                        task.wait(2)
                    end
                end)
            end
        else
            getgenv().AutoPromoteLoop = false
        end
    end,
})

-- Dropdown for selecting cats
local CatDropdown = MainTab:CreateDropdown({
    Name = "Select Cats",
    Options = {"Withered Beckoning Cat", "Wooden Beckoning Cat", "Polished Beckoning Cat", "Golden Beckoning Cat"},
    CurrentOption = {"Withered Beckoning Cat"},
    MultipleOptions = true,
    Flag = "CatDropdown",
    Callback = function(Options)
        getgenv().cat = Options
    end,
})

-- Autouse Cat Toggle
MainTab:CreateToggle({
    Name = "Autouse Cat",
    CurrentValue = false,
    Flag = "AutouseCat",
    Callback = function(Value)
        getgenv().Autousecat = Value
        if Value then
            if not getgenv().AutouseCatLoop then
                getgenv().AutouseCatLoop = true
                task.spawn(function()
                    while getgenv().AutouseCatLoop do
                        if getgenv().cat then
                            if type(getgenv().cat) == "table" then
                                for _, selectedCat in ipairs(getgenv().cat) do
                                    if getgenv().AutouseCatLoop and selectedCat and selectedCat ~= "" then
                                        raknet:EquipItem(selectedCat)
                                        task.wait(0.1)
                                    end
                                end
                            else
                                if getgenv().cat ~= "" then
                                    raknet:EquipItem(getgenv().cat)
                                else
                                    warn("Cat category not selected.")
                                end
                            end
                        else
                            warn("Cat category not selected.")
                        end
                        task.wait(5)
                    end
                end)
            end
        else
            getgenv().AutouseCatLoop = false
        end
    end,
})

-- ESP & Notifications Toggle
local EspToggle = MainTab:CreateToggle({
    Name = "ESP & Notifications",
    CurrentValue = false,
    Flag = "EspItems",
    Callback = function(Value)
        getgenv().esp = Value
        if Value then
            if not getgenv().EspLoop then
                getgenv().EspLoop = true
                local espObjects = {}
                local espConnection

                -- Function to get the primary part of an object
                local function getPrimaryPart(item)
                    if item:IsA("Model") then
                        return item.PrimaryPart or item:FindFirstChildWhichIsA("BasePart")
                    elseif item:IsA("BasePart") then
                        return item
                    end
                    return nil
                end

                -- Function to create ESP
                local function createESP(item, adornee)
                    local BillboardGui = Instance.new("BillboardGui")
                    local TextLabel = Instance.new("TextLabel")
                    BillboardGui.Name = "ESP"
                    BillboardGui.AlwaysOnTop = true
                    BillboardGui.Size = UDim2.new(0, 100, 0, 50)
                    BillboardGui.Adornee = adornee
                    BillboardGui.Parent = adornee
                    TextLabel.Parent = BillboardGui
                    TextLabel.Size = UDim2.new(1, 0, 1, 0)
                    TextLabel.BackgroundTransparency = 1
                    TextLabel.TextColor3 = Color3.new(1, 1, 1)
                    TextLabel.TextScaled = true
                    TextLabel.Font = Enum.Font.SourceSansBold
                    return {billboard = BillboardGui, textLabel = TextLabel}
                end

                -- Function to update ESP
                local function updateESP(item, guiTable, adornee)
                    local hrp = raknet:GetPrimaryPart()
                    if not hrp then return end
                    local distance = (hrp.Position - adornee.Position).Magnitude
                    guiTable.textLabel.Text = string.format("%s\n%.1f studs", item.Name, distance)
                end

                -- Function to handle new item
                local function onNewItem(item)
                    if item.Name == "Talisman" then
                        return
                    end
                    local adornee = getPrimaryPart(item)
                    if adornee and not espObjects[item] then
                        local guiTable = createESP(item, adornee)
                        espObjects[item] = {guiTable = guiTable, adornee = adornee}
                        updateESP(item, guiTable, adornee)
                        
                        -- Add notification
                        Rayfield:Notify({
                            Title = "Esp",
                            Content = string.format("Added new item: %s", item.Name),
                            Duration = 5,
                            Image = "bell"
                        })
                    end
                end

                -- Function to clear ESP
                local function clearESP()
                    for item, data in pairs(espObjects) do
                        local guiTable = data.guiTable
                        if guiTable then
                            guiTable.billboard:Destroy()
                        end
                    end
                    espObjects = {}
                end

                -- Function to start ESP
                local function startESP()
                    local drops = raknet:GetDrops()
                    if not drops then
                        warn("Drops folder not found in workspace -> Objects -> Drops")
                        return
                    end
                    if typeof(drops) ~= "Instance" or not drops:IsA("Folder") then
                        warn("Expected drops to be a Folder instance, got:", typeof(drops))
                        return
                    end
                    for _, item in ipairs(drops:GetChildren()) do
                        onNewItem(item)
                    end
                    espConnection = raknet:GetService("RunService").RenderStepped:Connect(function()
                        if not getgenv().esp then
                            clearESP()
                            if espConnection then
                                espConnection:Disconnect()
                                espConnection = nil
                            end
                            return
                        end
                        for item, data in pairs(espObjects) do
                            if data.adornee and data.guiTable then
                                updateESP(item, data.guiTable, data.adornee)
                            end
                        end
                    end)
                    drops.ChildAdded:Connect(function(newItem)
                        onNewItem(newItem)
                    end)
                end

                startESP()
            end
        else
            getgenv().EspLoop = false
            -- Clear ESP elements
            for _, data in pairs(processedObjects) do
                if data.guiTable and data.guiTable.billboard then
                    data.guiTable.billboard:Destroy()
                end
            end
            processedObjects = {}
        end
    end,
})

-- Button for No Cooldown for Xeno users
StuffTab:CreateButton({
    Name = "NoCd for xeno users",
    Callback = function()
        local args = {
            [1] = "0 COOLDOWN FOR DEBUGGING"
        }
        local combatSkillRemote = raknet:GetReplicatedStorage().Remotes.Server.Combat.Skill
        if combatSkillRemote then
            combatSkillRemote:FireServer(unpack(args))
            print("No cooldown activated for xeno users.")
        else
            warn("Combat Skill Remote not found.")
        end
    end
})

-- Variable for selected cursed tool
local cursedTool = nil

-- Dropdown for selecting cursed tools
local CursedToolsDropdown = StuffTab:CreateDropdown({
    Name = "Select Cursed Tools",
    Options = {
        "Heavenly Restriction", "Ravenous Axe", "Turbo Mask", "Heian Gauntlets",
        "Executioner Sword", "The Impossible Dream", "Inventory Curse", "Electric Staff",
        "Blood Sword", "Playful Cloud", "Vengeance", "Split Soul",
        "Inverted Spear of Heaven", "Viscera Scythe", "Feather Spear", "Dragon Bone"
    },
    CurrentOption = "Heavenly Restriction",
    MultipleOptions = false,
    Flag = "CursedTools",
    Callback = function(option)
        if typeof(option) == "table" then
            cursedTool = option[1] or ""
        else
            cursedTool = option or ""
        end
        print("Selected Cursed Tool:", cursedTool)
    end,
})

-- Button to set infinite level
StuffTab:CreateButton({
    Name = "Inf lvl",
    Callback = function()
        local replicatedData = player:FindFirstChild("ReplicatedData")
        if replicatedData then
            local level = replicatedData:FindFirstChild("level")
            if level then
                level.Value = math.huge
                print("Player level set to infinity.")
            else
                warn("Level object not found in ReplicatedData.")
            end
        else
            warn("ReplicatedData not found for player:", player.Name)
        end
    end
})

-- Button to give selected cursed tool
StuffTab:CreateButton({
    Name = "Give Selected Tool",
    Callback = function()
        if not cursedTool or cursedTool == "" then
            warn("No tool selected!")
            return
        end
        local newTool = Instance.new("Tool")
        if type(cursedTool) ~= "string" then
            warn("Unable to assign property Name. string expected, got", typeof(cursedTool))
            return
        end
        newTool.Name = cursedTool
        local handle = Instance.new("Part")
        handle.Name = "Handle"
        handle.Size = Vector3.new(1, 1, 1)
        handle.Parent = newTool
        local backpack = player:FindFirstChild("Backpack")
        if backpack then
            newTool.Parent = backpack
            print("Tool given:", cursedTool)
        else
            warn("Backpack not found for player:", player.Name)
        end
    end
})

-- Dropdown for selecting spin slot
local SpinSlotDropdown = SpinTab:CreateDropdown({
    Name = "Select Spin Slot",
    Options = {"1","2","3","4"},
    CurrentOption = "1",
    MultipleOptions = false,
    Flag = "SpinSlotDropdown",
    Callback = function(Option)
        if typeof(Option) == "table" then
            getgenv().Spinslot = Option[1] or "1"
        else
            getgenv().Spinslot = Option
        end
        print("Selected Spin Slot:", getgenv().Spinslot)
    end,
})

-- Lists for legendary and special techniques
local legendary = {"Volcano", "Hydrokinesis", "Judgeman"}
local specialGrade = {"Infinity", "Demon Vessel", "Curse Queen", "Soul Manipulation", "Gambler Fever", "Star Rage"}

-- Dropdown for selecting legendary techniques
local LegendaryDropdown = SpinTab:CreateDropdown({
    Name = "Legendary technique",
    Options = legendary,
    CurrentOption = "Volcano",
    MultipleOptions = true,
    Flag = "LegendaryDropdown",
    Callback = function(Options)
        getgenv().LegendaryDropdown = Options
        print("Selected Legendary Techniques:", table.concat(getgenv().LegendaryDropdown, ", "))
    end,
})

-- Dropdown for selecting special techniques
local SpecialDropdown = SpinTab:CreateDropdown({
    Name = "Special technique",
    Options = specialGrade,
    CurrentOption = "Infinity",
    MultipleOptions = true,
    Flag = "SpecialDropdown",
    Callback = function(Options)
        getgenv().SpecialDropdown = Options
        print("Selected Special Techniques:", table.concat(getgenv().SpecialDropdown, ", "))
    end,
})

-- Auto Spin Toggle
local AutoSpinToggle = SpinTab:CreateToggle({
    Name = "Auto spin selected slot",
    CurrentValue = false,
    Flag = "Autospin",
    Callback = function(Value)
        getgenv().autospin = Value
        if Value then
            if not getgenv().AutoSpinLoop then
                getgenv().AutoSpinLoop = true
                task.spawn(function()
                    while getgenv().AutoSpinLoop do
                        local desiredTechniques = {}
                        if getgenv().LegendaryDropdown then
                            for _, v in ipairs(getgenv().LegendaryDropdown) do
                                if v then
                                    table.insert(desiredTechniques, v)
                                end
                            end
                        end
                        if getgenv().SpecialDropdown then
                            for _, v in ipairs(getgenv().SpecialDropdown) do
                                if v then
                                    table.insert(desiredTechniques, v)
                                end
                            end
                        end

                        local function isDesired(value)
                            for _, v in ipairs(desiredTechniques) do
                                if v == value then
                                    return true
                                end
                            end
                            return false
                        end

                        local spinslotIndex
                        if typeof(getgenv().Spinslot) == "table" then
                            spinslotIndex = tostring(getgenv().Spinslot[1] or "1")
                        else
                            spinslotIndex = tostring(getgenv().Spinslot)
                        end

                        print("Using spinslotIndex:", spinslotIndex)

                        local replicatedData = player:FindFirstChild("ReplicatedData")
                        if not replicatedData then
                            warn("ReplicatedData not found for player:", player.Name)
                            break
                        end

                        local innates = replicatedData:FindFirstChild("innates")
                        if not innates then
                            warn("innates not found.")
                            break
                        end

                        local slotData = innates:FindFirstChild(spinslotIndex)
                        if not slotData then
                            warn("Slot data not found: " .. tostring(spinslotIndex))
                            break
                        end

                        local innateValue = slotData.Value
                        if isDesired(innateValue) then
                            print("Desired technique obtained:", innateValue)
                            getgenv().AutoSpinLoop = false
                            break
                        end

                        local innateSpin = raknet:GetRemote({"Remotes", "Server", "Data", "InnateSpin"})
                        if innateSpin then
                            innateSpin:InvokeServer(spinslotIndex)
                            print("Invoked InnateSpin for slot:", spinslotIndex)
                        else
                            warn("InnateSpin Remote not found.")
                            break
                        end
                        task.wait(1)
                    end
                end)
            end
        else
            getgenv().AutoSpinLoop = false
        end
    end,
})

-- Table for spin labels
local labels = {}

-- Update spin labels on each frame
raknet:OnRenderStep("LabelUpdater", function()
    local replicatedData = player:FindFirstChild("ReplicatedData")
    if not replicatedData then return end
    local innates = replicatedData:FindFirstChild("innates")
    if not innates then return end
    for i = 1, 4 do
        local slotData = innates:FindFirstChild(tostring(i))
        if slotData then
            if not labels[i] then
                labels[i] = SpinTab:CreateLabel(tostring(slotData.Value), "rewind")
            else
                labels[i]:Set(tostring(slotData.Value), "rewind")
            end
        else
            if labels[i] then
                labels[i]:Destroy()
                labels[i] = nil
            end
        end
    end
end)

-- All in one Toggle + AutoReplay
getgenv().AutoAll = false

InvestTab:CreateToggle({
    Name = "Autofarm",
    CurrentValue = false,
    Flag = "AutoAll",
    Callback = function(state)
        getgenv().AutoAll = state
        if state then
            -- All the code inside the toggle
            
            -- Define variables necessary inside the toggle
            local autoAllTask, flipLoopTask, autoReplayTask, sosaltask
            local SAFE_PLACE = Vector3.new(0,300,0)
            local RETURN_POSITION = Vector3.new(-2866.146, 135.067902, 4350.21533)
            
            -- Settings for small delays.
            local PRESS_BS_DURATION = 0.07 -- Delay for BackSlash
            local PRESS_RETURN_DURATION = 0.05
            local TELEPORT_DELAY = 0.2
            local FLIP_SPAM = 5
            local FLIP_LOOP_WAIT = 0.1
            
            -- Create neon platform for "safe" spot
            local safePlatform = Instance.new("Part")
            safePlatform.Name = "SafePlatform"
            safePlatform.Anchored = true
            safePlatform.Size = Vector3.new(100, 1, 100)
            safePlatform.Position = SAFE_PLACE
            safePlatform.Material = Enum.Material.Neon
            safePlatform.BrickColor = BrickColor.new("Bright green")
            safePlatform.CanCollide = true
            safePlatform.Parent = workspace
            
            local function teleportTo(pos)
                local plr = game:GetService("Players").LocalPlayer
                if not plr then return end
                local char = plr.Character or plr.CharacterAdded:Wait()
                local hrp = char:WaitForChild("HumanoidRootPart", 5)
                if hrp then
                    hrp.CFrame = CFrame.new(pos)
                    task.wait(TELEPORT_DELAY)
                end
            end
            
            -- This function finds a suitable BasePart (PrimaryPart, HumanoidRootPart, etc.)
            local function findBasePart(x)
                if x:IsA("Model") then
                    if x.PrimaryPart then
                        return x.PrimaryPart
                    end
                    local a = x:FindFirstChild("HumanoidRootPart")
                    if a and a:IsA("BasePart") then
                        return a
                    end
                    local b = x:FindFirstChildWhichIsA("BasePart")
                    if b then
                        return b
                    end
                elseif x:IsA("BasePart") then
                    return x
                end
                return nil
            end
            
            -- Instead of pressing E, use fireproximityprompt
            local function firePrompt(obj)
                if not obj then return end
                local prompt = obj:FindFirstChildOfClass("ProximityPrompt")
                if prompt then
                    -- Call FireProximityPrompt.
                    fireproximityprompt(prompt, 1)
                end
            end
            
            -- Spam flip loop for loot (Flip animation)
            local function spamFlipLoop()
                local plr = game:GetService("Players").LocalPlayer
                local lootGui = plr and plr:WaitForChild("PlayerGui"):WaitForChild("Loot", 10)
                if not lootGui or not lootGui:IsA("ScreenGui") then return end
                while getgenv().AutoAll do
                    if lootGui.Enabled then
                        -- "Open" GUI via BackSlash (simulate)
                        game:GetService("VirtualInputManager"):SendKeyEvent(true, Enum.KeyCode.BackSlash, false, game)
                        task.wait(0.05)
                        local frame = lootGui:FindFirstChild("Frame")
                        if frame then
                            local flip = frame:FindFirstChild("Flip")
                            if flip and flip:IsA("GuiObject") then
                                game:GetService("GuiService").SelectedObject = flip
                                task.wait(0.05)
                                for i = 1, FLIP_SPAM do
                                    game:GetService("VirtualInputManager"):SendKeyEvent(true, Enum.KeyCode.Return, false, game)
                                    task.wait(PRESS_RETURN_DURATION)
                                    game:GetService("VirtualInputManager"):SendKeyEvent(false, Enum.KeyCode.Return, false, game)
                                    task.wait(0.02)
                                end
                            end
                        end
                        -- "Close" GUI
                        game:GetService("VirtualInputManager"):SendKeyEvent(false, Enum.KeyCode.BackSlash, false, game)
                        task.wait(0.1)
                    else
                        task.wait(FLIP_LOOP_WAIT)
                    end
                end
            end
            
            -- When Finger Bearer appears, teleport to the platform and then to it
            local function handleFingerBearerSpawned(c)
                if not getgenv().AutoAll then return end
                if c.Name == "Finger Bearer" and c:IsA("Model") then
                    -- Teleport to the green platform
                    teleportTo(safePlatform.Position + Vector3.new(0, 5, 0))
                    task.wait(10) -- small pause
                    local bp = findBasePart(c)
                    if bp then
                        teleportTo(bp.Position + Vector3.new(0, 2, 0))
                    end
                end
            end
            
            -- Monitor when Finger Bearer spawns
            local function monitorFingerBearer()
                local mf = workspace:FindFirstChild("Objects") and workspace.Objects:FindFirstChild("Mobs")
                if not mf or not mf:IsA("Folder") then return end
                for _, x in ipairs(mf:GetChildren()) do
                    handleFingerBearerSpawned(x)
                end
                mf.ChildAdded:Connect(handleFingerBearerSpawned)
            end
            
            -- Process Civilians
            local function processCivilian(c)
                if not getgenv().AutoAll then return end
                local bp = findBasePart(c)
                if bp then
                    teleportTo(bp.Position + Vector3.new(0,1.5,0))
                    firePrompt(c)
                    task.wait(0.2)
                    teleportTo(RETURN_POSITION)
                    task.wait(0.2)
                end
            end
            
            -- Process Cursed Objects
            local function processCursedObject(o)
                if not getgenv().AutoAll then return end
                local bp = findBasePart(o)
                if bp then
                    teleportTo(bp.Position + Vector3.new(0,1.5,0))
                    firePrompt(o)
                    task.wait(0.2)
                    teleportTo(RETURN_POSITION)
                    task.wait(0.2)
                end
            end
            
            -- Process Chests
            local function processChest(ch)
                if not getgenv().AutoAll then return end
                local bp = findBasePart(ch)
                if bp then
                    teleportTo(bp.Position + Vector3.new(0,1.5,0))
                    firePrompt(ch)
                    task.wait(0.5)
                    teleportTo(RETURN_POSITION)
                    task.wait(0.2)
                end
            end
            
            -- Process Mobs
            local function processMob(m)
                if not getgenv().AutoAll then return end
                if m.Name == "Finger Bearer" then
                    wait(10)
                end
                local bp = findBasePart(m)
                if bp then
                    teleportTo(bp.Position + Vector3.new(0,2,0))
                    firePrompt(m)
                    task.wait(0.2)
                    teleportTo(RETURN_POSITION)
                    task.wait(0.2)
                end
            end
            
            -- Main "All in One" Loop
            local function autoAllLoop()
                monitorFingerBearer()
                while getgenv().AutoAll do
                    local obj = workspace:FindFirstChild("Objects")
                    if not obj then
                        task.wait(0.5)
                        continue
                    end
                    
                    local mis = obj:FindFirstChild("MissionItems")
                    local drp = obj:FindFirstChild("Drops")
                    local mob = obj:FindFirstChild("Mobs")
                    
                    local foundSomething = false
                    
                    -- Civilian / CursedObject
                    if mis and mis:IsA("Folder") then
                        for _, i in ipairs(mis:GetChildren()) do
                            if not getgenv().AutoAll then break end
                            if i.Name=="Civilian" then
                                foundSomething = true
                                processCivilian(i)
                            elseif i.Name=="CursedObject" then
                                foundSomething = true
                                processCursedObject(i)
                            end
                        end
                    end
                    
                    -- Chests (Drops)
                    if drp and drp:IsA("Folder") then
                        for _, d in ipairs(drp:GetDescendants()) do
                            if not getgenv().AutoAll then break end
                            if d:IsA("Model") and string.find(d.Name:lower(), "chest") then
                                foundSomething = true
                                processChest(d)
                            end
                        end
                    end
                    
                    -- Mobs
                    if mob and mob:IsA("Folder") then
                        for _, mm in ipairs(mob:GetChildren()) do
                            if not getgenv().AutoAll then break end
                            if mm:IsA("Model") then
                                foundSomething = true
                                processMob(mm)
                            end
                        end
                    end
                    
                    if not foundSomething then
                        task.wait(0.5)
                    end
                end
            end
            
            getgenv().InstaKill = true
            
            task.spawn(function()
                while getgenv().InstaKill do
                    pcall(function()
                        local mobs = workspace.Objects.Mobs
                        if mobs and mobs:IsA("Folder") then
                            for _, mob in ipairs(mobs:GetChildren()) do
                                if mob:IsA("Model") and mob:FindFirstChildOfClass("Humanoid") then
                                    local humanoid = mob:FindFirstChildOfClass("Humanoid")
                                    if humanoid and humanoid.Health > 0 then
                                        humanoid:ChangeState(15)
                                        humanoid.Health = 0
                                    end
                                end
                            end
                        else
                            warn("Mobs folder not found or is not a folder.")
                        end
                    end)
                    task.wait(0.01)
                end
            end)
            
            local hrp = game.Players.LocalPlayer.Character:WaitForChild("HumanoidRootPart")
            
            local bp = Instance.new("BodyPosition", hrp)
            bp.MaxForce = Vector3.new(1e5, 1e5, 1e5)
            bp.Position = hrp.Position
            
            game:GetService("RunService").Stepped:Connect(function()
                bp.Position = hrp.Position
            end)
            
            local function sosal()
                while getgenv().AutoAll do
                    game:GetService("ReplicatedStorage").Remotes.Client.StorylineDialogueSkip:FireServer(true)
                    task.wait()
                end
            end
            
            -- AutoReplay without 20-second wait, use short delay
            local function autoReplayLoop()
                local plr = game:GetService("Players").LocalPlayer
                local pg = plr and plr:FindFirstChild("PlayerGui")
                if not pg then return end
                while getgenv().AutoAll do
                    local rs = pg:FindFirstChild("ReadyScreen")
                    if rs and rs:IsA("ScreenGui") and rs.Enabled then
                        task.wait(2)
                        if getgenv().AutoAll and rs.Enabled then
                            local frm = rs:FindFirstChild("Frame")
                            if frm then
                                local rply = frm:FindFirstChild("Replay")
                                if rply and rply:IsA("GuiButton") then
                                    local vim = game:GetService("VirtualInputManager")
                                    local gs = game:GetService("GuiService")
                                    vim:SendKeyEvent(true,Enum.KeyCode.BackSlash,false,game)
                                    task.wait(0.2)
                                    gs.SelectedObject = rply
                                    task.wait(0.2)
                                    vim:SendKeyEvent(true,Enum.KeyCode.Return,false,game)
                                    task.wait(0.1)
                                    vim:SendKeyEvent(false,Enum.KeyCode.Return,false,game)
                                    task.wait(0.1)
                                    vim:SendKeyEvent(true,Enum.KeyCode.BackSlash,false,game)
                                    vim:SendKeyEvent(false,Enum.KeyCode.BackSlash,false,game)
                                end
                            end
                        end
                    end
                    task.wait(1)
                end
            end
            
            getgenv().InstaKill = true
            autoAllTask = task.spawn(autoAllLoop)
            flipLoopTask = task.spawn(spamFlipLoop)
            autoReplayTask = task.spawn(autoReplayLoop)
            sosaltask = task.spawn(sosal)
            
        else
            getgenv().AutoAll = false
            getgenv().InstaKill = false
        end
    end,
})

-- Load saved configuration
Rayfield:LoadConfiguration()

-- Additional Script Added to the Separate Tab
-- Code from the second script you provided
-- Note: I've adjusted variable names and function calls to match the existing code and to use 'raknet' where appropriate.

do
    local MainTab = BossTab  -- Use the new tab for the additional script

    -- Variables to store task handlers
    local instaKillTask
    local autoFlipTask
    local autoReplayTask
    local chestTask

    -- AutoFarm Toggle
    MainTab:CreateToggle({
        Name = "AutoFarm",
        CurrentValue = false,
        Flag = "Autofarm",
        Callback = function(state)
            getgenv().AutoFarm = state

            if state then
                -- Constants
                local BOSS_SPAWN_NAME = "BossSpawn"
                local SAFE_PLACE = Vector3.new(0, 50, 0)
                local FLIP_SPAM_DELAY = 0.1
                local REPLAY_WAIT = 26
                local CHEST_NAME_MATCH = "chest"

                -- Safe Platform
                local safePlatform = Instance.new("Part")
                safePlatform.Name = "SafePlatform"
                safePlatform.Anchored = true
                safePlatform.Size = Vector3.new(100,1,100)
                safePlatform.Position = SAFE_PLACE
                safePlatform.Material = Enum.Material.Neon
                safePlatform.BrickColor = BrickColor.new("Bright green")
                safePlatform.CanCollide = true
                safePlatform.Parent = workspace

                -- Variables and Flags
                local hasReplayed = false

                -- Notification Function
                local function notify(title, content, duration)
                    Rayfield:Notify({
                        Title = title,
                        Content = content,
                        Duration = duration or 2
                    })
                end

                notify("AutoFarm", "Enabled")

                -- Functions Related to AutoFarm

                -- Function to press GUI Button with VirtualInputManager
                local function pressGuiButton(button)
                    local vim = game:GetService("VirtualInputManager")
                    local gs = game:GetService("GuiService")

                    vim:SendKeyEvent(true, Enum.KeyCode.BackSlash, false, game)
                    task.wait(0.15)
                    gs.SelectedObject = button
                    task.wait(0.15)
                    vim:SendKeyEvent(true, Enum.KeyCode.Return, false, game)
                    task.wait(0.1)
                    vim:SendKeyEvent(false, Enum.KeyCode.Return, false, game)
                    task.wait(0.1)
                    vim:SendKeyEvent(false, Enum.KeyCode.BackSlash, false, game)
                end

                -- Teleport function
                local function teleportTo(pos)
                    local plr = raknet:GetLocalPlayer()
                    if plr and raknet:GetCharacter() and raknet:GetPrimaryPart() then
                        raknet:GetPrimaryPart().CFrame = CFrame.new(pos)
                        notify("Teleport", "Teleported to "..tostring(pos))
                    else
                        print("Teleport Failed: Player or HumanoidRootPart not found.")
                    end
                end

                -- Insta Kill Loop
                local function instaKillLoop()
                    local plr = raknet:GetLocalPlayer()
                    while task.wait(0.5) do
                        if not getgenv().AutoFarm then break end
                        local char = raknet:GetCharacter()
                        for _, obj in ipairs(workspace:GetDescendants()) do
                            if not getgenv().AutoFarm then break end
                            if obj:IsA("Humanoid") and obj.Parent ~= char then
                                if obj.Health > 0 then
                                    obj.Health = 0
                                    notify("InstaKill", "Killed "..(obj.Parent and obj.Parent.Name or "Unknown"), 1)
                                end
                            end
                        end
                    end
                end

                -- Flip Loop
                local function autoFlip()
                    local plr = raknet:GetLocalPlayer()
                    local VirtualInputManager = game:GetService("VirtualInputManager")
                    local GuiService = game:GetService("GuiService")

                    while task.wait(0.1) do
                        if not getgenv().AutoFarm then break end
                        if plr and plr.PlayerGui:FindFirstChild("Loot") and plr.PlayerGui.Loot.Enabled then
                            VirtualInputManager:SendKeyEvent(true, Enum.KeyCode.BackSlash, false, game)
                            task.wait(0.2)

                            local targetElement = plr.PlayerGui.Loot.Frame:FindFirstChild("Flip")
                            if targetElement and targetElement:IsA("GuiObject") then
                                GuiService.SelectedObject = targetElement

                                while plr.PlayerGui.Loot.Enabled and getgenv().AutoFarm do
                                    VirtualInputManager:SendKeyEvent(true, Enum.KeyCode.Return, false, game)
                                    task.wait(0.1)
                                    VirtualInputManager:SendKeyEvent(false, Enum.KeyCode.Return, false, game)
                                    task.wait(FLIP_SPAM_DELAY)
                                end
                            else
                                notify("Flip Not Found", "Couldn't find the 'Flip' GuiButton", 2)
                            end

                            VirtualInputManager:SendKeyEvent(true, Enum.KeyCode.BackSlash, false, game)
                            task.wait(0.1)
                            VirtualInputManager:SendKeyEvent(false, Enum.KeyCode.BackSlash, false, game)
                        end
                    end
                end

                -- Open Chest Function
                local function openChest(chestModel)
                    local prompt = chestModel:FindFirstChildOfClass("ProximityPrompt")
                    if not prompt then
                        notify("Chest", "No ProximityPrompt found in: "..chestModel.Name, 2)
                        return
                    end

                    local basePart = chestModel:FindFirstChild("HumanoidRootPart") or chestModel:FindFirstChildWhichIsA("BasePart")
                    if not basePart then
                        notify("Chest", "No BasePart found in: "..chestModel.Name, 2)
                        return
                    end

                    teleportTo(basePart.Position + Vector3.new(0,3,0))

                    local holdTime = 0.1
                    if typeof(prompt.HoldDuration) == "number" and prompt.HoldDuration > 0 then
                        holdTime = prompt.HoldDuration + 0.1
                    end

                    notify("Chest", "Opening: "..chestModel.Name.." (holding "..holdTime.."s)", 2)

                    prompt:InputHoldBegin()
                    task.wait(holdTime)
                    prompt:InputHoldEnd()
                end

                -- Process All Chests
                local function processAllChests()
                    local objectsFolder = workspace:FindFirstChild("Objects")
                    if not objectsFolder then
                        print("Objects folder not found.")
                        return
                    end
                    local dropsFolder = objectsFolder:FindFirstChild("Drops")
                    if not dropsFolder or not dropsFolder:IsA("Folder") then
                        print("Drops folder not found or not a Folder.")
                        return
                    end

                    for _, item in ipairs(dropsFolder:GetDescendants()) do
                        if not getgenv().AutoFarm then break end
                        if item:IsA("Model") and item.Name:lower():find(CHEST_NAME_MATCH) then
                            openChest(item)
                        end
                    end
                end

                -- Chest Loop
                local function chestLoop()
                    while task.wait(2) do
                        if not getgenv().AutoFarm then break end
                        processAllChests()
                    end
                end

                -- Auto Replay Loop
                local function autoReplayLoop()
                    local plr = raknet:GetLocalPlayer()
                    local pg = plr:FindFirstChild("PlayerGui")
                    if not pg then
                        print("PlayerGui not found.")
                        return
                    end

                    while task.wait(1) do
                        if not getgenv().AutoFarm then break end
                        local rs = pg:FindFirstChild("ReadyScreen")
                        if rs and rs:IsA("ScreenGui") and rs.Enabled then
                            if not hasReplayed then
                                notify("Replay Timer", "ReadyScreen detected. Will press Replay in "..REPLAY_WAIT.."s", 3)
                                task.wait(REPLAY_WAIT)

                                if getgenv().AutoFarm and rs.Enabled then
                                    local frm = rs:FindFirstChild("Frame")
                                    if frm then
                                        local replayBtn = frm:FindFirstChild("Replay")
                                        if replayBtn and replayBtn:IsA("GuiButton") then
                                            notify("Replay", "Pressing Replay now...", 2)
                                            pressGuiButton(replayBtn)
                                            hasReplayed = true
                                        else
                                            notify("Replay Error", "Replay button not found or not a GuiButton", 2)
                                        end
                                    else
                                        print("Frame not found in ReadyScreen.")
                                    end
                                end
                            end
                        else
                            hasReplayed = false
                        end
                    end
                end

                -- Teleport to Boss
                local function teleportToBoss()
                    local spawns = workspace:FindFirstChild("Objects")
                    if spawns and spawns:FindFirstChild("Spawns") then
                        local bossSpawn = spawns.Spawns:FindFirstChild(BOSS_SPAWN_NAME)
                        if bossSpawn and bossSpawn:IsA("BasePart") then
                            teleportTo(bossSpawn.Position + Vector3.new(0,5,0))
                        else
                            notify("Boss Error", "Boss spawn not found or not a BasePart. Check BOSS_SPAWN_NAME.", 3)
                        end
                    else
                        notify("Boss Error", "Objects/Spawns folder not found. Check your structure.", 3)
                    end
                end

                -- Main Automation Function
                local function mainAutomation()
                    notify("AutoFarm", "Starting up all loops...")
                    instaKillTask = task.spawn(instaKillLoop)
                    autoFlipTask = task.spawn(autoFlip)
                    autoReplayTask = task.spawn(autoReplayLoop)
                    chestTask = task.spawn(chestLoop)
                    teleportToBoss()
                end

                -- Start Automation
                mainAutomation()

                -- Cleanup function when AutoFarm is turned off
                getgenv().cleanupAutoFarm = function()
                    if instaKillTask then
                        task.cancel(instaKillTask)
                        instaKillTask = nil
                    end
                    if autoFlipTask then
                        task.cancel(autoFlipTask)
                        autoFlipTask = nil
                    end
                    if autoReplayTask then
                        task.cancel(autoReplayTask)
                        autoReplayTask = nil
                    end
                    if chestTask then
                        task.cancel(chestTask)
                        chestTask = nil
                    end
                    if safePlatform and safePlatform.Parent then
                        safePlatform:Destroy()
                        safePlatform = nil
                    end
                    hasReplayed = false
                    getgenv().cleanupAutoFarm = nil
                    notify("AutoFarm", "Disabled")
                    print("AutoFarm Disabled.")
                end

            else
                if getgenv().cleanupAutoFarm then
                    getgenv().cleanupAutoFarm()
                else
                    Rayfield:Notify({
                        Title = "AutoFarm",
                        Content = "Disabled",
                        Duration = 2
                    })
                    print("AutoFarm Disabled.")
                end
            end
        end
    })

    -- You can add more functionalities (like webhook integration) here
    -- Adjust any paths and variable names to match with raknet functions
end

local raidTypes = {"Finger Bearer", "Ocean Curse", "Soul Curse", "Volcano Curse", "Sorcerer Killer", "Heian Imaginary Demon"}
local difficulties = {"Easy", "Medium", "Hard", "Nightmare"}
local investigate = {"Cursed School", "Yasohachi Bridge", "Tokyo Subway", "Eerie Farm", "Detention Center"}
getgenv().selectedRaidType = raidTypes[1]
getgenv().selectedinvestigate = investigate[1]
getgenv().selectedDifficulty = difficulties[1]

local Dropdown = Lobby:CreateDropdown({
    Name = "Raid types", 
    Options = raidTypes,
    CurrentOption = raidTypes[1],
    MultipleOptions = false,
    Flag = "Raidtype",
    Callback = function(Options)
        getgenv().selectedRaidType = Options
    end,
})

local Dropdown = Lobby:CreateDropdown({
    Name = "Investigate Dropdown",
    Options = investigate, 
    CurrentOption = investigate[1],
    MultipleOptions = false,
    Flag = "InvestigateType",
    Callback = function(Options)
        getgenv().selectedinvestigate = Options
    end,
})

local Dropdown = Lobby:CreateDropdown({
    Name = "Difficulty",
    Options = difficulties,
    CurrentOption = difficulties[1],
    MultipleOptions = false,
    Flag = "Difficulty",
    Callback = function(Options)
        getgenv().selectedDifficulty = Options
    end,
})

-- Store connection references
local bossLobbyConnection
local investigateLobbyConnection 
local startLobbyConnection

Lobby:CreateToggle({
    Name = "Auto Create Lobby Boss",
    CurrentValue = false,
    Flag = "AutoCreateLobbyBoss",
    Callback = function(Value)
        getgenv().AutoCreateLobby = Value
        if Value then
            bossLobbyConnection = game:GetService("RunService").Heartbeat:Connect(function()
                pcall(function()
                    game:GetService("ReplicatedStorage").Remotes.Server.Raids.CreateLobby:InvokeServer(
                        "Boss",
                        getgenv().selectedRaidType,
                        getgenv().selectedDifficulty,
                        ""
                    )
                end)
                task.wait(5)
            end)
            Notify("Auto Create Lobby", "Lobby creation enabled.", "check_circle")
        else
            if bossLobbyConnection then
                bossLobbyConnection:Disconnect()
                bossLobbyConnection = nil
            end
            Notify("Auto Create Lobby Disabled", "Lobby creation stopped.", "info")
        end
    end,
})

Lobby:CreateToggle({
    Name = "Auto Create Lobby Investigate", 
    CurrentValue = false,
    Flag = "AutoCreateLobbyInvestigate",
    Callback = function(Value)
        getgenv().AutoCreateLobby = Value
        if Value then
            investigateLobbyConnection = game:GetService("RunService").Heartbeat:Connect(function()
                pcall(function()
                    game:GetService("ReplicatedStorage").Remotes.Server.Raids.CreateLobby:InvokeServer(
                        "Investigation",
                        getgenv().selectedinvestigate,
                        getgenv().selectedDifficulty,
                        ""
                    )
                end)
                task.wait(5)
            end)
            Notify("Auto Create Lobby", "Lobby creation enabled.", "check_circle")
        else
            if investigateLobbyConnection then
                investigateLobbyConnection:Disconnect()
                investigateLobbyConnection = nil
            end
            Notify("Auto Create Lobby Disabled", "Lobby creation stopped.", "info")
        end
    end,
})

Lobby:CreateToggle({
    Name = "Auto Start Lobby",
    CurrentValue = false, 
    Flag = "AutoStartLobby",
    Callback = function(Value)
        getgenv().AutoStartLobby = Value
        if Value then
            startLobbyConnection = game:GetService("RunService").Heartbeat:Connect(function()
                pcall(function()
                    game:GetService("ReplicatedStorage").Remotes.Server.Raids.StartLobby:InvokeServer("Boss")
                end)
                task.wait(5)
            end)
            Notify("Auto Start Lobby", "Lobby auto-start enabled.", "check_circle")
        else
            if startLobbyConnection then
                startLobbyConnection:Disconnect()
                startLobbyConnection = nil
            end
            Notify("Auto Start Lobby Disabled", "Lobby auto-start stopped.", "info")
        end
    end,
})

local function isValidWebhook(url)
    return string.match(url, "^https://discord%.com/api/webhooks/%d+/%S+$") ~= nil
end

WebhookTab:CreateInput({
    Name = "Webhook URL",
    CurrentValue = "",
    PlaceholderText = "Enter webhook URL here",
    RemoveTextAfterFocusLost = false,
    Flag = "webhookurl",
    Callback = function(Text)
        if isValidWebhook(Text) then
            getgenv().webhookinput = Text
            Rayfield:Notify({Title = "Webhook URL",Content = "URL set successfully.",Duration = 2})
        else
            Rayfield:Notify({Title = "Invalid URL",Content = "Please enter a valid Discord Webhook URL.",Duration = 2})
        end
    end,
})

local function sendWebhook(content, retries)
    retries = retries or 3
    if getgenv().webhookinput and getgenv().webhookinput ~= "" then
        for attempt = 1, retries do
            local success = pcall(function()
                http_request({
                    Url = getgenv().webhookinput,
                    Method = "POST",
                    Headers = {["Content-Type"] = "application/json"},
                    Body = game:GetService("HttpService"):JSONEncode({content = content})
                })
            end)
            if success then
                Rayfield:Notify({Title = "Webhook Sent",Content = "Success",Duration = 2})
                return
            end
            task.wait(1)
        end
        Rayfield:Notify({Title = "Webhook Failed",Content = "Failed after " .. retries .. " attempts",Duration = 2})
    else
        Rayfield:Notify({Title = "Webhook URL Missing",Content = "Set webhook URL first",Duration = 2})
    end
end

WebhookTab:CreateButton({
    Name = "Test Webhook",
    Callback = function()
        sendWebhook("🔔 PrimeHub Webhook Test")
    end
})

WebhookTab:CreateToggle({
    Name = "Auto Webhook",
    CurrentValue = false,
    Flag = "AutoWebhook",
    Callback = function(Value)
        if not Value then return end
        
        local Players = game:GetService("Players")
        local LocalPlayer = Players.LocalPlayer
        local ReadyScreen = LocalPlayer:WaitForChild("PlayerGui"):WaitForChild("ReadyScreen")
        local LootGui = LocalPlayer.PlayerGui:FindFirstChild("Loot")
        local Cards = LootGui and LootGui:FindFirstChild("Frame") and LootGui.Frame:FindFirstChild("Cards")
        
        if not Cards then return end
        
        local previousTexts = {}
        local rewardsCount = {}
        
        local function checkAndLogChanges()
            for _, lootCard in ipairs(Cards:GetChildren()) do
                if lootCard:IsA("Frame") and lootCard:FindFirstChild("Back") and lootCard.Back:FindFirstChild("Reward") then
                    local rewardLabel = lootCard.Back.Reward
                    if rewardLabel:IsA("TextLabel") then
                        local currentText = rewardLabel.Text
                        if currentText ~= previousTexts[lootCard] then
                            previousTexts[lootCard] = currentText
                            if currentText and currentText ~= "" then
                                rewardsCount[currentText] = (rewardsCount[currentText] or 0) + 1
                            end
                        end
                    end
                end
            end
        end
        
        local function generateRewardList()
            local rewardStrings = {}
            for text, count in pairs(rewardsCount) do
                table.insert(rewardStrings, count > 1 and text.." x"..count or text)
            end
            return rewardStrings
        end
        
        local function sendWebhookEmbed(username, takentime, rewardStrings)
            if not getgenv().webhookinput or getgenv().webhookinput == "" then return end
            
            pcall(function()
                http_request({
                    Url = getgenv().webhookinput,
                    Method = "POST",
                    Headers = {["Content-Type"] = "application/json"},
                    Body = game:GetService("HttpService"):JSONEncode({
                        embeds = {{
                            title = "PrimeHub Report",
                            color = 3447003,
                            timestamp = os.date("!%Y-%m-%dT%H:%M:%SZ"),
                            thumbnail = {url = "https://c.tenor.com/Bqix4zMtV_YAAAAd/tenor.gif"},
                            image = {url = "https://i.gifer.com/Dv9E.gif"},
                            fields = {
                                {name = "📦 Username",value = "```"..username.."```",inline = true},
                                {name = "⏱ Time",value = "```"..takentime.."```",inline = true},
                                {name = "🎁 Rewards",value = "```"..table.concat(rewardStrings, "\n").."```",inline = false}
                            }
                        }}
                    })
                })
            end)
        end
        
        task.spawn(function()
            while Value do
                checkAndLogChanges()
                task.wait(1)
            end
        end)
        
        local replayButton = ReadyScreen:FindFirstChild("Frame") and ReadyScreen.Frame:FindFirstChild("Replay")
        if replayButton and replayButton:IsA("ImageButton") then
            replayButton.MouseButton1Click:Connect(function()
                if not Value then return end
                
                local username = LocalPlayer.Name
                local takentime = os.date("%H:%M:%S")
                local rewardStrings = generateRewardList()
                
                if #rewardStrings > 0 then
                    sendWebhookEmbed(username, takentime, rewardStrings)
                end
                
                rewardsCount = {}
                previousTexts = {}
            end)
        end
    end,
})

Rayfield:LoadConfiguration()