﻿//#define HOLDEM_PROFILE

using UdonSharp;
using UnityEngine;
using VRC.SDKBase;
using UCS;

/// <summary>
/// Texas Holdem game state and logic.
/// room master runs the state transitions and logic.
/// /// </summary>
[UdonBehaviourSyncMode(BehaviourSyncMode.Manual)]
public class HoldemGame : UdonSharpBehaviour
{
    const int MAX_SEATS = 10;
    public int seats = 10;
    public HoldemPlayer[] players;
    public Sprite[] atlasSprites;

    
    public CardFlipController cardFlipController;
public AudioPoolPlayer cardFlipPlayer;

    public AudioPoolPlayer dingPlayer;
    public AudioPoolPlayer victoryPlayer;

    public HoldemProfiler profiler;



    // packed game state to fit through udon's networking. max 182 bytes as experimentally determined
    // in mahjong. TODO recheck assumptions, maybe it's better?
    [HideInInspector] [UdonSynced] string gameState0;
    [HideInInspector] [UdonSynced] string gameState1;

    [Header("Tournament Mode Settings")]
    [UdonSynced] public bool isTournamentMode = false;
    [UdonSynced] public bool isTournamentActive = false;
    [UdonSynced] public int tournamentBuyIn = 1000;
    [UdonSynced] public int tournamentStartingStack = 10000;
    [UdonSynced] public float tournamentLevelDurationSeconds = 600f; // 10 minutes
    public float eliminationBlindTimerCutSeconds = 300f; // 5 minutes
    [UdonSynced] public int currentBlindLevelIndex = 0;
    [UdonSynced] public int blindLevelStartMillis = 0;
    [UdonSynced] public bool[] tournamentEliminated = new bool[MAX_SEATS];
    [UdonSynced] public int[] playerRanks = new int[MAX_SEATS];
    [UdonSynced] public string[] tournamentPlayerNames = new string[MAX_SEATS];
    [UdonSynced] public int totalParticipants = 0;
    [UdonSynced] public int[] tournamentPlayerIds = new int[MAX_SEATS];

    private int[] tournamentBlindLevels = new int[] { 100, 200, 400, 800, 1600, 3200, 6400, 12800, 25600 };

    // How long every remaining player has to be away from their seat before an active
    // tournament is treated as abandoned and resolved on chip count.
    public int abandonedTournamentTimeoutSecs = 30;
    public bool noSeatedActiveArmed = false;
    public int noSeatedActiveSinceMillis = 0;

    private int[] seatWinnings = new int[MAX_SEATS];
    [UdonSynced] public bool[] wasSeated = new bool[MAX_SEATS];
    private int[] lastBankBalances = new int[MAX_SEATS];
    private int[] preTransitionStacks = new int[MAX_SEATS];
    // stacks as of the deal, used to order same-hand tournament bustouts. Distinct from
    // preTransitionStacks, which is refreshed every tick to drive the bank flush.
    [UdonSynced] public int[] handStartStacks = new int[MAX_SEATS];

    // Tracks the last processed rebuy version per seat so the master doesn't reprocess.
    private int[] lastRebuyVersion = new int[MAX_SEATS];

    private int[] preTransitionPlayerState = new int[MAX_SEATS];
    private int preTransitionTableState = TABLE_UNINITIALIZED;

    public int getWinningsForPlayerIdx(int idx)
    {
        return seatWinnings[idx];
    }

    private byte byt(int i)
    {
#if HOLDEM_DEBUG
        if (i < 0 || i > 255) Log($"{i} out of range");
#endif
        return (byte)i;
    }

    private uint unt(int i)
    {
#if HOLDEM_DEBUG
        if (i < 0) Log($"{i} negative, clamping to uint 0");
#endif
        return (uint)Mathf.Max(0, i);
    }

    private void DumpState()
    {
#if HOLDEM_DEBUG
        string s = $"now {GetTimeMillis()} epoch {epoch} state {tableState} bettingRound {bettingRound} headsUp {headsUp} " +
            $"dealer {dealerSeat} acting {actingSeat} \n" +
            $"{flop0} {flop1} {flop2} {turn} {river} \n" +
            $"bb {bigBlind} minRaise {minimumRaise} currentBet {currentBet} callOnly {callOnlyMask}\n" +
            $"last transition {lastTransitionMillis} elapsed {GetTimeMillis() - lastTransitionMillis}\n";

        for (int i = 0; i < seats; ++i)
        {
            s += $"seat {i} state {playerState[i]} " +
                $"seated {players[i].IsSeated()} ready {players[i].playerReady} commit {players[i].committedEpoch} " +
                $"hole0 {holeCards0[i]} hole1 {holeCards1[i]}" +
                $" stack {stacks[i]} potCon {potContribution[i]} roundCon {roundContribution[i]}\n";
        }
        Debug.Log(s);
#endif
    }

    private void SerializeState()
    {
        // increment epoch
        epoch = (epoch + 1) % 255;
        DumpState();

        byte[] buf = new byte[182];
        int n = 0;
        buf[n++] = byt(epoch);
        buf[n++] = byt(tableState);
        buf[n++] = byt(bettingRound);
        buf[n++] = (byte)(headsUp ? 1 : 0);
        buf[n++] = (byte)(wonByFold ? 1 : 0);
        buf[n++] = byt(dealerSeat);
        buf[n++] = byt(actingSeat);
        // Map seat -1 to 255 for byte storage
        buf[n++] = (byte)(aggressorSeat == -1 ? 255 : aggressorSeat);
        // Pack 10 bit winner mask into two bytes
        buf[n++] = byt(winnerMask & 255);        // Low 8 bits
        buf[n++] = byt((winnerMask >> 8) & 255); // High 2+ bits

        buf[n++] = byt(flop0);
        buf[n++] = byt(flop1);
        buf[n++] = byt(flop2);
        buf[n++] = byt(turn);
        buf[n++] = byt(river);

        WriteInt(unt(bigBlind), n, buf); n += 4;
        WriteInt(unt(minimumRaise), n, buf); n += 4;
        WriteInt(unt(currentBet), n, buf); n += 4;

        // XXX can't figure out how to write signed integers, so have this hack
        // lastTransitionMillis uses Networking.GetServerTImeMillis which seems to
        // go negative depending on the server instance?
        WriteInt(unt(Mathf.Abs(lastTransitionMillis)), n, buf); n += 4;
        buf[n++] = lastTransitionMillis >= 0 ? (byte)1 : (byte)0;

        for (int i = 0; i < seats; ++i)
        {
            // playerState only uses 0..3, so the short-all-in call-only bit rides in bit 2.
            // The packet is exactly full (182 bytes), so there's no room for a field of its own.
            buf[n++] = byt(playerState[i] | (((callOnlyMask >> i) & 1) << 2));

            buf[n++] = byt(holeCards0[i]);
            buf[n++] = byt(holeCards1[i]);

            // XXX +1 so I can use the -1 sentinel
            WriteInt(unt(Mathf.Max(-1, stacks[i]) + 1), n, buf); n += 4;
            WriteInt(unt(potContribution[i]), n, buf); n += 4;
            WriteInt(unt(roundContribution[i]), n,  buf); n += 4;
        }

        var frame = SerializeFrame(buf);
        gameState0 = new string(frame, 0, maxSyncedStringSize);
        gameState1 = new string(frame, maxSyncedStringSize, maxSyncedStringSize);
    }

    private void DeserializeState()
    {
        if (gameState0.Length != maxSyncedStringSize || gameState1.Length != maxSyncedStringSize) return;
        var frame = new char[maxPacketCharSize];
        gameState0.CopyTo(0, frame, 0, maxSyncedStringSize);
        gameState1.CopyTo(0, frame, gameState0.Length, maxSyncedStringSize);

        var buf = DeserializeFrame(frame);
        var n = 0;

        epoch = buf[n++];
        tableState = buf[n++];
        bettingRound = buf[n++];
        headsUp = buf[n++] > 0;
        wonByFold = buf[n++] > 0;
        dealerSeat = buf[n++];
        actingSeat = buf[n++];
        int rawAggressor = (int)buf[n++];
        aggressorSeat = (rawAggressor == 255 ? -1 : rawAggressor);
        // Unpack 10 bit winner mask
        int winnerMaskLow = buf[n++];
        int winnerMaskHigh = buf[n++];
        winnerMask = winnerMaskLow | (winnerMaskHigh << 8);

        flop0 = buf[n++];
        flop1 = buf[n++];
        flop2 = buf[n++];
        turn =  buf[n++];
        river = buf[n++];

        bigBlind = (int)ReadInt(n, buf); n += 4;
        minimumRaise = (int)ReadInt(n, buf); n += 4;
        currentBet = (int)ReadInt(n, buf); n += 4;

        // XXX that weird negative thing
        var transitionValue = (int)ReadInt(n, buf); n += 4;
        var transitionPositive = buf[n++] > 0;
        lastTransitionMillis = transitionPositive ? transitionValue : -transitionValue;


        callOnlyMask = 0;
        for (int i = 0; i < seats; ++i)
        {
            int packedState = buf[n++];
            playerState[i] = packedState & 3;
            if ((packedState & 4) != 0) callOnlyMask |= (1 << i);

            holeCards0[i] = buf[n++];
            holeCards1[i] = buf[n++];

            // XXX -1
            stacks[i] = (int)ReadInt(n, buf) - 1; n += 4;
            potContribution[i] = (int)ReadInt(n, buf); n += 4;
            roundContribution[i] = (int)ReadInt(n, buf); n += 4;
        }
    }
    
    // called when udon updates its synced variables
    override public void OnDeserialization()
    {
        if (!Networking.IsOwner(gameObject))
        {
            Debug.Log("[HoldemGame] OnDeserialization");
            DeserializeState();
        }
    }

    void WriteInt(uint i, int pos, byte[] buf)
    {
        buf[pos] = (byte)(i >> 24);
        buf[pos + 1] = (byte)((i >> 16) & 255);
        buf[pos + 2] = (byte)((i >> 8) & 255);
        buf[pos + 3] = (byte)(i & 255);
    }
    uint ReadInt(int n, byte[] buf)
    {
        uint pack = buf[n];
        pack = (pack << 8) + buf[n + 1];
        pack = (pack << 8) + buf[n + 2];
        pack = (pack << 8) + buf[n + 3];
        return pack;
    }

    private const int maxSyncedStringSize = 105;
    private const int maxPacketCharSize = maxSyncedStringSize * 2;
    // 14 bits leftover to do something with
    // possibly packing player id + seqNo to monitor per-player packet loss.
    private const int headerCharSize = 2;
    // for simplicity of the byte -> 7bit packing, which packs 7 bytes to 8 chars, 56 bits at a time
    // header size at 2 makes this a nice round 208 chars or 182 bytes
    private const int maxDataCharSize = (int)((maxPacketCharSize - headerCharSize) / 8f) * 8;
    private const int maxDataByteSize = maxDataCharSize / 8 * 7;

    private char[] SerializeFrame(byte[] buf)
    {
        var frame = new char[maxPacketCharSize];
        int n = 0;
        for (int i = 0; i < maxDataByteSize;)
        {
            // pack 7 bytes into 56 bits;
            ulong pack = buf[i++];
            pack = (pack << 8) + buf[i++];
            pack = (pack << 8) + buf[i++];

            pack = (pack << 8) + buf[i++];
            pack = (pack << 8) + buf[i++];
            pack = (pack << 8) + buf[i++];
            pack = (pack << 8) + buf[i++];
            //DebugLong("packed: ", pack);

            // unpack into 8 7bit asciis
            frame[n++] = (char)((pack >> 49) & (ulong)127);
            frame[n++] = (char)((pack >> 42) & (ulong)127);
            frame[n++] = (char)((pack >> 35) & (ulong)127);
            frame[n++] = (char)((pack >> 28) & (ulong)127);

            frame[n++] = (char)((pack >> 21) & (ulong)127);
            frame[n++] = (char)((pack >> 14) & (ulong)127);
            frame[n++] = (char)((pack >> 7) & (ulong)127);
            frame[n++] = (char)(pack & (ulong)127);
            //DebugChars("chars: ", chars, n - 8);
        }
        return frame;
    }

    private byte[] DeserializeFrame(char[] frame)
    {
        var packet = new byte[maxDataByteSize];
        int n = 0;
        for (int i = 0; i < maxDataByteSize;)
        {
            //DebugChars("deser: ", chars, n);
            // pack 8 asciis into 56 bits;
            ulong pack = frame[n++];
            pack = (pack << 7) + frame[n++];
            pack = (pack << 7) + frame[n++];
            pack = (pack << 7) + frame[n++];

            pack = (pack << 7) + frame[n++];
            pack = (pack << 7) + frame[n++];
            pack = (pack << 7) + frame[n++];
            pack = (pack << 7) + frame[n++];
            //DebugLong("unpacked: ", pack);

            // unpack into 7 bytes
            packet[i++] = (byte)((pack >> 48) & (ulong)255);
            packet[i++] = (byte)((pack >> 40) & (ulong)255);
            packet[i++] = (byte)((pack >> 32) & (ulong)255);
            packet[i++] = (byte)((pack >> 24) & (ulong)255);

            packet[i++] = (byte)((pack >> 16) & (ulong)255);
            packet[i++] = (byte)((pack >> 8) & (ulong)255);
            packet[i++] = (byte)((pack >> 0) & (ulong)255);
        }
        return packet;
    }

