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

/// <summary>
/// Static (non-dynamic) chip presentation with a table-like fixture: several denominations and seats.
/// A recalculation always lands on the same total, so these tests assert chip composition and identity:
/// bets must pile up chip by chip, and the pot must grow by transfer.
/// </summary>
public class StaticChipTransferTests
{
    private const int FIVE = 0, TWENTY_FIVE = 1, HUNDRED = 2;
    private static readonly int[] Denominations = { 5, 25, 100 };

    private readonly List<GameObject> spawned = new List<GameObject>();
    private LocalObjectPool[] pools;
    private HoldemGame game;
    private HoldemPlayer[] players;

    [SetUp]
    public void SetUp()
    {
        pools = new LocalObjectPool[Denominations.Length];
        for (int d = 0; d < pools.Length; d++)
        {
            GameObject poolObject = Spawn("Pool" + Denominations[d]);
            pools[d] = poolObject.AddComponent<LocalObjectPool>();
            pools[d].denomination = Denominations[d];
            pools[d].Pool = new GameObject[40];
            for (int i = 0; i < pools[d].Pool.Length; i++)
            {
                GameObject chip = Spawn("Chip" + Denominations[d] + "_" + i);
                chip.transform.SetParent(poolObject.transform);
                Rigidbody body = chip.AddComponent<Rigidbody>();
                body.isKinematic = true;
                body.useGravity = false;
                chip.AddComponent<BoxCollider>().enabled = false;
                pools[d].Pool[i] = chip;
            }
            VrcRuntimeFake.InvokeNoArg(pools[d], "Start");
        }

        game = Spawn("Game").AddComponent<HoldemGame>();
        game.seats = 2;
        game.tableState = HoldemGame.TABLE_PLAYING;
        game.potPile = CreatePile("Pot");

        players = new HoldemPlayer[2];
        for (int i = 0; i < players.Length; i++)
        {
            players[i] = Spawn("Player" + i).AddComponent<HoldemPlayer>();
            players[i].game = game;
            players[i].seatIdx = i;
            players[i].stackPile = CreatePile("Stack" + i);
            players[i].roundContributionPile = CreatePile("Round" + i);
            players[i].playerPotPile = CreatePile("Winnings" + i);
        }
        game.players = players;
        game.SetAnimatedChipContainersEnabled(false);
    }

    [TearDown]
    public void TearDown()
    {
        for (int i = spawned.Count - 1; i >= 0; i--)
            if (spawned[i] != null) Object.DestroyImmediate(spawned[i]);
        spawned.Clear();
    }

    [Test]
    public void IncrementalCalls_KeepSmallChipsInsteadOfRecalculating()
    {
        players[0].stackPile.SetTotalChips(500);
        for (int contribution = 5; contribution <= 25; contribution += 5)
        {
            game.roundContribution[0] = contribution;
            Present(0);
        }

        // Recalculating 25 would give a single 25 chip.
        Assert.AreEqual(5, players[0].roundContributionPile.GetDisplayedDenominationCount(FIVE));
        Assert.AreEqual(0, players[0].roundContributionPile.GetDisplayedDenominationCount(TWENTY_FIVE));
        Assert.AreEqual(25, players[0].roundContributionPile.GetTotalDisplayedValue());
    }

    [Test]
    public void RoundClose_MovesChipsIntoPotWithoutChangingDenominations()
    {
        players[0].stackPile.SetTotalChips(500);
        for (int contribution = 5; contribution <= 25; contribution += 5)
        {
            game.roundContribution[0] = contribution;
            Present(0);
        }
        var roundChips = Children(players[0].roundContributionPile);

        game.potContribution[0] = 25;
        game.roundContribution[0] = 0;
        Present(25);

        Assert.AreEqual(5, game.potPile.GetDisplayedDenominationCount(FIVE), "A recalculated pot would be one 25 chip");
        Assert.AreEqual(0, game.potPile.GetDisplayedDenominationCount(TWENTY_FIVE));
        AssertChildrenAreFrom(game.potPile, roundChips);
        Assert.AreEqual(0, players[0].roundContributionPile.GetTotalDisplayedValue());
    }

