-- Rack & Ruin: Chips.lua
-- Shared chip balances used by any betting game (Roulette, Lucky 7, etc).
-- Chips persist for the lifetime of the WoW session - they only reset when
-- you fully log out or /reload, not when you close/reopen a game window.
-- Your own chip count is broadcast to the table so it can be shown in the
-- Table Tracker window alongside everyone else's.

RackAndRuin = RackAndRuin or {}
RackAndRuin.Chips = RackAndRuin.Chips or {}

local Chips = RackAndRuin.Chips
local GAME_ID = "CHIPS"
local STARTING_CHIPS = 500

Chips.data = Chips.data or {} -- name -> chip count, session-lifetime only

local function RefreshTrackerIfPresent()
    if RackAndRuin.TableTracker_Refresh then
        RackAndRuin.TableTracker_Refresh()
    end
end

-- Returns a player's current chip count, initializing them to the starting
-- amount the first time they're seen this session.
function Chips.Get(name)
    name = name or UnitName("player")
    if Chips.data[name] == nil then
        Chips.data[name] = STARTING_CHIPS
    end
    return Chips.data[name]
end

-- Sets a player's chip count. Broadcasts to the table if this is your own
-- balance changing, so others' Table Trackers stay up to date.
function Chips.Set(name, value)
    Chips.data[name] = value
    if name == UnitName("player") then
        RackAndRuin.Net.Send(GAME_ID, "UPDATE", tostring(value))
    end
    RefreshTrackerIfPresent()
end

function Chips.Add(name, delta)
    Chips.Set(name, Chips.Get(name) + delta)
end

RackAndRuin.Net.RegisterHandler(GAME_ID, "UPDATE", function(sender, payload)
    local val = tonumber(payload)
    if val then
        Chips.data[sender] = val
        RefreshTrackerIfPresent()
    end
end)
