--[[
	Game05 - ESP + ZipTie + Fly + Freecam + Aim

	P  ESP on / off        U  auto ZipTie
	H  Hide / show panel   M  Free mouse
	K  Flyjump             L  Freecam
	J  Aim (silent head aim on Pistol / AK47)

	Drag the header. Slider = ESP draw distance.
	Lobby mode: flyjump + freecam only.

	Mobile: every control is a button, no hotkey needed.
	Freecam gets drag-to-look plus an on-screen move pad.

	Config is saved to Game05_Config.txt (executor writefile) and restored on the
	next run: every toggle, the ESP range, the panel position and the loot
	selection. A missing or corrupt file simply means "no config".
	Free to use, modify and share. Made with love by xain01.
	This is original.
]]

if getgenv and getgenv().Game05Running then return end
if getgenv then getgenv().Game05Running = true end

local Players = game:GetService("Players")
local RunService = game:GetService("RunService")
local UIS = game:GetService("UserInputService")
local CS = game:GetService("CollectionService")
local CAS = game:GetService("ContextActionService")
local RS = game:GetService("ReplicatedStorage")

local function wc(p, n, waitSec)
	if not p then return nil end
	local c = p:FindFirstChild(n)
	if c then return c end
	if not waitSec then return nil end
	local ok, r = pcall(function() return p:WaitForChild(n, waitSec) end)
	return ok and r or nil
end

-- Bootstrap: LocalPlayer is a property, not a child, so it can be absent on the
-- first frame after an auto-execute or a queued-teleport resume. PlayerGui is
-- guaranteed to exist once LocalPlayer does, so a bounded wait is safe here.
local LP = Players.LocalPlayer
if not LP then
	local t0 = os.clock()
	repeat
		task.wait()
		LP = Players.LocalPlayer
	until LP or os.clock() - t0 > 30
end

local PG = nil
if LP then
	PG = LP:FindFirstChild("PlayerGui")
	if not PG then
		local ok, r = pcall(function() return LP:WaitForChild("PlayerGui", 30) end)
		PG = ok and r or nil
	end
end

if not LP or not PG then
	if getgenv then getgenv().Game05Running = nil end
	warn("[Game05] bootstrap failed: LocalPlayer or PlayerGui never arrived")
	return
end

local Loot = workspace:FindFirstChild("Loot")

local Cam = workspace.CurrentCamera
if not Cam then
	local t0 = os.clock()
	repeat
		task.wait()
		Cam = workspace.CurrentCamera
	until Cam or os.clock() - t0 > 10
end

local TOP = 2147483647
local TAGS = { "Npc", "Cop", "Guard", "Dog" }
local TAGCOL = {
	Npc = Color3.fromRGB(140, 255, 160),
	Cop = Color3.fromRGB(90, 170, 255),
	Guard = Color3.fromRGB(255, 170, 70),
	Dog = Color3.fromRGB(255, 130, 220),
}
local CARDS = { CreditCard = true, GiftCard = true }
local STASH = {
	MedKit = 1, BananaPeel = 1, Package = 1, ACGas = 1, SpikeStrip = 1,
	Jammer = 1, TruckKey = 1, HeliKeys = 1, DesertMap = 1, SprayCan = 1,
	Sponge = 1, EmptyCan = 1, Tool = 1,
}
local PALETTE = {
	Color3.fromRGB(255, 90, 90), Color3.fromRGB(255, 190, 70),
	Color3.fromRGB(120, 255, 140), Color3.fromRGB(90, 200, 255),
	Color3.fromRGB(190, 130, 255), Color3.fromRGB(255, 130, 220),
	Color3.fromRGB(255, 255, 255),
}

local ESP_ON, ZIP_ON, HIDDEN = true, true, false
local ALL_SELECTED = true
local MOUSE_ON, FLY_ON, FC_ON, CLOSED = false, false, false, false
local AIM_ON = false
local WALL_ON, FALL_ON = false, false
local NPC_ON, LINE_ON = true, true
local LOBBY = Loot == nil
local MIN_R, MAX_R = 100, 5000
local RANGE = 300
local ZIPTIE_DIST = 24

local types, rows, chosen, items, npcs, conns = {}, {}, {}, {}, {}, {}
local lastScan, lastList, orderDirty, lastPrune = 0, 0, false, 0
local UI = { sliding = false, from = nil, at = nil, moved = false }

------------------------------------------------------------ config

-- Everything the user sets is written to a file and read back on the next run.
-- The file is parsed into a throwaway table and validated field by field before
-- anything is assigned, so a missing file, an unreadable one or a single malformed
-- line is treated as "no config" and the defaults above stay untouched.
local CFG = {
	file = "Game05_Config.txt",
	version = "game05-cfg-1",
	max = 65536,
	ready = false,
	queued = false,
	picksOn = false,
	picks = {},
	allSel = true,
	want = nil,
	pos = nil,
	save = nil,
}

function CFG.writer()
	local f = writefile or (syn and syn.write_file) or (fluxus and fluxus.write_file)
	return type(f) == "function" and f or nil
end

function CFG.reader()
	local f = readfile or (syn and syn.read_file) or (fluxus and fluxus.read_file)
	return type(f) == "function" and f or nil
end

-- Plain percent-escaping: keeps keys (=, spaces, rich text chars) on one line and
-- needs no loadstring on the way back in.
function CFG.encode(s)
	return (tostring(s):gsub("[^%w_%-%.:]", function(c)
		return string.format("%%%02X", string.byte(c))
	end))
end

function CFG.decode(s)
	local ok, out = pcall(function()
		return (s:gsub("%%(%x%x)", function(h)
			-- The capture is exactly two hex digits, so tonumber cannot fail;
			-- assert() just narrows number? to number for the typechecker.
			return string.char(assert(tonumber(h, 16)))
		end))
	end)
	if not ok or type(out) ~= "string" or out == "" then return nil end
	return out
end

function CFG.bool(v)
	if v == "1" or v == "true" then return true end
	if v == "0" or v == "false" then return false end
	return nil
end

