using UdonSharp;
using UnityEngine;
using VRC.SDKBase;
using VRC.SDK3.UdonNetworkCalling;
using VRC.Udon.Common.Interfaces;
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
{
    public const int MAX_SEATS = 10;
    public int seats = 10;
    public HoldemPlayer[] players;
    
    public CardFlipController cardFlipController;
    public TableCardFlipController tableCardFlipController;
    public AudioPoolPlayer cardFlipPlayer;

    public AudioPoolPlayer dingPlayer;
    public AudioPoolPlayer victoryPlayer;

    // 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];

    public 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;

    public int[] seatWinnings = new int[MAX_SEATS];
    [UdonSynced] public bool[] wasSeated = new bool[MAX_SEATS];
    private int[] lastBankBalances = new int[MAX_SEATS];
    private bool[] bankBaselineSeeded = new bool[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;

    // Owner-local action history. Results are persisted only after the hand reaches TABLE_WINNER.
    private bool pokerStatsHandActive;
    private int pokerStatsDealtMask;
    private int[] pokerStatsPlayerIds = new int[MAX_SEATS];
    private int[] pokerStatsMasks = new int[MAX_SEATS];
    private int pokerStatsPreflopRaiseCount;
    private int pokerStatsPreflopOpenerSeat = -1;
    private int pokerStatsPreflopAggressorSeat = -1;
    private int pokerStatsPendingThreeBetResponseSeat = -1;
    private int pokerStatsCBetCandidateSeat = -1;
    private bool pokerStatsCBetResolved;
    private int pokerStatsCBetAmount;
    private int pokerStatsAwaitingCBetResponseMask;

    private byte byt(int i)
    {
        return HoldemPacketCodec.byt(i);
    }

    private uint unt(int i)
    {
        return HoldemPacketCodec.unt(i);
    }

    // ---- Manual network sync protocol (packed state; see WriteStatePacket/DeserializeState) ----
    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();
        WriteStatePacket();
    }

    private int publishedRevealMask = 0;

    private int RevealedMask()
    {
        int mask = 0;
        for (int i = 0; i < seats; ++i)
            if (IsHandRevealed(i)) mask |= 1 << i;
        return mask;
    }

    private void WriteStatePacket()
    {
        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

        // Board cards go out only once their street is reached
        bool boardLive = tableState == TABLE_PLAYING || tableState == TABLE_WINNER;
        buf[n++] = byt(PublicCard(flop0, boardLive && bettingRound >= FLOP));
        buf[n++] = byt(PublicCard(flop1, boardLive && bettingRound >= FLOP));
        buf[n++] = byt(PublicCard(flop2, boardLive && bettingRound >= FLOP));
        buf[n++] = byt(PublicCard(turn, boardLive && bettingRound >= TURN));
        buf[n++] = byt(PublicCard(river, boardLive && bettingRound >= 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;

        int revealMask = 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));

            // Hole cards go out only when the rules show them; players get their own privately
            bool revealed = IsHandRevealed(i);
            if (revealed) revealMask |= 1 << i;
            buf[n++] = byt(PublicCard(holeCards0[i], revealed));
            buf[n++] = byt(PublicCard(holeCards1[i], revealed));

            // 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;
        }

        publishedRevealMask = revealMask;

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

    private void DeserializeState()
    {
        if (gameState0 == null || gameState1 == null) return;
        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 = HoldemPacketCodec.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 = CardFromByte(buf[n++]);
        flop1 = CardFromByte(buf[n++]);
        flop2 = CardFromByte(buf[n++]);
        turn =  CardFromByte(buf[n++]);
        river = CardFromByte(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] = CardFromByte(buf[n++]);
            holeCards1[i] = CardFromByte(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");
            // Only the dealer knows the hidden cards; if we inherit the table mid-hand we can't finish it
            holdsDeal = false;
            DeserializeState();
            RefreshRevealedHands();
        }
    }

    // ---- Hole card reveal & RPC ----
    private int[] lastSeenHole0 = new int[MAX_SEATS];
    private int[] lastSeenHole1 = new int[MAX_SEATS];

    private void RefreshRevealedHands()
    {
        if (players == null) return;
        for (int i = 0; i < seats; ++i)
        {
            if (holeCards0[i] == lastSeenHole0[i] && holeCards1[i] == lastSeenHole1[i]) continue;
            lastSeenHole0[i] = holeCards0[i];
            lastSeenHole1[i] = holeCards1[i];
            if (players[i] != null && players[i].grabbableHand != null) players[i]._UpdateCardDisplay();
            highlightsDirty = true;
        }
    }


    // Bumped on every deal so private card deliveries can be matched to their hand
    [UdonSynced] public int handId = 0;
    // Pot shares for the winner display, since other clients can't rank hands they can't see
    [UdonSynced] public int[] seatWinningsSynced = new int[MAX_SEATS];
    // False on a client that took over the table without having dealt the current hand
    private bool holdsDeal = true;

    // Per seat, a hash of the hole cards and a private salt, so a new owner can check reported cards
    [UdonSynced] public long[] holeCommitments = new long[MAX_SEATS];
    // Who each seat's cards were dealt to; anyone else sitting there mid-hand can't hold up a recovery
    [UdonSynced] public int[] dealtPlayerIds = new int[MAX_SEATS];
    private int[] holeSaltA = new int[MAX_SEATS];
    private int[] holeSaltB = new int[MAX_SEATS];
    // Seats still to commit; hashing is spread one seat per frame so the deal doesn't hitch
    private int pendingCommitMask;

    // Set while a new owner collects hole cards to resume the hand the old dealer left; -1 otherwise
    [UdonSynced] public int recoveryHandId = -1;
    public int handRecoveryTimeoutSecs = 8;
    private bool recovering = false;
    private int recoveryStartMillis;
    private int recoveredMask;

    private bool ownershipJustTransferredToMe = false;

    public override void OnOwnershipTransferred(VRCPlayerApi player)
    {
        if (player != null && player.isLocal) ownershipJustTransferredToMe = true;
    }

    private int PublicCard(int card, bool revealed)
    {
        return HoldemDeckUtil.PublicCard(card, revealed);
    }

    private int CardFromByte(int value)
    {
        return HoldemDeckUtil.CardFromByte(value);
    }

    public bool IsShowdown()
    {
        if (tableState != TABLE_WINNER) return false;
        int challengers = 0;
        for (int i = 0; i < seats; ++i)
        {
            if (playerState[i] == PLAYER_COMMITED) challengers++;
        }
        return challengers > 1;
    }

    public void _ApplyShowdownPresentation()
    {
        bool showdown = IsShowdown();
        if (tableCardFlipController != null) tableCardFlipController.SetMaskVolumeEnabled(!showdown);
        if (!showdown || players == null) return;

        for (int i = 0; i < seats; ++i)
        {
            if (playerState[i] != PLAYER_DEAD) continue;
            if (players[i] != null && players[i].grabbableHand != null) players[i].grabbableHand.SetEnabled(false);
        }
    }

    // ---- Best-hand highlight (local presentation only) ----
    private bool highlightsDirty = true;
    private int highlightEpoch = -1;
    private int highlightSeatChangeVersion = -1;

    public void _MarkHighlightsDirty()
    {
        highlightsDirty = true;
    }

    // Board card as this client knows it: streets that haven't been dealt yet read as hidden
    private int VisibleBoardCard(int card, int firstRound)
    {
        return bettingRound >= firstRound ? card : -1;
    }

    // During the hand the local seated player's own best hand lights up (hole cards, and the board on
    // this client's displays). At showdown the best visible hand(s) light up instead, whoever holds them.
    // Only hands made of two or more cards light up, and kickers never do.
    public void _RefreshHandHighlights()
    {
        highlightsDirty = false;
        if (players == null) return;

        int[] holeMasks = new int[MAX_SEATS];
        int boardMask = 0;

        bool showdown = IsShowdown();
        if (showdown)
        {
            ulong best = 0UL;
            ulong[] values = new ulong[MAX_SEATS];
            for (int i = 0; i < seats; ++i)
            {
                if (!IsHandRevealed(i)) continue;
                values[i] = HoldemHandEvaluator.BestFiveValue(
                    holeCards0[i], holeCards1[i], flop0, flop1, flop2, turn, river);
                if (values[i] > best) best = values[i];
            }

            for (int i = 0; i < seats; ++i)
            {
                if (best == 0UL || values[i] != best) continue;
                int mask = HoldemHandEvaluator.HighlightMask(
                    holeCards0[i], holeCards1[i], flop0, flop1, flop2, turn, river);
                holeMasks[i] = mask & 3;
                boardMask |= mask >> 2;
            }
        }
        else if (tableState == TABLE_PLAYING || tableState == TABLE_WINNER)
        {
            for (int i = 0; i < seats; ++i)
            {
                HoldemPlayer seat = players[i];
                if (seat == null || playerState[i] == PLAYER_DEAD || !seat._IsLocallySeated()) continue;

                int mask = HoldemHandEvaluator.HighlightMask(
                    seat.LocalHoleCard(0), seat.LocalHoleCard(1),
                    VisibleBoardCard(flop0, FLOP), VisibleBoardCard(flop1, FLOP), VisibleBoardCard(flop2, FLOP),
                    VisibleBoardCard(turn, TURN), VisibleBoardCard(river, RIVER));
                holeMasks[i] = mask & 3;
                boardMask |= mask >> 2;
            }
        }

        for (int i = 0; i < seats; ++i)
        {
            if (players[i] == null || players[i].grabbableHand == null) continue;
            players[i].grabbableHand.SetHoleHighlight((holeMasks[i] & 1) != 0, (holeMasks[i] & 2) != 0);
        }
        if (cardFlipController != null) cardFlipController.SetBoardHighlight(boardMask);
        if (tableCardFlipController != null) tableCardFlipController.SetBoardHighlight(boardMask);
    }

    // Same rules as HoldemPlayer.CanShowHoles: all-in runouts, showdown aggressor and winners, or shown by the player
    private bool IsHandRevealed(int seat)
    {
        if (tableState != TABLE_PLAYING && tableState != TABLE_WINNER) return false;
        if (playerState[seat] == PLAYER_DEAD) return false;

        bool showdown = IsShowdown();

        if (headsUp && !showdown) return true;
        if (showdown && (aggressorSeat == seat || (winnerMask & (1 << seat)) != 0)) return true;
        return players != null && players[seat] != null && players[seat].IsShownBySeatedPlayer();
    }

    // Owner: re-sends the caller's own cards if the deal event didn't reach them
    [NetworkCallable(2)]
    public void RequestHoleCards()
    {
        if (!Networking.IsOwner(gameObject) || !holdsDeal) return;
        if (tableState != TABLE_PLAYING && tableState != TABLE_WINNER) return;
        VRCPlayerApi caller = NetworkCalling.CallingPlayer;
        if (!Utilities.IsValid(caller)) return;

        for (int i = 0; i < seats; i++)
        {
            HoldemPlayer seat = players[i];
            if (seat == null || playerState[i] == PLAYER_DEAD || !seat.IsSeated()) continue;
            VRCPlayerApi owner = Networking.GetOwner(seat.gameObject);
            if (Utilities.IsValid(owner) && owner.playerId == caller.playerId) SendHoleCards(i);
        }
    }

    private void SendHoleCards(int seat)
    {
        players[seat].SendCustomNetworkEvent(NetworkEventTarget.Owner, nameof(HoldemPlayer.ReceiveHoleCards),
            handId, holeCards0[seat], holeCards1[seat], holeSaltA[seat], holeSaltB[seat]);
    }

    // ---- Hand recovery after the dealer leaves ----

    // New owner: the hidden cards left with the old dealer, so collect each seat's cards from its player
    private void BeginRecovery()
    {
        Log("took over mid-hand without the deck, collecting hole cards to resume it");
        recovering = true;
        recoveryStartMillis = GetTimeMillis();
        recoveryHandId = handId;
        recoveredMask = 0;
        for (int i = 0; i < seats; i++)
        {
            // Hands the table already revealed came through the synced state
            if (holeCards0[i] >= 0 && holeCards1[i] >= 0) recoveredMask |= 1 << i;
        }
        for (int i = 0; i < seats; i++)
        {
            HoldemPlayer seat = players[i];
            if (seat == null || !seat._HasPrivateCards()) continue;
            int card0 = seat.PrivateCard(0);
            int card1 = seat.PrivateCard(1);
            int saltA = seat.PrivateSalt(0);
            int saltB = seat.PrivateSalt(1);
            AcceptReport(i, handId, card0, card1, saltA, saltB);
        }
        // Restart the acting player's countdown so it doesn't run out on everyone's screen meanwhile
        lastTransitionMillis = GetTimeMillis();
        WriteStatePacket();
        RequestSerialization();
    }

    // Owner, while recovering: a seated player proves their hole cards against the deal's commitment
    [NetworkCallable(2)]
    public void ReportHoleCards(int reportHandId, int card0, int card1, int saltA, int saltB)
    {
        if (!Networking.IsOwner(gameObject) || !recovering) return;
        VRCPlayerApi caller = NetworkCalling.CallingPlayer;
        if (!Utilities.IsValid(caller)) return;

        for (int i = 0; i < seats; i++)
        {
            if (!HeldByDealtPlayer(i)) continue;
            VRCPlayerApi owner = Networking.GetOwner(players[i].gameObject);
            if (Utilities.IsValid(owner) && owner.playerId == caller.playerId)
                AcceptReport(i, reportHandId, card0, card1, saltA, saltB);
        }
    }

    // The seat is still occupied by the player its cards were dealt to
    private bool HeldByDealtPlayer(int seat)
    {
        HoldemPlayer player = players[seat];
        return player != null && player.IsSeated() && player.ActivePlayerId() == dealtPlayerIds[seat];
    }

    private bool AcceptReport(int seat, int reportHandId, int card0, int card1, int saltA, int saltB)
    {
        if (reportHandId != handId || (recoveredMask & (1 << seat)) != 0) return false;
        if (card0 < 0 || card0 > 51 || card1 < 0 || card1 > 51 || card0 == card1) return false;
        if (holeCommitments[seat] == 0) return false;
        if (HoldemCommit.Commit(reportHandId, seat, card0, card1, saltA, saltB) != holeCommitments[seat]) return false;

        holeCards0[seat] = card0;
        holeCards1[seat] = card1;
        holeSaltA[seat] = saltA;
        holeSaltB[seat] = saltB;
        recoveredMask |= 1 << seat;
        return true;
    }

    // False while still waiting on a seated player's cards. Gives up and voids the hand after the timeout.
    private bool TickRecovery(int nowMillis)
    {
        int missing = 0;
        for (int i = 0; i < seats; i++)
        {
            if (playerState[i] == PLAYER_DEAD || (recoveredMask & (1 << i)) != 0) continue;
            if (HeldByDealtPlayer(i)) missing++;
        }

        if (missing > 0)
        {
            if ((nowMillis - recoveryStartMillis) / 1000 < handRecoveryTimeoutSecs) return false;
            Log($"{missing} seated players never proved their cards");
            EndRecovery();
            VoidHand();
            return true;
        }

        FinishRecovery(nowMillis);
        return true;
    }

    // Every seated hand is known: fold the vacant ones and reshuffle the board cards nobody has seen
    private void FinishRecovery(int nowMillis)
    {
        bool[] used = new bool[52];
        if (bettingRound >= FLOP)
        {
            MarkUsed(used, flop0);
            MarkUsed(used, flop1);
            MarkUsed(used, flop2);
        }
        if (bettingRound >= TURN) MarkUsed(used, turn);
        if (bettingRound >= RIVER) MarkUsed(used, river);

        for (int i = 0; i < seats; i++)
        {
            if ((recoveredMask & (1 << i)) != 0)
            {
                MarkUsed(used, holeCards0[i]);
                MarkUsed(used, holeCards1[i]);
            }
            else if (playerState[i] != PLAYER_DEAD)
            {
                Log($"seat {i} left with unknown cards, folding it");
                playerState[i] = PLAYER_DEAD;
                callOnlyMask &= ~(1 << i);
            }
        }

        int[] rest = HoldemDeckUtil.ShuffleExcluding(used);
        int n = 0;
        if (bettingRound < FLOP)
        {
            flop0 = rest[n++];
            flop1 = rest[n++];
            flop2 = rest[n++];
        }
        if (bettingRound < TURN) turn = rest[n++];
        if (bettingRound < RIVER) river = rest[n++];

        Log("hand recovered, resuming");
        EndRecovery();
        holdsDeal = true;
        // The acting player gets a full turn back
        lastTransitionMillis = nowMillis;
        WriteStatePacket();
        RequestSerialization();
    }

    // Owner: hashes the next dealt seat's cards, and syncs the commitments once all are done
    private void CommitNextSeat()
    {
        for (int i = 0; i < seats; i++)
        {
            if ((pendingCommitMask & (1 << i)) == 0) continue;
            pendingCommitMask &= ~(1 << i);
            holeCommitments[i] = HoldemCommit.Commit(handId, i, holeCards0[i], holeCards1[i], holeSaltA[i], holeSaltB[i]);
            if (pendingCommitMask == 0) RequestSerialization();
            return;
        }
    }

    private void MarkUsed(bool[] used, int card)
    {
        if (card >= 0 && card < 52) used[card] = true;
    }

    private void EndRecovery()
    {
        recovering = false;
        recoveryHandId = -1;
    }

    // Board-aware best hand for the given hole cards at the current street
    public ulong BestHandForRound(int h0, int h1)
    {
        if (h0 < 0 || h1 < 0) return 0;
        if (bettingRound >= RIVER) return HoldemHandEvaluator.BestPlayerHand(h0, h1, flop0, flop1, flop2, turn, river);
        if (bettingRound == TURN) return HoldemHandEvaluator.BestPlayerHandTurn(h0, h1, flop0, flop1, flop2, turn);
        if (bettingRound == FLOP) return HoldemHandEvaluator.EvaluateHand(h0, h1, flop0, flop1, flop2);
        return 0;
    }

    // The seat's best five cards on the full board, packed for persistence
    public int PackedBestFiveForSeat(int seat)
    {
        return HoldemHandEvaluator.PackBestFive(holeCards0[seat], holeCards1[seat], flop0, flop1, flop2, turn, river);
    }

    // Each seat's share of the pot; a fold win hands all of it to the first live seat
    public int[] ResolveWinnings(ulong[] handValues)
    {
        if (!wonByFold) return HoldemPotMath.DividePot(seats, potContribution, HoldemHandEvaluator.RankPlayers(seats, handValues), dealerSeat);

        int[] winnings = new int[MAX_SEATS];
        int winner = -1;
        int pot = 0;
        for (int i = 0; i < seats; i++)
        {
            pot += potContribution[i];
            if (winner < 0 && playerState[i] != PLAYER_DEAD) winner = i;
        }
        if (winner >= 0) winnings[winner] = pot;
        return winnings;
    }

    // New owner without the deck: give every contribution back and start over
    private void VoidHand()
    {
        Log("took over mid-hand without the deck, voiding the hand");
        for (int i = 0; i < seats; i++) stacks[i] += potContribution[i] + roundContribution[i];
        _ResetHandState();
        flop0 = -1;
        flop1 = -1;
        flop2 = -1;
        turn = -1;
        river = -1;
        tableState = TABLE_IDLE;
        lastTransitionMillis = GetTimeMillis();
        holdsDeal = true;
    }

    private void BeginPokerStatsHand(bool[] dealtPlayers)
    {
        pokerStatsHandActive = true;
        pokerStatsDealtMask = 0;
        pokerStatsPreflopRaiseCount = 0;
        pokerStatsPreflopOpenerSeat = -1;
        pokerStatsPreflopAggressorSeat = -1;
        pokerStatsPendingThreeBetResponseSeat = -1;
        pokerStatsCBetCandidateSeat = -1;
        pokerStatsCBetResolved = false;
        pokerStatsCBetAmount = 0;
        pokerStatsAwaitingCBetResponseMask = 0;

        for (int i = 0; i < seats; i++)
        {
            pokerStatsMasks[i] = 0;
            pokerStatsPlayerIds[i] = 0;
            if (!dealtPlayers[i]) continue;

            pokerStatsDealtMask |= 1 << i;
            if (players[i] != null) pokerStatsPlayerIds[i] = players[i].ActivePlayerId();
        }
    }

    private void DiscardPokerStatsHand()
    {
        pokerStatsHandActive = false;
        pokerStatsDealtMask = 0;
        pokerStatsPendingThreeBetResponseSeat = -1;
        pokerStatsCBetCandidateSeat = -1;
        pokerStatsAwaitingCBetResponseMask = 0;
    }

    private PlayerBalanceComponent PokerStatsBalanceComponent(int seat)
    {
        int playerId = pokerStatsPlayerIds[seat];
        if (playerId > 0)
        {
            VRCPlayerApi player = VRCPlayerApi.GetPlayerById(playerId);
            if (player == null || !Utilities.IsValid(player)) return null;
            return PlayerBalanceComponent.GetPlayerBalanceComponent(player);
        }

        return HoldemBalanceOps.GetSeatBalanceComponent(this, seat);
    }

    private void FinalizePokerStatsHand()
    {
        if (!pokerStatsHandActive) return;

        for (int i = 0; i < seats; i++)
        {
            if ((pokerStatsDealtMask & (1 << i)) == 0) continue;
            PlayerBalanceComponent balance = PokerStatsBalanceComponent(i);
            if (balance) balance.RecordHoldemHandStats(pokerStatsMasks[i] | PlayerBalanceComponent.HAND_STAT_TRACKED);
        }
        DiscardPokerStatsHand();
    }

    private void PrepareFlopPokerStats()
    {
        pokerStatsCBetCandidateSeat = pokerStatsPreflopRaiseCount > 0 ? pokerStatsPreflopAggressorSeat : -1;
        pokerStatsCBetResolved = false;
        pokerStatsCBetAmount = 0;
        pokerStatsAwaitingCBetResponseMask = 0;
    }

    private void RecordPokerAction(int seat, bool folded, int actionBet, int oldCurrentBet,
        int oldRoundContribution, int oldStack, int oldCallOnlyMask)
    {
        int seatBit = 1 << seat;
        if (!pokerStatsHandActive || (pokerStatsDealtMask & seatBit) == 0) return;

        bool aggressive = !folded && oldRoundContribution + actionBet > oldCurrentBet;

        if (bettingRound == PREFLOP)
        {
            if (pokerStatsPendingThreeBetResponseSeat == seat && pokerStatsPreflopRaiseCount == 2)
            {
                pokerStatsMasks[seat] |= PlayerBalanceComponent.HAND_STAT_FOLD_TO_THREE_BET_OPPORTUNITY;
                if (folded) pokerStatsMasks[seat] |= PlayerBalanceComponent.HAND_STAT_FOLD_TO_THREE_BET;
                pokerStatsPendingThreeBetResponseSeat = -1;
            }

            bool canRaise = (oldCallOnlyMask & seatBit) == 0 && oldRoundContribution + oldStack > oldCurrentBet;
            if (pokerStatsPreflopRaiseCount == 1 && seat != pokerStatsPreflopOpenerSeat && canRaise)
            {
                pokerStatsMasks[seat] |= PlayerBalanceComponent.HAND_STAT_THREE_BET_OPPORTUNITY;
            }

            if (!folded && actionBet > 0)
            {
                pokerStatsMasks[seat] |= PlayerBalanceComponent.HAND_STAT_VPIP;
            }

            if (aggressive)
            {
                pokerStatsMasks[seat] |= PlayerBalanceComponent.HAND_STAT_VPIP | PlayerBalanceComponent.HAND_STAT_PFR;
                pokerStatsPreflopRaiseCount++;
                pokerStatsPreflopAggressorSeat = seat;

                if (pokerStatsPreflopRaiseCount == 1)
                {
                    pokerStatsPreflopOpenerSeat = seat;
                }
                else if (pokerStatsPreflopRaiseCount == 2)
                {
                    pokerStatsMasks[seat] |= PlayerBalanceComponent.HAND_STAT_THREE_BET;
                    pokerStatsPendingThreeBetResponseSeat = pokerStatsPreflopOpenerSeat;
                }
                else
                {
                    // Once somebody 4-bets, the opener no longer faces the original 3-bet directly.
                    pokerStatsPendingThreeBetResponseSeat = -1;
                }
            }
            return;
        }

        if (bettingRound != FLOP) return;

        bool respondingToCBet = (pokerStatsAwaitingCBetResponseMask & seatBit) != 0
            && oldCurrentBet == pokerStatsCBetAmount;
        if (respondingToCBet)
        {
            pokerStatsMasks[seat] |= PlayerBalanceComponent.HAND_STAT_FOLD_TO_CBET_OPPORTUNITY;
            if (folded) pokerStatsMasks[seat] |= PlayerBalanceComponent.HAND_STAT_FOLD_TO_CBET;
            pokerStatsAwaitingCBetResponseMask &= ~seatBit;
        }

        bool madeCBet = false;
        if (!pokerStatsCBetResolved && seat == pokerStatsCBetCandidateSeat)
        {
            pokerStatsCBetResolved = true;
            if (oldCurrentBet == 0)
            {
                pokerStatsMasks[seat] |= PlayerBalanceComponent.HAND_STAT_CBET_OPPORTUNITY;
                if (aggressive)
                {
                    madeCBet = true;
                    pokerStatsMasks[seat] |= PlayerBalanceComponent.HAND_STAT_CBET;
                    pokerStatsCBetAmount = oldRoundContribution + actionBet;
                    for (int i = 0; i < seats; i++)
                    {
                        if (i != seat && playerState[i] != PLAYER_DEAD && stacks[i] > 0)
                            pokerStatsAwaitingCBetResponseMask |= 1 << i;
                    }
                }
            }
        }

        if (aggressive && !madeCBet && pokerStatsAwaitingCBetResponseMask != 0)
        {
            // Players behind now face this raise, not the continuation bet directly.
            pokerStatsAwaitingCBetResponseMask = 0;
        }
    }

    public void RecordPokerDepartureFold(int seat)
    {
        if (seat < 0 || seat >= seats || playerState[seat] == PLAYER_DEAD) return;
        RecordPokerAction(seat, true, 0, currentBet, roundContribution[seat], stacks[seat], callOnlyMask);
    }

    void WriteInt(uint i, int pos, byte[] buf)
    {
        HoldemPacketCodec.WriteInt(i, pos, buf);
    }
    uint ReadInt(int n, byte[] buf)
    {
        return HoldemPacketCodec.ReadInt(n, buf);
    }

    public const int maxSyncedStringSize = 105;
    public const int maxPacketCharSize = maxSyncedStringSize * 2;
    // 14 bits leftover to do something with
    // possibly packing player id + seqNo to monitor per-player packet loss.
    public 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
    public const int maxDataCharSize = (int)((maxPacketCharSize - headerCharSize) / 8f) * 8;
    public const int maxDataByteSize = maxDataCharSize / 8 * 7;

    // ---- Core table/betting state ----
    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;
    public int lastBettingRound = NOT_PLAYING;
    public 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()
    {
        bool[] playerIsSeated = new bool[MAX_SEATS];
        bool[] playerIsReady = new bool[MAX_SEATS];
        bool bReceivedBalanceUpdate = HoldemBalanceOps.ReconcileBankBalances(
            this, playerIsSeated, playerIsReady, lastBankBalances, bankBaselineSeeded, preTransitionStacks, lastRebuyVersion);
        HoldemBalanceOps.UnseatBrokePlayers(this, playerIsSeated, playerIsReady);

        // After the stack baselines, so the refund is flushed back to balances.
        // Gated on a ownership transfer event
        if (Networking.IsOwner(gameObject) && ownershipJustTransferredToMe)
        {
            ownershipJustTransferredToMe = false;
            if (!holdsDeal && tableState == TABLE_PLAYING) BeginRecovery();
        }

        // The hand stays frozen, timers included, until the hole cards are back
        // A reset or tournament cancel already settled the hand; there's nothing left to recover
        if (recovering && tableState != TABLE_PLAYING)
        {
            Log("table left the hand while recovering it, dropping the recovery");
            EndRecovery();
        }

        if (recovering)
        {
            bool voided = false;
            if (TickRecovery(GetTimeMillis())) voided = tableState != TABLE_PLAYING;
            if (recovering)
            {
                if (bReceivedBalanceUpdate)
                {
                    WriteStatePacket();
                    RequestSerialization();
                    UpdatePlayerBalances();
                }
                return;
            }
            if (voided) bReceivedBalanceUpdate = true;
        }

        if (HoldemTournament.TryResolveAbandonedTournament(this, playerIsSeated))
        {
            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)
            {
                HoldemTournament.AdvanceBlindLevel(this);
            }
            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 = HoldemPotMath.CalculateMedianStack(seats, stacks, playerStackedAndReady);
                int calculatedBigBlind = HoldemPotMath.CalculateBigBlindFromMedian(medianStack, bigBlindDivisor, minBigBlind);
                if (calculatedBigBlind != bigBlind)
                {
                    Log($"Calculated big blind: {calculatedBigBlind} from median stack {medianStack} with divisor {bigBlindDivisor}");
                }
                bigBlind = calculatedBigBlind;
            }
        }

        if (Advance(nowMillis, playerIsSeated, playerIsReady, bReceivedBalanceUpdate,
            actingPlayerBet, actingPlayerCommited, null))
        {
            bool dealt = preTransitionTableState == TABLE_READY && tableState == TABLE_PLAYING;
            if (dealt) holdsDeal = true;

            SerializeState();
            RequestSerialization();

            if (dealt)
            {
                for (int i = 0; i < seats; i++)
                {
                    if (playerState[i] != PLAYER_DEAD && players[i] != null) SendHoleCards(i);
                }
            }

            //Flush delta between player balance and stack size to players now.
            UpdatePlayerBalances();

            UpdatePlayerMetrics();

            // Check for tournament eliminations after stack update (only at the end of a hand when pots are distributed)
            if (isTournamentActive && tableState == TABLE_WINNER)
            {
                HoldemTournament.CheckHandEliminations(this);
            }

            if (isTournamentActive && tableState == TABLE_IDLE)
            {
                if (HoldemTournament.TryEndTournamentAtIdle(this))
                {
                    SerializeState();
                    RequestSerialization();
                }
            }
        }

        if (RevealedMask() != publishedRevealMask)
        {
            WriteStatePacket();
            RequestSerialization();
        }
    }

    // One tick of the whole state machine on the fields above. False when nothing serializable changed.
    // deck is a unit test hook; udon can't seed its RNG.
    public bool Advance(int nowMillis, bool[] playerIsSeated, bool[] playerIsReady, bool bReceivedBalanceUpdate,
        int actingPlayerBet, bool actingPlayerCommitted, int[] deck)
    {
        int newTableState = NextTableState(nowMillis, playerIsSeated, playerIsReady);
        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;

            if (tableState == TABLE_READY && newTableState == TABLE_PLAYING)
            {
                DealHand(playerIsSeated, playerIsReady, deck);
            }
            if (newTableState == TABLE_WINNER)
            {
                enteredWinner = true;
            }
            if (newTableState == TABLE_IDLE)
            {
                Log("Resetting player state for idle");
                _ResetHandState();

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

        if (tableState == TABLE_PLAYING && AdvanceBetting(nowMillis, playerIsSeated[actingSeat], actingPlayerBet, actingPlayerCommitted))
        {
            lastTransitionMillis = nowMillis;
            changed = true;
            if (wonByFold || bettingRound > RIVER)
            {
                tableState = TABLE_WINNER;
                enteredWinner = true;
            }
        }

        // This has to run after the betting step above, because that closes the final round
        // (raking roundContribution into potContribution and marking folds).
        if (enteredWinner)
        {
            AwardPot();
            FinalizePokerStatsHand();
        }

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

    // Ready to playing: sit in the players who can play, post blinds, shuffle and deal
    private void DealHand(bool[] playerIsSeated, bool[] playerIsReady, int[] deck)
    {
        bool[] playerStackedAndReady = new bool[MAX_SEATS];
        for (int i = 0; i < seats; i++)
        {
            preTransitionStacks[i] = stacks[i];
            handStartStacks[i] = stacks[i];
            playerStackedAndReady[i] = CanPlayHand(i, playerIsSeated, playerIsReady);
            playerState[i] = playerStackedAndReady[i] ? PLAYER_PENDING : PLAYER_DEAD;
            roundContribution[i] = 0;
            potContribution[i] = 0;
        }
        Log($"game started, dealing game");
        BeginPokerStatsHand(playerStackedAndReady);

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

        if (deck == null) deck = HoldemDeckUtil.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;
            }
        }
        // Bumped here so the commitments below carry the new hand's id
        handId++;
        pendingCommitMask = 0;
        for (int i = 0; i < seats; ++i)
        {
            holeCommitments[i] = 0;
            dealtPlayerIds[i] = 0;
            if (playerState[i] == PLAYER_DEAD) continue;
            if (players[i] != null) dealtPlayerIds[i] = players[i].ActivePlayerId();
            holeSaltA[i] = Random.Range(int.MinValue, int.MaxValue);
            holeSaltB[i] = Random.Range(int.MinValue, int.MaxValue);
            pendingCommitMask |= 1 << i;
        }

        // 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 (!(bool)setup[3])
        {
            // Bank blinds here
            for (int i = 0; i < seats; i++)
            {
                potContribution[i] += roundContribution[i];
                roundContribution[i] = 0;
                if (playerState[i] == PLAYER_PENDING) playerState[i] = PLAYER_COMMITED;
            }
            headsUp = true;
            Log("every dealt-in seat is all-in on the blinds, running the board out");
        }
    }

    // Pays the pot into the stacks and records each seat's share for the winner display
    private void AwardPot()
    {
        Log(wonByFold ? "game won by fold" : "game showdown.");
        ulong[] handValues = wonByFold ? null : HoldemHandEvaluator.GetHandValues(
            seats, playerState, holeCards0, holeCards1, flop0, flop1, flop2, turn, river);

        int[] winnings = ResolveWinnings(handValues);
        for (int i = 0; i < seats; ++i)
        {
            stacks[i] += winnings[i];
            seatWinningsSynced[i] = winnings[i];
            if (winnings[i] > 0) winnerMask |= (1 << i);
        }
    }

    // Back to an empty table: no cards, bets or pot
    public void _ResetHandState()
    {
        DiscardPokerStatsHand();
        for (int i = 0; i < seats; i++)
        {
            playerState[i] = PLAYER_DEAD;
            holeCards0[i] = -1;
            holeCards1[i] = -1;
            potContribution[i] = 0;
            roundContribution[i] = 0;
        }
        bettingRound = NOT_PLAYING;
        currentBet = 0;
        minimumRaise = 0;
        callOnlyMask = 0;
        headsUp = false;
        wonByFold = false;
        aggressorSeat = -1;
        winnerMask = 0;
    }

    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;

        // Commit players with no chips
        if (stacks[littleBlindSeat] == 0) playerState[littleBlindSeat] = PLAYER_COMMITED;
        if (stacks[bigBlindSeat] == 0) playerState[bigBlindSeat] = PLAYER_COMMITED;

        // First to act lookahead
        bool canAct = false;
        for (int i = 0; i < seats; i++)
        {
            int seat = (actingSeat + i) % seats;
            if (playerStackedAndReady[seat] && stacks[seat] > 0)
            {
                actingSeat = seat;
                canAct = true;
                break;
            }
        }
        if (canAct) playerState[actingSeat] = PLAYER_ACTING;
        return new object[]
        {
            actingSeat, dealerSeat, aggressorSeat, canAct
        };
    }

    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;
    }



    // Table layer: idle --(players ready and stacked)--> ready --(timeout)--> playing --(win)--> winner --(timeout)--> idle,
    // and back to idle when nobody is seated or too few are ready
    public int NextTableState(int nowMillis, bool[] playerIsSeated, bool[] playerIsReady)
    {
        if (isTournamentMode && !isTournamentActive)
        {
            return TABLE_IDLE;
        }

        int readyAndStacked = 0;
        int seated = 0;
        for (int i = 0; i < seats; ++i)
        {
            if (playerIsSeated[i]) seated++;
            if (CanPlayHand(i, playerIsSeated, playerIsReady)) readyAndStacked++;
        }

        var elapsedSecs = (nowMillis - lastTransitionMillis) / 1000;
        switch (tableState)
        {
            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 tableState;
    }

    // Whether this seat is dealt into the next hand
    private bool CanPlayHand(int seat, bool[] playerIsSeated, bool[] playerIsReady)
    {
        if (isTournamentActive) return !tournamentEliminated[seat] && stacks[seat] > 0;
        return playerIsSeated[seat] && playerIsReady[seat] && stacks[seat] >= bigBlind;
    }

    // Betting layer: waits on the acting seat, folds or checks on timeout, then moves the action or closes the round.
    // A seat that leaves mid-round stays pending until the action reaches it, then folds. False while waiting.
    public bool AdvanceBetting(int nowMillis, bool actingPlayerSeated, int actingPlayerBet, bool actingPlayerCommitted)
    {
        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 false;
            Log($"headsup timeout, round to {bettingRound + 1}");
            // increment round, change nothing else
            EnterRound(bettingRound + 1, 0, 0, 0, true, false);
            return true;
        }

        // waiting on acting player
        bool validBet = HoldemPotMath.IsBetLegal(actingPlayerBet, actingSeat, callOnlyMask, currentBet,
            minimumRaise, stacks, roundContribution);

        int liveSeats = 0;
        for (int i = 0; i < seats; i++)
        {
            if (playerState[i] != PLAYER_DEAD) liveSeats++;
        }

        // Everyone else folded out of turn (left the table); nothing to wait on
        if (liveSeats < 2)
        {
            Log($"{liveSeats} live seats left, closing round");
            if (playerState[actingSeat] == PLAYER_ACTING) playerState[actingSeat] = PLAYER_COMMITED;
            callOnlyMask &= ~(1 << actingSeat);
        }
        // Explicit fold or player left - always fold
        else if ((actingPlayerBet == -1 && actingPlayerCommitted) || !actingPlayerSeated)
        {
            Log($"acting player {actingSeat} folded or left");
            RecordPokerAction(actingSeat, true, 0, currentBet, roundContribution[actingSeat], stacks[actingSeat], callOnlyMask);
            playerState[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 > actionTimeoutSecs)
        {
            bool canCheck = roundContribution[actingSeat] == currentBet;
            if (canCheck)
            {
                Log($"acting player {actingSeat} timed out, auto-checking");
                RecordPokerAction(actingSeat, false, 0, currentBet, roundContribution[actingSeat], stacks[actingSeat], callOnlyMask);
                playerState[actingSeat] = PLAYER_COMMITED;
                callOnlyMask &= ~(1 << actingSeat);
            }
            else
            {
                Log($"acting player {actingSeat} timed out, auto-folding (cannot check)");
                RecordPokerAction(actingSeat, true, 0, currentBet, roundContribution[actingSeat], stacks[actingSeat], callOnlyMask);
                playerState[actingSeat] = PLAYER_DEAD;
                callOnlyMask &= ~(1 << actingSeat);
            }
        }
        else if (actingPlayerCommitted && validBet)
        {
            Log($"acting player {actingSeat} committed to bet of {actingPlayerBet}");
            RecordPokerAction(actingSeat, false, actingPlayerBet, currentBet, roundContribution[actingSeat], stacks[actingSeat], callOnlyMask);
            // 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 (playerState[i] == PLAYER_COMMITED && stacks[i] > 0) 
                            playerState[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 (playerState[i] == PLAYER_COMMITED && stacks[i] > 0
                            && roundContribution[i] < currentBet)
                        {
                            playerState[i] = PLAYER_PENDING;
                            callOnlyMask |= (1 << i);
                        }
                    }
                }
            }

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

        // if we're here, next action
        int nextActor = (actingSeat + 1) % seats;
        while (nextActor != actingSeat && playerState[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 (playerState[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;
            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 && playerState[i] == PLAYER_COMMITED && stacks[i] > 0)
                {
                    playerState[i] = PLAYER_PENDING;
                    pendingPlayers++;
                }
            }
            Log($"round {bettingRound} over, {pendingPlayers} players pending, {alivePlayers} players alive");

            if (bettingRound == PREFLOP && alivePlayers > 1) PrepareFlopPokerStats();

            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)
                EnterRound(bettingRound, 0, 0, bigBlind, false, true);
                return true;
            }
            else if (bettingRound == RIVER)
            {
                // showdown
                EnterRound(SHOWDOWN, 0, 0, bigBlind, false, false);
                return true;
            } else if (pendingPlayers > 1) 
            {
                // regular new round
                int roundStart = (dealerSeat + 1) % seats;
                while (playerState[roundStart] != PLAYER_PENDING)
                    roundStart = (roundStart + 1) % seats;
                playerState[roundStart] = PLAYER_ACTING;

                EnterRound(bettingRound + 1, roundStart, 0, bigBlind, false, false);
                return true;
            }
            else
            {
                // heads-up new round
                // flip players back to committed, no more action possible
                for (int i = 0; i < seats; i++)
                {
                    if (playerState[i] == PLAYER_PENDING) playerState[i] = PLAYER_COMMITED;
                }
                EnterRound(bettingRound + 1, 0, 0, bigBlind, true, false);
                return true;
            }
        }
        else
        {
            Log($"action moving to {nextActor} in round {bettingRound}");
            // same round, new player
            playerState[nextActor] = PLAYER_ACTING;
            EnterRound(bettingRound, nextActor, currentBet, minimumRaise, false, false);
            return true;
        }
    
    }

    private void EnterRound(int round, int actor, int bet, int minRaise, bool headsUpRound, bool foldWin)
    {
        bettingRound = round;
        actingSeat = actor;
        currentBet = bet;
        minimumRaise = minRaise;
        headsUp = headsUpRound;
        wonByFold = foldWin;
    }

    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 bool IsValidBet(int bet, int seatIdx)
    {
        return HoldemPotMath.IsBetLegal(bet, seatIdx, callOnlyMask, currentBet, minimumRaise, stacks, roundContribution);
    }
    // ---- Core table/betting state, continued (declared earlier in the file too, near tableState/bettingRound/playerState) ----
    // 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 = HoldemDeckUtil.NewHiddenSeats();
    public int[] holeCards1 = HoldemDeckUtil.NewHiddenSeats();



    // community cards. -1 (no card) by default
    int flop0 = -1, flop1 = -1, flop2 = -1, turn = -1, river = -1;

    // 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
    public 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;

    // Set by the world's HoldemAuthority at start
    [HideInInspector] public HoldemAuthority authority;

    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;

    [HideInInspector] public bool animatedChipContainersEnabled;
    private bool chipPresentationModeReady;
    private int[] presentedPotContribution = new int[MAX_SEATS];
    private PokerChipPile activeChipTransferDestination;
    private float activeChipTransferFinishTime;
    private bool activeChipTransferFinalizes;
    private PokerChipPile[] queuedChipTransferDestinations = new PokerChipPile[MAX_SEATS];
    private int queuedChipTransferCount;

    public void SetAnimatedChipContainersEnabled(bool enabled)
    {
        if (chipPresentationModeReady && animatedChipContainersEnabled == enabled) return;

        bool firstInitialization = !chipPresentationModeReady;
        chipPresentationModeReady = true;
        animatedChipContainersEnabled = enabled;
        if (potPile != null) potPile.preservePhysicsPlacement = enabled;
        if (players != null)
        {
            for (int i = 0; i < players.Length; i++)
            {
                HoldemPlayer player = players[i];
                if (player != null && player.roundContributionPile != null)
                    player.roundContributionPile.preservePhysicsPlacement = enabled;
            }
        }
        if (!enabled || firstInitialization) ReconcileStaticChipPresentation();
        if (!enabled) _FreezeChipsToStaticLayout();
        _SnapshotPresentedPotContributions();
        uiEpoch = -1;

        if (potPile != null) potPile.OpenContainer();
        if (players == null) return;
        for (int i = 0; i < players.Length; i++)
        {
            HoldemPlayer player = players[i];
            if (player != null && player.roundContributionPile != null)
                player.roundContributionPile.OpenContainer();
        }
    }

    private void _FreezeChipsToStaticLayout()
    {
        if (potPile != null) potPile._FreezeChipsToStaticLayout();
        for (int i = 0; players != null && i < players.Length; i++)
        {
            HoldemPlayer player = players[i];
            if (player == null) continue;
            if (player.roundContributionPile != null) player.roundContributionPile._FreezeChipsToStaticLayout();
            if (player.playerPotPile != null) player.playerPotPile._FreezeChipsToStaticLayout();
        }
    }

    public bool _IsChipPresentationModeReady()
    {
        return chipPresentationModeReady;
    }

    private void ReconcileStaticChipPresentation()
    {
        _FinishActiveChipTransfer();

        int potTotal = 0;
        for (int i = 0; i < seats; i++)
        {
            potTotal += potContribution[i];
            HoldemPlayer player = players != null && i < players.Length ? players[i] : null;
            if (player != null && player.roundContributionPile != null)
                player.roundContributionPile.SetTotalChips(roundContribution[i]);
        }
        if (potPile != null) potPile.SetTotalChips(potTotal);
        _SnapshotPresentedPotContributions();
    }

    public void _SettleDynamicChipPresentationForWinners()
    {
        _FinishActiveChipTransfer();
        for (int i = 0; players != null && i < players.Length; i++)
        {
            HoldemPlayer player = players[i];
            if (player != null && player.roundContributionPile != null)
                player.roundContributionPile.SetTotalChips(0);
        }
        if (potPile != null) potPile.SetTotalChips(0);
        _SnapshotPresentedPotContributions();
    }