    [Test]
    public void TwoRounds_PotKeepsEachRoundsComposition()
    {
        players[0].stackPile.SetTotalChips(500);
        BetInFives(0, 25);
        game.potContribution[0] = 25;
        game.roundContribution[0] = 0;
        Present(25);

        BetInFives(0, 25, 25);
        game.potContribution[0] = 50;
        game.roundContribution[0] = 0;
        Present(50);

        // A recalculated 50 would be two 25 chips.
        Assert.AreEqual(10, game.potPile.GetDisplayedDenominationCount(FIVE));
        Assert.AreEqual(0, game.potPile.GetDisplayedDenominationCount(TWENTY_FIVE));
    }

    [Test]
    public void TwoSeats_RoundCloseMovesBothRoundPilesIntoPot()
    {
        players[0].stackPile.SetTotalChips(500);
        players[1].stackPile.SetTotalChips(500);
        BetInFives(0, 25);
        BetInFives(1, 25);
        Assert.AreEqual(5, players[1].roundContributionPile.GetDisplayedDenominationCount(FIVE));

        game.potContribution[0] = 25;
        game.potContribution[1] = 25;
        game.roundContribution[0] = 0;
        game.roundContribution[1] = 0;
        Present(50);

        Assert.AreEqual(10, game.potPile.GetDisplayedDenominationCount(FIVE), "A recalculated 50 would be two 25 chips");
        Assert.AreEqual(0, players[0].roundContributionPile.GetTotalDisplayedValue());
        Assert.AreEqual(0, players[1].roundContributionPile.GetTotalDisplayedValue());
    }

    [Test]
    public void ActionArrivingWithClose_TransfersTheStacksOwnChip()
    {
        players[0].stackPile.SetTotalChips(200);
        var stackChips = Children(players[0].stackPile);

        // Call and round close land in one update, so the round pile never showed the chips.
        game.potContribution[0] = 100;
        game.roundContribution[0] = 0;
        Present(100);

        Assert.AreEqual(100, game.potPile.GetTotalDisplayedValue());
        Assert.AreEqual(1, game.potPile.transform.childCount);
        Assert.IsTrue(stackChips.Contains(game.potPile.transform.GetChild(0)),
            "The pot chip must be the stack's own chip, not a respawned one");
        Assert.AreEqual(100, players[0].stackPile.GetTotalDisplayedValue());
    }

    [Test]
    public void ActionArrivingWithClose_SpawnsFromPoolWhenStackLacksTheDenomination()
    {
        players[0].stackPile.SetTotalChips(200);

        game.potContribution[0] = 30;
        game.roundContribution[0] = 0;
        Present(30);

        Assert.AreEqual(30, game.potPile.GetTotalDisplayedValue());
        Assert.AreEqual(1, game.potPile.GetDisplayedDenominationCount(TWENTY_FIVE));
        Assert.AreEqual(1, game.potPile.GetDisplayedDenominationCount(FIVE));
        Assert.AreEqual(2, players[0].stackPile.GetDisplayedDenominationCount(HUNDRED), "Stack's own chips stay put");
    }

    [Test]
    public void PresentingTheSameStateTwice_DoesNotTouchChips()
    {
        players[0].stackPile.SetTotalChips(500);
        game.roundContribution[0] = 30;
        Present(0);
        var before = Children(players[0].roundContributionPile);
        int availableBefore = TotalAvailable();

        Present(0);

        Assert.AreEqual(availableBefore, TotalAvailable());
        Assert.IsTrue(before.SetEquals(Children(players[0].roundContributionPile)));
    }

