animTable[name][idx].anim = Instance.new("Animation")
			animTable[name][idx].anim.Name = name
			animTable[name][idx].anim.AnimationId = anim.id
			animTable[name][idx].weight = anim.weight
			animTable[name].count = animTable[name].count + 1
			animTable[name].totalWeight = animTable[name].totalWeight + anim.weight
			--			print(name .. " [" .. idx .. "] " .. anim.id .. " (" .. anim.weight .. ")")
		end
	end
end

-- Setup animation objects
function scriptChildModified(child)
	local fileList = animNames[child.Name]
	if (fileList ~= nil) then
		configureAnimationSet(child.Name, fileList)
	end	
end

script.ChildAdded:connect(scriptChildModified)
script.ChildRemoved:connect(scriptChildModified)

-- Clear any existing animation tracks
-- Fixes issue with characters that are moved in and out of the Workspace accumulating tracks
local animator = if Humanoid then Humanoid:FindFirstChildOfClass("Animator") else nil
if animator then
	local animTracks = animator:GetPlayingAnimationTracks()
	for i,track in ipairs(animTracks) do
		track:Stop(0)
		track:Destroy()
	end
end

for name, fileList in pairs(animNames) do 
	configureAnimationSet(name, fileList)
end	

-- functions

function setAnimationSpeed(speed)
	if speed ~= currentAnimSpeed then
		currentAnimSpeed = speed
		currentAnimTrack:AdjustSpeed(currentAnimSpeed)
	end
end

function keyFrameReachedFunc(frameName)
	if (frameName == "End") then

		local repeatAnim = currentAnim

		local animSpeed = currentAnimSpeed
		playAnimation(repeatAnim, 0.0, Humanoid)
		setAnimationSpeed(animSpeed)
	end
end

-- Preload animations
function playAnimation(animName, transitionTime, humanoid) 

	local roll = math.random(1, animTable[animName].totalWeight) 
	local origRoll = roll
	local idx = 1
	while (roll > animTable[animName][idx].weight) do
		roll = roll - animTable[animName][idx].weight
		idx = idx + 1
	end
	--		print(animName .. " " .. idx .. " [" .. origRoll .. "]")
	local anim = animTable[animName][idx].anim

	-- switch animation		
	if (anim ~= currentAnimInstance) then

		if (currentAnimTrack ~= nil) then
			currentAnimTrack:Stop(transitionTime)
			currentAnimTrack:Destroy()
		end

		currentAnimSpeed = 1.0

		-- load it to the humanoid; get AnimationTrack
		currentAnimTrack = humanoid:LoadAnimation(anim)
		currentAnimTrack.Priority = Enum.AnimationPriority.Core

		-- play the animation
		currentAnimTrack:Play(transitionTime)
		currentAnim = animName
		currentAnimInstance = anim

		-- set up keyframe name triggers
		if (currentAnimKeyframeHandler ~= nil) then
			currentAnimKeyframeHandler:disconnect()
		end
		currentAnimKeyframeHandler = currentAnimTrack.KeyframeReached:connect(keyFrameReachedFunc)

	end

end

local toolAnimName = ""
local toolAnimTrack = nil
local toolAnimInstance = nil
local currentToolAnimKeyframeHandler = nil


function onRunning(speed)
	speed /= getRigScale()

	if speed > 0.01 then
		playAnimation("walk", 0.1, Humanoid)
		if currentAnimInstance and currentAnimInstance.AnimationId == "http://www.roblox.com/asset/?id=180426354" then
			setAnimationSpeed(speed / 14.5)
		end
		pose = "Running"
	end
end

onRunning(30)  -  Edit - Script:57
  ١١:١٧:٢١.٥٨٤  ================================================================================  -  Edit - Script:58
  ١١:١٧:٢١.٥٨٤  