    public const int
        TABLE_UNINITIALIZED = 0,
        TABLE_IDLE = 1,
        TABLE_READY = 2,
        TABLE_PLAYING = 3,
        TABLE_WINNER = 5
        ;
    public int tableState = TABLE_UNINITIALIZED;

    public const int
        NOT_PLAYING = 0, PREFLOP = 1, FLOP = 2, TURN = 3, RIVER = 4, SHOWDOWN = 5;
    public int bettingRound = NOT_PLAYING;
    private int lastBettingRound = NOT_PLAYING;
    private int lastTableState = TABLE_UNINITIALIZED;

    // if in heads-up, no more player action possible so advance betting rounds on a timeout
    public bool headsUp = false;
    // all but one player folded; to avoid revealing cards in that case.
    public bool wonByFold = false;

    // tracking for card reveal logic
    [HideInInspector] public int aggressorSeat;
    [HideInInspector] public int winnerMask; // bitmask of winner seat indices

    public const int
        PLAYER_DEAD = 0,
        PLAYER_PENDING = 1,
        PLAYER_ACTING = 2,
        PLAYER_COMMITED = 3
        ;
    public int[] playerState = new int[MAX_SEATS];

    public int maxBuyIn = 100000;

    // as room master,
    // read external state (player, master-local UI, passage of time) and transition state,
    // serializing for other players.
    // for non-masters, the deserialization recovers the transition to play local animations and logs.
    public void Transition()
    {
#if HOLDEM_PROFILE
        profiler.Begin("HoldemGame.Transition");
        profiler.Begin("  Transition Pre-Check");
#endif
        bool[] playerIsSeated = new bool[MAX_SEATS];
        bool[] playerIsReady = new bool[MAX_SEATS];
        bool bReceivedBalanceUpdate = false;
        
        for (int i = 0; i < seats; i++)
        {
            var player = players[i];
            playerIsSeated[i] = player.IsSeated();
            playerIsReady[i] = player.playerReady && IsSeatBalanceReady(i);
            
            bool bIsSeatedAndReady = playerIsSeated[i] && IsSeatBalanceReady(i);

            if (isTournamentActive)
            {
                // In tournament mode, stacks are managed purely by game/tournament logic.
                // Do not update stacks from bank balance, and do not reset stacks to 0 if a player stands up/disconnects.
                if (bIsSeatedAndReady)
                {
                    lastBankBalances[i] = GetBalanceForSeat(i);
                }
            }
            else
            {
                if (bIsSeatedAndReady)
                {
                    int currentGlobalBalance = GetBalanceForSeat(i);
                    if (!wasSeated[i])
                    {
                        stacks[i] = Mathf.Min(currentGlobalBalance, maxBuyIn);
                        bReceivedBalanceUpdate = true;
                        wasSeated[i] = true;  // Mark as initialized only after successful setup
                    }
                    else
                    {
                        int externalDelta = currentGlobalBalance - lastBankBalances[i];
                        if (externalDelta < 0)
                        {
                            if (stacks[i] > currentGlobalBalance)
                            {
                                stacks[i] = Mathf.Max(currentGlobalBalance, 0);
                                bReceivedBalanceUpdate = true;
                            }
                        }
                        else if (externalDelta > 0)
                        {
                            if (currentGlobalBalance > 0)
                            {
                                stacks[i] = Mathf.Min(currentGlobalBalance, stacks[i] + externalDelta);
                                bReceivedBalanceUpdate = true;
                            }
                        }
                    }
                    lastBankBalances[i] = currentGlobalBalance;
                }
                else
                {
                    // Only reset stack and wasSeated if player actually left the table
                    // Don't reset if player is seated but balance just isn't ready yet (race condition)
                    if (!playerIsSeated[i])
                    {
                        stacks[i] = 0;
                        wasSeated[i] = false;
                    }
                    // If playerIsSeated[i] is true but bIsSeatedAndReady is false,
                    // it means balance isn't ready yet - leave stack as-is and keep wasSeated
                    // unchanged to allow initial setup to happen once balance becomes ready
                }
            }

            // Must be refreshed unconditionally, including down to 0. This is the baseline the
            // bank flush in UpdatePlayerBalances subtracts from, so leaving it stale on a busted
            // seat re-applies that seat's whole loss on every later state change. Bustout
            // ordering reads handStartStacks, not this.
            preTransitionStacks[i] = stacks[i];

            // Process rebuy (master only, cash game)
            if (!isTournamentActive && Networking.IsOwner(gameObject) &&
                player != null && player.rebuyVersion > lastRebuyVersion[i])
            {
                lastRebuyVersion[i] = player.rebuyVersion;
                int balance = GetBalanceForSeat(i);
                int target = Mathf.Min(balance, maxBuyIn);
                if (target > stacks[i])
                {
                    stacks[i] = target;
                    preTransitionStacks[i] = stacks[i];
                    lastBankBalances[i] = balance;
                    bReceivedBalanceUpdate = true;
                }
            }
        }

        if (isTournamentActive)
        {
            int totalActiveCount = 0;
            int seatedActiveCount = 0;
            for (int i = 0; i < seats; i++)
            {
                if (!tournamentEliminated[i])
                {
                    totalActiveCount++;
                    if (playerIsSeated[i])
                    {
                        seatedActiveCount++;
                    }
                }
            }

            // Nobody left sitting at all means the tournament has been abandoned; resolve it on
            // chip count instead of stalling forever with the buy-ins unrefunded. Held off by a
            // grace period on purpose: seats read as vacant for a tick or two during ordinary
            // joins, rejoins and ownership handoffs, and this must not fire on those.
            bool abandoned = false;
            if (totalActiveCount > 0 && seatedActiveCount == 0)
            {
                if (!noSeatedActiveArmed)
                {
                    noSeatedActiveArmed = true;
                    noSeatedActiveSinceMillis = GetTimeMillis();
                }
                abandoned = (GetTimeMillis() - noSeatedActiveSinceMillis) / 1000 > abandonedTournamentTimeoutSecs;
            }
            else
            {
                noSeatedActiveArmed = false;
            }

            if (totalActiveCount > 1 && (seatedActiveCount == 1 || abandoned))
            {
                int winnerSeat = -1;
                for (int i = 0; i < seats; i++)
                {
                    if (!tournamentEliminated[i] && playerIsSeated[i])
                    {
                        winnerSeat = i;
                        break;
                    }
                }

                if (winnerSeat == -1)
                {
                    for (int i = 0; i < seats; i++)
                    {
                        if (!tournamentEliminated[i] && (winnerSeat == -1 || stacks[i] > stacks[winnerSeat]))
                        {
                            winnerSeat = i;
                        }
                    }
                    Log($"Tournament abandoned with nobody seated; resolving on stack size. Winner: Seat {winnerSeat}");
                }

                if (winnerSeat != -1)
                {
                    int[] unseatedActiveSeats = new int[MAX_SEATS];
                    int unseatedCount = 0;
                    for (int i = 0; i < seats; i++)
                    {
                        if (!tournamentEliminated[i] && !playerIsSeated[i] && i != winnerSeat)
                        {
                            unseatedActiveSeats[unseatedCount] = i;
                            unseatedCount++;
                        }
                    }

                    // Selection sort: descending by stack size
                    for (int i = 0; i < unseatedCount - 1; i++)
                    {
                        for (int j = i + 1; j < unseatedCount; j++)
                        {
                            int seatI = unseatedActiveSeats[i];
                            int seatJ = unseatedActiveSeats[j];
                            if (stacks[seatI] < stacks[seatJ])
                            {
                                int temp = unseatedActiveSeats[i];
                                unseatedActiveSeats[i] = unseatedActiveSeats[j];
                                unseatedActiveSeats[j] = temp;
                            }
                        }
                    }

                    // Assign ranks starting from 2 to unseated active players
                    for (int i = 0; i < unseatedCount; i++)
                    {
                        int seatIdx = unseatedActiveSeats[i];
                        tournamentEliminated[seatIdx] = true;
                        playerRanks[seatIdx] = 2 + i;
                        Log($"Seat {seatIdx} left the join (unseated) and is ranked {playerRanks[seatIdx]} with stack {stacks[seatIdx]}");
                    }

                    playerRanks[winnerSeat] = 1;
                    Log($"Tournament Finished early! All but one player left. Winner: Seat {winnerSeat}");

                    DistributeTournamentPrizes(winnerSeat);

                    // Reset table and tournament state to IDLE
                    isTournamentActive = false;
                    for (int i = 0; i < seats; i++)
                    {
                        if (players[i] != null && players[i].IsSeated())
                        {
                            players[i].ReleaseControl();
                        }
                        wasSeated[i] = false; // Reset back to cash stack on next join
                        tournamentPlayerNames[i] = "";
                        tournamentPlayerIds[i] = 0;
                        playerState[i] = PLAYER_DEAD;
                        holeCards0[i] = 0;
                        holeCards1[i] = 0;
                        potContribution[i] = 0;
                        roundContribution[i] = 0;
                    }
                    bettingRound = NOT_PLAYING;
                    currentBet = 0;
                    minimumRaise = 0;
                    headsUp = false;
                    wonByFold = false;
                    aggressorSeat = -1;
                    winnerMask = 0;
                    tableState = TABLE_IDLE;

                    SerializeState();
                    RequestSerialization();
                    UpdatePlayerBalances();
                    UpdatePlayerMetrics();
                    return; // Early exit since tournament is finished and reset
                }
            }
        }

        preTransitionTableState = tableState;
        for (int i = 0; i < seats; ++i)
            preTransitionPlayerState[i] = playerState[i];

        var nowMillis = GetTimeMillis();
        var actingPlayerBet = players[actingSeat].bet;
        var actingPlayerCommited = players[actingSeat].committedEpoch == epoch;

        // Calculate dynamic big blind when starting a new game
        if (tableState == TABLE_READY)
        {
            if (isTournamentActive)
            {
                int timeElapsed = GetTimeMillis() - blindLevelStartMillis;
                if (timeElapsed >= tournamentLevelDurationSeconds * 1000)
                {
                    currentBlindLevelIndex++;
                    if (currentBlindLevelIndex >= tournamentBlindLevels.Length)
                    {
                        currentBlindLevelIndex = tournamentBlindLevels.Length - 1;
                    }
                    bigBlind = tournamentBlindLevels[currentBlindLevelIndex];
                    blindLevelStartMillis += (int)(tournamentLevelDurationSeconds * 1000);
                    Log($"Tournament blind level increased to Level {currentBlindLevelIndex + 1}. New BB: {bigBlind}");
                }
                else
                {
                    bigBlind = tournamentBlindLevels[currentBlindLevelIndex];
                }
            }
            else
            {
                // Build playerStackedAndReady array to calculate median
                bool[] playerStackedAndReady = new bool[MAX_SEATS];
                for (int i = 0; i < seats; i++)
                {
                    playerStackedAndReady[i] = playerIsSeated[i] && playerIsReady[i] && stacks[i] > 0;
                }
                int medianStack = CalculateMedianStack(stacks, playerStackedAndReady);
                bigBlind = CalculateBigBlindFromMedian(medianStack, bigBlindDivisor, minBigBlind);
                Log($"Calculated big blind: {bigBlind} from median stack {medianStack} with divisor {bigBlindDivisor}");
            }
        }

        // pack into pure state function
#if HOLDEM_PROFILE
        profiler.End(); // Transition Pre-Check
        profiler.Begin("  CalculateTransition");
#endif
        object[] newState = CalculateTransition(
            tableState, lastTransitionMillis, bettingRound, actingSeat, dealerSeat,
            currentBet, minimumRaise, headsUp, wonByFold,
            playerState, stacks, roundContribution, potContribution,
            flop0, flop1, flop2, turn, river, holeCards0, holeCards1,
            aggressorSeat, winnerMask,
             // external state
            nowMillis, bigBlind,
            winnerTimeoutSecs, readyTimeoutSecs,
            actionTimeoutSecs, headsUpTimeoutSecs,
            playerIsSeated, playerIsReady, bReceivedBalanceUpdate,
            actingPlayerBet, actingPlayerCommited,
            null /* deck for unit tests */
        );

        if (newState != null)
        {
            // and extract. not efficient but probably fine
            tableState = (int)newState[0];
            lastTransitionMillis = (int)newState[1];
            bettingRound = (int)newState[2];
            actingSeat = (int)newState[3];
            dealerSeat = (int)newState[4];

            currentBet = (int)newState[5];
            minimumRaise = (int)newState[6];
            headsUp = (bool)newState[7];
            wonByFold = (bool)newState[8];

            playerState = (int[])newState[9];
            stacks = (int[])newState[10];
            roundContribution = (int[])newState[11];
            potContribution = (int[])newState[12];

            flop0 = (int)newState[13];
            flop1 = (int)newState[14];
            flop2 = (int)newState[15];
            turn = (int)newState[16];
            river = (int)newState[17];
            holeCards0 = (int[])newState[18];
            holeCards1 = (int[])newState[19];
            aggressorSeat = (int)newState[20];
            winnerMask = (int)newState[21];
            callOnlyMask = (int)newState[22];
#if HOLDEM_PROFILE
            profiler.End(); // CalculateTransition
#endif

#if HOLDEM_PROFILE
            profiler.Begin("  SerializeState");
#endif
            SerializeState();
#if HOLDEM_PROFILE
            profiler.End(); // SerializeState
#endif
            RequestSerialization();

            //Flush delta between player balance and stack size to players now.
#if HOLDEM_PROFILE
            profiler.Begin("  UpdatePlayerBalances");
#endif
            UpdatePlayerBalances();
#if HOLDEM_PROFILE
            profiler.End(); // UpdatePlayerBalances
#endif

#if HOLDEM_PROFILE
            profiler.Begin("  UpdatePlayerMetrics");
#endif
            UpdatePlayerMetrics();
#if HOLDEM_PROFILE
            profiler.End(); // UpdatePlayerMetrics
#endif

            // Check for tournament eliminations after stack update (only at the end of a hand when pots are distributed)
            if (isTournamentActive && tableState == TABLE_WINNER)
            {
                int currentlyActive = 0;
                for (int i = 0; i < seats; i++)
                {
                    if (!tournamentEliminated[i]) currentlyActive++;
                }

                int[] newlyEliminated = new int[MAX_SEATS];
                int elimCount = 0;
                for (int i = 0; i < seats; i++)
                {
                    if (!tournamentEliminated[i] && stacks[i] <= 0)
                    {
                        newlyEliminated[elimCount++] = i;
                    }
                }

                if (elimCount > 0)
                {
                    // Sort newly eliminated ascending by their stack at the start of this hand.
                    // Whoever brought fewer chips to the hand busts first (worse rank).
                    for (int i = 0; i < elimCount - 1; i++)
                    {
                        for (int j = i + 1; j < elimCount; j++)
                        {
                            int seatI = newlyEliminated[i];
                            int seatJ = newlyEliminated[j];
                            if (handStartStacks[seatI] > handStartStacks[seatJ])
                            {
                                int temp = newlyEliminated[i];
                                newlyEliminated[i] = newlyEliminated[j];
                                newlyEliminated[j] = temp;
                            }
                        }
                    }

                    for (int i = 0; i < elimCount; i++)
                    {
                        int seatIdx = newlyEliminated[i];
                        tournamentEliminated[seatIdx] = true;
                        playerRanks[seatIdx] = currentlyActive;
                        currentlyActive--;
                        Log($"Seat {seatIdx} is eliminated in Rank {playerRanks[seatIdx]}!");
                        if (players[seatIdx] != null && players[seatIdx].IsSeated())
                        {
                            players[seatIdx].ReleaseControl();
                        }
                    }

                    blindLevelStartMillis -= elimCount * (int)(eliminationBlindTimerCutSeconds * 1000);
                }

                // Check if tournament is over
                if (currentlyActive <= 1)
                {
                    int winnerSeat = -1;
                    for (int i = 0; i < seats; i++)
                    {
                        if (!tournamentEliminated[i])
                        {
                            winnerSeat = i;
                            break;
                        }
                    }

                    if (winnerSeat != -1)
                    {
                        playerRanks[winnerSeat] = 1;
                        Log($"Tournament Finished! Winner: Seat {winnerSeat}");
                    }
                }
            }

            if (isTournamentActive && tableState == TABLE_IDLE)
            {
                int currentlyActive = 0;
                for (int i = 0; i < seats; i++)
                {
                    if (!tournamentEliminated[i]) currentlyActive++;
                }

                if (currentlyActive <= 1)
                {
                    int winnerSeat = -1;
                    for (int i = 0; i < seats; i++)
                    {
                        if (!tournamentEliminated[i])
                        {
                            winnerSeat = i;
                            break;
                        }
                    }

                    if (winnerSeat != -1)
                    {
                        playerRanks[winnerSeat] = 1;
                        DistributeTournamentPrizes(winnerSeat);
                    }

                    isTournamentActive = false;
                    for (int i = 0; i < seats; i++)
                    {
                        if (players[i] != null && players[i].IsSeated())
                        {
                            players[i].ReleaseControl();
                        }
                        wasSeated[i] = false; // Reset back to cash stack on next join
                        tournamentPlayerNames[i] = "";
                        tournamentPlayerIds[i] = 0;
                    }
                    SerializeState();
                    RequestSerialization();
                }
            }
        }
#if HOLDEM_PROFILE
        profiler.End(); // HoldemGame.Transition
#endif
    }