/// <summary>
    /// Static-mode counterpart of <see cref="_DistributeDynamicPotToWinners"/>: the winners' piles are filled by
    /// teleporting chips out of the pot, so a big pot stays a big pile instead of being recalculated into
    /// higher denominations.
    /// </summary>
    public void _DistributeStaticPotToWinners()
    {
        _FinishActiveChipTransfer();
        if (potPile == null) return;

        // A hand that ends without a closing betting update still has its last round on the table.
        for (int i = 0; players != null && i < players.Length; i++)
        {
            HoldemPlayer player = players[i];
            if (player == null || player.roundContributionPile == null) continue;
            player.roundContributionPile.TransferAllTo(potPile);
            player.roundContributionPile.SetTotalChips(0);
        }

        for (int i = 0; players != null && i < players.Length; i++)
        {
            HoldemPlayer player = players[i];
            if (player == null || player.playerPotPile == null) continue;

            PokerChipPile destination = player.playerPotPile;
            if (seatWinnings[i] <= 0)
            {
                destination.SetTotalChips(0);
                continue;
            }
            // Re-presenting the winner screen finds the pot already emptied and the winnings on display.
            if (potPile.GetTotalDisplayedValue() <= 0 && destination.GetTotalDisplayedValue() == seatWinnings[i]) continue;

            destination.SetTotalChips(0);
            int remaining = seatWinnings[i] - TransferHeldChipsValue(potPile, destination, seatWinnings[i]);
            if (remaining > 0) potPile.TransferValueApproximateTo(destination, remaining);
            // The won chips teleport straight to their final spot (no fall-in animation); stack them as one pile.
            destination._RestackLayout();
            destination.SetTotalChips(seatWinnings[i]);
        }

        potPile.SetTotalChips(0);
        _SnapshotPresentedPotContributions();
    }

