<roblox xmlns:xmime="http://www.w3.org/2005/05/xmlmime" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://www.roblox.com/roblox.xsd" version="4">
	<External>null</External>
	<External>nil</External>
	<Item class="Script" referent="RBX00000000000000000000000000000001">
		<Properties>
			<string name="Name">ModhelmGuard</string>
			<bool name="Disabled">false</bool>
			<ProtectedString name="Source"><![CDATA[--!strict
--[[
	ModhelmGuard.server.luau

	Anti-cheat for Modhelm (https://modhelm.com), using Roblox Open Cloud only.
	This script makes no web requests and does not use HttpService at all.

	What it does
	  1. Checks: every 0.25 seconds the server looks at each player's character and counts a hit when a player
	     moves faster than their WalkSpeed allows (speed), jumps a long way in one step (teleport), floats high above
	     the ground for too long (fly), passes through a solid part (noclip, off by default), fires RemoteEvents
	     too often (remotes), jumps again and again in the air (jump), spins to fling others (fling), fires a decoy
	     remote (honeypot), uses prompts or clicks from too far away or without holding (interact), or hits from too
	     far away when your weapons ask CheckHit (reach). Everything is measured on the server, the client is never
	     asked.
	  2. Hits: written into the MemoryStore queue "ModhelmGuard" (at most one item per player and check every
	     20 seconds, hits in between are counted into the next item). Modhelm reads the queue through Open Cloud,
	     shows the hits on the dashboard and posts alerts in Discord.
	  3. Kick (optional): with the action "kick", a player with kickAfter hits within 10 minutes is kicked.
	  4. Staff panel: the LocalScript "ModhelmGuardPanel" (a child of this script) is given to staff only. It opens
	     with the "Modhelm" button at the bottom left or the F2 key and shows the players of this server with their
	     hits, the latest hits, the replays of this server, and buttons to save a replay, go to a player or kick them.
	  5. Replays: the server keeps the last 35 seconds of every player's movement in memory (4 samples per second:
	     position and facing of the root part). 5 seconds after the first hit of a player it saves 35 seconds
	     (30 before the hit, 5 after) of that player and of up to 6 other players within 120 studs. At most one
	     replay per player every 2 minutes and at most 6 automatic replays per server every 10 minutes; staff can
	     also save one from the panel. Replays are stored in this game's own data store "ModhelmReplays"
	     (scope "global"), the key list in its entry "index". This script removes replays older than 7 days itself
	     (on start and every hour, a few per minute) and the oldest ones when more than 500 are stored, so Modhelm
	     never deletes anything in your data stores.

	Setup (details in docs/anticheat.md)
	  - Put this script into ServerScriptService (a Script, not a LocalScript), with the LocalScript
	    "ModhelmGuardPanel" inside it. The model file from the Modhelm dashboard already has both.
	  - Give the game's Open Cloud API key in Modhelm these extra permissions:
	      memory-store.queue: dequeue, discard                      (read the hits)
	      universe-datastores.objects: create, update               (send the settings to the game)
	      universe-messaging-service: publish                       (optional, new settings right away)
	      universe-datastores.objects: read                         (watch replays on the dashboard)
	  - Replays are saved by the game itself and need no permission for that. To watch them on the Modhelm
	    dashboard, Modhelm reads one entry of "ModhelmReplays" when someone opens it; nothing is copied.
	  - Modhelm Guard runs only while the game is connected to Modhelm: Modhelm writes the settings with an end date
	    ("until") into the data store and moves it forward every day. Without that (no data store permission, the
	    game removed from Modhelm, Modhelm Guard switched off) the script checks nothing, kicks nobody and saves no
	    replays; the panel only tells the team to set it up in the Modhelm dashboard.

	Your own scripts that move players on the server (PivotTo, CFrame changes, flings, vehicles without seats)
	should exempt them for a moment, otherwise this looks like a teleport:
	    local guard = game:GetService("ServerStorage"):WaitForChild("ModhelmGuard")
	    guard:WaitForChild("Exempt"):Fire(player, 3) -- seconds, at most 3600

	Reach (optional): if your weapons decide hits on the server, ask before you deal damage. It answers false when the
	attacker is too far from the victim, and records a "reach" hit:
	    local checkHit = guard:WaitForChild("CheckHit")
	    if checkHit:Invoke(attackerPlayer, victimPlayerOrModel, maxDistanceInStuds) then
	        -- deal the damage
	    end

	Also checked without any code of yours: decoy remotes "AdminRemote" and "GiveCurrency" in ReplicatedStorage that
	only exploit tools fire, and ProximityPrompts or ClickDetectors used from too far away or without holding.

	Staff (who gets the panel): the game owner (the user for a user game, rank 255 for a group game), group members
	with at least the rank set in Modhelm, and the user ids listed in Modhelm. In Studio, when the place is not
	published yet (game.CreatorId is 0), everyone in the test session gets the panel so you can try it.

	Data: hits send user ids, the name of the check, the measured value and its limit, place id, server id and time.
	A replay stores user ids, names and display names, and for each sample (4 per second) the position in studs
	with one decimal and the facing in whole degrees (0 to 359; yaw 0 faces -Z, the same turn as
	CFrame.Angles(0, math.rad(yaw), 0)). It stays in your game's data store and is removed after 7 days. No chat
	is ever stored or sent.
]]

local DataStoreService = game:GetService("DataStoreService")
local MemoryStoreService = game:GetService("MemoryStoreService")
local MessagingService = game:GetService("MessagingService")
local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local RunService = game:GetService("RunService")
local ProximityPromptService = game:GetService("ProximityPromptService")
local ServerStorage = game:GetService("ServerStorage")
local TextService = game:GetService("TextService")
local Workspace = game:GetService("Workspace")

-- Names Modhelm expects. Do not change them.
local QUEUE_NAME = "ModhelmGuard"
local DATA_STORE = "Modhelm"
local SETTINGS_KEY = "guard"
local TOPIC = "modhelm"
local MESSAGE_VERSION = 1
local REMOTE_NAME = "ModhelmGuardRemote"
local PANEL_SCRIPT_NAME = "ModhelmGuardPanel"
local PANEL_GUI_NAME = "ModhelmGuard"
local EXEMPT_FOLDER_NAME = "ModhelmGuard"

-- Timing.
local TICK = 0.25 -- seconds between checks
local RING = 5 -- samples kept for the speed check (5 x 0.25 s = 1 s)
local SPAWN_GRACE = 3 -- seconds without checks after spawning
local HIT_COOLDOWN = 0.9 -- one check counts at most one hit per player about every second
local ITEM_WINDOW = 20 -- seconds: at most one queue item per player and check
local KICK_WINDOW = 600 -- seconds in which kickAfter hits lead to a kick
local QUEUE_TTL = 86400 -- seconds an item waits in the queue for Modhelm
local SETTINGS_REFRESH = 120 -- seconds between settings reads
local OUTBOX_CAP = 200 -- items kept in memory while the queue cannot be reached (oldest are dropped)
local MAX_ITEM_TRIES = 8 -- an item that fails this often is dropped
local CLOSE_WAIT = if RunService:IsStudio() then 3 else 15 -- seconds to send the rest on shutdown
local FEED_SIZE = 50
local FEED_MERGE = 10 -- seconds: hits of the same player and check are merged into one feed line
local MAX_EXEMPT = 3600
local GOTO_EXEMPT = 3
local CALL_WINDOW = 5 -- panel requests: at most CALLS_PER_WINDOW per CALL_WINDOW seconds
local CALLS_PER_WINDOW = 10
local MAX_TEXT = 200
local DEFAULT_KICK_MESSAGE = "You were removed from this server by the anti-cheat."
local DEFAULT_STAFF_KICK_MESSAGE = "You were removed from this server by a moderator."

-- Replays (docs/anticheat.md "Replays"). Names Modhelm expects; do not change them.
local REPLAY_STORE = "ModhelmReplays"
local REPLAY_SCOPE = "global"
local REPLAY_INDEX_KEY = "index"
local REPLAY_HZ = 4 -- samples per second, one per TICK
local REPLAY_SAMPLES = 140 -- samples kept per player and stored per replay (35 s)
local REPLAY_BEFORE = 30 -- seconds before the hit
local REPLAY_AFTER = 5 -- seconds after the hit; the replay is saved this long after it
local REPLAY_PLAYER_GAP = 120 -- seconds: at most one replay per player
local REPLAY_SERVER_WINDOW = 600 -- seconds in which at most REPLAY_SERVER_MAX automatic replays are saved
local REPLAY_SERVER_MAX = 6
local REPLAY_RADIUS = 120 -- studs around the player in which others are recorded too
local REPLAY_OTHERS = 6
local REPLAY_KEEP = 7 * 86400 -- seconds a replay is kept
local REPLAY_INDEX_CAP = 500 -- entries in "index"; the oldest beyond this are removed
local REPLAY_LIST = 20 -- replays of this server shown in the panel and kept in memory
local REPLAY_CLEANUP_EVERY = 3600
local REPLAY_CLEANUP_MAX = 100 -- old replays removed per cleanup run
local REPLAY_REMOVE_GAP = 12 -- seconds between two removals (5 per minute, far below the data store budget)
local REPLAY_NEAR = 0.3 -- seconds: a sample this close to a stored point stands in for it
local REPLAY_MAX_STEP = 1 -- seconds: two samples further apart are not blended
local REPLAY_KEY_MAX = 50 -- data store keys are at most 50 characters

-- Check limits.
local SPEED_BONUS = 6 -- studs per second on top of WalkSpeed * factor
local FLY_HEIGHT = 10 -- studs above the ground
local FLY_FALLING = -3 -- vertical studs per second; slower than this counts as falling
local CLIMB_RADIUS = 3 -- studs around a rising player in which any part means climbing, not flying
local NOCLIP_THICKNESS = 1 -- studs
local MIN_NOCLIP_STEP = 0.5 -- studs; shorter steps are not checked for noclip
local AIR_JUMP_BOOST = 25 -- studs per second of sudden upward speed that counts as a jump
local AIR_JUMP_WINDOW = 6 -- seconds in which jumps in the air are counted
local FLING_SAMPLES = 3 -- samples in a row (0.75 s) the character must spin that fast
local TWO_PI = 2 * math.pi

-- airJumps: jumps in the air allowed in AIR_JUMP_WINDOW (double jumps of the game itself); fling: turns per second of
-- the character's root; interact and reach: studs on top of the allowed distance (lag and long arms).
type Limits = { speedFactor: number, teleport: number, fly: number, remotes: number, airJumps: number, fling: number, interact: number, reach: number }

local LIMITS: { [string]: Limits } = {
	low = { speedFactor = 2.0, teleport = 120, fly = 6, remotes = 60, airJumps = 4, fling = 10, interact = 20, reach = 8 },
	normal = { speedFactor = 1.6, teleport = 80, fly = 4, remotes = 40, airJumps = 2, fling = 6, interact = 12, reach = 5 },
	strict = { speedFactor = 1.3, teleport = 50, fly = 2.5, remotes = 25, airJumps = 1, fling = 4, interact = 6, reach = 3 },
}

local CHECK_NAMES = { "speed", "teleport", "fly", "noclip", "remotes", "jump", "fling", "honeypot", "interact", "reach" }

-- Decoy remotes (check "honeypot"): no code of the game knows them, so only exploit tools that scan and fire every
-- remote call them. Created in ReplicatedStorage unless the game already has something with that name.
local HONEYPOT_NAMES = { "AdminRemote", "GiveCurrency" }

-- In Studio JobId is empty; use a stable fake id so testing works (same as ModhelmLive).
if not script:IsDescendantOf(game:GetService("ServerScriptService")) then
	warn("[Modhelm] please put the ModhelmGuard script into ServerScriptService")
end

local serverKey = if game.JobId ~= "" then game.JobId else ("studio-" .. tostring(game.PlaceId))
local startedAt = os.clock()

---------------------------------------------------------------------------------------------------------------------
-- Small helpers
---------------------------------------------------------------------------------------------------------------------

local lastWarn: { [string]: number } = {}

-- warn() at most once per `every` seconds for the same key, so a broken service does not flood the output.
local function warnEvery(key: string, every: number, text: string)
	local now = os.clock()
	local last = lastWarn[key]
	if last and now - last < every then
		return
	end
	lastWarn[key] = now
	warn("[Modhelm] " .. text)
end

local function round1(value: number): number
	return math.floor(value * 10 + 0.5) / 10
end

local function isInteger(value: any): boolean
	return type(value) == "number" and value == value and value == math.floor(value) and math.abs(value) < 2 ^ 53
end

-- Trim and cut a text to at most `max` characters (UTF-8 aware).
local function clipText(text: string, max: number): string
	local trimmed = string.match(text, "^%s*(.-)%s*$") or ""
	local length = utf8.len(trimmed)
	if length == nil then
		return string.sub(trimmed, 1, max)
	end
	if length <= max then
		return trimmed
	end
	local cut = utf8.offset(trimmed, max + 1)
	return if cut then string.sub(trimmed, 1, cut - 1) else string.sub(trimmed, 1, max)
end

---------------------------------------------------------------------------------------------------------------------
-- Minimal JSON decoder (copied from ModhelmLive.server.luau). Open Cloud publishes messages as JSON strings.
-- HttpService:JSONDecode is not used on purpose, so the script needs no HttpService at all.
---------------------------------------------------------------------------------------------------------------------

local ESCAPES: { [string]: string } = { ['"'] = '"', ["\\"] = "\\", ["/"] = "/", b = "\b", f = "\f", n = "\n", r = "\r", t = "\t" }

local function decodeJson(text: string): any
	local pos = 1
	local len = #text

	local function fail(): never
		error("invalid json at " .. tostring(pos), 0)
	end

	local function skipSpace()
		while pos <= len do
			local c = string.byte(text, pos)
			if c == 32 or c == 9 or c == 10 or c == 13 then
				pos += 1
			else
				break
			end
		end
	end

	local parseValue: () -> any

	local function parseString(): string
		pos += 1 -- opening quote
		local parts: { string } = {}
		while true do
			if pos > len then
				fail()
			end
			local c = string.sub(text, pos, pos)
			if c == '"' then
				pos += 1
				break
			elseif c == "\\" then
				local e = string.sub(text, pos + 1, pos + 1)
				if e == "u" then
					local hex = string.sub(text, pos + 2, pos + 5)
					local code = tonumber(hex, 16)
					if not code or #hex ~= 4 then
						fail()
					end
					-- Surrogate pairs (characters outside the basic plane).
					if code >= 0xD800 and code <= 0xDBFF and string.sub(text, pos + 6, pos + 7) == "\\u" then
						local low = tonumber(string.sub(text, pos + 8, pos + 11), 16)
						if low and low >= 0xDC00 and low <= 0xDFFF then
							code = 0x10000 + (code - 0xD800) * 0x400 + (low - 0xDC00)
							pos += 6
						end
					end
					table.insert(parts, utf8.char(code))
					pos += 6
				else
					local ch = ESCAPES[e]
					if not ch then
						fail()
					end
					table.insert(parts, ch)
					pos += 2
				end
			else
				local stop = string.find(text, '["\\]', pos)
				if not stop then
					fail()
				end
				table.insert(parts, string.sub(text, pos, stop - 1))
				pos = stop
			end
		end
		return table.concat(parts)
	end

	local function parseNumber(): number
		local s, e = string.find(text, "^-?%d+%.?%d*[eE]?[-+]?%d*", pos)
		if not s then
			fail()
		end
		local n = tonumber(string.sub(text, s :: number, e :: number))
		if n == nil then
			fail()
		end
		pos = (e :: number) + 1
		return n :: number
	end

	local function parseObject(): { [string]: any }
		pos += 1
		local obj: { [string]: any } = {}
		skipSpace()
		if string.sub(text, pos, pos) == "}" then
			pos += 1
			return obj
		end
		while true do
			skipSpace()
			if string.sub(text, pos, pos) ~= '"' then
				fail()
			end
			local key = parseString()
			skipSpace()
			if string.sub(text, pos, pos) ~= ":" then
				fail()
			end
			pos += 1
			obj[key] = parseValue()
			skipSpace()
			local c = string.sub(text, pos, pos)
			pos += 1
			if c == "}" then
				return obj
			elseif c ~= "," then
				fail()
			end
		end
	end

	local function parseArray(): { any }
		pos += 1
		local arr: { any } = {}
		skipSpace()
		if string.sub(text, pos, pos) == "]" then
			pos += 1
			return arr
		end
		while true do
			table.insert(arr, parseValue())
			skipSpace()
			local c = string.sub(text, pos, pos)
			pos += 1
			if c == "]" then
				return arr
			elseif c ~= "," then
				fail()
			end
		end
	end

	parseValue = function(): any
		skipSpace()
		local c = string.sub(text, pos, pos)
		if c == "{" then
			return parseObject()
		elseif c == "[" then
			return parseArray()
		elseif c == '"' then
			return parseString()
		elseif c == "-" or string.match(c, "%d") then
			return parseNumber()
		elseif string.sub(text, pos, pos + 3) == "true" then
			pos += 4
			return true
		elseif string.sub(text, pos, pos + 4) == "false" then
			pos += 5
			return false
		elseif string.sub(text, pos, pos + 3) == "null" then
			pos += 4
			return nil
		end
		fail()
	end

	local value = parseValue()
	skipSpace()
	if pos <= len then
		fail()
	end
	return value
end

---------------------------------------------------------------------------------------------------------------------
-- Settings
---------------------------------------------------------------------------------------------------------------------

type Settings = {
	-- Modhelm's activation: false until a settings entry with an end date in the future was read.
	licensed: boolean,
	enabled: boolean,
	checks: { [string]: boolean },
	sensitivity: string,
	action: string,
	kickAfter: number,
	kickMessage: string,
	panelEnabled: boolean,
	panelUserIds: { [number]: boolean },
	groupRank: number?,
}

local function defaultSettings(): Settings
	return {
		licensed = false,
		enabled = true,
		checks = {
			speed = true,
			teleport = true,
			fly = true,
			noclip = false,
			remotes = true,
			jump = true,
			fling = true,
			honeypot = true,
			interact = true,
			reach = true,
		},
		sensitivity = "normal",
		action = "record",
		kickAfter = 5,
		kickMessage = "",
		panelEnabled = true,
		panelUserIds = {},
		groupRank = nil,
	}
end

-- Every field is checked on its own; a missing or broken field keeps its default. Unknown fields are ignored.
local function parseSettings(raw: any): Settings
	local s = defaultSettings()
	if type(raw) ~= "table" then
		return s
	end
	if type(raw.enabled) == "boolean" then
		s.enabled = raw.enabled
	end
	-- Only Modhelm writes "until" (unix seconds) and moves it forward every day. Past it, everything stays off.
	s.licensed = type(raw["until"]) == "number" and raw["until"] > os.time()
	if not s.licensed then
		s.enabled = false
	end
	if type(raw.checks) == "table" then
		for _, name in CHECK_NAMES do
			local value = raw.checks[name]
			if type(value) == "boolean" then
				s.checks[name] = value
			end
		end
	end
	if type(raw.sensitivity) == "string" and LIMITS[raw.sensitivity] then
		s.sensitivity = raw.sensitivity
	end
	if raw.action == "record" or raw.action == "kick" then
		s.action = raw.action
	end
	if isInteger(raw.kickAfter) then
		s.kickAfter = math.clamp(raw.kickAfter, 2, 20)
	end
	if type(raw.kickMessage) == "string" then
		s.kickMessage = clipText(raw.kickMessage, MAX_TEXT)
	end
	local panel = raw.panel
	if type(panel) == "table" then
		if type(panel.enabled) == "boolean" then
			s.panelEnabled = panel.enabled
		end
		if type(panel.userIds) == "table" then
			local count = 0
			for _, value in ipairs(panel.userIds) do
				-- Numbers as Modhelm writes them; numeric strings are accepted too.
				local id = if type(value) == "string" then tonumber(value) else value
				if isInteger(id) and id > 0 then
					s.panelUserIds[id] = true
					count += 1
					if count >= 50 then
						break
					end
				end
			end
		end
		if isInteger(panel.groupRank) and panel.groupRank >= 1 and panel.groupRank <= 255 then
			s.groupRank = panel.groupRank
		end
	end
	return s
end

local settings: Settings = defaultSettings()

---------------------------------------------------------------------------------------------------------------------
-- Player state
---------------------------------------------------------------------------------------------------------------------

type Aggregate = { n: number, x: number, l: number, sentAt: number }

type FeedEntry = {
	userId: number,
	name: string,
	displayName: string,
	check: string,
	n: number,
	x: number,
	l: number,
	at: number,
}

type PlayerState = {
	player: Player,
	userId: number,
	spawnAt: number,
	exemptUntil: number,
	-- Motion samples. The ring holds the last RING positions for the speed check (1 second).
	ringPos: { Vector3 },
	ringTime: { number },
	ringWalk: { number },
	ringHead: number,
	ringCount: number,
	lastPos: Vector3?,
	lastTime: number,
	airTime: number,
	-- Jump and fling checks.
	lastVy: number,
	airJumps: { number },
	spinSamples: number,
	-- Prompt hold starts (check "interact"): prompt -> os.clock() when the player began holding.
	holds: { [Instance]: number },
	-- Checks that run without a character (remotes) look at this flag, set by the motion pass.
	active: boolean,
	remoteCount: number,
	cooldown: { [string]: number },
	agg: { [string]: Aggregate },
	kickTimes: { number },
	kicked: boolean,
	-- For the panel.
	hits: number,
	checks: { [string]: number },
	lastAt: number?,
	-- Replay ring (REPLAY_SAMPLES slots, filled in place): root position, yaw in radians and the server tick the slot
	-- was written in. A slot whose tick does not match means the player was not there at that tick.
	repPos: { Vector3 },
	repYaw: { number },
	repTick: { number },
	replayAt: number, -- os.clock() of the last replay of this player (automatic or from the panel)
	-- Staff.
	rank: number?,
	rankRetryAt: number,
	calls: number,
	callWindow: number,
	panelBusy: boolean,
	panelAgain: boolean,
}

local states: { [Player]: PlayerState } = {}
local feed: { FeedEntry } = {}

local function newState(player: Player): PlayerState
	local now = os.clock()
	return {
		player = player,
		userId = player.UserId,
		spawnAt = now,
		exemptUntil = 0,
		ringPos = table.create(RING, Vector3.zero),
		ringTime = table.create(RING, 0),
		ringWalk = table.create(RING, 0),
		ringHead = 0,
		ringCount = 0,
		lastPos = nil,
		lastTime = now,
		airTime = 0,
		lastVy = 0,
		airJumps = {},
		spinSamples = 0,
		holds = setmetatable({}, { __mode = "k" }) :: any,
		active = false,
		remoteCount = 0,
		cooldown = {},
		agg = {},
		kickTimes = {},
		kicked = false,
		hits = 0,
		checks = {},
		lastAt = nil,
		repPos = table.create(REPLAY_SAMPLES, Vector3.zero),
		repYaw = table.create(REPLAY_SAMPLES, 0),
		repTick = table.create(REPLAY_SAMPLES, 0),
		replayAt = -math.huge,
		rank = nil,
		rankRetryAt = 0,
		calls = 0,
		callWindow = 0,
		panelBusy = false,
		panelAgain = false,
	}
end

-- Forget the motion history, so the next samples start fresh (after spawning, exemptions, teleports).
local function resetMotion(st: PlayerState)
	st.ringCount = 0
	st.ringHead = 0
	st.lastPos = nil
	st.airTime = 0
	st.lastVy = 0
	table.clear(st.airJumps)
	st.spinSamples = 0
end

---------------------------------------------------------------------------------------------------------------------
-- Staff
---------------------------------------------------------------------------------------------------------------------

local function ensureRank(st: PlayerState)
	if game.CreatorType ~= Enum.CreatorType.Group or st.rank ~= nil or os.clock() < st.rankRetryAt then
		return
	end
	local ok, rank = pcall(function()
		return st.player:GetRankInGroup(game.CreatorId)
	end)
	if ok and type(rank) == "number" then
		st.rank = rank
	else
		st.rankRetryAt = os.clock() + 30
		warnEvery("rank", 60, "could not read a group rank, trying again later: " .. tostring(rank))
	end
end

-- The owner, group members with the set rank and the listed users. They are never kicked by the anti-cheat and
-- cannot be kicked from the panel.
local function isProtected(st: PlayerState): boolean
	local userId = st.player.UserId
	if game.CreatorType == Enum.CreatorType.User then
		if userId == game.CreatorId and game.CreatorId ~= 0 then
			return true
		end
	elseif game.CreatorType == Enum.CreatorType.Group then
		local rank = st.rank
		if rank ~= nil then
			if rank >= 255 then
				return true
			end
			local needed = settings.groupRank
			if needed ~= nil and rank >= needed then
				return true
			end
		end
	end
	return settings.panelUserIds[userId] == true
end

-- Who may use the panel. In Studio without a published place (CreatorId 0) everyone may, for testing.
local function isStaff(st: PlayerState): boolean
	if not settings.panelEnabled then
		return false
	end
	if RunService:IsStudio() and game.CreatorId == 0 then
		return true
	end
	return isProtected(st)
end

---------------------------------------------------------------------------------------------------------------------
-- Queue (MemoryStore). Items wait in a small outbox and are sent one after another, with backoff on errors.
---------------------------------------------------------------------------------------------------------------------

local queue = MemoryStoreService:GetQueue(QUEUE_NAME)
local outbox: { { [string]: any } } = {}
local tries: { [any]: number } = setmetatable({}, { __mode = "k" }) :: any
local sending = false
local closing = false

local function sendOutbox()
	local backoff = 2
	while #outbox > 0 do
		local item = outbox[1]
		local ok, err = pcall(function()
			queue:AddAsync(item, QUEUE_TTL)
		end)
		if ok then
			-- While AddAsync waited, a full outbox may have dropped this item already.
			if outbox[1] == item then
				table.remove(outbox, 1)
			end
			backoff = 2
		else
			local count = (tries[item] or 0) + 1
			tries[item] = count
			if count >= MAX_ITEM_TRIES and outbox[1] == item then
				table.remove(outbox, 1)
			end
			warnEvery("queue", 60, "could not send anti-cheat hits to Modhelm, trying again: " .. tostring(err))
			-- Wait in small steps, so a server shutdown does not sit out a long backoff.
			local waitUntil = os.clock() + backoff
			repeat
				task.wait(0.5)
			until closing or os.clock() >= waitUntil
			backoff = math.min(backoff * 2, 60)
		end
	end
	sending = false
end

local function enqueue(item: { [string]: any })
	if #outbox >= OUTBOX_CAP then
		table.remove(outbox, 1)
		warnEvery("outbox", 300, "too many anti-cheat hits waiting, the oldest were dropped")
	end
	table.insert(outbox, item)
	if not sending then
		sending = true
		task.spawn(sendOutbox)
	end
end

local function sendAggregate(st: PlayerState, check: string, agg: Aggregate, now: number)
	if agg.n <= 0 then
		return
	end
	-- Studio test players have user ids below 1; Modhelm cannot use those.
	if st.userId > 0 then
		enqueue({
			v = MESSAGE_VERSION,
			t = "flag",
			u = st.userId,
			c = check,
			n = math.min(agg.n, 1000),
			-- Checks without a measured number (decoy remote, skipped prompt hold) send none.
			x = if agg.l > 0 then round1(agg.x) else nil,
			l = if agg.l > 0 then round1(agg.l) else nil,
			p = game.PlaceId,
			j = serverKey,
			at = os.time(),
		})
	end
	agg.n = 0
	agg.x = 0
	agg.l = 0
	agg.sentAt = now
end

-- Send the counts whose 20 second window is over (force = everything, for leaving players and shutdown).
local function flushDue(st: PlayerState, now: number, force: boolean)
	for check, agg in st.agg do
		if agg.n > 0 and (force or now - agg.sentAt >= ITEM_WINDOW) then
			sendAggregate(st, check, agg, now)
		end
	end
end

---------------------------------------------------------------------------------------------------------------------
-- Replays (data store "ModhelmReplays"). The main loop writes one sample per player and tick into rings that were
-- created when the player joined, so sampling allocates no tables. Building a replay happens only when one is saved.
---------------------------------------------------------------------------------------------------------------------

type ReplayFigure = { st: PlayerState, userId: number, name: string, displayName: string }

type ReplayJob = {
	focus: ReplayFigure,
	others: { ReplayFigure },
	check: string?,
	hitClock: number, -- os.clock() at the hit
	hitUnix: number, -- unix seconds at the hit, with milliseconds
}

type ReplayInfo = { key: string, userId: number, name: string, displayName: string, check: string?, at: number }

type IndexEntry = { id: string, at: number }

-- Server ticks: replayTick counts every pass of the main loop, replayClock holds os.clock() of the last
-- REPLAY_SAMPLES ticks (slot = (tick - 1) % REPLAY_SAMPLES + 1, the same slot the player rings use).
local replayTick = 0
local replayClock: { number } = table.create(REPLAY_SAMPLES, 0)
local replayCounter = 0 -- part of the key, counts the replays of this server
local replayTimes: { number } = {} -- os.clock() of the automatic replays in the last REPLAY_SERVER_WINDOW
local pendingReplays = 0 -- replays waiting for their 5 seconds or being written (BindToClose waits for them)
local savedReplays: { ReplayInfo } = {} -- newest first, at most REPLAY_LIST
local replayCache: { [string]: { [string]: any } } = {} -- the stored tables of savedReplays
local pendingIndex: { IndexEntry } = {} -- keys whose index update failed, added on the next try
local replayStoreObject: DataStore? = nil

local function replaySlot(tick: number): number
	return (tick - 1) % REPLAY_SAMPLES + 1
end

-- Call only inside pcall: GetDataStore throws when data stores cannot be used (for example an unpublished place).
local function replayStore(): DataStore
	local store = replayStoreObject
	if not store then
		store = DataStoreService:GetDataStore(REPLAY_STORE, REPLAY_SCOPE)
		replayStoreObject = store
	end
	return store :: DataStore
end

local function unixNow(): number
	return DateTime.now().UnixTimestampMillis / 1000
end

-- One sample per tick: position and yaw of the root part. Nothing is written while the player has no living
-- character, so those slots keep an old tick and count as "not there".
local function sampleReplay(st: PlayerState, slot: number)
	local character = st.player.Character
	if not character then
		return
	end
	local humanoid = character:FindFirstChildOfClass("Humanoid")
	local root = if humanoid then humanoid.RootPart else nil
	if not humanoid or not root or humanoid.Health <= 0 then
		return
	end
	local cf = root.CFrame
	local look = cf.LookVector
	st.repPos[slot] = cf.Position
	-- 0 faces -Z; the same turn as CFrame.Angles(0, yaw, 0).
	st.repYaw[slot] = math.atan2(-look.X, -look.Z)
	st.repTick[slot] = replayTick
end

-- The newest sample of a player (this tick or the one before, the main loop may not have reached them yet).
local function latestPos(st: PlayerState): Vector3?
	for back = 0, 1 do
		local tick = replayTick - back
		if tick >= 1 then
			local slot = replaySlot(tick)
			if st.repTick[slot] == tick then
				return st.repPos[slot]
			end
		end
	end
	return nil
end

local function figureOf(st: PlayerState): ReplayFigure
	return { st = st, userId = st.userId, name = st.player.Name, displayName = st.player.DisplayName }
end

-- Checks the limits and remembers who is in the replay. Returns nil and an error code when the limits say no.
-- Automatic replays count against the server limit, replays from the panel do not.
local function startReplay(st: PlayerState, check: string?, manual: boolean): (ReplayJob?, string?)
	local now = os.clock()
	if now - st.replayAt < REPLAY_PLAYER_GAP then
		return nil, "replay_recent"
	end
	if not manual then
		while replayTimes[1] and now - replayTimes[1] > REPLAY_SERVER_WINDOW do
			table.remove(replayTimes, 1)
		end
		if #replayTimes >= REPLAY_SERVER_MAX then
			return nil, "replay_limit"
		end
		table.insert(replayTimes, now)
	end
	st.replayAt = now

	-- The nearest players within REPLAY_RADIUS at this moment.
	local others: { ReplayFigure } = {}
	local center = latestPos(st)
	if center then
		local near: { { st: PlayerState, d: number } } = {}
		for _, other in states do
			if other ~= st then
				local pos = latestPos(other)
				if pos then
					local d = (pos - center).Magnitude
					if d <= REPLAY_RADIUS then
						table.insert(near, { st = other, d = d })
					end
				end
			end
		end
		table.sort(near, function(a, b)
			return a.d < b.d
		end)
		for i = 1, math.min(REPLAY_OTHERS, #near) do
			table.insert(others, figureOf(near[i].st))
		end
	end

	return {
		focus = figureOf(st),
		others = others,
		check = check,
		hitClock = now,
		hitUnix = unixNow(),
	}, nil
end

-- "x,y,z,yaw" with one decimal and whole degrees (0 to 359), or "" for an unusable value.
local function sampleText(pos: Vector3, yaw: number): string
	local x, y, z = pos.X, pos.Y, pos.Z
	if x ~= x or y ~= y or z ~= z or math.abs(x) > 1e7 or math.abs(y) > 1e7 or math.abs(z) > 1e7 then
		return ""
	end
	local degrees = math.floor(math.deg(yaw) + 0.5) % 360
	if degrees ~= degrees then
		degrees = 0
	end
	return string.format("%.1f,%.1f,%.1f,%d", x, y, z, degrees)
end

-- The ticks run about every 0.25 s but not exactly, so the stored samples are placed on an exact 1/REPLAY_HZ grid:
-- a point between two samples of the player is blended, a point next to one sample takes it, else it stays empty.
local function playerSamples(st: PlayerState, startClock: number, gridA: { number }, oldest: number, newest: number): string
	local parts = table.create(REPLAY_SAMPLES, "")
	local repTick, repPos, repYaw = st.repTick, st.repPos, st.repYaw
	for k = 1, REPLAY_SAMPLES do
		local g = startClock + (k - 1) / REPLAY_HZ
		local a = gridA[k]
		local b = a + 1
		local slotA, slotB = replaySlot(math.max(a, 1)), replaySlot(b)
		local okA = a >= oldest and repTick[slotA] == a
		local okB = b >= oldest and b <= newest and repTick[slotB] == b
		local clockA, clockB = replayClock[slotA], replayClock[slotB]
		local text = ""
		if okA and okB and clockB > clockA and clockB - clockA <= REPLAY_MAX_STEP then
			local w = math.clamp((g - clockA) / (clockB - clockA), 0, 1)
			text = sampleText(repPos[slotA]:Lerp(repPos[slotB], w), if w < 0.5 then repYaw[slotA] else repYaw[slotB])
		elseif okA and g - clockA <= REPLAY_NEAR then
			text = sampleText(repPos[slotA], repYaw[slotA])
		elseif okB and clockB - g <= REPLAY_NEAR then
			text = sampleText(repPos[slotB], repYaw[slotB])
		end
		parts[k] = text
	end
	return table.concat(parts, ";")
end

-- The table stored in the data store (docs/anticheat.md). Runs without yielding, so the rings do not move meanwhile.
local function buildReplay(job: ReplayJob, key: string, at: number): { [string]: any }
	local startUnix = math.floor((job.hitUnix - REPLAY_BEFORE) * 100 + 0.5) / 100
	local startClock = job.hitClock + (startUnix - job.hitUnix)
	local newest = replayTick
	local oldest = math.max(1, newest - REPLAY_SAMPLES + 1)
	-- For each stored point the newest tick at or before it (oldest - 1 when it lies before every kept tick).
	local gridA = table.create(REPLAY_SAMPLES, 0)
	local tick = oldest - 1
	for k = 1, REPLAY_SAMPLES do
		local g = startClock + (k - 1) / REPLAY_HZ
		while tick < newest and replayClock[replaySlot(tick + 1)] <= g do
			tick += 1
		end
		gridA[k] = tick
	end

	local players = {}
	local focus = job.focus
	table.insert(players, {
		u = focus.userId,
		n = focus.name,
		d = focus.displayName,
		f = true,
		s = playerSamples(focus.st, startClock, gridA, oldest, newest),
	})
	for _, other in job.others do
		table.insert(players, {
			u = other.userId,
			n = other.name,
			d = other.displayName,
			s = playerSamples(other.st, startClock, gridA, oldest, newest),
		})
	end

	return {
		v = 1,
		id = key,
		placeId = game.PlaceId,
		jobId = serverKey,
		at = at,
		check = job.check,
		focus = focus.userId,
		hz = REPLAY_HZ,
		start = startUnix,
		players = players,
	}
end

local function validIndex(raw: any): { IndexEntry }
	local list: { IndexEntry } = {}
	if type(raw) == "table" then
		for _, entry in ipairs(raw) do
			if type(entry) == "table" and type(entry.id) == "string" and type(entry.at) == "number" then
				table.insert(list, { id = entry.id, at = entry.at })
			end
		end
	end
	return list
end

local removeReplays: (ids: { string }, pruneIndex: boolean) -> ()

-- Adds keys to "index" and takes removed ones out, in one UpdateAsync. Entries beyond REPLAY_INDEX_CAP (the oldest)
-- leave the index and are removed from the store afterwards. Returns false when the data store could not be reached.
local function updateIndex(add: { IndexEntry }, remove: { [string]: boolean }?): boolean
	local overflow: { string } = {}
	local ok, err = pcall(function()
		replayStore():UpdateAsync(REPLAY_INDEX_KEY, function(old: any): any
			table.clear(overflow) -- UpdateAsync may call this more than once
			local list: { IndexEntry } = {}
			local seen: { [string]: boolean } = {}
			for _, entry in validIndex(old) do
				if not seen[entry.id] and not (remove and remove[entry.id]) then
					seen[entry.id] = true
					table.insert(list, entry)
				end
			end
			for _, entry in add do
				if not seen[entry.id] then
					seen[entry.id] = true
					table.insert(list, { id = entry.id, at = entry.at })
				end
			end
			if #list > REPLAY_INDEX_CAP then
				table.sort(list, function(a, b)
					return a.at < b.at
				end)
				while #list > REPLAY_INDEX_CAP do
					local dropped = table.remove(list, 1)
					if dropped then
						table.insert(overflow, dropped.id)
					end
				end
			end
			return list
		end)
	end)
	if not ok then
		warnEvery("replayIndex", 300, "could not update the replay list, trying again later: " .. tostring(err))
		return false
	end
	if #overflow > 0 then
		task.spawn(removeReplays, table.clone(overflow), false)
	end
	return true
end

local function forgetReplay(key: string)
	replayCache[key] = nil
	for i = #savedReplays, 1, -1 do
		if savedReplays[i].key == key then
			table.remove(savedReplays, i)
		end
	end
end

-- Removes replays a few per minute. pruneIndex: also take them out of "index" (not needed for overflow keys).
removeReplays = function(ids: { string }, pruneIndex: boolean)
	local removed: { [string]: boolean } = {}
	local count = 0
	for _, id in ids do
		if closing then
			break
		end
		local ok, err = pcall(function()
			replayStore():RemoveAsync(id)
		end)
		if ok then
			forgetReplay(id)
			removed[id] = true
			count += 1
			if pruneIndex and count >= 10 then
				updateIndex({}, removed)
				removed = {}
				count = 0
			end
		else
			warnEvery("replayRemove", 300, "could not remove an old replay, trying again later: " .. tostring(err))
		end
		task.wait(REPLAY_REMOVE_GAP)
	end
	if pruneIndex and count > 0 then
		updateIndex({}, removed)
	end
end

-- On start and every hour: index entries that failed before, then replays older than REPLAY_KEEP.
local function cleanupReplays()
	if #pendingIndex > 0 then
		local add = pendingIndex
		pendingIndex = {}
		if not updateIndex(add, nil) then
			for _, entry in add do
				table.insert(pendingIndex, entry)
			end
			return
		end
	end
	local okRead, raw = pcall(function()
		return replayStore():GetAsync(REPLAY_INDEX_KEY)
	end)
	if not okRead then
		warnEvery("replayCleanup", 600, "could not read the replay list, trying again in an hour: " .. tostring(raw))
		return
	end
	local cutoff = os.time() - REPLAY_KEEP
	local old: { string } = {}
	for _, entry in validIndex(raw) do
		if entry.at < cutoff then
			table.insert(old, entry.id)
			if #old >= REPLAY_CLEANUP_MAX then
				break
			end
		end
	end
	if #old > 0 then
		removeReplays(old, true)
	end
end

local function rememberReplay(value: { [string]: any }, job: ReplayJob)
	local key: string = value.id
	table.insert(savedReplays, 1, {
		key = key,
		userId = job.focus.userId,
		name = job.focus.name,
		displayName = job.focus.displayName,
		check = job.check,
		at = value.at,
	})
	replayCache[key] = value
	while #savedReplays > REPLAY_LIST do
		local dropped = table.remove(savedReplays)
		if dropped then
			replayCache[dropped.key] = nil
		end
	end
end

-- Builds and writes one replay (SetAsync, one retry), reports it to Modhelm and adds it to "index".
-- Returns the key, or nil when it could not be saved.
local function saveReplay(job: ReplayJob): string?
	replayCounter += 1
	local at = math.floor(job.hitUnix)
	local key = string.format("r_%d_%d_%d", at, math.max(job.focus.userId, 0), replayCounter)
	local okBuild, built = pcall(buildReplay, job, key, at)
	if not okBuild then
		warnEvery("replayBuild", 60, "could not build a replay: " .. tostring(built))
		return nil
	end
	local value: { [string]: any } = built
	local saved = false
	for attempt = 1, 2 do
		local ok, err = pcall(function()
			replayStore():SetAsync(key, value)
		end)
		if ok then
			saved = true
			break
		end
		warnEvery("replaySave" .. attempt, 60, "could not save a replay" .. (if attempt == 1 then ", trying once more: " else ": ") .. tostring(err))
		if attempt == 1 then
			task.wait(3)
		end
	end
	if not saved then
		return nil
	end

	rememberReplay(value, job)
	-- Studio test players have user ids below 1; Modhelm cannot use those.
	if job.focus.userId > 0 then
		enqueue({
			v = MESSAGE_VERSION,
			t = "replay",
			u = job.focus.userId,
			c = job.check,
			r = key,
			p = game.PlaceId,
			j = serverKey,
			at = os.time(),
		})
	end
	local entry = { id = key, at = at }
	if not updateIndex({ entry }, nil) then
		task.wait(5)
		if not updateIndex({ entry }, nil) then
			-- Added by the next cleanup run, so the replay is still removed after 7 days.
			table.insert(pendingIndex, entry)
		end
	end
	return key
end

-- Saves a replay of a started job after REPLAY_AFTER seconds. Yields; returns the key or nil.
local function finishReplay(job: ReplayJob): string?
	pendingReplays += 1
	task.wait(REPLAY_AFTER)
	local ok, key = pcall(saveReplay, job)
	pendingReplays -= 1
	if not ok then
		warnEvery("replaySave", 60, "could not save a replay: " .. tostring(key))
		return nil
	end
	return key
end

-- Called on every counted hit: the first hit of a player (none in the last 2 minutes) starts a replay.
local function autoReplay(st: PlayerState, check: string)
	local job = startReplay(st, check, false)
	if job then
		task.spawn(finishReplay, job)
	end
end

---------------------------------------------------------------------------------------------------------------------
-- Hits
---------------------------------------------------------------------------------------------------------------------

local function autoKick(st: PlayerState, check: string, now: number)
	st.kicked = true
	flushDue(st, now, true)
	if st.userId > 0 then
		enqueue({
			v = MESSAGE_VERSION,
			t = "kick",
			u = st.userId,
			c = check,
			n = math.min(#st.kickTimes, 1000),
			p = game.PlaceId,
			j = serverKey,
			at = os.time(),
		})
	end
	local message = if settings.kickMessage ~= "" then settings.kickMessage else DEFAULT_KICK_MESSAGE
	local player = st.player
	-- Deferred: kicking fires PlayerRemoving, which changes `states` while the check loop walks it.
	task.defer(function()
		local ok, err = pcall(function()
			player:Kick(message)
		end)
		if not ok then
			warnEvery("kick", 60, "could not kick a player: " .. tostring(err))
		end
	end)
end

local function addToFeed(st: PlayerState, check: string, value: number, limit: number)
	local at = os.time()
	local top = feed[1]
	if top and top.userId == st.userId and top.check == check and at - top.at <= FEED_MERGE then
		top.n += 1
		top.at = at
		if value > top.x then
			top.x = round1(value)
			top.l = round1(limit)
		end
		return
	end
	table.insert(feed, 1, {
		userId = st.userId,
		name = st.player.Name,
		displayName = st.player.DisplayName,
		check = check,
		n = 1,
		x = round1(value),
		l = round1(limit),
		at = at,
	})
	if #feed > FEED_SIZE then
		table.remove(feed)
	end
end

local function hit(st: PlayerState, check: string, value: number, limit: number, now: number)
	local until_ = st.cooldown[check]
	if until_ and now < until_ then
		return
	end
	st.cooldown[check] = now + HIT_COOLDOWN

	st.hits += 1
	st.checks[check] = (st.checks[check] or 0) + 1
	st.lastAt = os.time()
	addToFeed(st, check, value, limit)

	local agg = st.agg[check]
	if not agg then
		agg = { n = 0, x = 0, l = 0, sentAt = -math.huge }
		st.agg[check] = agg
	end
	agg.n += 1
	if value > agg.x then
		agg.x = value
		agg.l = limit
	end
	if now - agg.sentAt >= ITEM_WINDOW then
		sendAggregate(st, check, agg, now)
	end

	-- Before a possible kick, so the replay shows what led to it.
	autoReplay(st, check)

	if st.kicked then
		return
	end
	local times = st.kickTimes
	table.insert(times, now)
	while times[1] and now - times[1] > KICK_WINDOW do
		table.remove(times, 1)
	end
	if settings.action == "kick" and #times >= settings.kickAfter and not isProtected(st) then
		autoKick(st, check, now)
	end
end

---------------------------------------------------------------------------------------------------------------------
-- Checks
---------------------------------------------------------------------------------------------------------------------

-- One RaycastParams for all rays; it leaves out every character (rebuilt when characters change).
local rayParams = RaycastParams.new()
rayParams.FilterType = Enum.RaycastFilterType.Exclude
rayParams.IgnoreWater = true
rayParams.RespectCanCollide = true

-- Fly check: anything below counts as ground, water too (deep water is swimming, not flying).
local groundParams = RaycastParams.new()
groundParams.FilterType = Enum.RaycastFilterType.Exclude
groundParams.IgnoreWater = false

-- Fly check: parts right next to a rising player (ladders, trusses, walls). The server does not always see the
-- climbing state of a character the client moves, so rising next to something counts as climbing.
local nearParams = OverlapParams.new()
nearParams.FilterType = Enum.RaycastFilterType.Exclude
-- Used only after a noclip ray hit, to measure how thick the part is along the path.
local thicknessParams = RaycastParams.new()
thicknessParams.FilterType = Enum.RaycastFilterType.Include
thicknessParams.IgnoreWater = true

local function rebuildFilter()
	local characters: { Instance } = {}
	for _, player in Players:GetPlayers() do
		local character = player.Character
		if character then
			table.insert(characters, character)
		end
	end
	rayParams.FilterDescendantsInstances = characters
	groundParams.FilterDescendantsInstances = characters
	nearParams.FilterDescendantsInstances = characters
end

-- Distance from the root part down to the feet.
local function feetOffset(humanoid: Humanoid, root: BasePart): number
	if humanoid.RigType == Enum.HumanoidRigType.R6 then
		return root.Size.Y / 2 + 2
	end
	return humanoid.HipHeight + root.Size.Y / 2
end

-- True when the straight line between two samples goes through a solid part thicker than NOCLIP_THICKNESS.
-- Returns the thickness as the measured value.
local function crossedWall(from: Vector3, to: Vector3): number?
	local path = to - from
	local result = Workspace:Raycast(from, path, rayParams)
	if not result then
		return nil
	end
	local part = result.Instance
	if part == Workspace.Terrain or not part:IsA("BasePart") then
		return nil -- terrain slopes would give false hits
	end
	thicknessParams.FilterDescendantsInstances = { part }
	local back = Workspace:Raycast(to, -path, thicknessParams)
	local entry = (result.Position - from).Magnitude
	-- No hit on the way back means the player ended up inside the part.
	local exit = if back then (back.Position - to).Magnitude else 0
	local thickness = path.Magnitude - entry - exit
	return if thickness > NOCLIP_THICKNESS then thickness else nil
end

local function tickPlayer(st: PlayerState, now: number)
	local character = st.player.Character
	local humanoid = if character then character:FindFirstChildOfClass("Humanoid") else nil
	local root = if humanoid then humanoid.RootPart else nil

	local skip = now < st.exemptUntil or now - st.spawnAt < SPAWN_GRACE
	if humanoid and not skip then
		skip = humanoid.Health <= 0 or humanoid.Sit or humanoid.PlatformStand
	end
	-- Players without a character (menus, lobbies) still count for the remotes check.
	st.active = not skip
	if skip or not humanoid or not root then
		resetMotion(st)
		return
	end

	local checks = settings.checks
	local limits = LIMITS[settings.sensitivity]
	local pos = root.Position
	-- WalkSpeed as the server knows it (changes made on the client do not reach the server).
	local walk = humanoid.WalkSpeed
	local maxWalk = walk
	for i = 1, st.ringCount do
		maxWalk = math.max(maxWalk, st.ringWalk[i])
	end
	local speedLimit = maxWalk * limits.speedFactor + SPEED_BONUS

	local last = st.lastPos
	local teleported = false
	if last then
		local dt = now - st.lastTime
		if dt > 0 then
			local d = pos - last
			-- Falling is not a teleport: only horizontal and upward movement count for the step.
			local up = math.max(d.Y, 0)
			local step = math.sqrt(d.X * d.X + d.Z * d.Z + up * up)

			if checks.teleport and step > limits.teleport and step > speedLimit * dt then
				teleported = true
				hit(st, "teleport", step, limits.teleport, now)
			end

			if checks.noclip and not teleported and step > MIN_NOCLIP_STEP then
				-- Respect the character's collision group, so parts it may pass through do not count.
				rayParams.CollisionGroup = root.CollisionGroup
				local thickness = crossedWall(last, pos)
				if thickness then
					hit(st, "noclip", thickness, NOCLIP_THICKNESS, now)
				end
			end

			if checks.fly then
				local vy = d.Y / dt
				local state = humanoid:GetState()
				local floating = vy > FLY_FALLING
					and state ~= Enum.HumanoidStateType.Climbing
					and state ~= Enum.HumanoidStateType.Swimming
					and state ~= Enum.HumanoidStateType.Seated
				if floating then
					local reach = feetOffset(humanoid, root) + FLY_HEIGHT
					floating = Workspace:Raycast(pos, Vector3.new(0, -reach, 0), groundParams) == nil
				end
				if floating and vy > 1 then
					floating = #Workspace:GetPartBoundsInRadius(pos, CLIMB_RADIUS, nearParams) == 0
				end
				if floating then
					st.airTime += dt
					if st.airTime > limits.fly then
						hit(st, "fly", st.airTime, limits.fly, now)
						st.airTime = 0
					end
				else
					st.airTime = 0
				end
			end

			-- Infinite jump: a sudden upward push while the player was already in the air (the sample before had no
			-- ground below) and not next to something to climb. Double jumps of the game itself are allowed.
			local vy = d.Y / dt
			if checks.jump then
				if not teleported and vy - st.lastVy > AIR_JUMP_BOOST and vy > 10 then
					local reach = feetOffset(humanoid, root) + 2
					local grounded = Workspace:Raycast(last, Vector3.new(0, -reach, 0), groundParams) ~= nil
					if not grounded and #Workspace:GetPartBoundsInRadius(last, CLIMB_RADIUS, nearParams) == 0 then
						table.insert(st.airJumps, now)
					end
				end
				while st.airJumps[1] and now - st.airJumps[1] > AIR_JUMP_WINDOW do
					table.remove(st.airJumps, 1)
				end
				if #st.airJumps > limits.airJumps then
					hit(st, "jump", #st.airJumps, limits.airJumps, now)
					table.clear(st.airJumps)
				end
			end
			st.lastVy = vy
		end
	end

	-- Fling and spin: tools put a huge spin on the own character to throw others away. Normal turning stays far below.
	if checks.fling then
		local turns = root.AssemblyAngularVelocity.Magnitude / TWO_PI
		if turns > limits.fling then
			st.spinSamples += 1
			if st.spinSamples >= FLING_SAMPLES then
				hit(st, "fling", turns, limits.fling, now)
				st.spinSamples = 0
			end
		else
			st.spinSamples = 0
		end
	end

	-- A teleport starts the speed window again, so one jump is not counted twice.
	if teleported then
		st.ringCount = 0
		st.ringHead = 0
	end
	local head = st.ringHead % RING + 1
	st.ringHead = head
	st.ringPos[head] = pos
	st.ringTime[head] = now
	st.ringWalk[head] = walk
	if st.ringCount < RING then
		st.ringCount += 1
	end
	st.lastPos = pos
	st.lastTime = now

	if checks.speed and st.ringCount == RING then
		local oldest = head % RING + 1
		local elapsed = now - st.ringTime[oldest]
		if elapsed >= 0.9 then
			local o = st.ringPos[oldest]
			local dx, dz = pos.X - o.X, pos.Z - o.Z
			local speed = math.sqrt(dx * dx + dz * dz) / elapsed
			if speed > speedLimit then
				hit(st, "speed", speed, speedLimit, now)
			end
		end
	end
end

---------------------------------------------------------------------------------------------------------------------
-- Remotes: one extra listener on every RemoteEvent counts the calls per player.
---------------------------------------------------------------------------------------------------------------------

local watched: { [Instance]: boolean } = setmetatable({}, { __mode = "k" }) :: any

local function onRemoteCall(player: Player)
	local st = states[player]
	if st then
		st.remoteCount += 1
	end
end

-- Distance from a player's character to the thing they used (prompt or click detector parent), minus half the size
-- of a part, because Roblox measures to the part and big parts would count from their centre.
local function distanceTo(player: Player, target: Instance?): number?
	local character = player.Character
	local root = if character then character:FindFirstChild("HumanoidRootPart") else nil
	if not root or not root:IsA("BasePart") or not target then
		return nil
	end
	local rootPos = (root :: BasePart).Position
	if target:IsA("BasePart") then
		local part = target :: BasePart
		return math.max(0, (part.Position - rootPos).Magnitude - part.Size.Magnitude / 2)
	elseif target:IsA("Attachment") then
		return ((target :: Attachment).WorldPosition - rootPos).Magnitude
	elseif target:IsA("Model") then
		local ok, cf, size = pcall(function()
			return (target :: Model):GetBoundingBox()
		end)
		if ok then
			return math.max(0, (cf.Position - rootPos).Magnitude - size.Magnitude / 2)
		end
	end
	return nil
end

-- A prompt or click from further away than the game allows (tools like fireproximityprompt and fireclickdetector).
local function checkInteract(player: Player, target: Instance?, maxDistance: number): boolean
	local st = states[player]
	if not st or not settings.enabled or not settings.checks.interact or os.clock() < st.exemptUntil then
		return false
	end
	local dist = distanceTo(player, target)
	local allowed = maxDistance + LIMITS[settings.sensitivity].interact
	if dist and dist > allowed then
		hit(st, "interact", dist, allowed, os.clock())
		return true
	end
	return false
end

local watchedClicks: { [Instance]: boolean } = setmetatable({}, { __mode = "k" }) :: any

local function watchClick(instance: Instance)
	if watchedClicks[instance] then
		return
	end
	watchedClicks[instance] = true
	local detector = instance :: ClickDetector
	detector.MouseClick:Connect(function(player: Player)
		checkInteract(player, detector.Parent, detector.MaxActivationDistance)
	end)
end

local function watchRemote(instance: Instance)
	if instance:IsA("ClickDetector") then
		watchClick(instance)
		return
	end
	if watched[instance] or not instance:IsA("RemoteEvent") then
		return
	end
	watched[instance] = true
	(instance :: RemoteEvent).OnServerEvent:Connect(onRemoteCall)
end

-- Service by service, so one service the script may not read does not stop the others.
for _, service in game:GetChildren() do
	local okList, descendants = pcall(function()
		return service:GetDescendants()
	end)
	if okList then
		for _, instance in descendants do
			watchRemote(instance)
		end
	end
end
game.DescendantAdded:Connect(watchRemote)

-- Prompts: too far away, or triggered without holding as long as the prompt asks (a hold of at least half a second).
ProximityPromptService.PromptButtonHoldBegan:Connect(function(prompt: ProximityPrompt, player: Player)
	local st = states[player]
	if st then
		st.holds[prompt] = os.clock()
	end
end)
ProximityPromptService.PromptTriggered:Connect(function(prompt: ProximityPrompt, player: Player)
	local st = states[player]
	if not st then
		return
	end
	local began = st.holds[prompt]
	st.holds[prompt] = nil
	if checkInteract(player, prompt.Parent, prompt.MaxActivationDistance) then
		return
	end
	if not settings.enabled or not settings.checks.interact or os.clock() < st.exemptUntil then
		return
	end
	if prompt.HoldDuration >= 0.5 and (not began or os.clock() - began < prompt.HoldDuration * 0.5) then
		hit(st, "interact", 0, 0, os.clock())
	end
end)

-- Decoy remotes: any call is an exploit tool firing every remote it finds.
local function onHoneypot(player: Player)
	local st = states[player]
	if st and settings.enabled and settings.checks.honeypot then
		hit(st, "honeypot", 0, 0, os.clock())
	end
end
for _, name in HONEYPOT_NAMES do
	if not ReplicatedStorage:FindFirstChild(name) then
		local decoy = Instance.new("RemoteEvent")
		decoy.Name = name
		decoy.Parent = ReplicatedStorage
		decoy.OnServerEvent:Connect(onHoneypot)
	end
end

---------------------------------------------------------------------------------------------------------------------
-- Staff panel
---------------------------------------------------------------------------------------------------------------------

local templateWarned = false

local function panelTemplate(): LocalScript?
	local template = script:FindFirstChild(PANEL_SCRIPT_NAME)
	if template and template:IsA("LocalScript") then
		return template :: LocalScript
	end
	if not templateWarned then
		templateWarned = true
		warn("[Modhelm] the LocalScript " .. PANEL_SCRIPT_NAME .. " is missing inside this script, so there is no staff panel. The checks keep running.")
	end
	return nil
end

local function findPlayerGui(player: Player): PlayerGui?
	local playerGui = player:FindFirstChildOfClass("PlayerGui")
	if playerGui then
		return playerGui
	end
	local found = player:WaitForChild("PlayerGui", 30)
	if found and found:IsA("PlayerGui") then
		return found :: PlayerGui
	end
	return nil
end

-- Give the panel to staff and take it away from everyone else. Runs at most once at a time per player.
local function updatePanel(st: PlayerState)
	if st.panelBusy then
		st.panelAgain = true
		return
	end
	st.panelBusy = true
	repeat
		st.panelAgain = false
		local player = st.player
		if player.Parent ~= Players then
			break
		end
		ensureRank(st)
		local want = isStaff(st)
		local playerGui = findPlayerGui(player)
		if playerGui then
			local existing = playerGui:FindFirstChild(PANEL_GUI_NAME)
			if want and not existing then
				local template = panelTemplate()
				if template then
					local gui = Instance.new("ScreenGui")
					gui.Name = PANEL_GUI_NAME
					gui.ResetOnSpawn = false
					gui.DisplayOrder = 60
					gui.ZIndexBehavior = Enum.ZIndexBehavior.Sibling
					local copy = template:Clone()
					copy.Enabled = true
					copy.Parent = gui
					gui.Parent = playerGui
				end
			elseif not want and existing then
				existing:Destroy()
			end
		end
	until not st.panelAgain
	st.panelBusy = false
end

local function updateAllPanels()
	for _, st in states do
		task.spawn(updatePanel, st)
	end
end

---------------------------------------------------------------------------------------------------------------------
-- Settings loading
---------------------------------------------------------------------------------------------------------------------

local loading = false
local loadAgain = false

local function loadSettings()
	if loading then
		loadAgain = true
		return
	end
	loading = true
	repeat
		loadAgain = false
		local okRead, result = pcall(function()
			return DataStoreService:GetDataStore(DATA_STORE):GetAsync(SETTINGS_KEY)
		end)
		if okRead then
			local raw = result
			if type(raw) == "string" then
				local okDecode, decoded = pcall(decodeJson, raw)
				raw = if okDecode then decoded else nil
			end
			settings = parseSettings(raw)
			updateAllPanels()
		else
			warnEvery("settings", 600, "could not read the anti-cheat settings, keeping the current ones: " .. tostring(result))
		end
	until not loadAgain
	loading = false
end

local function handleMessage(message: { Data: any, Sent: number })
	local data = message.Data
	if type(data) == "string" then
		local okDecode, decoded = pcall(decodeJson, data)
		if not okDecode then
			return
		end
		data = decoded
	end
	if type(data) ~= "table" or data.v ~= MESSAGE_VERSION or data.type ~= "guard_config" then
		return -- other types belong to ModhelmLive or newer Modhelm versions
	end
	task.spawn(loadSettings)
end

local function subscribe()
	local delaySeconds = 5
	while true do
		local okSub, err = pcall(function()
			MessagingService:SubscribeAsync(TOPIC, handleMessage)
		end)
		if okSub then
			return
		end
		warnEvery("subscribe", 120, "could not listen for Modhelm messages, trying again: " .. tostring(err))
		task.wait(delaySeconds)
		delaySeconds = math.min(delaySeconds * 2, 120)
	end
end

---------------------------------------------------------------------------------------------------------------------
-- Panel requests
---------------------------------------------------------------------------------------------------------------------

local function fail(code: string): { [string]: any }
	return { ok = false, error = code }
end

local function targetFrom(payload: any): Player?
	if type(payload) ~= "table" or not isInteger(payload.userId) then
		return nil
	end
	return Players:GetPlayerByUserId(payload.userId)
end

local function buildState(): { [string]: any }
	local list = {}
	for _, player in Players:GetPlayers() do
		local st = states[player]
		local checks = {}
		if st then
			for name, count in st.checks do
				checks[name] = count
			end
		end
		table.insert(list, {
			userId = player.UserId,
			name = player.Name,
			displayName = player.DisplayName,
			hits = if st then st.hits else 0,
			checks = checks,
			lastAt = if st then st.lastAt else nil,
			staff = if st then isProtected(st) else false,
		})
	end
	return {
		ok = true,
		mode = {
			licensed = settings.licensed,
			enabled = settings.enabled,
			action = settings.action,
			sensitivity = settings.sensitivity,
			kickAfter = settings.kickAfter,
		},
		uptime = math.floor(os.clock() - startedAt),
		players = list,
		feed = feed,
		replays = savedReplays,
	}
end

-- "Save replay" in the panel: same per player limit as automatic replays, not counted against the server limit.
-- Answers after the replay is written (about REPLAY_AFTER seconds).
local function panelReplaySave(payload: any): { [string]: any }
	local target = targetFrom(payload)
	local targetState = if target then states[target] else nil
	if not targetState then
		return fail("not_found")
	end
	local job, code = startReplay(targetState, nil, true)
	if not job then
		return fail(code or "replay_failed")
	end
	local key = finishReplay(job)
	return if key then { ok = true, key = key } else fail("replay_failed")
end

local function validReplayKey(key: any): boolean
	return type(key) == "string" and #key <= REPLAY_KEY_MAX and string.match(key, "^r_[0-9A-Za-z_]+$") ~= nil
end

-- "Watch" in the panel: the stored table, from memory when this server saved it, else from the data store.
local function panelReplay(payload: any): { [string]: any }
	local key = if type(payload) == "table" then payload.key else nil
	if not validReplayKey(key) then
		return fail("replay_gone")
	end
	local cached = replayCache[key]
	if cached then
		return { ok = true, replay = cached }
	end
	local okRead, value = pcall(function()
		return replayStore():GetAsync(key)
	end)
	if not okRead then
		warnEvery("replayRead", 60, "could not read a replay: " .. tostring(value))
		return fail("replay_read")
	end
	if type(value) ~= "table" or value.v ~= 1 then
		return fail("replay_gone")
	end
	return { ok = true, replay = value }
end

local function panelKick(st: PlayerState, payload: any): { [string]: any }
	local target = targetFrom(payload)
	if not target then
		return fail("not_found")
	end
	if target == st.player then
		return fail("self")
	end
	local targetState = states[target]
	if targetState and isProtected(targetState) then
		return fail("staff")
	end
	local reason = ""
	if payload.reason ~= nil then
		if type(payload.reason) ~= "string" or #payload.reason > 2000 then
			return fail("reason")
		end
		reason = clipText(payload.reason, MAX_TEXT)
	end

	-- The reason is shown to another player, so it goes through the Roblox text filter first.
	local shown = DEFAULT_STAFF_KICK_MESSAGE
	if reason ~= "" then
		local okFilter, filtered = pcall(function()
			local result = TextService:FilterStringAsync(reason, st.player.UserId, Enum.TextFilterContext.PublicChat)
			return result:GetNonChatStringForUserAsync(target.UserId)
		end)
		if okFilter and type(filtered) == "string" and filtered ~= "" then
			shown = DEFAULT_STAFF_KICK_MESSAGE .. " Reason: " .. filtered
		end
	end

	if targetState then
		targetState.kicked = true
		flushDue(targetState, os.clock(), true)
	end
	if target.UserId > 0 and st.userId > 0 then
		enqueue({
			v = MESSAGE_VERSION,
			t = "staff_kick",
			u = target.UserId,
			by = st.userId,
			r = reason,
			p = game.PlaceId,
			j = serverKey,
			at = os.time(),
		})
	end
	local okKick = pcall(function()
		target:Kick(shown)
	end)
	return if okKick then { ok = true } else fail("kick_failed")
end

local function panelGoto(st: PlayerState, payload: any): { [string]: any }
	local target = targetFrom(payload)
	if not target or target == st.player then
		return fail("not_found")
	end
	local targetCharacter = target.Character
	local ownCharacter = st.player.Character
	if not targetCharacter or not ownCharacter then
		return fail("no_character")
	end
	-- The move itself must not count as a teleport.
	st.exemptUntil = math.max(st.exemptUntil, os.clock() + GOTO_EXEMPT)
	resetMotion(st)
	local okMove = pcall(function()
		local humanoid = ownCharacter:FindFirstChildOfClass("Humanoid")
		local seat = if humanoid then humanoid.SeatPart else nil
		if seat then
			-- Leave the seat first, otherwise the whole vehicle moves along.
			local weld = seat:FindFirstChild("SeatWeld")
			if weld then
				weld:Destroy()
			end
		end
		ownCharacter:PivotTo(targetCharacter:GetPivot() * CFrame.new(4, 0, 0))
	end)
	return if okMove then { ok = true } else fail("move_failed")
end

local remote: RemoteFunction
do
	local existing = ReplicatedStorage:FindFirstChild(REMOTE_NAME)
	if existing and existing:IsA("RemoteFunction") then
		remote = existing :: RemoteFunction
	else
		if existing then
			warn("[Modhelm] ReplicatedStorage." .. REMOTE_NAME .. " is not a RemoteFunction; please remove it")
		end
		remote = Instance.new("RemoteFunction")
		remote.Name = REMOTE_NAME
		remote.Parent = ReplicatedStorage
	end
end

remote.OnServerInvoke = function(player: Player, action: any, payload: any): any
	local st = states[player]
	if not st then
		return fail("not_ready")
	end
	-- Rate limit first, so spam from anyone stays cheap.
	local now = os.clock()
	if now - st.callWindow >= CALL_WINDOW then
		st.callWindow = now
		st.calls = 0
	end
	st.calls += 1
	if st.calls > CALLS_PER_WINDOW then
		return fail("slow_down")
	end
	ensureRank(st)
	if not isStaff(st) then
		return fail("forbidden")
	end
	if action == "state" then
		return buildState()
	elseif action == "kick" then
		return panelKick(st, payload)
	elseif action == "goto" then
		return panelGoto(st, payload)
	elseif action == "replay_save" then
		return panelReplaySave(payload)
	elseif action == "replay" then
		return panelReplay(payload)
	end
	return fail("unknown")
end

---------------------------------------------------------------------------------------------------------------------
-- Exemption for the game's own scripts
---------------------------------------------------------------------------------------------------------------------

do
	local folder: Instance
	local existingFolder = ServerStorage:FindFirstChild(EXEMPT_FOLDER_NAME)
	if existingFolder then
		folder = existingFolder
	else
		folder = Instance.new("Folder")
		folder.Name = EXEMPT_FOLDER_NAME
		folder.Parent = ServerStorage
	end
	local exemptEvent: BindableEvent
	local existingEvent = folder:FindFirstChild("Exempt")
	if existingEvent and existingEvent:IsA("BindableEvent") then
		exemptEvent = existingEvent :: BindableEvent
	else
		exemptEvent = Instance.new("BindableEvent")
		exemptEvent.Name = "Exempt"
		exemptEvent.Parent = folder
	end
	exemptEvent.Event:Connect(function(player: any, seconds: any)
		if typeof(player) ~= "Instance" or not player:IsA("Player") then
			return
		end
		if type(seconds) ~= "number" or seconds ~= seconds or seconds <= 0 then
			return
		end
		local st = states[player]
		if st then
			st.exemptUntil = math.max(st.exemptUntil, os.clock() + math.min(seconds, MAX_EXEMPT))
			resetMotion(st)
		end
	end)

	-- Reach: the game asks before it deals damage; false (and a "reach" hit) when the attacker is too far away.
	local checkHit: BindableFunction
	local existingCheck = folder:FindFirstChild("CheckHit")
	if existingCheck and existingCheck:IsA("BindableFunction") then
		checkHit = existingCheck :: BindableFunction
	else
		checkHit = Instance.new("BindableFunction")
		checkHit.Name = "CheckHit"
		checkHit.Parent = folder
	end
	checkHit.OnInvoke = function(attacker: any, victim: any, maxDistance: any): boolean
		if typeof(attacker) ~= "Instance" or not attacker:IsA("Player") or type(maxDistance) ~= "number" or maxDistance ~= maxDistance then
			return true
		end
		local st = states[attacker]
		if not st or not settings.enabled or not settings.checks.reach or os.clock() < st.exemptUntil then
			return true
		end
		local target: Instance? = nil
		if typeof(victim) == "Instance" then
			if victim:IsA("Player") then
				local character = victim.Character
				target = if character then character:FindFirstChild("HumanoidRootPart") else nil
			elseif victim:IsA("Model") then
				target = victim:FindFirstChild("HumanoidRootPart") or victim.PrimaryPart
			elseif victim:IsA("BasePart") then
				target = victim
			end
		end
		local character = attacker.Character
		local root = if character then character:FindFirstChild("HumanoidRootPart") else nil
		if not target or not target:IsA("BasePart") or not root or not root:IsA("BasePart") then
			return true
		end
		local dist = ((target :: BasePart).Position - (root :: BasePart).Position).Magnitude
		local allowed = maxDistance + LIMITS[settings.sensitivity].reach
		if dist > allowed then
			hit(st, "reach", dist, allowed, os.clock())
			return false
		end
		return true
	end
end

---------------------------------------------------------------------------------------------------------------------
-- Players
---------------------------------------------------------------------------------------------------------------------

local function onCharacter(player: Player)
	local st = states[player]
	if st then
		st.spawnAt = os.clock()
		resetMotion(st)
	end
	task.defer(rebuildFilter)
end

local function onPlayerAdded(player: Player)
	if states[player] then
		return
	end
	local st = newState(player)
	states[player] = st
	player.CharacterAdded:Connect(function()
		onCharacter(player)
	end)
	player.CharacterRemoving:Connect(function()
		task.defer(rebuildFilter)
	end)
	if player.Character then
		onCharacter(player)
	end
	task.spawn(updatePanel, st)
end

Players.PlayerAdded:Connect(onPlayerAdded)
for _, player in Players:GetPlayers() do
	task.spawn(onPlayerAdded, player)
end

Players.PlayerRemoving:Connect(function(player)
	local st = states[player]
	if st then
		flushDue(st, os.clock(), true)
		states[player] = nil
	end
	task.defer(rebuildFilter)
end)

game:BindToClose(function()
	closing = true
	local now = os.clock()
	for _, st in states do
		flushDue(st, now, true)
	end
	local deadline = os.clock() + CLOSE_WAIT
	-- Replays started in the last seconds are still saved when time allows; they add their queue item when done.
	while (#outbox > 0 or pendingReplays > 0) and os.clock() < deadline do
		if not sending then
			sending = true
			task.spawn(sendOutbox)
		end
		task.wait(0.2)
	end
end)

---------------------------------------------------------------------------------------------------------------------
-- Main loop: one loop for all players.
---------------------------------------------------------------------------------------------------------------------

task.spawn(function()
	local secondStart = os.clock()
	while true do
		task.wait(TICK)
		local now = os.clock()
		local elapsed = now - secondStart
		local everySecond = elapsed >= 1
		if everySecond then
			secondStart = now
		end
		replayTick += 1
		local slot = replaySlot(replayTick)
		replayClock[slot] = now
		for _, st in states do
			-- Replay samples are kept even while the checks are off, so staff can still save a replay.
			local okSample, sampleErr = pcall(sampleReplay, st, slot)
			if not okSample then
				warnEvery("sample", 60, "replay sample failed: " .. tostring(sampleErr))
			end
			if not settings.enabled or st.kicked then
				-- Start fresh when the checks come back on, so the gap is not seen as a teleport.
				resetMotion(st)
				st.active = false
			else
				local okTick, err = pcall(tickPlayer, st, now)
				if not okTick then
					warnEvery("tick", 60, "anti-cheat check failed: " .. tostring(err))
				end
				if everySecond and settings.checks.remotes and st.active then
					local limit = LIMITS[settings.sensitivity].remotes
					local rate = st.remoteCount / elapsed
					if rate > limit then
						hit(st, "remotes", rate, limit, now)
					end
				end
			end
			if everySecond then
				st.remoteCount = 0
				flushDue(st, now, false)
			end
		end
	end
end)

task.spawn(function()
	while true do
		loadSettings()
		task.wait(SETTINGS_REFRESH)
	end
end)

if RunService:IsServer() then
	task.spawn(subscribe)
end

-- Replay cleanup: shortly after start (a random delay, so servers that start together do not read at once) and
-- then every hour.
task.spawn(function()
	task.wait(math.random(20, 90))
	while true do
		local okClean, err = pcall(cleanupReplays)
		if not okClean then
			warnEvery("replayCleanup", 600, "replay cleanup failed: " .. tostring(err))
		end
		task.wait(REPLAY_CLEANUP_EVERY)
	end
end)
]]></ProtectedString>
		</Properties>
		<Item class="LocalScript" referent="RBX00000000000000000000000000000000">
			<Properties>
				<string name="Name">ModhelmGuardPanel</string>
				<bool name="Disabled">false</bool>
				<ProtectedString name="Source"><![CDATA[--!strict
--[[
	ModhelmGuardPanel.client.luau

	Staff panel of the Modhelm anti-cheat (https://modhelm.com). Keep this LocalScript inside the Script
	ModhelmGuard (ServerScriptService); the server copies it into the PlayerGui of staff only. Every request goes
	through ReplicatedStorage.ModhelmGuardRemote and is checked on the server again, so copying this script gives
	nobody else any rights.

	The "Modhelm" button at the bottom left or the F2 key opens the panel. It shows the players of this server with
	their hits (with "Save replay", "Go to" and "Kick"), the latest hits and the replays saved in this server. While
	it is open it asks the server for new data every 3 seconds; while it is closed it asks for nothing.

	Watching a replay hides the panel and plays the recorded movement with see-through figures that only you see
	(parts inside your camera, nothing is sent to anyone). Your own camera stays with you unless you press "Follow".
	Closing the replay, the "Modhelm" button or F2 bring the panel back. No HttpService, no other data.
]]

local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local RunService = game:GetService("RunService")
local UserInputService = game:GetService("UserInputService")
local Workspace = game:GetService("Workspace")

local localPlayer = Players.LocalPlayer

local found = ReplicatedStorage:WaitForChild("ModhelmGuardRemote", 60)
if not found or not found:IsA("RemoteFunction") then
	warn("[Modhelm] the anti-cheat panel could not find ReplicatedStorage.ModhelmGuardRemote")
	return
end
local remote = found :: RemoteFunction

local REFRESH_SECONDS = 3
local STATUS_SECONDS = 6
local PANEL_WIDTH = 640
local PANEL_HEIGHT = 380
local COMPACT_WIDTH = 560 -- below this, a player row shows its hits under the name and its buttons below
local ROW_HEIGHT = 56
local ROW_HEIGHT_COMPACT = 96
local REASON_HEIGHT = 44 -- extra height of a row while the kick reason is open
local FEED_ROW_HEIGHT = 48
local BUTTON_GAP = 8
local TAB_WIDTH = 96
local BAR_WIDTH = 640
local BAR_HEIGHT = 108
local REPLAY_MAX_PLAYERS = 12
local REPLAY_MAX_SAMPLES = 400
local REPLAY_HIT_AT = 30 -- seconds into a replay where the hit is, when the replay does not say otherwise
local FIGURE_SIZE = Vector3.new(2, 5, 1)
local FIGURE_TRANSPARENCY = 0.45

-- Modhelm colors (DESIGN.md, dark theme).
local COLORS = {
	surface1 = Color3.fromHex("#111829"),
	surface2 = Color3.fromHex("#172036"),
	surface3 = Color3.fromHex("#1E2843"),
	surface4 = Color3.fromHex("#263252"),
	canvas = Color3.fromHex("#0B1020"),
	hairline = Color3.fromHex("#232C45"),
	hairlineStrong = Color3.fromHex("#2F3A57"),
	ink = Color3.fromHex("#F4F6FB"),
	inkMuted = Color3.fromHex("#C9D3E3"),
	inkSubtle = Color3.fromHex("#95A1B9"),
	accent = Color3.fromHex("#FFB224"),
	onAccent = Color3.fromHex("#0E1424"),
	dangerFill = Color3.fromHex("#D1293D"),
	dangerText = Color3.fromHex("#FF6B7A"),
	white = Color3.new(1, 1, 1),
}

local FONT = Enum.Font.BuilderSans
local FONT_MEDIUM = Enum.Font.BuilderSansMedium
local FONT_BOLD = Enum.Font.BuilderSansBold

local CHECK_LABELS: { [string]: string } = {
	speed = "Speed",
	teleport = "Teleport",
	fly = "Fly",
	noclip = "Noclip",
	remotes = "Remote spam",
	jump = "Infinite jump",
	fling = "Fling",
	honeypot = "Decoy remote",
	interact = "Prompts and clicks",
	reach = "Reach",
}

local CHECK_UNITS: { [string]: string } = {
	speed = "studs/s",
	teleport = "studs",
	fly = "s in the air",
	noclip = "studs through a part",
	remotes = "calls/s",
	jump = "jumps in the air",
	fling = "turns/s",
	interact = "studs away",
	reach = "studs away",
}

local ERRORS: { [string]: string } = {
	forbidden = "You cannot use this panel.",
	slow_down = "Too many requests. Wait a moment and try again.",
	not_found = "This player is not in the server anymore.",
	self = "You cannot kick yourself.",
	staff = "Staff cannot be kicked from the panel.",
	no_character = "One of you has no character right now.",
	reason = "The reason is too long.",
	replay_recent = "This player already has a replay from the last 2 minutes. You find it under Replays.",
	replay_failed = "The replay could not be saved. Try again later.",
	replay_gone = "This replay is not stored anymore.",
	replay_read = "The replay could not be loaded. Try again.",
}

---------------------------------------------------------------------------------------------------------------------
-- Building blocks
---------------------------------------------------------------------------------------------------------------------

local function newLabel(parent: Instance, text: string, size: number, color: Color3, font: Enum.Font): TextLabel
	local label = Instance.new("TextLabel")
	label.BackgroundTransparency = 1
	label.BorderSizePixel = 0
	label.Font = font
	label.TextSize = size
	label.TextColor3 = color
	label.Text = text
	label.TextXAlignment = Enum.TextXAlignment.Left
	label.TextYAlignment = Enum.TextYAlignment.Center
	label.TextTruncate = Enum.TextTruncate.AtEnd
	label.Parent = parent
	return label
end

-- The fill a button goes back to after hover (tabs change theirs).
local baseFill: { [TextButton]: Color3 } = setmetatable({}, { __mode = "k" }) :: any

local function setFill(button: TextButton, color: Color3)
	baseFill[button] = color
	button.BackgroundColor3 = color
end

local function newButton(parent: Instance, text: string, fill: Color3, textColor: Color3): TextButton
	local button = Instance.new("TextButton")
	button.AutoButtonColor = false
	button.BorderSizePixel = 0
	button.Font = FONT_MEDIUM
	button.TextSize = 15
	button.TextColor3 = textColor
	button.Text = text
	setFill(button, fill)
	button.MouseEnter:Connect(function()
		local base = baseFill[button]
		if base then
			button.BackgroundColor3 = base:Lerp(COLORS.white, 0.08)
		end
	end)
	button.MouseLeave:Connect(function()
		local base = baseFill[button]
		if base then
			button.BackgroundColor3 = base
		end
	end)
	button.Parent = parent
	return button
end

local function newPage(parent: Instance): (ScrollingFrame, TextLabel)
	local page = Instance.new("ScrollingFrame")
	page.BackgroundTransparency = 1
	page.BorderSizePixel = 0
	page.Position = UDim2.fromOffset(0, 101)
	page.Size = UDim2.new(1, 0, 1, -125)
	page.CanvasSize = UDim2.new()
	page.AutomaticCanvasSize = Enum.AutomaticSize.Y
	page.ScrollingDirection = Enum.ScrollingDirection.Y
	page.ScrollBarThickness = 4
	page.ScrollBarImageColor3 = COLORS.surface4
	page.VerticalScrollBarInset = Enum.ScrollBarInset.ScrollBar
	page.Parent = parent
	local list = Instance.new("UIListLayout")
	list.Padding = UDim.new(0, 6)
	list.SortOrder = Enum.SortOrder.LayoutOrder
	list.Parent = page
	local empty = newLabel(page, "Loading", 15, COLORS.inkMuted, FONT)
	empty.Size = UDim2.new(1, 0, 0, 40)
	empty.TextWrapped = true
	empty.LayoutOrder = 0
	return page, empty
end

local function newStroke(parent: Instance)
	local stroke = Instance.new("UIStroke")
	stroke.Color = COLORS.hairlineStrong
	stroke.Thickness = 1
	stroke.ApplyStrokeMode = Enum.ApplyStrokeMode.Border
	stroke.Parent = parent
end

local function newPadding(parent: Instance, pad: number): UIPadding
	local padding = Instance.new("UIPadding")
	padding.PaddingTop = UDim.new(0, pad)
	padding.PaddingBottom = UDim.new(0, pad)
	padding.PaddingLeft = UDim.new(0, pad)
	padding.PaddingRight = UDim.new(0, pad)
	padding.Parent = parent
	return padding
end

---------------------------------------------------------------------------------------------------------------------
-- Layout
---------------------------------------------------------------------------------------------------------------------

local gui: ScreenGui
local parent = script.Parent
if parent and parent:IsA("ScreenGui") then
	gui = parent :: ScreenGui
else
	-- Placed somewhere else by hand: make an own ScreenGui.
	gui = Instance.new("ScreenGui")
	gui.Name = "ModhelmGuard"
	gui.ResetOnSpawn = false
	gui.DisplayOrder = 60
	gui.Parent = localPlayer:WaitForChild("PlayerGui")
end
gui.ScreenInsets = Enum.ScreenInsets.DeviceSafeInsets

-- The Modhelm logo drawn from rectangles (32 x 32 cells, made from brand/logo/modhelm-mark.svg), so no uploaded
-- image is needed. It scales with the frame it is put in.
local LOGO_COLORS = { Color3.fromRGB(255, 178, 36), Color3.fromRGB(201, 211, 227) }
local LOGO_RECTS = {
	{15,1,1,1,2}, {14,2,1,1,1}, {15,2,2,8,2}, {17,2,1,1,1}, {13,3,2,1,1}, {17,3,2,1,1}, {11,4,4,1,1},
	{17,4,4,1,1}, {10,5,5,1,1}, {17,5,5,1,1}, {9,6,6,1,1}, {17,6,6,1,1}, {8,7,7,1,1}, {17,7,7,1,1}, {7,8,8,2,1},
	{17,8,8,2,1}, {6,10,9,2,1}, {15,10,1,2,2}, {16,10,10,2,1}, {5,12,22,2,1}, {5,14,2,2,1}, {10,14,12,1,1},
	{25,14,2,2,1}, {15,15,2,1,1}, {5,16,4,1,1}, {22,16,5,1,1}, {6,17,7,1,1}, {19,17,7,1,1}, {7,18,18,6,1},
	{8,24,16,1,1}, {9,25,14,1,1}, {10,26,12,1,1}, {11,27,10,1,1}, {13,28,6,1,1}, {14,29,4,1,1}, {15,30,1,1,1}
}

local function makeLogo(size: number): Frame
	local frame = Instance.new("Frame")
	frame.Name = "ModhelmLogo"
	frame.BackgroundTransparency = 1
	frame.BorderSizePixel = 0
	frame.Size = UDim2.fromOffset(size, size)
	for _, r in LOGO_RECTS do
		local cell = Instance.new("Frame")
		cell.BorderSizePixel = 0
		cell.BackgroundColor3 = LOGO_COLORS[r[5]]
		cell.Position = UDim2.fromScale(r[1] / 32, r[2] / 32)
		-- a hair wider and taller, so no gaps show between neighbouring cells after rounding
		cell.Size = UDim2.fromScale((r[3] + 0.08) / 32, (r[4] + 0.08) / 32)
		cell.Parent = frame
	end
	return frame
end

local toggle = newButton(gui, "Modhelm", COLORS.accent, COLORS.onAccent)
toggle.Name = "Toggle"
toggle.Font = FONT_BOLD
toggle.AnchorPoint = Vector2.new(0, 1)
toggle.Position = UDim2.new(0, 12, 1, -12)
toggle.Size = UDim2.fromOffset(112, 36)
-- the drawn logo left of the word; on the amber button it sits on a dark square so the helmet stays visible
do
	local badge = Instance.new("Frame")
	badge.BorderSizePixel = 0
	badge.BackgroundColor3 = COLORS.surface1
	badge.Position = UDim2.fromOffset(6, 6)
	badge.Size = UDim2.fromOffset(24, 24)
	badge.Parent = toggle
	local logo = makeLogo(20)
	logo.Position = UDim2.fromOffset(2, 2)
	logo.Parent = badge
	local pad = Instance.new("UIPadding")
	pad.PaddingLeft = UDim.new(0, 30)
	pad.Parent = toggle
end

local panel = Instance.new("Frame")
panel.Name = "Panel"
panel.Active = true
panel.Visible = false
panel.AnchorPoint = Vector2.new(0.5, 0.5)
panel.Position = UDim2.fromScale(0.5, 0.5)
panel.Size = UDim2.fromOffset(PANEL_WIDTH, PANEL_HEIGHT)
panel.BackgroundColor3 = COLORS.surface1
panel.BorderSizePixel = 0
panel.Parent = gui
newStroke(panel)

local padding = newPadding(panel, 16)

local headerLogo = makeLogo(22)
headerLogo.Parent = panel
local title = newLabel(panel, "Modhelm Guard", 18, COLORS.ink, FONT_BOLD)
title.Position = UDim2.fromOffset(30, 0)
title.Size = UDim2.new(1, -118, 0, 22)

local modeLabel = newLabel(panel, "Loading", 14, COLORS.inkMuted, FONT)
modeLabel.Position = UDim2.fromOffset(30, 24)
modeLabel.Size = UDim2.new(1, -88, 0, 18)

local closeButton = newButton(panel, "Close", COLORS.surface3, COLORS.ink)
closeButton.AnchorPoint = Vector2.new(1, 0)
closeButton.Position = UDim2.new(1, 0, 0, 2)
closeButton.Size = UDim2.fromOffset(76, 32)

local playersTab = newButton(panel, "Players", COLORS.surface4, COLORS.ink)
local feedTab = newButton(panel, "Feed", COLORS.surface2, COLORS.inkMuted)
local replaysTab = newButton(panel, "Replays", COLORS.surface2, COLORS.inkMuted)
local tabs = { playersTab, feedTab, replaysTab }

local line = Instance.new("Frame")
line.BorderSizePixel = 0
line.BackgroundColor3 = COLORS.hairline
line.Position = UDim2.fromOffset(0, 92)
line.Size = UDim2.new(1, 0, 0, 1)
line.Parent = panel

local playersPage, playersEmpty = newPage(panel)
local feedPage, feedEmpty = newPage(panel)
feedPage.Visible = false
local replaysPage, replaysEmpty = newPage(panel)
replaysPage.Visible = false
replaysEmpty.AutomaticSize = Enum.AutomaticSize.Y

local status = newLabel(panel, "", 13, COLORS.inkMuted, FONT)
status.AnchorPoint = Vector2.new(0, 1)
status.Position = UDim2.fromScale(0, 1)
status.Size = UDim2.new(1, 0, 0, 18)

-- Replay bar at the bottom of the screen (shown while a replay plays).
local bar = Instance.new("Frame")
bar.Name = "Replay"
bar.Active = true
bar.Visible = false
bar.AnchorPoint = Vector2.new(0.5, 1)
bar.BackgroundColor3 = COLORS.surface1
bar.BorderSizePixel = 0
bar.Parent = gui
newStroke(bar)
newPadding(bar, 10)

local barTitle = newLabel(bar, "", 14, COLORS.ink, FONT_MEDIUM)
barTitle.Size = UDim2.new(1, -110, 0, 18)

local barTime = newLabel(bar, "", 14, COLORS.inkMuted, FONT)
barTime.AnchorPoint = Vector2.new(1, 0)
barTime.Position = UDim2.fromScale(1, 0)
barTime.Size = UDim2.fromOffset(104, 18)
barTime.TextXAlignment = Enum.TextXAlignment.Right

-- The track: a tall invisible button to tap or click on, with the thin line inside.
local track = Instance.new("TextButton")
track.AutoButtonColor = false
track.BackgroundTransparency = 1
track.BorderSizePixel = 0
track.Text = ""
track.Position = UDim2.fromOffset(0, 24)
track.Size = UDim2.new(1, 0, 0, 24)
track.Parent = bar

local trackLine = Instance.new("Frame")
trackLine.BackgroundColor3 = COLORS.surface4
trackLine.BorderSizePixel = 0
trackLine.AnchorPoint = Vector2.new(0, 0.5)
trackLine.Position = UDim2.fromScale(0, 0.5)
trackLine.Size = UDim2.new(1, 0, 0, 6)
trackLine.Parent = track

local trackFill = Instance.new("Frame")
trackFill.BackgroundColor3 = COLORS.inkMuted
trackFill.BorderSizePixel = 0
trackFill.Size = UDim2.fromScale(0, 1)
trackFill.Parent = trackLine

-- Where the hit happened.
local trackMark = Instance.new("Frame")
trackMark.BackgroundColor3 = COLORS.accent
trackMark.BorderSizePixel = 0
trackMark.AnchorPoint = Vector2.new(0.5, 0.5)
trackMark.Position = UDim2.fromScale(0, 0.5)
trackMark.Size = UDim2.new(0, 4, 1, -4)
trackMark.ZIndex = 2
trackMark.Parent = track

local playButton = newButton(bar, "Pause", COLORS.accent, COLORS.onAccent)
playButton.Position = UDim2.fromOffset(0, 56)
playButton.Size = UDim2.fromOffset(84, 32)

local barClose = newButton(bar, "Close", COLORS.surface3, COLORS.ink)
barClose.AnchorPoint = Vector2.new(1, 0)
barClose.Position = UDim2.new(1, 0, 0, 56)
barClose.Size = UDim2.fromOffset(76, 32)

local followButton = newButton(bar, "Follow", COLORS.surface3, COLORS.ink)
followButton.AnchorPoint = Vector2.new(1, 0)
followButton.Position = UDim2.new(1, -84, 0, 56)
followButton.Size = UDim2.fromOffset(92, 32)

local compact = false
local lastState: any = nil
local render: (state: any) -> ()

-- Fit the panel and the replay bar into the screen: full size on desktop, smaller on phones (texts and buttons keep
-- their size).
local function fitPanel()
	local area = gui.AbsoluteSize
	local width = math.clamp(area.X - 24, 280, PANEL_WIDTH)
	local height = math.clamp(area.Y - 24, 220, PANEL_HEIGHT)
	panel.Size = UDim2.fromOffset(width, height)
	local pad = if width < 460 then 10 else 16
	padding.PaddingTop = UDim.new(0, pad)
	padding.PaddingBottom = UDim.new(0, pad)
	padding.PaddingLeft = UDim.new(0, pad)
	padding.PaddingRight = UDim.new(0, pad)

	-- Three tabs side by side, narrower on small screens.
	local tabWidth = math.min(TAB_WIDTH, math.floor((width - 2 * pad - 2 * BUTTON_GAP) / 3))
	for index, tab in tabs do
		tab.Position = UDim2.fromOffset((index - 1) * (tabWidth + BUTTON_GAP), 52)
		tab.Size = UDim2.fromOffset(tabWidth, 32)
	end

	-- The bar sits above the "Modhelm" button when it would cover it.
	local barWidth = math.clamp(area.X - 24, 280, BAR_WIDTH)
	bar.Size = UDim2.fromOffset(barWidth, BAR_HEIGHT)
	local coversToggle = (area.X - barWidth) / 2 < 12 + 96 + 12
	bar.Position = UDim2.new(0.5, 0, 1, if coversToggle then -60 else -12)

	local nowCompact = width < COMPACT_WIDTH
	if nowCompact ~= compact then
		compact = nowCompact
		if lastState then
			render(lastState)
		end
	end
end

gui:GetPropertyChangedSignal("AbsoluteSize"):Connect(fitPanel)
fitPanel()

---------------------------------------------------------------------------------------------------------------------
-- Status line
---------------------------------------------------------------------------------------------------------------------

local statusToken = 0

local function setStatus(text: string, isError: boolean)
	statusToken += 1
	local token = statusToken
	status.Text = text
	status.TextColor3 = if isError then COLORS.dangerText else COLORS.inkMuted
	task.delay(STATUS_SECONDS, function()
		if statusToken == token then
			status.Text = ""
		end
	end)
end

local function errorText(result: any): string
	if type(result) == "table" and type(result.error) == "string" and ERRORS[result.error] then
		return ERRORS[result.error]
	end
	return "Something went wrong. Try again."
end

local function call(action: string, payload: any): (boolean, any)
	local ok, result = pcall(function()
		return remote:InvokeServer(action, payload)
	end)
	if ok and type(result) == "table" and result.ok == true then
		return true, result
	end
	return false, if ok then result else nil
end

---------------------------------------------------------------------------------------------------------------------
-- Formatting
---------------------------------------------------------------------------------------------------------------------

local function formatNumber(value: any): string
	if type(value) ~= "number" then
		return "?"
	end
	if value == math.floor(value) then
		return string.format("%d", value)
	end
	return string.format("%.1f", value)
end

local function clock(at: any): string
	if type(at) ~= "number" then
		return ""
	end
	local ok, t = pcall(function()
		return DateTime.fromUnixTimestamp(at):ToLocalTime()
	end)
	if not ok then
		return ""
	end
	return string.format("%02d:%02d:%02d", t.Hour, t.Minute, t.Second)
end

local function uptimeText(seconds: any): string
	if type(seconds) ~= "number" then
		return ""
	end
	local minutes = math.floor(seconds / 60)
	if minutes < 1 then
		return "less than 1 min"
	elseif minutes < 60 then
		return string.format("%d min", minutes)
	end
	return string.format("%d h %d min", math.floor(minutes / 60), minutes % 60)
end

local function modeText(mode: any): string
	if type(mode) ~= "table" then
		return ""
	end
	if mode.licensed == false then
		return "Not connected to Modhelm"
	elseif mode.enabled == false then
		return "Checks are off"
	elseif mode.action == "kick" and type(mode.kickAfter) == "number" then
		return string.format("Kicks after %d hits", mode.kickAfter)
	end
	return "Recording only"
end

local function hitsText(hits: number): string
	if hits <= 0 then
		return "No hits"
	elseif hits == 1 then
		return "1 hit"
	end
	return string.format("%d hits", hits)
end

-- "Speed 3, Fly 1": the two checks with the most hits.
local function topChecks(checks: any): string
	if type(checks) ~= "table" then
		return ""
	end
	local list: { { name: string, count: number } } = {}
	for name, count in checks do
		if type(name) == "string" and type(count) == "number" and count > 0 then
			table.insert(list, { name = name, count = count })
		end
	end
	table.sort(list, function(a, b)
		return a.count > b.count
	end)
	local parts: { string } = {}
	for i = 1, math.min(2, #list) do
		table.insert(parts, (CHECK_LABELS[list[i].name] or list[i].name) .. " " .. tostring(list[i].count))
	end
	return table.concat(parts, ", ")
end

-- "Speed" for an automatic replay, "Saved from the panel" for one saved by staff.
local function replayReason(check: any): string
	if type(check) == "string" then
		return CHECK_LABELS[check] or check
	end
	return "Saved from the panel"
end

---------------------------------------------------------------------------------------------------------------------
-- Players tab
---------------------------------------------------------------------------------------------------------------------

type Row = {
	frame: Frame,
	name: TextLabel,
	sub: TextLabel,
	hits: TextLabel,
	detail: TextLabel,
	saveButton: TextButton,
	gotoButton: TextButton,
	kickButton: TextButton,
	reason: TextBox,
	confirm: TextButton,
	cancel: TextButton,
	userId: number,
	displayName: string,
	handle: string,
	hitsLabel: string,
	isSelf: boolean,
	isStaff: boolean,
	kickOpen: boolean,
	busy: boolean,
	saving: boolean,
}

local rows: { [number]: Row } = {}
local refreshNow: () -> ()

-- Places the texts and buttons of a row. Wide panels: name, hits, buttons in one line. Narrow panels: name with
-- hits under it, the buttons in a second line. The kick reason opens below either.
local function layoutRow(row: Row)
	row.gotoButton.Visible = not row.isSelf
	row.kickButton.Visible = not row.isSelf and not row.isStaff
	if not row.kickButton.Visible then
		row.kickOpen = false
	end

	local buttons = { row.saveButton, row.gotoButton, row.kickButton }
	local total = 0
	for _, button in buttons do
		if button.Visible then
			total += button.Size.X.Offset + (if total > 0 then BUTTON_GAP else 0)
		end
	end
	local x = if compact then 10 else -(10 + total)
	local y = if compact then 54 else 12
	for _, button in buttons do
		if button.Visible then
			button.Position = UDim2.new(if compact then 0 else 1, x, 0, y)
			x += button.Size.X.Offset + BUTTON_GAP
		end
	end

	if compact then
		row.sub.Text = row.handle .. " | " .. row.hitsLabel
		row.name.Size = UDim2.new(1, -20, 0, 20)
		row.sub.Size = UDim2.new(1, -20, 0, 18)
		row.hits.Visible = false
		row.detail.Visible = false
	else
		-- Space right of the texts: the buttons, the right edge and a gap.
		local reserved = total + 10 + BUTTON_GAP
		row.sub.Text = row.handle
		row.name.Size = UDim2.new(0.55, -0.55 * reserved - 10, 0, 20)
		row.sub.Size = UDim2.new(0.55, -0.55 * reserved - 10, 0, 18)
		row.hits.Position = UDim2.new(0.55, -0.55 * reserved + 8, 0, 9)
		row.hits.Size = UDim2.new(0.45, -0.45 * reserved - 8, 0, 20)
		row.detail.Position = UDim2.new(0.55, -0.55 * reserved + 8, 0, 29)
		row.detail.Size = UDim2.new(0.45, -0.45 * reserved - 8, 0, 18)
		row.hits.Visible = true
		row.detail.Visible = true
	end

	local base = if compact then ROW_HEIGHT_COMPACT else ROW_HEIGHT
	local open = row.kickOpen
	row.reason.Visible = open
	row.confirm.Visible = open
	row.cancel.Visible = open
	row.reason.Position = UDim2.fromOffset(10, base)
	row.cancel.Position = UDim2.new(1, -146, 0, base)
	row.confirm.Position = UDim2.new(1, -74, 0, base)
	row.frame.Size = UDim2.new(1, 0, 0, if open then base + REASON_HEIGHT else base)
	if not open then
		row.reason.Text = ""
	end
end

local function setKickOpen(row: Row, open: boolean)
	row.kickOpen = open
	layoutRow(row)
end

local function newRow(userId: number): Row
	local frame = Instance.new("Frame")
	frame.BackgroundColor3 = COLORS.surface2
	frame.BorderSizePixel = 0
	frame.Size = UDim2.new(1, 0, 0, ROW_HEIGHT)
	frame.Parent = playersPage

	local name = newLabel(frame, "", 15, COLORS.ink, FONT_MEDIUM)
	name.Position = UDim2.fromOffset(10, 9)
	local sub = newLabel(frame, "", 13, COLORS.inkSubtle, FONT)
	sub.Position = UDim2.fromOffset(10, 29)
	local hits = newLabel(frame, "", 14, COLORS.ink, FONT_MEDIUM)
	local detail = newLabel(frame, "", 13, COLORS.inkMuted, FONT)

	local saveButton = newButton(frame, "Save replay", COLORS.surface3, COLORS.ink)
	saveButton.Size = UDim2.fromOffset(96, 32)
	local gotoButton = newButton(frame, "Go to", COLORS.surface3, COLORS.ink)
	gotoButton.Size = UDim2.fromOffset(64, 32)
	local kickButton = newButton(frame, "Kick", COLORS.dangerFill, COLORS.white)
	kickButton.Size = UDim2.fromOffset(64, 32)

	local reason = Instance.new("TextBox")
	reason.BackgroundColor3 = COLORS.canvas
	reason.BorderSizePixel = 0
	reason.ClearTextOnFocus = false
	reason.Font = FONT
	reason.TextSize = 14
	reason.TextColor3 = COLORS.ink
	reason.PlaceholderText = "Reason shown to the player (optional)"
	reason.PlaceholderColor3 = COLORS.inkSubtle
	reason.TextXAlignment = Enum.TextXAlignment.Left
	reason.TextTruncate = Enum.TextTruncate.AtEnd
	reason.Text = ""
	reason.Size = UDim2.new(1, -166, 0, 32)
	reason.Parent = frame
	local reasonPadding = Instance.new("UIPadding")
	reasonPadding.PaddingLeft = UDim.new(0, 8)
	reasonPadding.PaddingRight = UDim.new(0, 8)
	reasonPadding.Parent = reason

	local cancel = newButton(frame, "Cancel", COLORS.surface3, COLORS.ink)
	cancel.Size = UDim2.fromOffset(64, 32)
	local confirm = newButton(frame, "Kick", COLORS.dangerFill, COLORS.white)
	confirm.Size = UDim2.fromOffset(64, 32)

	local row: Row = {
		frame = frame,
		name = name,
		sub = sub,
		hits = hits,
		detail = detail,
		saveButton = saveButton,
		gotoButton = gotoButton,
		kickButton = kickButton,
		reason = reason,
		confirm = confirm,
		cancel = cancel,
		userId = userId,
		displayName = "",
		handle = "",
		hitsLabel = "",
		isSelf = false,
		isStaff = false,
		kickOpen = false,
		busy = false,
		saving = false,
	}
	layoutRow(row)

	-- Keep the reason short; the server cuts it at 200 characters too.
	reason:GetPropertyChangedSignal("Text"):Connect(function()
		local text = reason.Text
		local length = utf8.len(text)
		if length and length > 200 then
			local cut = utf8.offset(text, 201)
			if cut then
				reason.Text = string.sub(text, 1, cut - 1)
			end
		end
	end)

	kickButton.Activated:Connect(function()
		setKickOpen(row, not row.kickOpen)
		if row.kickOpen and not UserInputService.TouchEnabled then
			reason:CaptureFocus()
		end
	end)
	cancel.Activated:Connect(function()
		setKickOpen(row, false)
	end)
	confirm.Activated:Connect(function()
		if row.busy then
			return
		end
		row.busy = true
		confirm.Text = "Kicking"
		local ok, result = call("kick", { userId = row.userId, reason = reason.Text })
		row.busy = false
		confirm.Text = "Kick"
		if ok then
			setKickOpen(row, false)
			setStatus(row.displayName .. " was kicked from this server.", false)
			refreshNow()
		else
			setStatus(errorText(result), true)
		end
	end)
	gotoButton.Activated:Connect(function()
		if row.busy then
			return
		end
		row.busy = true
		local ok, result = call("goto", { userId = row.userId })
		row.busy = false
		if ok then
			setStatus("You are now next to " .. row.displayName .. ".", false)
		else
			setStatus(errorText(result), true)
		end
	end)
	-- The server waits 5 seconds after the press, so the replay also holds what happens right after it.
	saveButton.Activated:Connect(function()
		if row.saving then
			return
		end
		row.saving = true
		saveButton.Text = "Saving"
		setStatus("Saving a replay of " .. row.displayName .. ". This takes about 5 seconds.", false)
		local ok, result = call("replay_save", { userId = row.userId })
		row.saving = false
		saveButton.Text = "Save replay"
		if ok then
			setStatus("Replay of " .. row.displayName .. " saved. You find it under Replays.", false)
			refreshNow()
		else
			setStatus(errorText(result), true)
		end
	end)

	return row
end

local function renderPlayers(list: any)
	local entries: { any } = {}
	if type(list) == "table" then
		for _, info in ipairs(list) do
			if type(info) == "table" and type(info.userId) == "number" and type(info.name) == "string" then
				table.insert(entries, info)
			end
		end
	end
	-- Most hits first, then the latest hit, then by name.
	table.sort(entries, function(a, b)
		local ha = if type(a.hits) == "number" then a.hits else 0
		local hb = if type(b.hits) == "number" then b.hits else 0
		if ha ~= hb then
			return ha > hb
		end
		local la = if type(a.lastAt) == "number" then a.lastAt else 0
		local lb = if type(b.lastAt) == "number" then b.lastAt else 0
		if la ~= lb then
			return la > lb
		end
		return string.lower(a.name) < string.lower(b.name)
	end)

	local seen: { [number]: boolean } = {}
	for index, info in entries do
		local userId: number = info.userId
		seen[userId] = true
		local row = rows[userId]
		if not row then
			row = newRow(userId)
			rows[userId] = row
		end
		local displayName = if type(info.displayName) == "string" and info.displayName ~= "" then info.displayName else info.name
		local hits = if type(info.hits) == "number" then info.hits else 0
		local isSelf = userId == localPlayer.UserId
		local isStaff = info.staff == true
		row.displayName = displayName
		row.frame.LayoutOrder = index

		local handle = "@" .. info.name
		if isSelf then
			handle ..= " (you)"
		elseif isStaff then
			handle ..= " (staff)"
		end
		row.handle = handle
		row.hitsLabel = hitsText(hits)
		row.isSelf = isSelf
		row.isStaff = isStaff
		row.name.Text = displayName
		row.hits.Text = row.hitsLabel
		row.detail.Text = topChecks(info.checks)
		layoutRow(row)
	end
	for userId, row in rows do
		if not seen[userId] then
			row.frame:Destroy()
			rows[userId] = nil
		end
	end
	playersEmpty.Text = "No players in this server."
	playersEmpty.Visible = #entries == 0
end

---------------------------------------------------------------------------------------------------------------------
-- Feed tab
---------------------------------------------------------------------------------------------------------------------

type FeedRow = { frame: Frame, who: TextLabel, time: TextLabel, what: TextLabel }

local feedRows: { FeedRow } = {}

local function newFeedRow(): FeedRow
	local frame = Instance.new("Frame")
	frame.BackgroundColor3 = COLORS.surface2
	frame.BorderSizePixel = 0
	frame.Size = UDim2.new(1, 0, 0, FEED_ROW_HEIGHT)
	frame.Parent = feedPage
	local who = newLabel(frame, "", 14, COLORS.ink, FONT_MEDIUM)
	who.Position = UDim2.fromOffset(10, 6)
	who.Size = UDim2.new(1, -100, 0, 18)
	local time = newLabel(frame, "", 13, COLORS.inkSubtle, FONT)
	time.AnchorPoint = Vector2.new(1, 0)
	time.Position = UDim2.new(1, -10, 0, 6)
	time.Size = UDim2.fromOffset(80, 18)
	time.TextXAlignment = Enum.TextXAlignment.Right
	local what = newLabel(frame, "", 13, COLORS.inkMuted, FONT)
	what.Position = UDim2.fromOffset(10, 25)
	what.Size = UDim2.new(1, -20, 0, 18)
	return { frame = frame, who = who, time = time, what = what }
end

local function renderFeed(list: any, mode: any)
	local entries: { any } = {}
	if type(list) == "table" then
		for _, entry in ipairs(list) do
			if type(entry) == "table" and type(entry.check) == "string" and type(entry.name) == "string" then
				table.insert(entries, entry)
			end
		end
	end
	for index, entry in entries do
		local row = feedRows[index]
		if not row then
			row = newFeedRow()
			feedRows[index] = row
		end
		row.frame.LayoutOrder = index
		row.frame.Visible = true
		local displayName = if type(entry.displayName) == "string" and entry.displayName ~= "" then entry.displayName else entry.name
		row.who.Text = displayName .. " @" .. entry.name
		row.time.Text = clock(entry.at)
		local unit = CHECK_UNITS[entry.check] or ""
		local label = CHECK_LABELS[entry.check] or entry.check
		-- Checks without a number (decoy remote, prompt not held) send a limit of 0: show only their name.
		local text = if type(entry.l) == "number" and entry.l > 0
			then string.format("%s %s %s, limit %s", label, formatNumber(entry.x), unit, formatNumber(entry.l))
			else label
		if type(entry.n) == "number" and entry.n > 1 then
			text ..= string.format(" | %d times", entry.n)
		end
		row.what.Text = text
	end
	for index = #entries + 1, #feedRows do
		feedRows[index].frame.Visible = false
	end
	feedEmpty.Text = if type(mode) == "table" and mode.licensed == false
		then "Modhelm Guard is not connected yet. Set it up for this game in your Modhelm dashboard."
		elseif type(mode) == "table" and mode.enabled == false then "Checks are off in this server."
		else "No hits in this server yet."
	feedEmpty.Visible = #entries == 0
end

---------------------------------------------------------------------------------------------------------------------
-- Replays tab
---------------------------------------------------------------------------------------------------------------------

type ReplayRow = { frame: Frame, who: TextLabel, what: TextLabel, watch: TextButton, key: string, busy: boolean }

local replayRows: { ReplayRow } = {}
local watchReplay: (replay: any) -> ()

local function newReplayRow(): ReplayRow
	local frame = Instance.new("Frame")
	frame.BackgroundColor3 = COLORS.surface2
	frame.BorderSizePixel = 0
	frame.Size = UDim2.new(1, 0, 0, ROW_HEIGHT)
	frame.Parent = replaysPage
	local who = newLabel(frame, "", 15, COLORS.ink, FONT_MEDIUM)
	who.Position = UDim2.fromOffset(10, 9)
	who.Size = UDim2.new(1, -104, 0, 20)
	local what = newLabel(frame, "", 13, COLORS.inkMuted, FONT)
	what.Position = UDim2.fromOffset(10, 29)
	what.Size = UDim2.new(1, -104, 0, 18)
	local watch = newButton(frame, "Watch", COLORS.surface3, COLORS.ink)
	watch.Position = UDim2.new(1, -84, 0, 12)
	watch.Size = UDim2.fromOffset(74, 32)

	local row: ReplayRow = { frame = frame, who = who, what = what, watch = watch, key = "", busy = false }
	watch.Activated:Connect(function()
		if row.busy or row.key == "" then
			return
		end
		row.busy = true
		watch.Text = "Loading"
		local ok, result = call("replay", { key = row.key })
		row.busy = false
		watch.Text = "Watch"
		if ok then
			watchReplay(result.replay)
		else
			setStatus(errorText(result), true)
		end
	end)
	return row
end

local function renderReplays(list: any)
	local entries: { any } = {}
	if type(list) == "table" then
		for _, entry in ipairs(list) do
			if type(entry) == "table" and type(entry.key) == "string" and type(entry.name) == "string" then
				table.insert(entries, entry)
			end
		end
	end
	for index, entry in entries do
		local row = replayRows[index]
		if not row then
			row = newReplayRow()
			replayRows[index] = row
		end
		row.key = entry.key
		row.frame.LayoutOrder = index
		row.frame.Visible = true
		local displayName = if type(entry.displayName) == "string" and entry.displayName ~= "" then entry.displayName else entry.name
		row.who.Text = displayName .. " @" .. entry.name
		local when = clock(entry.at)
		row.what.Text = replayReason(entry.check) .. (if when ~= "" then " | " .. when else "")
	end
	for index = #entries + 1, #replayRows do
		replayRows[index].frame.Visible = false
		replayRows[index].key = ""
	end
	replaysEmpty.Text = "No replays in this server yet. One is saved 5 seconds after the first hit of a player, or with Save replay on the Players tab."
	replaysEmpty.Visible = #entries == 0
end

---------------------------------------------------------------------------------------------------------------------
-- Data
---------------------------------------------------------------------------------------------------------------------

render = function(state: any)
	lastState = state
	local text = modeText(state.mode)
	local up = uptimeText(state.uptime)
	if up ~= "" then
		text ..= " | Server up " .. up
	end
	modeLabel.Text = text
	renderPlayers(state.players)
	renderFeed(state.feed, state.mode)
	renderReplays(state.replays)
end

local requestCounter = 0
local appliedRequest = 0

local function refresh()
	requestCounter += 1
	local id = requestCounter
	local ok, result = call("state", nil)
	if id < appliedRequest then
		return -- a newer answer is already on screen
	end
	appliedRequest = id
	if ok then
		render(result)
	else
		setStatus(if result then errorText(result) else "Could not load the data. Trying again.", true)
	end
end

refreshNow = function()
	task.spawn(refresh)
end

---------------------------------------------------------------------------------------------------------------------
-- Replay player
---------------------------------------------------------------------------------------------------------------------

type Figure = {
	part: Part,
	billboard: BillboardGui,
	pos: { Vector3 },
	yaw: { number },
	has: { boolean },
	shown: boolean,
}

local isOpen = false
local watching = false
local figures: { Figure } = {}
local figureFolder: Folder? = nil
local focusPart: Part? = nil
local stepConnection: RBXScriptConnection? = nil
local subjectConnection: RBXScriptConnection? = nil
local sampleCount = 0
local sampleHz = 4
local duration = 0
local playTime = 0
local playing = false
local shownTenths = -1
local following = false
local subjectBefore: Instance? = nil

local function finite(value: any): boolean
	return type(value) == "number" and value == value and math.abs(value) < 1e9
end

-- "x,y,z,yaw;x,y,z,yaw;;..." into arrays; an empty or broken sample means the player was not there.
local function parseSamples(text: string, count: number): ({ Vector3 }, { number }, { boolean })
	local pos = table.create(count, Vector3.zero)
	local yaw = table.create(count, 0)
	local has = table.create(count, false)
	local parts = string.split(text, ";")
	for i = 1, math.min(count, #parts) do
		local part = parts[i]
		if part ~= "" then
			local sx, sy, sz, sw = string.match(part, "^([^,]+),([^,]+),([^,]+),([^,]+)$")
			local x, y, z, w = tonumber(sx), tonumber(sy), tonumber(sz), tonumber(sw)
			if finite(x) and finite(y) and finite(z) and finite(w) then
				pos[i] = Vector3.new(x :: number, y :: number, z :: number)
				yaw[i] = w :: number
				has[i] = true
			end
		end
	end
	return pos, yaw, has
end

local function newFigure(folder: Folder, label: string, isFocus: boolean): (Part, BillboardGui)
	local part = Instance.new("Part")
	part.Name = label
	part.Size = FIGURE_SIZE
	part.Anchored = true
	part.CanCollide = false
	part.CanQuery = false
	part.CanTouch = false
	part.CastShadow = false
	part.Locked = true
	part.Material = Enum.Material.SmoothPlastic
	part.TopSurface = Enum.SurfaceType.Smooth
	part.BottomSurface = Enum.SurfaceType.Smooth
	part.Color = if isFocus then COLORS.accent else COLORS.inkSubtle
	part.Transparency = 1

	local billboard = Instance.new("BillboardGui")
	billboard.Adornee = part
	billboard.AlwaysOnTop = true
	billboard.LightInfluence = 0
	billboard.Size = UDim2.fromOffset(200, 24)
	billboard.StudsOffset = Vector3.new(0, FIGURE_SIZE.Y / 2 + 1.2, 0)
	billboard.Enabled = false
	billboard.Parent = part

	local text = newLabel(billboard, label, 14, if isFocus then COLORS.onAccent else COLORS.ink, FONT_MEDIUM)
	text.BackgroundTransparency = 0
	text.BackgroundColor3 = if isFocus then COLORS.accent else COLORS.surface1
	text.AnchorPoint = Vector2.new(0.5, 0)
	text.Position = UDim2.fromScale(0.5, 0)
	text.Size = UDim2.fromOffset(0, 24)
	text.AutomaticSize = Enum.AutomaticSize.X
	text.TextXAlignment = Enum.TextXAlignment.Center
	text.TextTruncate = Enum.TextTruncate.None
	local textPadding = Instance.new("UIPadding")
	textPadding.PaddingLeft = UDim.new(0, 6)
	textPadding.PaddingRight = UDim.new(0, 6)
	textPadding.Parent = text

	part.Parent = folder
	return part, billboard
end

-- Moves every figure to the current time, blending between two samples (shortest turn for the facing).
local function placeFigures()
	local f = math.clamp(playTime * sampleHz, 0, math.max(sampleCount - 1, 0))
	local i = math.floor(f)
	local w = f - i
	local a = i + 1
	local b = math.min(a + 1, sampleCount)
	for _, figure in figures do
		local hasA, hasB = figure.has[a] == true, figure.has[b] == true
		local pos: Vector3? = nil
		local yaw = 0
		if hasA and hasB then
			pos = figure.pos[a]:Lerp(figure.pos[b], w)
			local turn = (figure.yaw[b] - figure.yaw[a] + 180) % 360 - 180
			yaw = figure.yaw[a] + turn * w
		elseif hasA and w < 0.5 then
			pos = figure.pos[a]
			yaw = figure.yaw[a]
		elseif hasB and w >= 0.5 then
			pos = figure.pos[b]
			yaw = figure.yaw[b]
		end
		if pos then
			figure.part.CFrame = CFrame.new(pos) * CFrame.Angles(0, math.rad(yaw), 0)
			if not figure.shown then
				figure.shown = true
				figure.part.Transparency = FIGURE_TRANSPARENCY
				figure.billboard.Enabled = true
			end
		elseif figure.shown then
			figure.shown = false
			figure.part.Transparency = 1
			figure.billboard.Enabled = false
		end
	end
end

local function updateBar()
	local tenths = math.floor(playTime * 10 + 0.5)
	if tenths ~= shownTenths then
		shownTenths = tenths
		barTime.Text = string.format("%.1f / %.1f s", tenths / 10, duration)
		trackFill.Size = UDim2.fromScale(if duration > 0 then math.clamp(playTime / duration, 0, 1) else 0, 1)
	end
end

local function setPlaying(on: boolean)
	if on and playTime >= duration then
		playTime = 0 -- play again from the start
	end
	playing = on
	playButton.Text = if on then "Pause" else "Play"
end

local function setFollow(on: boolean)
	local camera = Workspace.CurrentCamera
	if subjectConnection then
		subjectConnection:Disconnect()
		subjectConnection = nil
	end
	if on and camera and focusPart then
		local cam: Camera = camera
		subjectBefore = cam.CameraSubject
		cam.CameraSubject = focusPart
		following = true
		-- The game or a respawn may take the camera back; the button then shows that.
		subjectConnection = cam:GetPropertyChangedSignal("CameraSubject"):Connect(function()
			if cam.CameraSubject ~= focusPart then
				setFollow(false)
			end
		end)
	else
		if following and camera and focusPart and camera.CameraSubject == focusPart then
			local subject = subjectBefore
			if not subject or not subject:IsDescendantOf(game) then
				local character = localPlayer.Character
				subject = if character then character:FindFirstChildOfClass("Humanoid") else nil
			end
			if subject then
				camera.CameraSubject = subject
			end
		end
		following = false
		subjectBefore = nil
	end
	followButton.Text = if following then "Following" else "Follow"
	setFill(followButton, if following then COLORS.surface4 else COLORS.surface3)
end

-- Ends the replay and removes everything it made. Safe to call any time, also twice.
local function stopReplay()
	local wasWatching = watching
	watching = false
	setFollow(false)
	if stepConnection then
		stepConnection:Disconnect()
		stepConnection = nil
	end
	local folder = figureFolder
	figureFolder = nil
	if folder then
		folder:Destroy()
	end
	table.clear(figures)
	focusPart = nil
	playing = false
	bar.Visible = false
	panel.Visible = isOpen
	if wasWatching and isOpen then
		refreshNow()
	end
end

watchReplay = function(replay: any)
	stopReplay()
	if not isOpen then
		return -- the panel was closed while the replay loaded
	end
	if type(replay) ~= "table" or type(replay.players) ~= "table" then
		setStatus(ERRORS.replay_gone, true)
		return
	end
	local camera = Workspace.CurrentCamera
	if not camera then
		setStatus("Something went wrong. Try again.", true)
		return
	end

	sampleHz = if type(replay.hz) == "number" and replay.hz >= 1 and replay.hz <= 20 then replay.hz else 4
	local entries: { { label: string, text: string, isFocus: boolean } } = {}
	local count = 0
	for _, info in ipairs(replay.players) do
		if #entries >= REPLAY_MAX_PLAYERS then
			break
		end
		if type(info) == "table" and type(info.s) == "string" and #info.s <= 200000 then
			local name = if type(info.n) == "string" then info.n else tostring(info.u)
			local label = if type(info.d) == "string" and info.d ~= "" then info.d else name
			local isFocus = info.f == true or (info.u ~= nil and info.u == replay.focus)
			table.insert(entries, { label = label, text = info.s, isFocus = isFocus })
			-- Samples are separated by ";", so a player with n samples has n - 1 of them.
			local _, separators = string.gsub(info.s, ";", "")
			count = math.max(count, separators + 1)
		end
	end
	count = math.min(count, REPLAY_MAX_SAMPLES)
	if #entries == 0 or count < 2 then
		setStatus("This replay has no movement to show.", true)
		return
	end
	sampleCount = count
	duration = count / sampleHz

	local folder = Instance.new("Folder")
	folder.Name = "ModhelmReplay"
	local focusLabel = ""
	for _, entry in entries do
		local pos, yaw, has = parseSamples(entry.text, count)
		local part, billboard = newFigure(folder, entry.label, entry.isFocus)
		table.insert(figures, { part = part, billboard = billboard, pos = pos, yaw = yaw, has = has, shown = false })
		if entry.isFocus and not focusPart then
			focusPart = part
			focusLabel = entry.label
		end
	end
	-- Inside the camera: only this player sees the figures, and nothing replicates.
	folder.Parent = camera
	figureFolder = folder

	-- The hit is REPLAY_HIT_AT seconds in, unless at and start say otherwise.
	local mark = REPLAY_HIT_AT
	if finite(replay.at) and finite(replay.start) then
		mark = replay.at - replay.start
	end
	mark = math.clamp(mark, 0, duration)
	trackMark.Position = UDim2.fromScale(mark / duration, 0.5)

	local reason = replayReason(replay.check)
	barTitle.Text = if focusLabel ~= "" then "Replay of " .. focusLabel .. " | " .. reason else "Replay | " .. reason
	playTime = 0
	shownTenths = -1
	watching = true
	panel.Visible = false
	bar.Visible = true
	setFollow(false)
	setPlaying(true)
	placeFigures()
	updateBar()

	stepConnection = RunService.RenderStepped:Connect(function(dt: number)
		if playing then
			playTime += dt
			if playTime >= duration then
				playTime = duration
				setPlaying(false)
			end
		end
		placeFigures()
		updateBar()
	end)
end

playButton.Activated:Connect(function()
	setPlaying(not playing)
end)
followButton.Activated:Connect(function()
	setFollow(not following)
end)
barClose.Activated:Connect(stopReplay)

-- Tap or click on the track to jump there.
track.InputBegan:Connect(function(input: InputObject)
	if input.UserInputType ~= Enum.UserInputType.MouseButton1 and input.UserInputType ~= Enum.UserInputType.Touch then
		return
	end
	local width = track.AbsoluteSize.X
	if not watching or width <= 0 then
		return
	end
	local share = math.clamp((input.Position.X - track.AbsolutePosition.X) / width, 0, 1)
	playTime = share * duration
end)

---------------------------------------------------------------------------------------------------------------------
-- Open, close, tabs
---------------------------------------------------------------------------------------------------------------------

local generation = 0

local function refreshLoop(gen: number)
	while isOpen and gen == generation do
		if not watching then
			refresh()
		end
		task.wait(REFRESH_SECONDS)
	end
end

local function setOpen(open: boolean)
	if open == isOpen then
		return
	end
	isOpen = open
	if not open then
		stopReplay()
	end
	panel.Visible = open and not watching
	if open then
		generation += 1
		task.spawn(refreshLoop, generation)
	end
end

-- While a replay plays, the button and F2 end it and bring the panel back.
local function onToggle()
	if watching then
		stopReplay()
	else
		setOpen(not isOpen)
	end
end

local function showTab(name: string)
	local pages: { [string]: ScrollingFrame } = { players = playersPage, feed = feedPage, replays = replaysPage }
	local buttons: { [string]: TextButton } = { players = playersTab, feed = feedTab, replays = replaysTab }
	for key, page in pages do
		local active = key == name
		page.Visible = active
		local button = buttons[key]
		setFill(button, if active then COLORS.surface4 else COLORS.surface2)
		button.TextColor3 = if active then COLORS.ink else COLORS.inkMuted
	end
end

toggle.Activated:Connect(onToggle)
closeButton.Activated:Connect(function()
	setOpen(false)
end)
playersTab.Activated:Connect(function()
	showTab("players")
end)
feedTab.Activated:Connect(function()
	showTab("feed")
end)
replaysTab.Activated:Connect(function()
	showTab("replays")
end)

UserInputService.InputBegan:Connect(function(input: InputObject, processed: boolean)
	if processed then
		return -- typing in a text box or chat
	end
	if input.KeyCode == Enum.KeyCode.F2 then
		onToggle()
	end
end)

-- The figures live in the camera, not in this panel, so they are removed when the panel goes away (the server takes
-- it from players who are no longer staff).
script.Destroying:Connect(stopReplay)
gui.Destroying:Connect(stopReplay)
gui.AncestryChanged:Connect(function()
	if not gui:IsDescendantOf(game) then
		stopReplay()
	end
end)

showTab("players")
]]></ProtectedString>
			</Properties>
		</Item>
	</Item>
</roblox>
