using System;
using System.Collections.Generic;
using NUnit.Framework;
using UnityEngine;
using VRC.SDKBase;

public class TournamentTests
{
    private GameObject gameGo;
    private HoldemGame game;

    // A minimal stand-in for VRChat's player API. Nothing in the editor can turn a player id
    // back into a balance component on its own, and that lookup is the whole mechanism
    // tournament payouts run on, so the tests supply it.
    private readonly Dictionary<GameObject, VRCPlayerApi> seatOwners = new Dictionary<GameObject, VRCPlayerApi>();
    private readonly Dictionary<int, VRCPlayerApi> playersById = new Dictionary<int, VRCPlayerApi>();
    private readonly Dictionary<VRCPlayerApi, GameObject> playerObjects = new Dictionary<VRCPlayerApi, GameObject>();
    private bool playerApiHooked;
    private Func<GameObject, VRCPlayerApi> previousGetOwner;
    private Func<int, VRCPlayerApi> previousGetPlayerById;
    private Func<VRCPlayerApi, GameObject[]> previousGetPlayerObjects;

    [SetUp]
    public void SetUp()
    {
        gameGo = new GameObject("HoldemGameTest");
        game = gameGo.AddComponent<HoldemGame>();
        game.seats = 10;
        
        // Mock players array
        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()
    {
        UnhookPlayerApi();
        UnityEngine.Object.DestroyImmediate(gameGo);
    }

    // Routes Networking.GetOwner, VRCPlayerApi.GetPlayerById and the player-object lookup at
    // the fake players registered by SeatAndBuyIn. Networking.IsOwner runs separate
    private void HookPlayerApi()
    {
        if (playerApiHooked) return;
        playerApiHooked = true;

        previousGetOwner = Networking._GetOwner;
        previousGetPlayerById = VRCPlayerApi._GetPlayerById;
        previousGetPlayerObjects = Networking._GetPlayerPersistence;

        Networking._GetOwner = go =>
        {
            VRCPlayerApi owner;
            return seatOwners.TryGetValue(go, out owner) ? owner : null;
        };
        VRCPlayerApi._GetPlayerById = id =>
        {
            VRCPlayerApi player;
            return playersById.TryGetValue(id, out player) ? player : null;
        };
        Networking._GetPlayerPersistence = player =>
        {
            GameObject playerObject;
            if (player != null && playerObjects.TryGetValue(player, out playerObject) && playerObject)
            {
                return new GameObject[] { playerObject };
            }
            return new GameObject[0];
        };
    }

    private void UnhookPlayerApi()
    {
        if (!playerApiHooked) return;
        playerApiHooked = false;

        Networking._GetOwner = previousGetOwner;
        VRCPlayerApi._GetPlayerById = previousGetPlayerById;
        Networking._GetPlayerPersistence = previousGetPlayerObjects;

        seatOwners.Clear();
        playersById.Clear();
        playerObjects.Clear();
    }

    // Ids stay away from -1 / -2 which seat code uses.
    private const int FirstFakePlayerId = 101;

    private VRCPlayerApi MakeFakePlayer(int playerId, string displayName)
    {
        var flags = System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance;
        var player = new VRCPlayerApi();
        typeof(VRCPlayerApi).GetField("mPlayerId", flags).SetValue(player, playerId);
        typeof(VRCPlayerApi).GetField("_isValid", flags).SetValue(player, true);
        player.displayName = displayName;
        return player;
    }

    [Test]
    public void TestLobbyRemainsIdleBeforeStart()
    {
        game.isTournamentMode = true;
        game.isTournamentActive = false;

        // Mock 4 seated and ready players with standard stack sizes
        bool[] playerIsSeated = new bool[10];
        bool[] playerIsReady = new bool[10];
        int[] stacks = new int[10];
        for (int i = 0; i < 4; i++)
        {
            playerIsSeated[i] = true;
            playerIsReady[i] = true;
            stacks[i] = 10000;
        }

        // Run transition
        int resultState = game.CalculateTableTransition(
            HoldemGame.TABLE_IDLE, 0, 0, 0, false, 100, 10, 5,
            playerIsSeated, playerIsReady, stacks
        );

        // Should remain IDLE because tournament is not active yet (waiting for Master to start)
        Assert.AreEqual(HoldemGame.TABLE_IDLE, resultState);
    }

    [Test]
    public void TestTableTransitionCountsNonEliminatedPlayers()
    {
        game.isTournamentMode = true;
        game.isTournamentActive = true;
        game.tournamentEliminated = new bool[10];

        // Mock players: 3 players active, 1 eliminated, 6 empty
        bool[] playerIsSeated = new bool[10];
        bool[] playerIsReady = new bool[10];
        int[] stacks = new int[10];

        for (int i = 0; i < 4; i++)
        {
            playerIsSeated[i] = true;
            playerIsReady[i] = true;
            stacks[i] = i == 0 ? 0 : 5000; // Seat 0 has 0 stack (eliminated)
            game.tournamentEliminated[i] = (i == 0);
        }
        for (int i = 4; i < 10; i++)
        {
            game.tournamentEliminated[i] = true;
        }

        // Check transition from IDLE with 3 active players remaining (which is > 1)
        int resultState = game.CalculateTableTransition(
            HoldemGame.TABLE_IDLE, 0, 0, HoldemGame.NOT_PLAYING, false, 100, 10, 5,
            playerIsSeated, playerIsReady, stacks
        );

        // Should transition to TABLE_READY because there are at least 2 active players
        Assert.AreEqual(HoldemGame.TABLE_READY, resultState);
    }

    [Test]
    public void TestDealInExcludesEliminatedPlayers()
    {
        game.isTournamentActive = true;
        game.tournamentEliminated = new bool[10];
        
        // Setup player states
        bool[] playerIsSeated = new bool[10];
        bool[] playerIsReady = new bool[10];
        int[] stacks = new int[10];
        int[] roundContribution = new int[10];
        int[] potContribution = new int[10];
        int[] holeCards0 = new int[10];
        int[] holeCards1 = new int[10];
        int[] playerState = new int[10];

        // Seat 0: seated, but eliminated with 0 stack
        playerIsSeated[0] = true;
        playerIsReady[0] = true;
        stacks[0] = 0;
        game.tournamentEliminated[0] = true;

        // Seat 1: seated, active, 5000 stack
        playerIsSeated[1] = true;
        playerIsReady[1] = true;
        stacks[1] = 5000;

        // Seat 2: seated, active, 3000 stack
        playerIsSeated[2] = true;
        playerIsReady[2] = true;
        stacks[2] = 3000;

        // Run CalculateTransition from TABLE_READY to TABLE_PLAYING
        object[] result = game.CalculateTransition(
            HoldemGame.TABLE_READY, 0, HoldemGame.NOT_PLAYING, 0, 0,
            0, 0, false, false,
            playerState, stacks, roundContribution, potContribution,
            0, 0, 0, 0, 0, holeCards0, holeCards1,
            -1, 0,
            10000, 100, // nowMillis = 10000 (10s), which is > readyTimeoutSecs (5s)
            10, 5, 15, 3,
            playerIsSeated, playerIsReady, false,
            0, false,
            new int[52] // mock deck
        );

        Assert.IsNotNull(result);
        int[] newPlayerStates = (int[])result[9];

        // Seat 0 should be PLAYER_DEAD since they are eliminated
        Assert.AreEqual(HoldemGame.PLAYER_DEAD, newPlayerStates[0]);

        // Seat 1 and 2 should be PLAYER_PENDING (dealt in) or PLAYER_ACTING
        Assert.IsTrue(newPlayerStates[1] != HoldemGame.PLAYER_DEAD);
        Assert.IsTrue(newPlayerStates[2] != HoldemGame.PLAYER_DEAD);
    }

    [Test]
    public void TestStartingStackNotOverwrittenByPersistentBalance()
    {
        // Setup tournament settings
        game.isTournamentMode = true;
        game.isTournamentActive = true; // Tournament is active
        game.tournamentStartingStack = 10000;
        game.tournamentBuyIn = 1000;
        game.maxBuyIn = 2000;

        // Mock 2 players
        var activePlayerIdField = typeof(HoldemPlayer).GetField("activePlayerId", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
        var balanceField = typeof(HoldemPlayer).GetField("ActivePlayerBalanceComponent", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
        var isReadyField = typeof(PlayerBalanceComponent).GetField("bIsReady", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);

        var lastBankBalancesField = typeof(HoldemGame).GetField("lastBankBalances", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
        var wasSeatedArr = game.wasSeated; // public field; a NonPublic-only reflection lookup returns null
        var lastBankBalancesArr = (int[])lastBankBalancesField.GetValue(game);

        for (int i = 0; i < 2; i++)
        {
            var player = game.players[i];
            activePlayerIdField.SetValue(player, -2); // Mock player being seated (activePlayerId == OwnerId() which is -2 in test)

            // Mock PlayerBalanceComponent
            var balanceGo = new GameObject("Balance_" + i);
            var balanceComponent = balanceGo.AddComponent<PlayerBalanceComponent>();
            balanceComponent.CurrentSyncedBalance = 5000; // Player has 5000 in persistent balance
            isReadyField.SetValue(balanceComponent, true);

            balanceField.SetValue(player, balanceComponent);

            wasSeatedArr[i] = true;
            lastBankBalancesArr[i] = 6000; // Mock last recorded balance
            game.stacks[i] = 10000; // Initialize stack to tournament starting stack
        }

        // Run Transition
        game.Transition();

        // Stacks should remain at 10000 (starting stack) and not be overwritten/modified by 5000 (persistent balance) or 2000 (maxBuyIn)
        Assert.AreEqual(10000, game.stacks[0]);
        Assert.AreEqual(10000, game.stacks[1]);
    }

    [Test]
    public void TestAllInDoesNotEliminatePlayerMidHand()
    {
        // 1. Setup active tournament
        game.isTournamentActive = true;
        game.tournamentEliminated = new bool[10];

        // Player 0 and Player 1 are active
        game.tournamentEliminated[0] = false;
        game.tournamentEliminated[1] = false;
        for (int i = 2; i < 10; i++)
        {
            game.tournamentEliminated[i] = true;
        }

        // Mock Player 0 going all in (stack becomes 0) during playing state
        game.tableState = HoldemGame.TABLE_PLAYING;
        game.stacks[0] = 0;
        game.stacks[1] = 5000;

        // Mock players array to prevent NullReferenceException during Transition
        var activePlayerIdField = typeof(HoldemPlayer).GetField("activePlayerId", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
        for (int i = 0; i < 10; i++)
        {
            activePlayerIdField.SetValue(game.players[i], -1); // Unseated/inactive players
        }
        // Active tournament players are seated
        activePlayerIdField.SetValue(game.players[0], -2);
        activePlayerIdField.SetValue(game.players[1], -2);

        // Run Transition while in TABLE_PLAYING state
        game.Transition();

        // Player 0 should NOT be eliminated yet since the hand is still in progress (TABLE_PLAYING)
        Assert.IsFalse(game.tournamentEliminated[0]);

        // 2. Now transition/simulate hand finishing (TABLE_WINNER)
        game.wonByFold = true;
        
        // Run Transition to transition the game to TABLE_WINNER (assuming Player 0 didn't win chips back and stack is still 0)
        game.Transition();

        // Player 0 should now be eliminated
        Assert.IsTrue(game.tournamentEliminated[0]);
        Assert.AreEqual(2, game.playerRanks[0]); // Second place since 2 players were active
    }

    [Test]
    public void TestToggleTournamentMode()
    {
        game.isTournamentMode = false;
        game.isTournamentActive = false;
        game.tableState = HoldemGame.TABLE_IDLE;

        game.ToggleTournamentMode();

        // ToggleTournamentMode is master-only. This used to wrap every assertion below in
        // `if (game.isTournamentMode)`, so the test silently passed while checking nothing if
        // the runner wasn't master. Assert it outright instead.
        Assert.IsTrue(game.isTournamentMode, "Toggling on from TABLE_IDLE should take effect (test runner must be master)");

        // Toggling OFF is allowed from any table state; the idle restriction only guards
        // turning it on.
        game.tableState = HoldemGame.TABLE_PLAYING;
        game.ToggleTournamentMode();
        Assert.IsFalse(game.isTournamentMode, "Should be able to toggle tournament mode off even if table is not idle");

        game.tableState = HoldemGame.TABLE_PLAYING;
        game.ToggleTournamentMode();
        Assert.IsFalse(game.isTournamentMode, "Should NOT be able to toggle tournament mode on while table is active (TABLE_PLAYING)");

        game.tableState = HoldemGame.TABLE_WINNER;
        game.ToggleTournamentMode();
        Assert.IsFalse(game.isTournamentMode, "Should NOT be able to toggle tournament mode on while table is active (TABLE_WINNER)");

        game.tableState = HoldemGame.TABLE_READY;
        game.ToggleTournamentMode();
        Assert.IsFalse(game.isTournamentMode, "Should NOT be able to toggle tournament mode on while table is active (TABLE_READY)");

        game.tableState = HoldemGame.TABLE_IDLE;
        game.ToggleTournamentMode();
        Assert.IsTrue(game.isTournamentMode, "Should be able to toggle tournament mode on when table is idle (TABLE_IDLE)");

        // Cannot leave tournament mode while a tournament is under way.
        game.isTournamentActive = true;
        game.ToggleTournamentMode();
        Assert.IsTrue(game.isTournamentMode, "Should NOT be able to toggle tournament mode off while tournament is active");

        game.isTournamentActive = false;
        game.ToggleTournamentMode();
        Assert.IsFalse(game.isTournamentMode, "Should be able to toggle tournament mode off once tournament is finished");
    }

    [Test]
    public void TestAdjustBlindTimer()
    {
        // Default should be 600f (10 minutes)
        Assert.AreEqual(600f, game.tournamentLevelDurationSeconds);

        // Increase blind timer
        game.IncreaseBlindTimer();
        Assert.AreEqual(660f, game.tournamentLevelDurationSeconds, "Increase should add 60 seconds (1 minute)");

        // Decrease blind timer
        game.DecreaseBlindTimer();
        Assert.AreEqual(600f, game.tournamentLevelDurationSeconds, "Decrease should subtract 60 seconds");

        // Test bounds
        game.tournamentLevelDurationSeconds = 3540f;
        game.IncreaseBlindTimer();
        Assert.AreEqual(3600f, game.tournamentLevelDurationSeconds, "Should increase to max (3600 seconds)");
        game.IncreaseBlindTimer();
        Assert.AreEqual(3600f, game.tournamentLevelDurationSeconds, "Should clamp at max of 3600 seconds");

        game.tournamentLevelDurationSeconds = 120f;
        game.DecreaseBlindTimer();
        Assert.AreEqual(60f, game.tournamentLevelDurationSeconds, "Should decrease to min (60 seconds)");
        game.DecreaseBlindTimer();
        Assert.AreEqual(60f, game.tournamentLevelDurationSeconds, "Should clamp at min of 60 seconds");

        // Adjusting should not be allowed when tournament is active
        game.isTournamentActive = true;
        game.tournamentLevelDurationSeconds = 600f;
        game.IncreaseBlindTimer();
        Assert.AreEqual(600f, game.tournamentLevelDurationSeconds, "Should not increase when tournament is active");
        game.DecreaseBlindTimer();
        Assert.AreEqual(600f, game.tournamentLevelDurationSeconds, "Should not decrease when tournament is active");
    }

    [Test]
    public void TestTournamentProfitStats()
    {
        // 1. Setup tournament settings
        game.isTournamentMode = true;
        game.isTournamentActive = false;
        game.tournamentBuyIn = 1000;
        game.tournamentStartingStack = 10000;

        // Mock 2 players
        var activePlayerIdField = typeof(HoldemPlayer).GetField("activePlayerId", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
        var balanceField = typeof(HoldemPlayer).GetField("ActivePlayerBalanceComponent", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
        var isReadyField = typeof(PlayerBalanceComponent).GetField("bIsReady", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);

        PlayerBalanceComponent[] balanceComponents = new PlayerBalanceComponent[2];

        for (int i = 0; i < 2; i++)
        {
            var player = game.players[i];
            activePlayerIdField.SetValue(player, -2); // Mock player being seated

            var balanceGo = new GameObject("Balance_" + i);
            balanceComponents[i] = balanceGo.AddComponent<PlayerBalanceComponent>();
            balanceComponents[i].CurrentSyncedBalance = 5000;
            isReadyField.SetValue(balanceComponents[i], true);
            balanceField.SetValue(player, balanceComponents[i]);
        }

        // 2. Start the tournament
        game.StartTournament();

        // Check that the buy-in of 1000 has been deducted from their profit stats pregame
        Assert.AreEqual(-1000, balanceComponents[0].GetProfit());
        Assert.AreEqual(-1000, balanceComponents[1].GetProfit());

        // 3. Play a hand (simulate hand ending and winnings distribution via Transition)
        // Since isTournamentActive is true, during hand play net profit should not change.
        // Setup stacks
        game.stacks[0] = 3000;
        game.stacks[1] = 7000;
        game.potContribution[0] = 1000;
        game.potContribution[1] = 1000;
        
        // Let's call UpdatePlayerMetrics directly to simulate hand win
        // Setup table state to winner
        game.tableState = HoldemGame.TABLE_WINNER;
        game.wonByFold = true;
        // player 0 folded, player 1 wins pot of 2000
        game.playerState[0] = HoldemGame.PLAYER_DEAD;
        game.playerState[1] = HoldemGame.PLAYER_PENDING;

        // Run metrics update
        typeof(HoldemGame).GetMethod("UpdatePlayerMetrics", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance).Invoke(game, null);

        // Profits should STILL be -1000 (no change from the hand play)
        Assert.AreEqual(-1000, balanceComponents[0].GetProfit());
        Assert.AreEqual(-1000, balanceComponents[1].GetProfit());

        // 4. End the tournament (Player 0 has 0 stack, Player 1 wins)
        game.stacks[0] = 0;
        game.stacks[1] = 20000;
        game.tournamentEliminated[0] = true;
        game.tournamentEliminated[1] = false;
        
        // Run Transition (which triggers winner checks and rank assignments in TABLE_WINNER)
        game.Transition();

        // Since the winner timeout has not expired yet, the showdown is still active
        // and payouts have not been issued yet.
        Assert.IsTrue(game.isTournamentActive);
        Assert.AreEqual(HoldemGame.TABLE_WINNER, game.tableState);
        Assert.AreEqual(-1000, balanceComponents[0].GetProfit());
        Assert.AreEqual(-1000, balanceComponents[1].GetProfit());

        // Mock time passing to trigger transition to TABLE_IDLE (winnerTimeoutSecs defaults to 7f)
        game.lastTransitionMillis = game.GetTimeMillis() - 20000; // 20s ago

        // Run Transition again (which will transition to TABLE_IDLE and distribute payouts)
        game.Transition();

        // Now the tournament should be finished
        Assert.IsFalse(game.isTournamentActive);
        Assert.AreEqual(HoldemGame.TABLE_IDLE, game.tableState);

        // Player 1 wins first prize (total pool of 2000)
        // Player 1's final profit should be: -1000 (buy-in) + 2000 (payout) = 1000
        // Player 0's final profit should be: -1000 (buy-in)
        Assert.AreEqual(-1000, balanceComponents[0].GetProfit());
        Assert.AreEqual(1000, balanceComponents[1].GetProfit());
    }

    [Test]
    public void TestTournamentRejoining()
    {
        // 1. Setup tournament settings
        game.isTournamentMode = true;
        game.isTournamentActive = false;
        game.tournamentBuyIn = 1000;
        game.tournamentStartingStack = 10000;

        var activePlayerIdField = typeof(HoldemPlayer).GetField("activePlayerId", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
        var balanceField = typeof(HoldemPlayer).GetField("ActivePlayerBalanceComponent", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
        var isReadyField = typeof(PlayerBalanceComponent).GetField("bIsReady", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);

        PlayerBalanceComponent[] balanceComponents = new PlayerBalanceComponent[2];

        for (int i = 0; i < 2; i++)
        {
            var player = game.players[i];
            activePlayerIdField.SetValue(player, -2); // Mock player being seated

            var balanceGo = new GameObject("Balance_" + i);
            var balanceComponent = balanceGo.AddComponent<PlayerBalanceComponent>();
            balanceComponent.CurrentSyncedBalance = 5000;
            isReadyField.SetValue(balanceComponent, true);
            balanceField.SetValue(player, balanceComponent);
            balanceComponents[i] = balanceComponent;
        }

        // Start tournament (assigns tournamentPlayerNames to "(Editor)" for seats 0 and 1, since Networking.GetOwner is null in tests)
        game.StartTournament();

        Assert.IsTrue(game.isTournamentActive);
        Assert.AreEqual("(Editor)", game.tournamentPlayerNames[0]);
        Assert.AreEqual("(Editor)", game.tournamentPlayerNames[1]);
        Assert.AreEqual("", game.tournamentPlayerNames[2]);

        // Rejoining is only allowed between hands, and this test is about seat eligibility,
        // not hand timing. Pin the table so the assertions below don't depend on how far the
        // editor's clock has advanced: GetTimeMillis falls back to Time.time when there is no
        // local player, so StartTournament's Transition deals in the moment the run has been
        // going longer than readyTimeoutSecs.
        game.tableState = HoldemGame.TABLE_IDLE;

        // Now simulate players standing up (leaving table)
        for (int i = 0; i < 10; i++)
        {
            game.players[i].ReleaseControl();
            Assert.IsFalse(game.players[i].IsSeated());
        }

        // Try to take control on seat 2 (which wasn't in the tournament)
        // Set the balance component back first so TakeControl() doesn't return early in tests
        var balanceGo2 = new GameObject("Balance_2");
        var balanceComponent2 = balanceGo2.AddComponent<PlayerBalanceComponent>();
        balanceComponent2.CurrentSyncedBalance = 5000;
        isReadyField.SetValue(balanceComponent2, true);
        balanceField.SetValue(game.players[2], balanceComponent2);

        game.players[2].TakeControl();
        Assert.IsFalse(game.players[2].IsSeated(), "Should not be able to join a seat that wasn't in the tournament");

        // Try to take control on seat 0 (was in the tournament and not eliminated)
        // Set the balance component back first so TakeControl() doesn't return early in tests
        balanceField.SetValue(game.players[0], balanceComponents[0]);

        game.players[0].TakeControl();
        Assert.IsTrue(game.players[0].IsSeated(), "Should be able to rejoin own seat in active tournament");

        // Release control on seat 0 again
        game.players[0].ReleaseControl();

        // Now eliminate seat 0
        game.tournamentEliminated[0] = true;

        // Try to take control on seat 0 again
        balanceField.SetValue(game.players[0], balanceComponents[0]);
        game.players[0].TakeControl();
        Assert.IsFalse(game.players[0].IsSeated(), "Should not be able to rejoin if eliminated");
    }

    [Test]
    public void TestTournamentCancellationSeating()
    {
        // 1. Setup tournament settings
        game.isTournamentMode = true;
        game.isTournamentActive = false;
        game.tournamentBuyIn = 1000;
        game.tournamentStartingStack = 10000;

        var activePlayerIdField = typeof(HoldemPlayer).GetField("activePlayerId", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
        var balanceField = typeof(HoldemPlayer).GetField("ActivePlayerBalanceComponent", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
        var isReadyField = typeof(PlayerBalanceComponent).GetField("bIsReady", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);

        PlayerBalanceComponent[] balanceComponents = new PlayerBalanceComponent[3];

        for (int i = 0; i < 3; i++)
        {
            var player = game.players[i];
            activePlayerIdField.SetValue(player, -2); // Mock player being seated

            var balanceGo = new GameObject("Balance_" + i);
            var balanceComponent = balanceGo.AddComponent<PlayerBalanceComponent>();
            balanceComponent.CurrentSyncedBalance = 5000;
            isReadyField.SetValue(balanceComponent, true);
            balanceField.SetValue(player, balanceComponent);
            balanceComponents[i] = balanceComponent;
        }

        // Start tournament (seats 0, 1, 2 are seated and registered)
        game.StartTournament();

        Assert.IsTrue(game.isTournamentActive);

        // Now simulate players standing up
        for (int i = 0; i < 10; i++)
        {
            game.players[i].ReleaseControl();
            Assert.IsFalse(game.players[i].IsSeated());
        }

        // Cancel the tournament
        game.CancelTournament();

        Assert.IsFalse(game.isTournamentActive);

        // Since tournament is canceled, player names should be cleared and anyone can take any seat
        for (int i = 0; i < 3; i++)
        {
            Assert.AreEqual("", game.tournamentPlayerNames[i]);
            
            // Set the balance component back so TakeControl() works
            balanceField.SetValue(game.players[i], balanceComponents[i]);
            game.players[i].TakeControl();
            Assert.IsTrue(game.players[i].IsSeated(), $"Should be able to freely take seat {i} after tournament cancel");
        }
    }

    [Test]
    public void TestTournamentEarlyWinWhenPlayersLeave()
    {
        // 1. Setup tournament settings
        game.isTournamentMode = true;
        game.isTournamentActive = true;
        game.tournamentBuyIn = 1000;
        game.totalParticipants = 3;

        var activePlayerIdField = typeof(HoldemPlayer).GetField("activePlayerId", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
        var balanceField = typeof(HoldemPlayer).GetField("ActivePlayerBalanceComponent", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
        var isReadyField = typeof(PlayerBalanceComponent).GetField("bIsReady", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);

        PlayerBalanceComponent[] balanceComponents = new PlayerBalanceComponent[3];

        for (int i = 0; i < 3; i++)
        {
            var player = game.players[i];
            activePlayerIdField.SetValue(player, -2); // Mock player being seated

            var balanceGo = new GameObject("Balance_" + i);
            var balanceComponent = balanceGo.AddComponent<PlayerBalanceComponent>();
            balanceComponent.CurrentSyncedBalance = 5000;
            isReadyField.SetValue(balanceComponent, true);
            balanceField.SetValue(player, balanceComponent);
            balanceComponents[i] = balanceComponent;
        }

        // Initialize players 0, 1, 2 as active in the tournament
        game.tournamentEliminated = new bool[10];
        game.tournamentEliminated[0] = false;
        game.tournamentEliminated[1] = false;
        game.tournamentEliminated[2] = false;
        for (int i = 3; i < 10; i++)
        {
            game.tournamentEliminated[i] = true;
        }

        // Setup stacks: Seat 0 has 3000 chips, Seat 1 has 8000 chips, Seat 2 has 5000 chips
        game.stacks[0] = 3000;
        game.stacks[1] = 8000;
        game.stacks[2] = 5000;

        // Mock Player 0 and Player 1 leaving the join (are not seated)
        activePlayerIdField.SetValue(game.players[0], -1); // Unseated
        activePlayerIdField.SetValue(game.players[1], -1); // Unseated
        // Player 2 remains seated (activePlayerId is still -2, matching OwnerId of -2)

        // Run Transition to check if early win is triggered
        game.Transition();

        // Player 2 should automatically win (Rank 1)
        Assert.AreEqual(1, game.playerRanks[2]);
        Assert.IsFalse(game.tournamentEliminated[2]);

        // Unseated players should be ranked by their chip sizes:
        // Seat 1 has 8000 chips -> Rank 2
        Assert.AreEqual(2, game.playerRanks[1]);
        Assert.IsTrue(game.tournamentEliminated[1]);

        // Seat 0 has 3000 chips -> Rank 3
        Assert.AreEqual(3, game.playerRanks[0]);
        Assert.IsTrue(game.tournamentEliminated[0]);

        // The tournament should now be inactive
        Assert.IsFalse(game.isTournamentActive);

        // The table state should have returned to TABLE_IDLE
        Assert.AreEqual(HoldemGame.TABLE_IDLE, game.tableState);

        // Check payouts:
        // Total pool = 3 players * 1000 = 3000, split 70/30 with integer math.
        // Winner gets 2100 (balance becomes 5000 + 2100 = 7100).
        // 2nd place (Seat 1) gets 900 (balance becomes 5000 + 900 = 5900).
        // 3rd place (Seat 0) gets 0 profit (balance remains 5000).
        Assert.AreEqual(5000 + 2100, balanceComponents[2].GetBalance());
        Assert.AreEqual(5000 + 900, balanceComponents[1].GetBalance());
        Assert.AreEqual(5000, balanceComponents[0].GetBalance());
        Assert.AreEqual(3000,
            (balanceComponents[0].GetBalance() - 5000) + (balanceComponents[1].GetBalance() - 5000) + (balanceComponents[2].GetBalance() - 5000),
            "The whole prize pool must be paid out, with nothing lost to rounding");
    }

    [Test]
    public void TestTournamentRejoiningDuringHandBlocked()
    {
        // 1. Setup tournament settings
        game.isTournamentMode = true;
        game.isTournamentActive = true;
        game.tournamentBuyIn = 1000;
        game.tournamentStartingStack = 10000;
        game.totalParticipants = 2;

        var activePlayerIdField = typeof(HoldemPlayer).GetField("activePlayerId", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
        var balanceField = typeof(HoldemPlayer).GetField("ActivePlayerBalanceComponent", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
        var isReadyField = typeof(PlayerBalanceComponent).GetField("bIsReady", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);

        PlayerBalanceComponent[] balanceComponents = new PlayerBalanceComponent[2];

        for (int i = 0; i < 2; i++)
        {
            var player = game.players[i];
            activePlayerIdField.SetValue(player, -2); // Mock player being seated

            var balanceGo = new GameObject("Balance_" + i);
            var balanceComponent = balanceGo.AddComponent<PlayerBalanceComponent>();
            balanceComponent.CurrentSyncedBalance = 5000;
            isReadyField.SetValue(balanceComponent, true);
            balanceField.SetValue(player, balanceComponent);
            balanceComponents[i] = balanceComponent;
        }

        // Setup active tournament players
        game.tournamentEliminated = new bool[10];
        game.tournamentPlayerNames[0] = "(Editor)";
        game.tournamentPlayerNames[1] = "(Editor)";

        // Simulate player 0 standing up
        game.players[0].ReleaseControl();
        Assert.IsFalse(game.players[0].IsSeated());

        // Test rejoining when tableState is TABLE_PLAYING -> Should be blocked
        game.tableState = HoldemGame.TABLE_PLAYING;
        balanceField.SetValue(game.players[0], balanceComponents[0]);
        game.players[0].TakeControl();
        Assert.IsFalse(game.players[0].IsSeated(), "Should NOT be able to rejoin during active hand (TABLE_PLAYING)");

        // Test rejoining when tableState is TABLE_WINNER -> Should be blocked
        game.tableState = HoldemGame.TABLE_WINNER;
        balanceField.SetValue(game.players[0], balanceComponents[0]);
        game.players[0].TakeControl();
        Assert.IsFalse(game.players[0].IsSeated(), "Should NOT be able to rejoin during showdown (TABLE_WINNER)");

        // Test rejoining when tableState is TABLE_READY -> Should be allowed
        game.tableState = HoldemGame.TABLE_READY;
        balanceField.SetValue(game.players[0], balanceComponents[0]);
        game.players[0].TakeControl();
        Assert.IsTrue(game.players[0].IsSeated(), "Should be able to rejoin when between hands (TABLE_READY)");

        // Release control again
        game.players[0].ReleaseControl();

        // Test rejoining when tableState is TABLE_IDLE -> Should be allowed
        game.tableState = HoldemGame.TABLE_IDLE;
        balanceField.SetValue(game.players[0], balanceComponents[0]);
        game.players[0].TakeControl();
        Assert.IsTrue(game.players[0].IsSeated(), "Should be able to rejoin when between hands (TABLE_IDLE)");
    }

    [Test]
    public void TestMultipleTournamentEliminationsRankedByStack()
    {
        game.isTournamentActive = true;
        game.tournamentEliminated = new bool[10];
        game.tableState = HoldemGame.TABLE_PLAYING;
        game.wonByFold = true;
        game.lastTransitionMillis = game.GetTimeMillis();

        var activePlayerIdField = typeof(HoldemPlayer).GetField("activePlayerId", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
        activePlayerIdField.SetValue(game.players[0], -2);
        activePlayerIdField.SetValue(game.players[1], -2);
        activePlayerIdField.SetValue(game.players[2], -2);

        // Player 0 (stack 10000) is winner
        // Player 1 (started with 5000) and Player 2 (started with 100) both bust out this hand (stacks == 0)
        // Bustout order comes from the stacks players brought into the hand.
        game.handStartStacks[0] = 10000;
        game.handStartStacks[1] = 5000; // Seat 1 started with 5000
        game.handStartStacks[2] = 100;  // Seat 2 started with 100

        game.stacks[0] = 15100;
        game.stacks[1] = 0;
        game.stacks[2] = 0;

        for (int i = 3; i < 10; i++)
        {
            game.tournamentEliminated[i] = true;
        }

        // Run Transition to transition from TABLE_PLAYING to TABLE_WINNER
        game.Transition();

        // Seat 1 (started with 5000) should get 2nd place (Rank 2)
        // Seat 2 (started with 100) should get 3rd place (Rank 3)
        Assert.AreEqual(2, game.playerRanks[1], "Player with larger starting stack should be ranked 2nd");
        Assert.AreEqual(3, game.playerRanks[2], "Player with smaller starting stack should be ranked 3rd");
    }

    [Test]
    public void TestTournamentSinglePlayerRemainingDeclaresWinner()
    {
        game.isTournamentActive = true;
        game.tournamentEliminated = new bool[10];
        for (int i = 1; i < 10; i++)
        {
            game.tournamentEliminated[i] = true;
        }

        // Only Seat 0 is active (not eliminated)
        game.tableState = HoldemGame.TABLE_READY;
        game.lastTransitionMillis = game.GetTimeMillis();

        var activePlayerIdField = typeof(HoldemPlayer).GetField("activePlayerId", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
        activePlayerIdField.SetValue(game.players[0], -2);

        game.Transition();

        Assert.IsFalse(game.isTournamentActive, "Tournament should end when only 1 non-eliminated player remains");
        Assert.AreEqual(1, game.playerRanks[0], "Sole remaining player should be assigned Rank 1 (Winner)");
    }

    [Test]
    public void TestTournamentBlindLevelEscalation()
    {
        game.isTournamentMode = true;
        game.isTournamentActive = true;
        game.currentBlindLevelIndex = 0;
        game.tournamentLevelDurationSeconds = 300;
        game.blindLevelStartMillis = game.GetTimeMillis() - 301000; // 5 mins + 1 sec passed
        game.tableState = HoldemGame.TABLE_READY;

        game.Transition();

        Assert.AreEqual(1, game.currentBlindLevelIndex, "Blind level index should increment after timer interval");
        Assert.AreEqual(200, game.bigBlind, "Big blind should escalate to next level in schedule");
    }

    [Test]
    public void TestTournamentEndUnseatsSeatedPlayers()
    {
        game.isTournamentActive = true;
        game.tournamentEliminated = new bool[10];
        for (int i = 1; i < 10; i++)
        {
            game.tournamentEliminated[i] = true;
        }

        // Seat 0 is the sole remaining active player and is seated
        game.tableState = HoldemGame.TABLE_READY;
        game.lastTransitionMillis = game.GetTimeMillis();

        var activePlayerIdField = typeof(HoldemPlayer).GetField("activePlayerId", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
        activePlayerIdField.SetValue(game.players[0], -2);

        Assert.IsTrue(game.players[0].IsSeated(), "Player 0 should be seated before tournament ends");

        game.Transition();

        Assert.IsFalse(game.isTournamentActive, "Tournament should end when only 1 player remains");
        Assert.IsFalse(game.players[0].IsSeated(), "Seated player should be removed from table when tournament ends");
    }

    // Seats `count` players with ready balance components. Each gets a real positive player id
    // reachable through VRCPlayerApi.GetPlayerById, with its balance component hanging off that
    // player's player object, so payouts resolve the same way they do in game.
    private PlayerBalanceComponent[] SeatAndBuyIn(int count, int balance)
    {
        HookPlayerApi();

        var activePlayerIdField = typeof(HoldemPlayer).GetField("activePlayerId", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
        var balanceField = typeof(HoldemPlayer).GetField("ActivePlayerBalanceComponent", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
        var isReadyField = typeof(PlayerBalanceComponent).GetField("bIsReady", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);

        var components = new PlayerBalanceComponent[count];
        for (int i = 0; i < count; i++)
        {
            int playerId = FirstFakePlayerId + i;
            var player = MakeFakePlayer(playerId, "Player" + i);

            var balanceGo = new GameObject("Balance_" + i);
            components[i] = balanceGo.AddComponent<PlayerBalanceComponent>();
            components[i].CurrentSyncedBalance = balance;
            isReadyField.SetValue(components[i], true);

            seatOwners[game.players[i].gameObject] = player;
            playersById[playerId] = player;
            playerObjects[player] = balanceGo;

            activePlayerIdField.SetValue(game.players[i], playerId);
            balanceField.SetValue(game.players[i], components[i]);
            Assert.IsTrue(game.players[i].IsSeated(), $"Seat {i} should be occupied by fake player {playerId}");
        }
        return components;
    }

    // Mimics ReleaseControl followed by OnDeserialization on every client: the seat is vacated
    // and its cached balance reference dropped, leaving the recorded buy-in id as the only way
    // back to this player. The player stays in the instance.
    private void StandUp(int seatIdx)
    {
        typeof(HoldemPlayer).GetField("activePlayerId", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)
            .SetValue(game.players[seatIdx], -1);
        typeof(HoldemPlayer).GetField("ActivePlayerBalanceComponent", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)
            .SetValue(game.players[seatIdx], null);
    }

    // Regression: a player who stood up mid-tournament was skipped by the refund loop, and
    // their seat's balance component is gone by then, so the buy-in was simply kept.
    [Test]
    public void TestCancelRefundsParticipantWhoStoodUp()
    {
        game.isTournamentMode = true;
        game.tournamentBuyIn = 1000;
        game.tournamentStartingStack = 10000;

        var balances = SeatAndBuyIn(3, 5000);
        game.StartTournament();

        Assert.AreEqual(-1000, balances[0].GetProfit(), "Buy-in should be taken on start");
        Assert.AreEqual(-1000, balances[2].GetProfit(), "Buy-in should be taken on start");

        // Seat 2 stands up but is still in the tournament (not eliminated).
        StandUp(2);
        Assert.IsFalse(game.players[2].IsSeated());
        Assert.IsNull(game.GetSeatBalanceComponent(2), "Standing up should orphan the seat's balance component");

        game.CancelTournament();

        Assert.IsFalse(game.isTournamentActive);
        Assert.AreEqual(0, balances[0].GetProfit(), "Seated participant refunded");
        Assert.AreEqual(0, balances[1].GetProfit(), "Seated participant refunded");
        Assert.AreEqual(0, balances[2].GetProfit(), "Participant who stood up must still be refunded");
    }

    // Regression: with nobody seated the early-finish check never fired, so the tournament
    // stayed active forever and the prize pool was never paid out.
    [Test]
    public void TestTournamentResolvesWhenEveryoneStandsUp()
    {
        game.isTournamentMode = true;
        game.tournamentBuyIn = 1000;
        game.tournamentStartingStack = 10000;

        var balances = SeatAndBuyIn(3, 5000);
        game.StartTournament();

        // Chip leader is seat 1, then seat 2, then seat 0.
        game.stacks[0] = 1000;
        game.stacks[1] = 5000;
        game.stacks[2] = 2000;

        for (int i = 0; i < 3; i++) StandUp(i);

        // First pass only arms the grace period; a transient vacant seat must not end anything.
        game.Transition();
        Assert.IsTrue(game.isTournamentActive, "Tournament should survive a brief everyone-unseated blip");
        Assert.IsTrue(game.noSeatedActiveArmed, "Grace period should be armed");

        // Rewind past the abandonment timeout and let it resolve.
        game.noSeatedActiveSinceMillis = game.GetTimeMillis() - (game.abandonedTournamentTimeoutSecs + 5) * 1000;
        game.Transition();

        Assert.IsFalse(game.isTournamentActive, "Tournament should resolve rather than stall with nobody seated");
        Assert.AreEqual(HoldemGame.TABLE_IDLE, game.tableState);

        Assert.AreEqual(1, game.playerRanks[1], "Chip leader takes 1st");
        Assert.AreEqual(2, game.playerRanks[2], "Second largest stack takes 2nd");
        Assert.AreEqual(3, game.playerRanks[0], "Smallest stack takes 3rd");

        // Pool is 3 * 1000; three-way split pays 70% / 30% with no chips lost to rounding.
        Assert.AreEqual(-1000 + 2100, balances[1].GetProfit(), "1st place takes 2100 of the 3000 pool");
        Assert.AreEqual(-1000 + 900, balances[2].GetProfit(), "2nd place takes 900 of the 3000 pool");
        Assert.AreEqual(-1000, balances[0].GetProfit(), "3rd place is not paid in a 3-player tournament");
    }

    // Regression: bustout order was read from preTransitionStacks, which is refreshed every
    // tick, so it reflected the stack just before the final all-in rather than the hand start.
    [Test]
    public void TestSameHandBustoutsRankedByHandStartStack()
    {
        game.isTournamentMode = true;
        game.isTournamentActive = true;
        game.totalParticipants = 3;
        game.tournamentEliminated = new bool[10];
        game.playerRanks = new int[10];

        var activePlayerIdField = typeof(HoldemPlayer).GetField("activePlayerId", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
        for (int i = 0; i < 3; i++) activePlayerIdField.SetValue(game.players[i], -2);

        // Seats 0 and 1 are already all-in and busted; seat 2 covers both.
        game.stacks[0] = 0;
        game.stacks[1] = 0;
        game.stacks[2] = 1000;
        game.potContribution[0] = 500;
        game.potContribution[1] = 200;
        game.potContribution[2] = 500;

        // Seat 0 brought the bigger stack into the hand, so seat 1 should bust first (rank 3).
        game.handStartStacks[0] = 500;
        game.handStartStacks[1] = 200;
        // Deliberately reversed: the old code sorted on this and would flip the two ranks.
        var preTransitionStacksField = typeof(HoldemGame).GetField("preTransitionStacks", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
        preTransitionStacksField.SetValue(game, new int[10] { 200, 500, 1000, 0, 0, 0, 0, 0, 0, 0 });

        // Board 2S(39) 3H(14) 4C(28) 7D(5) 9H(20); seat 2 holds aces and wins.
        game.holeCards0[0] = 11; game.holeCards1[0] = 24; // KD KH
        game.holeCards0[1] = 10; game.holeCards1[1] = 23; // QD QH
        game.holeCards0[2] = 12; game.holeCards1[2] = 25; // AD AH
        SetBoard(39, 14, 28, 5, 20);

        game.playerState[0] = HoldemGame.PLAYER_COMMITED;
        game.playerState[1] = HoldemGame.PLAYER_COMMITED;
        game.playerState[2] = HoldemGame.PLAYER_ACTING;
        game.tableState = HoldemGame.TABLE_PLAYING;
        game.bettingRound = HoldemGame.RIVER;
        game.actingSeat = 2;
        game.currentBet = 0;
        game.minimumRaise = 0;
        game.lastTransitionMillis = game.GetTimeMillis();
        game.players[2].bet = 0;
        game.players[2].committedEpoch = game.epoch;

        game.Transition();

        Assert.AreEqual(HoldemGame.TABLE_WINNER, game.tableState, "River close should reach TABLE_WINNER");
        Assert.AreEqual(1200 + 1000, game.stacks[2], "Seat 2 should collect both pot layers");

        Assert.IsTrue(game.tournamentEliminated[0]);
        Assert.IsTrue(game.tournamentEliminated[1]);
        Assert.AreEqual(3, game.playerRanks[1], "Shorter hand-start stack busts first, taking last place");
        Assert.AreEqual(2, game.playerRanks[0], "Deeper hand-start stack outlasts, taking 2nd");
        Assert.AreEqual(1, game.playerRanks[2], "Survivor wins the tournament");
    }

    private void SetBoard(int f0, int f1, int f2, int t, int r)
    {
        var flags = System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance;
        typeof(HoldemGame).GetField("flop0", flags).SetValue(game, f0);
        typeof(HoldemGame).GetField("flop1", flags).SetValue(game, f1);
        typeof(HoldemGame).GetField("flop2", flags).SetValue(game, f2);
        typeof(HoldemGame).GetField("turn", flags).SetValue(game, t);
        typeof(HoldemGame).GetField("river", flags).SetValue(game, r);
    }

    // Two-handed the whole pool goes to the winner; there is no second prize to carve out.
    [Test]
    public void TestPrizePool_HeadsUpWinnerTakesEverything()
    {
        game.isTournamentMode = true;
        game.tournamentBuyIn = 1000;
        game.tournamentStartingStack = 10000;

        var balances = SeatAndBuyIn(2, 5000);
        game.StartTournament();
        Assert.AreEqual(2, game.totalParticipants);

        // Seat 0 walks away, leaving seat 1 as the only seated live player.
        StandUp(0);
        game.Transition();

        Assert.IsFalse(game.isTournamentActive);
        Assert.AreEqual(1, game.playerRanks[1], "The remaining player wins");
        Assert.AreEqual(2, game.playerRanks[0]);

        Assert.AreEqual(-1000 + 2000, balances[1].GetProfit(), "Winner takes the whole 2000 pool");
        Assert.AreEqual(-1000, balances[0].GetProfit(), "Runner-up gets nothing back heads-up");
    }

    // Four or more players pay three places: 70 / 30 / 10, with the rounding remainder
    // landing on first so the pool is never short.
    [Test]
    public void TestPrizePool_FourPlayersPayThreePlaces()
    {
        game.isTournamentMode = true;
        game.tournamentBuyIn = 1000;
        game.tournamentStartingStack = 10000;

        var balances = SeatAndBuyIn(4, 5000);
        game.StartTournament();
        Assert.AreEqual(4, game.totalParticipants);

        // Chip counts decide the finishing order when the tournament is abandoned.
        game.stacks[0] = 4000;
        game.stacks[1] = 3000;
        game.stacks[2] = 2000;
        game.stacks[3] = 1000;

        for (int i = 0; i < 4; i++) StandUp(i);

        game.Transition();
        game.noSeatedActiveSinceMillis = game.GetTimeMillis() - (game.abandonedTournamentTimeoutSecs + 5) * 1000;
        game.Transition();

        Assert.IsFalse(game.isTournamentActive);
        Assert.AreEqual(1, game.playerRanks[0]);
        Assert.AreEqual(2, game.playerRanks[1]);
        Assert.AreEqual(3, game.playerRanks[2]);
        Assert.AreEqual(4, game.playerRanks[3]);

        // Pool is 4 * 1000 = 4000: 1200 to second, 400 to third, the remaining 2400 to first.
        Assert.AreEqual(-1000 + 2400, balances[0].GetProfit(), "1st takes the pool less the other prizes");
        Assert.AreEqual(-1000 + 1200, balances[1].GetProfit(), "2nd takes 30%");
        Assert.AreEqual(-1000 + 400, balances[2].GetProfit(), "3rd takes 10%");
        Assert.AreEqual(-1000, balances[3].GetProfit(), "4th is out of the money");

        int paidOut = 0;
        for (int i = 0; i < 4; i++) paidOut += balances[i].GetProfit() + 1000;
        Assert.AreEqual(4000, paidOut, "The whole prize pool must be paid out, with nothing lost to rounding");
    }

    [Test]
    public void TestTournamentBlindLevelClampsAtTopOfSchedule()
    {
        game.isTournamentMode = true;
        game.isTournamentActive = true;
        game.tournamentLevelDurationSeconds = 300;
        game.tableState = HoldemGame.TABLE_READY;

        // The schedule tops out at 25600; the level index must not run off the end of it.
        game.currentBlindLevelIndex = 8;
        game.blindLevelStartMillis = game.GetTimeMillis() - 301000;

        game.Transition();

        Assert.AreEqual(8, game.currentBlindLevelIndex, "Blind level index should stop at the last scheduled level");
        Assert.AreEqual(25600, game.bigBlind, "Big blind should hold at the top of the schedule");
    }

    // Busting a player has to run the hand out through Transition: the elimination check only
    // fires on the call that actually lands the table on TABLE_WINNER.
    private void PlayOutHandWithBustedSeats(int[] handStartStacks, int[] endStacks)
    {
        game.isTournamentActive = true;
        game.isTournamentMode = true;
        game.tournamentEliminated = new bool[10];
        game.tableState = HoldemGame.TABLE_PLAYING;
        game.wonByFold = true;
        game.lastTransitionMillis = game.GetTimeMillis();

        var activePlayerIdField = typeof(HoldemPlayer).GetField("activePlayerId", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
        for (int i = 0; i < handStartStacks.Length; i++)
        {
            activePlayerIdField.SetValue(game.players[i], -2);
            game.handStartStacks[i] = handStartStacks[i];
            game.stacks[i] = endStacks[i];
        }
        for (int i = handStartStacks.Length; i < 10; i++)
        {
            game.tournamentEliminated[i] = true;
        }

        game.Transition();
    }

    [Test]
    public void TestEliminationCutsFiveMinutesOffTheBlindTimer()
    {
        game.currentBlindLevelIndex = 0;
        game.tournamentLevelDurationSeconds = 900; // long enough that the cut cannot run the level out
        int startMillis = game.GetTimeMillis();
        game.blindLevelStartMillis = startMillis;

        // Four players in, seat 3 busts.
        PlayOutHandWithBustedSeats(
            new int[] { 10000, 5000, 5000, 2000 },
            new int[] { 12000, 5000, 5000, 0 });

        Assert.IsTrue(game.tournamentEliminated[3], "Seat 3 busted and should be eliminated");
        Assert.AreEqual(startMillis - 300000, game.blindLevelStartMillis,
            "An elimination should take 5 minutes off the current blind level by default");
    }

    [Test]
    public void TestEliminationBlindTimerCutHonoursTheConfiguredAmount()
    {
        game.currentBlindLevelIndex = 0;
        game.tournamentLevelDurationSeconds = 900;
        game.eliminationBlindTimerCutSeconds = 120f; // a table that wants a gentler squeeze
        int startMillis = game.GetTimeMillis();
        game.blindLevelStartMillis = startMillis;

        PlayOutHandWithBustedSeats(
            new int[] { 10000, 5000, 5000, 2000 },
            new int[] { 12000, 5000, 5000, 0 });

        Assert.IsTrue(game.tournamentEliminated[3], "Seat 3 busted and should be eliminated");
        Assert.AreEqual(startMillis - 120000, game.blindLevelStartMillis,
            "The cut should follow the configured setting, not a hard-coded 5 minutes");
    }

    [Test]
    public void TestEliminationBlindTimerCutCarriesPastTheEndOfTheLevel()
    {
        game.currentBlindLevelIndex = 0;
        game.tournamentLevelDurationSeconds = 300; // a 5 minute level, and two players bust at once
        game.blindLevelStartMillis = game.GetTimeMillis();

        PlayOutHandWithBustedSeats(
            new int[] { 10000, 5000, 2000, 2000 },
            new int[] { 19000, 5000, 0, 0 });

        Assert.IsTrue(game.tournamentEliminated[2] && game.tournamentEliminated[3], "Both short stacks should be eliminated");

        // 10 minutes off a 5 minute level: the level is spent and the extra 5 minutes must
        // survive on the clock rather than being clamped away at the level boundary.
        int elapsed = game.GetTimeMillis() - game.blindLevelStartMillis;
        Assert.GreaterOrEqual(elapsed, 600000, "The full cut should be on the clock");
        Assert.LessOrEqual(elapsed, 602000, "The cut should not exceed what the eliminations bought");
        Assert.AreEqual(0, game.currentBlindLevelIndex, "The level advances on the next hand, not inside the cut");
    }

    [Test]
    public void TestBlindLevelAdvanceCarriesSurplusIntoTheNextLevel()
    {
        // The clock is 12 minutes into a 10 minute level, so the next level starts 2 minutes
        // in rather than with a fresh 10 minutes. Restarting from "now" here would silently
        // hand back every minute an elimination took off.
        game.isTournamentMode = true;
        game.isTournamentActive = true;
        game.currentBlindLevelIndex = 0;
        game.tournamentLevelDurationSeconds = 600;
        game.blindLevelStartMillis = game.GetTimeMillis() - 720000;
        game.tableState = HoldemGame.TABLE_READY;

        game.Transition();

        Assert.AreEqual(1, game.currentBlindLevelIndex, "The spent level should advance");
        Assert.AreEqual(200, game.bigBlind, "Big blind moves to the next level in the schedule");

        int elapsed = game.GetTimeMillis() - game.blindLevelStartMillis;
        Assert.GreaterOrEqual(elapsed, 120000, "The 2 minute surplus must carry into the new level");
        Assert.LessOrEqual(elapsed, 122000, "Only the surplus carries, not the whole overrun");
    }

    [Test]
    public void TestEliminationLateInALevelShortensTheNextOne()
    {
        // 3 minutes left on a 10 minute level when a player busts: the 5 minute cut spends
        // what is left and the next level opens 2 minutes deep, leaving 8 minutes on it.
        game.currentBlindLevelIndex = 0;
        game.tournamentLevelDurationSeconds = 600;
        game.blindLevelStartMillis = game.GetTimeMillis() - 420000; // 7 minutes gone, 3 left

        PlayOutHandWithBustedSeats(
            new int[] { 10000, 5000, 5000, 2000 },
            new int[] { 12000, 5000, 5000, 0 });

        Assert.IsTrue(game.tournamentEliminated[3], "Seat 3 busted and should be eliminated");

        game.tableState = HoldemGame.TABLE_READY;
        game.lastTransitionMillis = game.GetTimeMillis();
        game.Transition();

        Assert.AreEqual(1, game.currentBlindLevelIndex, "The cut should have run the level out");

        int remaining = (int)game.tournamentLevelDurationSeconds - (game.GetTimeMillis() - game.blindLevelStartMillis) / 1000;
        Assert.GreaterOrEqual(remaining, 478, "The new level should open about 2 minutes in");
        Assert.LessOrEqual(remaining, 481, "The new level should open about 2 minutes in");
    }

    [Test]
    public void TestTournamentBlindLevelHoldsBeforeTheTimerExpires()
    {
        game.isTournamentMode = true;
        game.isTournamentActive = true;
        game.currentBlindLevelIndex = 1;
        game.tournamentLevelDurationSeconds = 300;
        game.blindLevelStartMillis = game.GetTimeMillis() - 60000; // only a minute in
        game.tableState = HoldemGame.TABLE_READY;

        game.Transition();

        Assert.AreEqual(1, game.currentBlindLevelIndex, "The level must not advance early");
        Assert.AreEqual(200, game.bigBlind, "Big blind stays on the current level");
    }

    [Test]
    public void TestAdjustBuyIn()
    {
        Assert.AreEqual(1000, game.tournamentBuyIn);

        game.IncreaseBuyIn();
        Assert.AreEqual(1500, game.tournamentBuyIn, "Increase should add 500");
        game.DecreaseBuyIn();
        Assert.AreEqual(1000, game.tournamentBuyIn, "Decrease should subtract 500");

        game.tournamentBuyIn = 500;
        game.DecreaseBuyIn();
        Assert.AreEqual(500, game.tournamentBuyIn, "Should clamp at the 500 minimum");

        game.tournamentBuyIn = 100000;
        game.IncreaseBuyIn();
        Assert.AreEqual(100000, game.tournamentBuyIn, "Should clamp at the 100000 maximum");

        game.isTournamentActive = true;
        game.tournamentBuyIn = 1000;
        game.IncreaseBuyIn();
        game.DecreaseBuyIn();
        Assert.AreEqual(1000, game.tournamentBuyIn, "Buy-in must not move once players have paid it");
    }

    [Test]
    public void TestAdjustStartingStack()
    {
        Assert.AreEqual(10000, game.tournamentStartingStack);

        game.IncreaseStartingStack();
        Assert.AreEqual(11000, game.tournamentStartingStack, "Increase should add 1000");
        game.DecreaseStartingStack();
        Assert.AreEqual(10000, game.tournamentStartingStack, "Decrease should subtract 1000");

        game.tournamentStartingStack = 1000;
        game.DecreaseStartingStack();
        Assert.AreEqual(1000, game.tournamentStartingStack, "Should clamp at the 1000 minimum");

        game.tournamentStartingStack = 500000;
        game.IncreaseStartingStack();
        Assert.AreEqual(500000, game.tournamentStartingStack, "Should clamp at the 500000 maximum");

        game.isTournamentActive = true;
        game.tournamentStartingStack = 10000;
        game.IncreaseStartingStack();
        game.DecreaseStartingStack();
        Assert.AreEqual(10000, game.tournamentStartingStack, "Starting stack must not move mid-tournament");
    }

    [Test]
    public void TestStartTournamentRequiresTwoPlayersAndTheBuyIn()
    {
        game.isTournamentMode = true;
        game.tournamentBuyIn = 1000;

        var solo = SeatAndBuyIn(1, 5000);
        game.StartTournament();
        Assert.IsFalse(game.isTournamentActive, "One player is not a tournament");
        Assert.AreEqual(0, solo[0].GetProfit(), "Nobody should be charged for a tournament that never started");

        // Seat a second player who cannot cover the buy-in.
        var balanceGo = new GameObject("Balance_broke");
        var broke = balanceGo.AddComponent<PlayerBalanceComponent>();
        broke.CurrentSyncedBalance = 100;
        typeof(PlayerBalanceComponent).GetField("bIsReady", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)
            .SetValue(broke, true);
        typeof(HoldemPlayer).GetField("activePlayerId", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)
            .SetValue(game.players[1], -2);
        typeof(HoldemPlayer).GetField("ActivePlayerBalanceComponent", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)
            .SetValue(game.players[1], broke);

        game.StartTournament();

        Assert.IsFalse(game.isTournamentActive, "A player short of the buy-in blocks the start");
        Assert.AreEqual(0, solo[0].GetProfit(), "The buy-in must not be taken from anyone on a failed start");
        Assert.AreEqual(100, broke.GetBalance());
    }

    // Busting out of a tournament should take the player off the table, not leave them
    // sitting in a seat they can no longer play from.
    [Test]
    public void TestEliminatedPlayerIsUnseated()
    {
        game.isTournamentMode = true;
        game.isTournamentActive = true;
        game.totalParticipants = 2;
        game.tournamentEliminated = new bool[10];
        game.tableState = HoldemGame.TABLE_PLAYING;
        game.wonByFold = true;
        game.lastTransitionMillis = game.GetTimeMillis();

        var activePlayerIdField = typeof(HoldemPlayer).GetField("activePlayerId", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
        activePlayerIdField.SetValue(game.players[0], -2);
        activePlayerIdField.SetValue(game.players[1], -2);
        for (int i = 2; i < 10; i++) game.tournamentEliminated[i] = true;

        game.handStartStacks[0] = 5000;
        game.handStartStacks[1] = 5000;
        game.stacks[0] = 10000;
        game.stacks[1] = 0;

        Assert.IsTrue(game.players[1].IsSeated());

        game.Transition();

        Assert.IsTrue(game.tournamentEliminated[1]);
        Assert.AreEqual(2, game.playerRanks[1]);
        Assert.IsFalse(game.players[1].IsSeated(), "A busted player should be released from their seat");
        Assert.IsTrue(game.players[0].IsSeated(), "The survivor keeps their seat");
    }

    // Regression: the record of who paid a buy-in lived only in a master-local component
    // array, so a master that took over mid-tournament had nothing to pay into and the prize
    // for anyone no longer sat in their seat was silently dropped. The synced ids are what
    // survives the handover.
    [Test]
    public void TestPayoutResolvesFromBuyInIdWithNoSeatAndNoLocalState()
    {
        game.isTournamentMode = true;
        game.tournamentBuyIn = 1000;
        game.tournamentStartingStack = 10000;

        var balances = SeatAndBuyIn(3, 5000);
        game.StartTournament();
        Assert.IsTrue(game.isTournamentActive);

        for (int i = 0; i < 3; i++)
        {
            Assert.AreEqual(FirstFakePlayerId + i, game.tournamentPlayerIds[i],
                $"Seat {i} should record the id of whoever paid its buy-in");
        }
        for (int i = 3; i < 10; i++)
        {
            Assert.AreEqual(0, game.tournamentPlayerIds[i], $"Empty seat {i} should record no id");
        }

        // The player walks away from the table but stays in the instance. This is the state a
        // freshly promoted master sees: a vacated seat and no local memory of the buy-in.
        StandUp(0);

        Assert.IsNull(game.GetSeatBalanceComponent(0),
            "A vacated seat has no balance component -- this is what used to lose the payout");
        Assert.AreSame(balances[0], game.GetTournamentBalanceComponent(0),
            "The payout target must still be reachable from the recorded buy-in id alone");

        // Seats still occupied resolve to the same component either way.
        Assert.AreSame(balances[1], game.GetTournamentBalanceComponent(1));

        game.CancelTournament();

        Assert.AreEqual(0, balances[0].GetProfit(),
            "The participant who stood up must be refunded off the recorded id");
        for (int i = 0; i < 10; i++)
        {
            Assert.AreEqual(0, game.tournamentPlayerIds[i],
                $"Seat {i} should be off the payout roster once the tournament is over");
        }
    }

    // If they left the instance outright there is nobody to pay, and resolving must come back
    // empty rather than land on whoever inherited their player objects.
    [Test]
    public void TestPayoutResolvesToNothingWhenTheBuyerLeftTheInstance()
    {
        game.isTournamentMode = true;
        game.tournamentBuyIn = 1000;

        SeatAndBuyIn(2, 5000);
        game.StartTournament();

        StandUp(0);
        playersById.Remove(FirstFakePlayerId); // they disconnected

        Assert.IsNull(game.GetTournamentBalanceComponent(0),
            "A departed player should resolve to nothing at all");
        Assert.AreEqual(FirstFakePlayerId, game.tournamentPlayerIds[0],
            "Their seat should still name them, in case they reconnect and retake it");
    }

    // handStartStacks is what orders same-hand bustouts, so it has to be written on the deal
    // rather than reconstructed later. It is synced so a new master inherits it mid-hand.
    [Test]
    public void TestHandStartStacksAreCapturedOnTheDeal()
    {
        game.isTournamentMode = true;
        game.isTournamentActive = true;
        game.tournamentEliminated = new bool[10];
        for (int i = 3; i < 10; i++) game.tournamentEliminated[i] = true;

        var activePlayerIdField = typeof(HoldemPlayer).GetField("activePlayerId", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
        for (int i = 0; i < 3; i++) activePlayerIdField.SetValue(game.players[i], -2);

        game.stacks[0] = 7000;
        game.stacks[1] = 3000;
        game.stacks[2] = 500;

        // Stale values from a previous hand; the deal must overwrite them.
        game.handStartStacks[0] = 123;
        game.handStartStacks[1] = 123;
        game.handStartStacks[2] = 123;

        game.tableState = HoldemGame.TABLE_READY;
        game.lastTransitionMillis = game.GetTimeMillis() - 60000;
        game.Transition();

        Assert.AreEqual(HoldemGame.TABLE_PLAYING, game.tableState, "The table should have dealt in");
        Assert.AreEqual(7000, game.handStartStacks[0]);
        Assert.AreEqual(3000, game.handStartStacks[1]);
        Assert.AreEqual(500, game.handStartStacks[2]);
    }

    [Test]
    public void TestTournamentCancelUnseatsSeatedPlayers()
    {
        game.isTournamentMode = true;
        game.isTournamentActive = true;
        game.tournamentBuyIn = 1000;
        game.tournamentEliminated = new bool[10];

        var activePlayerIdField = typeof(HoldemPlayer).GetField("activePlayerId", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
        for (int i = 0; i < 3; i++)
        {
            activePlayerIdField.SetValue(game.players[i], -2);
            Assert.IsTrue(game.players[i].IsSeated());
        }

        game.CancelTournament();

        Assert.IsFalse(game.isTournamentActive);
        for (int i = 0; i < 3; i++)
        {
            Assert.IsFalse(game.players[i].IsSeated(), $"Player {i} should be removed from table when tournament is cancelled");
        }
    }
}