    [Test]
    public void NewHand_ReturnsEveryChipToThePools()
    {
        players[0].stackPile.SetTotalChips(500);
        game.roundContribution[0] = 30;
        Present(0);
        game.potContribution[0] = 30;
        game.roundContribution[0] = 0;
        Present(30);
        game.roundContribution[1] = 25;
        Present(30);

        game.potContribution[0] = 0;
        game.roundContribution[1] = 0;
        Present(0);

        Assert.AreEqual(0, game.potPile.GetTotalDisplayedValue());
        Assert.AreEqual(0, players[1].roundContributionPile.GetTotalDisplayedValue());
        Assert.AreEqual(TotalCapacity() - HeldOutsidePools(), TotalAvailable());
    }

    [Test]
    public void ChipCount_IsConservedAcrossABettingSequence()
    {
        players[0].stackPile.SetTotalChips(500);
        players[1].stackPile.SetTotalChips(500);
        int total = TotalCapacity();

        game.roundContribution[0] = 5;
        game.roundContribution[1] = 10;
        Present(0);
        game.roundContribution[0] = 30;
        Present(0);
        game.potContribution[0] = 30;
        game.potContribution[1] = 30;
        game.roundContribution[0] = 0;
        game.roundContribution[1] = 0;
        Present(60);

        Assert.AreEqual(total, TotalAvailable() + HeldOutsidePools(), "No chip may be lost or duplicated");
    }

    [Test]
    public void DynamicToStatic_FreezesPotAndWinningsChipsToo()
    {
        game.SetAnimatedChipContainersEnabled(true);
        game.potPile.SpawnDynamicChips(30, game.potPile.transform.position);
        players[0].playerPotPile.SpawnDynamicChips(25, players[0].playerPotPile.transform.position);

        game.SetAnimatedChipContainersEnabled(false);

        foreach (PokerChipPile pile in new[] { game.potPile, players[0].playerPotPile })
        {
            for (int i = 0; i < pile.transform.childCount; i++)
            {
                Transform chip = pile.transform.GetChild(i);
                Assert.IsTrue(chip.GetComponent<Rigidbody>().isKinematic, pile.name + " chip left physical");
                Assert.IsFalse(chip.GetComponent<Collider>().enabled);
            }
        }
    }

    [Test]
    public void Raise_PlaysFallInAnimationForAddedChipsOnly()
    {
        players[0].stackPile.SetTotalChips(500);
        BetInFives(0, 10);
        PokerChipPile round = players[0].roundContributionPile;
        InvokeSettle(round);
        Assert.AreEqual(0, AnimCount(round));

        game.roundContribution[0] = 25;
        Present(0);

        Assert.AreEqual(3, AnimCount(round), "Only the three newly added chips animate");
        Assert.IsTrue(round.enabled, "The pile must update to play the animation");
        Assert.AreEqual(25, round.GetTotalDisplayedValue());
    }

    [Test]
    public void RoundClose_PlaysFallInAnimationForChipsArrivingInPot()
    {
        players[0].stackPile.SetTotalChips(500);
        BetInFives(0, 10);
        game.potContribution[0] = 10;
        game.roundContribution[0] = 0;
        Present(10);
        PokerChipPile pot = game.potPile;
        InvokeSettle(pot);

        BetInFives(0, 15, 10);
        game.potContribution[0] = 25;
        game.roundContribution[0] = 0;
        Present(25);

        Assert.AreEqual(3, AnimCount(pot), "Only chips that just arrived in the pot animate, not the existing two");
        Assert.AreEqual(5, pot.GetDisplayedDenominationCount(FIVE));
        Assert.IsTrue(pot.enabled);
    }