================================================================================  -  Edit - Script:50
  ١١:١٧:٢١.٥٨٤  🔹 اسم السكربت: OpenSkinShop----------icancel  -  Edit - Script:51
  ١١:١٧:٢١.٥٨٤  📍 المسار: Workspace.InteractableParts.ClickerSkinShops.OpenSkinShop----------icancel  -  Edit - Script:52
  ١١:١٧:٢١.٥٨٤  📄 النوع: Script  -  Edit - Script:53
  ١١:١٧:٢١.٥٨٥  🔢 مفعّل: false  -  Edit - Script:54
  ١١:١٧:٢١.٥٨٥  --------------------------------------------------------------------------------  -  Edit - Script:55
  ١١:١٧:٢١.٥٨٥  📝 محتوى السكربت:  -  Edit - Script:56
  ١١:١٧:٢١.٥٨٥  local RepStorage = game:GetService("ReplicatedStorage")
local Remotes = RepStorage:WaitForChild("Remotes")
local Modules = RepStorage:WaitForChild("Modules")

local Zone = require(Modules:WaitForChild("Zone"))
local PlayersInZone = require(Modules:WaitForChild("Zone"):WaitForChild("PlayersInZone"))

local ClickerSkinFolder = script.Parent.Parent:WaitForChild("ClickerSkinShops")
local LoadShop = Remotes:WaitForChild("LoadShop")

for _, Open in pairs(ClickerSkinFolder:GetChildren()) do
	if Open:IsA("MeshPart") then
		local newzone = Zone.new(Open)
		newzone.playerEntered:Connect(function(player)
			table.insert(PlayersInZone,player)
			
			LoadShop:FireClient(player)
		end)

		newzone.playerExited:Connect(function(player)
			local findPlayer = table.find(PlayersInZone,player)

			table.remove(PlayersInZone,findPlayer)		
		end)
	end
end  -  Edit - Script:57
  ١١:١٧:٢١.٥٨٥  ================================================================================  -  Edit - Script:58
  ١١:١٧:٢١.٥٨٥  
================================================================================  -  Edit - Script:50
  ١١:١٧:٢١.٥٨٥  🔹 اسم السكربت: OpenIndexShop  -  Edit - Script:51
  ١١:١٧:٢١.٥٨٥  📍 المسار: Workspace.InteractableParts.Misc.IndexMachine.OpenIndexShop  -  Edit - Script:52
  ١١:١٧:٢١.٥٨٥  📄 النوع: Script  -  Edit - Script:53
  ١١:١٧:٢١.٥٨٥  🔢 مفعّل: true  -  Edit - Script:54
  ١١:١٧:٢١.٥٨٥  --------------------------------------------------------------------------------  -  Edit - Script:55
  ١١:١٧:٢١.٥٨٦  📝 محتوى السكربت:  -  Edit - Script:56
  ١١:١٧:٢١.٥٨٦  local RepStorage = game:GetService("ReplicatedStorage")
local Remotes = RepStorage:WaitForChild("Remotes")
local Modules = RepStorage:WaitForChild("Modules")

local Zone = require(Modules:WaitForChild("Zone"))
local PlayersInZone = require(Modules:WaitForChild("Zone"):WaitForChild("PlayersInZone"))

local OpenIndex = Remotes:WaitForChild("OpenIndex")
local CloseIndex = Remotes:WaitForChild("CloseIndex")

local newzone = Zone.new(script.Parent)
newzone.playerEntered:Connect(function(player)
	table.insert(PlayersInZone,player)

	OpenIndex:FireClient(player)
end)

newzone.playerExited:Connect(function(player)
	local findPlayer = table.find(PlayersInZone,player)

	table.remove(PlayersInZone,findPlayer)		
	
	CloseIndex:FireClient(player)
end)  -  Edit - Script:57
  ١١:١٧:٢١.٥٨٦  ================================================================================  -  Edit - Script:58
  ١١:١٧:٢١.٥٨٦  
================================================================================  -  Edit - Script:50
  ١١:١٧:٢١.٥٨٦  🔹 اسم السكربت: OpenUpgradesShop  -  Edit - Script:51
  ١١:١٧:٢١.٥٨٦  📍 المسار: Workspace.InteractableParts.Misc.UpgradesMachine.OpenUpgradesShop  -  Edit - Script:52
  ١١:١٧:٢١.٥٨٧  📄 النوع: Script  -  Edit - Script:53
  ١١:١٧:٢١.٥٨٧  🔢 مفعّل: true  -  Edit - Script:54
  ١١:١٧:٢١.٥٨٧  --------------------------------------------------------------------------------  -  Edit - Script:55
  ١١:١٧:٢١.٥٨٧  📝 محتوى السكربت:  -  Edit - Script:56
  ١١:١٧:٢١.٥٨٧  local RepStorage = game:GetService("ReplicatedStorage")
