using NUnit.Framework;
using UnityEngine;

// Coverage for the pure betting/table state machines and the blind helpers around them.
public class BettingLogicTests
{
    private GameObject gameGo;
    private HoldemGame game;

    // CalculateGameTransition result layout.
    private const int R_ROUND = 0, R_ACTOR = 1, R_BET = 2, R_MINRAISE = 3, R_HEADSUP = 4,
                      R_WONBYFOLD = 5, R_STATE = 6, R_STACKS = 7, R_ROUNDCONTRIB = 8,
                      R_POTCONTRIB = 9, R_AGGRESSOR = 10, R_CALLONLY = 11;

    private const System.Reflection.BindingFlags PRIVATE_INSTANCE =
        System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance;

    [SetUp]
    public void SetUp()
    {
        gameGo = new GameObject("HoldemGameTest");
        game = gameGo.AddComponent<HoldemGame>();
        game.seats = 10;

        game.players = new HoldemPlayer[10];
        for (int i = 0; i < 10; i++)
        {
            var pGo = new GameObject("Player_" + i);
            pGo.transform.SetParent(gameGo.transform);
            game.players[i] = pGo.AddComponent<HoldemPlayer>();
            game.players[i].game = game;
            game.players[i].seatIdx = i;
        }
    }

    [TearDown]
    public void TearDown()
    {
        Object.DestroyImmediate(gameGo);
    }

    private object Invoke(string method, params object[] args)
    {
        var m = typeof(HoldemGame).GetMethod(method, PRIVATE_INSTANCE);
        Assert.IsNotNull(m, $"{method} should exist");
        return m.Invoke(game, args);
    }

    // ------------------------------------------------------- short all-in call-only rights

    [Test]
    public void TestIsValidBet_CallOnlySeatMayOnlyCall()
    {
        game.stacks[0] = 5000;
        game.roundContribution[0] = 2500;
        game.currentBet = 3500;
        game.minimumRaise = 2500;
        game.callOnlyMask = 1;

        Assert.IsTrue(game.IsValidBet(1000, 0), "Calling the extra 1000 is the one legal wager");
        Assert.IsFalse(game.IsValidBet(3500, 0), "A call-only seat cannot re-raise");
        Assert.IsFalse(game.IsValidBet(5000, 0), "A call-only seat cannot shove over the top");
        Assert.IsFalse(game.IsValidBet(500, 0), "A call-only seat cannot underpay while it still has chips");

        game.callOnlyMask = 0;
        Assert.IsTrue(game.IsValidBet(3500, 0), "Clearing the flag restores raising rights");
    }

    [Test]
    public void TestIsValidBet_CallOnlySeatShorterThanTheCallMayStillShove()
    {
        game.stacks[0] = 400;
        game.roundContribution[0] = 2500;
        game.currentBet = 3500;
        game.minimumRaise = 2500;
        game.callOnlyMask = 1;

        Assert.IsTrue(game.IsValidBet(400, 0), "Shoving for less than the call is allowed");
        Assert.IsFalse(game.IsValidBet(200, 0), "Anything short of the whole stack is not");
    }

    [Test]
    public void TestGameTransition_FullRaiseClearsCallOnlyAndReopensRaising()
    {
        // Seat 0 is call-only from an earlier short all-in; seat 1 now makes a legal full raise.
        int[] playerState = new int[10] { HoldemGame.PLAYER_PENDING, HoldemGame.PLAYER_ACTING, 0, 0, 0, 0, 0, 0, 0, 0 };
        int[] stacks = new int[10] { 5000, 20000, 0, 0, 0, 0, 0, 0, 0, 0 };
        int[] roundContribution = new int[10] { 2500, 0, 0, 0, 0, 0, 0, 0, 0, 0 };

        object[] result = game.CalculateGameTransition(
            lastTransitionMillis: 0, bettingRound: HoldemGame.FLOP, actingSeat: 1,
            currentBet: 3500, minimumRaise: 2500, headsUp: false,
            currentPlayerState: playerState, stacks: stacks,
            roundContribution: roundContribution, potContribution: new int[10],
            nowMillis: 1000, actTimeoutSecs: 16, headsUpTimeoutSecs: 3, bigBlind: 100,
            dealerSeat: 0, actingPlayerSeated: true,
            actingPlayerBet: 6000, actingPlayerCommitted: true, aggressorSeat: 1, callOnlyMask: 1);

        Assert.IsNotNull(result);
        Assert.AreEqual(0, (int)result[R_CALLONLY], "A legal full raise gives everyone their raising rights back");
        Assert.AreEqual(6000, (int)result[R_BET]);
        Assert.AreEqual(2500, (int)result[R_MINRAISE]);
    }

    [Test]
    public void TestIsValidBet_UnactedSeatSizesAReRaiseOffTheLastFullRaise()
    {
        // Seat 0 bet 100, seat 2 shoved 105. The incomplete 5 rides along -- it does not
        // become the new raise increment -- so an unflagged seat still has to reach 205.
        game.stacks[1] = 1000;
        game.roundContribution[1] = 0;
        game.currentBet = 105;
        game.minimumRaise = 100;
        game.callOnlyMask = 1; // seat 0 only

        Assert.IsTrue(game.IsValidBet(105, 1), "Seat 1 can just call the shove");
        Assert.IsTrue(game.IsValidBet(205, 1), "currentBet plus the last full raise is the minimum re-raise");
        Assert.IsFalse(game.IsValidBet(204, 1), "One chip short of a full raise is not a raise");
        Assert.IsFalse(game.IsValidBet(110, 1), "Raising by only the incomplete increment is not enough");
    }

    [Test]
    public void TestGameTransition_ShortAllInDoesNotFlagASeatThatHasNotActed()
    {
        // Seat 0 has acted (in for 100), seat 1 has not acted at all, seat 2 shoves short.
        int[] playerState = new int[10] { HoldemGame.PLAYER_COMMITED, HoldemGame.PLAYER_PENDING, HoldemGame.PLAYER_ACTING, 0, 0, 0, 0, 0, 0, 0 };
        int[] stacks = new int[10] { 1000, 1000, 105, 0, 0, 0, 0, 0, 0, 0 };
        int[] roundContribution = new int[10] { 100, 0, 0, 0, 0, 0, 0, 0, 0, 0 };

        object[] shove = game.CalculateGameTransition(
            lastTransitionMillis: 0, bettingRound: HoldemGame.FLOP, actingSeat: 2,
            currentBet: 100, minimumRaise: 100, headsUp: false,
            currentPlayerState: playerState, stacks: stacks,
            roundContribution: roundContribution, potContribution: new int[10],
            nowMillis: 1000, actTimeoutSecs: 16, headsUpTimeoutSecs: 3, bigBlind: 100,
            dealerSeat: 0, actingPlayerSeated: true,
            actingPlayerBet: 105, actingPlayerCommitted: true, aggressorSeat: 0, callOnlyMask: 0);

        Assert.IsNotNull(shove);
        int mask = (int)shove[R_CALLONLY];
        Assert.AreEqual(1 << 0, mask & (1 << 0), "Seat 0 already acted, so it loses its raising rights");
        Assert.AreEqual(0, mask & (1 << 1), "Seat 1 has not acted yet and keeps full raising rights");
        Assert.AreEqual(0, mask & (1 << 2), "The all-in seat itself is not call-only");
        Assert.AreEqual(105, (int)shove[R_BET], "currentBet moves up to the shove");
        Assert.AreEqual(100, (int)shove[R_MINRAISE], "An incomplete raise does not become the new increment");
    }