    // the whole thing but unit testable
    public object[] CalculateTransition(
            // internal state
            int tableState, int lastTransitionMillis, int bettingRound, int actingSeat, int dealerSeat,
            int currentBet, int minimumRaise, bool headsUp, bool wonByFold,
            // per player state, XXX mutated in place for simplicity
            int[] playerState, int[] stacks, int[] roundContribution, int[] potContribution,

            // deal
            int flop0, int flop1, int flop2, int turn, int river,
            int[] holeCards0, int[] holeCards1,
            int aggressorSeat, int winnerMask,

            // external state
            int nowMillis, int bigBlind,
            int winnerTimeoutSecs, int readyTimeoutSecs,
            int actionTimeoutSecs, int headsUpTimeoutSecs,
            bool[] playerIsSeated, bool[] playerIsReady, bool bReceivedBalanceUpdate,
            int actingPlayerBet, bool actingPlayerCommited,
            // XXX for unit testing, the deck that will be dealt from instead of random;
            // udon doesn't support seeding the RNG (outside of a small 32-bit int).
            // will be null in game
            int[] deck
        )
    {
        int newTableState = CalculateTableTransition(
                 tableState, lastTransitionMillis,
                 nowMillis, bettingRound, wonByFold, bigBlind, winnerTimeoutSecs,
                 readyTimeoutSecs, playerIsSeated, playerIsReady, stacks);
        bool changed = false;
        // set by whichever path moves us into TABLE_WINNER; the pot is awarded once, below.
        bool enteredWinner = false;

        if (newTableState != tableState)
        {
            Log($"table from {tableState} to {newTableState}");
            lastTransitionMillis = nowMillis;
            changed = true;

            // edge triggered stuff
            if (tableState == TABLE_READY && newTableState == TABLE_PLAYING)
            {
                bool[] playerStackedAndReady = new bool[MAX_SEATS];
                // initialize ready players
                for (int i = 0; i < seats; i++)
                {
                    preTransitionStacks[i] = stacks[i];
                    handStartStacks[i] = stacks[i];
                    bool isReadyPlayer = false;
                    if (isTournamentActive)
                    {
                        isReadyPlayer = !tournamentEliminated[i] && stacks[i] > 0;
                    }
                    else
                    {
                        isReadyPlayer = playerIsSeated[i] && playerIsReady[i] && stacks[i] >= bigBlind;
                    }

                    if (isReadyPlayer)
                    {
                        playerState[i] = PLAYER_PENDING;
                        playerStackedAndReady[i] = true;
                    }
                    else
                    {
                        playerState[i] = PLAYER_DEAD;
                    }
                    roundContribution[i] = 0;
                    potContribution[i] = 0;
                }
                Log($"game started, dealing game");

                var setup = SetupBlinds(
                    dealerSeat, bigBlind, playerState, stacks, roundContribution, playerStackedAndReady);
                actingSeat = (int)setup[0];
                dealerSeat = (int)setup[1];

                // XXX hack for unit testing; in-game will run shuffle
                if (deck == null) deck = ShuffleDeck();

                // deal all 10 seats and community cards
                int deal = 0;
                for (int i = 0; i < seats; ++i)
                {
                    holeCards0[i] = deck[deal++];
                    holeCards1[i] = deck[deal++];
                    // sort higher for nice display;
                    if (holeCards1[i] > holeCards0[i])
                    {
                        var swap = holeCards0[i];
                        holeCards0[i] = holeCards1[i];
                        holeCards1[i] = swap;
                    }
                }
                // burn cards per tradition
                deal++;
                flop0 = deck[deal++];
                flop1 = deck[deal++];
                flop2 = deck[deal++];
                deal++;
                turn = deck[deal++];
                deal++;
                river = deck[deal++];

                bettingRound = PREFLOP;
                currentBet = bigBlind;
                minimumRaise = bigBlind;
                callOnlyMask = 0;

                wonByFold = false;
                headsUp = false;
                winnerMask = 0;
                aggressorSeat = (int)setup[2];
            }
            if (newTableState == TABLE_WINNER)
            {
                // Paid out below, once, after the game transition has had its say.
                enteredWinner = true;
            }
            if (newTableState == TABLE_IDLE)
            {
                // Reset all player state when returning to idle
                Log("Resetting player state for idle");
                for (int i = 0; i < seats; i++)
                {
                    playerState[i] = PLAYER_DEAD;
                    holeCards0[i] = 0;
                    holeCards1[i] = 0;
                    potContribution[i] = 0;
                    roundContribution[i] = 0;
                }
                bettingRound = NOT_PLAYING;
                currentBet = 0;
                minimumRaise = 0;
                callOnlyMask = 0;
                headsUp = false;
                wonByFold = false;
                aggressorSeat = -1;
                winnerMask = 0;

                // Hide all community cards on idle (round end, all players left, etc.)
                if (cardFlipController != null) cardFlipController.ResetAllCards();
            }
        }
        tableState = newTableState;

        if (tableState == TABLE_PLAYING)
        {
            object[] newGameState = CalculateGameTransition(
                lastTransitionMillis, bettingRound, actingSeat,
                currentBet, minimumRaise, headsUp, playerState,
                stacks, roundContribution, potContribution,
                nowMillis,
                actionTimeoutSecs, headsUpTimeoutSecs, bigBlind, dealerSeat, playerIsSeated[actingSeat],
                actingPlayerBet, actingPlayerCommited, aggressorSeat, callOnlyMask);
            if (newGameState != null)
            {
                // have new state
                lastTransitionMillis = nowMillis;
                bettingRound = (int)newGameState[0];
                actingSeat = (int)newGameState[1];
                currentBet = (int)newGameState[2];
                minimumRaise = (int)newGameState[3];
                headsUp = (bool)newGameState[4];
                wonByFold = (bool)newGameState[5];
                aggressorSeat = (int)newGameState[10];
                callOnlyMask = (int)newGameState[11];
                if (wonByFold || bettingRound > RIVER)
                {
                    tableState = TABLE_WINNER;
                    enteredWinner = true;
                }
                // arrays got mutated by reference
                changed = true;
            }
        }

        // Award the pot on the tick the table enters TABLE_WINNER, whichever path got us
        // here. This has to run after the game transition above, because that's what closes
        // the final round (raking roundContribution into potContribution and marking folds).
        if (enteredWinner)
        {
            if (wonByFold)
            {
                // sweep it up
                int winner = -1;
                int winnings = 0;
                for (int i = 0; i < seats; i++)
                {
                    if (winner < 0 && playerState[i] != PLAYER_DEAD) winner = i;
                    winnings += potContribution[i];
                }
                if (winner >= 0)
                {
                    Log($"game won by {winner} by fold");
                    stacks[winner] += winnings;
                    winnerMask |= (1 << winner);
                }
            }
            else
            {
                Log($"game showdown.");
                ulong[] handValues = GetHandValues(
                    playerState, holeCards0, holeCards1, flop0, flop1, flop2, turn, river);
                int[] playerRanksByHandValues = RankPlayers(handValues);

                int[] winnings = DividePot(potContribution, playerRanksByHandValues, dealerSeat);
                for (int i = 0; i < seats; ++i)
                {
                    stacks[i] += winnings[i];
                    if (winnings[i] > 0) winnerMask |= (1 << i);
                }
            }
        }

        //If we received a balance update, always push an update to table state.
        changed = changed || bReceivedBalanceUpdate;

        if (changed)
        {
            return new object[] {
                tableState, lastTransitionMillis, bettingRound, actingSeat, dealerSeat,
                currentBet, minimumRaise, headsUp, wonByFold,
                playerState, stacks, roundContribution, potContribution,
                flop0, flop1, flop2, turn, river, holeCards0, holeCards1,
                aggressorSeat, winnerMask, callOnlyMask
            };
        } else
        {
            return null;
        }
    }
    private object[] SetupBlinds(
        int lastDealerSeat,
        int bigBlind, 
        // XXX mutated through
        int[] playerState, int[] stacks, int[] roundContribution,
        bool[] playerStackedAndReady)
    {
        var dealerSeat = NextReadySeat(lastDealerSeat, playerStackedAndReady);
               var littleBlindSeat = NextReadySeat(dealerSeat, playerStackedAndReady);
        var bigBlindSeat = NextReadySeat(littleBlindSeat, playerStackedAndReady);
        int actingSeat;
        // if only two players, then the dealer posts the small blind and dealer acts first before the flop.
        if (bigBlindSeat == dealerSeat)
        {
            bigBlindSeat = littleBlindSeat;
            littleBlindSeat = dealerSeat;

            actingSeat = dealerSeat;
        }
        else
        {
            actingSeat = NextReadySeat(bigBlindSeat, playerStackedAndReady);
        }
        Log($"dealer {dealerSeat}, little {littleBlindSeat} big {bigBlindSeat}");
        int aggressorSeat = bigBlindSeat;

        int sbPost = Mathf.Min(stacks[littleBlindSeat], bigBlind / 2);
        roundContribution[littleBlindSeat] = sbPost;
        stacks[littleBlindSeat] -= sbPost;

        int bbPost = Mathf.Min(stacks[bigBlindSeat], bigBlind);
        roundContribution[bigBlindSeat] = bbPost;
        stacks[bigBlindSeat] -= bbPost;

        playerState[actingSeat] = PLAYER_ACTING;
        return new object[]
        {
            actingSeat, dealerSeat, aggressorSeat
        };
    }