/// <summary>
    /// Moves chips the source actually shows, largest denomination that fits first, until about
    /// <paramref name="targetValue"/> has moved. Unlike TransferValueApproximateTo it never spawns a larger
    /// denomination while smaller chips are on display. Returns the value moved.
    /// </summary>
    private int TransferHeldChipsValue(PokerChipPile source, PokerChipPile destination, int targetValue)
    {
        int remaining = targetValue;
        while (remaining > 0)
        {
            int bestDenomination = -1;
            int bestValue = 0;
            for (int d = 0; d < source.denominationValues.Length; d++)
            {
                int value = source.denominationValues[d];
                if (value <= 0 || value > remaining || value <= bestValue) continue;
                if (source.GetDisplayedDenominationCount(d) <= 0) continue;
                bestDenomination = d;
                bestValue = value;
            }
            if (bestDenomination < 0) break;

            int count = Mathf.Min(source.GetDisplayedDenominationCount(bestDenomination), remaining / bestValue);
            int moved = source.TransferDenominationTo(destination, bestDenomination, count);
            if (moved <= 0) break;
            remaining -= moved * bestValue;
        }
        return targetValue - remaining;
    }

public void _DistributeDynamicPotToWinners()
    {
        _FinishActiveChipTransfer();
        if (potPile == null) return;

        int winnerCount = 0;
        for (int i = 0; players != null && i < players.Length; i++)
        {
            HoldemPlayer player = players[i];
            if (player != null && player.roundContributionPile != null)
                player.roundContributionPile.SetTotalChips(0);
            if (player != null && player.playerPotPile != null && seatWinnings[i] > 0)
                winnerCount++;
        }

        int winnerIndex = 0;
        for (int i = 0; players != null && i < players.Length; i++)
        {
            HoldemPlayer player = players[i];
            if (player == null || player.playerPotPile == null || seatWinnings[i] <= 0) continue;

            winnerIndex++;
            PokerChipPile destination = player.playerPotPile;
            // Re-presenting the winner screen (e.g. after a chip-mode toggle) finds the pot already emptied; the
            // winnings are on display, so releasing the pile would wipe them with nothing left to transfer.
            if (potPile.GetTotalDisplayedValue() <= 0 && destination.GetTotalDisplayedValue() >= seatWinnings[i]) continue;
            destination.ReleaseAllToPools();
            player._PrepareDynamicPotPile();
            destination.BeginAnimatedGather(false);
            potPile.TransferApproximateValueAnimatedTo(destination, seatWinnings[i], winnerIndex == winnerCount);
            destination.OverrideText(seatWinnings[i].ToString());
            destination.StartAnimatedGather();
        }

        potPile.OverrideText("");
        _SnapshotPresentedPotContributions();
    }


    public void OpenPlayerChipContainer(HoldemPlayer player)
    {
        if (!animatedChipContainersEnabled || player == null || player.roundContributionPile == null) return;
        if (activeChipTransferDestination == player.roundContributionPile) EndActiveChipTransfer(false);
        player.roundContributionPile.OpenContainer();
    }

    public bool CollectCommittedChips(HoldemPlayer player)
    {
        if (!animatedChipContainersEnabled || player == null || player.roundContributionPile == null) return false;

        PokerChipPile destination = player.roundContributionPile;
        destination.BeginAnimatedGather(false);
        int moved = 0;
        if (player.betPile != null) moved += player.betPile.TransferAllAnimatedTo(destination);
        if (player.physicalRaisePile != null && player.physicalRaisePile.raisePile != null)
            moved += player.physicalRaisePile.raisePile.TransferAllAnimatedTo(destination);
        if (moved <= 0)
        {
            destination.EndAnimatedContraction();
            return false;
        }
        QueueOrBeginChipTransfer(destination);
        return true;
    }

    public void AnimateNewRoundChips(HoldemPlayer player, int deltaValue, Vector3 spawnOrigin)
    {
        if (!animatedChipContainersEnabled || player == null || player.roundContributionPile == null) return;
        PokerChipPile pile = player.roundContributionPile;
        pile.BeginAnimatedGather(false);
        
        pile.SpawnDynamicChips(deltaValue, spawnOrigin);
        QueueOrBeginChipTransfer(pile);
    }

    public bool CollectRoundPilesToPot()
    {
        if (!animatedChipContainersEnabled || potPile == null || tableState != TABLE_PLAYING) return false;
        int displayed = 0;
        for (int i = 0; players != null && i < players.Length; i++)
        {
            HoldemPlayer player = players[i];
            if (player == null || player.roundContributionPile == null) continue;

            PokerChipPile pile = player.roundContributionPile;
            int closedRoundValue = Mathf.Max(0, potContribution[i] - presentedPotContribution[i]);
            int missingValue = closedRoundValue - pile.GetTotalDisplayedValue();
            if (missingValue > 0)
                pile.SpawnDynamicChips(missingValue, pile.transform.position);
            displayed += pile.GetTotalDisplayedValue();
            presentedPotContribution[i] = potContribution[i];
        }
        if (displayed <= 0) return false;

        EndActiveChipTransfer(false);
        ClearQueuedChipTransfers();
        potPile.BeginAnimatedGather(true);
        int moved = 0;
        for (int i = 0; players != null && i < players.Length; i++)
        {
            HoldemPlayer player = players[i];
            if (player == null || player.roundContributionPile == null) continue;
            player.roundContributionPile.OpenContainer();
            moved += player.roundContributionPile.TransferAllAnimatedTo(potPile);
        }
        if (moved <= 0)
        {
            potPile.FinishAnimatedGather();
            return false;
        }
        BeginActiveChipTransfer(potPile, true);
        return true;
    }

    /// <summary>
    /// Static-mode counterpart of <see cref="CollectRoundPilesToPot"/>: tops each round pile up with the chips of
    /// the action that closed the round (it may have arrived in the same update as the close), then teleports
    /// the round chips into the pot so the pot grows by transfer instead of being recalculated.
    /// </summary>
    public bool _CollectRoundPilesToPotStatic()
    {
        if (animatedChipContainersEnabled || potPile == null || tableState != TABLE_PLAYING) return false;
        bool moved = false;
        int[] potBefore = new int[potPile.denominationValues.Length];
        potPile.CopyDisplayedDenominationCounts(potBefore);
        for (int i = 0; players != null && i < players.Length; i++)
        {
            HoldemPlayer player = players[i];
            if (player == null || player.roundContributionPile == null) continue;

            PokerChipPile pile = player.roundContributionPile;
            int closedRoundValue = Mathf.Max(0, potContribution[i] - presentedPotContribution[i]);
            int missingValue = closedRoundValue - pile.GetTotalDisplayedValue();
            if (missingValue > 0) _TakeBetChipsFromStack(i, pile, missingValue);
            if (pile.GetTotalDisplayedValue() > 0 && pile.TransferAllTo(potPile) > 0) moved = true;
        }
        if (moved) potPile.AnimateChipsAddedSince(potBefore);
        return moved;
    }

    /// <summary>
    /// Adds <paramref name="value"/> of bet chips to <paramref name="destination"/>, taking the seat's own stack
    /// chips only while the stack pile shows more than the synced stack. HoldemPlayer may already have redrawn the
    /// stack without the bet (its Update can run first, and call/physical presentation deducts before the commit);
    /// taking the bet from it again would show the stack short. The rest spawns from the pools.
    /// </summary>
    public void _TakeBetChipsFromStack(int seat, PokerChipPile destination, int value)
    {
        if (destination == null || value <= 0) return;
        HoldemPlayer player = players != null && seat >= 0 && seat < players.Length ? players[seat] : null;
        PokerChipPile stackPile = player != null ? player.stackPile : null;
        int fromStack = 0;
        if (stackPile != null && stacks != null && seat < stacks.Length)
        {
            int stackDisplayed = stackPile.GetTotalDisplayedValue();
            int stackExcess = stackDisplayed - Mathf.Max(0, stacks[seat]);
            int stackTarget = Mathf.Min(value, stackExcess);
            if (stackTarget > 0) fromStack = stackPile.TransferValueApproximateTo(destination, stackTarget);
        }
        int remaining = value - fromStack;
        if (remaining > 0) destination.AddValueFromPool(remaining);
    }

    public void _SnapshotPresentedPotContributions()
    {
        if (presentedPotContribution == null || presentedPotContribution.Length != MAX_SEATS)
            presentedPotContribution = new int[MAX_SEATS];
        for (int i = 0; i < MAX_SEATS; i++)
            presentedPotContribution[i] = potContribution != null && i < potContribution.Length
                ? potContribution[i]
                : 0;
    }

    public void _FinishActiveChipTransfer()
    {
        if (activeChipTransferDestination != null) activeChipTransferDestination.FinishAnimatedGather();
        activeChipTransferDestination = null;
        activeChipTransferFinishTime = 0f;
        activeChipTransferFinalizes = false;
        ClearQueuedChipTransfers();
        if (potPile != null) potPile.FinishAnimatedGather();
        for (int i = 0; players != null && i < players.Length; i++)
        {
            HoldemPlayer player = players[i];
            if (player != null && player.roundContributionPile != null)
                player.roundContributionPile.FinishAnimatedGather();
        }
    }

    public void _FinishActiveChipTransferDelayed()
    {
        if (activeChipTransferDestination == null) return;
        if (Time.time + 0.01f < activeChipTransferFinishTime)
        {
            SendCustomEventDelayedSeconds(nameof(_FinishActiveChipTransferDelayed), activeChipTransferFinishTime - Time.time);
            return;
        }
        bool finalize = activeChipTransferFinalizes;
        EndActiveChipTransfer(finalize);
        StartNextQueuedChipTransfer();
    }

    private void QueueOrBeginChipTransfer(PokerChipPile destination)
    {
        if (activeChipTransferDestination == null)
        {
            BeginActiveChipTransfer(destination, false);
            return;
        }
        if (activeChipTransferDestination == destination)
        {
            activeChipTransferFinishTime = Time.time + destination.AnimatedGatherDuration();
            return;
        }
        for (int i = 0; i < queuedChipTransferCount; i++)
            if (queuedChipTransferDestinations[i] == destination) return;
        if (queuedChipTransferCount < queuedChipTransferDestinations.Length)
            queuedChipTransferDestinations[queuedChipTransferCount++] = destination;
    }

    private void BeginActiveChipTransfer(PokerChipPile destination, bool finalize)
    {
        activeChipTransferDestination = destination;
        activeChipTransferFinalizes = finalize;
        destination.StartAnimatedGather();
        activeChipTransferFinishTime = Time.time + destination.AnimatedGatherDuration();
        SendCustomEventDelayedSeconds(nameof(_FinishActiveChipTransferDelayed), destination.AnimatedGatherDuration());
    }

    private void EndActiveChipTransfer(bool finalize)
    {
        if (activeChipTransferDestination != null)
        {
            if (finalize) activeChipTransferDestination.FinishAnimatedGather();
            else activeChipTransferDestination.EndAnimatedContraction();
        }
        activeChipTransferDestination = null;
        activeChipTransferFinishTime = 0f;
        activeChipTransferFinalizes = false;
    }

    private void StartNextQueuedChipTransfer()
    {
        if (queuedChipTransferCount <= 0) return;
        PokerChipPile destination = queuedChipTransferDestinations[0];
        for (int i = 1; i < queuedChipTransferCount; i++)
            queuedChipTransferDestinations[i - 1] = queuedChipTransferDestinations[i];
        queuedChipTransferDestinations[--queuedChipTransferCount] = null;
        if (destination != null) BeginActiveChipTransfer(destination, false);
    }

    private void ClearQueuedChipTransfers()
    {
        for (int i = 0; i < queuedChipTransferCount; i++)
        {
            if (queuedChipTransferDestinations[i] != null)
                queuedChipTransferDestinations[i].EndAnimatedContraction();
            queuedChipTransferDestinations[i] = null;
        }
        queuedChipTransferCount = 0;
    }



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

    // Seat syncs ask for an early transition, at most this often, so spamming them can't stall the master
    const float requestedTransitionInterval = 0.1f;
    private bool transitionRequested;
    private float lastOwnerTransitionTime = float.MinValue;

    public void _RequestTransition()
    {
        transitionRequested = true;
    }

    public int lastLocalEpoch = -1;

    // Inputs the status UI was last built from
    private int uiEpoch = -1;
    private int uiSeatChangeVersion = -1;
    private int uiSince = int.MinValue;
    private int uiLevelSeconds = int.MinValue;
    private bool uiTournamentMode;
    private bool uiTournamentActive;
    private int uiTournamentBuyIn;
    private int uiTournamentStartingStack;
    private float uiTournamentLevelDuration;
    public bool uiOwner;
    public bool uiOwnerKnown;

    // 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;

    public string winnerText = "winnerText";

    // ---- Unity/VRChat lifecycle & admin ----
    private void Start()
    {
        for (int i = 0; i < seats; ++i)
        {
            players[i].game = this;
            players[i].seatIdx = i;
        }
    }

    private void Update()
    {

        HoldemPresentation.HandleBettingRoundReveal(this, flop0, flop1, flop2, turn, river);
        HoldemPresentation.HandleTableStateTransition(this);

        if (highlightsDirty || highlightEpoch != epoch || highlightSeatChangeVersion != seatChangeVersion)
        {
            highlightEpoch = epoch;
            highlightSeatChangeVersion = seatChangeVersion;
            _RefreshHandHighlights();
        }

        bool isOwner = Networking.IsOwner(gameObject);

        HoldemPresentation.UpdateOwnerVisibility(this, isOwner);

        if (isOwner)
        {
            if (pendingCommitMask != 0) CommitNextSeat();

            bool due = (ownerUpdateCountdown -= Time.deltaTime) < 0;
            if (due || (transitionRequested && Time.time - lastOwnerTransitionTime >= requestedTransitionInterval))
            {
                ownerUpdateCountdown = updateInterval;
                transitionRequested = false;
                lastOwnerTransitionTime = Time.time;
                _Transition();
            }
        }

        var now = GetTimeMillis();

        // local stuff
        if (lastLocalEpoch != epoch)
        {
            HoldemPresentation.HandleEpochChange(this, now, flop0, flop1, flop2, turn, river);
        }

        var since = (now - lastTransitionMillis) / 1000;
        int levelSeconds = isTournamentActive ? (now - blindLevelStartMillis) / 1000 : 0;

        bool stateChanged = uiEpoch != epoch;
        if (!stateChanged && uiSeatChangeVersion == seatChangeVersion && uiSince == since && uiLevelSeconds == levelSeconds
            && uiTournamentMode == isTournamentMode && uiTournamentActive == isTournamentActive
            && uiTournamentBuyIn == tournamentBuyIn && uiTournamentStartingStack == tournamentStartingStack
            && uiTournamentLevelDuration == tournamentLevelDurationSeconds)
        {
            return;
        }
        uiEpoch = epoch;
        uiSeatChangeVersion = seatChangeVersion;
        uiSince = since;
        uiLevelSeconds = levelSeconds;
        uiTournamentMode = isTournamentMode;
        uiTournamentActive = isTournamentActive;
        uiTournamentBuyIn = tournamentBuyIn;
        uiTournamentStartingStack = tournamentStartingStack;
        uiTournamentLevelDuration = tournamentLevelDurationSeconds;

        HoldemPresentation.RefreshUI(this, since, levelSeconds, stateChanged);

    }

    public 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;
    }

    public 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();

    }

    // Ownership only moves to the new master when the owner leaves, which never asks
    public override bool OnOwnershipRequest(VRCPlayerApi requestingPlayer, VRCPlayerApi requestedOwner)
    {
        return false;
    }

    // Table buttons are pressed locally by the owner; the same events sent over the network are ignored
    private bool IsLocalOwnerAction()
    {
        return !NetworkCalling.InNetworkCall && Networking.IsOwner(gameObject);
    }

    



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