    [Test]
    public void TestGameTransition_UnactedSeatReRaisesOverShortAllInAndReopensEveryone()
    {
        // Same three seats, played all the way through: seat 2 shoves short, seat 0 is stuck
        // with a call, then seat 1 -- who never acted -- puts in a legal full raise.
        int[] playerState = new int[10] { HoldemGame.PLAYER_COMMITED, HoldemGame.PLAYER_PENDING, HoldemGame.PLAYER_ACTING, 0, 0, 0, 0, 0, 0, 0 };
        int[] stacks = new int[10] { 1000, 1000, 105, 0, 0, 0, 0, 0, 0, 0 };
        int[] roundContribution = new int[10] { 100, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
        int[] potContribution = new int[10];

        // The arrays are mutated in place, so each step feeds the next.
        object[] shove = game.CalculateGameTransition(
            lastTransitionMillis: 0, bettingRound: HoldemGame.FLOP, actingSeat: 2,
            currentBet: 100, minimumRaise: 100, headsUp: false,
            currentPlayerState: playerState, stacks: stacks,
            roundContribution: roundContribution, potContribution: potContribution,
            nowMillis: 1000, actTimeoutSecs: 16, headsUpTimeoutSecs: 3, bigBlind: 100,
            dealerSeat: 0, actingPlayerSeated: true,
            actingPlayerBet: 105, actingPlayerCommitted: true, aggressorSeat: 0, callOnlyMask: 0);

        Assert.IsNotNull(shove);
        Assert.AreEqual(0, (int)shove[R_ACTOR], "Seat 0 is first back in line");

        // Seat 0 is call-only and pays the extra 5.
        object[] call = game.CalculateGameTransition(
            lastTransitionMillis: 1000, bettingRound: HoldemGame.FLOP, actingSeat: 0,
            currentBet: (int)shove[R_BET], minimumRaise: (int)shove[R_MINRAISE], headsUp: false,
            currentPlayerState: playerState, stacks: stacks,
            roundContribution: roundContribution, potContribution: potContribution,
            nowMillis: 2000, actTimeoutSecs: 16, headsUpTimeoutSecs: 3, bigBlind: 100,
            dealerSeat: 0, actingPlayerSeated: true,
            actingPlayerBet: 5, actingPlayerCommitted: true, aggressorSeat: 2,
            callOnlyMask: (int)shove[R_CALLONLY]);

        Assert.IsNotNull(call);
        Assert.AreEqual(0, (int)call[R_CALLONLY], "Seat 0's flag clears once it has called");
        Assert.AreEqual(1, (int)call[R_ACTOR], "Action passes to the seat that never acted");

        // Seat 1 re-raises to 205 -- a full raise on top of the shove.
        object[] reraise = game.CalculateGameTransition(
            lastTransitionMillis: 2000, bettingRound: HoldemGame.FLOP, actingSeat: 1,
            currentBet: (int)call[R_BET], minimumRaise: (int)call[R_MINRAISE], headsUp: false,
            currentPlayerState: playerState, stacks: stacks,
            roundContribution: roundContribution, potContribution: potContribution,
            nowMillis: 3000, actTimeoutSecs: 16, headsUpTimeoutSecs: 3, bigBlind: 100,
            dealerSeat: 0, actingPlayerSeated: true,
            actingPlayerBet: 205, actingPlayerCommitted: true, aggressorSeat: 2,
            callOnlyMask: (int)call[R_CALLONLY]);

        Assert.IsNotNull(reraise);
        Assert.AreEqual(205, (int)reraise[R_BET], "The re-raise stands");
        Assert.AreEqual(100, (int)reraise[R_MINRAISE], "minimumRaise stays at the last full raise");
        Assert.AreEqual(1, (int)reraise[R_AGGRESSOR], "Seat 1 is the aggressor now");
        Assert.AreEqual(0, (int)reraise[R_CALLONLY], "Nobody is call-only against a legal full raise");

        int[] states = (int[])reraise[R_STATE];
        Assert.AreEqual(0, (int)reraise[R_ACTOR], "Seat 0 has to answer the raise");
        Assert.AreEqual(HoldemGame.PLAYER_ACTING, states[0], "Seat 0 is reopened with full raising rights");
        Assert.AreEqual(HoldemGame.PLAYER_COMMITED, states[2], "The all-in seat has nothing left to decide");
    }

    [Test]
    public void TestSerializationRoundTripsCallOnlyMask()
    {
        game.playerState[0] = HoldemGame.PLAYER_PENDING;
        game.playerState[1] = HoldemGame.PLAYER_COMMITED;
        game.playerState[2] = HoldemGame.PLAYER_ACTING;
        game.callOnlyMask = (1 << 0) | (1 << 2);

        Invoke("SerializeState");
        game.playerState = new int[10];
        game.callOnlyMask = 0;
        Invoke("DeserializeState");

        Assert.AreEqual((1 << 0) | (1 << 2), game.callOnlyMask, "call-only bits survive the packet");
        Assert.AreEqual(HoldemGame.PLAYER_PENDING, game.playerState[0], "the state itself is unharmed");
        Assert.AreEqual(HoldemGame.PLAYER_COMMITED, game.playerState[1]);
        Assert.AreEqual(HoldemGame.PLAYER_ACTING, game.playerState[2]);
    }

    // ---------------------------------------------------------------- IsValidBet

    [Test]
    public void TestIsValidBet_CallRaiseAndAllIn()
    {
        game.stacks[0] = 1000;
        game.roundContribution[0] = 50;
        game.currentBet = 100;
        game.minimumRaise = 100;

        Assert.IsTrue(game.IsValidBet(50, 0), "Completing the call to 100 is valid");
        Assert.IsTrue(game.IsValidBet(150, 0), "Raising to exactly currentBet + minimumRaise is valid");
        Assert.IsTrue(game.IsValidBet(400, 0), "Raising beyond the minimum is valid");
        Assert.IsTrue(game.IsValidBet(1000, 0), "Shoving the whole stack is valid");

        Assert.IsFalse(game.IsValidBet(149, 0), "A raise short of minimumRaise is not valid");
        Assert.IsFalse(game.IsValidBet(20, 0), "Betting less than the call is not valid");
        Assert.IsFalse(game.IsValidBet(1001, 0), "Betting more than the stack is not valid");
    }

    [Test]
    public void TestIsValidBet_ShortAllInIsAllowedBelowMinimumRaise()
    {
        // 120 neither calls (100) nor makes a full raise (would need 200), but it is
        // everything the seat has, so it has to be legal.
        game.stacks[1] = 120;
        game.roundContribution[1] = 0;
        game.currentBet = 100;
        game.minimumRaise = 100;

        Assert.IsTrue(game.IsValidBet(120, 1), "A short all-in is always a legal action");
        Assert.IsFalse(game.IsValidBet(119, 1), "One chip short of all-in is neither a call nor a raise");
    }

    [Test]
    public void TestIsValidBet_CheckWhenNothingToCall()
    {
        game.stacks[2] = 500;
        game.roundContribution[2] = 0;
        game.currentBet = 0;
        game.minimumRaise = 100;

        Assert.IsTrue(game.IsValidBet(0, 2), "Checking a 0 bet is valid when there is nothing to call");
        Assert.IsFalse(game.IsValidBet(50, 2), "An opening bet below the minimum raise is not valid");
        Assert.IsTrue(game.IsValidBet(100, 2), "An opening bet of the minimum raise is valid");
    }

    // ------------------------------------------------------- blind sizing helpers

    [Test]
    public void TestCalculateMedianStack_OddAndEvenCounts()
    {
        int[] stacks = new int[10] { 100, 300, 200, 0, 0, 0, 0, 0, 0, 0 };
        bool[] ready = new bool[10] { true, true, true, false, false, false, false, false, false, false };
        Assert.AreEqual(200, (int)Invoke("CalculateMedianStack", stacks, ready), "Odd count takes the middle stack");

        stacks[3] = 400;
        ready[3] = true;
        Assert.AreEqual(250, (int)Invoke("CalculateMedianStack", stacks, ready), "Even count averages the two middle stacks");
    }

    [Test]
    public void TestCalculateMedianStack_IgnoresUnreadySeatsAndEmptyTable()
    {
        int[] stacks = new int[10] { 100, 999999, 300, 0, 0, 0, 0, 0, 0, 0 };
        bool[] ready = new bool[10] { true, false, true, false, false, false, false, false, false, false };

        Assert.AreEqual(200, (int)Invoke("CalculateMedianStack", stacks, ready),
            "A seat that isn't stacked and ready must not skew the median");

        Assert.AreEqual(0, (int)Invoke("CalculateMedianStack", stacks, new bool[10]),
            "No ready players means no median");
    }

    [Test]
    public void TestCalculateBigBlindFromMedian_RoundsUpToTenAndRespectsFloor()
    {
        // 7500 / 75 = 100 exactly.
        Assert.AreEqual(100, (int)Invoke("CalculateBigBlindFromMedian", 7500, 75, 10));
        // 825 / 75 = 11, which rounds up to the next multiple of 10.
        Assert.AreEqual(20, (int)Invoke("CalculateBigBlindFromMedian", 825, 75, 10));
        // Tiny stacks fall back to the configured floor.
        Assert.AreEqual(10, (int)Invoke("CalculateBigBlindFromMedian", 100, 75, 10));
        Assert.AreEqual(50, (int)Invoke("CalculateBigBlindFromMedian", 100, 75, 50), "The floor wins when it is higher");
    }

    [Test]
    public void TestCalculateBigBlindFromMedian_GuardsDegenerateInput()
    {
        Assert.AreEqual(10, (int)Invoke("CalculateBigBlindFromMedian", 0, 75, 10), "An empty table cannot divide by the median");
        Assert.AreEqual(10, (int)Invoke("CalculateBigBlindFromMedian", 7500, 0, 10), "A zero divisor must not divide by zero");
        Assert.AreEqual(10, (int)Invoke("CalculateBigBlindFromMedian", -500, 75, 10));
    }

    // ------------------------------------------------------------- NextReadySeat

    [Test]
    public void TestNextReadySeat_SkipsEmptySeatsAndWraps()
    {
        bool[] ready = new bool[10];
        ready[2] = true;
        ready[5] = true;

        Assert.AreEqual(2, (int)Invoke("NextReadySeat", 0, ready), "Skips seat 1");
        Assert.AreEqual(5, (int)Invoke("NextReadySeat", 2, ready));
        Assert.AreEqual(2, (int)Invoke("NextReadySeat", 5, ready), "Wraps past seat 9 back around to seat 2");
    }

    [Test]
    public void TestNextReadySeat_ReturnsStartWhenNobodyElseIsReady()
    {
        bool[] ready = new bool[10];
        ready[3] = true;

        Assert.AreEqual(3, (int)Invoke("NextReadySeat", 3, ready), "A lone ready seat is its own successor");
        Assert.AreEqual(0, (int)Invoke("NextReadySeat", 0, new bool[10]), "No ready seats at all falls back to the start");
    }

    // ---------------------------------------------------------------- SetupBlinds

    [Test]
    public void TestSetupBlinds_ThreeHandedSkipsEmptySeats()
    {
        int[] playerState = new int[10];
        int[] stacks = new int[10];
        int[] roundContribution = new int[10];
        bool[] ready = new bool[10];
        foreach (int seat in new int[] { 2, 5, 8 })
        {
            stacks[seat] = 1000;
            ready[seat] = true;
        }

        object[] args = new object[] { 0 /* last dealer */, 100 /* BB */, playerState, stacks, roundContribution, ready };
        object[] setup = (object[])Invoke("SetupBlinds", args);

        int actingSeat = (int)setup[0], dealerSeat = (int)setup[1], aggressorSeat = (int)setup[2];

        Assert.AreEqual(2, dealerSeat, "The button moves to the next occupied seat after the last dealer");
        Assert.AreEqual(50, roundContribution[5], "Seat 5 is the small blind");
        Assert.AreEqual(950, stacks[5]);
        Assert.AreEqual(100, roundContribution[8], "Seat 8 is the big blind");
        Assert.AreEqual(900, stacks[8]);
        Assert.AreEqual(2, actingSeat, "Three-handed, the button acts first pre-flop");
        Assert.AreEqual(HoldemGame.PLAYER_ACTING, playerState[2]);
        Assert.AreEqual(8, aggressorSeat, "The big blind is the standing aggressor pre-flop");
        Assert.AreEqual(0, roundContribution[2], "The button posts nothing three-handed");
    }

    [Test]
    public void TestSetupBlinds_OddBigBlindHalvesDownForTheSmallBlind()
    {
        int[] playerState = new int[10];
        int[] stacks = new int[10] { 1000, 1000, 1000, 0, 0, 0, 0, 0, 0, 0 };
        int[] roundContribution = new int[10];
        bool[] ready = new bool[10] { true, true, true, false, false, false, false, false, false, false };

        // Last dealer was seat 2, so the button lands on seat 0, small blind 1, big blind 2.
        object[] args = new object[] { 2, 25, playerState, stacks, roundContribution, ready };
        Invoke("SetupBlinds", args);

        // Integer division: a 25 big blind posts a 12 small blind, and the chip is not conjured.
        Assert.AreEqual(12, roundContribution[1], "Small blind is bigBlind / 2, rounded down");
        Assert.AreEqual(988, stacks[1]);
        Assert.AreEqual(25, roundContribution[2]);
        Assert.AreEqual(975, stacks[2]);
    }

    // ------------------------------------------------- CalculateTableTransition

    private int TableTransition(int state, int lastMillis, int nowMillis, int bettingRound, bool wonByFold,
                                bool[] seated, bool[] ready, int[] stacks)
    {
        return game.CalculateTableTransition(
            state, lastMillis, nowMillis, bettingRound, wonByFold,
            100 /* bigBlind */, 10 /* winnerTimeoutSecs */, 5 /* readyTimeoutSecs */,
            seated, ready, stacks);
    }

    private void SeatPlayers(bool[] seated, bool[] ready, int[] stacks, int count, int stack)
    {
        for (int i = 0; i < count; i++)
        {
            seated[i] = true;
            ready[i] = true;
            stacks[i] = stack;
        }
    }

    [Test]
    public void TestTableTransition_UninitializedBecomesIdle()
    {
        Assert.AreEqual(HoldemGame.TABLE_IDLE,
            TableTransition(HoldemGame.TABLE_UNINITIALIZED, 0, 0, HoldemGame.NOT_PLAYING, false,
                new bool[10], new bool[10], new int[10]));
    }

    [Test]
    public void TestTableTransition_IdleNeedsTwoPlayersWhoCanCoverTheBigBlind()
    {
        bool[] seated = new bool[10];
        bool[] ready = new bool[10];
        int[] stacks = new int[10];
        SeatPlayers(seated, ready, stacks, 2, 1000);

        Assert.AreEqual(HoldemGame.TABLE_READY,
            TableTransition(HoldemGame.TABLE_IDLE, 0, 0, HoldemGame.NOT_PLAYING, false, seated, ready, stacks),
            "Two funded, ready players start the clock");

        // One of them cannot cover the 100 big blind.
        stacks[1] = 99;
        Assert.AreEqual(HoldemGame.TABLE_IDLE,
            TableTransition(HoldemGame.TABLE_IDLE, 0, 0, HoldemGame.NOT_PLAYING, false, seated, ready, stacks),
            "A seat short of the big blind does not count towards starting a hand");

        // Funded but not ready.
        stacks[1] = 1000;
        ready[1] = false;
        Assert.AreEqual(HoldemGame.TABLE_IDLE,
            TableTransition(HoldemGame.TABLE_IDLE, 0, 0, HoldemGame.NOT_PLAYING, false, seated, ready, stacks),
            "A seated player who has not readied up does not count either");
    }

    [Test]
    public void TestTableTransition_ReadyDealsAfterTimeoutAndBacksOutIfPlayersLeave()
    {
        bool[] seated = new bool[10];
        bool[] ready = new bool[10];
        int[] stacks = new int[10];
        SeatPlayers(seated, ready, stacks, 2, 1000);

        Assert.AreEqual(HoldemGame.TABLE_READY,
            TableTransition(HoldemGame.TABLE_READY, 0, 3000, HoldemGame.NOT_PLAYING, false, seated, ready, stacks),
            "Still inside the 5s ready countdown");

        Assert.AreEqual(HoldemGame.TABLE_PLAYING,
            TableTransition(HoldemGame.TABLE_READY, 0, 6000, HoldemGame.NOT_PLAYING, false, seated, ready, stacks),
            "Past the countdown, deal");

        seated[1] = false;
        ready[1] = false;
        Assert.AreEqual(HoldemGame.TABLE_IDLE,
            TableTransition(HoldemGame.TABLE_READY, 0, 3000, HoldemGame.NOT_PLAYING, false, seated, ready, stacks),
            "Dropping below two players cancels the deal");
    }

    [Test]
    public void TestTableTransition_PlayingEndsOnFoldWinShowdownOrEmptyTable()
    {
        bool[] seated = new bool[10];
        bool[] ready = new bool[10];
        int[] stacks = new int[10];
        SeatPlayers(seated, ready, stacks, 3, 1000);

        Assert.AreEqual(HoldemGame.TABLE_PLAYING,
            TableTransition(HoldemGame.TABLE_PLAYING, 0, 1000, HoldemGame.FLOP, false, seated, ready, stacks),
            "A hand in progress stays in progress");

        Assert.AreEqual(HoldemGame.TABLE_WINNER,
            TableTransition(HoldemGame.TABLE_PLAYING, 0, 1000, HoldemGame.FLOP, true, seated, ready, stacks),
            "wonByFold ends the hand on any street");

        Assert.AreEqual(HoldemGame.TABLE_WINNER,
            TableTransition(HoldemGame.TABLE_PLAYING, 0, 1000, HoldemGame.SHOWDOWN, false, seated, ready, stacks),
            "Passing the river ends the hand");

        Assert.AreEqual(HoldemGame.TABLE_IDLE,
            TableTransition(HoldemGame.TABLE_PLAYING, 0, 1000, HoldemGame.FLOP, false, new bool[10], new bool[10], stacks),
            "Everyone leaving mid-hand drops the table back to idle");
    }

    [Test]
    public void TestTableTransition_WinnerHoldsUntilDisplayTimeout()
    {
        bool[] seated = new bool[10];
        bool[] ready = new bool[10];
        int[] stacks = new int[10];
        SeatPlayers(seated, ready, stacks, 2, 1000);

        Assert.AreEqual(HoldemGame.TABLE_WINNER,
            TableTransition(HoldemGame.TABLE_WINNER, 0, 9000, HoldemGame.RIVER, true, seated, ready, stacks),
            "The winner is shown for the full 10s");

        Assert.AreEqual(HoldemGame.TABLE_IDLE,
            TableTransition(HoldemGame.TABLE_WINNER, 0, 11000, HoldemGame.RIVER, true, seated, ready, stacks));
    }

    // -------------------------------------------------- CalculateGameTransition

    [Test]
    public void TestGameTransition_TimeoutAutoChecksWhenNothingToCall()
    {
        int[] playerState = new int[10] { HoldemGame.PLAYER_COMMITED, HoldemGame.PLAYER_ACTING, HoldemGame.PLAYER_PENDING, 0, 0, 0, 0, 0, 0, 0 };
        int[] stacks = new int[10] { 1000, 1000, 1000, 0, 0, 0, 0, 0, 0, 0 };
        int[] roundContribution = new int[10] { 100, 100, 100, 0, 0, 0, 0, 0, 0, 0 };

        object[] result = game.CalculateGameTransition(
            lastTransitionMillis: 0, bettingRound: HoldemGame.FLOP, actingSeat: 1,
            currentBet: 100, minimumRaise: 100, headsUp: false,
            currentPlayerState: playerState, stacks: stacks,
            roundContribution: roundContribution, potContribution: new int[10],
            nowMillis: 20000, actTimeoutSecs: 16, headsUpTimeoutSecs: 3, bigBlind: 100,
            dealerSeat: 0, actingPlayerSeated: true,
            actingPlayerBet: 0, actingPlayerCommitted: false, aggressorSeat: 0, callOnlyMask: 0);

        Assert.IsNotNull(result, "A timeout is a state change");
        Assert.AreEqual(HoldemGame.PLAYER_COMMITED, ((int[])result[R_STATE])[1],
            "A player facing no bet should be checked down, not folded");
        Assert.AreEqual(1000, ((int[])result[R_STACKS])[1], "Auto-checking costs nothing");
        Assert.AreEqual(2, (int)result[R_ACTOR]);
    }

    [Test]
    public void TestGameTransition_TimeoutFoldsWhenFacingABet()
    {
        int[] playerState = new int[10] { HoldemGame.PLAYER_COMMITED, HoldemGame.PLAYER_ACTING, HoldemGame.PLAYER_PENDING, 0, 0, 0, 0, 0, 0, 0 };
        int[] stacks = new int[10] { 1000, 1000, 1000, 0, 0, 0, 0, 0, 0, 0 };
        int[] roundContribution = new int[10] { 100, 0, 100, 0, 0, 0, 0, 0, 0, 0 };

        object[] result = game.CalculateGameTransition(
            lastTransitionMillis: 0, bettingRound: HoldemGame.FLOP, actingSeat: 1,
            currentBet: 100, minimumRaise: 100, headsUp: false,
            currentPlayerState: playerState, stacks: stacks,
            roundContribution: roundContribution, potContribution: new int[10],
            nowMillis: 20000, actTimeoutSecs: 16, headsUpTimeoutSecs: 3, bigBlind: 100,
            dealerSeat: 0, actingPlayerSeated: true,
            actingPlayerBet: 0, actingPlayerCommitted: false, aggressorSeat: 0, callOnlyMask: 0);

        Assert.IsNotNull(result);
        Assert.AreEqual(HoldemGame.PLAYER_DEAD, ((int[])result[R_STATE])[1],
            "Timing out with chips owed to the pot folds the hand");
        Assert.AreEqual(1000, ((int[])result[R_STACKS])[1], "A timeout fold must not pay the call");
    }

    [Test]
    public void TestGameTransition_WaitingOnTheActingPlayerReturnsNull()
    {
        int[] playerState = new int[10] { HoldemGame.PLAYER_COMMITED, HoldemGame.PLAYER_ACTING, HoldemGame.PLAYER_PENDING, 0, 0, 0, 0, 0, 0, 0 };
        int[] stacks = new int[10] { 1000, 1000, 1000, 0, 0, 0, 0, 0, 0, 0 };

        object[] result = game.CalculateGameTransition(
            lastTransitionMillis: 0, bettingRound: HoldemGame.FLOP, actingSeat: 1,
            currentBet: 100, minimumRaise: 100, headsUp: false,
            currentPlayerState: playerState, stacks: stacks,
            roundContribution: new int[10] { 100, 0, 100, 0, 0, 0, 0, 0, 0, 0 }, potContribution: new int[10],
            nowMillis: 1000, actTimeoutSecs: 16, headsUpTimeoutSecs: 3, bigBlind: 100,
            dealerSeat: 0, actingPlayerSeated: true,
            actingPlayerBet: 0, actingPlayerCommitted: false, aggressorSeat: 0, callOnlyMask: 0);

        Assert.IsNull(result, "Nothing has happened yet, so there is nothing to serialize");
        Assert.AreEqual(HoldemGame.PLAYER_ACTING, playerState[1], "The acting player is left alone");
    }

    [Test]
    public void TestGameTransition_IllegalBetIsIgnored()
    {
        int[] playerState = new int[10] { HoldemGame.PLAYER_COMMITED, HoldemGame.PLAYER_ACTING, HoldemGame.PLAYER_PENDING, 0, 0, 0, 0, 0, 0, 0 };
        int[] stacks = new int[10] { 1000, 1000, 1000, 0, 0, 0, 0, 0, 0, 0 };
        int[] roundContribution = new int[10] { 100, 0, 100, 0, 0, 0, 0, 0, 0, 0 };

        // 5 chips against a bet of 100 is neither a call, a legal raise, nor an all-in.
        object[] result = game.CalculateGameTransition(
            lastTransitionMillis: 0, bettingRound: HoldemGame.FLOP, actingSeat: 1,
            currentBet: 100, minimumRaise: 100, headsUp: false,
            currentPlayerState: playerState, stacks: stacks,
            roundContribution: roundContribution, potContribution: new int[10],
            nowMillis: 1000, actTimeoutSecs: 16, headsUpTimeoutSecs: 3, bigBlind: 100,
            dealerSeat: 0, actingPlayerSeated: true,
            actingPlayerBet: 5, actingPlayerCommitted: true, aggressorSeat: 0, callOnlyMask: 0);

        Assert.IsNull(result, "An illegal bet must not advance the game");
        Assert.AreEqual(1000, stacks[1], "An illegal bet must not take chips");
        Assert.AreEqual(0, roundContribution[1]);
    }

    [Test]
    public void TestGameTransition_FullRaiseReopensActionAndRatchetsMinimumRaise()
    {
        int[] playerState = new int[10] { HoldemGame.PLAYER_COMMITED, HoldemGame.PLAYER_COMMITED, HoldemGame.PLAYER_ACTING, 0, 0, 0, 0, 0, 0, 0 };
        int[] stacks = new int[10] { 1000, 1000, 1000, 0, 0, 0, 0, 0, 0, 0 };
        int[] roundContribution = new int[10] { 100, 100, 0, 0, 0, 0, 0, 0, 0, 0 };

        // Seat 2 raises to 200: a full 100 raise on top of the 100 bet.
        object[] result = game.CalculateGameTransition(
            lastTransitionMillis: 0, bettingRound: HoldemGame.PREFLOP, actingSeat: 2,
            currentBet: 100, minimumRaise: 100, headsUp: false,
            currentPlayerState: playerState, stacks: stacks,
            roundContribution: roundContribution, potContribution: new int[10],
            nowMillis: 1000, actTimeoutSecs: 16, headsUpTimeoutSecs: 3, bigBlind: 100,
            dealerSeat: 0, actingPlayerSeated: true,
            actingPlayerBet: 200, actingPlayerCommitted: true, aggressorSeat: 0, callOnlyMask: 0);

        Assert.IsNotNull(result);
        int[] newStates = (int[])result[R_STATE];
        // Both committed seats are reopened; seat 0 is immediately promoted to acting.
        Assert.AreEqual(HoldemGame.PLAYER_ACTING, newStates[0], "A full raise reopens action to seat 0");
        Assert.AreEqual(HoldemGame.PLAYER_PENDING, newStates[1], "A full raise reopens action to seat 1");
        Assert.AreEqual(HoldemGame.PLAYER_COMMITED, newStates[2]);
        Assert.AreEqual(200, (int)result[R_BET], "currentBet moves to the raise");
        Assert.AreEqual(100, (int)result[R_MINRAISE], "minimumRaise is the size of the raise just made");
        Assert.AreEqual(2, (int)result[R_AGGRESSOR]);
        Assert.AreEqual(0, (int)result[R_ACTOR], "Action passes to the first reopened seat");
        Assert.AreEqual(800, ((int[])result[R_STACKS])[2]);
    }

    [Test]
    public void TestGameTransition_RaiseDoesNotReopenActionToAnAllInSeat()
    {
        // Seat 0 is already all-in, so a raise cannot put it back in the decision.
        int[] playerState = new int[10] { HoldemGame.PLAYER_COMMITED, HoldemGame.PLAYER_COMMITED, HoldemGame.PLAYER_ACTING, 0, 0, 0, 0, 0, 0, 0 };
        int[] stacks = new int[10] { 0, 1000, 1000, 0, 0, 0, 0, 0, 0, 0 };
        int[] roundContribution = new int[10] { 100, 100, 0, 0, 0, 0, 0, 0, 0, 0 };

        object[] result = game.CalculateGameTransition(
            lastTransitionMillis: 0, bettingRound: HoldemGame.PREFLOP, actingSeat: 2,
            currentBet: 100, minimumRaise: 100, headsUp: false,
            currentPlayerState: playerState, stacks: stacks,
            roundContribution: roundContribution, potContribution: new int[10],
            nowMillis: 1000, actTimeoutSecs: 16, headsUpTimeoutSecs: 3, bigBlind: 100,
            dealerSeat: 0, actingPlayerSeated: true,
            actingPlayerBet: 200, actingPlayerCommitted: true, aggressorSeat: 0, callOnlyMask: 0);

        Assert.IsNotNull(result);
        int[] newStates = (int[])result[R_STATE];
        Assert.AreEqual(HoldemGame.PLAYER_COMMITED, newStates[0], "An all-in seat has no action left to reopen");
        Assert.AreEqual(HoldemGame.PLAYER_ACTING, newStates[1], "Seat 1 is reopened and takes the action");
        Assert.AreEqual(1, (int)result[R_ACTOR], "Action skips the all-in seat");
    }

    [Test]
    public void TestGameTransition_HeadsUpRunoutWaitsThenAdvancesOneStreet()
    {
        int[] playerState = new int[10] { HoldemGame.PLAYER_COMMITED, HoldemGame.PLAYER_COMMITED, 0, 0, 0, 0, 0, 0, 0, 0 };
        int[] stacks = new int[10];

        object[] tooSoon = game.CalculateGameTransition(
            lastTransitionMillis: 0, bettingRound: HoldemGame.PREFLOP, actingSeat: 0,
            currentBet: 0, minimumRaise: 0, headsUp: true,
            currentPlayerState: playerState, stacks: stacks,
            roundContribution: new int[10], potContribution: new int[10],
            nowMillis: 1000, actTimeoutSecs: 16, headsUpTimeoutSecs: 3, bigBlind: 100,
            dealerSeat: 0, actingPlayerSeated: true,
            actingPlayerBet: 0, actingPlayerCommitted: false, aggressorSeat: 0, callOnlyMask: 0);

        Assert.IsNull(tooSoon, "Each run-out street is held on screen for the heads-up timeout");

        object[] result = game.CalculateGameTransition(
            lastTransitionMillis: 0, bettingRound: HoldemGame.PREFLOP, actingSeat: 0,
            currentBet: 0, minimumRaise: 0, headsUp: true,
            currentPlayerState: playerState, stacks: stacks,
            roundContribution: new int[10], potContribution: new int[10],
            nowMillis: 5000, actTimeoutSecs: 16, headsUpTimeoutSecs: 3, bigBlind: 100,
            dealerSeat: 0, actingPlayerSeated: true,
            actingPlayerBet: 0, actingPlayerCommitted: false, aggressorSeat: 0, callOnlyMask: 0);

        Assert.IsNotNull(result);
        Assert.AreEqual(HoldemGame.FLOP, (int)result[R_ROUND], "One street per timeout");
        Assert.IsTrue((bool)result[R_HEADSUP], "The table stays in run-out mode");
        Assert.IsFalse((bool)result[R_WONBYFOLD]);
    }

    [Test]
    public void TestGameTransition_ClosingARoundRakesChipsAndStartsLeftOfTheButton()
    {
        int[] playerState = new int[10] { HoldemGame.PLAYER_COMMITED, HoldemGame.PLAYER_COMMITED, HoldemGame.PLAYER_ACTING, 0, 0, 0, 0, 0, 0, 0 };
        int[] stacks = new int[10] { 1000, 1000, 1000, 0, 0, 0, 0, 0, 0, 0 };
        int[] roundContribution = new int[10] { 50, 50, 50, 0, 0, 0, 0, 0, 0, 0 };
        int[] potContribution = new int[10] { 100, 100, 100, 0, 0, 0, 0, 0, 0, 0 };

        // Seat 2 checks behind, closing the flop.
        object[] result = game.CalculateGameTransition(
            lastTransitionMillis: 0, bettingRound: HoldemGame.FLOP, actingSeat: 2,
            currentBet: 50, minimumRaise: 50, headsUp: false,
            currentPlayerState: playerState, stacks: stacks,
            roundContribution: roundContribution, potContribution: potContribution,
            nowMillis: 1000, actTimeoutSecs: 16, headsUpTimeoutSecs: 3, bigBlind: 100,
            dealerSeat: 0, actingPlayerSeated: true,
            actingPlayerBet: 0, actingPlayerCommitted: true, aggressorSeat: 1, callOnlyMask: 0);

        Assert.IsNotNull(result);
        Assert.AreEqual(HoldemGame.TURN, (int)result[R_ROUND]);
        Assert.AreEqual(1, (int)result[R_ACTOR], "Post-flop action opens on the seat left of the button");
        Assert.AreEqual(HoldemGame.PLAYER_ACTING, ((int[])result[R_STATE])[1]);
        Assert.AreEqual(HoldemGame.PLAYER_PENDING, ((int[])result[R_STATE])[0]);
        Assert.AreEqual(HoldemGame.PLAYER_PENDING, ((int[])result[R_STATE])[2]);

        int[] newPot = (int[])result[R_POTCONTRIB];
        int[] newRound = (int[])result[R_ROUNDCONTRIB];
        for (int i = 0; i < 3; i++)
        {
            Assert.AreEqual(150, newPot[i], $"Seat {i}'s round bet should be raked into the pot");
            Assert.AreEqual(0, newRound[i], $"Seat {i}'s round contribution should be cleared");
        }

        Assert.AreEqual(0, (int)result[R_BET], "A new street opens with no bet to call");
        Assert.AreEqual(100, (int)result[R_MINRAISE], "The minimum raise resets to the big blind");
    }

    [Test]
    public void TestGameTransition_RoundClosesIntoRunoutWhenOnlyOneSeatCanStillAct()
    {
        // Seat 0 is all-in; once seat 1 calls there is nobody left to bet into.
        int[] playerState = new int[10] { HoldemGame.PLAYER_COMMITED, HoldemGame.PLAYER_ACTING, 0, 0, 0, 0, 0, 0, 0, 0 };
        int[] stacks = new int[10] { 0, 1000, 0, 0, 0, 0, 0, 0, 0, 0 };
        int[] roundContribution = new int[10] { 100, 100, 0, 0, 0, 0, 0, 0, 0, 0 };

        object[] result = game.CalculateGameTransition(
            lastTransitionMillis: 0, bettingRound: HoldemGame.FLOP, actingSeat: 1,
            currentBet: 100, minimumRaise: 100, headsUp: false,
            currentPlayerState: playerState, stacks: stacks,
            roundContribution: roundContribution, potContribution: new int[10],
            nowMillis: 1000, actTimeoutSecs: 16, headsUpTimeoutSecs: 3, bigBlind: 100,
            dealerSeat: 0, actingPlayerSeated: true,
            actingPlayerBet: 0, actingPlayerCommitted: true, aggressorSeat: 0, callOnlyMask: 0);

        Assert.IsNotNull(result);
        Assert.IsTrue((bool)result[R_HEADSUP], "With one live seat left the rest of the board is just run out");
        Assert.AreEqual(HoldemGame.TURN, (int)result[R_ROUND]);
        int[] newStates = (int[])result[R_STATE];
        Assert.AreEqual(HoldemGame.PLAYER_COMMITED, newStates[0], "Nobody is left pending during a run-out");
        Assert.AreEqual(HoldemGame.PLAYER_COMMITED, newStates[1]);
    }

    [Test]
    public void TestGameTransition_FoldOnTheRiverWinsByFoldRatherThanShowdown()
    {
        int[] playerState = new int[10] { HoldemGame.PLAYER_ACTING, HoldemGame.PLAYER_COMMITED, 0, 0, 0, 0, 0, 0, 0, 0 };
        int[] stacks = new int[10] { 1000, 1000, 0, 0, 0, 0, 0, 0, 0, 0 };
        int[] roundContribution = new int[10] { 100, 100, 0, 0, 0, 0, 0, 0, 0, 0 };
        int[] potContribution = new int[10];

        object[] result = game.CalculateGameTransition(
            lastTransitionMillis: 0, bettingRound: HoldemGame.RIVER, actingSeat: 0,
            currentBet: 100, minimumRaise: 100, headsUp: false,
            currentPlayerState: playerState, stacks: stacks,
            roundContribution: roundContribution, potContribution: potContribution,
            nowMillis: 1000, actTimeoutSecs: 16, headsUpTimeoutSecs: 3, bigBlind: 100,
            dealerSeat: 0, actingPlayerSeated: true,
            actingPlayerBet: -1, actingPlayerCommitted: true, aggressorSeat: 1, callOnlyMask: 0);

        Assert.IsNotNull(result);
        Assert.IsTrue((bool)result[R_WONBYFOLD], "The last fold wins the pot outright, even on the river");
        Assert.AreEqual(HoldemGame.RIVER, (int)result[R_ROUND], "A fold win must not fall through to SHOWDOWN");
        Assert.AreEqual(HoldemGame.PLAYER_DEAD, ((int[])result[R_STATE])[0]);
        Assert.AreEqual(200, ((int[])result[R_POTCONTRIB])[0] + ((int[])result[R_POTCONTRIB])[1],
            "The final round's bets are still raked into the pot before it is awarded");
    }

    // ------------------------------------------------------------------ DividePot

    [Test]
    public void TestDividePot_EmptyPotPaysNobody()
    {
        int[] winnings = game.DividePot(new int[10], new int[10] { 0, 1, -1, -1, -1, -1, -1, -1, -1, -1 });

        for (int i = 0; i < 10; i++)
        {
            Assert.AreEqual(0, winnings[i], $"Seat {i} should be paid nothing out of an empty pot");
        }
    }

    [Test]
    public void TestDividePot_OddChipsGoClockwiseFromTheButton()
    {
        // 32 chips split three ways is 10 each with 2 left over; those two go to the first
        // two winners clockwise from the button (seats 1 and 2), not to whoever sorts first.
        int[] potContribution = new int[10] { 8, 8, 8, 8, 0, 0, 0, 0, 0, 0 };
        int[] playerRanks = new int[10] { 0, 0, 0, 1, -1, -1, -1, -1, -1, -1 };

        int[] winnings = game.DividePot(potContribution, playerRanks, dealerSeat: 0);

        Assert.AreEqual(10, winnings[0]);
        Assert.AreEqual(11, winnings[1], "First seat left of the button takes an odd chip");
        Assert.AreEqual(11, winnings[2], "Second seat left of the button takes the other odd chip");
        Assert.AreEqual(0, winnings[3], "The losing hand is paid nothing");
        Assert.AreEqual(32, winnings[0] + winnings[1] + winnings[2] + winnings[3],
            "Every chip in the pot must be paid out");
    }

    [Test]
    public void TestDividePot_LoneLiveHandCollectsEveryLayer()
    {
        // Seats 1 and 2 folded after putting in different amounts. Nothing may be stranded
        // in a layer just because only one player is eligible for it.
        int[] potContribution = new int[10] { 100, 50, 25, 0, 0, 0, 0, 0, 0, 0 };
        int[] playerRanks = new int[10] { 0, -1, -1, -1, -1, -1, -1, -1, -1, -1 };

        int[] winnings = game.DividePot(potContribution, playerRanks);

        Assert.AreEqual(175, winnings[0], "The only live hand takes the whole 175-chip pot");
        Assert.AreEqual(0, winnings[1]);
        Assert.AreEqual(0, winnings[2]);
    }

    [Test]
    public void TestDividePot_AllInWinnerCannotTouchTheSidePot()
    {
        // Seat 0 has the best hand but only covered 100; seat 2 beats seat 1 for the rest.
        int[] potContribution = new int[10] { 100, 400, 400, 0, 0, 0, 0, 0, 0, 0 };
        int[] playerRanks = new int[10] { 0, 2, 1, -1, -1, -1, -1, -1, -1, -1 };

        int[] winnings = game.DividePot(potContribution, playerRanks);

        Assert.AreEqual(300, winnings[0], "Main pot is capped at the short stack's 100 from each of three players");
        Assert.AreEqual(0, winnings[1], "Worst hand at showdown wins nothing");
        Assert.AreEqual(600, winnings[2], "Side pot of (400-100) * 2 goes to the best hand that covered it");
        Assert.AreEqual(900, winnings[0] + winnings[1] + winnings[2]);
    }
// ------------------------------------------------------------------ Fold-win pot integrity
    // When a player bets big and everyone folds, the winner must only net
    // the blinds (their own bet is returned as part of the pot award).

    [Test]
    public void TestFoldWin_PotAwardedDoesNotInflateWinnerNet()
    {
        // Three players at seats 0 (dealer), 1 (SB), 2 (BB). Player 0 bets
        // a huge amount; both opponents fold. Player 0 must only gain the
        // blinds (SB+BB = 150 chips), not their own 9000 back as "profit."
        int initialStack = 10000;
        int[] playerState = new int[10] { HoldemGame.PLAYER_ACTING, HoldemGame.PLAYER_PENDING, HoldemGame.PLAYER_PENDING, 0, 0, 0, 0, 0, 0, 0 };
        int[] stacks = new int[10] { initialStack, initialStack - 50, initialStack - 100, 0, 0, 0, 0, 0, 0, 0 };
        int[] roundContribution = new int[10] { 0, 50, 100, 0, 0, 0, 0, 0, 0, 0 };
        int[] potContribution = new int[10];

        // Step 1: Seat 0 makes a huge bet of 9000 (9000 > currentBet of 100)
        object[] r1 = game.CalculateGameTransition(
            lastTransitionMillis: 0, bettingRound: HoldemGame.PREFLOP, actingSeat: 0,
            currentBet: 100, minimumRaise: 100, headsUp: false,
            currentPlayerState: playerState, stacks: stacks,
            roundContribution: roundContribution, potContribution: potContribution,
            nowMillis: 1000, actTimeoutSecs: 16, headsUpTimeoutSecs: 3, bigBlind: 100,
            dealerSeat: 0, actingPlayerSeated: true,
            actingPlayerBet: 9000, actingPlayerCommitted: true, aggressorSeat: 2, callOnlyMask: 0);

        Assert.IsNotNull(r1);
        // After the raise, action moves to seat 1 (SB)
        Assert.AreEqual(1, (int)r1[R_ACTOR]);
        int[] s1 = (int[])r1[R_STACKS];
        int[] rc1 = (int[])r1[R_ROUNDCONTRIB];
        Assert.AreEqual(1000, s1[0], "Seat 0 bet 9000 out of 10000");
        Assert.AreEqual(9000, rc1[0], "Round contribution reflects the raised bet");
        Assert.AreEqual(initialStack - 50, s1[1], "Seat 1 stack has SB already deducted");

        // Step 2: Seat 1 folds
        int[] ps2 = (int[])r1[R_STATE];
        int[] pc1 = (int[])r1[R_POTCONTRIB];
        object[] r2 = game.CalculateGameTransition(
            lastTransitionMillis: 0, bettingRound: (int)r1[R_ROUND], actingSeat: 1,
            currentBet: (int)r1[R_BET], minimumRaise: (int)r1[R_MINRAISE], headsUp: false,
            currentPlayerState: ps2, stacks: s1,
            roundContribution: rc1, potContribution: pc1,
            nowMillis: 2000, actTimeoutSecs: 16, headsUpTimeoutSecs: 3, bigBlind: 100,
            dealerSeat: 0, actingPlayerSeated: true,
            actingPlayerBet: -1, actingPlayerCommitted: true, aggressorSeat: 0, callOnlyMask: 0);

        Assert.IsNotNull(r2);
        Assert.AreEqual(2, (int)r2[R_ACTOR], "Action moves to seat 2 after seat 1 folds");

        // Step 3: Seat 2 folds -> round closes, wonByFold
        int[] ps3 = (int[])r2[R_STATE];
        int[] s3 = (int[])r2[R_STACKS];
        int[] rc3 = (int[])r2[R_ROUNDCONTRIB];
        int[] pc2 = (int[])r2[R_POTCONTRIB];
        object[] r3 = game.CalculateGameTransition(
            lastTransitionMillis: 0, bettingRound: (int)r2[R_ROUND], actingSeat: 2,
            currentBet: (int)r2[R_BET], minimumRaise: (int)r2[R_MINRAISE], headsUp: false,
            currentPlayerState: ps3, stacks: s3,
            roundContribution: rc3, potContribution: pc2,
            nowMillis: 3000, actTimeoutSecs: 16, headsUpTimeoutSecs: 3, bigBlind: 100,
            dealerSeat: 0, actingPlayerSeated: true,
            actingPlayerBet: -1, actingPlayerCommitted: true, aggressorSeat: 0, callOnlyMask: 0);

        Assert.IsNotNull(r3);
        Assert.IsTrue((bool)r3[R_WONBYFOLD], "Round closes with one player alive; won-by-fold");

        // potContribution after rake: seat0=9000, seat1=50, seat2=100
        int[] pcFinal = (int[])r3[R_POTCONTRIB];
        Assert.AreEqual(9000, pcFinal[0]);
        Assert.AreEqual(50, pcFinal[1]);
        Assert.AreEqual(100, pcFinal[2]);

        // Simulate the pot-award step (same as CalculateTransition lines 1002-1017).
        int[] finalStacks = (int[])r3[R_STACKS];
        int[] finalStates = (int[])r3[R_STATE];
        int winner = -1;
        int winnings = 0;
        for (int i = 0; i < 10; i++)
        {
            if (winner < 0 && finalStates[i] != HoldemGame.PLAYER_DEAD) winner = i;
            winnings += pcFinal[i];
        }
        Assert.AreEqual(0, winner, "Seat 0 is the only surviving player");
        finalStacks[winner] += winnings;

        // Winner's final stack: initial 10000 - 9000 bet + (9000+50+100) pot = 10150
        Assert.AreEqual(initialStack + 150, finalStacks[winner],
            "Winner only nets the blinds (150); their own 9000 bet is refunded via the pot");
    }

    [Test]
    public void TestFoldWin_TwoPlayersBigBetOnlyWinsBigBlind()
    {
        // Heads-up: seat 0 is dealer/SB, seat 1 is BB. Seat 0 bets big,
        // seat 1 folds. Winner should only gain BB=100.
        int initialStack = 10000;
        int[] playerState = new int[10] { HoldemGame.PLAYER_ACTING, HoldemGame.PLAYER_PENDING, 0, 0, 0, 0, 0, 0, 0, 0 };
        int[] stacks = new int[10] { initialStack - 50, initialStack - 100, 0, 0, 0, 0, 0, 0, 0, 0 };
        int[] roundContribution = new int[10] { 50, 100, 0, 0, 0, 0, 0, 0, 0, 0 };
        int[] potContribution = new int[10];

        // Step 1: Seat 0 (SB/dealer) bets 7000
        object[] r1 = game.CalculateGameTransition(
            lastTransitionMillis: 0, bettingRound: HoldemGame.PREFLOP, actingSeat: 0,
            currentBet: 100, minimumRaise: 100, headsUp: false,
            currentPlayerState: playerState, stacks: stacks,
            roundContribution: roundContribution, potContribution: potContribution,
            nowMillis: 1000, actTimeoutSecs: 16, headsUpTimeoutSecs: 3, bigBlind: 100,
            dealerSeat: 0, actingPlayerSeated: true,
            actingPlayerBet: 7000, actingPlayerCommitted: true, aggressorSeat: 1, callOnlyMask: 0);

        Assert.IsNotNull(r1);
        int[] s1 = (int[])r1[R_STACKS];
        Assert.AreEqual(2950, s1[0], "Seat 0 bet 7000 out of 9950 (had 50 SB already deducted)");

        // Step 2: Seat 1 folds
        int[] ps2 = (int[])r1[R_STATE];
        int[] rc1 = (int[])r1[R_ROUNDCONTRIB];
        int[] pc1 = (int[])r1[R_POTCONTRIB];
        object[] r2 = game.CalculateGameTransition(
            lastTransitionMillis: 0, bettingRound: (int)r1[R_ROUND], actingSeat: 1,
            currentBet: (int)r1[R_BET], minimumRaise: (int)r1[R_MINRAISE], headsUp: false,
            currentPlayerState: ps2, stacks: s1,
            roundContribution: rc1, potContribution: pc1,
            nowMillis: 2000, actTimeoutSecs: 16, headsUpTimeoutSecs: 3, bigBlind: 100,
            dealerSeat: 0, actingPlayerSeated: true,
            actingPlayerBet: -1, actingPlayerCommitted: true, aggressorSeat: 0, callOnlyMask: 0);

        Assert.IsNotNull(r2);
        Assert.IsTrue((bool)r2[R_WONBYFOLD], "Only seat 0 survives; won-by-fold");

        int[] pcFinal = (int[])r2[R_POTCONTRIB];
        int[] finalStacks2 = (int[])r2[R_STACKS];
        int[] finalStates = (int[])r2[R_STATE];

        // Simulate pot award
        int winner2 = -1;
        int winnings2 = 0;
        for (int i = 0; i < 10; i++)
        {
            if (winner2 < 0 && finalStates[i] != HoldemGame.PLAYER_DEAD) winner2 = i;
            winnings2 += pcFinal[i];
        }
        Assert.AreEqual(0, winner2, "Seat 0 is the only survivor in heads-up");
        finalStacks2[winner2] += winnings2;

        // Net gain should be the big blind (100), since seat 0's own SB+bet
        // are returned as part of the pot.
        Assert.AreEqual(initialStack + 100, finalStacks2[winner2],
            "Heads-up fold-win: winner nets only BB (100), big bet refunded via pot");
    }

    [Test]
    public void TestFoldWin_MultiStreetBetCallFoldStacksAreCorrect()
    {
        // Scenario: P0 bets, P1 calls, P2 folds preflop. P0 bets on flop, P1 folds.
        // P0 only nets opponent contributions (P1: 200 + P2: 100 = 300).
        int initialStack = 10000;
        int[] playerState = new int[10] { HoldemGame.PLAYER_ACTING, HoldemGame.PLAYER_PENDING, HoldemGame.PLAYER_PENDING, 0, 0, 0, 0, 0, 0, 0 };
        int[] stacks = new int[10] { initialStack, initialStack - 50, initialStack - 100, 0, 0, 0, 0, 0, 0, 0 };
        int[] roundContribution = new int[10] { 0, 50, 100, 0, 0, 0, 0, 0, 0, 0 };
        int[] potContribution = new int[10];

        // Preflop: Seat 0 raises to 200
        object[] r1 = game.CalculateGameTransition(
            lastTransitionMillis: 0, bettingRound: HoldemGame.PREFLOP, actingSeat: 0,
            currentBet: 100, minimumRaise: 100, headsUp: false,
            currentPlayerState: playerState, stacks: stacks,
            roundContribution: roundContribution, potContribution: potContribution,
            nowMillis: 1000, actTimeoutSecs: 16, headsUpTimeoutSecs: 3, bigBlind: 100,
            dealerSeat: 0, actingPlayerSeated: true,
            actingPlayerBet: 200, actingPlayerCommitted: true, aggressorSeat: 2, callOnlyMask: 0);
        Assert.IsNotNull(r1);
        Assert.AreEqual(1, (int)r1[R_ACTOR]);

        // Preflop: Seat 1 calls
        int[] ps1 = (int[])r1[R_STATE];
        int[] s1 = (int[])r1[R_STACKS];
        int[] rc1 = (int[])r1[R_ROUNDCONTRIB];
        int[] pc1 = (int[])r1[R_POTCONTRIB];
        object[] r2 = game.CalculateGameTransition(
            lastTransitionMillis: 0, bettingRound: (int)r1[R_ROUND], actingSeat: 1,
            currentBet: (int)r1[R_BET], minimumRaise: (int)r1[R_MINRAISE], headsUp: false,
            currentPlayerState: ps1, stacks: s1,
            roundContribution: rc1, potContribution: pc1,
            nowMillis: 2000, actTimeoutSecs: 16, headsUpTimeoutSecs: 3, bigBlind: 100,
            dealerSeat: 0, actingPlayerSeated: true,
            actingPlayerBet: 150, actingPlayerCommitted: true, aggressorSeat: 0, callOnlyMask: 0);
        Assert.IsNotNull(r2);
        Assert.AreEqual(2, (int)r2[R_ACTOR]);

        // Preflop: Seat 2 folds
        int[] ps2 = (int[])r2[R_STATE];
        int[] s2 = (int[])r2[R_STACKS];
        int[] rc2 = (int[])r2[R_ROUNDCONTRIB];
        int[] pc2 = (int[])r2[R_POTCONTRIB];
        object[] r3 = game.CalculateGameTransition(
            lastTransitionMillis: 0, bettingRound: (int)r2[R_ROUND], actingSeat: 2,
            currentBet: (int)r2[R_BET], minimumRaise: (int)r2[R_MINRAISE], headsUp: false,
            currentPlayerState: ps2, stacks: s2,
            roundContribution: rc2, potContribution: pc2,
            nowMillis: 3000, actTimeoutSecs: 16, headsUpTimeoutSecs: 3, bigBlind: 100,
            dealerSeat: 0, actingPlayerSeated: true,
            actingPlayerBet: -1, actingPlayerCommitted: true, aggressorSeat: 0, callOnlyMask: 0);
        Assert.IsNotNull(r3);
        Assert.AreEqual(HoldemGame.FLOP, (int)r3[R_ROUND], "Preflop closed with 2 alive → FLOP");

        // FLOP: Seat 1 (SB, left of dealer) acts first, bets 500
        int[] ps3 = (int[])r3[R_STATE];
        int[] s3 = (int[])r3[R_STACKS];
        int[] rc3 = (int[])r3[R_ROUNDCONTRIB];
        int[] pc3 = (int[])r3[R_POTCONTRIB];
        object[] r4 = game.CalculateGameTransition(
            lastTransitionMillis: 0, bettingRound: (int)r3[R_ROUND], actingSeat: (int)r3[R_ACTOR],
            currentBet: (int)r3[R_BET], minimumRaise: (int)r3[R_MINRAISE], headsUp: false,
            currentPlayerState: ps3, stacks: s3,
            roundContribution: rc3, potContribution: pc3,
            nowMillis: 4000, actTimeoutSecs: 16, headsUpTimeoutSecs: 3, bigBlind: 100,
            dealerSeat: 0, actingPlayerSeated: true,
            actingPlayerBet: 500, actingPlayerCommitted: true, aggressorSeat: 0, callOnlyMask: 0);
        Assert.IsNotNull(r4);

        // FLOP: Seat 0 folds → seat 1 wins by fold
        int[] ps4 = (int[])r4[R_STATE];
        int[] s4 = (int[])r4[R_STACKS];
        int[] rc4 = (int[])r4[R_ROUNDCONTRIB];
        int[] pc4 = (int[])r4[R_POTCONTRIB];
        object[] r5 = game.CalculateGameTransition(
            lastTransitionMillis: 0, bettingRound: (int)r4[R_ROUND], actingSeat: (int)r4[R_ACTOR],
            currentBet: (int)r4[R_BET], minimumRaise: (int)r4[R_MINRAISE], headsUp: false,
            currentPlayerState: ps4, stacks: s4,
            roundContribution: rc4, potContribution: pc4,
            nowMillis: 5000, actTimeoutSecs: 16, headsUpTimeoutSecs: 3, bigBlind: 100,
            dealerSeat: 0, actingPlayerSeated: true,
            actingPlayerBet: -1, actingPlayerCommitted: true, aggressorSeat: 1, callOnlyMask: 0);
        Assert.IsNotNull(r5);
        Assert.IsTrue((bool)r5[R_WONBYFOLD], "Seat 0 folded on flop; seat 1 wins by fold");

        // Simulate pot award
        int[] pcFinal = (int[])r5[R_POTCONTRIB];
        int[] finalStacks = (int[])r5[R_STACKS];
        int[] finalStates = (int[])r5[R_STATE];
        int winner = -1;
        int winningsTotal = 0;
        for (int i = 0; i < 10; i++)
        {
            if (winner < 0 && finalStates[i] != HoldemGame.PLAYER_DEAD) winner = i;
            winningsTotal += pcFinal[i];
        }
        Assert.AreEqual(1, winner, "Seat 1 is the only survivor");
        finalStacks[winner] += winningsTotal;

        // Seat 1 put in: SB 50 + call 150 + flop bet 500 = 700.
        // Pot: seat 0 preflop 200 + seat 1 preflop 200 + seat 2 BB 100 + seat 1 flop 500 = 1000.
        // Seat 1 started: 10000 - 700 = 9300 + 1000 = 10300. Net = seat 0's 200 + seat 2's 100 = 300.
        Assert.AreEqual(initialStack + 300, finalStacks[winner],
            "Winner only nets opponent contributions (300), own bets refunded via pot");
    }
}