local Remotes = RepStorage:WaitForChild("Remotes")
local Modules = RepStorage:WaitForChild("Modules")

local Zone = require(Modules:WaitForChild("Zone"))
local PlayersInZone = require(Modules:WaitForChild("Zone"):WaitForChild("PlayersInZone"))

local OpenUpgrades = Remotes:WaitForChild("OpenUpgrades")
local CloseUpgrades = Remotes:WaitForChild("CloseUpgrades")

local newzone = Zone.new(script.Parent)
newzone.playerEntered:Connect(function(player)
	table.insert(PlayersInZone,player)

	OpenUpgrades:FireClient(player)
end)

newzone.playerExited:Connect(function(player)
	local findPlayer = table.find(PlayersInZone,player)

	table.remove(PlayersInZone,findPlayer)		
	
	CloseUpgrades:FireClient(player)
end)  -  Edit - Script:57
  ١١:١٧:٢١.٥٨٧  ================================================================================  -  Edit - Script:58
  ١١:١٧:٢١.٥٨٧  
================================================================================  -  Edit - Script:50
  ١١:١٧:٢١.٥٨٧  🔹 اسم السكربت: OpenRainbowMachine  -  Edit - Script:51
  ١١:١٧:٢١.٥٨٨  📍 المسار: Workspace.InteractableParts.Misc.RainbowMachine.OpenRainbowMachine  -  Edit - Script:52
  ١١:١٧:٢١.٥٨٨  📄 النوع: Script  -  Edit - Script:53
  ١١:١٧:٢١.٥٨٨  🔢 مفعّل: true  -  Edit - Script:54
  ١١:١٧:٢١.٥٨٨  --------------------------------------------------------------------------------  -  Edit - Script:55
  ١١:١٧:٢١.٥٨٨  📝 محتوى السكربت:  -  Edit - Script:56
  ١١:١٧:٢١.٥٨٨  local RepStorage = game:GetService("ReplicatedStorage")
local Remotes = RepStorage:WaitForChild("Remotes")
local Modules = RepStorage:WaitForChild("Modules")

local Zone = require(Modules:WaitForChild("Zone"))
local PlayersInZone = require(Modules:WaitForChild("Zone"):WaitForChild("PlayersInZone"))

local OpenRainbowMachine = Remotes:WaitForChild("Egg_Stuff"):WaitForChild("OpenRainbow")
local CloseRainbowMachine = Remotes:WaitForChild("Egg_Stuff"):WaitForChild("CloseRainbow")

local newzone = Zone.new(script.Parent)
newzone.playerEntered:Connect(function(player)
	table.insert(PlayersInZone,player)

	OpenRainbowMachine:FireClient(player)
end)

newzone.playerExited:Connect(function(player)
	local findPlayer = table.find(PlayersInZone,player)

	table.remove(PlayersInZone,findPlayer)		
	
	CloseRainbowMachine:FireClient(player)
end)  -  Edit - Script:57
  ١١:١٧:٢١.٥٨٨  ================================================================================  -  Edit - Script:58
  ١١:١٧:٢١.٥٨٨  
================================================================================  -  Edit - Script:50
  ١١:١٧:٢١.٥٨٨  🔹 اسم السكربت: OpenSkinShop  -  Edit - Script:51
  ١١:١٧:٢١.٥٨٨  📍 المسار: Workspace.InteractableParts.Misc.GoldenMachine.OpenSkinShop  -  Edit - Script:52
  ١١:١٧:٢١.٥٨٩  📄 النوع: Script  -  Edit - Script:53
  ١١:١٧:٢١.٥٨٩  🔢 مفعّل: true  -  Edit - Script:54
  ١١:١٧:٢١.٥٨٩  --------------------------------------------------------------------------------  -  Edit - Script:55
  ١١:١٧:٢١.٥٨٩  📝 محتوى السكربت:  -  Edit - Script:56
  ١١:١٧:٢١.٥٨٩  local RepStorage = game:GetService("ReplicatedStorage")
