local Players = game:GetService("Players")
local NexusData = require(game.ServerScriptService.NexusData)

local Store = NexusData.CreateStore("NexusPatterns_v1", {
    Coins = 0,
    XP = 0,
    Inventory = {},
    Settings = { Music = true },
})

Players.PlayerAdded:Connect(function(player)
    local profile, err = Store:LoadProfileAsync(player.UserId)
    if not profile then
        player:Kick("Data failed to load. Please rejoin.")
        warn(err)
        return
    end

    profile:Increment("Coins", 10)
    profile:Set("XP", 100)
    profile:ArrayInsert("Inventory", "StarterSword")
    profile:Set("Settings", {
        Music = false,
    })

    local coins = profile:Get("Coins", 0)
    print("Coins:", coins)

    local updated = profile:Update("XP", function(currentXP)
        return (currentXP or 0) + 50
    end)
    print("XP:", updated)

    local ok, saveError = profile:Save()
    if not ok then warn(saveError) end
end)

Players.PlayerRemoving:Connect(function(player)
    Store:ReleaseProfile(player.UserId)
end)

game:BindToClose(function()
    NexusData.CloseAll()
end)