    [Test]
    public void AnimatedChips_LandOnTheirStaticSlots()
    {
        players[0].stackPile.SetTotalChips(500);
        game.roundContribution[0] = 10;
        Present(0);
        PokerChipPile round = players[0].roundContributionPile;
        var finalPositions = new Dictionary<Transform, Vector3>();
        InvokeSettle(round);
        for (int i = 0; i < round.transform.childCount; i++)
            finalPositions[round.transform.GetChild(i)] = round.transform.GetChild(i).localPosition;

        game.roundContribution[0] = 25;
        Present(0);
        InvokeSettle(round);

        foreach (var pair in finalPositions)
            Assert.AreEqual(pair.Value, pair.Key.localPosition, "Existing chips must not move");
        for (int i = 0; i < round.transform.childCount; i++)
            Assert.IsTrue(round.transform.GetChild(i).GetComponent<Rigidbody>().isKinematic);
        Assert.AreEqual(0, AnimCount(round));
    }

    [Test]
    public void Winner_ReceivesThePotsChipsWithoutRecalculating()
    {
        PotOfFives(50);
        var potChips = Children(game.potPile);
        game.tableState = HoldemGame.TABLE_WINNER;
        game.seatWinnings[0] = 50;

        game._DistributeStaticPotToWinners();

        Assert.AreEqual(10, players[0].playerPotPile.GetDisplayedDenominationCount(FIVE), "A recalculated 50 would be two 25 chips");
        Assert.AreEqual(0, players[0].playerPotPile.GetDisplayedDenominationCount(TWENTY_FIVE));
        AssertChildrenAreFrom(players[0].playerPotPile, potChips);
        Assert.AreEqual(0, game.potPile.GetTotalDisplayedValue());
    }

    [Test]
    public void SplitPot_EachWinnerGetsTheirShareOfTheSameChips()
    {
        PotOfFives(50);
        var potChips = Children(game.potPile);
        game.tableState = HoldemGame.TABLE_WINNER;
        game.seatWinnings[0] = 25;
        game.seatWinnings[1] = 25;

        game._DistributeStaticPotToWinners();

        Assert.AreEqual(5, players[0].playerPotPile.GetDisplayedDenominationCount(FIVE));
        Assert.AreEqual(5, players[1].playerPotPile.GetDisplayedDenominationCount(FIVE));
        var received = Children(players[0].playerPotPile);
        received.UnionWith(Children(players[1].playerPotPile));
        Assert.IsTrue(potChips.SetEquals(received));
        Assert.AreEqual(0, game.potPile.GetTotalDisplayedValue());
    }

    [Test]
    public void Winner_LeavesLosersPilesEmpty()
    {
        PotOfFives(25);
        game.tableState = HoldemGame.TABLE_WINNER;
        game.seatWinnings[1] = 25;

        game._DistributeStaticPotToWinners();

        Assert.AreEqual(0, players[0].playerPotPile.GetTotalDisplayedValue());
        Assert.AreEqual(25, players[1].playerPotPile.GetTotalDisplayedValue());
    }

    [Test]
    public void Winner_AlsoTakesRoundChipsThatNeverClosed()
    {
        PotOfFives(25);
        BetInFives(1, 25, 25);
        game.tableState = HoldemGame.TABLE_WINNER;
        game.seatWinnings[0] = 50;

        game._DistributeStaticPotToWinners();

        Assert.AreEqual(10, players[0].playerPotPile.GetDisplayedDenominationCount(FIVE));
        Assert.AreEqual(0, players[1].roundContributionPile.GetTotalDisplayedValue());
        Assert.AreEqual(0, game.potPile.GetTotalDisplayedValue());
    }

    [Test]
    public void RepresentingTheWinnerScreen_KeepsTheSameWinningsChips()
    {
        PotOfFives(50);
        game.tableState = HoldemGame.TABLE_WINNER;
        game.seatWinnings[0] = 50;
        game._DistributeStaticPotToWinners();
        var before = Children(players[0].playerPotPile);

        game._DistributeStaticPotToWinners();

        Assert.IsTrue(before.SetEquals(Children(players[0].playerPotPile)));
        Assert.AreEqual(10, players[0].playerPotPile.GetDisplayedDenominationCount(FIVE));
    }