local Remotes = RepStorage:WaitForChild("Remotes")
local Modules = RepStorage:WaitForChild("Modules")

local Zone = require(Modules:WaitForChild("Zone"))
local PlayersInZone = require(Modules:WaitForChild("Zone"):WaitForChild("PlayersInZone"))

local LoadGoldenMachine = Remotes:WaitForChild("Egg_Stuff"):WaitForChild("OpenGolden")
local CloseGoldenMachine = Remotes:WaitForChild("Egg_Stuff"):WaitForChild("CloseGolden")

local newzone = Zone.new(script.Parent)
newzone.playerEntered:Connect(function(player)
	table.insert(PlayersInZone,player)

	LoadGoldenMachine:FireClient(player)
end)

newzone.playerExited:Connect(function(player)
	local findPlayer = table.find(PlayersInZone,player)

	table.remove(PlayersInZone,findPlayer)		
	
	CloseGoldenMachine:FireClient(player)
end)  -  Edit - Script:57
  ١١:١٧:٢١.٥٨٩  ================================================================================  -  Edit - Script:58
  ١١:١٧:٢١.٥٨٩  
================================================================================  -  Edit - Script:50
  ١١:١٧:٢١.٥٨٩  🔹 اسم السكربت: Zone_Manager-------icancel  -  Edit - Script:51
  ١١:١٧:٢١.٥٨٩  📍 المسار: Workspace.InteractableParts.Zones.Zone_Manager-------icancel  -  Edit - Script:52
  ١١:١٧:٢١.٥٨٩  📄 النوع: Script  -  Edit - Script:53
  ١١:١٧:٢١.٥٩٠  🔢 مفعّل: false  -  Edit - Script:54
  ١١:١٧:٢١.٥٩٠  --------------------------------------------------------------------------------  -  Edit - Script:55
  ١١:١٧:٢١.٥٩٠  📝 محتوى السكربت:  -  Edit - Script:56
  ١١:١٧:٢١.٥٩٠  local RepStorage = game:GetService("ReplicatedStorage")
local Remotes = RepStorage:WaitForChild("Remotes")
local Modules = RepStorage:WaitForChild("Modules")

local ZoneModule = require(Modules:WaitForChild("Zone"))
local PlayersInZone = require(Modules:WaitForChild("Zone"):WaitForChild("PlayersInZone"))
local Manager = require(game:GetService("ServerScriptService"):WaitForChild("PlayerData"):WaitForChild("Manager"))

task.wait(3)

if not game.Loaded then
	task.wait(5)
end

for _, Zone in pairs(script.Parent.Parent.Zones:GetChildren()) do
	if Zone:IsA("Part") then
		local newzone = ZoneModule.new(Zone)

		newzone.playerEntered:Connect(function(player)
			local profile = Manager.Profiles[player]
			table.insert(PlayersInZone,player)

			if player:GetAttribute("CurrentZone") then
				player:SetAttribute("CurrentZone",Zone:GetAttribute("Zone"))
			end

		end)

		newzone.playerExited:Connect(function(player)
			local findPlayer = table.find(PlayersInZone,player)
			table.remove(PlayersInZone,findPlayer)		
		end)
	end
end  -  Edit - Script:57
  ١١:١٧:٢١.٥٩٠  ================================================================================  -  Edit - Script:58
  ١١:١٧:٢١.٥٩٠  
================================================================================  -  Edit - Script:50
  ١١:١٧:٢١.٥٩٠  🔹 اسم السكربت: Rainbow Color Script  -  Edit - Script:51
  ١١:١٧:٢١.٥٩٠  📍 المسار: Workspace.rainbow machine2.Cylinder.Rainbow Color Script  -  Edit - Script:52
  ١١:١٧:٢١.٥٩٠  📄 النوع: Script  -  Edit - Script:53
  ١١:١٧:٢١.٥٩٠  🔢 مفعّل: true  -  Edit - Script:54
  ١١:١٧:٢١.٥٩١  --------------------------------------------------------------------------------  -  Edit - Script:55
  ١١:١٧:٢١.٥٩١  📝 محتوى السكربت:  -  Edit - Script:56
  ١١:١٧:٢١.٥٩١  while wait() do
	script.Parent.Color = Color3.fromHSV(tick()%5/5,1,1)
