-- ModuleScript: ServerScriptService/LobbyRound
-- Pure transition logic. No Roblox services, UI, rewards or matchmaking.
local LobbyRound = {}
LobbyRound.__index = LobbyRound
local function finite(n)
    return type(n) == "number" and n == n and n > -math.huge and n < math.huge
end
function LobbyRound.new(minPlayers, countdownSeconds, roundSeconds)
    assert(finite(minPlayers) and minPlayers >= 1 and minPlayers % 1 == 0, "Invalid minimum")
    assert(finite(countdownSeconds) and countdownSeconds > 0, "Invalid countdown")
    assert(finite(roundSeconds) and roundSeconds > 0, "Invalid round duration")
    return setmetatable({phase = "Waiting", minPlayers = minPlayers,
        countdownSeconds = countdownSeconds, roundSeconds = roundSeconds,
        participants = {}, deadline = nil, lastTime = nil}, LobbyRound)
end
function LobbyRound:step(now, readyIds)
    assert(finite(now) and (self.lastTime == nil or now >= self.lastTime), "Clock must not move backwards")
    self.lastTime = now
    local ids, seen = {}, {}
    for _, id in ipairs(readyIds) do
        assert(finite(id) and id % 1 == 0, "Expected integer player IDs")
        if not seen[id] then
            seen[id] = true
            table.insert(ids, id)
        end
    end
    table.sort(ids)
    local result = {}
    if self.phase == "Waiting" then
        if #ids >= self.minPlayers then
            self.phase = "Countdown"
            self.deadline = now + self.countdownSeconds
        end
    elseif self.phase == "Countdown" then
        if #ids < self.minPlayers then
            self.phase, self.deadline = "Waiting", nil
        elseif now >= self.deadline then
            self.phase = "Round"
            self.deadline = now + self.roundSeconds
            self.participants = ids
            result.startIds = table.clone(ids)
        end
    elseif self.phase == "Round" and now >= self.deadline then
        result.returnIds = table.clone(self.participants)
        self.phase, self.deadline, self.participants = "Waiting", nil, {}
    end
    result.phase = self.phase
    result.remaining = self.deadline and math.max(0, math.ceil(self.deadline - now)) or 0
    return result
end
return LobbyRound