    [Test]
    public void Winner_TeleportsChipsWithoutAnimationAndConservesChips()
    {
        PotOfFives(50);
        int total = TotalCapacity();
        game.tableState = HoldemGame.TABLE_WINNER;
        game.seatWinnings[0] = 50;

        game._DistributeStaticPotToWinners();

        Assert.AreEqual(0, AnimCount(players[0].playerPotPile));
        Assert.AreEqual(10, players[0].playerPotPile.GetDisplayedDenominationCount(FIVE));
        Assert.AreEqual(total, TotalAvailable() + HeldOutsidePools());
        for (int i = 0; i < players[0].playerPotPile.transform.childCount; i++)
            Assert.IsTrue(players[0].playerPotPile.transform.GetChild(i).GetComponent<Rigidbody>().isKinematic);
    }

    // ---- stack pile vs. HoldemPlayer refresh order ----
    // HoldemPlayer.RefreshSeatUi draws stackPile with SetTotalChips(stacks[seat]) on the same epoch change as the
    // presentation, in no fixed order. Either order must end with the stack showing the synced stack.

    [Test]
    public void PlayerRefreshedFirst_BetDoesNotDeductTheStackTwice()
    {
        SyncStack(0, 500);
        game.stacks[0] = 470;
        PlayerRefresh(0);

        game.roundContribution[0] = 30;
        Present(0);

        Assert.AreEqual(470, players[0].stackPile.GetTotalDisplayedValue(), "The bet was already taken off the stack");
        Assert.AreEqual(30, players[0].roundContributionPile.GetTotalDisplayedValue());
    }

    [Test]
    public void GameRefreshedFirst_BetMovesTheStacksOwnChips()
    {
        SyncStack(0, 500);
        var stackChips = Children(players[0].stackPile);
        game.stacks[0] = 400;

        game.roundContribution[0] = 100;
        Present(0);

        Assert.AreEqual(400, players[0].stackPile.GetTotalDisplayedValue());
        Assert.AreEqual(1, players[0].roundContributionPile.transform.childCount);
        Assert.IsTrue(stackChips.Contains(players[0].roundContributionPile.transform.GetChild(0)),
            "The bet chip must be the stack's own chip, not a respawned one");
    }

    [Test]
    public void GameRefreshedFirst_FollowingPlayerRefreshKeepsTheStackChips()
    {
        SyncStack(0, 500);
        game.stacks[0] = 400;
        game.roundContribution[0] = 100;
        Present(0);
        var stackChips = Children(players[0].stackPile);
        int availableBefore = TotalAvailable();

        PlayerRefresh(0);

        Assert.IsTrue(stackChips.SetEquals(Children(players[0].stackPile)), "Stack must not be redrawn");
        Assert.AreEqual(availableBefore, TotalAvailable());
    }

    [Test]
    public void CallPresentedBeforeCommit_IsNotTakenFromTheStackAgain()
    {
        // Call-only / physical betting: HoldemPlayer shows stack - call while the seat is still deciding.
        game.stacks[0] = 500;
        players[0].stackPile.SetTotalChips(500 - 50);

        // The call commits: the synced stack now matches what was already on display.
        game.stacks[0] = 450;
        game.roundContribution[0] = 50;
        Present(0);

        Assert.AreEqual(450, players[0].stackPile.GetTotalDisplayedValue());
        Assert.AreEqual(50, players[0].roundContributionPile.GetTotalDisplayedValue());
    }

    [Test]
    public void PlayerRefreshedFirst_ClosingCallDoesNotDeductTheStackTwice()
    {
        SyncStack(0, 500);
        game.stacks[0] = 400;
        PlayerRefresh(0);

        // Call and round close arrive together.
        game.potContribution[0] = 100;
        game.roundContribution[0] = 0;
        Present(100);

        Assert.AreEqual(400, players[0].stackPile.GetTotalDisplayedValue());
        Assert.AreEqual(100, game.potPile.GetTotalDisplayedValue());
        Assert.AreEqual(0, players[0].roundContributionPile.GetTotalDisplayedValue());
    }

