local Players = game:GetService("Players")
local DataStoreService = game:GetService("DataStoreService")

local DataStore = DataStoreService:GetDataStore("PlayerData_v1")

local DEFAULT_DATA = {
	Coins = 0
}

local function createData(player, data)
	local leaderstats = Instance.new("Folder")
	leaderstats.Name = "leaderstats"
	leaderstats.Parent = player

	local coins = Instance.new("IntValue")
	coins.Name = "Coins"
	coins.Value = data.Coins or DEFAULT_DATA.Coins
	coins.Parent = leaderstats
end

local function loadData(player)
	local success, data = pcall(function()
		return DataStore:GetAsync("Player_" .. player.UserId)
	end)

	if not success then
		warn("[DataSave] Failed to load " .. player.Name)
		data = nil
	end

	if typeof(data) ~= "table" then
		data = table.clone(DEFAULT_DATA)
	end

	createData(player, data)
end

local function saveData(player)
	local leaderstats = player:FindFirstChild("leaderstats")

	if not leaderstats then
		return
	end

	local coins = leaderstats:FindFirstChild("Coins")

	local data = {
		Coins = coins and coins.Value or 0
	}

	local success, errorMessage = pcall(function()
		DataStore:UpdateAsync("Player_" .. player.UserId, function()
			return data
		end)
	end)

	if not success then
		warn("[DataSave] Failed to save " .. player.Name .. ": " .. tostring(errorMessage))
	end
end

Players.PlayerAdded:Connect(loadData)

Players.PlayerRemoving:Connect(saveData)

game:BindToClose(function()
	for _, player in ipairs(Players:GetPlayers()) do
		task.spawn(saveData, player)
	end

	task.wait(3)
end)