    private int NextReadySeat(int start, bool[] playerStackedAndReady)
    {
        int i = (start + 1) % seats;
        while (i != start)
        {
            if (playerStackedAndReady[i])
                return i;
            i = (i + 1) % seats;
        }
        return start;
    }

    // Calculate median stack from players who are ready and stacked
    private int CalculateMedianStack(int[] stacks, bool[] playerStackedAndReady)
    {
        // Collect all stacks from ready players
        int[] sortedStacks = new int[MAX_SEATS];
        int count = 0;
        for (int i = 0; i < seats; i++)
        {
            if (playerStackedAndReady[i])
            {
                sortedStacks[count++] = stacks[i];
            }
        }
        
        if (count == 0) return 0;
        
        // Sort the stacks
        for (int i = 1; i < count; i++)
        {
            int key = sortedStacks[i];
            int j = i - 1;
            while (j >= 0 && sortedStacks[j] > key)
            {
                sortedStacks[j + 1] = sortedStacks[j];
                j--;
            }
            sortedStacks[j + 1] = key;
        }
        
        // Return median (middle value for odd count, average of two middle for even)
        if (count % 2 == 1)
        {
            return sortedStacks[count / 2];
        }
        else
        {
            return (sortedStacks[count / 2 - 1] + sortedStacks[count / 2]) / 2;
        }
    }

    // Calculate big blind from median stack: round up to nearest 10
    private int CalculateBigBlindFromMedian(int medianStack, int divisor, int minBigBlind)
    {
        if (medianStack <= 0 || divisor <= 0) return minBigBlind;
        
        int rawBigBlind = medianStack / divisor;
        // Round up to nearest multiple of 10
        int roundedBigBlind = ((rawBigBlind + 9) / 10) * 10;
        
        // Ensure minimum big blind
        return Mathf.Max(roundedBigBlind, minBigBlind);
    }



    private int[] ShuffleDeck()
    {
        int[] deck = new int[52];
        for (int i = 0; i < 52; ++i)
        {
            deck[i] = i;
        }
        int swap;
        for (int i = 51; i >= 1; --i)
        {
            var j = Random.Range(0, i + 1); // range max is exclusive
            swap = deck[j];
            deck[j] = deck[i];
            deck[i] = swap;
        }
        return deck;
    }

    //CalculateTableTransition resolves what table state the current table should transition to.
    //The comment below mentions a tuple, but I think it was meant to be for CalculateGameTransition.
    
    // from the current internal state plus external state, the new state
    // packed into a tuple returns null if there's no serializable change.
    // plenty of garbage, but we're not doing it every frame at least.
    // "table" layer is idle/ready and stacks
    // idle --(players ready and stacked) --> ready --(timeout)--> playing --(win) --> win --(timeout)--> idle
    //  --(0 players seated)-->idle
    //  --(not playing and <2 players ready)-->idle
    public int CalculateTableTransition(
            // internal state
            int currentTableState, int lastTransitionMillis, 

            // external state
            int nowMillis, int bettingRound, bool wonByFold, int bigBlind, 
            int winnerTimeoutSecs, int readyTimeoutSecs, 
            bool[] playerIsSeated, bool[] playerIsReady, int[] stacks
        )
    {
        if (isTournamentMode && !isTournamentActive)
        {
            return TABLE_IDLE;
        }

        int readyAndStacked = 0;
        int seated = 0;
        if (isTournamentActive)
        {
            for (int i = 0; i < seats; ++i)
            {
                if (playerIsSeated[i]) seated++;
                if (!tournamentEliminated[i] && stacks[i] > 0) readyAndStacked++;
            }
        }
        else
        {
            for (int i = 0; i < seats; ++i)
            {
                if (playerIsSeated[i]) seated++;
                if (playerIsSeated[i] && playerIsReady[i] && stacks[i] >= bigBlind) readyAndStacked++;
            }
        }

        var elapsedSecs = (nowMillis - lastTransitionMillis) / 1000;
        switch (currentTableState)
        {
            case TABLE_UNINITIALIZED:
                Log($"initialized table");
                return TABLE_IDLE;
            case TABLE_IDLE:
                if (readyAndStacked > 1)
                {
                    Log($"{readyAndStacked} players ready and stacked, ready");
                    return TABLE_READY;
                }
                break;
            case TABLE_READY:
                if (readyAndStacked < 2)
                {
                    Log($"{readyAndStacked} players ready, need more, back to idle");
                    return TABLE_IDLE;
                }
                if (elapsedSecs > readyTimeoutSecs)
                {
                    Log($"{elapsedSecs} passed, time to deal");
                    return TABLE_PLAYING;
                }
                break;
            case TABLE_PLAYING:
                if (seated < 1)
                {
                    Log($"all players left, returning to idle");
                    return TABLE_IDLE;
                }
                if (bettingRound > RIVER || wonByFold)
                {
                    Log($"game state in winning state, table_winner");
                    return TABLE_WINNER;
                }
                break;
            case TABLE_WINNER:
                if (elapsedSecs > winnerTimeoutSecs)
                {
                    Log($"winner display timeout, returning to idle");
                    return TABLE_IDLE;
                }
                break;
        }
        return currentTableState;
    }

    // if table idle or table winner -> null
    // if table playing and not playing -> deal
    // if table playing and playing -> next
    // if table playing and showdown -> null

    // game state doesn't matter about cards until showdown

    // game is bettingRound/dealer/acting/bigBlind/currentBet/minRaise/stacks/round/pot/player(DEAD/PENDING/ACTING/COMMIT)/timeout


    // fixed game state on deal bigBlind, dealerSeat
    //
    // changing per round are bettingRound, playerState, stack/round/pot, actingSeat

    // cards not matter

    // can transition the acting player first, 
    //  ACTING --(not seated)-->DEAD
    //  ACTING --(timeout)--> DEAD
    //  ACTING --(valid commit)--> COMMMITED
    // 
    // only transition on acting player, the not_seated check can run on each individually
    // as in if a player leaves in the middle of a round, they're pending until they become acting, then they immediately fold


    
    // from the current internal state plus external state, the new state
    // packed into a tuple returns null if there's no serializable change.
    // plenty of garbage, but we're not doing it every frame at least.
    public object[] CalculateGameTransition(
            // internal state
            int lastTransitionMillis, int bettingRound, int actingSeat,
            int currentBet, int minimumRaise, bool headsUp,  
            // per player state, XXX mutated in place for simplicity
            int[] currentPlayerState,
            int[] stacks, int[] roundContribution, int[] potContribution,
            // external state
            int nowMillis,
            int actTimeoutSecs, int headsUpTimeoutSecs, int bigBlind, int dealerSeat, bool actingPlayerSeated,
            int actingPlayerBet, bool actingPlayerCommitted,
            int aggressorSeat, int callOnlyMask
        )
    {
        var elapsed = (nowMillis - lastTransitionMillis) / 1000;
        if (headsUp)
        {
            // XXX does check if players left/died during headsup (except for table check 0 players -> IDLE)
            // I could do a won-by-fold check here, but I think it'll otherwise work fine.
            if (elapsed < headsUpTimeoutSecs) return null;
            Log($"headsup timeout, round to {bettingRound + 1}");
            // increment round, change nothing else
            return new object[] {
                bettingRound + 1, 0, 0, 0, true, false,
                // all the same
                currentPlayerState, stacks, roundContribution, potContribution, aggressorSeat,
                callOnlyMask
            };
        }

        // waiting on acting player
        // A seat reopened by a short all-in owes the difference but has no raising rights,
        // so its only legal wager is the call (or a shove for less than the call).
        bool actingSeatIsCallOnly = ((callOnlyMask >> actingSeat) & 1) != 0;
        bool validBet = actingSeatIsCallOnly
            ? actingPlayerBet == Mathf.Min(currentBet - roundContribution[actingSeat], stacks[actingSeat])
            : actingPlayerBet <= stacks[actingSeat] &&
              (roundContribution[actingSeat] + actingPlayerBet == currentBet || // call/check
               actingPlayerBet == stacks[actingSeat] || // all in
               (roundContribution[actingSeat] + actingPlayerBet - currentBet) >= minimumRaise // (re) raise of appropriate size
              );

        // Explicit fold or player left - always fold
        if ((actingPlayerBet == -1 && actingPlayerCommitted) || !actingPlayerSeated)
        {
            Log($"acting player {actingSeat} folded or left");
            currentPlayerState[actingSeat] = PLAYER_DEAD;
            callOnlyMask &= ~(1 << actingSeat);
            // current bet and stacks stay the same
            // advance to next actor/round
        }
        // Timeout - auto-check if possible, otherwise fold
        else if (elapsed > actTimeoutSecs)
        {
            bool canCheck = roundContribution[actingSeat] == currentBet;
            if (canCheck)
            {
                Log($"acting player {actingSeat} timed out, auto-checking");
                currentPlayerState[actingSeat] = PLAYER_COMMITED;
                callOnlyMask &= ~(1 << actingSeat);
            }
            else
            {
                Log($"acting player {actingSeat} timed out, auto-folding (cannot check)");
                currentPlayerState[actingSeat] = PLAYER_DEAD;
                callOnlyMask &= ~(1 << actingSeat);
            }
        }
        else if (actingPlayerCommitted && validBet)
        {
            Log($"acting player {actingSeat} committed to bet of {actingPlayerBet}");
            // update currentBet, minimum raise, stacks/contribution
            stacks[actingSeat] -= actingPlayerBet;
            roundContribution[actingSeat] += actingPlayerBet;
            
            // if they bet more than the current, more action. if they simply
            // called/checked or went all-in below, no more action
            if (roundContribution[actingSeat] > currentBet)
            {
                int raiseDelta = roundContribution[actingSeat] - currentBet;
                currentBet = roundContribution[actingSeat];
                aggressorSeat = actingSeat;

                // Only ratchet up minimumRaise and reopen action if this raise is at least equal to minimumRaise
                if (raiseDelta >= minimumRaise)
                {
                    minimumRaise = raiseDelta;
                    Log($"acting player {actingSeat} raised to {minimumRaise}");

                    // a legal full raise reopens raising rights for everyone
                    callOnlyMask = 0;
                    // flip all previously COMMITED to PENDING if they have chips to bet;
                    for (int i = 0; i < seats; i++)
                    {
                        if (currentPlayerState[i] == PLAYER_COMMITED && stacks[i] > 0) 
                            currentPlayerState[i] = PLAYER_PENDING;
                    }
                }
                else
                {
                    Log($"acting player {actingSeat} short all-in for {raiseDelta} (below minRaise {minimumRaise})");
                    //call or fold decision for short raise
                    for (int i = 0; i < seats; i++)
                    {
                        if (currentPlayerState[i] == PLAYER_COMMITED && stacks[i] > 0
                            && roundContribution[i] < currentBet)
                        {
                            currentPlayerState[i] = PLAYER_PENDING;
                            callOnlyMask |= (1 << i);
                        }
                    }
                }
            }

            currentPlayerState[actingSeat] = PLAYER_COMMITED;
            callOnlyMask &= ~(1 << actingSeat);
        } else
        {
            return null; // waiting;
        }

        // if we're here, next action
        int nextActor = (actingSeat + 1) % seats;
        while (nextActor != actingSeat && currentPlayerState[nextActor] != PLAYER_PENDING)
            nextActor = (nextActor + 1) % seats;

        int alivePlayers = 0;
        for (int i = 0; i < seats; i++)
        {
            // if player has more chips to play
            if (currentPlayerState[i] != PLAYER_DEAD) alivePlayers++;
        }

        bool roundClosed = (nextActor == actingSeat) || alivePlayers < 2;
        if (roundClosed)
        {
            // call-only is a within-round restriction; the next street starts clean
            callOnlyMask = 0;
            int pendingPlayers = 0;
            // rake
            for (int i = 0; i < seats; i++)
            {
                potContribution[i] += roundContribution[i];
                roundContribution[i] = 0;
                // flip player to pending if they can still play
                if (bettingRound < RIVER && currentPlayerState[i] == PLAYER_COMMITED && stacks[i] > 0)
                {
                    currentPlayerState[i] = PLAYER_PENDING;
                    pendingPlayers++;
                }
            }
            Log($"round {bettingRound} over, {pendingPlayers} players pending, {alivePlayers} players alive");

            if (alivePlayers == 1)
            {
                // they won by fold ; keep betting round the same
                // Check this FIRST so winning by fold works on any betting round (including RIVER)
                return new object[] {
                    bettingRound, 0, 0, bigBlind, false, true /* wonByFold */,
                    currentPlayerState, stacks, roundContribution, potContribution, aggressorSeat,
                    callOnlyMask
                };
            }
            else if (bettingRound == RIVER)
            {
                // showdown
                return new object[] {
                    SHOWDOWN, 0, 0, bigBlind, false /* headsUp */, false /* wonByFold */,
                    currentPlayerState, stacks, roundContribution, potContribution, aggressorSeat,
                    callOnlyMask
                };
            } else if (pendingPlayers > 1) 
            {
                // regular new round
                int roundStart = (dealerSeat + 1) % seats;
                while (currentPlayerState[roundStart] != PLAYER_PENDING)
                    roundStart = (roundStart + 1) % seats;
                currentPlayerState[roundStart] = PLAYER_ACTING;

                return new object[] {
                    // most of this mutated in place.
                    bettingRound + 1, roundStart, 0, bigBlind, false /* headsUp */, false /* wonByFold */,
                    currentPlayerState, stacks, roundContribution, potContribution, aggressorSeat,
                    callOnlyMask
                };

            }
            else
            {
                // heads-up new round
                // flip players back to committed, no more action possible
                for (int i = 0; i < seats; i++)
                {
                    if (currentPlayerState[i] == PLAYER_PENDING) currentPlayerState[i] = PLAYER_COMMITED;
                }
                return new object[] {
                    bettingRound + 1, 
                    // doesn't matter
                    0, 0, bigBlind, true /* heads up */, false /* wonByFold */,
                    // mutated in place, and now fixed for the rest of the game
                    currentPlayerState, stacks, roundContribution, potContribution, aggressorSeat,
                    callOnlyMask
                };
            }
        }
        else
        {
            Log($"action moving to {nextActor} in round {bettingRound}");
            // same round, new player
            currentPlayerState[nextActor] = PLAYER_ACTING;
            return new object[] {
                // most of this mutated in place.
                bettingRound, nextActor, currentBet, minimumRaise, false /* headsUp */, false /* wonByFold */,
                currentPlayerState, stacks, roundContribution, potContribution, aggressorSeat,
                callOnlyMask
            };
        }
    }