    [Test]
    public void StackShowingPartOfTheBet_GivesOnlyThatPart()
    {
        SyncStack(0, 400);
        players[0].stackPile.SetTotalChips(450);
        game.stacks[0] = 400;

        game.roundContribution[0] = 100;
        Present(0);

        Assert.AreEqual(400, players[0].stackPile.GetTotalDisplayedValue());
        Assert.AreEqual(100, players[0].roundContributionPile.GetTotalDisplayedValue());
    }

    [Test]
    public void MissingStackPile_BetIsStillPresented()
    {
        players[0].stackPile = null;

        BetInFives(0, 15);

        Assert.AreEqual(3, players[0].roundContributionPile.GetDisplayedDenominationCount(FIVE),
            "Spawned chips must still pile up chip by chip");
    }

    [TestCase(true)]
    [TestCase(false)]
    public void FullHand_StackAlwaysMatchesTheSyncedStack(bool playerFirst)
    {
        int total = TotalCapacity();
        SyncStack(0, 500);
        SyncStack(1, 500);

        // Preflop: blinds, a raise and a call.
        Step(playerFirst, 0, 5, 0);
        Step(playerFirst, 1, 10, 0);
        Step(playerFirst, 0, 30, 0);
        // The closing call arrives with the round close.
        game.stacks[1] = 470;
        game.roundContribution[0] = 0;
        game.roundContribution[1] = 0;
        game.potContribution[0] = 30;
        game.potContribution[1] = 30;
        StepPresent(playerFirst, 60);
        // Flop: a bet and a call, closed separately.
        Step(playerFirst, 0, 25, 60);
        Step(playerFirst, 1, 25, 60);
        game.roundContribution[0] = 0;
        game.roundContribution[1] = 0;
        game.potContribution[0] = 55;
        game.potContribution[1] = 55;
        StepPresent(playerFirst, 110);

        for (int seat = 0; seat < 2; seat++)
        {
            Assert.AreEqual(game.stacks[seat], players[seat].stackPile.GetTotalDisplayedValue(), "Seat " + seat);
            Assert.AreEqual(0, players[seat].roundContributionPile.GetTotalDisplayedValue());
        }
        Assert.AreEqual(110, game.potPile.GetTotalDisplayedValue());
        Assert.AreEqual(total, TotalAvailable() + HeldOutsidePools(), "No chip may be lost or duplicated");

        game.tableState = HoldemGame.TABLE_WINNER;
        game.seatWinnings[1] = 110;
        game._DistributeStaticPotToWinners();
        Assert.AreEqual(110, players[1].playerPotPile.GetTotalDisplayedValue());
        Assert.AreEqual(0, game.potPile.GetTotalDisplayedValue());
        Assert.AreEqual(total, TotalAvailable() + HeldOutsidePools());
    }

    // ---- first presentation without a matching snapshot (late join / sync after mode init) ----

    [Test]
    public void LateJoin_FirstUpdateBetweenStreets_DoesNotDrainTheStacks()
    {
        // The mode was initialised before sync, so the presented snapshot is all zeros.
        game.stacks[0] = 400;
        game.stacks[1] = 300;
        PlayerRefresh(0);
        PlayerRefresh(1);
        game.potContribution[0] = 100;
        game.potContribution[1] = 100;

        Present(200);

        Assert.AreEqual(400, players[0].stackPile.GetTotalDisplayedValue());
        Assert.AreEqual(300, players[1].stackPile.GetTotalDisplayedValue());
        Assert.AreEqual(200, game.potPile.GetTotalDisplayedValue());
        Assert.AreEqual(0, players[0].roundContributionPile.GetTotalDisplayedValue());
    }

