using NUnit.Framework;
using UnityEngine;

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

    // Card indices are suit * 13 + (rank - 2): 0..12 clubs, 13..25 diamonds,
    // 26..38 hearts, 39..51 spades. Rank runs 2..14, where 14 is the ace.
    private const int CLUBS = 0, DIAMONDS = 13, HEARTS = 26, SPADES = 39;
    private static int Card(int suit, int rank) { return suit + rank - 2; }

    // holeCards0/holeCards1 are parallel per-seat arrays: seat i holds
    // holeCards0[i] and holeCards1[i]. Both of a seat's cards never live in the
    // same array.
    private static void Deal(int[] holeCards0, int[] holeCards1, int seat, int card0, int card1)
    {
        holeCards0[seat] = card0;
        holeCards1[seat] = card1;
    }

    [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()
    {
        Object.DestroyImmediate(gameGo);
    }

    [Test]
    public void TestBlindCappingAvoidsNegativeStacks()
    {
        // Setup stacks where little blind has fewer chips than blind amount
        int[] stacks = new int[10];
        int[] roundContribution = new int[10];
        int[] playerState = new int[10];
        bool[] playerStackedAndReady = new bool[10];

        for (int i = 0; i < 3; i++)
        {
            stacks[i] = i == 1 ? 20 : 1000; // Seat 1 has only 20 chips
            playerStackedAndReady[i] = true;
        }

        // Call private SetupBlinds via Reflection
        var setupBlindsMethod = typeof(HoldemGame).GetMethod("SetupBlinds", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
        Assert.IsNotNull(setupBlindsMethod, "SetupBlinds method should exist");

        object[] args = new object[] {
            9, // dealer (so NextReady(9)=0 dealer, NextReady(0)=1 little blind, NextReady(1)=2 big blind)
            100, // BB (SB is 50)
            playerState,
            stacks,
            roundContribution,
            playerStackedAndReady
        };

        setupBlindsMethod.Invoke(game, args);

        // Seat 1 is little blind seat. Small blind is 50. Since stacks[1] was 20, it should be capped to 20.
        // It should NOT become negative (-30).
        Assert.AreEqual(20, roundContribution[1]);
        Assert.AreEqual(0, stacks[1]);

        // Seat 2 is big blind seat. Big blind is 100.
        Assert.AreEqual(100, roundContribution[2]);
        Assert.AreEqual(900, stacks[2]);
    }

    [Test]
    public void TestDividePotExcludesDeadPlayers()
    {
        // Seat 0: Active, 10 chips in pot, Pair of Aces
        // Seat 1: Active, 10 chips in pot, Pair of Kings
        // Seat 2: DEAD (Folded), 100 chips in pot
        int[] potContribution = new int[10] { 10, 10, 100, 0, 0, 0, 0, 0, 0, 0 };
        int[] playerState = new int[10] { HoldemGame.PLAYER_COMMITED, HoldemGame.PLAYER_COMMITED, HoldemGame.PLAYER_DEAD, 0, 0, 0, 0, 0, 0, 0 };
        
        // Seat 0 pocket aces, seat 1 pocket kings, seat 2 (dead) pocket queens.
        int[] holeCards0 = new int[10];
        int[] holeCards1 = new int[10];
        Deal(holeCards0, holeCards1, 0, Card(CLUBS, 14), Card(DIAMONDS, 14));
        Deal(holeCards0, holeCards1, 1, Card(CLUBS, 13), Card(DIAMONDS, 13));
        Deal(holeCards0, holeCards1, 2, Card(CLUBS, 12), Card(DIAMONDS, 12));

        // Board 2S 7D 9H JC 4H: no board pair, no straight, no flush.
        ulong[] handValues = game.GetHandValues(playerState, holeCards0, holeCards1,
            Card(SPADES, 2), Card(DIAMONDS, 7), Card(HEARTS, 9), Card(CLUBS, 11), Card(HEARTS, 4));
        int[] playerRanks = game.RankPlayers(handValues);

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

        // Dead player (Seat 2) should NOT receive any winnings!
        Assert.AreEqual(0, winnings[2], "Dead/Folded player should NOT receive winnings from pot!");
        Assert.AreEqual(-1, playerRanks[2], "Dead player rank should be -1");
        // Winner (Seat 0) wins main pot (30) plus uncollected chips (90) = 120 total
        // Seat 1 (Rank 1, lost to Seat 0) receives 0
        Assert.AreEqual(120, winnings[0], "Winner should receive main pot plus uncollected chips");
        Assert.AreEqual(0, winnings[1], "Rank 1 player (lost to Rank 0) should receive 0");
    }

    [Test]
    public void TestShortAllInDoesNotReduceMinimumRaise()
    {
        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, 100, 0, 0, 0, 0, 0, 0, 0, 0 };
        int[] potContribution = new int[10];

        // Seat 2 goes short all-in for 105 (raises currentBet from 100 to 105, a raise of only 5 chips, below minRaise of 100)
        object[] result = game.CalculateGameTransition(
            10000, HoldemGame.PREFLOP, 2,
            100, 100, false,
            playerState, stacks, roundContribution, potContribution,
            10005, 16, 3, 100, 0, true,
            105, true, 0, 0
        );

        Assert.IsNotNull(result);
        int newMinRaise = (int)result[3];

        // minimumRaise should NOT shrink from 100 to 5!
        Assert.AreEqual(100, newMinRaise, "Short all-in should NOT reduce minimumRaise below original minRaise");
    }

    [Test]
    public void TestShortAllInReopensCallOnlyActionToCommittedPlayers()
    {
        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, 100, 0, 0, 0, 0, 0, 0, 0, 0 };
        int[] potContribution = new int[10];

        // Seat 2 goes short all-in for 105 (below minRaise of 100)
        object[] result = game.CalculateGameTransition(
            10000, HoldemGame.PREFLOP, 2,
            100, 100, false,
            playerState, stacks, roundContribution, potContribution,
            10005, 16, 3, 100, 0, true,
            105, true, 0, 0
        );

        Assert.IsNotNull(result);
        int[] newPlayerStates = (int[])result[6];
        int newCallOnlyMask = (int)result[11];

        // Seat 0 is in for 100 against a currentBet of 105, so it still owes 5. A short all-in
        // takes away its raising rights, not its right to call. Seat 0 is the only seat left
        // to act, so it goes straight to PLAYER_ACTING.
        Assert.AreEqual(0, (int)result[1], "Action comes back to seat 0");
        Assert.AreEqual(HoldemGame.PLAYER_ACTING, newPlayerStates[0],
            "Short all-in should reopen a call-or-fold decision to committed players who are now short");
        Assert.AreEqual(1, newCallOnlyMask & 1, "Seat 0 should be flagged call-only");
        Assert.AreEqual(0, newCallOnlyMask & (1 << 1), "A seat that has not acted yet keeps its raising rights");
        Assert.AreEqual(0, newCallOnlyMask & (1 << 2), "The all-in seat itself is not call-only");
    }

    [Test]
    public void TestShortAllInLetsTheOriginalBettorCallAndTheRemainderStaysInThePot()
    {
        // The reported bug: seat 0 bets 2500, seat 1 shoves 3500. Seat 0 could not call the
        // extra 1000, so it was left uncalled and handed straight back to seat 1 at showdown.
        int[] playerState = new int[10] { HoldemGame.PLAYER_COMMITED, HoldemGame.PLAYER_ACTING, 0, 0, 0, 0, 0, 0, 0, 0 };
        int[] stacks = new int[10] { 7500, 3500, 0, 0, 0, 0, 0, 0, 0, 0 };
        int[] roundContribution = new int[10] { 2500, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
        int[] potContribution = new int[10];

        // minimumRaise is 2500 (seat 0's bet), so 3500 is a raise of only 1000 -- a short all-in.
        object[] shove = game.CalculateGameTransition(
            10000, HoldemGame.FLOP, 1,
            2500, 2500, false,
            playerState, stacks, roundContribution, potContribution,
            10005, 16, 3, 100, 0, true,
            3500, true, 0, 0
        );

        Assert.IsNotNull(shove);
        Assert.AreEqual(3500, (int)shove[2], "currentBet moves up to the shove");
        Assert.AreEqual(2500, (int)shove[3], "A short all-in does not shrink minimumRaise");
        Assert.AreEqual(0, (int)shove[1], "Action comes back to seat 0");
        Assert.AreEqual(HoldemGame.PLAYER_ACTING, ((int[])shove[6])[0], "Seat 0 gets to act again");
        Assert.AreEqual(1, (int)shove[11] & 1, "Seat 0 may only call or fold");

        // Seat 0 calls the extra 1000.
        object[] call = game.CalculateGameTransition(
            10005, HoldemGame.FLOP, 0,
            3500, 2500, false,
            playerState, stacks, roundContribution, potContribution,
            10010, 16, 3, 100, 0, true,
            1000, true, 1, (int)shove[11]
        );

        Assert.IsNotNull(call);
        int[] newPot = (int[])call[9];
        Assert.AreEqual(3500, newPot[0], "Seat 0's call lands in the pot");
        Assert.AreEqual(3500, newPot[1], "Seat 1's shove is fully matched");
        Assert.AreEqual(6500, stacks[0], "Seat 0 paid the extra 1000");
        Assert.AreEqual(0, (int)call[11], "call-only clears once the round closes");

        // Nothing comes back to seat 1: seat 0 wins the whole 7000.
        int[] ranks = new int[10] { 0, 1, -1, -1, -1, -1, -1, -1, -1, -1 };
        int[] winnings = game.DividePot(newPot, ranks, 0);
        Assert.AreEqual(7000, winnings[0], "The winner takes the fully matched pot");
        Assert.AreEqual(0, winnings[1], "No uncalled remainder is refunded to the all-in player");
    }

    [Test]
    public void TestShortAllInDoesNotReopenSeatsWithNoChipsLeft()
    {
        // Seat 0 is already all-in for 100 and cannot cover the extra 5.
        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] { 0, 1000, 105, 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(
            10000, HoldemGame.PREFLOP, 2,
            100, 100, false,
            playerState, stacks, roundContribution, potContribution,
            10005, 16, 3, 100, 0, true,
            105, true, 0, 0
        );

        Assert.IsNotNull(result);
        int[] newPlayerStates = (int[])result[6];
        int newCallOnlyMask = (int)result[11];

        Assert.AreEqual(HoldemGame.PLAYER_COMMITED, newPlayerStates[0], "An already all-in seat has nothing to decide");
        Assert.AreEqual(0, newCallOnlyMask & 1, "An already all-in seat is not call-only");
    }

    [Test]
    public void TestHandEvaluation_RoyalFlushBeatsStraightFlush()
    {
        int[] playerState = new int[10] { HoldemGame.PLAYER_COMMITED, HoldemGame.PLAYER_COMMITED, 0, 0, 0, 0, 0, 0, 0, 0 };
        
        int[] holeCards0 = new int[10];
        int[] holeCards1 = new int[10];
        // Seat 0: KS AS -> royal flush (10S JS QS KS AS)
        Deal(holeCards0, holeCards1, 0, Card(SPADES, 13), Card(SPADES, 14));
        // Seat 1: 8S 3C -> queen-high straight flush (8S 9S 10S JS QS)
        Deal(holeCards0, holeCards1, 1, Card(SPADES, 8), Card(CLUBS, 3));

        // Board: 9S 10S JS QS 2H
        ulong[] handValues = game.GetHandValues(holeCards0: holeCards0, holeCards1: holeCards1, playerState: playerState,
            flop0: Card(SPADES, 10), flop1: Card(SPADES, 11), flop2: Card(SPADES, 12),
            turn: Card(SPADES, 9), river: Card(HEARTS, 2));
        int[] ranks = game.RankPlayers(handValues);

        Assert.IsTrue(handValues[0] > handValues[1], "Royal Flush should have higher hand value than Straight Flush");
        Assert.AreEqual(0, ranks[0], "Royal Flush should rank 1st (Rank 0)");
        Assert.AreEqual(1, ranks[1], "Straight Flush should rank 2nd (Rank 1)");
    }

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

        // Board has 4 Eights: 8S(45), 8H(19), 8D(6), 8C(32), 2S(39)
        // Seat 0 has Ace kicker (AS = 51)
        // Seat 1 has King kicker (KH = 24)
        int[] holeCards0 = new int[10] { 51, 24, 0, 0, 0, 0, 0, 0, 0, 0 }; // Seat 0: AS, Seat 1: KH
        int[] holeCards1 = new int[10] { 40, 41, 0, 0, 0, 0, 0, 0, 0, 0 }; // Seat 0: 3S, Seat 1: 4S

        ulong[] handValues = game.GetHandValues(playerState, holeCards0, holeCards1, 45, 19, 6, 32, 39);
        int[] ranks = game.RankPlayers(handValues);

        Assert.IsTrue(handValues[0] > handValues[1], "Four of a Kind with Ace kicker beats Four of a Kind with King kicker");
        Assert.AreEqual(0, ranks[0]);
        Assert.AreEqual(1, ranks[1]);
    }

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

        // Board: AS(51), AH(25), KS(50), KH(24), 2S(39)
        // Seat 0 has AD(12) -> Aces full of Kings (A-A-A-K-K)
        // Seat 1 has KD(11) -> Kings full of Aces (K-K-K-A-A)
        int[] holeCards0 = new int[10] { 12, 11, 0, 0, 0, 0, 0, 0, 0, 0 }; // Seat 0: AD, Seat 1: KD
        int[] holeCards1 = new int[10] { 40, 41, 0, 0, 0, 0, 0, 0, 0, 0 }; // Seat 0: 3S, Seat 1: 4S

        ulong[] handValues = game.GetHandValues(playerState, holeCards0, holeCards1, 51, 25, 50, 24, 39);
        int[] ranks = game.RankPlayers(handValues);

        Assert.IsTrue(handValues[0] > handValues[1], "Aces full of Kings beats Kings full of Aces");
        Assert.AreEqual(0, ranks[0]);
        Assert.AreEqual(1, ranks[1]);
    }

    [Test]
    public void TestHandEvaluation_WheelStraightComparison()
    {
        int[] playerState = new int[10];
        playerState[0] = HoldemGame.PLAYER_COMMITED;
        playerState[1] = HoldemGame.PLAYER_COMMITED;

        int[] holeCards0 = new int[10];
        int[] holeCards1 = new int[10];
        // Seat 0: AS QS -> wheel straight A-2-3-4-5 (5-high)
        Deal(holeCards0, holeCards1, 0, Card(SPADES, 14), Card(SPADES, 12));
        // Seat 1: 6S QH -> 6-high straight 2-3-4-5-6
        Deal(holeCards0, holeCards1, 1, Card(SPADES, 6), Card(HEARTS, 12));

        // Board: 2S 3D 4H 5H 9S
        ulong[] handValues = game.GetHandValues(playerState, holeCards0, holeCards1,
            Card(SPADES, 2), Card(DIAMONDS, 3), Card(HEARTS, 4), Card(HEARTS, 5), Card(SPADES, 9));
        int[] ranks = game.RankPlayers(handValues);

        Assert.IsTrue(handValues[1] > handValues[0], "6-high straight beats 5-high wheel straight");
        Assert.AreEqual(0, ranks[1]);
        Assert.AreEqual(1, ranks[0]);
    }

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

        // Board is a spade royal flush; neither seat can improve on it, so both play the board.
        int[] holeCards0 = new int[10];
        int[] holeCards1 = new int[10];
        Deal(holeCards0, holeCards1, 0, Card(CLUBS, 2), Card(DIAMONDS, 3));
        Deal(holeCards0, holeCards1, 1, Card(HEARTS, 4), Card(CLUBS, 5));

        ulong[] handValues = game.GetHandValues(playerState, holeCards0, holeCards1,
            Card(SPADES, 10), Card(SPADES, 11), Card(SPADES, 12), Card(SPADES, 13), Card(SPADES, 14));
        int[] ranks = game.RankPlayers(handValues);

        // Both players have identical 5-card Royal Flush from board
        Assert.AreEqual(handValues[0], handValues[1], "Both players playing board have identical hand values");
        Assert.AreEqual(0, ranks[0], "Player 0 is Rank 0 (tied)");
        Assert.AreEqual(0, ranks[1], "Player 1 is Rank 0 (tied)");

        int[] potContribution = new int[10] { 100, 100, 0, 0, 0, 0, 0, 0, 0, 0 };
        int[] winnings = game.DividePot(potContribution, ranks);

        Assert.AreEqual(100, winnings[0], "Split pot: Player 0 gets 100");
        Assert.AreEqual(100, winnings[1], "Split pot: Player 1 gets 100");
    }

    [Test]
    public void TestSidePot_ThreeWayAllInDifferentStacks()
    {
        // Seat 0: Short stack all-in 100
        // Seat 1: Medium stack all-in 250
        // Seat 2: Big stack covers 500
        int[] potContribution = new int[10] { 100, 250, 250, 0, 0, 0, 0, 0, 0, 0 };
        int[] playerRanks = new int[10] { 0, 1, 2, -1, -1, -1, -1, -1, -1, -1 }; // Seat 0 wins Main Pot, Seat 1 wins Side Pot

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

        // Main pot = 100 * 3 = 300 -> Seat 0 (Rank 0) wins 300
        Assert.AreEqual(300, winnings[0], "Short stack winner (Rank 0) should win Main Pot (300)");
        // Side pot = (250 - 100) * 2 = 300 -> Seat 1 (Rank 1) wins 300
        Assert.AreEqual(300, winnings[1], "Medium stack winner (Rank 1) should win Side Pot (300)");
        // Seat 2 loses
        Assert.AreEqual(0, winnings[2], "Covering player (Rank 2) wins 0 from main/side pots");
    }

    [Test]
    public void TestSidePot_SplitPotOddChip()
    {
        // Pot total = 101 chips (Seat 0 put 51, Seat 1 put 50)
        int[] potContribution = new int[10] { 51, 50, 0, 0, 0, 0, 0, 0, 0, 0 };
        int[] playerRanks = new int[10] { 0, 0, -1, -1, -1, -1, -1, -1, -1, -1 }; // Tied Rank 0

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

        // Total distributed must equal total pot (101)
        int totalWinnings = winnings[0] + winnings[1];
        Assert.AreEqual(101, totalWinnings, "Total pot of 101 must be fully distributed without losing chips");
        Assert.IsTrue(winnings[0] >= 50 && winnings[1] >= 50, "Both tied players get at least half");
    }

    [Test]
    public void TestSplitSidePot_BothPlayersPaidEqualShare()
    {
        // Seat 0: Short stack all-in 100 (Wins Main Pot = 300)
        // Seat 1: Stack 500 (Ties Seat 2 for 2nd place / Side Pot)
        // Seat 2: Stack 500 (Ties Seat 1 for 2nd place / Side Pot)
        int[] potContribution = new int[10] { 100, 500, 500, 0, 0, 0, 0, 0, 0, 0 };
        int[] playerRanks = new int[10] { 0, 1, 1, -1, -1, -1, -1, -1, -1, -1 }; // Seat 0 Rank 0, Seats 1&2 tied Rank 1

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

        // Main pot = 100 * 3 = 300 -> Seat 0 (Rank 0) wins 300
        Assert.AreEqual(300, winnings[0], "Seat 0 should win Main Pot (300)");
        // Side pot = (500 - 100) * 2 = 800 -> Split equally between Seat 1 and Seat 2 (400 each)
        Assert.AreEqual(400, winnings[1], "Seat 1 should win half of Side Pot (400)");
        Assert.AreEqual(400, winnings[2], "Seat 2 should win half of Side Pot (400)");
    }

    [Test]
    public void TestSidePot_ShortStackVsMediumStackVsFoldedLargeStack()
    {
        // Seat 0: Short stack all-in 100 (Rank 0 - Best Hand)
        // Seat 1: Medium stack all-in 200 (Rank 1 - Second Best Hand)
        // Seat 2: Large stack 500 (Rank -1 - Folded)
        int[] potContribution = new int[10] { 100, 200, 500, 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);

        // Layer 0 (0..100): 100 * 3 = 300 -> Seat 0 (Rank 0) wins Main Pot 300 (capped at all-in 100 * 3)
        // Layer 1 (100..200): (200-100) * 2 = 200 -> Seat 1 (Rank 1, reached 200) wins 200 side pot
        // Layer 2 (200..500): (500-200) = 300 -> Uncollected from folded Seat 2 goes to highest active contributor Seat 1 (300)
        Assert.AreEqual(300, winnings[0], "Seat 0 should win 300 main pot (capped at all-in 100 * 3)");
        Assert.AreEqual(500, winnings[1], "Seat 1 should win 200 side pot + 300 uncollected chips above active cap");
        Assert.AreEqual(0, winnings[2], "Folded Seat 2 receives 0");
    }

    [Test]
    public void TestDividePot_OddChipDistributionByDealerSeatPosition()
    {
        // Total pot = 101 chips (Seat 0: 50, Seat 1: 50, Seat 2: 1), Seat 0 & 1 tie (Rank 0), Seat 2 loses (Rank 1)
        int[] potContribution = new int[10] { 50, 50, 1, 0, 0, 0, 0, 0, 0, 0 };
        int[] playerRanks = new int[10] { 0, 0, 1, -1, -1, -1, -1, -1, -1, -1 };

        // Case A: Dealer is Seat 0. Small blind position is Seat 1. Seat 1 should receive the odd chip!
        int[] winningsDealer0 = game.DividePot(potContribution, playerRanks, dealerSeat: 0);
        Assert.AreEqual(50, winningsDealer0[0], "Seat 0 (Dealer) receives equal split 50");
        Assert.AreEqual(51, winningsDealer0[1], "Seat 1 (Small Blind) receives odd chip (51 total)");

        // Case B: Dealer is Seat 1. Small blind position is Seat 0. Seat 0 should receive the odd chip!
        int[] winningsDealer1 = game.DividePot(potContribution, playerRanks, dealerSeat: 1);
        Assert.AreEqual(51, winningsDealer1[0], "Seat 0 (Small Blind) receives odd chip (51 total)");
        Assert.AreEqual(50, winningsDealer1[1], "Seat 1 (Dealer) receives equal split 50");
    }

    [Test]
    public void TestSinglePlayerWinsWhenAllFold()
    {
        int[] playerState = new int[10] { HoldemGame.PLAYER_DEAD, HoldemGame.PLAYER_DEAD, HoldemGame.PLAYER_COMMITED, 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 };
        int[] potContribution = new int[10] { 100, 100, 100, 0, 0, 0, 0, 0, 0, 0 };
        bool[] playerIsSeated = new bool[10] { true, true, true, false, false, false, false, false, false, false };
        bool[] playerIsReady = new bool[10] { true, true, true, false, false, false, false, false, false, false };
        int[] holeCards0 = new int[10];
        int[] holeCards1 = new int[10];

        // Seat 0 and 1 folded (PLAYER_DEAD). Action completes on Seat 2.
        object[] result = game.CalculateTransition(
            HoldemGame.TABLE_PLAYING, 10000, HoldemGame.PREFLOP, 2, 0,
            100, 100, false, false,
            playerState, stacks, roundContribution, potContribution,
            0, 0, 0, 0, 0, holeCards0, holeCards1, 0, 0,
            10005, 100, 10, 10, 16, 3,
            playerIsSeated, playerIsReady, false,
            100, true, null
        );

        Assert.IsNotNull(result);
        int newTableState = (int)result[0];
        bool wonByFold = (bool)result[8];
        int winnerMask = (int)result[21];

        Assert.AreEqual(HoldemGame.TABLE_WINNER, newTableState, "Game should transition to TABLE_WINNER when all but 1 fold");
        Assert.IsTrue(wonByFold, "wonByFold should be true");
        Assert.AreEqual((1 << 2), winnerMask, "winnerMask should be set to (1 << 2) for fold win");
    }

    // Regression: the table used to reach TABLE_WINNER without ever running the payout edge,
    // so the pot was silently destroyed instead of being credited to the winner's stack.
    [Test]
    public void TestShowdownCreditsPotToWinnerStack()
    {
        // Three seats, all still in on the river with 100 each already in the round.
        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] { 900, 900, 900, 0, 0, 0, 0, 0, 0, 0 };
        int[] roundContribution = new int[10] { 100, 100, 100, 0, 0, 0, 0, 0, 0, 0 };
        int[] potContribution = new int[10];
        bool[] playerIsSeated = new bool[10] { true, true, true, false, false, false, false, false, false, false };
        bool[] playerIsReady = new bool[10] { true, true, true, false, false, false, false, false, false, false };

        // Seat 0 pocket aces, seat 1 pocket kings, seat 2 pocket queens.
        int[] holeCards0 = new int[10];
        int[] holeCards1 = new int[10];
        Deal(holeCards0, holeCards1, 0, Card(CLUBS, 14), Card(DIAMONDS, 14));
        Deal(holeCards0, holeCards1, 1, Card(CLUBS, 13), Card(DIAMONDS, 13));
        Deal(holeCards0, holeCards1, 2, Card(CLUBS, 12), Card(DIAMONDS, 12));

        int chipsBefore = 0;
        for (int i = 0; i < 10; i++) chipsBefore += stacks[i] + roundContribution[i] + potContribution[i];

        // Seat 2 checks, closing the river. currentBet matches what everyone already has in for
        // the round, so a bet of 0 reads as a check rather than a raise.
        // Board 2S 3D 4H 7C 9D: no straight, no flush, no board pair.
        object[] result = game.CalculateTransition(
            HoldemGame.TABLE_PLAYING, 10000, HoldemGame.RIVER, 2, 0,
            100, 100, false, false,
            playerState, stacks, roundContribution, potContribution,
            Card(SPADES, 2), Card(DIAMONDS, 3), Card(HEARTS, 4), Card(CLUBS, 7), Card(DIAMONDS, 9),
            holeCards0, holeCards1, 0, 0,
            10005, 100, 10, 10, 16, 3,
            playerIsSeated, playerIsReady, false,
            0, true, null
        );

        Assert.IsNotNull(result);
        Assert.AreEqual(HoldemGame.TABLE_WINNER, (int)result[0], "River close should land on TABLE_WINNER");
        Assert.IsFalse((bool)result[8], "This is a showdown, not a fold win");

        int[] newStacks = (int[])result[10];
        Assert.AreEqual(1200, newStacks[0], "Seat 0 (best hand) should be credited the 300 pot on top of its 900 stack");
        Assert.AreEqual(900, newStacks[1], "Seat 1 stack should be untouched");
        Assert.AreEqual(900, newStacks[2], "Seat 2 stack should be untouched");
        Assert.AreEqual(1 << 0, (int)result[21], "winnerMask should mark seat 0");

        int[] newPot = (int[])result[12];
        int chipsAfter = 0;
        for (int i = 0; i < 10; i++) chipsAfter += newStacks[i] + ((int[])result[11])[i] + newPot[i];
        Assert.AreEqual(chipsBefore, chipsAfter - 300,
            "Chips must be conserved: the pot is now in a stack, so it is counted twice here");
    }

    // Regression: same payout edge, reached via the fold-win path instead of a showdown.
    [Test]
    public void TestFoldWinCreditsPotToWinnerStack()
    {
        int[] playerState = new int[10] { HoldemGame.PLAYER_DEAD, HoldemGame.PLAYER_DEAD, HoldemGame.PLAYER_COMMITED, 0, 0, 0, 0, 0, 0, 0 };
        int[] stacks = new int[10] { 900, 900, 900, 0, 0, 0, 0, 0, 0, 0 };
        int[] roundContribution = new int[10];
        int[] potContribution = new int[10] { 100, 100, 100, 0, 0, 0, 0, 0, 0, 0 };
        bool[] playerIsSeated = new bool[10] { true, true, true, false, false, false, false, false, false, false };
        bool[] playerIsReady = new bool[10] { true, true, true, false, false, false, false, false, false, false };
        int[] holeCards0 = new int[10];
        int[] holeCards1 = new int[10];

        // Seat 2 is last standing and checks; nothing left to call, so the round closes.
        object[] result = game.CalculateTransition(
            HoldemGame.TABLE_PLAYING, 10000, HoldemGame.FLOP, 2, 0,
            0, 0, false, false,
            playerState, stacks, roundContribution, potContribution,
            0, 0, 0, 0, 0, holeCards0, holeCards1, 0, 0,
            10005, 100, 10, 10, 16, 3,
            playerIsSeated, playerIsReady, false,
            0, true, null
        );

        Assert.IsNotNull(result);
        Assert.AreEqual(HoldemGame.TABLE_WINNER, (int)result[0]);
        Assert.IsTrue((bool)result[8], "wonByFold should be true");

        int[] newStacks = (int[])result[10];
        Assert.AreEqual(1200, newStacks[2], "Sole survivor should be credited the whole 300 pot");
        Assert.AreEqual(900, newStacks[0], "Folded seat 0 gets nothing back");
        Assert.AreEqual(900, newStacks[1], "Folded seat 1 gets nothing back");
        Assert.AreEqual(1 << 2, (int)result[21], "winnerMask should mark seat 2");
    }

    // The pot has to survive a split too, with no chips created or destroyed.
    [Test]
    public void TestShowdownSplitPotCreditsBothStacks()
    {
        int[] playerState = new int[10] { HoldemGame.PLAYER_COMMITED, HoldemGame.PLAYER_ACTING, 0, 0, 0, 0, 0, 0, 0, 0 };
        int[] stacks = new int[10] { 900, 900, 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];
        bool[] playerIsSeated = new bool[10] { true, true, false, false, false, false, false, false, false, false };
        bool[] playerIsReady = new bool[10] { true, true, false, false, false, false, false, false, false, false };

        // Board is a spade royal flush; both seats play the board for an identical hand.
        int[] holeCards0 = new int[10];
        int[] holeCards1 = new int[10];
        Deal(holeCards0, holeCards1, 0, Card(CLUBS, 2), Card(CLUBS, 3)); // 2C 3C
        Deal(holeCards0, holeCards1, 1, Card(CLUBS, 4), Card(CLUBS, 5)); // 4C 5C

        object[] result = game.CalculateTransition(
            HoldemGame.TABLE_PLAYING, 10000, HoldemGame.RIVER, 1, 0,
            100, 100, false, false,
            playerState, stacks, roundContribution, potContribution,
            Card(SPADES, 10), Card(SPADES, 11), Card(SPADES, 12), Card(SPADES, 13), Card(SPADES, 14),
            holeCards0, holeCards1, 0, 0,
            10005, 100, 10, 10, 16, 3,
            playerIsSeated, playerIsReady, false,
            0, true, null
        );

        Assert.IsNotNull(result);
        Assert.AreEqual(HoldemGame.TABLE_WINNER, (int)result[0]);

        int[] newStacks = (int[])result[10];
        Assert.AreEqual(1000, newStacks[0], "Seat 0 takes back its half of the 200 pot");
        Assert.AreEqual(1000, newStacks[1], "Seat 1 takes back its half of the 200 pot");
        Assert.AreEqual((1 << 0) | (1 << 1), (int)result[21], "Both seats should be flagged as winners");
    }

    [Test]
    public void TestActingPlayerDisconnectFoldsHand()
    {
        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 };
        int[] potContribution = new int[10];

        // Seat 1 is acting player but has left/unseated (actingPlayerBet == -1, actingPlayerCommited == false)
        object[] result = game.CalculateGameTransition(
            10000, HoldemGame.PREFLOP, 1,
            100, 100, false,
            playerState, stacks, roundContribution, potContribution,
            10005, 16, 3, 100, 0, false,
            -1, false, 0, 0
        );

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

        Assert.AreEqual(HoldemGame.PLAYER_DEAD, newPlayerStates[1], "Unseated/Disconnected acting player hand should be marked PLAYER_DEAD (folded)");
    }

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

        var setupBlindsMethod = typeof(HoldemGame).GetMethod("SetupBlinds", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
        Assert.IsNotNull(setupBlindsMethod);

        object[] args = new object[] {
            1, // last dealer seat 1 (so next dealer for this hand is Seat 0)
            100, // BB 100 (SB 50)
            playerState,
            stacks,
            roundContribution,
            playerStackedAndReady
        };

        setupBlindsMethod.Invoke(game, args);

        // In Heads-up, Dealer (Seat 0) posts Small Blind (50), NextReady(0)=Seat 1 posts Big Blind (100)
        Assert.AreEqual(50, roundContribution[0], "Heads-up dealer (Seat 0) should post Small Blind (50)");
        Assert.AreEqual(100, roundContribution[1], "Heads-up opponent (Seat 1) should post Big Blind (100)");
    }

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

        int[] holeCards0 = new int[10];
        int[] holeCards1 = new int[10];
        // Seat 0: AS 3S -> ace-high flush A-9-7-4-3
        Deal(holeCards0, holeCards1, 0, Card(SPADES, 14), Card(SPADES, 3));
        // Seat 1: QS 3C -> queen-high flush Q-9-7-4-2
        Deal(holeCards0, holeCards1, 1, Card(SPADES, 12), Card(CLUBS, 3));

        // Board: 2S 4S 7S 9S KD
        ulong[] handValues = game.GetHandValues(playerState, holeCards0, holeCards1,
            Card(SPADES, 2), Card(SPADES, 4), Card(SPADES, 7), Card(SPADES, 9), Card(DIAMONDS, 13));
        int[] ranks = game.RankPlayers(handValues);

        Assert.IsTrue(handValues[0] > handValues[1], "Ace-high flush beats Queen-high flush");
        Assert.AreEqual(0, ranks[0]);
        Assert.AreEqual(1, ranks[1]);
    }

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

        int[] holeCards0 = new int[10];
        int[] holeCards1 = new int[10];
        // Seat 0: KS 3S -> two pair A & 8 with a king kicker
        Deal(holeCards0, holeCards1, 0, Card(SPADES, 13), Card(SPADES, 3));
        // Seat 1: QS 3H -> two pair A & 8 with a queen kicker
        Deal(holeCards0, holeCards1, 1, Card(SPADES, 12), Card(HEARTS, 3));

        // Board: AC AD 8C 8D 2H
        ulong[] handValues = game.GetHandValues(playerState, holeCards0, holeCards1,
            Card(CLUBS, 14), Card(DIAMONDS, 14), Card(CLUBS, 8), Card(DIAMONDS, 8), Card(HEARTS, 2));
        int[] ranks = game.RankPlayers(handValues);

        Assert.IsTrue(handValues[0] > handValues[1], "Two Pair AA88 with King kicker beats Two Pair AA88 with Queen kicker");
        Assert.AreEqual(0, ranks[0]);
        Assert.AreEqual(1, ranks[1]);
    }

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

        int[] holeCards0 = new int[10];
        int[] holeCards1 = new int[10];
        // Seat 0: AC JS -> pair of kings with A-J-9 kickers
        Deal(holeCards0, holeCards1, 0, Card(CLUBS, 14), Card(SPADES, 11));
        // Seat 1: AH 10S -> pair of kings with A-10-9 kickers
        Deal(holeCards0, holeCards1, 1, Card(HEARTS, 14), Card(SPADES, 10));

        // Board: KC KD 9H 4S 2D
        ulong[] handValues = game.GetHandValues(playerState, holeCards0, holeCards1,
            Card(CLUBS, 13), Card(DIAMONDS, 13), Card(HEARTS, 9), Card(SPADES, 4), Card(DIAMONDS, 2));
        int[] ranks = game.RankPlayers(handValues);

        Assert.IsTrue(handValues[0] > handValues[1], "Pair of Kings with A-J kicker beats Pair of Kings with A-10 kicker");
        Assert.AreEqual(0, ranks[0]);
        Assert.AreEqual(1, ranks[1]);
    }

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

        int[] holeCards0 = new int[10];
        int[] holeCards1 = new int[10];
        // Seat 0: AC KS -> trips 7s with A-K kickers
        Deal(holeCards0, holeCards1, 0, Card(CLUBS, 14), Card(SPADES, 13));
        // Seat 1: AD QS -> trips 7s with A-Q kickers
        Deal(holeCards0, holeCards1, 1, Card(DIAMONDS, 14), Card(SPADES, 12));

        // Board: 7C 7D 7H 2S 3H
        ulong[] handValues = game.GetHandValues(playerState, holeCards0, holeCards1,
            Card(CLUBS, 7), Card(DIAMONDS, 7), Card(HEARTS, 7), Card(SPADES, 2), Card(HEARTS, 3));
        int[] ranks = game.RankPlayers(handValues);

        Assert.IsTrue(handValues[0] > handValues[1], "Trips 7s with A-K kickers beats Trips 7s with A-Q kickers");
        Assert.AreEqual(0, ranks[0]);
        Assert.AreEqual(1, ranks[1]);
    }

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

        int[] holeCards0 = new int[10];
        int[] holeCards1 = new int[10];
        // Seat 0: JC 9D -> high card A-K-Q-J-9
        Deal(holeCards0, holeCards1, 0, Card(CLUBS, 11), Card(DIAMONDS, 9));
        // Seat 1: JS 8D -> high card A-K-Q-J-8
        Deal(holeCards0, holeCards1, 1, Card(SPADES, 11), Card(DIAMONDS, 8));

        // Board: AC KD QH 2S 3H
        ulong[] handValues = game.GetHandValues(playerState, holeCards0, holeCards1,
            Card(CLUBS, 14), Card(DIAMONDS, 13), Card(HEARTS, 12), Card(SPADES, 2), Card(HEARTS, 3));
        int[] ranks = game.RankPlayers(handValues);

        Assert.IsTrue(handValues[0] > handValues[1], "High card A-K-Q-J-9 beats A-K-Q-J-8");
        Assert.AreEqual(0, ranks[0]);
        Assert.AreEqual(1, ranks[1]);
    }

    [Test]
    public void TestSetupBlinds_BigBlindStackShortAllIn()
    {
        int[] playerState = new int[10];
        int[] stacks = new int[10] { 1000, 1000, 30, 0, 0, 0, 0, 0, 0, 0 }; // Seat 2 (BB) has only 30 chips
        int[] roundContribution = new int[10];
        bool[] playerStackedAndReady = new bool[10] { true, true, true, false, false, false, false, false, false, false };

        var setupBlindsMethod = typeof(HoldemGame).GetMethod("SetupBlinds", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
        Assert.IsNotNull(setupBlindsMethod);

        object[] args = new object[] {
            // Last dealer seat, not the button for this hand: the button advances to the next
            // ready seat, so passing 2 here puts the button on 0, SB on 1 and BB on 2.
            2,
            100, // BB amount 100
            playerState,
            stacks,
            roundContribution,
            playerStackedAndReady
        };

        setupBlindsMethod.Invoke(game, args);

        // Big blind is 100, but Seat 2 only had 30 chips -> contribution capped to 30, stack drops to 0
        Assert.AreEqual(50, roundContribution[1], "Seat 1 is the small blind and posts the full 50");
        Assert.AreEqual(30, roundContribution[2], "Big blind contribution should be capped to available stack (30)");
        Assert.AreEqual(0, stacks[2], "Big blind stack should be reduced to 0 (all-in)");
    }

    [Test]
    public void TestBettingRound_AllInPlayersDoNotNeedToAct()
    {
        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, 0, 1000, 0, 0, 0, 0, 0, 0, 0 }; // Seat 1 is All-In (stack 0)
        int[] roundContribution = new int[10] { 100, 100, 50, 0, 0, 0, 0, 0, 0, 0 };
        int[] potContribution = new int[10];

        // Seat 1 acts by calling/all-in (bet 0 since stack is 0)
        object[] result = game.CalculateGameTransition(
            10000, HoldemGame.PREFLOP, 1,
            100, 100, false,
            playerState, stacks, roundContribution, potContribution,
            10005, 16, 3, 100, 0, true,
            0, true, 0, 0
        );

        Assert.IsNotNull(result);
        int nextActor = (int)result[1];

        // Action should skip all-in player and move to Seat 2
        Assert.AreEqual(2, nextActor, "Action should move to Seat 2 (skipping all-in player)");
    }

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

        int[] holeCards0 = new int[10];
        int[] holeCards1 = new int[10];
        // Seat 0: 9C 2D -> 9-high straight 5-6-7-8-9
        Deal(holeCards0, holeCards1, 0, Card(CLUBS, 9), Card(DIAMONDS, 2));
        // Seat 1: 4C 3D -> 8-high straight 4-5-6-7-8
        Deal(holeCards0, holeCards1, 1, Card(CLUBS, 4), Card(DIAMONDS, 3));

        // Board: 5C 6D 7H 8S 2S
        ulong[] handValues = game.GetHandValues(playerState, holeCards0, holeCards1,
            Card(CLUBS, 5), Card(DIAMONDS, 6), Card(HEARTS, 7), Card(SPADES, 8), Card(SPADES, 2));
        int[] ranks = game.RankPlayers(handValues);

        Assert.IsTrue(handValues[0] > handValues[1], "9-high straight beats 8-high straight");
        Assert.AreEqual(0, ranks[0]);
        Assert.AreEqual(1, ranks[1]);
    }

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

        int[] holeCards0 = new int[10];
        int[] holeCards1 = new int[10];
        // Seat 0: 10H 3D -> trip 10s
        Deal(holeCards0, holeCards1, 0, Card(HEARTS, 10), Card(DIAMONDS, 3));
        // Seat 1: 6H KD -> two pair, 10s and 6s
        Deal(holeCards0, holeCards1, 1, Card(HEARTS, 6), Card(DIAMONDS, 13));

        // Board: 10C 10D 2H 4S 6C
        ulong[] handValues = game.GetHandValues(playerState, holeCards0, holeCards1,
            Card(CLUBS, 10), Card(DIAMONDS, 10), Card(HEARTS, 2), Card(SPADES, 4), Card(CLUBS, 6));
        int[] ranks = game.RankPlayers(handValues);

        Assert.IsTrue(handValues[0] > handValues[1], "Three of a kind beats Two Pair");
        Assert.AreEqual(0, ranks[0]);
        Assert.AreEqual(1, ranks[1]);
    }

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

        int[] holeCards0 = new int[10];
        int[] holeCards1 = new int[10];
        // Seat 0: 10D 6H -> two pair, 10s and 6s
        Deal(holeCards0, holeCards1, 0, Card(DIAMONDS, 10), Card(HEARTS, 6));
        // Seat 1: 10H AC -> one pair of 10s with an ace kicker
        Deal(holeCards0, holeCards1, 1, Card(HEARTS, 10), Card(CLUBS, 14));

        // Board: 10C 2H 4S 6C 9D
        ulong[] handValues = game.GetHandValues(playerState, holeCards0, holeCards1,
            Card(CLUBS, 10), Card(HEARTS, 2), Card(SPADES, 4), Card(CLUBS, 6), Card(DIAMONDS, 9));
        int[] ranks = game.RankPlayers(handValues);

        Assert.IsTrue(handValues[0] > handValues[1], "Two Pair beats One Pair");
        Assert.AreEqual(0, ranks[0]);
        Assert.AreEqual(1, ranks[1]);
    }

    [Test]
    public void TestDeck_52UniqueCards()
    {
        // The shuffle is the only deck source; a typo'd method name here used to make the
        // whole body a no-op, so assert the method exists rather than skipping.
        var shuffleDeckMethod = typeof(HoldemGame).GetMethod("ShuffleDeck", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
        Assert.IsNotNull(shuffleDeckMethod, "ShuffleDeck method should exist");

        int[] deck = (int[])shuffleDeckMethod.Invoke(game, null);
        Assert.AreEqual(52, deck.Length, "Deck must contain 52 cards");
        bool[] seen = new bool[52];
        for (int i = 0; i < 52; i++)
        {
            Assert.IsTrue(deck[i] >= 0 && deck[i] < 52, $"Card {deck[i]} must be between 0 and 51");
            Assert.IsFalse(seen[deck[i]], $"Card {deck[i]} must not be duplicated");
            seen[deck[i]] = true;
        }
    }

    [Test]
    public void TestDeck_ShuffleActuallyReorders()
    {
        var shuffleDeckMethod = typeof(HoldemGame).GetMethod("ShuffleDeck", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);

        // A correct shuffle leaving the deck in perfect order 5 times running is
        // vanishingly unlikely; an unshuffled deck fails every time.
        bool anyReordered = false;
        for (int attempt = 0; attempt < 5 && !anyReordered; attempt++)
        {
            int[] deck = (int[])shuffleDeckMethod.Invoke(game, null);
            for (int i = 0; i < 52; i++)
            {
                if (deck[i] != i) { anyReordered = true; break; }
            }
        }
        Assert.IsTrue(anyReordered, "ShuffleDeck should not hand back the deck in its original order");
    }

    // ---------------------------------------------------------------------
    // Bank flush / metrics regressions
    // ---------------------------------------------------------------------

    private static readonly System.Reflection.BindingFlags Priv =
        System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance;

    // Seats a player at seatIdx with a ready balance component holding `bank`, and returns it.
    private PlayerBalanceComponent SeatPlayerWithBank(int seatIdx, int bank)
    {
        var activePlayerIdField = typeof(HoldemPlayer).GetField("activePlayerId", Priv);
        var balanceField = typeof(HoldemPlayer).GetField("ActivePlayerBalanceComponent", Priv);
        var isReadyField = typeof(PlayerBalanceComponent).GetField("bIsReady", Priv);

        var player = game.players[seatIdx];
        // OwnerId() reports -2 with no VRChat player present, so this reads as seated.
        activePlayerIdField.SetValue(player, -2);
        player.playerReady = true;

        var balanceGo = new GameObject("Balance_" + seatIdx);
        balanceGo.transform.SetParent(gameGo.transform);
        var balance = balanceGo.AddComponent<PlayerBalanceComponent>();
        balance.CurrentSyncedBalance = bank;
        isReadyField.SetValue(balance, true);
        balanceField.SetValue(player, balance);

        return balance;
    }

    // Regression: preTransitionStacks is the baseline UpdatePlayerBalances subtracts from to
    // work out what to flush to the bank. It used to be refreshed only while stacks[i] > 0, so
    // a seat that busted to exactly 0 kept a stale baseline and had its entire lost stack
    // deducted from the bank again on every later state change. Only visible when the bank
    // still holds more than the table stack (bank > maxBuyIn), otherwise the clamp at 0 in
    // ModifyBalance hides it.
    [Test]
    public void TestBustedSeatIsNotChargedToTheBankTwice()
    {
        game.isTournamentActive = false;
        game.maxBuyIn = 10000;

        // Seat 0 bought in for maxBuyIn out of a 25000 bank and just lost the lot. The losing
        // hand already flushed -10000, so the bank sits at 15000 and the table stack at 0.
        var bustedBalance = SeatPlayerWithBank(0, 15000);
        // Seat 1 is untouched this tick and acts as a control.
        var idleBalance = SeatPlayerWithBank(1, 10000);

        var wasSeated = game.wasSeated; // public field; a NonPublic-only reflection lookup returns null
        var lastBankBalances = (int[])typeof(HoldemGame).GetField("lastBankBalances", Priv).GetValue(game);
        var preTransitionStacksField = typeof(HoldemGame).GetField("preTransitionStacks", Priv);
        var preTransitionStacks = (int[])preTransitionStacksField.GetValue(game);

        wasSeated[0] = true; lastBankBalances[0] = 15000;
        wasSeated[1] = true; lastBankBalances[1] = 10000;

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

        // The stale baseline left behind by the tick that busted seat 0.
        preTransitionStacks[0] = 10000;
        preTransitionStacks[1] = 10000;

        // Sit on the winner screen with the timeout already expired, so this Transition
        // produces a real state change (WINNER -> IDLE) and therefore runs the bank flush.
        game.tableState = HoldemGame.TABLE_WINNER;
        game.lastTransitionMillis = game.GetTimeMillis() - 20000;

        game.Transition();

        Assert.AreEqual(HoldemGame.TABLE_IDLE, game.tableState,
            "Winner timeout should have expired, so the flush path must have run");

        Assert.AreEqual(15000, bustedBalance.GetBalance(),
            "A seat already flushed down to a 0 stack must not be charged its lost stack again");
        Assert.AreEqual(10000, idleBalance.GetBalance(),
            "A seat whose stack did not move must not be charged anything");

        // The baseline has to come down to 0 as well, or the next state change re-charges.
        preTransitionStacks = (int[])preTransitionStacksField.GetValue(game);
        Assert.AreEqual(0, preTransitionStacks[0],
            "preTransitionStacks must track a busted stack down to 0, not hold the old value");
    }

    // Regression: UpdatePlayerMetrics ranked hands from preTransitionPlayerState, a snapshot
    // taken before this tick's action. A seat that folds on the action closing the river is
    // still live in that snapshot, so it got ranked into the pot here even though the real
    // award in CalculateTransition excluded it -- handing the folder's profit to them and
    // booking the actual winner a full loss.
    [Test]
    public void TestShowdownProfitIgnoresSeatThatFoldedToCloseTheRiver()
    {
        game.isTournamentActive = false;

        var winner = SeatPlayerWithBank(0, 10000);   // trip nines, actually wins
        var loser = SeatPlayerWithBank(1, 10000);    // pair of kings
        var folder = SeatPlayerWithBank(2, 10000);   // trip jacks, but folded

        // Board: 2c 7d 9h Jc 4s -- no straight or flush available.
        var flops = new string[] { "flop0", "flop1", "flop2", "turn", "river" };
        var cards = new int[]
        {
            Card(CLUBS, 2), Card(DIAMONDS, 7), Card(HEARTS, 9), Card(CLUBS, 11), Card(SPADES, 4)
        };
        for (int i = 0; i < flops.Length; i++)
        {
            typeof(HoldemGame).GetField(flops[i], Priv).SetValue(game, cards[i]);
        }

        Deal(game.holeCards0, game.holeCards1, 0, Card(CLUBS, 9), Card(DIAMONDS, 9));
        Deal(game.holeCards0, game.holeCards1, 1, Card(CLUBS, 13), Card(DIAMONDS, 13));
        Deal(game.holeCards0, game.holeCards1, 2, Card(DIAMONDS, 11), Card(HEARTS, 11));

        game.potContribution[0] = 1000;
        game.potContribution[1] = 1000;
        game.potContribution[2] = 1000;

        // Post-transition truth: seat 2 folded on the action that closed the river.
        game.playerState[0] = HoldemGame.PLAYER_COMMITED;
        game.playerState[1] = HoldemGame.PLAYER_COMMITED;
        game.playerState[2] = HoldemGame.PLAYER_DEAD;

        // Pre-transition snapshot still has seat 2 alive and acting. This is the input that
        // used to drive the ranking.
        var preState = (int[])typeof(HoldemGame).GetField("preTransitionPlayerState", Priv).GetValue(game);
        preState[0] = HoldemGame.PLAYER_COMMITED;
        preState[1] = HoldemGame.PLAYER_COMMITED;
        preState[2] = HoldemGame.PLAYER_ACTING;

        game.tableState = HoldemGame.TABLE_WINNER;
        typeof(HoldemGame).GetField("preTransitionTableState", Priv)
            .SetValue(game, HoldemGame.TABLE_PLAYING);
        game.wonByFold = false;
        game.dealerSeat = 0;
        game.winnerMask = 1 << 0;

        typeof(HoldemGame).GetMethod("UpdatePlayerMetrics", Priv).Invoke(game, null);

        // Seat 0 takes the 3000 pot having put in 1000. Seat 2's trip jacks never reach
        // showdown, so they simply lose what they had already committed.
        Assert.AreEqual(2000, winner.GetProfit(),
            "The seat that actually won the pot should be credited the full net win");
        Assert.AreEqual(-1000, loser.GetProfit(),
            "A seat that reached showdown and lost is out its contribution");
        Assert.AreEqual(-1000, folder.GetProfit(),
            "A seat that folded must lose its contribution, not be paid for a hand it folded");
    }
// Regression: UpdatePlayerBalances flushes stack deltas to the bank but was
    // not updating lastBankBalances. On the next Transition tick, the external
    // sync loop compared currentGlobalBalance against stale lastBankBalances,
    // recomputed a bogus externalDelta, and re-inflated the stack — causing the
    // winner to gain more chips than the blinds when everyone else folded.
    [Test]
    public void TestFoldWinBankFlushUpdatesLastBankBalances()
    {
        game.isTournamentActive = false;
        game.maxBuyIn = 10000;

        // Install VRChat runtime fakes so Networking.IsOwner returns true and
        // UpdatePlayerBalances / ModifyBalance actually execute in EditMode.
        var fake = new VrcRuntimeFake();
        fake.Install(1);
        try
        {

            // Three players: seat 0 won by fold after betting big.
            var winnerBal = SeatPlayerWithBank(0, 10000);
            var folder1Bal = SeatPlayerWithBank(1, 10000);
            var folder2Bal = SeatPlayerWithBank(2, 10000);

            // After blinds posted, seat 0 bet big, both opponents folded, pot awarded:
            //   stacks[0] = 10000 + 150 (blinds only) = 10150
            //   stacks[1] = 9950
            //   stacks[2] = 9900
            game.stacks[0] = 10150;
            game.stacks[1] = 9950;
            game.stacks[2] = 9900;

            var wasSeated = game.wasSeated; // public field; a NonPublic-only reflection lookup returns null
            var lastBankBalancesField = typeof(HoldemGame).GetField("lastBankBalances", Priv);
            var lastBankBalances = (int[])lastBankBalancesField.GetValue(game);
            var preTransitionStacksField = typeof(HoldemGame).GetField("preTransitionStacks", Priv);
            var preTransitionStacks = (int[])preTransitionStacksField.GetValue(game);

            // preTransitionStacks = stacks at the start of the tick that produced
            // the TABLE_WINNER state (before pot award).
            for (int i = 0; i < 3; i++)
            {
                wasSeated[i] = true;
                lastBankBalances[i] = 10000; // bank baseline from when they sat down
                preTransitionStacks[i] = 10000; // stack baseline from tick start
            }

            // Call UpdatePlayerBalances directly. With VrcRuntimeFake installed,
            // Networking.IsOwner returns true so the method body actually runs.
            var updateBalMethod = typeof(HoldemGame).GetMethod("UpdatePlayerBalances", Priv);
            Assert.IsNotNull(updateBalMethod, "UpdatePlayerBalances must exist");
            updateBalMethod.Invoke(game, null);

            // After the flush, bank balances must reflect the net changes
            Assert.AreEqual(10150, winnerBal.GetBalance(),
                "Winner's bank must be credited the net gain (+150)");
            Assert.AreEqual(9950, folder1Bal.GetBalance(),
                "Seat 1 lost only the small blind (-50)");
            Assert.AreEqual(9900, folder2Bal.GetBalance(),
                "Seat 2 lost only the big blind (-100)");

            // CRITICAL: lastBankBalances must now match the current bank balances.
            // If this fails, the external sync loop in the next Transition tick
            // sees a stale baseline and re-inflates or shrinks the stack.
            lastBankBalances = (int[])lastBankBalancesField.GetValue(game);
            Assert.AreEqual(10150, lastBankBalances[0],
                "lastBankBalances[0] must track the flushed bank, not hold the stale 10000");
            Assert.AreEqual(9950, lastBankBalances[1],
                "lastBankBalances[1] must track the flushed bank");
            Assert.AreEqual(9900, lastBankBalances[2],
                "lastBankBalances[2] must track the flushed bank");

            // Also verify CurrentSyncedBalance was eagerly set so that any
            // subsequent read of GetBalanceForSeat() or GetBalance() returns
            // the correct value, even before the network event round-trips
            // (ModifyBalance sends SendCustomNetworkEvent for non-owners).
            Assert.AreEqual(10150, winnerBal.CurrentSyncedBalance,
                "CurrentSyncedBalance must be updated eagerly so GetBalance() is correct");
            Assert.AreEqual(9950, folder1Bal.CurrentSyncedBalance);
            Assert.AreEqual(9900, folder2Bal.CurrentSyncedBalance);
        }
        finally
        {
            // Process-global VRC statics: leaking them fails every later test that expects no local player.
            fake.Uninstall();
        }
    }
}