    public int GetTimeMillis()
    {
        return Networking.LocalPlayer == null ? (int)(Time.time * 1000) :
             // XXX note that this doesn't really have any meaning, and can be negative
             // presumably remains consistent across an instance though
             Networking.GetServerTimeInMilliseconds();
    }

    public ulong[] GetHandValues(
            int[] playerState, int[] holeCards0, int[] holeCards1,
            int flop0, int flop1, int flop2, int turn, int river)
    {
        ulong[] handValues = new ulong[MAX_SEATS];
        for (int i = 0; i < seats; ++i)
        {
            if (playerState[i] != PLAYER_DEAD)
            {
                handValues[i] = BestPlayerHand(
                    holeCards0[i], holeCards1[i],
                    flop0, flop1, flop2, turn, river);
            } 
        }
        return handValues;
    }

    // returns 
    public int[] RankPlayers(ulong[] handValues)
    {
        ulong[] sortedHandValues = new ulong[MAX_SEATS];
        for (int i = 0; i < seats; ++i)
        {
            sortedHandValues[i] = handValues[i];
        }

        // sort descending
        for (int i = 1; i < seats; ++i)
        {
            int j = i - 1;
            ulong k = sortedHandValues[i];
            while (j >= 0 && sortedHandValues[j] < k)
            {
                sortedHandValues[j + 1] = sortedHandValues[j];
                j--;
            }
            sortedHandValues[j + 1] = k;
        }

        // write ranks. probably a way to do this within the sorting loop, but
        // I couldn't figure it out
        int[] playerRanksByHandValues = new int[MAX_SEATS];
        for (int i = 0; i < seats; ++i)
        {
            ulong value = handValues[i];
            if (value == 0UL)
            {
                playerRanksByHandValues[i] = -1; // Dead/Folded player
                continue;
            }
            int rank = -1;
            ulong last = ulong.MaxValue;
            for (int j = 0; j < seats; ++j)
            {
                ulong otherVal = sortedHandValues[j]; 
                if (otherVal == 0UL) break; // Exclude dead/folded players
                if (last != otherVal)
                {
                    rank++;
                    last = otherVal;
                }
                if (otherVal == value)
                {
                    playerRanksByHandValues[i] = rank;
                    break;
                }
            }
        }

        return playerRanksByHandValues;
    }

    public ulong BestPlayerHandSeat(int seat)
    {
        return BestPlayerHand(holeCards0[seat], holeCards1[seat], flop0, flop1, flop2, turn, river);
    }

    public ulong umax(ulong a, ulong b)
    {
        return a > b ? a : b;
    }

    // there are more efficient ways to do this yes.
    public ulong BestPlayerHand(int h0, int h1, int flop0, int flop1, int flop2, int turn, int river)
    {
        // 7 choose 5 = 21 combinations
 
        // both hole cards used (5 choose 3 = 10 combinations):
        ulong max =     EvaluateHand(h0, h1, flop0, flop1, flop2);
        max = umax(max, EvaluateHand(h0, h1, flop0, flop1, turn));  
        max = umax(max, EvaluateHand(h0, h1, flop0, flop1, river)); 
        max = umax(max, EvaluateHand(h0, h1, flop0, flop2, turn));
        max = umax(max, EvaluateHand(h0, h1, flop0, flop2, river)); 
        max = umax(max, EvaluateHand(h0, h1, flop0, turn, river));
        max = umax(max, EvaluateHand(h0, h1, flop1, flop2, turn));
        max = umax(max, EvaluateHand(h0, h1, flop1, flop2, river)); 
        max = umax(max, EvaluateHand(h0, h1, flop1, turn, river));
        max = umax(max, EvaluateHand(h0, h1, flop2, turn, river));

        // One hole card h0 used (5 choose 4 = 5 combinations):
        max = umax(max, EvaluateHand(h0, flop0, flop1, flop2, turn)); 
        max = umax(max, EvaluateHand(h0, flop0, flop1, flop2, river));
        max = umax(max, EvaluateHand(h0, flop0, flop1, turn, river)); 
        max = umax(max, EvaluateHand(h0, flop0, flop2, turn, river)); 
        max = umax(max, EvaluateHand(h0, flop1, flop2, turn, river)); 

        // One hole card h1 used (5 choose 4 = 5 combinations):
        max = umax(max, EvaluateHand(h1, flop0, flop1, flop2, turn));
        max = umax(max, EvaluateHand(h1, flop0, flop1, flop2, river));
        max = umax(max, EvaluateHand(h1, flop0, flop1, turn, river));
        max = umax(max, EvaluateHand(h1, flop0, flop2, turn, river));
        max = umax(max, EvaluateHand(h1, flop1, flop2, turn, river));

        // No hole cards (1 choose 1 = 1):
        max = umax(max, EvaluateHand(flop0, flop1, flop2, turn, river));

        return max;
    }

    public ulong BestPlayerHandTurnSeat(int seat)
    {
        return BestPlayerHandTurn(holeCards0[seat], holeCards1[seat], flop0, flop1, flop2, turn);
    }

 public ulong BestPlayerHandTurn(int h0, int h1, int flop0, int flop1, int flop2, int turn)
    {
        ulong max = EvaluateHand(h0, h1, flop0, flop1, flop2);
        max = umax(max, EvaluateHand(h0, h1, flop0, flop1, turn));
        max = umax(max, EvaluateHand(h0, h1, flop0, flop2, turn));
        max = umax(max, EvaluateHand(h0, h1, flop1, flop2, turn));
        max = umax(max, EvaluateHand(h0, flop0, flop1, flop2, turn));
        max = umax(max, EvaluateHand(h1, flop0, flop1, flop2, turn));
        return max;
    }
    
    public ulong BestPlayerHandFlop(int seat)
    {
        return EvaluateHand(holeCards0[seat], holeCards1[seat], flop0, flop1, flop2);
    }

    // Figure out split and side pots 
    public int[] DividePot(int[] contributions, int[] playerRanksByHandValues, int dealerSeat = 0)
    {
        int[] winnings = new int[MAX_SEATS];

        // Collect all unique non-zero contribution levels
        int numLevels = 0;
        int[] levels = new int[MAX_SEATS];
        for (int i = 0; i < seats; ++i)
        {
            int c = contributions[i];
            if (c > 0)
            {
                bool exists = false;
                for (int j = 0; j < numLevels; ++j)
                {
                    if (levels[j] == c)
                    {
                        exists = true;
                        break;
                    }
                }
                if (!exists)
                {
                    levels[numLevels++] = c;
                }
            }
        }

        // Sort levels ascending
        for (int i = 1; i < numLevels; ++i)
        {
            int k = levels[i];
            int j = i - 1;
            while (j >= 0 && levels[j] > k)
            {
                levels[j + 1] = levels[j];
                j--;
            }
            levels[j + 1] = k;
        }

        int prevCap = 0;
        for (int L = 0; L < numLevels; ++L)
        {
            int cap = levels[L];
            int layerPot = 0;

            // Calculate chips contributed to this layer (between prevCap and cap)
            for (int j = 0; j < seats; ++j)
            {
                if (contributions[j] > prevCap)
                {
                    layerPot += Mathf.Min(contributions[j], cap) - prevCap;
                }
            }

            if (layerPot <= 0)
            {
                prevCap = cap;
                continue;
            }

            // Find eligible active players who reached this cap (contributions[j] >= cap and rank >= 0)
            int bestRank = int.MaxValue;
            for (int j = 0; j < seats; ++j)
            {
                if (contributions[j] >= cap && playerRanksByHandValues[j] >= 0)
                {
                    if (playerRanksByHandValues[j] < bestRank)
                    {
                        bestRank = playerRanksByHandValues[j];
                    }
                }
            }

            int sharingCount = 0;
            int[] sharingPlayers = new int[MAX_SEATS];

            if (bestRank != int.MaxValue)
            {
                // Active players reached this cap: award layerPot to best rank among them (in positional order starting from Small Blind)
                for (int step = 0; step < seats; ++step)
                {
                    int j = (dealerSeat + 1 + step) % seats;
                    if (contributions[j] >= cap && playerRanksByHandValues[j] == bestRank)
                    {
                        sharingPlayers[sharingCount++] = j;
                    }
                }
            }
            else
            {
                // No active player reached this cap (uncollected chips from folded/dead players).
                // Award to active player(s) with best rank among those who reached the highest active contribution.
                int maxActiveContrib = 0;
                for (int j = 0; j < seats; ++j)
                {
                    if (playerRanksByHandValues[j] >= 0 && contributions[j] > maxActiveContrib)
                    {
                        maxActiveContrib = contributions[j];
                    }
                }

                int bestActiveRank = int.MaxValue;
                for (int j = 0; j < seats; ++j)
                {
                    if (playerRanksByHandValues[j] >= 0 && contributions[j] >= maxActiveContrib)
                    {
                        if (playerRanksByHandValues[j] < bestActiveRank)
                        {
                            bestActiveRank = playerRanksByHandValues[j];
                        }
                    }
                }

                if (bestActiveRank != int.MaxValue)
                {
                    for (int step = 0; step < seats; ++step)
                    {
                        int j = (dealerSeat + 1 + step) % seats;
                        if (playerRanksByHandValues[j] == bestActiveRank && contributions[j] >= maxActiveContrib)
                        {
                            sharingPlayers[sharingCount++] = j;
                        }
                    }
                }
            }

            if (sharingCount > 0)
            {
                int share = layerPot / sharingCount;
                int remainder = layerPot % sharingCount;

                for (int s = 0; s < sharingCount; ++s)
                {
                    winnings[sharingPlayers[s]] += share;
                }

                // Distribute remaining odd chips 1 by 1 in positional order
                for (int r = 0; r < remainder; ++r)
                {
                    winnings[sharingPlayers[r]] += 1;
                }
            }

            prevCap = cap;
        }

        return winnings;
    }


    public bool IsValidBet(int bet, int seatIdx)
    {
        // reopened with short all in
        if (((callOnlyMask >> seatIdx) & 1) != 0)
            return bet == Mathf.Min(currentBet - roundContribution[seatIdx], stacks[seatIdx]);

        return
            bet <= stacks[seatIdx] &&
            (roundContribution[seatIdx] + bet == currentBet || // call
             bet == stacks[seatIdx] || // all in
             (roundContribution[seatIdx] + bet - currentBet) >= minimumRaise // (re) raise of appropriate size
            );
    }
    // incrementing int of current state, used to check that seat commits are for the current action
    public int epoch = 0;

    // the last time something happened, used for timeouts.
    public int lastTransitionMillis;

    public int bigBlind = 50;
    public int bigBlindDivisor = 75;
    public int minBigBlind = 10;

    // chip count per seat
    public int[] stacks = new int[MAX_SEATS];

    // two parallel arrays for seats's hole cards. int[][] bad in udon
    public int[] holeCards0 = new int[MAX_SEATS];
    public int[] holeCards1 = new int[MAX_SEATS];

    // community cards
    int flop0, flop1, flop2, turn, river;

    // in most states, the seat idx that currently needs to act
    public int actingSeat = 2;
    // dealer seat index
    public int dealerSeat = 0;

    // betting round state tracking
    // keep track of total pot contributions per seat for side pots
    public int[] potContribution = new int[MAX_SEATS];
    // current bet to match
    public int currentBet = 0;
    // current minimum raise
    public int minimumRaise = 0;

    // call only mask for short all in
    public int callOnlyMask = 0;