    [Test]
    public void LateJoin_ThenNextRoundClose_CollectsOnlyTheNewRound()
    {
        game.stacks[0] = 400;
        game.stacks[1] = 300;
        PlayerRefresh(0);
        PlayerRefresh(1);
        game.potContribution[0] = 100;
        game.potContribution[1] = 100;
        Present(200);
        InvokeSettle(game.potPile);

        Step(false, 0, 50, 200);
        Step(false, 1, 50, 200);
        game.roundContribution[0] = 0;
        game.roundContribution[1] = 0;
        game.potContribution[0] = 150;
        game.potContribution[1] = 150;
        StepPresent(false, 300);

        Assert.AreEqual(350, players[0].stackPile.GetTotalDisplayedValue());
        Assert.AreEqual(250, players[1].stackPile.GetTotalDisplayedValue());
        Assert.AreEqual(300, game.potPile.GetTotalDisplayedValue());
    }

    [Test]
    public void LateJoin_MidRound_ShowsRoundPilesWithoutDrainingTheStacks()
    {
        game.stacks[0] = 400;
        PlayerRefresh(0);
        game.potContribution[0] = 100;
        game.roundContribution[0] = 40;

        Present(100);

        Assert.AreEqual(400, players[0].stackPile.GetTotalDisplayedValue());
        Assert.AreEqual(40, players[0].roundContributionPile.GetTotalDisplayedValue());
        Assert.AreEqual(100, game.potPile.GetTotalDisplayedValue());
    }

    [Test]
    public void SwitchToStaticMidHand_NextRoundCloseDoesNotDrainTheStacks()
    {
        game.SetAnimatedChipContainersEnabled(true);
        game.stacks[0] = 400;
        game.potContribution[0] = 100;
        game.roundContribution[0] = 50;
        game.SetAnimatedChipContainersEnabled(false);
        PlayerRefresh(0);
        Present(100);

        // The round's 50 was already taken off the synced stack when it was bet.
        game.roundContribution[0] = 0;
        game.potContribution[0] = 150;
        PlayerRefresh(0);
        Present(150);

        Assert.AreEqual(400, players[0].stackPile.GetTotalDisplayedValue());
        Assert.AreEqual(150, game.potPile.GetTotalDisplayedValue());
        Assert.AreEqual(0, players[0].roundContributionPile.GetTotalDisplayedValue());
    }

    // ---- AddValueFromPool ----

    [Test]
    public void AddValueFromPool_KeepsExistingChipsAndAddsLargestFirst()
    {
        PokerChipPile pile = players[0].roundContributionPile;
        pile.SetTotalChips(10);
        var existing = Children(pile);

        int added = pile.AddValueFromPool(130);

        Assert.AreEqual(130, added);
        Assert.AreEqual(140, pile.GetTotalDisplayedValue());
        Assert.AreEqual(1, pile.GetDisplayedDenominationCount(HUNDRED));
        Assert.AreEqual(1, pile.GetDisplayedDenominationCount(TWENTY_FIVE));
        Assert.AreEqual(3, pile.GetDisplayedDenominationCount(FIVE));
        foreach (Transform chip in existing) Assert.AreEqual(pile.transform, chip.parent);
    }

    [Test]
    public void AddValueFromPool_NeverExceedsTheTarget()
    {
        PokerChipPile pile = players[0].roundContributionPile;

        int added = pile.AddValueFromPool(7);

        Assert.AreEqual(5, added, "The 2 remainder is below the smallest denomination");
        Assert.AreEqual(5, pile.GetTotalDisplayedValue());
    }

    [Test]
    public void AddValueFromPool_FallsBackToSmallerChipsWhenAPoolIsEmpty()
    {
        PokerChipPile pile = players[0].roundContributionPile;
        while (pools[HUNDRED].availableCount > 0) pools[HUNDRED].TryToSpawn();

        int added = pile.AddValueFromPool(100);

        Assert.AreEqual(100, added);
        Assert.AreEqual(0, pile.GetDisplayedDenominationCount(HUNDRED));
        Assert.AreEqual(4, pile.GetDisplayedDenominationCount(TWENTY_FIVE));
    }

    // ---- helpers ----

    // The synced stack and HoldemPlayer's drawing of it.
    private void SyncStack(int seat, int stack)
    {
        game.stacks[seat] = stack;
        PlayerRefresh(seat);
    }