end
  -  Edit - Script:57
  ١١:١٧:٢١.٥٩١  ================================================================================  -  Edit - Script:58
  ١١:١٧:٢١.٥٩١  
================================================================================  -  Edit - Script:50
  ١١:١٧:٢١.٥٩١  🔹 اسم السكربت: Rainbow Script 5  -  Edit - Script:51
  ١١:١٧:٢١.٥٩٢  📍 المسار: Workspace.rainbow machine2.Cylinder.007.Rainbow Script 5  -  Edit - Script:52
  ١١:١٧:٢١.٥٩٢  📄 النوع: Script  -  Edit - Script:53
  ١١:١٧:٢١.٥٩٢  🔢 مفعّل: true  -  Edit - Script:54
  ١١:١٧:٢١.٥٩٢  --------------------------------------------------------------------------------  -  Edit - Script:55
  ١١:١٧:٢١.٥٩٢  📝 محتوى السكربت:  -  Edit - Script:56
  ١١:١٧:٢١.٥٩٢  while wait() do
	script.Parent.Color = Color3.fromHSV(tick()%5/5,1,1)
end
  -  Edit - Script:57
  ١١:١٧:٢١.٥٩٢  ================================================================================  -  Edit - Script:58
  ١١:١٧:٢١.٥٩٢  
================================================================================  -  Edit - Script:50
  ١١:١٧:٢١.٥٩٢  🔹 اسم السكربت: Rainbow Color Script3  -  Edit - Script:51
  ١١:١٧:٢١.٥٩٢  📍 المسار: Workspace.rainbow machine2.Cylinder.013.Rainbow Color Script3  -  Edit - Script:52
  ١١:١٧:٢١.٥٩٢  📄 النوع: Script  -  Edit - Script:53
  ١١:١٧:٢١.٥٩٣  🔢 مفعّل: true  -  Edit - Script:54
  ١١:١٧:٢١.٥٩٣  --------------------------------------------------------------------------------  -  Edit - Script:55
  ١١:١٧:٢١.٥٩٣  📝 محتوى السكربت:  -  Edit - Script:56
  ١١:١٧:٢١.٥٩٣  while wait() do
	script.Parent.Color = Color3.fromHSV(tick()%5/5,1,1)
end
  -  Edit - Script:57
  ١١:١٧:٢١.٥٩٣  ================================================================================  -  Edit - Script:58
  ١١:١٧:٢١.٥٩٣  
================================================================================  -  Edit - Script:50
  ١١:١٧:٢١.٥٩٣  🔹 اسم السكربت: Rainbow Color Script 2  -  Edit - Script:51
  ١١:١٧:٢١.٥٩٣  📍 المسار: Workspace.rainbow machine2.Cylinder.015.Rainbow Color Script 2  -  Edit - Script:52
  ١١:١٧:٢١.٥٩٣  📄 النوع: Script  -  Edit - Script:53
  ١١:١٧:٢١.٥٩٣  🔢 مفعّل: true  -  Edit - Script:54
  ١١:١٧:٢١.٥٩٤  --------------------------------------------------------------------------------  -  Edit - Script:55
  ١١:١٧:٢١.٥٩٤  📝 محتوى السكربت:  -  Edit - Script:56
  ١١:١٧:٢١.٥٩٤  while wait() do
	script.Parent.Color = Color3.fromHSV(tick()%5/5,1,1)
end
  -  Edit - Script:57
  ١١:١٧:٢١.٥٩٤  ================================================================================  -  Edit - Script:58
  ١١:١٧:٢١.٥٩٤  