    // per-seat bet/call for the round
    public int[] roundContribution = new int[MAX_SEATS];

    // round over if current seat is CHECKED/CALLED/(RE)RAISED/ALLIN and all
    // other seats are not WAITING.

    // how long after ready before next round
    int readyTimeoutSecs = 5;
    // how long to display headsup rounds
    int headsUpTimeoutSecs = 3;
    // how long to display winner
    public int winnerTimeoutSecs = 10;

    // how long to wait for seat action before folding them
    public int actionTimeoutSecs = 16;

    public UdonChips udonChips;

    public int initialStackSize = 1000;

    public UnityEngine.UI.Text uiPot, uiGameStatus, uiRoundStatus, uiDebugToggleText;
    public UnityEngine.UI.Text uiTournamentSettingsInfo;
    public GameObject goDebug;

    public GameObject tournamentGameObject;

    public UnityEngine.UI.Toggle uiDebugToggle;

    public PokerChipPile potPile;

    const float updateInterval = 0.5f;
    private float ownerUpdateCountdown = 0;

    private int lastLocalEpoch = -1;

    // Bumped when a seat's activePlayerId changes (join/leave/disconnect takeover), so the
    // HoldemPlayer seatedAnywhere cache can invalidate on seat membership, not just game epoch.
    public int seatChangeVersion = 0;

    private string winnerText = "winnerText";

    private void Start()
    {
        for (int i = 0; i < seats; ++i)
        {
            players[i].game = this;
            players[i].seatIdx = i;
        }
    }

    private void Update()
    {
#if HOLDEM_PROFILE
        profiler.Begin("Game.Update");
#endif

        // Detect betting round transitions and reveal community cards.
        // Uses cumulative range checks so late-joining players see every card
        // dealt up to the current round, not just the latest one.
        if (bettingRound != lastBettingRound)
        {
            int oldRound = lastBettingRound;
            lastBettingRound = bettingRound;

            if (bettingRound == PREFLOP)
            {
                Debug.Log("Playing ding sound");
                dingPlayer.Play();
            }

            if (bettingRound == FLOP || bettingRound == TURN || bettingRound == RIVER)
            {
                Debug.Log("Playing flip card sound");
                cardFlipPlayer.Play();
            }

            if (cardFlipController != null)
            {
                // Cumulative reveals: if we're past a deal point but hadn't
                // yet processed it (including on late join), reveal it now.
                if (bettingRound >= FLOP && oldRound < FLOP)
                    cardFlipController.RevealFlop(flop0, flop1, flop2);
                if (bettingRound >= TURN && oldRound < TURN)
                    cardFlipController.RevealTurn(turn);
                if (bettingRound >= RIVER && oldRound < RIVER)
                    cardFlipController.RevealRiver(river);
            }
        }

        // Keyed off the table state rather than bettingRound: a fold win leaves bettingRound
        // untouched, so hanging this off the block above meant it never fired for fold wins.
        if (tableState != lastTableState)
        {
            lastTableState = tableState;
            if (tableState == TABLE_PLAYING)
            {
                // Play deal animation on active hands. Index starts at 0 for actingSeat
                // (first to act in preflop) and increments for subsequent active players.
                int dealIndex = 0;
                for (int i = 0; i < seats; i++)
                {
                    int seat = (actingSeat + i) % seats;
                    if (playerState[seat] != PLAYER_DEAD)
                    {
                        if (players[seat] != null && players[seat].grabbableHand != null)
                        {
                            players[seat].grabbableHand.DealCards(dealIndex);
                        }
                        dealIndex++;
                    }
                }
            }

            if (tableState == TABLE_WINNER)
            {
                Debug.Log("Playing victory sound");
                victoryPlayer.Play();
            }
            // Hide community cards when transitioning to idle (covers non-owner clients
            // who receive state via serialisation rather than running Transition directly).
            if (tableState == TABLE_IDLE)
            {
                if (cardFlipController != null) cardFlipController.ResetAllCards();
                // Return to idle animation on all player cards
                for (int i = 0; i < seats; i++)
                {
                    if (players[i] != null && players[i].grabbableHand != null)
                    {
                        players[i].grabbableHand.ReturnToIdleAnimation();
                    }
                }
            }
        }

        var now = GetTimeMillis();

        int readyAndStacked = 0;
        int seated = 0;
        int pending = 0;
        int commited = 0;
        int inPlay = 0;
        for (int i = 0; i < seats; ++i)
        {
            if (players[i].IsSeated() || (isTournamentActive && !tournamentEliminated[i]))
            {
                if (players[i].IsSeated()) seated++;
                
                bool isPlayerActiveInTournament = isTournamentActive && !tournamentEliminated[i] && stacks[i] > 0;
                bool isPlayerReadyForCash = !isTournamentActive && players[i].playerReady && stacks[i] >= bigBlind;
                
                if (isPlayerActiveInTournament || isPlayerReadyForCash) readyAndStacked++;
                if (playerState[i] != PLAYER_DEAD) inPlay++;
                if (playerState[i] == PLAYER_PENDING) pending++;
                if (playerState[i] == PLAYER_COMMITED) commited++;
            }
        }

        var since = (now - lastTransitionMillis) / 1000;

#if HOLDEM_PROFILE
        profiler.Begin("  UI Status Text");
#endif
        if (isTournamentActive)
        {
            int levelRemainingSeconds = Mathf.Max(0, (int)(tournamentLevelDurationSeconds - (now - blindLevelStartMillis) / 1000));
            string timeStr = $"{levelRemainingSeconds / 60}m {levelRemainingSeconds % 60}s";
            int remainingPlayers = 0;
            int totalParts = 0;
            for (int i = 0; i < seats; i++)
            {
                if (playerRanks[i] > 0 || !tournamentEliminated[i]) totalParts++;
                if (!tournamentEliminated[i]) remainingPlayers++;
            }

            uiGameStatus.text = $"[TOURNAMENT] Level {currentBlindLevelIndex + 1} (Blinds {bigBlind/2}/{bigBlind}) - Next level in {timeStr} - Players: {remainingPlayers}/{totalParts}\n" + 
                (tableState == TABLE_PLAYING ? 
                  ((bettingRound == PREFLOP ? "Pre-Flop" :
                   bettingRound == FLOP ? "Flop" :
                   bettingRound == TURN ? "Turn" : "River"
                  ) + (headsUp ? $" (Heads-Up, next round in {headsUpTimeoutSecs - since}s)" :
                  $" ({OwnerName(players[actingSeat].gameObject)} has {actionTimeoutSecs - since}s to act)")) :
                tableState == TABLE_READY ? $"Ready... Dealing in {readyTimeoutSecs - since}s" :
                tableState == TABLE_IDLE ? "Lobby / Pre-Hand" :
                winnerText + $"\nNext hand in {winnerTimeoutSecs - since}s...");
        }
        else if (isTournamentMode && !isTournamentActive)
        {
            uiGameStatus.text = $"[TOURNAMENT LOBBY] Seated: {seated}\n" +
                $"Buy-in: {tournamentBuyIn} | Starting Stack: {tournamentStartingStack}\n" +
                $"Waiting for Master to start...";
        }
        else
        {
            uiGameStatus.text =
                tableState == TABLE_UNINITIALIZED ? "Uninitialized" :
                tableState == TABLE_IDLE ? $"Idle ({readyAndStacked} players ready)\n" :
                tableState == TABLE_READY ? 
                  $"{readyAndStacked} players ready. Dealing in {readyTimeoutSecs - since}..." :
                tableState == TABLE_PLAYING ? ((
                  bettingRound == PREFLOP ? "Pre-Flop" :
                  bettingRound == FLOP ? "Flop" :
                  bettingRound == TURN ? "Turn" : "River"
                    ) + (headsUp ? $" (Heads-Up, next round in {headsUpTimeoutSecs - since})" :
                    $" ({OwnerName(players[actingSeat].gameObject)} has {actionTimeoutSecs - since} to act)")) :
                winnerText + $"\nNext game in {winnerTimeoutSecs - since}...";
        }
        int potTotal = 0, roundTotal = 0;
        for (int i = 0; i < seats; ++i)
        {
            potTotal += potContribution[i];
            roundTotal += roundContribution[i];
        }

        // set player round pots
        for (int i = 0; i < seats; i++)
        {
            players[i].roundContributionPile.SetTotalChips(roundContribution[i]);
        }

        uiPot.text = $"{potTotal} (+{roundTotal} round)";
        uiRoundStatus.text = $"Current Bet: {currentBet} Min-raise: {minimumRaise}\n" +
            $"{inPlay} players, {pending} to act, {commited} commited";
#if HOLDEM_PROFILE
        profiler.End(); // UI Status Text
#endif

        if (uiTournamentSettingsInfo != null)
        {
            uiTournamentSettingsInfo.text = $"Tournament Mode: {(isTournamentMode ? "ENABLED" : "DISABLED")}\n" +
                $"Buy-In: {tournamentBuyIn} chips\n" +
                $"Starting Stack: {tournamentStartingStack} chips\n" +
                $"Status: {(isTournamentActive ? "ACTIVE" : "LOBBY")}";
        }
        var dealt = tableState == TABLE_PLAYING || tableState == TABLE_WINNER;
        uiPot.enabled = dealt;
        uiRoundStatus.enabled = dealt;

#if HOLDEM_PROFILE
        profiler.Begin("  Per-Seat UI Loop");
#endif
        bool flopped = dealt && bettingRound >= FLOP;

        if (dealt)
        {
            bool splitWinnings = false;
            for (int idx = 0; idx < seats; idx++)
            {
                players[idx].playerPotPile.SetTotalChips(seatWinnings[idx]);
                if (seatWinnings[idx] > 0)
                {
                    splitWinnings = true;
                    players[idx].MovePotPile(potPile.transform);
                }
            }
            if (splitWinnings)
                potPile.SetTotalChips(0);
            else
                potPile.SetTotalChips(potTotal);
        }
#if HOLDEM_PROFILE
        profiler.End(); // Per-Seat UI Loop
#endif

#if HOLDEM_DEBUG
        uiDebugToggleText.text = $"Enable Debug (Master: {OwnerName(gameObject)})";
#endif

        bool isOwner = Networking.IsOwner(gameObject);

#if HOLDEM_DEBUG
        // Sync toggle button visibility
        if (uiDebugToggle != null && uiDebugToggle.gameObject.activeSelf != isOwner)
        {
            uiDebugToggle.gameObject.SetActive(isOwner);
        }
#endif

#if HOLDEM_PROFILE
        profiler.Begin("  Owner Tick & Debug");
#endif
        if (goDebug != null)
        {
            if (isOwner)
            {
                if (!goDebug.activeSelf)
                {
                    goDebug.SetActive(true);
                }

#if HOLDEM_DEBUG
                // Toggle MasterDebug panel based on toggle status
                Transform masterDebug = goDebug.transform.Find("MasterDebug");
                if (masterDebug != null && masterDebug.gameObject.activeSelf != uiDebugToggle.isOn)
                {
                    masterDebug.gameObject.SetActive(uiDebugToggle.isOn);
                }

                // The Log and DebugToggleText should be active
                Transform logTrans = goDebug.transform.Find("Log");
                if (logTrans != null && !logTrans.gameObject.activeSelf)
                {
                    logTrans.gameObject.SetActive(true);
                }
                if (uiDebugToggleText != null && !uiDebugToggleText.gameObject.activeSelf)
                {
                    uiDebugToggleText.gameObject.SetActive(true);
                }
#endif
            }
            else
            {
                if (goDebug.activeSelf)
                {
                    goDebug.SetActive(false);
                }
            }
        }

        if (tournamentGameObject != null)
        {
            tournamentGameObject.SetActive(isOwner);
        }

        if (isOwner)
        {

            if ((ownerUpdateCountdown -= Time.deltaTime) < 0)
            {
                ownerUpdateCountdown = updateInterval;
                Transition();
            }
        }
#if HOLDEM_PROFILE
        profiler.End(); // Owner Tick & Debug
#endif

        // local stuff
        if (lastLocalEpoch != epoch)
        {
#if HOLDEM_PROFILE
            profiler.Begin("  Epoch Change");
#endif
            lastLocalEpoch = epoch;
#if HOLDEM_DEBUG
            if (!Networking.IsOwner(gameObject))
            {
                string s =
                    $"new state: now {now} epoch {epoch} state {tableState} bettingRound {bettingRound} headsUp {headsUp}\n" +
                    $"dealer {dealerSeat} acting {actingSeat}\n" +
                    $"bb {bigBlind} minRaise {minimumRaise} currentBet {currentBet} callOnly {callOnlyMask}\n" +
                    $"last transition {lastTransitionMillis} elapsed {now - lastTransitionMillis}\n" +
                    $"playerState [{JoinIntArray(playerState)}]\n" +
                    $"stacks [{JoinIntArray(stacks)}]\n" +
                    $"potCon [{JoinIntArray(potContribution)}]\n" +
                    $"roundCon [{JoinIntArray(roundContribution)}]\n" +
                    $"";
                Log(s);
            }
#endif
            // edge-triggered stuff
            if (tableState == TABLE_WINNER)
            {
                winnerText = "";
                ulong[] handValues;
                if (wonByFold)
                {
                    seatWinnings = new int[MAX_SEATS];
                    int winner = -1;
                    int foldWinnings = 0;
                    for (int i = 0; i < seats; i++)
                    {
                        foldWinnings += potContribution[i];
                        if (winner < 0 && playerState[i] != PLAYER_DEAD) { winner = i; }
                    }
                    if (winner >= 0)
                    {
                        seatWinnings[winner] = foldWinnings;
                    }
                    handValues = null;
                } else
                {
                    handValues = GetHandValues(
                        playerState, holeCards0, holeCards1, flop0, flop1, flop2, turn, river);
                    int[] playerRanksByHandValues = RankPlayers(handValues);
                    seatWinnings = DividePot(potContribution, playerRanksByHandValues, dealerSeat);
                }
                for (int i = 0; i < seats; ++i)
                {
                    if (playerState[i] != PLAYER_DEAD && seatWinnings[i] > 0)
                    {
                        winnerText += $"{OwnerName(players[i].gameObject)} wins {seatWinnings[i]}";
                        if (!wonByFold)
                        {
                            winnerText += $" with {HandClass(handValues[i])}";
                        }
                        winnerText += "\n";
                    }
                    Log(winnerText);
                }
            }

            if (tableState == TABLE_IDLE || tableState == TABLE_READY)
            {
                seatWinnings = new int[MAX_SEATS];
                for (int i = 0; i < seats; i++)
                {
                    seatWinnings[i] = 0;
                }
            }
#if HOLDEM_PROFILE
            profiler.End(); // Epoch Change
#endif
        }
#if HOLDEM_PROFILE
        profiler.End(); // HoldemGame.Update
#endif
    }

