<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">ModhelmReports</string>
			<bool name="Disabled">false</bool>
			<ProtectedString name="Source"><![CDATA[--!strict
--[[
	ModhelmReports.server.luau

	Modhelm Reports (https://modhelm.com): players report other players right in the game. A small "Report" button
	opens a window where the player picks someone of this server, a reason and an optional text. This script checks
	every report on the server and writes it into the MemoryStore queue "ModhelmReports". Modhelm reads that queue
	through Open Cloud and opens a case in your Discord. The script makes no web requests, so "Allow HTTP Requests"
	can stay off.

	Setup
	  - Put this Script into ServerScriptService with the LocalScript "ModhelmReportsClient" inside it. The Modhelm
	    Reports plugin for Roblox Studio and the model file from modhelm.com/downloads already do that.
	  - The game's Open Cloud API key in Modhelm needs: memory-store.queue: dequeue, discard
	  - In the Modhelm dashboard, open Games and turn on in-game reports for this game.
	  - Publish the place. Do this for every place of the experience players can report in.

	Report categories: Modhelm may write the server's categories into the data store "Modhelm", key "reports"
	({ v = 1, categories = { "exploiting", "harassment", ... } }). Without it the built-in list below is used, which
	matches the default categories of a new Modhelm server. Unknown categories end up as "other" in Modhelm.

	Your own report UI: set GIVE_UI to false and report from your server code instead.
	    local reports = game:GetService("ServerStorage"):WaitForChild("ModhelmReports")
	    local sent = reports:WaitForChild("Report"):Invoke(reporterPlayer, targetUserId, "exploiting", "optional text")
	It answers true when the report was queued and false when a check or a limit stopped it.

	Checks and limits: the target must be in this server or have left it in the last 10 minutes, nobody can report
	themselves, the text has at most 500 characters. One report per player a minute and 5 an hour, the same player
	once an hour per reporter, 30 reports a minute per server. Modhelm has its own limits on top.

	Data in a queue item: the user ids of reporter and target, the category and the text. The text is not shown to
	other players, it only goes to your moderators.
]]

local DataStoreService = game:GetService("DataStoreService")
local MemoryStoreService = game:GetService("MemoryStoreService")
local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local ServerStorage = game:GetService("ServerStorage")

-- false: no Report button for players, only ServerStorage.ModhelmReports.Report for your own UI.
local GIVE_UI = true

-- Names Modhelm expects. Do not change them.
local QUEUE_NAME = "ModhelmReports"
local DATA_STORE = "Modhelm"
local CATEGORIES_KEY = "reports"
local REMOTE_NAME = "ModhelmReportsRemote"
local API_FOLDER_NAME = "ModhelmReports"
local CLIENT_SCRIPT_NAME = "ModhelmReportsClient"
local GUI_NAME = "ModhelmReports"

local QUEUE_TTL = 604800 -- seconds a report waits in the queue for Modhelm (one week)
local MAX_TEXT = 500 -- characters
local RECENT_SECONDS = 600 -- players who left this long ago can still be reported
local RECENT_CAP = 50
local COOLDOWN = 60 -- seconds between two reports of one player
local HOUR = 3600
local MAX_PER_HOUR = 5
local SAME_TARGET_WINDOW = 3600 -- one report of the same player per reporter in this time
local SERVER_PER_MINUTE = 30
local CALL_WINDOW = 10 -- remote calls: at most CALLS_PER_WINDOW per CALL_WINDOW seconds
local CALLS_PER_WINDOW = 10
local CATEGORIES_REFRESH = 300 -- seconds between category reads
local MAX_CATEGORIES = 25
local MAX_CATEGORY_LENGTH = 50

type Category = { id: string, label: string }

-- Default categories of a new Modhelm server, in this order. Child safety reports go through the Modhelm portal.
local DEFAULT_CATEGORIES: { string } = { "exploiting", "harassment", "scamming", "inappropriate", "other" }

local DEFAULT_LABELS: { [string]: string } = {
	exploiting = "Cheating or exploiting",
	harassment = "Harassment or bullying",
	scamming = "Scamming",
	inappropriate = "Inappropriate behavior",
	other = "Something else",
}

local queue = MemoryStoreService:GetQueue(QUEUE_NAME)

---------------------------------------------------------------------------------------------------------------------
-- Helpers
---------------------------------------------------------------------------------------------------------------------

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

local function warnEvery(key: string, seconds: number, message: string)
	local now = os.clock()
	if lastWarn[key] and now - lastWarn[key] < seconds then
		return
	end
	lastWarn[key] = now
	warn("[Modhelm] " .. message)
end

-- Trimmed text without control characters, or nil when it is longer than max characters or not valid UTF-8.
local function cleanText(value: any, max: number): string?
	if value == nil then
		return ""
	end
	if type(value) ~= "string" then
		return nil
	end
	local cleaned = string.gsub(value, "[%c]", function(c: string)
		return if c == "\n" then "\n" else " "
	end)
	cleaned = string.match(cleaned, "^%s*(.-)%s*$") or ""
	local length = utf8.len(cleaned)
	if length == nil or length > max then
		return nil
	end
	return cleaned
end

local function defaultCategories(): { Category }
	local list: { Category } = {}
	for _, id in DEFAULT_CATEGORIES do
		table.insert(list, { id = id, label = DEFAULT_LABELS[id] })
	end
	return list
end

-- The stored categories, or nil when the value is not a usable list. "other" is always there, at the end.
local function parseCategories(raw: any): { Category }?
	local entries = if type(raw) == "table" and type(raw.categories) == "table" then raw.categories else raw
	if type(entries) ~= "table" then
		return nil
	end
	local list: { Category } = {}
	local seen: { [string]: boolean } = {}
	for _, entry in ipairs(entries) do
		if #list >= MAX_CATEGORIES then
			break
		end
		local name = if type(entry) == "table" then entry.id else entry
		local label = if type(entry) == "table" then entry.label else nil
		local cleaned = cleanText(name, MAX_CATEGORY_LENGTH)
		if cleaned and cleaned ~= "" and not string.find(cleaned, "\n") then
			local id = string.lower(cleaned)
			if not seen[id] and id ~= "other" then
				seen[id] = true
				local shown = cleanText(label, MAX_CATEGORY_LENGTH)
				table.insert(list, { id = id, label = if shown and shown ~= "" then shown else DEFAULT_LABELS[id] or cleaned })
			end
		end
	end
	if #list == 0 then
		return nil
	end
	table.insert(list, { id = "other", label = DEFAULT_LABELS.other })
	return list
end

local categories: { Category } = defaultCategories()

local function findCategory(id: any): string?
	if type(id) ~= "string" then
		return nil
	end
	local wanted = string.lower(id)
	for _, c in categories do
		if c.id == wanted then
			return c.id
		end
	end
	return nil
end

local function loadCategories()
	local ok, result = pcall(function()
		return DataStoreService:GetDataStore(DATA_STORE):GetAsync(CATEGORIES_KEY)
	end)
	if not ok then
		warnEvery("categories", 1800, "could not read the report categories, using the built-in list: " .. tostring(result))
		return
	end
	categories = parseCategories(result) or defaultCategories()
end

---------------------------------------------------------------------------------------------------------------------
-- Players who left recently
---------------------------------------------------------------------------------------------------------------------

type Recent = { userId: number, name: string, displayName: string, at: number }
local recent: { Recent } = {}

local function pruneRecent(now: number)
	for i = #recent, 1, -1 do
		if now - recent[i].at > RECENT_SECONDS then
			table.remove(recent, i)
		end
	end
	while #recent > RECENT_CAP do
		table.remove(recent, 1)
	end
end

local function targetAllowed(userId: number): boolean
	if Players:GetPlayerByUserId(userId) then
		return true
	end
	local now = os.time()
	for _, r in recent do
		if r.userId == userId and now - r.at <= RECENT_SECONDS then
			return true
		end
	end
	return false
end

---------------------------------------------------------------------------------------------------------------------
-- Limits
---------------------------------------------------------------------------------------------------------------------

local sentBy: { [number]: { number } } = {} -- reporter -> times of their reports in the last hour
local lastPair: { [string]: number } = {} -- "reporter:target" -> time of the last report
local serverSent: { number } = {}
local calls: { [number]: { number } } = {}

local function prune(list: { number }, now: number, window: number)
	for i = #list, 1, -1 do
		if now - list[i] >= window then
			table.remove(list, i)
		end
	end
end

-- Seconds until this player may report again (0 = now).
local function cooldownLeft(userId: number, now: number): number
	local list = sentBy[userId]
	if not list or #list == 0 then
		return 0
	end
	local last = list[#list]
	return math.max(0, COOLDOWN - (now - last))
end

local function callAllowed(player: Player): boolean
	local now = os.clock()
	local list = calls[player.UserId]
	if not list then
		list = {}
		calls[player.UserId] = list
	end
	prune(list, now, CALL_WINDOW)
	if #list >= CALLS_PER_WINDOW then
		return false
	end
	table.insert(list, now)
	return true
end

---------------------------------------------------------------------------------------------------------------------
-- Reporting
---------------------------------------------------------------------------------------------------------------------

local function addToQueue(item: { [string]: any }): boolean
	for attempt = 1, 3 do
		local ok, err = pcall(function()
			queue:AddAsync(item, QUEUE_TTL)
		end)
		if ok then
			return true
		end
		warnEvery("queue", 60, "could not add the report to the queue: " .. tostring(err))
		if attempt < 3 then
			task.wait(attempt)
		end
	end
	return false
end

type Result = { ok: boolean, error: string?, wait: number? }

local function report(reporter: any, targetUserId: any, category: any, text: any, strictCategory: boolean): Result
	if typeof(reporter) ~= "Instance" or not reporter:IsA("Player") or reporter.Parent ~= Players then
		return { ok = false, error = "reporter" }
	end
	if type(targetUserId) ~= "number" or targetUserId ~= targetUserId or targetUserId <= 0 or targetUserId >= 2 ^ 53 or targetUserId % 1 ~= 0 then
		return { ok = false, error = "target" }
	end
	if targetUserId == reporter.UserId then
		return { ok = false, error = "self" }
	end
	if not targetAllowed(targetUserId) then
		return { ok = false, error = "target" }
	end
	local categoryId = findCategory(category)
	if not categoryId then
		if strictCategory then
			return { ok = false, error = "category" }
		end
		categoryId = "other"
	end
	local cleaned = cleanText(text, MAX_TEXT)
	if cleaned == nil then
		return { ok = false, error = "text" }
	end

	local now = os.time()
	local wait = cooldownLeft(reporter.UserId, now)
	if wait > 0 then
		return { ok = false, error = "cooldown", wait = wait }
	end
	local list = sentBy[reporter.UserId] or {}
	sentBy[reporter.UserId] = list
	prune(list, now, HOUR)
	if #list >= MAX_PER_HOUR then
		return { ok = false, error = "limit" }
	end
	local pairKey = tostring(reporter.UserId) .. ":" .. tostring(targetUserId)
	if lastPair[pairKey] and now - lastPair[pairKey] < SAME_TARGET_WINDOW then
		return { ok = false, error = "already" }
	end
	prune(serverSent, now, 60)
	if #serverSent >= SERVER_PER_MINUTE then
		return { ok = false, error = "busy" }
	end

	-- Hold the slots while the queue call runs, so a second click cannot slip through; give them back on failure.
	table.insert(list, now)
	lastPair[pairKey] = now
	table.insert(serverSent, now)
	local queued = addToQueue({
		reporter = reporter.UserId,
		target = targetUserId,
		category = categoryId,
		text = cleaned,
	})
	if not queued then
		table.remove(list, table.find(list, now) or #list)
		lastPair[pairKey] = nil
		table.remove(serverSent, table.find(serverSent, now) or #serverSent)
		return { ok = false, error = "unavailable" }
	end
	return { ok = true }
end

---------------------------------------------------------------------------------------------------------------------
-- Server API for games with their own UI
---------------------------------------------------------------------------------------------------------------------

local apiFolder = ServerStorage:FindFirstChild(API_FOLDER_NAME)
if not apiFolder then
	apiFolder = Instance.new("Folder")
	apiFolder.Name = API_FOLDER_NAME
	apiFolder.Parent = ServerStorage
end
local existingReport = (apiFolder :: Instance):FindFirstChild("Report")
if not existingReport then
	local created = Instance.new("BindableFunction")
	created.Name = "Report"
	created.Parent = apiFolder
	existingReport = created
end
if existingReport and existingReport:IsA("BindableFunction") then
	(existingReport :: BindableFunction).OnInvoke = function(reporter: any, targetUserId: any, category: any, text: any): boolean
		local okCall, result = pcall(report, reporter, tonumber(targetUserId), category, text, false)
		return okCall and result.ok
	end
else
	warn("[Modhelm] ServerStorage.ModhelmReports.Report is not a BindableFunction, the server API is off")
end

---------------------------------------------------------------------------------------------------------------------
-- Remote for the Report window
---------------------------------------------------------------------------------------------------------------------

local function stateFor(player: Player): { [string]: any }
	local now = os.time()
	pruneRecent(now)
	local left = {}
	for _, r in recent do
		if r.userId ~= player.UserId and not Players:GetPlayerByUserId(r.userId) then
			table.insert(left, { userId = r.userId, name = r.name, displayName = r.displayName })
		end
	end
	return { ok = true, categories = categories, wait = cooldownLeft(player.UserId, now), maxText = MAX_TEXT, recent = left }
end

if GIVE_UI then
	local found = ReplicatedStorage:FindFirstChild(REMOTE_NAME)
	if found and not found:IsA("RemoteFunction") then
		warn("[Modhelm] ReplicatedStorage." .. REMOTE_NAME .. " is not a RemoteFunction, the Report button is off")
	else
		local remote = found :: RemoteFunction?
		if not remote then
			local created = Instance.new("RemoteFunction")
			created.Name = REMOTE_NAME
			created.Parent = ReplicatedStorage
			remote = created
		end
		(remote :: RemoteFunction).OnServerInvoke = function(player: Player, action: any, payload: any): any
			if not callAllowed(player) then
				return { ok = false, error = "slow_down" }
			end
			if action == "state" then
				return stateFor(player)
			elseif action == "send" and type(payload) == "table" then
				return report(player, payload.target, payload.category, payload.text, true)
			end
			return { ok = false, error = "bad_request" }
		end
	end
end

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

local clientTemplate = script:FindFirstChild(CLIENT_SCRIPT_NAME)
if GIVE_UI and not (clientTemplate and clientTemplate:IsA("LocalScript")) then
	warn("[Modhelm] the LocalScript " .. CLIENT_SCRIPT_NAME .. " is missing inside this script, players get no Report button")
end

local function giveUi(player: Player)
	if not GIVE_UI or not clientTemplate or not clientTemplate:IsA("LocalScript") then
		return
	end
	local playerGui = player:WaitForChild("PlayerGui", 60)
	if not playerGui or player.Parent ~= Players or playerGui:FindFirstChild(GUI_NAME) then
		return
	end
	local gui = Instance.new("ScreenGui")
	gui.Name = GUI_NAME
	gui.ResetOnSpawn = false
	gui.DisplayOrder = 50
	gui.ZIndexBehavior = Enum.ZIndexBehavior.Sibling
	local copy = clientTemplate:Clone()
	copy.Enabled = true
	copy.Parent = gui
	gui.Parent = playerGui
end

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

Players.PlayerRemoving:Connect(function(player: Player)
	local now = os.time()
	for i = #recent, 1, -1 do
		if recent[i].userId == player.UserId then
			table.remove(recent, i)
		end
	end
	table.insert(recent, { userId = player.UserId, name = player.Name, displayName = player.DisplayName, at = now })
	pruneRecent(now)
	calls[player.UserId] = nil
	-- sentBy and the pair times stay, so leaving and joining again does not reset the limits of this server.
end)

-- Forget limits that ran out, so a server that runs for days keeps its tables small.
local function cleanUp()
	local now = os.time()
	for userId, list in sentBy do
		prune(list, now, HOUR)
		if #list == 0 then
			sentBy[userId] = nil
		end
	end
	for key, at in lastPair do
		if now - at >= SAME_TARGET_WINDOW then
			lastPair[key] = nil
		end
	end
	pruneRecent(now)
end

task.spawn(function()
	while true do
		loadCategories()
		cleanUp()
		task.wait(CATEGORIES_REFRESH)
	end
end)
]]></ProtectedString>
		</Properties>
		<Item class="LocalScript" referent="RBX00000000000000000000000000000000">
			<Properties>
				<string name="Name">ModhelmReportsClient</string>
				<bool name="Disabled">false</bool>
				<ProtectedString name="Source"><![CDATA[--!strict
--[[
	ModhelmReports.client.luau

	The Report window of Modhelm Reports (https://modhelm.com). Keep this LocalScript inside the Script
	"ModhelmReports" in ServerScriptService, named "ModhelmReportsClient"; the server copies it to every player. It
	asks the server through ReplicatedStorage.ModhelmReportsRemote, which checks every report again.

	A small "Report" button on the right opens the window: pick a player of this server, a reason and an optional
	text, then send. Works with mouse, touch and gamepad. Your own scripts can open it too:
	    local gui = game:GetService("Players").LocalPlayer.PlayerGui:WaitForChild("ModhelmReports")
	    gui:WaitForChild("Open"):Fire(userId) -- userId is optional and picks that player right away
]]

-- Roblox image of the Modhelm logo, like "rbxassetid://1234567890". Empty shows the word Modhelm instead.
local LOGO_ASSET = ""
-- false hides the Report button (for games that open the window from their own button through "Open").
local SHOW_BUTTON = true
-- Where the Report button sits: right edge, a little above the middle (clear of the jump button and the chat).
local BUTTON_POSITION = UDim2.new(1, -12, 0.42, 0)

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

local localPlayer = Players.LocalPlayer

local found = ReplicatedStorage:WaitForChild("ModhelmReportsRemote", 60)
if not found or not found:IsA("RemoteFunction") then
	warn("[Modhelm] the Report window could not find ReplicatedStorage.ModhelmReportsRemote")
	return
end
local remote = found :: RemoteFunction

local PANEL_WIDTH = 420
local PANEL_HEIGHT = 540
local ROW_HEIGHT = 52
local SEARCH_FROM = 9 -- show the search field from this many players on
local STATUS_SECONDS = 8

-- Modhelm colors (DESIGN.md, dark theme).
local COLORS = {
	canvas = Color3.fromHex("#0B1020"),
	surface1 = Color3.fromHex("#111829"),
	surface2 = Color3.fromHex("#172036"),
	surface3 = Color3.fromHex("#1E2843"),
	surface4 = Color3.fromHex("#263252"),
	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"),
	dangerText = Color3.fromHex("#FF6B7A"),
	successText = Color3.fromHex("#2BD47D"),
	white = Color3.new(1, 1, 1),
}

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

local ERRORS: { [string]: string } = {
	limit = "You sent many reports in the last hour. Try again later.",
	already = "You already reported this player. The moderators will look at it.",
	busy = "Many reports right now. Try again in a minute.",
	target = "This player is not in this server anymore.",
	self = "You cannot report yourself.",
	category = "Pick a reason.",
	text = "The text is too long.",
	slow_down = "Too many requests. Wait a moment and try again.",
}
local GENERIC_ERROR = "The report could not be sent. Try again later."

type Category = { id: string, label: string }
type Person = { userId: number, name: string, displayName: string, left: boolean }

---------------------------------------------------------------------------------------------------------------------
-- 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

local baseFill: { [GuiButton]: Color3 } = setmetatable({}, { __mode = "k" }) :: any

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

local function hover(button: GuiButton)
	button.MouseEnter:Connect(function()
		local base = baseFill[button]
		if base and button.Active 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)
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 = 16
	button.TextColor3 = textColor
	button.Text = text
	setFill(button, fill)
	hover(button)
	button.Parent = parent
	return button
end

local function pad(parent: Instance, x: number, y: number)
	local padding = Instance.new("UIPadding")
	padding.PaddingLeft = UDim.new(0, x)
	padding.PaddingRight = UDim.new(0, x)
	padding.PaddingTop = UDim.new(0, y)
	padding.PaddingBottom = UDim.new(0, y)
	padding.Parent = parent
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 = "ModhelmReports"
	gui.ResetOnSpawn = false
	gui.DisplayOrder = 50
	gui.Parent = localPlayer:WaitForChild("PlayerGui")
end
gui.ScreenInsets = Enum.ScreenInsets.DeviceSafeInsets

local openEvent = gui:FindFirstChild("Open")
if not openEvent then
	local created = Instance.new("BindableEvent")
	created.Name = "Open"
	created.Parent = gui
	openEvent = created
end

local toggle = newButton(gui, "Report", COLORS.surface1, COLORS.ink)
toggle.Name = "ReportButton"
toggle.Font = FONT_BOLD
toggle.AnchorPoint = Vector2.new(1, 0.5)
toggle.Position = BUTTON_POSITION
toggle.Size = UDim2.fromOffset(84, 36)
toggle.Visible = SHOW_BUTTON
local toggleStroke = Instance.new("UIStroke")
toggleStroke.Color = COLORS.hairlineStrong
toggleStroke.ApplyStrokeMode = Enum.ApplyStrokeMode.Border
toggleStroke.Parent = toggle

local panel = Instance.new("Frame")
panel.Name = "Window"
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.ZIndex = 5
panel.Parent = gui
local panelStroke = Instance.new("UIStroke")
panelStroke.Color = COLORS.hairlineStrong
panelStroke.ApplyStrokeMode = Enum.ApplyStrokeMode.Border
panelStroke.Parent = panel
local panelPadding = Instance.new("UIPadding")
panelPadding.Parent = panel

-- 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

-- Header: logo (an uploaded image when LOGO_ASSET is set, else the drawn logo with the word Modhelm), title, Close.
local brand: GuiObject
if LOGO_ASSET ~= "" then
	local logo = Instance.new("ImageLabel")
	logo.BackgroundTransparency = 1
	logo.BorderSizePixel = 0
	logo.Image = LOGO_ASSET
	logo.ScaleType = Enum.ScaleType.Fit
	logo.Size = UDim2.fromOffset(20, 20)
	logo.Position = UDim2.fromOffset(0, 0)
	logo.Parent = panel
	brand = logo
else
	local holder = Instance.new("Frame")
	holder.BackgroundTransparency = 1
	holder.BorderSizePixel = 0
	holder.Size = UDim2.fromOffset(110, 20)
	holder.Parent = panel
	makeLogo(20).Parent = holder
	local word = newLabel(holder, "Modhelm", 14, COLORS.accent, FONT_BOLD)
	word.Position = UDim2.fromOffset(26, 0)
	word.Size = UDim2.fromOffset(84, 20)
	brand = holder
end
brand.Name = "Brand"

local title = newLabel(panel, "Report a player", 20, COLORS.ink, FONT_BOLD)
title.Position = UDim2.fromOffset(0, 22)
title.Size = UDim2.new(1, -92, 0, 26)

local closeButton = newButton(panel, "Close", COLORS.surface3, COLORS.ink)
closeButton.AnchorPoint = Vector2.new(1, 0)
closeButton.Position = UDim2.new(1, 0, 0, 4)
closeButton.Size = UDim2.fromOffset(80, 40)

local HEADER = 60
local FOOTER = 88

local body = Instance.new("ScrollingFrame")
body.Name = "Body"
body.BackgroundTransparency = 1
body.BorderSizePixel = 0
body.Position = UDim2.fromOffset(0, HEADER)
body.Size = UDim2.new(1, 0, 1, -(HEADER + FOOTER))
body.CanvasSize = UDim2.new()
body.AutomaticCanvasSize = Enum.AutomaticSize.Y
body.ScrollingDirection = Enum.ScrollingDirection.Y
body.ScrollBarThickness = 4
body.ScrollBarImageColor3 = COLORS.surface4
body.VerticalScrollBarInset = Enum.ScrollBarInset.ScrollBar
body.Parent = panel
local bodyList = Instance.new("UIListLayout")
bodyList.Padding = UDim.new(0, 6)
bodyList.SortOrder = Enum.SortOrder.LayoutOrder
bodyList.Parent = body

local footer = Instance.new("Frame")
footer.Name = "Footer"
footer.BackgroundTransparency = 1
footer.AnchorPoint = Vector2.new(0, 1)
footer.Position = UDim2.fromScale(0, 1)
footer.Size = UDim2.new(1, 0, 0, FOOTER)
footer.Parent = panel

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

local status = newLabel(footer, "", 14, COLORS.inkMuted, FONT)
status.Position = UDim2.fromOffset(0, 8)
status.Size = UDim2.new(1, 0, 0, 20)
status.TextTruncate = Enum.TextTruncate.None
status.TextWrapped = true

local primary = newButton(footer, "Send report", COLORS.accent, COLORS.onAccent)
primary.Font = FONT_BOLD
primary.AnchorPoint = Vector2.new(0, 1)
primary.Position = UDim2.fromScale(0, 1)
primary.Size = UDim2.new(1, 0, 0, 44)

-- Fit the window into the screen: full size on desktop, the whole screen minus a margin on phones.
local function fitPanel()
	local area = gui.AbsoluteSize
	local width = math.clamp(area.X - 24, 260, PANEL_WIDTH)
	local height = math.clamp(area.Y - 24, 240, PANEL_HEIGHT)
	panel.Size = UDim2.fromOffset(width, height)
	local p = if width < 360 then 12 else 16
	panelPadding.PaddingTop = UDim.new(0, p)
	panelPadding.PaddingBottom = UDim.new(0, p)
	panelPadding.PaddingLeft = UDim.new(0, p)
	panelPadding.PaddingRight = UDim.new(0, p)
end
gui:GetPropertyChangedSignal("AbsoluteSize"):Connect(fitPanel)
fitPanel()

---------------------------------------------------------------------------------------------------------------------
-- State
---------------------------------------------------------------------------------------------------------------------

local categories: { Category } = {}
local recentLeft: { Person } = {}
local maxText = 500
local cooldownUntil = 0
local step: "pick" | "details" | "done" | "error" = "pick"
local chosen: Person? = nil
local chosenCategory: string? = nil
local text = ""
local search = ""
local sending = false
local statusToken = 0

local function setStatus(message: string, kind: "info" | "error" | "success")
	statusToken += 1
	local token = statusToken
	status.Text = message
	status.TextColor3 = if kind == "error" then COLORS.dangerText elseif kind == "success" then COLORS.successText else COLORS.inkMuted
	if kind ~= "info" and message ~= "" then
		task.delay(STATUS_SECONDS, function()
			if statusToken == token then
				status.Text = ""
			end
		end)
	end
end

local function waitLeft(): number
	return math.max(0, math.ceil(cooldownUntil - os.clock()))
end

local function setPrimary(label: string, enabled: boolean)
	primary.Text = label
	primary.Active = enabled
	primary.AutoButtonColor = false
	setFill(primary, if enabled then COLORS.accent else COLORS.surface3)
	primary.TextColor3 = if enabled then COLORS.onAccent else COLORS.inkSubtle
end

local function clearBody()
	for _, child in body:GetChildren() do
		if not child:IsA("UIListLayout") then
			child:Destroy()
		end
	end
	body.CanvasPosition = Vector2.zero
end

local function sectionLabel(text_: string, order: number): TextLabel
	local label = newLabel(body, text_, 15, COLORS.inkMuted, FONT_MEDIUM)
	label.Size = UDim2.new(1, 0, 0, 28)
	label.TextWrapped = true
	label.TextTruncate = Enum.TextTruncate.None
	label.LayoutOrder = order
	return label
end

local function people(): { Person }
	local list: { Person } = {}
	for _, p in Players:GetPlayers() do
		if p ~= localPlayer then
			table.insert(list, { userId = p.UserId, name = p.Name, displayName = p.DisplayName, left = false })
		end
	end
	table.sort(list, function(a, b)
		return string.lower(a.displayName) < string.lower(b.displayName)
	end)
	for _, r in recentLeft do
		if not Players:GetPlayerByUserId(r.userId) then
			table.insert(list, r)
		end
	end
	return list
end

local render: () -> ()

local function personRow(person: Person, order: number, selectable: boolean): Frame
	local row = Instance.new("Frame")
	row.BackgroundColor3 = COLORS.surface2
	row.BorderSizePixel = 0
	row.Size = UDim2.new(1, 0, 0, ROW_HEIGHT)
	row.LayoutOrder = order
	row.Parent = body

	local face = Instance.new("ImageLabel")
	face.BackgroundColor3 = COLORS.surface3
	face.BorderSizePixel = 0
	face.Image = "rbxthumb://type=AvatarHeadShot&id=" .. tostring(person.userId) .. "&w=48&h=48"
	face.Position = UDim2.fromOffset(8, 8)
	face.Size = UDim2.fromOffset(36, 36)
	face.Parent = row

	local nameLabel = newLabel(row, person.displayName, 16, COLORS.ink, FONT_MEDIUM)
	nameLabel.Position = UDim2.fromOffset(54, 7)
	nameLabel.Size = UDim2.new(1, -62, 0, 20)
	local handle = "@" .. person.name .. (if person.left then ", left the server" else "")
	local handleLabel = newLabel(row, handle, 14, COLORS.inkSubtle, FONT)
	handleLabel.Position = UDim2.fromOffset(54, 27)
	handleLabel.Size = UDim2.new(1, -62, 0, 18)

	if selectable then
		local hit = Instance.new("TextButton")
		hit.BackgroundTransparency = 1
		hit.Text = ""
		hit.Size = UDim2.fromScale(1, 1)
		hit.ZIndex = 2
		hit.Parent = row
		hit.MouseEnter:Connect(function()
			row.BackgroundColor3 = COLORS.surface3
		end)
		hit.MouseLeave:Connect(function()
			row.BackgroundColor3 = COLORS.surface2
		end)
		hit.Activated:Connect(function()
			chosen = person
			step = "details"
			render()
		end)
	end
	return row
end

local function renderPick()
	title.Text = "Report a player"
	local list = people()
	local order = 1
	sectionLabel("Who do you want to report?", order)
	order += 1
	if #list >= SEARCH_FROM then
		local box = Instance.new("TextBox")
		box.BackgroundColor3 = COLORS.surface2
		box.BorderSizePixel = 0
		box.ClearTextOnFocus = false
		box.Font = FONT
		box.TextSize = 16
		box.TextColor3 = COLORS.ink
		box.PlaceholderColor3 = COLORS.inkSubtle
		box.PlaceholderText = "Search by name"
		box.Text = search
		box.TextXAlignment = Enum.TextXAlignment.Left
		box.Size = UDim2.new(1, 0, 0, 40)
		box.LayoutOrder = order
		pad(box, 10, 0)
		box.Parent = body
		box:GetPropertyChangedSignal("Text"):Connect(function()
			search = box.Text
			for _, child in body:GetChildren() do
				local id = child:GetAttribute("Search")
				if child:IsA("Frame") and type(id) == "string" then
					child.Visible = search == "" or string.find(id, string.lower(search), 1, true) ~= nil
				end
			end
		end)
		order += 1
	end
	if #list == 0 then
		local empty = sectionLabel("Nobody else is in this server right now.", order)
		empty.TextColor3 = COLORS.inkSubtle
	end
	local needle = string.lower(search)
	for _, person in list do
		local row = personRow(person, order, true)
		local key = string.lower(person.displayName .. " " .. person.name)
		row:SetAttribute("Search", key)
		row.Visible = needle == "" or string.find(key, needle, 1, true) ~= nil
		order += 1
	end
	setPrimary("Send report", false)
	primary.Visible = false
	local wait = waitLeft()
	if wait > 0 then
		setStatus(string.format("You can send another report in %d seconds.", wait), "info")
	end
end

local function renderDetails()
	local person = chosen
	if not person then
		step = "pick"
		render()
		return
	end
	title.Text = "Report a player"
	local order = 1
	personRow(person, order, false)
	local change = newButton(body, "Change player", COLORS.surface3, COLORS.ink)
	change.Size = UDim2.new(1, 0, 0, 40)
	change.LayoutOrder = order + 1
	change.Activated:Connect(function()
		chosen = nil
		chosenCategory = nil
		step = "pick"
		render()
	end)
	order += 2

	sectionLabel("What happened?", order)
	order += 1
	for _, category in categories do
		local selected = chosenCategory == category.id
		local option = newButton(body, category.label, if selected then COLORS.surface4 else COLORS.surface2, if selected then COLORS.ink else COLORS.inkMuted)
		option.Font = if selected then FONT_BOLD else FONT_MEDIUM
		option.TextXAlignment = Enum.TextXAlignment.Left
		option.TextTruncate = Enum.TextTruncate.AtEnd
		option.Size = UDim2.new(1, 0, 0, 44)
		option.LayoutOrder = order
		pad(option, 12, 0)
		if selected then
			local bar = Instance.new("Frame")
			bar.BorderSizePixel = 0
			bar.BackgroundColor3 = COLORS.accent
			bar.Position = UDim2.fromOffset(-12, 0)
			bar.Size = UDim2.new(0, 3, 1, 0)
			bar.Parent = option
		end
		option.Activated:Connect(function()
			chosenCategory = category.id
			local y = body.CanvasPosition
			render()
			body.CanvasPosition = y
		end)
		order += 1
	end

	sectionLabel("More details, if you like", order)
	order += 1
	local box = Instance.new("TextBox")
	box.BackgroundColor3 = COLORS.surface2
	box.BorderSizePixel = 0
	box.ClearTextOnFocus = false
	box.MultiLine = true
	box.TextWrapped = true
	box.Font = FONT
	box.TextSize = 16
	box.TextColor3 = COLORS.ink
	box.PlaceholderColor3 = COLORS.inkSubtle
	box.PlaceholderText = "What did they do? Leave out personal info."
	box.Text = text
	box.TextXAlignment = Enum.TextXAlignment.Left
	box.TextYAlignment = Enum.TextYAlignment.Top
	box.Size = UDim2.new(1, 0, 0, 96)
	box.LayoutOrder = order
	pad(box, 10, 8)
	box.Parent = body
	order += 1
	local counter = newLabel(body, "", 13, COLORS.inkSubtle, FONT)
	counter.Size = UDim2.new(1, 0, 0, 18)
	counter.TextXAlignment = Enum.TextXAlignment.Right
	counter.LayoutOrder = order
	local function updateCounter()
		local length = utf8.len(box.Text) or #box.Text
		if length > maxText then
			local cut = utf8.offset(box.Text, maxText + 1)
			box.Text = if cut then string.sub(box.Text, 1, cut - 1) else string.sub(box.Text, 1, maxText)
			return
		end
		text = box.Text
		counter.Text = string.format("%d of %d", length, maxText)
	end
	box:GetPropertyChangedSignal("Text"):Connect(updateCounter)
	updateCounter()

	primary.Visible = true
	local wait = waitLeft()
	if wait > 0 then
		setPrimary(string.format("Wait %d seconds", wait), false)
	elseif sending then
		setPrimary("Sending", false)
	else
		setPrimary("Send report", chosenCategory ~= nil)
	end
end

local function renderDone()
	title.Text = "Report sent"
	local order = 1
	local thanks = sectionLabel("Thanks. The moderators of this game will look at your report.", order)
	thanks.TextColor3 = COLORS.ink
	thanks.Size = UDim2.new(1, 0, 0, 48)
	local note = sectionLabel("You can keep playing now.", order + 1)
	note.TextColor3 = COLORS.inkSubtle
	note.Size = UDim2.new(1, 0, 0, 48)
	primary.Visible = true
	setPrimary("Close", true)
end

local function renderError()
	title.Text = "Report a player"
	local message = sectionLabel("Reports are not available right now. Try again in a moment.", 1)
	message.Size = UDim2.new(1, 0, 0, 48)
	primary.Visible = true
	setPrimary("Try again", true)
end

render = function()
	clearBody()
	if step == "pick" then
		renderPick()
	elseif step == "details" then
		renderDetails()
	elseif step == "done" then
		renderDone()
	else
		renderError()
	end
end

---------------------------------------------------------------------------------------------------------------------
-- Talking to the server
---------------------------------------------------------------------------------------------------------------------

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

local function applyState(state: any)
	local list: { Category } = {}
	if type(state.categories) == "table" then
		for _, c in state.categories do
			if type(c) == "table" and type(c.id) == "string" and type(c.label) == "string" then
				table.insert(list, { id = c.id, label = c.label })
			end
		end
	end
	categories = list
	local left: { Person } = {}
	if type(state.recent) == "table" then
		for _, r in state.recent do
			if type(r) == "table" and type(r.userId) == "number" and type(r.name) == "string" then
				table.insert(left, { userId = r.userId, name = r.name, displayName = if type(r.displayName) == "string" then r.displayName else r.name, left = true })
			end
		end
	end
	recentLeft = left
	if type(state.maxText) == "number" then
		maxText = state.maxText
	end
	if type(state.wait) == "number" and state.wait > 0 then
		cooldownUntil = os.clock() + state.wait
	end
end

local loading = false

local function refresh(preselect: number?)
	if loading then
		return
	end
	loading = true
	setStatus("Loading", "info")
	local ok, state = call("state", nil)
	loading = false
	if not ok or #((state :: any).categories or {}) == 0 then
		step = "error"
		setStatus("", "info")
		render()
		return
	end
	applyState(state)
	setStatus("", "info")
	if preselect then
		for _, person in people() do
			if person.userId == preselect then
				chosen = person
				step = "details"
			end
		end
	end
	render()
end

local function send()
	local person = chosen
	if sending or not person or not chosenCategory or waitLeft() > 0 then
		return
	end
	sending = true
	render()
	local ok, result = call("send", { target = person.userId, category = chosenCategory, text = text })
	sending = false
	if ok then
		cooldownUntil = os.clock() + 60
		step = "done"
		chosen = nil
		chosenCategory = nil
		text = ""
		setStatus("", "info")
		render()
		return
	end
	local code = if type(result) == "table" and type(result.error) == "string" then result.error else ""
	if code == "cooldown" and type(result.wait) == "number" then
		cooldownUntil = os.clock() + result.wait
		setStatus(string.format("You can send another report in %d seconds.", math.ceil(result.wait)), "error")
	else
		setStatus(ERRORS[code] or GENERIC_ERROR, "error")
	end
	render()
end

---------------------------------------------------------------------------------------------------------------------
-- Open and close
---------------------------------------------------------------------------------------------------------------------

local function close()
	panel.Visible = false
	toggle.Visible = SHOW_BUTTON
end

local function open(preselect: number?)
	if step == "done" or step == "error" then
		step = "pick"
	end
	if preselect == nil and step == "details" and chosen and chosen.left and not Players:GetPlayerByUserId(chosen.userId) then
		step = "pick"
	end
	search = ""
	panel.Visible = true
	toggle.Visible = false
	render()
	task.spawn(refresh, preselect)
end

toggle.Activated:Connect(function()
	open(nil)
end)
closeButton.Activated:Connect(close)
primary.Activated:Connect(function()
	if not primary.Active then
		return
	end
	if step == "done" then
		close()
	elseif step == "error" then
		step = "pick"
		render()
		task.spawn(refresh, nil)
	elseif step == "details" then
		send()
	end
end)
;(openEvent :: any).Event:Connect(function(userId: any)
	open(if type(userId) == "number" then userId else nil)
end)

UserInputService.InputBegan:Connect(function(input: InputObject, processed: boolean)
	if not processed and panel.Visible and (input.KeyCode == Enum.KeyCode.Escape or input.KeyCode == Enum.KeyCode.ButtonB) then
		close()
	end
end)

-- Keep the player list and the waiting time current while the window is open.
local function onPlayersChanged()
	if panel.Visible and step == "pick" then
		render()
	end
end
Players.PlayerAdded:Connect(onPlayersChanged)
Players.PlayerRemoving:Connect(function(player: Player)
	if player ~= localPlayer then
		for i = #recentLeft, 1, -1 do
			if recentLeft[i].userId == player.UserId then
				table.remove(recentLeft, i)
			end
		end
		table.insert(recentLeft, 1, { userId = player.UserId, name = player.Name, displayName = player.DisplayName, left = true })
	end
	task.defer(onPlayersChanged)
end)

task.spawn(function()
	while true do
		task.wait(1)
		if panel.Visible and step == "details" and not sending then
			local wait = waitLeft()
			if wait > 0 then
				setPrimary(string.format("Wait %d seconds", wait), false)
			elseif primary.Text ~= "Send report" then
				setPrimary("Send report", chosenCategory ~= nil)
			end
		end
	end
end)
]]></ProtectedString>
			</Properties>
		</Item>
	</Item>
</roblox>