================================================================================  -  Edit - Script:50
  ١١:١٧:٢١.٥٩٤  🔹 اسم السكربت: Script  -  Edit - Script:51
  ١١:١٧:٢١.٥٩٤  📍 المسار: Workspace.StealsBoard.Main.SurfaceGui.MainFrame.ScrollingFrame.Script  -  Edit - Script:52
  ١١:١٧:٢١.٥٩٤  📄 النوع: Script  -  Edit - Script:53
  ١١:١٧:٢١.٥٩٤  🔢 مفعّل: true  -  Edit - Script:54
  ١١:١٧:٢١.٥٩٤  --------------------------------------------------------------------------------  -  Edit - Script:55
  ١١:١٧:٢١.٥٩٤  📝 محتوى السكربت:  -  Edit - Script:56
  ١١:١٧:٢١.٥٩٥  -- True Global Steals Leaderboard Server Script (DataStore-based) - FIXED VERSION
-- Place this script directly IN the ScrollingFrame (script.Parent = ScrollingFrame)

local Players = game:GetService("Players")
local DataStoreService = game:GetService("DataStoreService")
local RunService = game:GetService("RunService")

-- Configuration
local MAX_PLAYERS = 100
local UPDATE_INTERVAL = 30
local SAVE_INTERVAL = 15 -- Increased from 5 to 15 seconds to reduce DataStore load
local MIN_CHANGE_THRESHOLD = 1 -- Save even on small changes to ensure names are updated
local POSITION_COLORS = {
	[1] = Color3.fromRGB(255, 215, 0),   -- Gold
	[2] = Color3.fromRGB(192, 192, 192), -- Silver  
	[3] = Color3.fromRGB(205, 127, 50),  -- Bronze
}
local DEFAULT_COLOR = Color3.fromRGB(255, 255, 255)

-- DataStore setup
local stealsOrderedStore = DataStoreService:GetOrderedDataStore("GlobalStealsLeaderboard")
local playerDataStore = DataStoreService:GetDataStore("PlayerStealsData")

-- UI references
local scrollingFrame = script.Parent
local template = scrollingFrame:WaitForChild("Template")

-- Cache and state management
local playerTemplates = {}
local isUpdating = false
local lastUpdateTime = 0
local lastSaveTime = 0
local playerStealsCache = {}
local saveQueue = {}
local isSaving = false

-- Optimized number formatting with cached results
local formatCache = {}
local function formatNumber(num)
	num = tonumber(num) or 0

	if formatCache[num] then
		return formatCache[num]
	end

	local result
	if num >= 1000000000000000000 then
		result = string.format("%.1fQ", num / 1000000000000000000)
	elseif num >= 1000000000000000 then
		result = string.format("%.1fQa", num / 1000000000000000)
	elseif num >= 1000000000000 then
		result = string.format("%.1fT", num / 1000000000000)
	elseif num >= 1000000000 then
		result = string.format("%.1fB", num / 1000000000)
	elseif num >= 1000000 then
		result = string.format("%.1fM", num / 1000000)
	elseif num >= 1000 then
		result = string.format("%.1fK", num / 1000)
	else
		result = string.format("%.0f", num)
	end

	formatCache[num] = result
	return result
end

-- Get player steals value efficiently
local function getPlayerSteals(player)
	local leaderstats = player:FindFirstChild("leaderstats")
	if leaderstats then
		local steals = leaderstats:FindFirstChild("Steals")
		return steals and tonumber(steals.Value) or 0
	end
	return 0
end

-- Save player steals to DataStore with throttling
local function savePlayerSteals(player, steals)
	if steals <= 0 then return end

	local userId = player.UserId
	local key = "Player_" .. userId

	-- Add to save queue instead of immediate save
	saveQueue[userId] = {
		player = player,
		steals = steals,
		timestamp = tick()
	}
end