    string JoinIntArray(int[] arr)
    {
        if (arr == null || arr.Length == 0)
            return "";

        string result = arr[0].ToString();
        for (int i = 1; i < arr.Length; i++)
        {
            result += "," + arr[i];
        }
        return result;
    }

    private string OwnerName(GameObject obj)
    {
        var owner = Networking.GetOwner(obj);
        if (owner == null) return "(Editor)";
        return owner.displayName;
    }

    public void OnPlayerLeft(VRCPlayerApi player)
    {
        // try and pick up change early;
        if (Networking.IsOwner(gameObject)) Transition();

    }

    private string[] ranks = new string[] { "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A" };

    public Sprite spritecard(int card)
    {
        return atlasSprites[card];
    }

    // there are better evaluators in:
    // https://www.codingthewheel.com/archives/poker-hand-evaluator-roundup/
    // but this one is mine, and I don't think I stuff any of the table-based lookups
    // into the udon heap reasonably.
    public ulong EvaluateHand(int a, int b, int c, int d, int e)
    {
        int swap, r0, r1, r2, r3, r4;
        // flush check
        bool flush = true;
        int suit = a / 13;
        if (b / 13 != suit) flush = false;
        else if (c / 13 != suit) flush = false;
        else if (d / 13 != suit) flush = false;
        else if (e / 13 != suit) flush = false;
        // rank sort 
        // 2 bias to diasambiguate "no pair" from 2, 
        // and get numeral cards to line up (2=2, 10=10, 11=J, 12=Q, 13=K, 14=A)
        r0 = a % 13 + 2; 
        r1 = b % 13 + 2;
        if (r0 > r1) { swap = r1; r1 = r0; r0 = swap; }
        r2 = c % 13 + 2;
        if (r1 > r2)
        {
            swap = r2; r2 = r1; r1 = swap;
            if (r0 > r1) { swap = r1; r1 = r0; r0 = swap; }
        }
        r3 = d % 13 + 2;
        if (r2 > r3)
        {
            swap = r3; r3 = r2; r2 = swap;
            if (r1 > r2)
            {
                swap = r2; r2 = r1; r1 = swap;
                if (r0 > r1) { swap = r1; r1 = r0; r0 = swap; }
            }
        }
        r4 = e % 13 + 2;
        if (r3 > r4)
        {
            swap = r4; r4 = r3; r3 = swap;
            if (r2 > r3)
            {
                swap = r3; r3 = r2; r2 = swap;
                if (r1 > r2)
                {
                    swap = r2; r2 = r1; r1 = swap;
                    if (r0 > r1) { swap = r1; r1 = r0; r0 = swap; }
                }
            }
        }
        // wheel straights are ranked lower than other straights so it's a bit weird.
        bool straight = true, wheelStraight = false;
        if (r1 != r0 + 1) straight = false;
        else if (r2 != r1 + 1) straight = false;
        else if (r3 != r2 + 1) straight = false;
        else if (r4 != r3 + 1)
        {
            straight = false;
            // ace-low "wheel" straight
            if (r4 == 14 && r0 == 2)
            {
                wheelStraight = true;
            } 
        }

        int pair0 = 0, pair1 = 0, triple = 0;
        if (!straight)
        {
            // check for same rank
            if (r1 == r0)
            {
                pair0 = r1;
            }
            if (r2 == r1)
            {
                if (pair0 == r1)
                {
                    triple = r2;
                    // zero the first pair so we can detect the second one
                    // consistently
                    pair0 = 0; 
                } else
                {
                    pair0 = r2;
                }
            }
            if (r3 == r2)
            {
                if (triple == r2)
                {
                    pair1 = r3; // quad
                    pair0 = r3;
                } else if (pair0 == r2)
                {
                    triple = r3;
                    pair0 = 0;
                } else if (pair0 == r1)
                {
                    pair1 = r3;
                } else
                {
                    pair0 = r3;
                }
            }
            if (r4 == r3)
            {
                if (triple == r3)
                {
                    pair0 = r4; // quad
                    pair1 = r4; 
                }
                else if (pair1 == r3) // big full house
                {
                    triple = r4;
                    pair1 = 0;
                }
                else if (pair0 == r3)
                {
                    triple = r4;
                    pair0 = 0;
                } else if (pair0 == r2 || pair0 == r1 || triple == r2) // two pair or small full house
                {
                    pair1 = r4;
                } else
                {
                    pair0 = r4;
                }
            }
        }
        
        // 4 bits cover the 13 card ranks 23456789TJQKA , which are  biased upward
        // by 2 so that e.g. "no pair" is represented by '0', and 2 is e.g. a pair
        // of 2s.
        //
        // [1 bit straight flush]
        // [1 bit wheel-straight flush]
        // [1 bit 4 of a kind] (both pairs are the same for the rank)
        // [1 bit full house]
        // [1 bit flush]
        // [1 bit straight]
        // [1 bit wheel-straight] (ranked lower than other straights)
        // [4 bit 3 of a kind]
        // [4 bit 2nd pair (the higher pair rank if present)]
        // [4 bit, 1st pair]
        // [5 x 4 bit kickers (the hand spelled out in rank order)]
        //
        // spelling out the kickers is slightly redundant with the pair cards, but it's
        // at least correct for evaluation (the pair/triple/4 of a kind conditions are higher bits)

        ulong r = (ulong)(straight && flush ? 1 : 0);
        r = (r << 1) + (ulong)(wheelStraight && flush ? 1 : 0);
        r = (r << 1) + (ulong)(pair0 > 0 && pair0 == pair1 ? 1 : 0);
        r = (r << 1) + (ulong)(triple > 0 && (pair0 > 0 || pair1 > 0) ? 1 : 0);
        r = (r << 1) + (ulong)(flush ? 1 : 0);
        r = (r << 1) + (ulong)(straight ? 1 : 0);
        r = (r << 1) + (ulong)(wheelStraight ? 1 : 0);
        r = (r << 4) + (ulong)triple;
        r = (r << 4) + (ulong)pair1;
        r = (r << 4) + (ulong)pair0;

        r = (r << 4) + (ulong)r4;
        r = (r << 4) + (ulong)r3;
        r = (r << 4) + (ulong)r2;
        r = (r << 4) + (ulong)r1;
        r = (r << 4) + (ulong)r0;
        return r;
    }

    public string HandClass(ulong v)
    {
        int highCard = (int)((v >> 16) & 15UL) - 2;

        // hand bits after the pairs/kickers
        int h = (int)(v >> 32);
        if (((h >> 6) & 1) == 1)
        {
            if (((ulong)(v >> 16) & (ulong)15) == (ulong)14)
            {
                return "Royal Flush";
            } else
            {
                return "Straight Flush";
            }
        }
        if (((h >> 5) & 1) == 1)
        {
            return "Straight Flush (Wheel)";
        }
        if (((h >> 4) & 1) == 1)
        {
            int card = (int)((v >> 20) & 15UL) - 2;
            return $"Four of a Kind ({ranks[card]})";
        }
        if (((h >> 3) & 1) == 1)
        {
            int triple = (int)((v >> 28) & 15UL) - 2;
            int p1 = (int)((v >> 24) & 15UL) - 2;
            int p0 = (int)((v >> 20) & 15UL) - 2;
            int pair = p1 > -1 ? p1 : p0;
            return $"Full House ({ranks[triple]}/{ranks[pair]})";
        }
        if (((h >> 2) & 1) == 1)
        {
            return "Flush";
        }
        if (((h >> 1) & 1) == 1)
        {
            return "Straight";
        }
        if ((h & 1) == 1)
        {
            return "Straight (Wheel)";
        }
        if (((ulong)(v >> 28) & (ulong)15) > (ulong)0)
        {
            int triple = (int)((v >> 28) & 15UL) - 2;
            return $"Three of a Kind ({ranks[triple]})";
        }
        if (((ulong)(v >> 24) & (ulong)15) > (ulong)0)
        {
            int pair1 = (int)((v >> 24) & 15UL) -2;
            int pair0 = (int)((v >> 20) & 15UL) -2;
            return $"Two Pairs ({ranks[pair1]}/{ranks[pair0]})";
        }
        if (((ulong)(v >> 20) & (ulong)15) > (ulong)0)
        {
            int pair = (int)((v >> 20) & 15UL) -2;
            return $"Pair ({ranks[pair]})";
        }

        return $"High Card ({ranks[highCard]})";
    }

    public int GetHandClassInt(ulong v)
    {
        int h = (int)(v >> 32);
        if (((h >> 6) & 1) == 1)
        {
            if (((ulong)(v >> 16) & (ulong)15) == (ulong)14) return 9; // Royal Flush
            return 8; // Straight Flush
        }
        if (((h >> 5) & 1) == 1) return 8; // Straight Flush (Wheel)
        if (((h >> 4) & 1) == 1) return 7; // Four of a Kind
        if (((h >> 3) & 1) == 1) return 6; // Full House
        if (((h >> 2) & 1) == 1) return 5; // Flush
        if (((h >> 1) & 1) == 1) return 4; // Straight
        if ((h & 1) == 1) return 4; // Straight (Wheel)
        if (((ulong)(v >> 28) & (ulong)15) > (ulong)0) return 3; // Three of a Kind
        if (((ulong)(v >> 24) & (ulong)15) > (ulong)0) return 2; // Two Pairs
        if (((ulong)(v >> 20) & (ulong)15) > (ulong)0) return 1; // Pair
        return 0; // High Card
    }

    private void Log(string log)
    {
        Debug.Log("[Holdem] " + log);
    }

    //Used to add initialStackSize to each player's balance.
    public void GiveMoney()
    {
        if (!Networking.IsOwner(gameObject))
        {
            return;
        }
        
        for (int Index = 0; Index < seats; Index++)
        {
            if (players[Index].IsSeated())
            {
                ModifyBalanceForSeat(Index, initialStackSize);
            }
        }
        SerializeState();
        RequestSerialization();
    }

    public void ResetGame()
    {
        if (!Networking.IsOwner(gameObject)) return;
        Log("RESET GAME BUTTON PRESSED");
        tableState = TABLE_UNINITIALIZED;
        Transition();
    }

    public PlayerBalanceComponent GetSeatBalanceComponent(int SeatIndex)
    {
        if (SeatIndex < 0 || SeatIndex >= players.Length || !players[SeatIndex])
        {
            return null;
        }

        return players[SeatIndex].OwnerPlayerBalanceComponent();
    }

    //Returns true if the player at a given seat has a balance component that is ready to be used.
    //Should be used to check if a player can participate in a round.
    public bool IsSeatBalanceReady(int SeatIndex)
    {
        PlayerBalanceComponent BalanceComponent = GetSeatBalanceComponent(SeatIndex);
        return BalanceComponent && BalanceComponent.IsReady();
    }
    
    public int GetBalanceForSeat(int SeatIndex)
    {
        PlayerBalanceComponent BalanceComponent = GetSeatBalanceComponent(SeatIndex);
        return BalanceComponent ? BalanceComponent.GetBalance() : 0;
    }

    public void ModifyBalanceForSeat(int SeatIndex, int Delta)
    {
        PlayerBalanceComponent BalanceComponent = GetSeatBalanceComponent(SeatIndex);
        if (BalanceComponent)
        {
            BalanceComponent.ModifyBalance(Delta);
        }
    }