    // What HoldemPlayer.RefreshSeatUi does to the stack pile for a seat that is not deciding.
    private void PlayerRefresh(int seat)
    {
        players[seat].stackPile.SetTotalChips(game.stacks[seat]);
    }

    // One synced bet: the stack drops by the added amount, then both Updates run in the given order.
    private void Step(bool playerFirst, int seat, int roundContribution, int potTotal)
    {
        game.stacks[seat] -= roundContribution - game.roundContribution[seat];
        game.roundContribution[seat] = roundContribution;
        StepPresent(playerFirst, potTotal);
    }

    private void StepPresent(bool playerFirst, int potTotal)
    {
        if (playerFirst) { PlayerRefresh(0); PlayerRefresh(1); }
        Present(potTotal);
        if (!playerFirst) { PlayerRefresh(0); PlayerRefresh(1); }
    }

    // Builds a pot made of 5 chips (what incremental calls produce) worth `total`, funded by seat 0.
    private void PotOfFives(int total)
    {
        players[0].stackPile.SetTotalChips(500);
        BetInFives(0, total);
        game.potContribution[0] = total;
        game.roundContribution[0] = 0;
        Present(total);
        Assert.AreEqual(total / 5, game.potPile.GetDisplayedDenominationCount(FIVE), "Sanity: pot built from small chips");
    }

    private static int AnimCount(PokerChipPile pile)
    {
        return (int)VrcRuntimeFake.GetPrivate(pile, "animCount");
    }

    private static void InvokeSettle(PokerChipPile pile)
    {
        typeof(PokerChipPile).GetMethod("SettleAnimation",
            System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance).Invoke(pile, null);
    }

    private void BetInFives(int seat, int total, int potTotal = 0)
    {
        for (int contribution = 5; contribution <= total; contribution += 5)
        {
            game.roundContribution[seat] = contribution;
            Present(potTotal);
        }
    }

    private void Present(int potTotal)
    {
        HoldemPresentation.PresentPlayingChipsStatic(game, potTotal);
    }

    private static HashSet<Transform> Children(PokerChipPile pile)
    {
        var set = new HashSet<Transform>();
        for (int i = 0; i < pile.transform.childCount; i++) set.Add(pile.transform.GetChild(i));
        return set;
    }

    private static void AssertChildrenAreFrom(PokerChipPile pile, HashSet<Transform> expected)
    {
        Assert.AreEqual(expected.Count, pile.transform.childCount);
        for (int i = 0; i < pile.transform.childCount; i++)
            Assert.IsTrue(expected.Contains(pile.transform.GetChild(i)), "Chip was respawned instead of transferred");
    }

    private int TotalAvailable()
    {
        int total = 0;
        for (int d = 0; d < pools.Length; d++) total += pools[d].availableCount;
        return total;
    }

    private int TotalCapacity()
    {
        int total = 0;
        for (int d = 0; d < pools.Length; d++) total += pools[d].Pool.Length;
        return total;
    }

    private int HeldOutsidePools()
    {
        int total = 0;
        foreach (PokerChipPile pile in Object.FindObjectsOfType<PokerChipPile>())
            for (int d = 0; d < Denominations.Length; d++) total += pile.GetDisplayedDenominationCount(d);
        return total;
    }

    private PokerChipPile CreatePile(string name)
    {
        GameObject pileObject = Spawn(name);
        PokerChipPile pile = pileObject.AddComponent<PokerChipPile>();
        pile.denominationValues = (int[])Denominations.Clone();
        pile.denominationPools = (LocalObjectPool[])pools.Clone();
        pile.gatherTransportDuration = 0f;
        VrcRuntimeFake.InvokeNoArg(pile, "Start");
        return pile;
    }

    private GameObject Spawn(string name)
    {
        GameObject value = new GameObject(name);
        spawned.Add(value);
        return value;
    }
}