-- Validate into a fresh table; nil means "ignore the whole file".
function CFG.parse(text)
	if type(text) ~= "string" or text == "" or #text > CFG.max then return nil end
	if text:sub(1, #CFG.version) ~= CFG.version then return nil end

	local out = { picks = {}, hasPicks = false }
	local picks = 0
	local first = true
	for line in string.gmatch(text, "[^\r\n]+") do
		if first then
			if line ~= CFG.version then return nil end
			first = false
		else
			local k, v = string.match(line, "^(%a+)=(.*)$")
			if not k or not v or v == "" then return nil end
			if k == "esp" or k == "zip" or k == "npc" or k == "line"
				or k == "aim" or k == "fly" or k == "fc" or k == "mouse"
				or k == "wall" or k == "fall"
				or k == "hidden" or k == "allsel" then
				local b = CFG.bool(v)
				if b == nil then return nil end
				out[k] = b
			elseif k == "range" then
				local n = tonumber(v)
				if not n or n ~= n then return nil end
				out.range = math.clamp(n, MIN_R, MAX_R)
			elseif k == "px" or k == "py" or k == "psx" or k == "psy" then
				local n = tonumber(v)
				if not n or n ~= n or math.abs(n) > 100000 then return nil end
				out[k] = n
			elseif k == "pick" or k == "skip" then
				local s = CFG.decode(v)
				if not s or #s > 160 then return nil end
				picks = picks + 1
				if picks > 400 then return nil end
				out.picks[s] = k == "pick"
				out.hasPicks = true
			end
		end
	end
	if first then return nil end
	return out
end

function CFG.load()
	local read = CFG.reader()
	if not read then return end
	local ok, text = pcall(read, CFG.file)
	if not ok then return end
	local c = CFG.parse(text)
	if not c then return end

	ESP_ON = c.esp ~= false
	ZIP_ON = c.zip ~= false
	NPC_ON = c.npc ~= false
	LINE_ON = c.line ~= false
	HIDDEN = c.hidden == true
	ALL_SELECTED = c.allsel ~= false
	if c.range then RANGE = c.range end

	CFG.allSel = ALL_SELECTED
	CFG.picksOn = c.hasPicks
	CFG.picks = c.picks
	-- Freecam / fly / aim / mouse are replayed through their real setters further
	-- down, once those exist: flipping the flags directly would leave the aim hook
	-- and the render bindings uninstalled.
	CFG.want = {
		mouse = c.mouse == true,
		fly = c.fly == true,
		fc = c.fc == true,
		aim = c.aim == true,
		wall = c.wall == true,
		fall = c.fall == true,
	}
	if c.px ~= nil and c.py ~= nil then
		CFG.pos = { xs = c.psx or 0, xo = c.px, ys = c.psy or 0.5, yo = c.py }
	end
end

-- Debounced write: drags and sliders fire constantly, disks do not like that.
function CFG.queue()
	if not CFG.ready or CLOSED or CFG.queued then return end
	if type(CFG.save) ~= "function" then return end
	CFG.queued = true
	task.delay(0.75, function()
		CFG.queued = false
		if not CFG.ready or CLOSED or type(CFG.save) ~= "function" then return end
		pcall(CFG.save)
	end)
end

CFG.load()

-- adaptive ESP budget: level 0 = full speed, 4 = minimum work
local AD = {
	lvl = 0,
	scan = { 0.10, 0.18, 0.32, 0.55, 0.90 },
	over = { 0, 1 / 30, 1 / 20, 1 / 10, 1 / 5 },
	cap = { 768, 192, 80, 40, 16 },
	ms = { 0.048, 0.040, 0.032, 0.024, 0.016 },
	list = { 0.5, 0.5, 0.64, 0.86, 0.93 },
	raw = 1 / 60,
	sm = 1 / 60,
	bad = 0,
	good = 0,
	lvlT = 0,
	acc = 0,
}

local IS_TOUCH = UIS.TouchEnabled and not UIS.KeyboardEnabled

local BTN_W, BTN_GAP, BTN_H = 68, 4, 26
local PANEL_W, PANEL_H = 236, 512
local LOBBY_H = 88

local TITLE_GAME = "xain01. Hotkey: (H)ide, Es(P)"
local TITLE_LOBBY = "Join a game"

local function new(cls, props, parent)
	local i = Instance.new(cls)
	for k, v in props do i[k] = v end
	i.Parent = parent
	return i
end

local function on(sig, fn)
	local c = sig:Connect(fn)
	conns[#conns + 1] = c
	return c
end

local function money(n)
	return "$" .. tostring(math.floor(n)):reverse():gsub("(%d%d%d)", "%1,"):reverse():gsub("^,", "")
end

local function hash(k)
	local n = 0
	for i = 1, #k do n = (n * 31 + string.byte(k, i)) % 1000003 end
	return PALETTE[n % #PALETTE + 1]
end

------------------------------------------------------------ hot path

-- The scan used to re-derive Kind/Template/Weight/Stashable for every model in
-- Loot on every pass: ~10 reflected GetAttribute calls per model, three passes
-- per tick. Those fields are static per instance, so memoise them and clear the
-- entry only when the instance really fires AttributeChanged.
local gAttr = game.GetAttribute
local gIsA = game.IsA
local gIsDesc = game.IsDescendantOf
local gFind = game.FindFirstChild
local gClass = game.FindFirstChildOfClass
local gFFWIA = game.FindFirstChildWhichIsA

local infoCache = setmetatable({}, { __mode = "k" })
local lootList, lootN, lootAt = {}, 0, -1

-- Loot:GetChildren() allocated a fresh array for every caller on every tick:
-- twice per scan plus once per list refresh. One cached array per frame is
-- enough, the child set only changes at scan rate anyway.
local function lootKids()
	if not Loot or not Loot.Parent then
		Loot = workspace:FindFirstChild("Loot")
		lootAt = -1
	end
	local now = os.clock()
	if now - lootAt < 0.08 then return lootList, lootN end
	lootAt = now
	lootN = 0
	if Loot then
		for _, m in Loot:GetChildren() do
			if gIsA(m, "Model") then
				lootN = lootN + 1
				lootList[lootN] = m
			end
		end
	end
	for i = lootN + 1, #lootList do lootList[i] = nil end
	return lootList, lootN
end

local function feet()
	local c = LP.Character
	local h = c and c:FindFirstChild("HumanoidRootPart")
	return h and h.Position or nil
end

local function body(m)
	local h = gFind(m, "HumanoidRootPart")
	if h and gIsA(h, "BasePart") then return h end
	local d = gFind(m, "Head")
	if d and gIsA(d, "BasePart") then return d end
	return m.PrimaryPart
end

local function down(m)
	if gAttr(m, "Pose") == "Out" then return true end
	local h = gClass(m, "Humanoid")
	return h ~= nil and h.Health <= 0
end

local function screen(p)
	if not Cam then return nil end
	local v = Cam:WorldToViewportPoint(p)
	if v.Z <= 0 then return nil end
	return Vector2.new(v.X, v.Y)
end

local function stashable(m)
	local f = m:GetAttribute("Stashable")
	if f ~= nil then return f == true end
	local kind = m:GetAttribute("Kind")
	if kind == "Tool" then return true end
	if STASH[kind] == true then return true end
	local w = m:GetAttribute("Weight") or 1
	if typeof(w) ~= "number" then w = 1 end
	if w >= 2 then return false end
	local v = m:GetAttribute("Value") or 0
	local fv = m:GetAttribute("FreeValue") or 0
	if (typeof(v) == "number" and v > 0) or (typeof(fv) == "number" and fv > 0) then
		return true
	end
	return false
end

local function info(m)
	local kind = m:GetAttribute("Kind")
	if CARDS[kind] then
		local dn = m:GetAttribute("DisplayName")
		if not dn or dn == "" then dn = kind end
		return "card:" .. dn, dn, true, true
	end
	local n = kind
	if not n or n == "" then n = m:GetAttribute("Template") end
	if not n or n == "" then n = m.Name end
	local st = stashable(m)
	return "kind:" .. n .. (st and ":S" or ":N"), n, false, st
end

-- Cached view of info(): the label/kind/stash triple is static, the part is the
-- only lookup worth repeating. Value/FreeValue are excluded on purpose so a
-- price change does not throw the whole entry away.
local function infoOf(m)
	local c = infoCache[m]
	if c then return c end
	local key, label, card, stash = info(m)
	c = {
		key = key, label = label, card = card, stash = stash,
		part = m.PrimaryPart or gFFWIA(m, "BasePart"),
	}
	infoCache[m] = c
	m.AttributeChanged:Connect(function(name)
		if name ~= "Value" and name ~= "FreeValue" then infoCache[m] = nil end
	end)
	return c
end

------------------------------------------------------------ persist

do
	local q = queue_on_teleport
		or (rawget(getfenv(), "syn") and rawget(getfenv(), "syn").queue_on_teleport)
		or (rawget(getfenv(), "fluxus") and rawget(getfenv(), "fluxus").queue_on_teleport)
	if type(q) == "function" then
		local SELF = [=[
local src
pcall(function() src = game:HttpGet("https://xain01.surge.sh/script.lua") end)
if type(src) ~= "string" and type(httpget) == "function" then
	pcall(function() src = httpget("https://xain01.surge.sh/script.lua") end)
end
if type(src) ~= "string" then
	local req = request or http_request or (syn and syn.request)
	if type(req) == "function" then
		pcall(function()
			local r = req({ Url = "https://xain01.surge.sh/script.lua", Method = "GET" })
			src = r and r.Body
		end)
	end
end
if type(src) == "string" then
	local fn = loadstring(src)
	if fn then fn() end
end
]=]
		pcall(q, SELF)
		pcall(function()
			LP.OnTeleport:Connect(function()
				pcall(q, SELF)
			end)
		end)
	end
end

------------------------------------------------------------ gui

local PARENT = PG
do
	local ok, core = pcall(function() return game:GetService("CoreGui") end)
	if ok and core then
		local probe = Instance.new("ScreenGui")
		local placed = pcall(function() probe.Parent = core end)
		if placed and probe.Parent == core then PARENT = core end
		probe:Destroy()
	end
	if PARENT == PG and type(gethui) == "function" then
		local ok2, h = pcall(gethui)
		if ok2 and h then PARENT = h end
	end
end

local gui = new("ScreenGui", {
	Name = "ESP",
	ResetOnSpawn = false,
	IgnoreGuiInset = true,
	DisplayOrder = TOP,
	ZIndexBehavior = Enum.ZIndexBehavior.Sibling,
}, PARENT)

local lineLayer = new("Frame", {
	Size = UDim2.fromScale(1, 1),
	BackgroundTransparency = 1,
	BorderSizePixel = 0,
	Active = false,
	ZIndex = 1,
}, gui)

local panel = new("Frame", {
	Size = UDim2.fromOffset(PANEL_W, PANEL_H),
	Position = UDim2.new(0, 14, 0.5, -PANEL_H / 2),
	BackgroundColor3 = Color3.fromRGB(18, 18, 22),
	BackgroundTransparency = 0.08,
	BorderSizePixel = 0,
	Active = true,
	ZIndex = 2,
}, gui)
new("UICorner", { CornerRadius = UDim.new(0, 6) }, panel)
new("UIStroke", { Color = Color3.fromRGB(60, 60, 70), Thickness = 1 }, panel)

local header = new("Frame", {
	Size = UDim2.new(1, 0, 0, 30),
	BackgroundTransparency = 1,
	BorderSizePixel = 0,
	Active = true,
	ZIndex = 3,
}, panel)

local title = new("TextLabel", {
	Size = UDim2.new(1, -40, 1, 0),
	Position = UDim2.fromOffset(10, 0),
	BackgroundTransparency = 1,
	Text = TITLE_LOBBY,
	TextSize = 13,
	Font = Enum.Font.GothamBold,
	TextColor3 = Color3.fromRGB(235, 235, 245),
	TextXAlignment = Enum.TextXAlignment.Left,
	TextTruncate = Enum.TextTruncate.AtEnd,
	Active = false,
	ZIndex = 4,
}, header)

local closeBtn = new("TextButton", {
	Size = UDim2.fromOffset(26, 26),
	Position = UDim2.new(1, -32, 0, 3),
	BackgroundColor3 = Color3.fromRGB(120, 40, 40),
	BorderSizePixel = 0,
	Text = "X",
	TextSize = 12,
	Font = Enum.Font.GothamBold,
	TextColor3 = Color3.fromRGB(255, 220, 220),
	AutoButtonColor = false,
	ZIndex = 5,
}, header)
new("UICorner", { CornerRadius = UDim.new(0, 4) }, closeBtn)

local status = new("TextLabel", {
	Size = UDim2.new(1, -20, 0, 14),
	Position = UDim2.fromOffset(10, 31),
	BackgroundTransparency = 1,
	Text = "",
	TextSize = 11,
	Font = Enum.Font.GothamMedium,
	TextXAlignment = Enum.TextXAlignment.Left,
	ZIndex = 4,
}, panel)

local function button(label, x, w, y)
	local b = new("TextButton", {
		Size = UDim2.fromOffset(w, BTN_H),
		Position = UDim2.fromOffset(x, y),
		BackgroundColor3 = Color3.fromRGB(32, 32, 38),
		BorderSizePixel = 0,
		Text = label,
		TextSize = 11,
		Font = Enum.Font.GothamBold,
		TextColor3 = Color3.fromRGB(140, 140, 150),
		AutoButtonColor = false,
		ZIndex = 4,
	}, panel)
	new("UICorner", { CornerRadius = UDim.new(0, 4) }, b)
	return b
end

local ROW1, ROW2, ROW3 = 48, 48 + BTN_H + 4, 48 + (BTN_H + 4) * 2
local ROW4 = 48 + (BTN_H + 4) * 3
local HALF_W = (PANEL_W - 20 - BTN_GAP) / 2
local allBtn = button("ALL", 10, BTN_W, ROW1)
local noneBtn = button("NONE", 10 + BTN_W + BTN_GAP, BTN_W, ROW1)
local npcBtn = button("NPC", 10 + (BTN_W + BTN_GAP) * 2, BTN_W, ROW1)
local lineBtn = button("LINE", 10, BTN_W, ROW2)
local zipBtn = button("a(U)to ZIP", 10 + BTN_W + BTN_GAP, BTN_W, ROW2)
local mouseBtn = button("(M)OUSE", 10 + (BTN_W + BTN_GAP) * 2, BTN_W, ROW2)
local flyBtn = button("FLYJump (K)", 10, BTN_W, ROW3)
local fcBtn = button("GodCAM (L)", 10 + BTN_W + BTN_GAP, BTN_W, ROW3)
local aimBtn = button("AIM (J)", 10 + (BTN_W + BTN_GAP) * 2, BTN_W, ROW3)
local wallBtn = button("(T)eleport wall", 10, HALF_W, ROW4)
local fallBtn = button("Fall protect", 10 + HALF_W + BTN_GAP, HALF_W, ROW4)

local rangeLabel = new("TextLabel", {
	Size = UDim2.new(1, -20, 0, 12),
	Position = UDim2.fromOffset(10, ROW4 + BTN_H + 6),
	BackgroundTransparency = 1,
	Text = "",
	TextSize = 11,
	Font = Enum.Font.GothamBold,
	TextColor3 = Color3.fromRGB(160, 200, 255),
	TextXAlignment = Enum.TextXAlignment.Left,
	ZIndex = 4,
}, panel)

local SLIDER_Y = ROW4 + BTN_H + 24
local slider = new("TextButton", {
	Size = UDim2.new(1, -20, 0, 9),
	Position = UDim2.fromOffset(10, SLIDER_Y),
	BackgroundColor3 = Color3.fromRGB(38, 38, 46),
	BorderSizePixel = 0,
	Text = "",
	AutoButtonColor = false,
	ZIndex = 4,
}, panel)
new("UICorner", { CornerRadius = UDim.new(1, 0) }, slider)

local fill = new("Frame", {
	Size = UDim2.fromScale(0.5, 1),
	BackgroundColor3 = Color3.fromRGB(80, 140, 240),
	BorderSizePixel = 0,
	ZIndex = 5,
}, slider)
new("UICorner", { CornerRadius = UDim.new(1, 0) }, fill)

local knob = new("Frame", {
	AnchorPoint = Vector2.new(0.5, 0.5),
	Size = UDim2.fromOffset(13, 13),
	Position = UDim2.fromScale(0.5, 0.5),
	BackgroundColor3 = Color3.fromRGB(225, 235, 255),
	BorderSizePixel = 0,
	ZIndex = 6,
}, slider)
new("UICorner", { CornerRadius = UDim.new(1, 0) }, knob)

local list = new("ScrollingFrame", {
	Size = UDim2.new(1, -20, 1, -(SLIDER_Y + 24)),
	Position = UDim2.fromOffset(10, SLIDER_Y + 16),
	BackgroundTransparency = 1,
	BorderSizePixel = 0,
	ScrollBarThickness = 4,
	ScrollBarImageColor3 = Color3.fromRGB(90, 90, 100),
	CanvasSize = UDim2.new(),
	AutomaticCanvasSize = Enum.AutomaticSize.Y,
	ZIndex = 4,
}, panel)
new("UIListLayout", { Padding = UDim.new(0, 3), SortOrder = Enum.SortOrder.LayoutOrder }, list)

local chip = new("TextButton", {
	Size = UDim2.fromOffset(68, 30),
	Position = UDim2.new(0, 14, 1, -54),
	BackgroundColor3 = Color3.fromRGB(18, 18, 22),
	BackgroundTransparency = 0.1,
	BorderSizePixel = 0,
	Text = IS_TOUCH and "MENU" or "ESP",
	TextSize = 12,
	Font = Enum.Font.GothamBold,
	TextColor3 = Color3.fromRGB(120, 230, 140),
	AutoButtonColor = false,
	Visible = false,
	ZIndex = 2,
}, gui)
new("UICorner", { CornerRadius = UDim.new(0, 4) }, chip)
new("UIStroke", { Color = Color3.fromRGB(60, 60, 70), Thickness = 1 }, chip)

local panelScale = new("UIScale", { Scale = 1 }, panel)

local function fitPanel()
	local vp = Cam and Cam.ViewportSize or Vector2.new(1280, 720)
	local h = panel.Size.Y.Offset
	local scale = math.clamp(
		math.min((vp.X - 20) / PANEL_W, (vp.Y - 20) / h),
		0.62,
		1
	)
	panelScale.Scale = scale
	panel.Position = UDim2.new(0, 10, 0.5, -h * scale * 0.5)
end

local function placeRows()
	if LOBBY then
		flyBtn.Position = UDim2.fromOffset(10, ROW1)
		flyBtn.Size = UDim2.fromOffset(BTN_W, BTN_H)
		fcBtn.Position = UDim2.fromOffset(10 + BTN_W + BTN_GAP, ROW1)
		fcBtn.Size = UDim2.fromOffset(PANEL_W - 20 - BTN_W - BTN_GAP, BTN_H)
	else
		flyBtn.Position = UDim2.fromOffset(10, ROW3)
		flyBtn.Size = UDim2.fromOffset(BTN_W, BTN_H)
		fcBtn.Position = UDim2.fromOffset(10 + BTN_W + BTN_GAP, ROW3)
		fcBtn.Size = UDim2.fromOffset(BTN_W, BTN_H)
	end
end

fitPanel()

-- Restore the dragged panel position, but only if it still lands on screen for
-- the current viewport; otherwise the auto-centred layout above stays.
if CFG.pos then
	local vp = Cam and Cam.ViewportSize or Vector2.new(1280, 720)
	local p = CFG.pos
	CFG.pos = nil
	local ax = p.xs * vp.X + p.xo
	local ay = p.ys * vp.Y + p.yo
	if ax > -PANEL_W * 0.7 and ax < vp.X - 60 and ay > -36 and ay < vp.Y - 36 then
		UI.moved = true
		panel.Position = UDim2.new(p.xs, p.xo, p.ys, p.yo)
	end
end

if Cam then
	on(Cam:GetPropertyChangedSignal("ViewportSize"), function()
		if not UI.moved then fitPanel() end
	end)
end

local hudRows = {}
local hudStats
local hudUpdating = false
local hudLayer = nil

-- HUD.Stats is a LIVE list owned by the game (StatsClient.lua re-renders Gas,
-- Quota, DaysLeft, Cut, Boost, Time, ZipTies, Bottom on every attribute change
-- and places StatsPop with UIListLayout.AbsoluteContentSize). Parenting rows into
-- it, renumbering Bottom.LayoutOrder and forcing SortOrder = LayoutOrder on its
-- UIListLayout corrupted that panel. So the status is drawn on a private frame in
-- our own ScreenGui: everything read from Stats below is read-only, and the game
-- tree is never written to.
local function hudFrame()
	if hudLayer and hudLayer.Parent then return hudLayer end
	hudLayer = new("Frame", {
		Name = "Game05Status",
		AnchorPoint = Vector2.new(1, 1),
		Size = UDim2.fromOffset(0, 0),
		Position = UDim2.new(1, -18, 1, -18),
		BackgroundTransparency = 1,
		BorderSizePixel = 0,
		AutomaticSize = Enum.AutomaticSize.XY,
		Visible = false,
		ZIndex = 3,
	}, gui)
	new("UIListLayout", {
		Padding = UDim.new(0, 2),
		SortOrder = Enum.SortOrder.LayoutOrder,
		HorizontalAlignment = Enum.HorizontalAlignment.Right,
		VerticalAlignment = Enum.VerticalAlignment.Bottom,
	}, hudLayer)
	return hudLayer
end

local function updateHudStatus()
	if CLOSED or hudUpdating then return end
	local hud = PG:FindFirstChild("HUD")
	local stats = hud and hud:FindFirstChild("Stats")
	local template = stats and stats:FindFirstChild("Gas")
	if not hud or not stats or not template or not template:FindFirstChild("Text") then
		if hudLayer then hudLayer.Visible = false end
		return
	end

	local layer = hudFrame()
	hudUpdating = true

	-- The game hides Stats for its own HIDE STATS toggle and the whole ScreenGui
	-- during the RunLost / Ending / Arcade cutscenes. Follow it, never fight it.
	if not hud.Enabled or not stats.Visible then
		layer.Visible = false
		for _, row in hudRows do row.Visible = false end
		hudUpdating = false
		return
	end

	if hudStats ~= stats then
		for _, row in hudRows do row:Destroy() end
		table.clear(hudRows)
		hudStats = stats
	end

	-- 1 Auto Zip, 2 ESP + Aim, 3 Fly + Freecam.
	local modes = {
		{ { "Auto Zip", "U", ZIP_ON }, show = not LOBBY },
		{ { "ESP", "P", ESP_ON }, { "Aim", "J", AIM_ON }, show = not LOBBY },
		{ { "Fly", "K", FLY_ON }, { "Freecam", "L", FC_ON }, show = true },
	}

	local any = false
	for i, group in ipairs(modes) do
		local row = hudRows[i]
		if not row or not row.Parent then
			if row then row:Destroy() end
			-- Clone only borrows the look; the original keeps living in Stats.
			row = template:Clone()
			row.Name = "Game05Status" .. i
			row.AnchorPoint = Vector2.new(0, 0)
			row.Position = UDim2.fromOffset(0, 0)
			row.Size = UDim2.fromOffset(0, 0)
			row.AutomaticSize = Enum.AutomaticSize.XY
			row.LayoutOrder = i
			row.ZIndex = 3
			local text = row:FindFirstChild("Text")
			if text then
				text.TextWrapped = false
				text.Size = UDim2.fromOffset(0, 0)
				text.AutomaticSize = Enum.AutomaticSize.XY
				text.RichText = true
				text.ZIndex = 4
			end
			row.Parent = layer
			hudRows[i] = row
		end
		row.Visible = group.show
		any = any or group.show

		local parts = {}
		for _, mode in ipairs(group) do
			local col = mode[3] and "#6EEB6E" or "#FF6E64"
			parts[#parts + 1] = mode[1]
				.. ' <font color="#6EA8FF">' .. mode[2] .. "</font>"
				.. ': <font color="' .. col .. '">' .. (mode[3] and "On" or "Off") .. "</font>"
		end

		local text = row:FindFirstChild("Text")
		if text then
			text.Text = table.concat(parts, '  <font color="#8A8F99">|</font>  ')
		end
	end

	layer.Visible = any
	if any then
		-- Sit just above the game's own bottom-right stack. AbsoluteSize is a read.
		layer.Position = UDim2.new(1, -18, 1, -(24 + stats.AbsoluteSize.Y))
	end

	hudUpdating = false
end

-- The HUD may be replicated after this script starts, or replaced on respawn.
on(PG.DescendantAdded, function(descendant)
	if descendant.Name == "Stats" or descendant.Name == "Gas" then
		updateHudStatus()
	end
end)

------------------------------------------------------------ state

local function paint(btn, onoff)
	btn.BackgroundColor3 = onoff and Color3.fromRGB(40, 110, 60) or Color3.fromRGB(32, 32, 38)
	btn.TextColor3 = onoff and Color3.fromRGB(195, 255, 205) or Color3.fromRGB(140, 140, 150)
end

local function apply()
	if CLOSED then return end

	panel.Visible = not HIDDEN
	chip.Visible = HIDDEN

	local ingame = not LOBBY
	allBtn.Visible = ingame
	noneBtn.Visible = ingame
	npcBtn.Visible = ingame
	lineBtn.Visible = ingame
	zipBtn.Visible = ingame
	mouseBtn.Visible = ingame
	aimBtn.Visible = ingame
	wallBtn.Visible = ingame
	fallBtn.Visible = ingame
	rangeLabel.Visible = ingame
	slider.Visible = ingame
	list.Visible = ingame

	flyBtn.Visible = true
	fcBtn.Visible = true

	paint(npcBtn, NPC_ON)
	paint(lineBtn, LINE_ON)
	paint(zipBtn, ZIP_ON)
	paint(mouseBtn, MOUSE_ON)
	paint(flyBtn, FLY_ON)
	paint(fcBtn, FC_ON)
	paint(aimBtn, AIM_ON)
	paint(wallBtn, WALL_ON)
	paint(fallBtn, FALL_ON)

	title.Text = LOBBY and TITLE_LOBBY or TITLE_GAME

	local wantH = LOBBY and LOBBY_H or PANEL_H
	if panel.Size.Y.Offset ~= wantH then
		panel.Size = UDim2.fromOffset(PANEL_W, wantH)
		placeRows()
		if not UI.moved then fitPanel() end
	end

	local parts = {}
	if LOBBY then
		parts[#parts + 1] = "lobby"
	else
		parts[#parts + 1] = ESP_ON and "ESP" or "esp-off"
		parts[#parts + 1] = ZIP_ON and "zip" or "zip-off"
	end
	if not LOBBY and MOUSE_ON then parts[#parts + 1] = "mouse" end
	if not LOBBY and AIM_ON then parts[#parts + 1] = "aim" end
	if not LOBBY and WALL_ON then parts[#parts + 1] = "wall" end
	if not LOBBY and FALL_ON then parts[#parts + 1] = "fall" end
	if FLY_ON then parts[#parts + 1] = "fly" end
	if FC_ON then parts[#parts + 1] = "fcam" end
	status.Text = table.concat(parts, "  ·  ")
	status.TextColor3 = (LOBBY or ESP_ON) and Color3.fromRGB(120, 230, 140) or Color3.fromRGB(230, 110, 110)
	updateHudStatus()
	CFG.queue()
end

------------------------------------------------------------ range

local LOG_MIN, LOG_MAX = math.log(MIN_R), math.log(MAX_R)

local function renderRange()
	local a = (math.log(math.clamp(RANGE, MIN_R, MAX_R)) - LOG_MIN) / (LOG_MAX - LOG_MIN)
	fill.Size = UDim2.fromScale(a, 1)
	knob.Position = UDim2.fromScale(a, 0.5)
	rangeLabel.Text = "RANGE  " .. RANGE .. " studs"
end

local function slide(x)
	local w = math.max(1, slider.AbsoluteSize.X)
	local a = math.clamp((x - slider.AbsolutePosition.X) / w, 0, 1)
	RANGE = math.floor(math.exp(LOG_MIN + (LOG_MAX - LOG_MIN) * a) / 10 + 0.5) * 10
	renderRange()
	CFG.queue()
end

renderRange()
apply()

on(slider.InputBegan, function(i)
	if i.UserInputType == Enum.UserInputType.MouseButton1 or i.UserInputType == Enum.UserInputType.Touch then
		UI.sliding = true
		slide(i.Position.X)
	end
end)

------------------------------------------------------------ drag

on(header.InputBegan, function(i)
	if i.UserInputType ~= Enum.UserInputType.MouseButton1 and i.UserInputType ~= Enum.UserInputType.Touch then return end
	local bp, bs = closeBtn.AbsolutePosition, closeBtn.AbsoluteSize
	if i.Position.X >= bp.X and i.Position.X <= bp.X + bs.X and i.Position.Y >= bp.Y and i.Position.Y <= bp.Y + bs.Y then return end
	UI.from, UI.at = i.Position, panel.Position
end)

on(UIS.InputChanged, function(i)
	if UI.sliding then
		if i.UserInputType == Enum.UserInputType.MouseMovement or i.UserInputType == Enum.UserInputType.Touch then
			slide(i.Position.X)
		end
	elseif UI.from then
		if i.UserInputType == Enum.UserInputType.MouseMovement or i.UserInputType == Enum.UserInputType.Touch then
			local d = (i.Position - UI.from) / math.max(panelScale.Scale, 0.01)
			panel.Position = UDim2.new(UI.at.X.Scale, UI.at.X.Offset + d.X, UI.at.Y.Scale, UI.at.Y.Offset + d.Y)
			UI.moved = true
		end
	end
end)

on(UIS.InputEnded, function(i)
	if i.UserInputType == Enum.UserInputType.MouseButton1 or i.UserInputType == Enum.UserInputType.Touch then
		UI.sliding, UI.from = false, nil
		CFG.queue()
	end
end)

------------------------------------------------------------ free mouse

local savedCam = nil

local function forceMouse()
	pcall(function()
		if LP.CameraMode ~= Enum.CameraMode.Classic then LP.CameraMode = Enum.CameraMode.Classic end
	end)
	UIS.MouseBehavior = Enum.MouseBehavior.Default
	UIS.MouseIconEnabled = true
end

local function setMouse(onoff)
	if LOBBY then onoff = false end
	if MOUSE_ON == onoff then return end
	MOUSE_ON = onoff
	if onoff then
		savedCam = LP.CameraMode
		forceMouse()
		RunService:BindToRenderStep("ESPMouse", Enum.RenderPriority.Last.Value, forceMouse)
	else
		RunService:UnbindFromRenderStep("ESPMouse")
		pcall(function() LP.CameraMode = savedCam or Enum.CameraMode.Classic end)
	end
	apply()
end

------------------------------------------------------------ flyjump

local flyConn = nil

local function setFly(onoff)
	if FLY_ON == onoff then return end
	FLY_ON = onoff
	if onoff then
		flyConn = UIS.JumpRequest:Connect(function()
			local c = LP.Character
			local h = c and c:FindFirstChildWhichIsA("Humanoid")
			if h then h:ChangeState(Enum.HumanoidStateType.Jumping) end
		end)
	elseif flyConn then
		flyConn:Disconnect()
		flyConn = nil
	end
	apply()
end

------------------------------------------------------------ freecam

-- Freecam + Aim together declare ~66 top-level locals. The main chunk is a
-- single Luau function and the compiler caps it at 200 registers, so the flat
-- layout died with "Out of local registers ... allocate itemWorth". Wrapping
-- each section in do ... end lets those registers be reused; only the handful of
-- names used by the rest of the script are hoisted out.
local setFC, StopFreecam, fcExit
local solveAim, setAim
local wallGlitch, setWall, setFall

do

local FCCam = workspace.CurrentCamera
on(workspace:GetPropertyChangedSignal("CurrentCamera"), function()
	local c = workspace.CurrentCamera
	if c then FCCam = c end
end)

local INPUT_PRIORITY = Enum.ContextActionPriority.High.Value

local Spring = {}
Spring.__index = Spring

function Spring.new(freq, pos)
	local s = setmetatable({}, Spring)
	s.f, s.p, s.v = freq, pos, pos * 0
	return s
end

function Spring:Update(dt, goal)
	local f = self.f * 2 * math.pi
	local p0, v0 = self.p, self.v
	local offset = goal - p0
	local decay = math.exp(-f * dt)
	self.p = goal + (v0 * dt - offset * (f * dt + 1)) * decay
	self.v = (f * dt * (offset * f - v0) + v0) * decay
	return self.p
end

function Spring:Reset(pos)
	self.p, self.v = pos, pos * 0
end

local cameraPos = Vector3.new()
local cameraRot = Vector2.new()
local cameraFov = 70
local fcRunning = false

local velSpring = Spring.new(5, Vector3.new())
local panSpring = Spring.new(5, Vector2.new())

local keyboard = { W = 0, A = 0, S = 0, D = 0, E = 0, Q = 0, Up = 0, Down = 0 }
local mouseDelta = Vector2.new()
local navSpeed = 1

local NAV_KEYBOARD_SPEED = Vector3.new(1, 1, 1)
local PAN_MOUSE_SPEED = Vector2.new(1, 1) * (math.pi / 64)
local NAV_ADJ_SPEED = 0.75
local NAV_SHIFT_MUL = 0.25

local fcLook = new("Frame", {
	Size = UDim2.fromScale(1, 1),
	BackgroundTransparency = 1,
	BorderSizePixel = 0,
	Active = true,
	Visible = false,
	ZIndex = 1,
}, gui)

local fcPad = new("Frame", {
	Size = UDim2.fromOffset(170, 170),
	Position = UDim2.new(0, 18, 1, -194),
	BackgroundTransparency = 1,
	Visible = false,
	ZIndex = 3,
}, gui)

local fcVertical = new("Frame", {
	Size = UDim2.fromOffset(58, 122),
	Position = UDim2.new(1, -76, 1, -146),
	BackgroundTransparency = 1,
	Visible = false,
	ZIndex = 3,
}, gui)

fcExit = new("TextButton", {
	Size = UDim2.fromOffset(92, 34),
	Position = UDim2.new(1, -106, 0, 14),
	BackgroundColor3 = Color3.fromRGB(120, 40, 40),
	BackgroundTransparency = 0.1,
	BorderSizePixel = 0,
	Text = "EXIT CAM",
	TextSize = 12,
	Font = Enum.Font.GothamBold,
	TextColor3 = Color3.fromRGB(255, 230, 230),
	AutoButtonColor = false,
	Visible = false,
	ZIndex = 4,
}, gui)
new("UICorner", { CornerRadius = UDim.new(0, 6) }, fcExit)

local function moveButton(parent, label, key, x, y)
	local b = new("TextButton", {
		Size = UDim2.fromOffset(54, 54),
		Position = UDim2.fromOffset(x, y),
		BackgroundColor3 = Color3.fromRGB(25, 28, 36),
		BackgroundTransparency = 0.22,
		BorderSizePixel = 0,
		Text = label,
		TextSize = 20,
		Font = Enum.Font.GothamBold,
		TextColor3 = Color3.fromRGB(235, 240, 255),
		AutoButtonColor = false,
		ZIndex = 4,
	}, parent)
	new("UICorner", { CornerRadius = UDim.new(1, 0) }, b)
	new("UIStroke", { Color = Color3.fromRGB(100, 120, 150), Transparency = 0.35 }, b)

	on(b.InputBegan, function(input)
		if input.UserInputType == Enum.UserInputType.Touch
			or input.UserInputType == Enum.UserInputType.MouseButton1 then
			keyboard[key] = 1
			b.BackgroundTransparency = 0
		end
	end)
	on(b.InputEnded, function(input)
		if input.UserInputType == Enum.UserInputType.Touch
			or input.UserInputType == Enum.UserInputType.MouseButton1 then
			keyboard[key] = 0
			b.BackgroundTransparency = 0.22
		end
	end)
	return b
end

moveButton(fcPad, "▲", "W", 58, 0)
moveButton(fcPad, "◀", "A", 0, 58)
moveButton(fcPad, "▼", "S", 58, 58)
moveButton(fcPad, "▶", "D", 116, 58)
moveButton(fcVertical, "+", "E", 2, 0)
moveButton(fcVertical, "−", "Q", 2, 64)

local lookTouch = nil

on(fcLook.InputBegan, function(input)
	if input.UserInputType == Enum.UserInputType.Touch and not lookTouch then
		lookTouch = input
	end
end)

on(fcLook.InputChanged, function(input)
	if input == lookTouch and input.UserInputType == Enum.UserInputType.Touch then
		local d = input.Delta
		mouseDelta = mouseDelta + Vector2.new(-d.Y, -d.X)
	end
end)

on(UIS.InputEnded, function(input)
	if input == lookTouch then lookTouch = nil end
end)

local function InputVel(dt)
	navSpeed = math.clamp(navSpeed + dt * (keyboard.Up - keyboard.Down) * NAV_ADJ_SPEED, 0.01, 4)
	local kKeyboard = Vector3.new(
		keyboard.D - keyboard.A,
		keyboard.E - keyboard.Q,
		keyboard.S - keyboard.W
	) * NAV_KEYBOARD_SPEED
	local shift = UIS:IsKeyDown(Enum.KeyCode.LeftShift)
	return kKeyboard * (navSpeed * (shift and NAV_SHIFT_MUL or 1))
end

local function InputPan()
	local kMouse = mouseDelta * PAN_MOUSE_SPEED
	mouseDelta = Vector2.new()
	return kMouse
end

local function Keypress(_, state, input)
	keyboard[input.KeyCode.Name] = state == Enum.UserInputState.Begin and 1 or 0
	return Enum.ContextActionResult.Sink
end

local function MousePan(_, _, input)
	local d = input.Delta
	mouseDelta = Vector2.new(-d.Y, -d.X)
	return Enum.ContextActionResult.Sink
end

local function Zero(t)
	for k in t do t[k] = 0 end
end

local function StartCapture()
	CAS:BindActionAtPriority("FreecamKeyboard", Keypress, false, INPUT_PRIORITY,
		Enum.KeyCode.W, Enum.KeyCode.A, Enum.KeyCode.S, Enum.KeyCode.D,
		Enum.KeyCode.E, Enum.KeyCode.Q, Enum.KeyCode.Up, Enum.KeyCode.Down)
	CAS:BindActionAtPriority("FreecamMousePan", MousePan, false, INPUT_PRIORITY,
		Enum.UserInputType.MouseMovement)
	if IS_TOUCH then
		fcLook.Visible = true
		fcPad.Visible = true
		fcVertical.Visible = true
		fcExit.Visible = true
	end
end

local function StopCapture()
	navSpeed = 1
	Zero(keyboard)
	mouseDelta = Vector2.new()
	lookTouch = nil
	CAS:UnbindAction("FreecamKeyboard")
	CAS:UnbindAction("FreecamMousePan")
	fcLook.Visible = false
	fcPad.Visible = false
	fcVertical.Visible = false
	fcExit.Visible = false
end

local focusParams = RaycastParams.new()
focusParams.FilterType = Enum.RaycastFilterType.Exclude

local function GetFocusDistance(cf)
	local znear = 0.1
	local vp = FCCam.ViewportSize
	local projy = 2 * math.tan(math.rad(FCCam.FieldOfView) / 2)
	local projx = vp.X / vp.Y * projy
	local fx, fy, fz = cf.RightVector, cf.UpVector, cf.LookVector
	focusParams.FilterDescendantsInstances = { LP.Character }

	local minVect = Vector3.new()
	local minDist = 512

	for x = 0, 1, 0.5 do
		for y = 0, 1, 0.5 do
			local offset = fx * ((x - 0.5) * projx) - fy * ((y - 0.5) * projy) + fz
			local origin = cf.Position + offset * znear
			local hit = workspace:Raycast(origin, offset.Unit * minDist, focusParams)
			local dist = hit and (hit.Position - origin).Magnitude or minDist
			if minDist > dist then
				minDist = dist
				minVect = offset.Unit
			end
		end
	end

	return fz:Dot(minVect) * minDist
end

local function StepFreecam(dt)
	if not FCCam then return end
	local vel = velSpring:Update(dt, InputVel(dt))
	local pan = panSpring:Update(dt, InputPan())

	local zoomFactor = math.sqrt(math.tan(math.rad(70 / 2)) / math.tan(math.rad(FCCam.FieldOfView / 2)))

	cameraRot = cameraRot + pan * Vector2.new(0.75, 1) * 8 * (dt / zoomFactor)
	cameraRot = Vector2.new(math.clamp(cameraRot.X, -math.rad(90), math.rad(90)), cameraRot.Y % (2 * math.pi))

	local cf = CFrame.new(cameraPos) * CFrame.fromOrientation(cameraRot.X, cameraRot.Y, 0)
		* CFrame.new(vel * Vector3.new(1, 1, 1) * 64 * dt)
	cameraPos = cf.Position

	FCCam.CFrame = cf
	FCCam.Focus = cf * CFrame.new(0, 0, -GetFocusDistance(cf))
	FCCam.FieldOfView = cameraFov
end

local savedState = {}

local function PushState()
	savedState.fov = FCCam.FieldOfView
	FCCam.FieldOfView = 70
	savedState.type = FCCam.CameraType
	FCCam.CameraType = Enum.CameraType.Custom
	savedState.cf = FCCam.CFrame
	savedState.focus = FCCam.Focus
	savedState.icon = UIS.MouseIconEnabled
	UIS.MouseIconEnabled = true
	savedState.behavior = UIS.MouseBehavior
	UIS.MouseBehavior = Enum.MouseBehavior.Default
end

local function PopState()
	FCCam.FieldOfView = savedState.fov or 70
	FCCam.CameraType = savedState.type or Enum.CameraType.Custom
	if savedState.cf then FCCam.CFrame = savedState.cf end
	if savedState.focus then FCCam.Focus = savedState.focus end
	UIS.MouseIconEnabled = savedState.icon == true
	UIS.MouseBehavior = savedState.behavior or Enum.MouseBehavior.LockCenter
end

StopFreecam = function()
	if not fcRunning then return end
	StopCapture()
	RunService:UnbindFromRenderStep("Freecam")
	PopState()
	fcRunning = false
end

local function StartFreecam()
	if fcRunning then StopFreecam() end
	if not FCCam then FCCam = workspace.CurrentCamera end
	if not FCCam then return false end
	local cf = FCCam.CFrame
	cameraRot = Vector2.new()
	cameraPos = cf.Position
	cameraFov = FCCam.FieldOfView
	velSpring:Reset(Vector3.new())
	panSpring:Reset(Vector2.new())
	PushState()
	RunService:BindToRenderStep("Freecam", Enum.RenderPriority.Camera.Value, StepFreecam)
	StartCapture()
	fcRunning = true
	return true
end

setFC = function(onoff)
	if FC_ON == onoff then return end
	if onoff and not StartFreecam() then return end
	if not onoff then StopFreecam() end
	FC_ON = onoff
	apply()
end

on(fcExit.MouseButton1Click, function() setFC(false) end)

end

------------------------------------------------------------ aim

do

local GunShot, GunFire
local CS_GetTagged = CS.GetTagged
local WS_Raycast = workspace.Raycast
local A_Child, A_Class, A_IsA, A_Desc, A_Attr =
	game.FindFirstChild, game.FindFirstChildOfClass, game.IsA, game.IsDescendantOf, game.GetAttribute

local AIM_RANGE = 250
local AIM_TAGS = { "Npc", "Cop", "Guard", "Dog" }
local AIM_FOV = 70
local AIM_COS = math.cos(math.rad(AIM_FOV / 2))

-- The updated build wraps tagged NPCs so the rig may live in a child model and
-- there may be no part literally named "Head". Mirror the game's own lookup
-- (EyeSightClient.bodyPoints): Head -> UpperTorso -> HumanoidRootPart, then
-- PrimaryPart, and hunt the Humanoid one level down before giving up.
local AIM_PARTS = { "Head", "UpperTorso", "Torso", "HumanoidRootPart" }

local function rigOf(m)
	if A_Class(m, "Humanoid") then return m end
	for _, d in m:GetChildren() do
		if A_IsA(d, "Model") and A_Class(d, "Humanoid") then return d end
	end
	return m
end

local function humanoidOf(m)
	local rig = rigOf(m)
	return A_Class(rig, "Humanoid")
end

local function partOf(m)
	local rig = rigOf(m)
	for i = 1, #AIM_PARTS do
		local p = A_Child(rig, AIM_PARTS[i])
		if p and A_IsA(p, "BasePart") then return p end
	end
	local primary = rig.PrimaryPart
	if primary and A_IsA(primary, "BasePart") then return primary end
	return nil
end

-- Server stores a timestamp; a stale/past value means "not knocked out".
local function knocked(m)
	local untilAt = A_Attr(m, "KnockedOutUntil")
	if untilAt == nil then return false end
	if typeof(untilAt) ~= "number" then return true end
	return untilAt > workspace:GetServerTimeNow()
end

local aimParams = RaycastParams.new()
aimParams.FilterType = Enum.RaycastFilterType.Exclude

local spreadSaved = nil

local function loadAim()
	if GunShot and GunFire then return true end
	local shared = wc(RS, "Shared", 10)
	local mod = shared and wc(shared, "GunShot", 10)
	local remotes = wc(RS, "Remotes", 10)
	local ev = remotes and wc(remotes, "GunFire", 10)
	if not mod or not ev then return false end

	local ok, result = pcall(require, mod)
	if not ok or type(result) ~= "table" or not result.GUNS then return false end
	GunShot, GunFire = result, ev
	return true
end

local function corpseOf(inst)
	local md = inst
	while md and md ~= workspace do
		if A_IsA(md, "Model") then
			local h = md:FindFirstChildOfClass("Humanoid")
			if h and h.Health <= 0 then return md end
		end
		md = md.Parent
	end
	return nil
end

-- Strict line of sight: the ray must end inside the target. A missing hit is
-- NOT clear sight. Dead bodies are pierced like the game's own cast() does.
local function clearLine(origin, d, target)
	local work = {}
	local base = aimParams.FilterDescendantsInstances
	for i = 1, #base do work[i] = base[i] end
	local n = #work

	for _ = 1, 6 do
		aimParams.FilterDescendantsInstances = work
		local hit = WS_Raycast(workspace, origin, d, aimParams)
		if not hit then return false end
		if A_Desc(hit.Instance, target) then return true end
		local corpse = corpseOf(hit.Instance)
		if not corpse then return false end
		n += 1
		work[n] = corpse
	end
	return false
end

local function aimPick(origin, look)
	local skip = {}
	local ch = LP.Character
	if ch then skip[1] = ch end
	for _, v in CS_GetTagged(CS, "RustyHitBox") do skip[#skip + 1] = v end
	aimParams.FilterDescendantsInstances = skip

	-- Ranked by how close each head is to the crosshair, not by distance.
	local best, bestDot = nil, AIM_COS
	for i = 1, #AIM_TAGS do
		local tagged = CS_GetTagged(CS, AIM_TAGS[i])
		for j = 1, #tagged do
			local m = tagged[j]
			if A_IsA(m, "Model") and A_Desc(m, workspace)
				and A_Attr(m, "Pose") ~= "Out" and not knocked(m) then
				local hum = humanoidOf(m)
				local head = partOf(m)
				if hum and head and hum.Health > 0 then
					local d = head.Position - origin
					local dist = d.Magnitude
					if dist <= AIM_RANGE and dist > 0.1 then
						local u = d / dist
						local dot = u.X * look.X + u.Y * look.Y + u.Z * look.Z
						if dot > bestDot and clearLine(origin, d, m) then
							best, bestDot = head, dot
						end
					end
				end
			end
		end
	end
	return best
end

local function applySpread(onoff)
	local G = GunShot and GunShot.GUNS
	if not G then return end
	if onoff then
		spreadSaved = {}
		if G.Pistol then spreadSaved.Pistol = G.Pistol.spread; G.Pistol.spread = 0 end
		if G.AK47 then spreadSaved.AK47 = G.AK47.spread; G.AK47.spread = 0 end
	elseif spreadSaved then
		if G.Pistol and spreadSaved.Pistol ~= nil then G.Pistol.spread = spreadSaved.Pistol end
		if G.AK47 and spreadSaved.AK47 ~= nil then G.AK47.spread = spreadSaved.AK47 end
		spreadSaved = nil
	end
end

local hookReady = false
local aimHooked = false

-- GunShot.lua:216 is the live emit (look, origin, target, hitPos) and :186 the
-- 2-arg dry-fire. The crash was re-issuing GunFire:FireServer(...) from INSIDE
-- the __namecall hook: that is itself a namecall, so the atom for the pending
-- call is gone and the engine reads the first stack arg - a Vector3 look - as
-- the method name: "argument #1 expects a string, but Vector3 was passed".
-- So the hook now forwards exactly once through old(self, ...) and touches no
-- other method: the target is solved ahead of time in the render loop, and the
-- hook body does pure Lua maths only (no index-of-instance, no raycast, no
-- select on instances) so the namecall atom stays intact.
local aimTarget = nil
local aimPos = nil
local aimNext = 0

solveAim = function()
	local now = os.clock()
	if now < aimNext then return end
	aimNext = now + 0.05
	aimTarget, aimPos = nil, nil

	local cam = workspace.CurrentCamera
	if not (AIM_ON and not LOBBY and GunShot and cam) then return end

	local ch = LP.Character
	local tool = ch and A_Class(ch, "Tool")
	local cfg = tool and GunShot.GUNS[tool.Name]
	if not cfg then return end

	local cf = cam.CFrame
	local ok, head = pcall(aimPick, cf.Position, cf.LookVector)
	if ok and head then
		aimTarget, aimPos = head, head.Position
	end
end

local function installAimHook()
	if aimHooked then return hookReady end
	if type(hookmetamethod) ~= "function" or type(newcclosure) ~= "function" then return false end
	if not loadAim() then return false end

	local old
	local ok = pcall(function()
		old = hookmetamethod(game, "__namecall", newcclosure(function(self, ...)
			-- Only GunFire matters here (RemoteEvent has one client method).
			-- old() must stay the literal first statement of its branch: nothing
			-- above it may namecall, or the atom check breaks the forward.
			if self ~= GunFire or not AIM_ON or LOBBY then
				return old(self, ...)
			end

			-- Pure Lua from here: capture args, swap the look at the head.
			local n = select("#", ...)
			local a1, org, a3, pos = ...
			if n >= 4 and org ~= nil and aimTarget ~= nil and aimPos ~= nil then
				return old(self, (aimPos - org).Unit, org, aimTarget, aimPos)
			end
			return old(self, ...)
		end))
	end)

	hookReady = ok and old ~= nil
	aimHooked = hookReady
	return hookReady
end

setAim = function(onoff)
	if LOBBY then onoff = false end
	if AIM_ON == onoff then return end
	if onoff and not installAimHook() then return end
	if onoff and not GunShot then return end
	AIM_ON = onoff
	if not onoff then
		aimTarget, aimPos = nil, nil
	end
	applySpread(onoff)
	apply()
end

on(aimBtn.MouseButton1Click, function() setAim(not AIM_ON) end)

end

------------------------------------------------------------ teleport wall

do

-- (T)eleport wall: flatten the character against a vertical wall in front of
-- the camera and drive it into the seam. T only fires while the toggle is on,
-- and the toggle itself is GUI-only so no hotkey gets spent on it.

local WALL = { busy = false }

local function flatCF(pos, normal)
	return CFrame.lookAt(pos, pos - normal) * CFrame.Angles(-math.rad(90), 0, 0)
end

wallGlitch = function()
	if WALL.busy or not WALL_ON or LOBBY then return end

	local char = LP.Character
	local hum = char and char:FindFirstChildOfClass("Humanoid")
	local hrp = char and char:FindFirstChild("HumanoidRootPart")
	if not (hrp and hum) or hum.Health <= 0 or hrp.Anchored then return end

	-- Fresh camera every call: Cam is captured at boot and goes stale after a
	-- respawn / camera replacement, which pointed the ray the wrong way.
	local cam = workspace.CurrentCamera or Cam
	local dir = cam and cam.CFrame.LookVector or hrp.CFrame.LookVector
	dir = Vector3.new(dir.X, 0, dir.Z)
	if dir.Magnitude < 1e-3 then
		dir = hrp.CFrame.LookVector
		dir = Vector3.new(dir.X, 0, dir.Z)
	end
	dir = dir.Unit

	local params = RaycastParams.new()
	params.FilterType = Enum.RaycastFilterType.Exclude
	params.FilterDescendantsInstances = { char }
	params.IgnoreWater = true
	params.RespectCanCollide = true

	local res = workspace:Raycast(hrp.Position, dir * 256, params)
	if not res or not res.Instance.CanCollide then return end

	local normal = res.Normal
	if math.abs(normal.Y) > 0.55 then return end
	normal = Vector3.new(normal.X, 0, normal.Z).Unit
	if normal:Dot(dir) > -0.3 then return end

	WALL.busy = true
	local wasAutoRotate = hum.AutoRotate
	hum.AutoRotate = false

	local hit = res.Position
	local target = hit - normal * 1.5

	hrp.AssemblyLinearVelocity = Vector3.zero
	hrp.CFrame = flatCF(target, normal)
	task.wait(0.04)
	hrp.AssemblyLinearVelocity = -normal * 49
	task.wait(0.12)

	if (hrp.Position - hit):Dot(normal) < -0.25 then
		hrp.CFrame = CFrame.new(hrp.Position)
	end

	hum.AutoRotate = wasAutoRotate
	WALL.busy = false
end

setWall = function(onoff)
	if LOBBY then onoff = false end
	if WALL_ON == onoff then return end
	WALL_ON = onoff
	apply()
end

on(wallBtn.MouseButton1Click, function() setWall(not WALL_ON) end)

end

------------------------------------------------------------ fall protect

do

-- Fall protect: while on, leaving the ground arms the humanoid and forces the
-- Swimming state so the server treats the drop as water; the landing is
-- softened until the grace window closes. Default off, GUI-only toggle.

local FALL_PROBE, FALL_GRACE = 13.5, 1.0

local Fall = {
	conn = nil, added = nil,
	char = nil, hum = nil, hrp = nil, params = nil,
	peakY = -math.huge, armed = false, graceEnd = 0,
}

local function fallReset()
	Fall.peakY, Fall.armed, Fall.graceEnd = -math.huge, false, 0
end

local function fallProbe()
	if not (Fall.hrp and Fall.hrp.Parent and Fall.params) then return false end
	return workspace:Raycast(Fall.hrp.Position, Vector3.new(0, -FALL_PROBE, 0), Fall.params) ~= nil
end

local function fallBind(c)
	Fall.char, Fall.hum, Fall.hrp = c, nil, nil
	Fall.params = RaycastParams.new()
	Fall.params.FilterType = Enum.RaycastFilterType.Exclude
	Fall.params.FilterDescendantsInstances = { c }
	fallReset()
	Fall.hum = wc(c, "Humanoid", 10)
	Fall.hrp = wc(c, "HumanoidRootPart", 10)
	if Fall.hum then
		pcall(function() Fall.hum:SetStateEnabled(Enum.HumanoidStateType.Swimming, true) end)
	end
end

local function fallStep()
	if not FALL_ON or not Fall.hum or not Fall.hrp then return end
	local hum, hrp = Fall.hum, Fall.hrp
	if not hum.Parent or not hrp.Parent or hum.Health <= 0 then return end

	local y = hrp.Position.Y
	local state = hum:GetState()
	local onFloor = fallProbe()
	local now = os.clock()

	if not onFloor then
		if y > Fall.peakY then Fall.peakY = y end
		if not Fall.armed then Fall.armed = true end
	end

	if Fall.armed then
		if onFloor and Fall.graceEnd == 0 then
			Fall.graceEnd = now + FALL_GRACE
		end

		if Fall.graceEnd ~= 0 and now >= Fall.graceEnd then
			Fall.armed = false
			Fall.graceEnd = 0
			Fall.peakY = -math.huge
			pcall(function() hum:ChangeState(Enum.HumanoidStateType.Running) end)
			return
		end

		if state ~= Enum.HumanoidStateType.Swimming then
			pcall(function() hum:ChangeState(Enum.HumanoidStateType.Swimming) end)
		end

		if onFloor then
			local v = hrp.AssemblyLinearVelocity
			hrp.AssemblyLinearVelocity = Vector3.new(v.X, math.min(v.Y, 0), v.Z)
		end
	elseif onFloor then
		Fall.peakY = y
	end
end

local function fallStop()
	if Fall.conn then Fall.conn:Disconnect(); Fall.conn = nil end
	if Fall.added then Fall.added:Disconnect(); Fall.added = nil end
	if Fall.hum and Fall.armed then
		pcall(function() Fall.hum:ChangeState(Enum.HumanoidStateType.Running) end)
	end
	Fall.char, Fall.hum, Fall.hrp, Fall.params = nil, nil, nil, nil
	fallReset()
end

setFall = function(onoff)
	if LOBBY then onoff = false end
	if FALL_ON == onoff then return end
	FALL_ON = onoff
	if onoff then
		fallStop()
		Fall.conn = RunService.PreSimulation:Connect(fallStep)
		Fall.added = LP.CharacterAdded:Connect(fallBind)
		if LP.Character then fallBind(LP.Character) end
	else
		fallStop()
	end
	apply()
end

on(fallBtn.MouseButton1Click, function() setFall(not FALL_ON) end)

end

------------------------------------------------------------ config save

-- Snapshot everything writable. The pick map is merged over the loaded one so
-- loot kinds that have not spawned yet this session keep their saved state.
function CFG.save()
	local w = CFG.writer()
	if not w then return end

	local picks = {}
	for k, v in CFG.picks do picks[k] = v end
	for k in types do picks[k] = chosen[k] == true end

	local out = { CFG.version }
	local function put(line) out[#out + 1] = line end
	local function flag(k, v) put(k .. "=" .. (v and "1" or "0")) end
	flag("esp", ESP_ON)
	flag("zip", ZIP_ON)
	flag("npc", NPC_ON)
	flag("line", LINE_ON)
	flag("aim", AIM_ON)
	flag("fly", FLY_ON)
	flag("fc", FC_ON)
	flag("mouse", MOUSE_ON)
	flag("wall", WALL_ON)
	flag("fall", FALL_ON)
	flag("hidden", HIDDEN)
	flag("allsel", ALL_SELECTED)
	put("range=" .. tostring(math.floor(RANGE + 0.5)))
	put("psx=" .. string.format("%.6f", panel.Position.X.Scale))
	put("px=" .. string.format("%.1f", panel.Position.X.Offset))
	put("psy=" .. string.format("%.6f", panel.Position.Y.Scale))
	put("py=" .. string.format("%.1f", panel.Position.Y.Offset))
	for k in picks do
		put((picks[k] and "pick=" or "skip=") .. CFG.encode(k))
	end

	pcall(w, CFG.file, table.concat(out, "\n") .. "\n")
end

-- Replay the saved active toggles now that every setter and the aim hook exist.
-- The in-game-only setters (mouse / aim / wall / fall) coerce themselves to false
-- while LOBBY is true, and on a fresh join Loot is often not replicated yet, so
-- the first attempt can be swallowed. The want list is therefore kept pending and
-- replayed once the player really is in a game (see the lobby transition in the
-- Heartbeat loop) instead of painting the button on while the feature stays off.
CFG.ready = true
CFG.pending = CFG.want
CFG.want = nil

CFG.replay = function()
	if CLOSED or LOBBY or not CFG.pending then return end
	local want = CFG.pending
	CFG.pending = nil
	pcall(function()
		if want.mouse then setMouse(true) end
		if want.fly then setFly(true) end
		if want.fc then setFC(true) end
		if want.aim then setAim(true) end
		if want.wall then setWall(true) end
		if want.fall then setFall(true) end
	end)
end

task.defer(function() CFG.replay() end)

------------------------------------------------------------ rows

local function rowText(t)
	return (t.stash and "\u{25A3} " or "\u{25A2} ") .. t.label
end

local function paintRow(key)
	local r, t = rows[key], types[key]
	if not r or not t then return end
	local pick = chosen[key]
	r.btn.BackgroundColor3 = pick and Color3.fromRGB(40, 110, 60) or Color3.fromRGB(32, 32, 38)
	r.name.TextColor3 = pick and Color3.fromRGB(195, 255, 205) or Color3.fromRGB(140, 140, 150)
	r.worth.Text = t.card and "" or (t.value and money(t.value) or "")
	r.worth.TextColor3 = pick and Color3.fromRGB(235, 225, 150) or Color3.fromRGB(110, 110, 120)
end

local function makeRow(key)
	local t = types[key]
	if rows[key] or not t then return end

	local btn = new("TextButton", {
		Size = UDim2.new(1, -6, 0, 26),
		BackgroundColor3 = Color3.fromRGB(32, 32, 38),
		BorderSizePixel = 0,
		Text = "",
		AutoButtonColor = false,
		ZIndex = 5,
	}, list)
	new("UICorner", { CornerRadius = UDim.new(0, 4) }, btn)
	new("Frame", {
		Size = UDim2.fromOffset(7, 7),
		Position = UDim2.new(0, 7, 0.5, -3.5),
		BackgroundColor3 = t.color,
		BorderSizePixel = 0,
		ZIndex = 6,
	}, btn)

	local name = new("TextLabel", {
		Size = UDim2.new(1, -80, 1, 0),
		Position = UDim2.fromOffset(20, 0),
		BackgroundTransparency = 1,
		Text = rowText(t),
		TextSize = 12,
		Font = Enum.Font.GothamMedium,
		TextXAlignment = Enum.TextXAlignment.Left,
		TextTruncate = Enum.TextTruncate.AtEnd,
		ZIndex = 6,
	}, btn)

	local worth = new("TextLabel", {
		Size = UDim2.fromOffset(54, 1),
		Position = UDim2.new(1, -60, 0, 0),
		BackgroundTransparency = 1,
		Text = "",
		TextSize = 11,
		Font = Enum.Font.GothamBold,
		TextXAlignment = Enum.TextXAlignment.Right,
		ZIndex = 6,
	}, btn)

	rows[key] = { btn = btn, name = name, worth = worth }

	on(btn.MouseButton1Click, function()
		chosen[key] = not chosen[key] or nil
		t.pendingAuto = false
		ALL_SELECTED = true
		for k in types do
			if not chosen[k] then ALL_SELECTED = false; break end
		end
		paintRow(key)
		CFG.queue()
	end)

	paintRow(key)
	orderDirty = true
end

local function resort()
	local keys = {}
	for k in types do keys[#keys + 1] = k end
	table.sort(keys, function(a, b)
		local x, y = types[a], types[b]
		if x.card ~= y.card then return x.card end
		if x.stash ~= y.stash then return x.stash end
		local vx, vy = x.value or -1, y.value or -1
		if vx ~= vy then return vx > vy end
		return x.label:lower() < y.label:lower()
	end)
	for i, k in ipairs(keys) do
		if rows[k] then rows[k].btn.LayoutOrder = i end
	end
	orderDirty = false
end

local function itemWorth(m, card)
	if card then return math.huge end
	local v = m:GetAttribute("Value")
	if typeof(v) == "number" and v > 0 then return v end
	local fv = m:GetAttribute("FreeValue")
	if typeof(fv) == "number" and fv > 0 then return fv end
	return 0
end

local function setNewChoice(key, value)
	-- A saved config wins over the auto-select heuristics for kinds it knows
	-- about; kinds added after the save follow the saved ALL flag.
	if CFG.picksOn then
		local saved = CFG.picks[key]
		if saved == nil then saved = CFG.allSel end
		chosen[key] = saved
		types[key].pendingAuto = false
		return
	end
	chosen[key] = ALL_SELECTED or value >= 1000
	types[key].pendingAuto = value <= 0 and not chosen[key]
end

local function refreshList()
	for _, m in lootKids() do
		if m:IsA("Model") then
			local key, label, card, stash = info(m)
			local t = types[key]
			if not t then
				t = { label = label, card = card, stash = stash, color = hash(key), value = nil }
				types[key] = t
				local value = itemWorth(m, card)
				if not card and value > 0 then t.value = value end
				setNewChoice(key, value)
				makeRow(key)
			end
			if not card then
				local v = itemWorth(m, false)
				if v > 0 then
					t.value = v
					if t.pendingAuto then
						if v >= 1000 then chosen[key] = true end
						t.pendingAuto = false
					end
				end
			end
		end
	end
	for key in rows do paintRow(key) end
	orderDirty = true
end

on(allBtn.MouseButton1Click, function()
	ALL_SELECTED = true
	for k in types do
		chosen[k] = true
		types[k].pendingAuto = false
		paintRow(k)
	end
	CFG.queue()
end)

on(noneBtn.MouseButton1Click, function()
	ALL_SELECTED = false
	for k in types do
		chosen[k] = false
		types[k].pendingAuto = false
		paintRow(k)
	end
	CFG.queue()
end)

on(npcBtn.MouseButton1Click, function() NPC_ON = not NPC_ON; apply() end)
on(lineBtn.MouseButton1Click, function() LINE_ON = not LINE_ON; apply() end)
on(zipBtn.MouseButton1Click, function() ZIP_ON = not ZIP_ON; apply() end)
on(mouseBtn.MouseButton1Click, function() setMouse(not MOUSE_ON) end)
on(flyBtn.MouseButton1Click, function() setFly(not FLY_ON) end)
on(fcBtn.MouseButton1Click, function() setFC(not FC_ON) end)
on(chip.MouseButton1Click, function()
	HIDDEN = false
	apply()
end)

------------------------------------------------------------ item esp

local function dropItem(m)
	local r = items[m]
	if not r then return end
	r.hl:Destroy()
	r.bg:Destroy()
	items[m] = nil
end

local function buildItem(m, key)
	local t = types[key]
	local part = m.PrimaryPart or m:FindFirstChildWhichIsA("BasePart")
	if not t or not part then return nil end

	local hl = new("Highlight", {
		Name = "ESPItem",
		Adornee = m,
		DepthMode = Enum.HighlightDepthMode.AlwaysOnTop,
		FillColor = t.color,
		OutlineColor = t.color,
		FillTransparency = t.stash and 0.55 or 0.85,
		OutlineTransparency = t.stash and 0 or 0.35,
	}, m)

	local bg = new("BillboardGui", {
		Name = "ESPLabel",
		Adornee = part,
		Size = UDim2.fromOffset(160, 18),
		StudsOffset = Vector3.new(0, 1.6, 0),
		AlwaysOnTop = true,
		LightInfluence = 0,
		MaxDistance = 0,
	}, PG)

	local txt = new("TextLabel", {
		Size = UDim2.fromScale(1, 1),
		BackgroundTransparency = 1,
		Font = Enum.Font.GothamBold,
		Text = "",
		TextScaled = true,
		TextColor3 = t.color,
		TextStrokeColor3 = Color3.new(),
		TextStrokeTransparency = 0.2,
	}, bg)

	return { hl = hl, bg = bg, text = txt, key = key }
end

------------------------------------------------------------ npc esp

local function dropNpc(m)
	local r = npcs[m]
	if not r then return end
	r.hl:Destroy()
	r.bg:Destroy()
	r.line:Destroy()
	npcs[m] = nil
end

local function buildNpc(m, tag)
	local b = body(m)
	if not b then return nil end
	local col = TAGCOL[tag] or Color3.new(1, 1, 1)

	local hl = new("Highlight", {
		Name = "ESPNpc",
		Adornee = m,
		DepthMode = Enum.HighlightDepthMode.AlwaysOnTop,
		FillColor = col,
		OutlineColor = col,
		FillTransparency = 0.75,
		OutlineTransparency = 0,
	}, m)

	local bg = new("BillboardGui", {
		Name = "ESPDist",
		Adornee = b,
		Size = UDim2.fromOffset(44, 15),
		StudsOffset = Vector3.new(0, 2.6, 0),
		AlwaysOnTop = true,
		LightInfluence = 0,
		MaxDistance = 0,
	}, PG)

	local txt = new("TextLabel", {
		Size = UDim2.fromScale(1, 1),
		BackgroundTransparency = 1,
		Font = Enum.Font.GothamBold,
		Text = "",
		TextScaled = true,
		TextColor3 = col,
		TextStrokeColor3 = Color3.new(),
		TextStrokeTransparency = 0.2,
	}, bg)

	local seg = new("Frame", {
		AnchorPoint = Vector2.new(0.5, 0.5),
		Size = UDim2.fromOffset(1, 1),
		BackgroundColor3 = col,
		BackgroundTransparency = 0.3,
		BorderSizePixel = 0,
		Visible = false,
		ZIndex = 1,
	}, lineLayer)

	return { hl = hl, bg = bg, text = txt, line = seg, part = b }
end

------------------------------------------------------------ zip ties

local prompts = {}
local fired = {}

on(workspace.DescendantAdded, function(d)
	if d:IsA("ProximityPrompt") and d.Name == "ZipTiePrompt" then
		prompts[#prompts + 1] = d
	end
end)

for _, d in workspace:GetDescendants() do
	if d:IsA("ProximityPrompt") and d.Name == "ZipTiePrompt" then
		prompts[#prompts + 1] = d
	end
end

local function tie(p)
	if not p.Parent then return end
	if p.MaxActivationDistance ~= ZIPTIE_DIST then
		p.MaxActivationDistance = ZIPTIE_DIST
		p.RequiresLineOfSight = false
		p.Exclusivity = Enum.ProximityPromptExclusivity.AlwaysShow
		p.HoldDuration = 0
	end
	pcall(function() p:InputHoldBegin() end)
	task.defer(function()
		if p.Parent then pcall(function() p:InputHoldEnd() end) end
	end)
end

------------------------------------------------------------ loops

on(RunService.Heartbeat, function(dt)
	if CLOSED then return end

	if MOUSE_ON and not FC_ON and not LOBBY then
		if UIS.MouseBehavior ~= Enum.MouseBehavior.Default then UIS.MouseBehavior = Enum.MouseBehavior.Default end
		if not UIS.MouseIconEnabled then UIS.MouseIconEnabled = true end
	end

	local inLobby = workspace:FindFirstChild("Loot") == nil
	if inLobby ~= LOBBY then
		LOBBY = inLobby
		if LOBBY then
			for m in items do dropItem(m) end
			for m in npcs do dropNpc(m) end
			if MOUSE_ON then setMouse(false) end
			if AIM_ON then setAim(false) end
			if WALL_ON then setWall(false) end
			if FALL_ON then setFall(false) end
		else
			lastList = 0
		end
		if not LOBBY and CFG.replay then CFG.replay() end
		apply()
	end

	if gui.DisplayOrder ~= TOP then gui.DisplayOrder = TOP end

	if LOBBY then return end

	local now = os.clock()

	AD.raw = dt
	local s = dt
	if s > 0.1 then s = 0.1 end
	AD.sm = AD.sm + (s - AD.sm) * 0.12

	if AD.raw > 0.18 then
		if AD.lvl < 4 then
			AD.lvl = math.min(4, AD.lvl + 2)
			AD.lvlT = now
			AD.acc = 0
		end
		AD.bad, AD.good = 0, 0
		lastScan = now
	elseif AD.sm > 0.045 then
		AD.bad = AD.bad + dt
		AD.good = 0
		if AD.bad >= 0.25 and AD.lvl < 4 and now - AD.lvlT >= 0.5 then
			AD.lvl = AD.lvl + 1
			AD.lvlT = now
			AD.bad = 0
			AD.acc = 0
		end
	elseif AD.sm < 0.035 then
		AD.good = AD.good + dt
		AD.bad = 0
		if AD.good >= 5 and AD.lvl > 0 and now - AD.lvlT >= 1.5 then
			AD.lvl = AD.lvl - 1
			AD.lvlT = now
			AD.good = 0
			AD.acc = 0
		end
	else
		AD.bad, AD.good = 0, 0
	end

	if ZIP_ON then
		for i = #prompts, 1, -1 do
			local p = prompts[i]
			if not p.Parent then
				table.remove(prompts, i)
				fired[p] = nil
			elseif p.Enabled then
				local lastTry = fired[p] or 0
				if os.clock() - lastTry >= 0.2 then
					fired[p] = os.clock()
					tie(p)
				end
			end
		end
	end

	local scanIV = AD.scan[AD.lvl + 1]

	if now - lastList >= AD.list[AD.lvl + 1] then
		lastList = now
		refreshList()
	end

	if now - lastScan < scanIV then return end
	lastScan = now
	local budget = AD.cap[AD.lvl + 1]
	local t0
	local built = 0
	local function room()
		if budget <= 0 then return false end
		if not t0 then t0 = os.clock() end
		if built > 0 and built % 4 == 0 and os.clock() - t0 > AD.ms[AD.lvl + 1] then
			budget = 0
			return false
		end
		built = built + 1
		budget = budget - 1
		return true
	end

	local pos = feet()
	local kids, kn = lootKids()
	local r2 = RANGE * RANGE
	local prune = now - lastPrune > 2
	if prune then lastPrune = now end

	for i = 1, kn do
		local m = kids[i]
		local c = infoOf(m)
		local key, label, card, stash = c.key, c.label, c.card, c.stash
		local t = types[key]
		if not t then
			t = { label = label, card = card, stash = stash, color = hash(key), value = nil }
			types[key] = t
			local value = itemWorth(m, card)
			if not card and value > 0 then t.value = value end
			setNewChoice(key, value)
			makeRow(key)
		end
		if not card then
			local v = itemWorth(m, false)
			if v > 0 and v ~= t.value then
				t.value = v
				if t.pendingAuto then
					if v >= 1000 then chosen[key] = true end
					t.pendingAuto = false
				end
				paintRow(key)
				orderDirty = true
			end
		end
	end

	if orderDirty then resort() end

	for i = 1, kn do
		local m = kids[i]
		local c = infoCache[m]
		local key = c and c.key
		local t = key and types[key]
		if t then
			local r = items[m]
			local part = c.part
			if not part then
				part = m.PrimaryPart or gFFWIA(m, "BasePart")
				c.part = part
			end
			local near = true
			if pos and part then
				local d = part.Position - pos
				near = d.X * d.X + d.Y * d.Y + d.Z * d.Z <= r2
			end

			if ESP_ON and near and chosen[key] then
				if r and (r.key ~= key or not r.hl.Parent) then
					dropItem(m)
					r = nil
				end
				if not r and part and room() then
					r = buildItem(m, key)
					if r then items[m] = r end
				end
				if r then
					local txt = rowText(t)
					if not t.card and t.value then txt = txt .. "  " .. money(t.value) end
					if r.text.Text ~= txt then r.text.Text = txt end
					if not r.hl.Enabled then r.hl.Enabled = true end
					if not r.bg.Enabled then r.bg.Enabled = true end
				end
			elseif r and r.hl.Enabled then
				-- Out of range / deselected: hide, do not destroy. Rebuilding a
				-- Highlight + BillboardGui on every range edge was pure churn.
				r.hl.Enabled = false
				r.bg.Enabled = false
			end
		end
	end

	if prune then
		for m in items do
			if m.Parent ~= Loot then dropItem(m) end
		end
	end

	local seen = {}
	for _, tag in TAGS do
		for _, m in CS:GetTagged(tag) do
			if gIsA(m, "Model") and gIsDesc(m, workspace) and not down(m) then
				seen[m] = true
				local r = npcs[m]
				local b = (r and r.part) or body(m)
				local near = b ~= nil
				if b and pos then
					local d = b.Position - pos
					near = d.X * d.X + d.Y * d.Y + d.Z * d.Z <= r2
				end

				if ESP_ON and NPC_ON and near then
					if not r then
						if room() then
							r = buildNpc(m, tag)
							if r then npcs[m] = r end
						end
					end
					if r then
						if not r.hl.Enabled then r.hl.Enabled = true end
						if not r.bg.Enabled then r.bg.Enabled = true end
					end
				elseif r and r.hl.Enabled then
					r.hl.Enabled = false
					r.bg.Enabled = false
					if r.line.Visible then r.line.Visible = false end
				end
			end
		end
	end

	if prune then
		for m in npcs do
			if not seen[m] then dropNpc(m) end
		end
	end
end)

on(RunService.RenderStepped, function(dt)
	if CLOSED then return end
	if AIM_ON then solveAim() end
	if LOBBY then return end

	AD.acc = AD.acc + dt
	if AD.acc < AD.over[AD.lvl + 1] then return end
	AD.acc = 0

	local pos = feet()
	local a = pos and screen(pos) or nil

	for m, r in npcs do
		local b = body(m)
		local c = b and screen(b.Position) or nil

		if a and c and LINE_ON and not down(m) then
			local d = c - a
			local len = d.Magnitude
			if len > 1 then
				r.line.Size = UDim2.fromOffset(len, 1)
				r.line.Position = UDim2.fromOffset((a.X + c.X) * 0.5, (a.Y + c.Y) * 0.5)
				r.line.Rotation = math.deg(math.atan2(d.Y, d.X))
				r.line.Visible = true
			else
				r.line.Visible = false
			end
		else
			r.line.Visible = false
		end

		if b and pos then
			local txt = tostring(math.floor((b.Position - pos).Magnitude + 0.5))
			if r.text.Text ~= txt then r.text.Text = txt end
		end
	end
end)

------------------------------------------------------------ close + keys

local function fullClose()
	if CLOSED then return end
	if type(CFG.save) == "function" then pcall(CFG.save) end
	CLOSED = true
	if getgenv then getgenv().Game05Running = nil end
	AD.lvl = 0
	AD.bad, AD.good, AD.acc = 0, 0, 0
	AD.sm = 1 / 60
	StopFreecam()
	setAim(false)
	setWall(false)
	setFall(false)
	if flyConn then flyConn:Disconnect() end
	RunService:UnbindFromRenderStep("ESPMouse")
	for _, c in conns do c:Disconnect() end
	table.clear(conns)
	for m in items do items[m].hl:Destroy(); items[m].bg:Destroy() end
	for m in npcs do npcs[m].hl:Destroy(); npcs[m].bg:Destroy(); npcs[m].line:Destroy() end
	table.clear(items)
	table.clear(npcs)
	for _, row in hudRows do row:Destroy() end
	table.clear(hudRows)
	if hudLayer then
		hudLayer:Destroy()
		hudLayer = nil
	end
	hudStats = nil
	gui:Destroy()
end

closeBtn.MouseButton1Click:Connect(fullClose)

on(UIS.InputBegan, function(i, processed)
	if CLOSED or processed or UIS:GetFocusedTextBox() then return end

	if i.KeyCode == Enum.KeyCode.P then
		if LOBBY then return end
		ESP_ON = not ESP_ON
		apply()
	elseif i.KeyCode == Enum.KeyCode.U then
		if LOBBY then return end
		ZIP_ON = not ZIP_ON
		apply()
	elseif i.KeyCode == Enum.KeyCode.H then
		HIDDEN = not HIDDEN
		apply()
	elseif i.KeyCode == Enum.KeyCode.M then
		if LOBBY then return end
		setMouse(not MOUSE_ON)
	elseif i.KeyCode == Enum.KeyCode.K then
		setFly(not FLY_ON)
	elseif i.KeyCode == Enum.KeyCode.L then
		setFC(not FC_ON)
	elseif i.KeyCode == Enum.KeyCode.J then
		if LOBBY then return end
		setAim(not AIM_ON)
	elseif i.KeyCode == Enum.KeyCode.T then
		if WALL_ON and not LOBBY then wallGlitch() end
	end
end)