    // Balance component to pay a tournament prize or refund into. Resolved from the player id
    // captured at buy-in. Falls back to the live seat for someone who reconnected under a new id
    // and retook their seat by name.
    public PlayerBalanceComponent GetTournamentBalanceComponent(int SeatIndex)
    {
        if (SeatIndex < 0 || SeatIndex >= tournamentPlayerIds.Length) return null;

        // -1 unseated, -2 editor, 0 cleared slot; no real player id is non-positive.
        int Id = tournamentPlayerIds[SeatIndex];
        if (Id > 0)
        {
            VRCPlayerApi Player = VRCPlayerApi.GetPlayerById(Id);
            if (Player != null && Utilities.IsValid(Player))
            {
                PlayerBalanceComponent Resolved = PlayerBalanceComponent.GetPlayerBalanceComponent(Player);
                if (Resolved) return Resolved;
            }
        }

        return GetSeatBalanceComponent(SeatIndex);
    }

    // Credits a tournament prize/refund and books it as profit in one step, so no caller can
    // move the money without also recording it.
    private void AwardTournamentPayout(int SeatIndex, int Amount)
    {
        PlayerBalanceComponent BalanceComponent = GetTournamentBalanceComponent(SeatIndex);
        if (!BalanceComponent)
        {
            Log($"No balance component for seat {SeatIndex}; {Amount} payout dropped");
            return;
        }
        BalanceComponent.ModifyBalance(Amount);
        BalanceComponent.RecordProfit(Amount);
    }

    //Pushes balance back to the balance component.
    private void UpdatePlayerBalances()
    {
        if (!Networking.IsOwner(gameObject))
        {
            return;
        }

        if (isTournamentActive)
        {
            return;
        }
        
        for (int Index = 0; Index < seats; Index++)
        {
            HoldemPlayer Player = players[Index];
            if (!Player || !Player.IsSeated())
            {
                continue;
            }

            PlayerBalanceComponent BalanceComponent = Player.OwnerPlayerBalanceComponent();

            if (!BalanceComponent || !BalanceComponent.IsBalanceReady())
            {
                continue;
            }

            int BalanceDelta = stacks[Index] - preTransitionStacks[Index];

            if (BalanceDelta != 0)
            {
                // Compute the expected new bank balance (same clamp that ModifyBalance uses).
                int expectedNewBalance = Mathf.Max(0, BalanceComponent.CurrentSyncedBalance + BalanceDelta);

                BalanceComponent.ModifyBalance(BalanceDelta);

                // ModifyBalance sends a network event for non-owners, so CurrentSyncedBalance
                // stays stale until the round-trip completes. Eagerly update our tracking
                // arrays so the next Transition() tick's external-sync loop (line ~400)
                // does not compute a bogus externalDelta and undo the pot award.
                lastBankBalances[Index] = expectedNewBalance;
                BalanceComponent.CurrentSyncedBalance = expectedNewBalance;
            }
        }
    }

    private void UpdatePlayerMetrics()
    {
        if (!Networking.IsOwner(gameObject)) return;

        //Folds
        if (tableState == TABLE_PLAYING && preTransitionTableState == TABLE_PLAYING)
        {
            for (int i = 0; i < seats; ++i)
            {
                if (preTransitionPlayerState[i] != PLAYER_DEAD && playerState[i] == PLAYER_DEAD)
                {
                    Debug.Log($"[Metrics] Seat {i} FOLD recorded");
                    PlayerBalanceComponent BalanceComponent = GetSeatBalanceComponent(i);
                    if (BalanceComponent) BalanceComponent.RecordFold();
                }
            }
        }

        //Win or Lose
        if (tableState == TABLE_WINNER && preTransitionTableState != TABLE_WINNER)
        {
            int[] winnings = new int[MAX_SEATS];
            ulong[] handValues = null;
            if (wonByFold)
            {
                // First non-dead seat, matching how the pot is actually awarded in
                // CalculateTransition. Exactly one seat survives a fold win, but the three
                // places that resolve the winner should not be able to disagree.
                int winner = -1;
                int potTotal = 0;
                for (int i = 0; i < seats; i++)
                {
                    potTotal += potContribution[i];
                    if (winner < 0 && playerState[i] != PLAYER_DEAD) winner = i;
                }
                if (winner >= 0) winnings[winner] = potTotal;
            }
            else
            {
                // playerState, not preTransitionPlayerState: the snapshot predates this tick's
                // action, so a seat that folded to close the river still reads as live in it and
                // would be ranked into the pot here while the real award in CalculateTransition
                // excluded them.
                handValues = GetHandValues(playerState, holeCards0, holeCards1, flop0, flop1, flop2, turn, river);
                int[] playerRanksByHandValues = RankPlayers(handValues);
                winnings = DividePot(potContribution, playerRanksByHandValues, dealerSeat);
            }

            if (!isTournamentActive)
            {
                for (int i = 0; i < seats; ++i)
                {
                    PlayerBalanceComponent BalanceComponent = GetSeatBalanceComponent(i);
                    if (!BalanceComponent) continue;

                    // Record profit change for all players who contributed to the pot
                    if (potContribution[i] > 0)
                    {
                        int netProfit = winnings[i] - potContribution[i];
                        BalanceComponent.RecordProfit(netProfit);
                    }
                }
            }

            if (wonByFold)
            {
                //Fold-win: the last surviving player gets a win
                for (int i = 0; i < seats; ++i)
                {
                    if (playerState[i] != PLAYER_DEAD)
                    {
                        Debug.Log($"[Metrics] Seat {i} WIN (by fold) recorded");
                        PlayerBalanceComponent BalanceComponent = GetSeatBalanceComponent(i);
                        if (BalanceComponent) BalanceComponent.RecordWin();
                    }
                }
            }
            else
            {
                //Showdown: check winnerMask for wins/losses
                for (int i = 0; i < seats; ++i)
                {
                    // Same reasoning as the hand values above: only seats that actually reached
                    // showdown get a hand class and a win/loss.
                    if (playerState[i] == PLAYER_DEAD) continue;

                    PlayerBalanceComponent BalanceComponent = GetSeatBalanceComponent(i);
                    if (!BalanceComponent) continue;

                    int handClassInt = GetHandClassInt(handValues[i]);
                    BalanceComponent.RecordHandClass(handClassInt);


                    if ((winnerMask & (1 << i)) != 0)
                    {
                        Debug.Log($"[Metrics] Seat {i} WIN (showdown) recorded");
                        BalanceComponent.RecordWin();
                    }
                    else
                    {
                        Debug.Log($"[Metrics] Seat {i} LOSS (showdown) recorded");
                        BalanceComponent.RecordLoss();
                    }
                }
            }
        }
    }

    // Pays out the prize pool to ranks 1..3. Expects playerRanks to already be assigned.
    // Remainders land on the top prize so the whole pool is always distributed.
    private void DistributeTournamentPrizes(int winnerSeat)
    {
        int totalPool = totalParticipants * tournamentBuyIn;
        Log($"Tournament ending. Issuing payouts from pool of {totalPool}. Winner: Seat {winnerSeat}");

        if (totalParticipants <= 2)
        {
            AwardTournamentPayout(winnerSeat, totalPool);
            return;
        }

        // Integer percentages, not floats: (int)(3000 * 0.7f) truncates to 2099 because 0.7f
        // isn't exactly 0.7, which shorted the winner a chip.
        int secSeat = FindSeatWithRank(2);
        if (totalParticipants == 3)
        {
            int secondPrize = secSeat != -1 ? totalPool * 30 / 100 : 0;
            AwardTournamentPayout(winnerSeat, totalPool - secondPrize);
            if (secSeat != -1) AwardTournamentPayout(secSeat, secondPrize);
            return;
        }

        int thirdSeat = FindSeatWithRank(3);
        int second = secSeat != -1 ? totalPool * 30 / 100 : 0;
        int third = thirdSeat != -1 ? totalPool * 10 / 100 : 0;
        AwardTournamentPayout(winnerSeat, totalPool - second - third);
        if (secSeat != -1) AwardTournamentPayout(secSeat, second);
        if (thirdSeat != -1) AwardTournamentPayout(thirdSeat, third);
    }

    private int FindSeatWithRank(int rank)
    {
        for (int i = 0; i < seats; i++)
        {
            if (playerRanks[i] == rank)
            {
                return i;
            }
        }
        return -1;
    }

    public void StartTournament()
    {
        if (!Networking.IsOwner(gameObject)) return;
        if (isTournamentActive) return;

        int seatedCount = 0;
        for (int i = 0; i < seats; i++)
        {
            if (players[i].IsSeated())
            {
                if (GetBalanceForSeat(i) < tournamentBuyIn)
                {
                    Log($"Cannot start: Player in seat {i} doesn't have the buy-in of {tournamentBuyIn}");
                    return;
                }
                seatedCount++;
            }
        }

        if (seatedCount < 2)
        {
            Log("Need at least 2 players to start a tournament.");
            return;
        }

        totalParticipants = seatedCount;
        for (int i = 0; i < seats; i++)
        {
            if (players[i].IsSeated())
            {
                PlayerBalanceComponent BalanceComponent = GetSeatBalanceComponent(i);
                // Remembered for the whole tournament so a prize or refund still reaches them
                // if they stand up, or the master changes, before it's awarded.
                tournamentPlayerIds[i] = players[i].ActivePlayerId();
                ModifyBalanceForSeat(i, -tournamentBuyIn);
                if (BalanceComponent)
                {
                    BalanceComponent.RecordProfit(-tournamentBuyIn);
                }
                stacks[i] = tournamentStartingStack;
                tournamentEliminated[i] = false;
                playerRanks[i] = 0;
                tournamentPlayerNames[i] = players[i].OwnerName();
                // Force player ready so they are dealt in immediately
                players[i].playerReady = true;
                players[i].RequestSerialization();
            }
            else
            {
                stacks[i] = 0;
                tournamentEliminated[i] = true;
                playerRanks[i] = 0;
                tournamentPlayerNames[i] = "";
                tournamentPlayerIds[i] = 0;
            }
        }

        currentBlindLevelIndex = 0;
        blindLevelStartMillis = GetTimeMillis();
        isTournamentActive = true;
        
        Log($"Tournament started with {totalParticipants} players! Buy-in: {tournamentBuyIn}, Starting stack: {tournamentStartingStack}");

        tableState = TABLE_READY;
        SerializeState();
        RequestSerialization();
        Transition();
    }

    public void CancelTournament()
    {
        if (!Networking.IsOwner(gameObject)) return;
        if (!isTournamentActive) return;

        isTournamentActive = false;
        for (int i = 0; i < seats; i++)
        {
            // Refund every player still in the tournament, whether or not they're currently
            // sat down -- standing up mid-tournament is a supported state (there's a Rejoin
            // flow), and they've still paid the buy-in.
            if (!tournamentEliminated[i] && tournamentPlayerNames[i] != "")
            {
                AwardTournamentPayout(i, tournamentBuyIn);
            }
            if (players[i] != null && players[i].IsSeated())
            {
                players[i].ReleaseControl();
            }
            wasSeated[i] = false; // Reset to cash stacks
            tournamentPlayerNames[i] = "";
            tournamentPlayerIds[i] = 0;
        }

        tableState = TABLE_IDLE;
        SerializeState();
        RequestSerialization();
        Transition();
        Log("Tournament cancelled and refunds issued to active players.");
    }

    public void ToggleTournamentMode()
    {
        if (!Networking.IsOwner(gameObject)) return;
        if (isTournamentActive) return;
        if (!isTournamentMode && tableState != TABLE_IDLE && tableState != TABLE_UNINITIALIZED) return;

        isTournamentMode = !isTournamentMode;
        if (!isTournamentMode)
        {
            for (int i = 0; i < seats; i++)
            {
                wasSeated[i] = false; // Reset stack initialization
            }
        }
        SerializeState();
        RequestSerialization();
        Transition();
        Log($"Tournament mode toggled to {isTournamentMode}");
    }

    public void IncreaseBuyIn()
    {
        if (!Networking.IsOwner(gameObject) || isTournamentActive) return;
        tournamentBuyIn = Mathf.Min(100000, tournamentBuyIn + 500);
        RequestSerialization();
    }

    public void DecreaseBuyIn()
    {
        if (!Networking.IsOwner(gameObject) || isTournamentActive) return;
        tournamentBuyIn = Mathf.Max(500, tournamentBuyIn - 500);
        RequestSerialization();
    }

    public void IncreaseStartingStack()
    {
        if (!Networking.IsOwner(gameObject) || isTournamentActive) return;
        tournamentStartingStack = Mathf.Min(500000, tournamentStartingStack + 1000);
        RequestSerialization();
    }

    public void DecreaseStartingStack()
    {
        if (!Networking.IsOwner(gameObject) || isTournamentActive) return;
        tournamentStartingStack = Mathf.Max(1000, tournamentStartingStack - 1000);
        RequestSerialization();
    }

    public void IncreaseBlindTimer()
    {
        if (!Networking.IsOwner(gameObject) || isTournamentActive) return;
        tournamentLevelDurationSeconds = Mathf.Min(3600f, tournamentLevelDurationSeconds + 60f); // Max 60 mins (3600s), step by 1 min (60s)
        RequestSerialization();
    }

    public void DecreaseBlindTimer()
    {
        if (!Networking.IsOwner(gameObject) || isTournamentActive) return;
        tournamentLevelDurationSeconds = Mathf.Max(60f, tournamentLevelDurationSeconds - 60f); // Min 1 min (60s), step by 1 min (60s)
        RequestSerialization();
    }
}