#if HOLDEM_DEBUG
    //Used to add initialStackSize to each player's balance.
    public void _GiveMoney()
    {
        if (!IsLocalOwnerAction())
        {
            return;
        }

        for (int Index = 0; Index < seats; Index++)
        {
            if (players[Index].IsSeated())
            {
                HoldemBalanceOps.ModifyBalanceForSeat(this, Index, initialStackSize);
            }
        }
        SerializeState();
        RequestSerialization();
    }
#endif

    // Master debug button: lifts every cheat flag in the world
    public void _ClearFlags()
    {
        if (!IsLocalOwnerAction() || authority == null) return;
        authority._ClearFlags();
    }

    public void _ResetGame()
    {
        if (!IsLocalOwnerAction()) return;
        Log("RESET GAME BUTTON PRESSED");
        tableState = TABLE_UNINITIALIZED;
        _Transition();
    }

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

        if (isTournamentActive)
        {
            return;
        }

        HoldemBalanceOps.UpdatePlayerBalances(seats, players, stacks, preTransitionStacks, lastBankBalances);
    }

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

        ulong[] handValues = wonByFold ? null : HoldemHandEvaluator.GetHandValues(
            seats, playerState, holeCards0, holeCards1, flop0, flop1, flop2, turn, river);
        HoldemBalanceOps.UpdatePlayerMetrics(this, preTransitionTableState, preTransitionPlayerState, handValues);
    }

    public void _StartTournament()
    {
        if (!IsLocalOwnerAction()) return;
        if (isTournamentActive) return;

        if (!HoldemTournament.TryStartTournament(this)) return;

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

    public void _CancelTournament()
    {
        if (!IsLocalOwnerAction()) return;
        if (!isTournamentActive) return;

        HoldemTournament.CancelTournament(this);

        tableState = TABLE_IDLE;
        SerializeState();
        RequestSerialization();
        _Transition();
    }

    public void _ToggleTournamentMode()
    {
        if (!IsLocalOwnerAction()) return;
        if (isTournamentActive) return;
        if (!isTournamentMode && tableState != TABLE_IDLE && tableState != TABLE_UNINITIALIZED) return;

        HoldemTournament.ToggleTournamentMode(this);

        SerializeState();
        RequestSerialization();
        _Transition();
    }

    private bool CanEditTournamentSettings()
    {
        return IsLocalOwnerAction() && !isTournamentActive;
    }

    public void _IncreaseBuyIn()
    {
        if (CanEditTournamentSettings()) HoldemTournament.AdjustBuyIn(this, 1);
    }

    public void _DecreaseBuyIn()
    {
        if (CanEditTournamentSettings()) HoldemTournament.AdjustBuyIn(this, -1);
    }

    public void _IncreaseStartingStack()
    {
        if (CanEditTournamentSettings()) HoldemTournament.AdjustStartingStack(this, 1);
    }

    public void _DecreaseStartingStack()
    {
        if (CanEditTournamentSettings()) HoldemTournament.AdjustStartingStack(this, -1);
    }

    public void _IncreaseBlindTimer()
    {
        if (CanEditTournamentSettings()) HoldemTournament.AdjustBlindTimer(this, 1);
    }

    public void _DecreaseBlindTimer()
    {
        if (CanEditTournamentSettings()) HoldemTournament.AdjustBlindTimer(this, -1);
    }
}