-- Process save queue with throttling
local function processSaveQueue()
	local queueSize = 0
	for _ in pairs(saveQueue) do queueSize = queueSize + 1 end

	if isSaving or queueSize == 0 then return end

	isSaving = true
	local processedCount = 0
	local maxProcessPerBatch = 3 -- Reduced to be more conservative

	for userId, data in pairs(saveQueue) do
		if processedCount >= maxProcessPerBatch then break end

		local player = data.player
		local steals = data.steals

		-- Ensure player is still valid
		if not player or not player.Parent then
			saveQueue[userId] = nil
			continue
		end

		-- Save both datastores together
		task.spawn(function()
			-- Save player info FIRST
			local success1, err1 = pcall(function()
				playerDataStore:SetAsync("Player_" .. userId, {
					UserId = tonumber(userId),
					Username = player.Name,
					DisplayName = player.DisplayName or player.Name,
					LastUpdate = tick()
				})
			end)

			-- Save steals value to OrderedDataStore
			local success2, err2 = pcall(function()
				stealsOrderedStore:SetAsync(userId, steals)
			end)

			if not success1 then
				warn("Failed to save player data for " .. player.Name .. ": " .. tostring(err1))
			end

			if not success2 then
				warn("Failed to save steals value for " .. player.Name .. ": " .. tostring(err2))
			end

			-- Remove from queue after processing
			saveQueue[userId] = nil
		end)

		processedCount = processedCount + 1
		task.wait(0.2) -- Increased delay to be more conservative
	end

	isSaving = false
end

-- Get top players from DataStore (global)
local function getGlobalTopPlayers()
	local success, result = pcall(function()
		return stealsOrderedStore:GetSortedAsync(false, MAX_PLAYERS)
	end)

	if success and result then
		local topPlayers = {}
		local page = result:GetCurrentPage()

		for _, entry in ipairs(page) do
			local userId = tonumber(entry.key)
			local steals = entry.value

			if steals and steals > 0 and userId then
				local username = "Loading..."
				local displayName = ""

				-- Try multiple methods to get the name
				local nameFound = false

				-- Method 1: Check saved data first
				local dataSuccess, savedData = pcall(function()
					return playerDataStore:GetAsync("Player_" .. userId)
				end)

				if dataSuccess and savedData and savedData.Username and savedData.Username ~= "" then
					username = savedData.Username
					displayName = savedData.DisplayName or ""
					nameFound = true
				end

				-- Method 2: Check if player is online
				if not nameFound then
					local livePlayer = Players:GetPlayerByUserId(userId)
					if livePlayer then
						username = livePlayer.Name
						displayName = livePlayer.DisplayName or ""
						nameFound = true

						-- Save their data for next time
						task.spawn(function()
							pcall(function()
								playerDataStore:SetAsync("Player_" .. userId, {
									UserId = userId,
									Username = livePlayer.Name,
									DisplayName = livePlayer.DisplayName or "",
									LastUpdate = tick()
								})
							end)
						end)
					end
				end

				-- Method 3: Use Roblox API (last resort)
				if not nameFound then
					local nameSuccess, nameResult = pcall(function()
						return Players:GetNameFromUserIdAsync(userId)
					end)

					if nameSuccess and nameResult and nameResult ~= "" then
						username = nameResult
						displayName = nameResult
						nameFound = true

						-- Save for next time
						task.spawn(function()
							pcall(function()
								playerDataStore:SetAsync("Player_" .. userId, {
									UserId = userId,
									Username = nameResult,
									DisplayName = nameResult,
									LastUpdate = tick()
								})
							end)
						end)
					end
				end

				-- Final fallback
				if not nameFound then
					username = "Player " .. userId
				end

				table.insert(topPlayers, {
					userId = userId,
					username = username,
					displayName = displayName,
					steals = steals
				})
			end
		end

		return topPlayers
	else
		warn("Failed to get global leaderboard: " .. tostring(result))
		return {}
	end
end

-- Get avatar URL
local function getPlayerAvatarUrl(userId)
	return "rbxthumb://type=AvatarHeadShot&id=" .. userId .. "&w=150&h=150"
end

-- Apply position colors
local function applyPositionColors(templateClone, position)
	local color = POSITION_COLORS[position] or DEFAULT_COLOR

	local elements = {"Value", "NameLabel", "PositionLabel"}
	for _, elementName in ipairs(elements) do
		local element = templateClone:FindFirstChild(elementName)
		if element then
			element.TextColor3 = color
		end
	end

	-- Add golden glow for #1 position
	if position == 1 then
		local avatarImage = templateClone:FindFirstChild("AvatarImage")
		if avatarImage and not avatarImage:FindFirstChild("UIStroke") then
			local uiStroke = Instance.new("UIStroke")
			uiStroke.Color = Color3.fromRGB(255, 215, 0)
			uiStroke.Thickness = 3
			uiStroke.Parent = avatarImage
		end
	end
end

-- Create or update template for global player
local function createOrUpdateGlobalTemplate(playerData, position)
	local userId = playerData.userId
	local templateClone = playerTemplates[userId]

	if not templateClone then
		templateClone = template:Clone()
		templateClone.Name = "GlobalPlayer_" .. userId
		templateClone.Visible = true
		templateClone.Parent = scrollingFrame
		playerTemplates[userId] = templateClone
	end

	templateClone.LayoutOrder = position - 1

	-- Update template elements
	local valueLabel = templateClone:FindFirstChild("Value")
	local avatarImage = templateClone:FindFirstChild("AvatarImage")
	local nameLabel = templateClone:FindFirstChild("NameLabel")
	local positionLabel = templateClone:FindFirstChild("PositionLabel")

	if valueLabel then
		valueLabel.Text = formatNumber(playerData.steals) .. " Steals"
	end

	if avatarImage then
		avatarImage.Image = getPlayerAvatarUrl(userId)
	end

	if nameLabel then
		local displayName = playerData.displayName
		if displayName and displayName ~= "" and displayName ~= playerData.username then
			nameLabel.Text = displayName
		else
			nameLabel.Text = playerData.username
		end
	end

	if positionLabel then
		positionLabel.Text = "#" .. position
	end

	applyPositionColors(templateClone, position)
	return templateClone
end

-- Cleanup unused templates
local function cleanupTemplates(activePlayerIds)
	for userId, templateClone in pairs(playerTemplates) do
		if not activePlayerIds[userId] then
			if templateClone and templateClone.Parent then
				templateClone:Destroy()
			end
			playerTemplates[userId] = nil
		end
	end
end

-- Update global leaderboard from DataStore
local function updateGlobalLeaderboard()
	local currentTime = tick()
	if isUpdating or (currentTime - lastUpdateTime) < UPDATE_INTERVAL then 
		return 
	end

	isUpdating = true
	lastUpdateTime = currentTime

	-- Get global top players from DataStore
	local globalTopPlayers = getGlobalTopPlayers()
	local activePlayerIds = {}

	-- Update templates for global top players
	for position, playerData in ipairs(globalTopPlayers) do
		if playerData.userId then
			activePlayerIds[playerData.userId] = true
			local success, err = pcall(createOrUpdateGlobalTemplate, playerData, position)
			if not success then
				warn("Template update error:", err)
			end
		end
	end

	-- Cleanup unused templates
	cleanupTemplates(activePlayerIds)

	-- Update canvas size
	local listLayout = scrollingFrame:FindFirstChild("UIListLayout")
	if listLayout then
		scrollingFrame.CanvasSize = UDim2.new(0, 0, 0, listLayout.AbsoluteContentSize.Y + 10)
	end

	isUpdating = false
end

-- Save current server players' steals to DataStore with improved throttling
local function saveCurrentServerPlayers()
	local currentTime = tick()
	if (currentTime - lastSaveTime) < SAVE_INTERVAL then
		return
	end

	lastSaveTime = currentTime

	for _, player in pairs(Players:GetPlayers()) do
		if player and player.Parent then
			local steals = getPlayerSteals(player)
			local lastSteals = playerStealsCache[player.UserId] or 0

			-- Only save if steals changed significantly (reduces DataStore calls)
			if math.abs(steals - lastSteals) >= MIN_CHANGE_THRESHOLD then
				playerStealsCache[player.UserId] = steals
				savePlayerSteals(player, steals)
			end
		end
	end

	-- Process the save queue
	task.spawn(processSaveQueue)
end

-- Handle player events
local function onPlayerAdded(player)
	-- IMMEDIATELY save their name data
	task.spawn(function()
		local success, err = pcall(function()