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

public class PokerChipPileTests
{
    private GameObject chipPileGo;
    private PokerChipPile chipPile;

    // Pools live outside the pile so PlacedChips only sees chips.
    private readonly List<GameObject> poolObjects = new List<GameObject>();

    [SetUp]
    public void SetUp()
    {
        chipPileGo = new GameObject("ChipPileTest");
        chipPile = chipPileGo.AddComponent<PokerChipPile>();
        chipPile.denominationValues = new int[] { 10, 50, 100, 500, 1000 };
    }

    [TearDown]
    public void TearDown()
    {
        Object.DestroyImmediate(chipPileGo);
        foreach (var go in poolObjects) Object.DestroyImmediate(go);
        poolObjects.Clear();
    }

    [Test]
    public void TestCalculateDenominationCounts_GreedyAllocation()
    {
        var calcMethod = typeof(PokerChipPile).GetMethod("CalculateDenominationCounts", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
        Assert.IsNotNull(calcMethod, "CalculateDenominationCounts method should exist");

        // 2660 chips -> 2x1000 + 1x500 + 1x100 + 1x50 + 1x10
        int[] counts = (int[])calcMethod.Invoke(chipPile, new object[] { 2660 });

        Assert.IsNotNull(counts);
        Assert.AreEqual(5, counts.Length);
        Assert.AreEqual(2, counts[4], "1000 denomination count should be 2");
        Assert.AreEqual(1, counts[3], "500 denomination count should be 1");
        Assert.AreEqual(1, counts[2], "100 denomination count should be 1");
        Assert.AreEqual(1, counts[1], "50 denomination count should be 1");
        Assert.AreEqual(1, counts[0], "10 denomination count should be 1");
    }

    [Test]
    public void TestCalculateDenominationCounts_ZeroValue()
    {
        var calcMethod = typeof(PokerChipPile).GetMethod("CalculateDenominationCounts", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
        int[] counts = (int[])calcMethod.Invoke(chipPile, new object[] { 0 });

        for (int i = 0; i < counts.Length; i++)
        {
            Assert.AreEqual(0, counts[i], $"Count for denomination index {i} should be 0 when value is 0");
        }
    }

    private int[] Counts(int totalValue)
    {
        var calcMethod = typeof(PokerChipPile).GetMethod("CalculateDenominationCounts", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
        return (int[])calcMethod.Invoke(chipPile, new object[] { totalValue });
    }

    private int Total(int[] counts)
    {
        int total = 0;
        for (int i = 0; i < counts.Length; i++)
        {
            total += counts[i] * chipPile.denominationValues[i];
        }
        return total;
    }

    [Test]
    public void TestCalculateDenominationCounts_BelowSmallestDenomination()
    {
        // Nothing in the pile can represent 7, so the display shows an empty stack rather
        // than rounding up to a chip the player does not have.
        int[] counts = Counts(7);

        for (int i = 0; i < counts.Length; i++)
        {
            Assert.AreEqual(0, counts[i], $"Denomination index {i} should not be used for a value below the smallest chip");
        }
    }

    [Test]
    public void TestCalculateDenominationCounts_DropsUnrepresentableRemainder()
    {
        // 2665 cannot be made from 10/50/100/500/1000; the odd 5 has nowhere to go.
        int[] counts = Counts(2665);

        Assert.AreEqual(2660, Total(counts), "The pile shows the largest representable amount at or below the total");
    }

    [Test]
    public void TestCalculateDenominationCounts_HandlesUnsortedDenominations()
    {
        // The greedy pass sorts denominations itself, so inspector order must not matter.
        chipPile.denominationValues = new int[] { 1000, 10, 500, 50, 100 };

        int[] counts = Counts(2660);

        Assert.AreEqual(2, counts[0], "1000 chips");
        Assert.AreEqual(1, counts[1], "10 chips");
        Assert.AreEqual(1, counts[2], "500 chips");
        Assert.AreEqual(1, counts[3], "50 chips");
        Assert.AreEqual(1, counts[4], "100 chips");
        Assert.AreEqual(2660, Total(counts));
    }

    [Test]
    public void TestCalculateDenominationCounts_LargeStackUsesTopDenomination()
    {
        int[] counts = Counts(1000000);

        Assert.AreEqual(1000, counts[4], "A million in chips is 1000 of the top denomination");
        Assert.AreEqual(1000000, Total(counts));
        for (int i = 0; i < 4; i++)
        {
            Assert.AreEqual(0, counts[i], "Nothing should be left over for the smaller denominations");
        }
    }

    /* -----------------------------------------------------------
     * Animation tracking tests
     *
     * The pile decides what animates by diffing against the previous
     * render, walking denominations from highest value to lowest:
     *   - above the first changed denomination -> nothing animates
     *   - at it                                -> only the added chips
     *   - below it                             -> every chip cascades
     * These drive that through the public SetTotalChips API and assert
     * on the queued animation itself, not just the bookkeeping.
     * ----------------------------------------------------------- */

    /// <summary>
    /// Wires the pile the way the prefab does — a pool per denomination, each holding
    /// `chipsPerPool` chips named Chip&lt;value&gt;_&lt;n&gt; — and runs Start(), which builds the hex
    /// grid, the animation buffers and prevCounts. Without this the pile is inert.
    /// </summary>
    private void BuildPileWithPools(int chipsPerPool)
    {
        int[] values = chipPile.denominationValues;
        var pools = new LocalObjectPool[values.Length];

        for (int d = 0; d < values.Length; d++)
        {
            var poolGo = new GameObject($"Pool_{values[d]}");
            poolObjects.Add(poolGo);

            var pool = poolGo.AddComponent<LocalObjectPool>();
            pool.denomination = values[d];
            pool.Pool = new GameObject[chipsPerPool];
            for (int c = 0; c < chipsPerPool; c++)
            {
                var chip = new GameObject($"Chip{values[d]}_{c}");
                chip.transform.SetParent(poolGo.transform);
                pool.Pool[c] = chip;
            }

            VrcRuntimeFake.InvokeNoArg(pool, "Start"); // InitializePool
            pools[d] = pool;
        }

        chipPile.denominationPools = pools;
        VrcRuntimeFake.InvokeNoArg(chipPile, "Start");
    }

    // The chips currently placed on the pile, by name.
    private List<string> PlacedChips()
    {
        var names = new List<string>();
        foreach (Transform child in chipPileGo.transform) names.Add(child.name);
        return names;
    }

    // The chips queued to fall in on the last render, by name.
    private List<string> AnimatingChips()
    {
        int animCount = (int)VrcRuntimeFake.GetPrivate(chipPile, "animCount");
        var targets = (Transform[])VrcRuntimeFake.GetPrivate(chipPile, "animTargets");

        var names = new List<string>();
        for (int i = 0; i < animCount; i++) names.Add(targets[i].name);
        return names;
    }

    /// <summary>
    /// HoldemGame opens the pot and round piles in its own Start, which can run before theirs.
    /// Unity never calls Start on a disabled behaviour, so a pile that disabled itself here
    /// stayed uninitialised and never showed chips.
    /// </summary>
    [Test]
    public void EntryPointsBeforeStart_KeepPileEnabledSoUnityStillStartsIt()
    {
        chipPile.OpenContainer();
        chipPile.BeginAnimatedGather(true);
        chipPile.FinishAnimatedGather();
        chipPile.SetTotalChips(0);
        chipPile.SetSelectableStackMode(false);
        Assert.IsTrue(chipPile.enabled, "A pile disabled before its Start is never started by Unity");

        BuildPileWithPools(4);
        chipPile.SetTotalChips(1150);

        CollectionAssert.AreEquivalent(
            new[] { "Chip1000_0", "Chip100_0", "Chip50_0" }, PlacedChips(),
            "Once started, the pile must show chips");
    }

    /// <summary>
    /// First render: nothing was on the table, so every chip is new and falls in.
    /// </summary>
    [Test]
    public void TestAnimation_FirstRenderAllChipsAnimate()
    {
        BuildPileWithPools(4);

        chipPile.SetTotalChips(1150); // 1x1000 + 1x100 + 1x50

        CollectionAssert.AreEquivalent(
            new[] { "Chip1000_0", "Chip100_0", "Chip50_0" }, PlacedChips(),
            "The greedy split of 1150 should be on the table");
        CollectionAssert.AreEquivalent(PlacedChips(), AnimatingChips(),
            "On the first render every chip is new, so all of them animate");
    }

    /// <summary>
    /// Re-rendering the same counts places the chips again but animates nothing —
    /// otherwise an unrelated state change would make a settled pile jump.
    /// </summary>
    [Test]
    public void TestAnimation_NoAnimationWhenCountsUnchanged()
    {
        BuildPileWithPools(4);
        chipPile.SetTotalChips(1150);

        // SetTotalChips short-circuits on an unchanged total, so the only way to reach a
        // redundant render is the private path a caller hits when the pile is re-displayed.
        var updateMethod = typeof(PokerChipPile).GetMethod("UpdateChipDisplay",
            System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
        updateMethod.Invoke(chipPile, new object[] { new int[] { 0, 1, 1, 0, 1 } });

        Assert.AreEqual(3, PlacedChips().Count, "The same chips are still placed");
        CollectionAssert.IsEmpty(AnimatingChips(), "Nothing changed, so nothing should fall in");
    }

    /// <summary>
    /// Adding a high-value chip animates only that new chip, but everything below it
    /// cascades because the new chip pushes those stacks along.
    /// </summary>
    [Test]
    public void TestAnimation_HighDenomChangeCascadesToLowerDenoms()
    {
        BuildPileWithPools(4);
        chipPile.SetTotalChips(1150); // 1x1000 + 1x100 + 1x50

        chipPile.SetTotalChips(2150); // adds a second 1000

        CollectionAssert.AreEquivalent(
            new[] { "Chip1000_0", "Chip1000_1", "Chip100_0", "Chip50_0" }, PlacedChips());
        CollectionAssert.AreEquivalent(
            new[] { "Chip1000_1", "Chip100_0", "Chip50_0" }, AnimatingChips(),
            "Only the added 1000 falls in; the 100 and 50 below it cascade");
        CollectionAssert.DoesNotContain(AnimatingChips(), "Chip1000_0",
            "The 1000 that was already sitting there must not move");
    }

    /// <summary>
    /// Adding the smallest chip leaves every larger denomination untouched — nothing
    /// above the change is disturbed.
    /// </summary>
    [Test]
    public void TestAnimation_LowDenomChangeDoesNotAffectHigher()
    {
        BuildPileWithPools(4);
        chipPile.SetTotalChips(2150); // 2x1000 + 1x100 + 1x50

        chipPile.SetTotalChips(2160); // adds a single 10

        CollectionAssert.AreEquivalent(
            new[] { "Chip10_0", "Chip1000_0", "Chip1000_1", "Chip100_0", "Chip50_0" }, PlacedChips());
        CollectionAssert.AreEquivalent(new[] { "Chip10_0" }, AnimatingChips(),
            "Only the new 10 animates; every larger denomination stays put");
    }

    /// <summary>
    /// When a count drops, the removed chip goes back to its pool silently and the
    /// survivors below the change cascade into the gap it left.
    /// </summary>
    [Test]
    public void TestAnimation_CountDecreaseCascadesToRemaining()
    {
        BuildPileWithPools(4);
        chipPile.SetTotalChips(2160); // 2x1000 + 1x100 + 1x50 + 1x10

        chipPile.SetTotalChips(1160); // one 1000 is taken away

        CollectionAssert.AreEquivalent(
            new[] { "Chip10_0", "Chip1000_0", "Chip100_0", "Chip50_0" }, PlacedChips(),
            "The removed 1000 should be back in its pool");
        CollectionAssert.AreEquivalent(
            new[] { "Chip10_0", "Chip100_0", "Chip50_0" }, AnimatingChips(),
            "The surviving chips below the change cascade; the remaining 1000 does not animate");
    }

    /// <summary>
    /// A pool that runs dry stops that denomination rather than throwing, so a pile
    /// worth more than the prefab has chips for still renders what it can.
    /// </summary>
    [Test]
    public void TestAnimation_ExhaustedPoolStopsAtTheChipsItHas()
    {
        BuildPileWithPools(1); // one chip per denomination

        chipPile.SetTotalChips(2000); // asks for 2x1000

        CollectionAssert.AreEquivalent(new[] { "Chip1000_0" }, PlacedChips(),
            "Only the chip the pool actually holds is placed");
        CollectionAssert.AreEquivalent(new[] { "Chip1000_0" }, AnimatingChips());
    }

    // Moves every queued chip to its landing spot, as if the fall finished long ago.
    private void SettleAnimation(PokerChipPile pile)
    {
        VrcRuntimeFake.SetPrivate(pile, "animStartTime", -1000f);
        VrcRuntimeFake.InvokeNoArg(pile, "Update");
    }

    /// <summary>Once every chip has landed the pile stops touching them each frame.</summary>
    [Test]
    public void TestAnimation_StopsOnceChipsLand()
    {
        BuildPileWithPools(4);
        chipPile.SetTotalChips(1150);
        var targets = (Vector3[])VrcRuntimeFake.GetPrivate(chipPile, "animTargetPositions");
        var landing = new Dictionary<string, Vector3>();
        var queued = (Transform[])VrcRuntimeFake.GetPrivate(chipPile, "animTargets");
        for (int i = 0; i < 3; i++) landing[queued[i].name] = targets[i];

        SettleAnimation(chipPile);

        Assert.AreEqual(0, (int)VrcRuntimeFake.GetPrivate(chipPile, "animCount"),
            "A settled pile should not keep animating");
        foreach (Transform child in chipPileGo.transform)
            Assert.AreEqual(landing[child.name], child.localPosition, child.name + " should rest where it landed");
    }

    /// <summary>A settled pile switches its Update off and new falling chips switch it back on.</summary>
    [Test]
    public void TestAnimation_UpdateOnlyRunsWhileAnimating()
    {
        BuildPileWithPools(4);
        Assert.IsFalse(chipPile.enabled, "An idle pile should not tick every frame");

        chipPile.SetTotalChips(1150);
        Assert.IsTrue(chipPile.enabled, "Falling chips need Update");

        SettleAnimation(chipPile);
        Assert.IsFalse(chipPile.enabled, "A settled pile should not tick every frame");

        chipPile.SetTotalChips(2150);
        Assert.IsTrue(chipPile.enabled,
            "A direct value update must restart animation even when the pile was idle");
    }

    /// <summary>The value readout only turns toward the player while the pile has chips.</summary>
    [Test]
    public void TestText_LookAtOnlyRunsWithChips()
    {
        var readout = new GameObject("Readout");
        poolObjects.Add(readout);
        chipPile.text = readout.AddComponent<TMPro.TextMeshPro>();
        chipPile.lookAtPlayer = readout.AddComponent<LookAtPlayerYawOnly>();
        BuildPileWithPools(4);

        Assert.IsFalse(chipPile.lookAtPlayer.enabled, "An empty pile has nothing to show");

        chipPile.SetTotalChips(100);
        Assert.IsTrue(chipPile.lookAtPlayer.enabled);

        chipPile.SetTotalChips(0);
        Assert.IsFalse(chipPile.lookAtPlayer.enabled);
    }

    /// <summary>Children that are not chips (the readout canvas) are never treated as chips.</summary>
    [Test]
    public void TestReturn_LeavesNonChipChildrenAlone()
    {
        BuildPileWithPools(4);
        var canvas = new GameObject("Canvas");
        canvas.transform.SetParent(chipPileGo.transform);

        var logs = new List<string>();
        Application.LogCallback capture = (message, stack, type) => logs.Add(message);
        Application.logMessageReceived += capture;
        try
        {
            chipPile.SetTotalChips(1150);
            chipPile.SetTotalChips(0);
        }
        finally
        {
            Application.logMessageReceived -= capture;
        }

        Assert.AreSame(chipPileGo.transform, canvas.transform.parent, "The canvas must stay on the pile");
        CollectionAssert.IsEmpty(logs.FindAll(m => m.Contains("could not be returned")),
            "Non-chip children should not produce pool warnings");
    }

    /// <summary>Adding a low chip leaves the chips above it completely untouched.</summary>
    [Test]
    public void TestUpdate_KeepsChipsThatDidNotChange()
    {
        BuildPileWithPools(4);
        chipPile.SetTotalChips(2150); // 2x1000 + 1x100 + 1x50
        SettleAnimation(chipPile);
        foreach (Transform child in chipPileGo.transform) child.hasChanged = false;

        chipPile.SetTotalChips(2160); // adds a 10 at the end of the layout

        foreach (Transform child in chipPileGo.transform)
        {
            if (child.name == "Chip10_0") continue;
            Assert.IsFalse(child.hasChanged, child.name + " did not change and should not be re-placed");
        }
    }

    /// <summary>Clearing a pile hands every chip back to its own pool, ready to spawn again.</summary>
    [Test]
    public void TestReturn_ChipsGoBackToTheirPool()
    {
        BuildPileWithPools(4);
        chipPile.SetTotalChips(2160);

        chipPile.SetTotalChips(0);

        CollectionAssert.IsEmpty(PlacedChips());
        foreach (var pool in chipPile.denominationPools)
        {
            foreach (var chip in pool.Pool)
            {
                Assert.AreSame(pool.transform, chip.transform.parent, chip.name + " should be back under its pool");
                Assert.IsFalse(chip.activeSelf, chip.name + " should be hidden in the pool");
            }
        }

        chipPile.SetTotalChips(2160);
        CollectionAssert.AreEquivalent(
            new[] { "Chip10_0", "Chip1000_0", "Chip1000_1", "Chip100_0", "Chip50_0" }, PlacedChips(),
            "Returned chips are reusable");
    }

    /// <summary>Two piles drawing from the same pools keep their own chips.</summary>
    [Test]
    public void TestReturn_SharedPoolsKeepOtherPilesChips()
    {
        BuildPileWithPools(4);
        var otherGo = new GameObject("OtherPile");
        poolObjects.Add(otherGo);
        var other = otherGo.AddComponent<PokerChipPile>();
        other.denominationValues = chipPile.denominationValues;
        other.denominationPools = chipPile.denominationPools;
        VrcRuntimeFake.InvokeNoArg(other, "Start");

        chipPile.SetTotalChips(1000);
        other.SetTotalChips(1000);
        chipPile.SetTotalChips(0);

        Assert.AreEqual(1, otherGo.transform.childCount, "The other pile keeps its 1000");
        Assert.AreEqual("Chip1000_1", otherGo.transform.GetChild(0).name);
        Assert.IsTrue(otherGo.transform.GetChild(0).gameObject.activeSelf);
    }

    /// <summary>After any sequence of changes the chips sit exactly where a fresh render puts them.</summary>
    [Test]
    public void TestUpdate_LayoutMatchesFreshRender()
    {
        BuildPileWithPools(8);
        foreach (int total in new[] { 2160, 5270, 1115, 7060, 3050 })
        {
            chipPile.SetTotalChips(total);
            SettleAnimation(chipPile);
        }

        var freshGo = new GameObject("FreshPile");
        poolObjects.Add(freshGo);
        var fresh = freshGo.AddComponent<PokerChipPile>();
        fresh.denominationValues = chipPile.denominationValues;
        var freshPools = new LocalObjectPool[chipPile.denominationValues.Length];
        for (int d = 0; d < freshPools.Length; d++)
        {
            var poolGo = new GameObject($"FreshPool_{d}");
            poolObjects.Add(poolGo);
            freshPools[d] = poolGo.AddComponent<LocalObjectPool>();
            freshPools[d].Pool = new GameObject[8];
            for (int c = 0; c < 8; c++)
            {
                var chip = new GameObject($"Chip{chipPile.denominationValues[d]}_{c}");
                chip.transform.SetParent(poolGo.transform);
                freshPools[d].Pool[c] = chip;
            }
            VrcRuntimeFake.InvokeNoArg(freshPools[d], "Start");
        }
        fresh.denominationPools = freshPools;
        VrcRuntimeFake.InvokeNoArg(fresh, "Start");
        fresh.SetTotalChips(3050);
        SettleAnimation(fresh);

        CollectionAssert.AreEquivalent(Layout(freshGo.transform), Layout(chipPileGo.transform));
    }

    /// <summary>A negative total (stack - bet while synced values disagree) must not break the pile.</summary>
    [Test]
    public void TestNegativeTotal_PileRecovers()
    {
        BuildPileWithPools(4);
        var otherGo = new GameObject("OtherPile");
        poolObjects.Add(otherGo);
        var other = otherGo.AddComponent<PokerChipPile>();
        other.denominationValues = chipPile.denominationValues;
        other.denominationPools = chipPile.denominationPools;
        VrcRuntimeFake.InvokeNoArg(other, "Start");
        other.SetTotalChips(1160);

        chipPile.SetTotalChips(2160);
        chipPile.SetTotalChips(-40);
        CollectionAssert.IsEmpty(PlacedChips());

        chipPile.SetTotalChips(2160);
        CollectionAssert.AreEquivalent(
            new[] { "Chip10_1", "Chip1000_1", "Chip1000_2", "Chip100_1", "Chip50_1" }, PlacedChips());
        Assert.AreEqual(4, otherGo.transform.childCount, "The other pile's chips must stay put");
    }

    // Each chip as "denomination@position/rotation", independent of which pooled object it is.
    private static List<string> Layout(Transform pile)
    {
        var entries = new List<string>();
        foreach (Transform child in pile)
        {
            string denomination = child.name.Substring(0, child.name.IndexOf('_'));
            entries.Add(denomination + "@" + child.localPosition.ToString("F5") + "/" + child.localRotation.eulerAngles.ToString("F3"));
        }
        return entries;
    }


    private int[] SelectableCounts(int totalValue)
    {
        var method = typeof(PokerChipPile).GetMethod("CalculateSelectableDenominationCounts",
            System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
        int previousMaxActive = chipPile.maxActiveDenominations;
        chipPile.maxActiveDenominations = 0;
        int[] counts = (int[])method.Invoke(chipPile, new object[] { totalValue });
        chipPile.maxActiveDenominations = previousMaxActive;
        return counts;
    }

    [Test]
    public void SelectableCounts_SeedsEveryAffordableDenominationBeforeGreedyRemainder()
    {
        chipPile.denominationValues = new[] { 5, 25, 100, 500, 2500 };
        CollectionAssert.AreEqual(new[] { 10, 10, 12, 1, 0 }, SelectableCounts(2000));
        CollectionAssert.AreEqual(new[] { 10, 9, 0, 0, 0 }, SelectableCounts(275));
    }

    [Test]
    public void SelectableCounts_HandleUnsortedAndNonPositiveDenominationsWithoutOverAllocation()
    {
        chipPile.denominationValues = new[] { 100, 0, 5, -1, 25 };
        int[] counts = SelectableCounts(275);

        Assert.AreEqual(0, counts[1]);
        Assert.AreEqual(0, counts[3]);
        Assert.LessOrEqual(Total(counts), 275);
        Assert.AreEqual(275, Total(counts));
    }

    [Test]
    public void SelectableLayout_UsesDenominationAndDisplayOffsets()
    {
        chipPile.denominationValues = new[] { 5, 25, 100, 500, 2500 };
        chipPile.denominationOffsets = new[]
        {
            new Vector3(-0.2f, 0f, 0f), new Vector3(-0.1f, 0f, 0f), Vector3.zero,
            new Vector3(0.1f, 0f, 0f), new Vector3(0.2f, 0f, 0f)
        };
        chipPile.selectableLayoutOffset = Vector3.zero; // the immersive shift has its own tests
        chipPile.supportsSelectableStackMode = true;
        BuildPileWithPools(20);
        chipPile.SetSelectableStackMode(true);
        chipPile.SetDisplayLocalOffset(new Vector3(0f, 0.01f, 0.03f));
        chipPile.SetTotalChips(275);

        Assert.AreEqual(10, chipPile.GetDisplayedDenominationCount(0));
        Assert.AreEqual(9, chipPile.GetDisplayedDenominationCount(1));
        Assert.AreEqual(chipPile.transform.TransformPoint(new Vector3(-0.1f, 0.01f, 0.03f)),
            chipPile.GetDenominationBaseWorldPosition(0));
        Assert.AreEqual(chipPile.GetDenominationBaseWorldPosition(0).y
            + 10 * chipPile.chipHeight * Mathf.Abs(chipPile.transform.lossyScale.y),
            chipPile.GetDenominationTopWorldY(0), 0.00001f);
    }

    [Test]
    public void DisplayedCount_ReportsActualSpawnedCountForActiveDenominationsWhenPoolIsExhausted()
    {
        chipPile.denominationValues = new[] { 5, 25, 100, 500, 2500 };
        chipPile.supportsSelectableStackMode = true;
        BuildPileWithPools(3);
        chipPile.SetSelectableStackMode(true);
        chipPile.SetTotalChips(2000);

        Assert.AreEqual(0, chipPile.GetDisplayedDenominationCount(0), "The 5 chip denomination is inactive at 2000");
        Assert.AreEqual(3, chipPile.GetDisplayedDenominationCount(1));
        Assert.AreEqual(3, chipPile.GetDisplayedDenominationCount(2));
        Assert.AreEqual(1, chipPile.GetDisplayedDenominationCount(3));
        Assert.AreEqual(0, chipPile.GetDisplayedDenominationCount(-1));
        Assert.AreEqual(0, chipPile.GetDenominationValue(99));
    }


    [Test]
    public void SelectableMode_IsIgnoredByPilesWithoutTheCapability()
    {
        BuildPileWithPools(20);
        chipPile.SetSelectableStackMode(true);
        Assert.IsFalse((bool)VrcRuntimeFake.GetPrivate(chipPile, "selectableStackMode"));
    }

    [Test]
    public void SelectableLayout_EleventhChipStartsANewTenChipStack()
    {
        chipPile.denominationValues = new[] { 5 };
        chipPile.denominationOffsets = new[] { Vector3.zero };
        chipPile.supportsSelectableStackMode = true;
        chipPile.stackHeight = 10;
        BuildPileWithPools(30);
        chipPile.SetSelectableStackMode(true);
        chipPile.SetTotalChips(125);
        SettleAnimation(chipPile);

        Transform first = chipPileGo.transform.Find("Chip5_0");
        Transform tenth = chipPileGo.transform.Find("Chip5_9");
        Transform eleventh = chipPileGo.transform.Find("Chip5_10");
        Assert.AreEqual(first.localPosition.y + 9f * chipPile.chipHeight, tenth.localPosition.y, 0.00001f);
        Assert.AreEqual(first.localPosition.y, eleventh.localPosition.y, 0.00001f);
        Vector2 firstHorizontal = new Vector2(first.localPosition.x, first.localPosition.z);
        Vector2 eleventhHorizontal = new Vector2(eleventh.localPosition.x, eleventh.localPosition.z);
        Assert.Greater((firstHorizontal - eleventhHorizontal).sqrMagnitude, 0.0001f,
            "Chip 11 must start a neighboring stack rather than increasing stack height");
    }

    [Test]
    public void ColumnQueries_MatchTenChipLaneGeometry()
    {
        chipPile.denominationValues = new[] { 5 };
        chipPile.denominationOffsets = new[] { new Vector3(0.1f, 0f, -0.02f) };
        chipPile.supportsSelectableStackMode = true;
        chipPile.stackHeight = 10;
        chipPile.positionJitter = 0.02f;
        BuildPileWithPools(30);
        chipPile.SetSelectableStackMode(true);
        chipPile.SetTotalChips(125);
        SettleAnimation(chipPile);

        Assert.AreEqual(3, chipPile.GetDenominationColumnCount(0));
        Assert.AreEqual(10, chipPile.GetDenominationColumnChipCount(0, 0));
        Assert.AreEqual(5, chipPile.GetDenominationColumnChipCount(0, 2));
        Assert.AreEqual(chipPile.GetDenominationColumnWorldPosition(0, 1),
            chipPileGo.transform.Find("Chip5_10").position);
        Assert.AreEqual(chipPile.GetDenominationColumnWorldPosition(0, 0).y + 10 * chipPile.chipHeight,
            chipPile.GetDenominationColumnTopWorldY(0, 0), 0.00001f);
    }

    [Test]
    public void ExactColumnTransfer_PreservesObjectsAndPoolSlotsAndReturnsExactlyOnce()
    {
        chipPile.denominationValues = new[] { 5 };
        chipPile.denominationOffsets = new[] { Vector3.zero };
        chipPile.supportsSelectableStackMode = true;
        chipPile.stackHeight = 10;
        BuildPileWithPools(30);
        chipPile.SetSelectableStackMode(true);
        chipPile.SetTotalChips(125);
        SettleAnimation(chipPile);

        GameObject destinationGo = new GameObject("RaisePileTest");
        poolObjects.Add(destinationGo);
        PokerChipPile destination = destinationGo.AddComponent<PokerChipPile>();
        destination.denominationValues = new[] { 5 };
        destination.denominationPools = chipPile.denominationPools;
        destination.stackHeight = 10;
        VrcRuntimeFake.InvokeNoArg(destination, "Start");

        GameObject selectedA = chipPileGo.transform.Find("Chip5_7").gameObject;
        GameObject selectedB = chipPileGo.transform.Find("Chip5_8").gameObject;
        GameObject selectedC = chipPileGo.transform.Find("Chip5_9").gameObject;
        int spawnedBefore = chipPile.denominationPools[0].spawnedCount;

        Assert.AreEqual(3, chipPile.TransferColumnTopTo(destination, 0, 0, 3));
        Assert.AreEqual(22, chipPile.GetDisplayedDenominationCount(0));
        Assert.AreEqual(3, destination.GetDisplayedDenominationCount(0));
        Assert.AreSame(destinationGo.transform, selectedA.transform.parent);
        Assert.AreSame(destinationGo.transform, selectedB.transform.parent);
        Assert.AreSame(destinationGo.transform, selectedC.transform.parent);
        Assert.AreEqual(spawnedBefore, chipPile.denominationPools[0].spawnedCount);

        Assert.AreEqual(3, destination.TransferAllTo(chipPile));
        Assert.AreEqual(25, chipPile.GetDisplayedDenominationCount(0));
        Assert.AreEqual(0, destination.GetDisplayedDenominationCount(0));
        Assert.AreEqual(0, destination.TransferAllTo(chipPile), "A repeated return must not duplicate chips");
        Assert.AreEqual(spawnedBefore, chipPile.denominationPools[0].spawnedCount);
    }

public void AnimatedTransfer_EnablesOnlyMovingChipPhysics()
    {
        chipPile.denominationValues = new[] { 5 };
        BuildPileWithPools(3);
        chipPile.SetTotalChips(15);
        SettleAnimation(chipPile);
        foreach (Transform child in chipPileGo.transform)
        {
            child.gameObject.AddComponent<Rigidbody>().isKinematic = true;
            child.gameObject.AddComponent<BoxCollider>().enabled = false;
        }

        GameObject destinationGo = new GameObject("AnimatedDestination");
        poolObjects.Add(destinationGo);
        PokerChipPile destination = destinationGo.AddComponent<PokerChipPile>();
        destination.denominationValues = new[] { 5 };
        destination.denominationPools = chipPile.denominationPools;
        VrcRuntimeFake.InvokeNoArg(destination, "Start");

        Assert.AreEqual(3, chipPile.TransferAllAnimatedTo(destination));
        foreach (Transform child in destinationGo.transform)
        {
            Assert.IsFalse(child.GetComponent<Rigidbody>().isKinematic);
            Assert.IsTrue(child.GetComponent<Collider>().enabled);
        }
    }

public void EndAnimatedContraction_LeavesChipsDynamic()
    {
        chipPile.denominationValues = new[] { 5 };
        BuildPileWithPools(3);
        chipPile.SetTotalChips(15);
        SettleAnimation(chipPile);
        foreach (Transform child in chipPileGo.transform)
        {
            child.gameObject.AddComponent<Rigidbody>().isKinematic = true;
            child.gameObject.AddComponent<BoxCollider>().enabled = false;
        }

        chipPile.MakeDisplayedChipsDynamic();
        chipPile.StartAnimatedGather();
        chipPile.EndAnimatedContraction();
        foreach (Transform child in chipPileGo.transform)
        {
            Assert.IsFalse(child.GetComponent<Rigidbody>().isKinematic);
            Assert.IsTrue(child.GetComponent<Collider>().enabled);
        }
    }

public void MakeDisplayedChipsDynamic_WakesPlacedChips()
    {
        chipPile.denominationValues = new[] { 5 };
        BuildPileWithPools(3);
        chipPile.SetTotalChips(15);
        SettleAnimation(chipPile);
        foreach (Transform child in chipPileGo.transform)
        {
            child.gameObject.AddComponent<Rigidbody>().isKinematic = true;
            child.gameObject.AddComponent<BoxCollider>().enabled = false;
        }

        Assert.AreEqual(3, chipPile.MakeDisplayedChipsDynamic());
        foreach (Transform child in chipPileGo.transform)
        {
            Assert.IsFalse(child.GetComponent<Rigidbody>().isKinematic);
            Assert.IsTrue(child.GetComponent<Collider>().enabled);
        }
    }

[Test]
    public void ApproximateWinnerSplit_PreservesEveryPhysicalChip()
    {
        chipPile.denominationValues = new[] { 5 };
        BuildPileWithPools(10);
        chipPile.SetTotalChips(25);
        SettleAnimation(chipPile);
        foreach (Transform child in chipPileGo.transform)
        {
            child.gameObject.AddComponent<Rigidbody>().isKinematic = true;
            child.gameObject.AddComponent<BoxCollider>().enabled = false;
        }
        chipPile.MakeDisplayedChipsDynamic();
        chipPile.FinishAnimatedGather();

        GameObject firstGo = new GameObject("FirstWinner");
        GameObject lastGo = new GameObject("LastWinner");
        poolObjects.Add(firstGo);
        poolObjects.Add(lastGo);
        PokerChipPile first = firstGo.AddComponent<PokerChipPile>();
        PokerChipPile last = lastGo.AddComponent<PokerChipPile>();
        first.denominationValues = new[] { 5 };
        last.denominationValues = new[] { 5 };
        first.denominationPools = chipPile.denominationPools;
        last.denominationPools = chipPile.denominationPools;
        VrcRuntimeFake.InvokeNoArg(first, "Start");
        VrcRuntimeFake.InvokeNoArg(last, "Start");

        Assert.AreEqual(15, chipPile.TransferApproximateValueAnimatedTo(first, 12, false));
        Assert.AreEqual(10, chipPile.TransferApproximateValueAnimatedTo(last, 13, true));
        Assert.AreEqual(0, chipPile.GetTotalDisplayedValue());
        Assert.AreEqual(15, first.GetTotalDisplayedValue());
        Assert.AreEqual(10, last.GetTotalDisplayedValue());
        Assert.AreEqual(5, firstGo.transform.childCount + lastGo.transform.childCount);
        foreach (Transform child in firstGo.transform)
            Assert.IsFalse(child.GetComponent<Rigidbody>().isKinematic);
        foreach (Transform child in lastGo.transform)
            Assert.IsFalse(child.GetComponent<Rigidbody>().isKinematic);
    }


    [Test]
    public void ActiveDenominationFilter_MirrorsBettingUiSelectionLogic()
    {
        chipPile.denominationValues = new[] { 5, 25, 100, 500, 2500 };
        chipPile.supportsSelectableStackMode = true;
        chipPile.maxActiveDenominations = 3;

        var pos0 = new GameObject("ActivePos0");
        var pos1 = new GameObject("ActivePos1");
        var pos2 = new GameObject("ActivePos2");
        pos0.transform.SetParent(chipPileGo.transform);
        pos1.transform.SetParent(chipPileGo.transform);
        pos2.transform.SetParent(chipPileGo.transform);
        pos0.transform.localPosition = new Vector3(-0.06f, 0f, 0f);
        pos1.transform.localPosition = Vector3.zero;
        pos2.transform.localPosition = new Vector3(0.06f, 0f, 0f);
        chipPile.activeDenominationPositions = new Transform[] { pos0.transform, pos1.transform, pos2.transform };

        BuildPileWithPools(30);
        chipPile.SetSelectableStackMode(true);

        chipPile.SetTotalChips(2000);
        Assert.IsTrue(chipPile.IsDenominationActive(1), "25 must be active for 2000 chips");
        Assert.IsTrue(chipPile.IsDenominationActive(2), "100 must be active for 2000 chips");
        Assert.IsTrue(chipPile.IsDenominationActive(3), "500 must be active for 2000 chips");
        Assert.IsFalse(chipPile.IsDenominationActive(0), "5 must be inactive for 2000 chips (not relevant)");
        Assert.IsFalse(chipPile.IsDenominationActive(4), "2500 must be inactive for 2000 chips (too large)");

        chipPile.SetTotalChips(275);
        Assert.IsTrue(chipPile.IsDenominationActive(0), "5 must be active for 275 chips");
        Assert.IsTrue(chipPile.IsDenominationActive(1), "25 must be active for 275 chips");
        Assert.IsTrue(chipPile.IsDenominationActive(2), "100 must be active for 275 chips");
        Assert.IsFalse(chipPile.IsDenominationActive(3), "500 must be inactive for 275 chips");

        chipPile.SetTotalChips(15);
        Assert.IsTrue(chipPile.IsDenominationActive(0), "5 must be active for 15 chips");
        Assert.IsTrue(chipPile.IsDenominationActive(1), "25 must be active for 15 chips");
        Assert.IsTrue(chipPile.IsDenominationActive(2), "100 must be active for 15 chips (fallback to first three)");
    }

    [Test]
    public void ActiveDenominationFilter_ShowsOnlyThreeColumns()
    {
        chipPile.denominationValues = new[] { 5, 25, 100, 500, 2500 };
        chipPile.supportsSelectableStackMode = true;
        chipPile.maxActiveDenominations = 3;

        var pos0 = new GameObject("ActivePos0");
        var pos1 = new GameObject("ActivePos1");
        var pos2 = new GameObject("ActivePos2");
        pos0.transform.SetParent(chipPileGo.transform);
        pos1.transform.SetParent(chipPileGo.transform);
        pos2.transform.SetParent(chipPileGo.transform);
        pos0.transform.localPosition = new Vector3(-0.06f, 0f, 0f);
        pos1.transform.localPosition = Vector3.zero;
        pos2.transform.localPosition = new Vector3(0.06f, 0f, 0f);
        chipPile.activeDenominationPositions = new Transform[] { pos0.transform, pos1.transform, pos2.transform };

        BuildPileWithPools(30);
        chipPile.SetSelectableStackMode(true);
        chipPile.SetTotalChips(2000);
        SettleAnimation(chipPile);

        Assert.AreEqual(0, chipPile.GetDisplayedDenominationCount(0), "Inactive denomination must show zero chips");
        Assert.AreEqual(0, chipPile.GetDenominationColumnCount(0), "Inactive denomination must have zero columns");
        Assert.Greater(chipPile.GetDisplayedDenominationCount(1), 0, "Active denomination 25 must show chips");
        Assert.Greater(chipPile.GetDisplayedDenominationCount(2), 0, "Active denomination 100 must show chips");
        Assert.Greater(chipPile.GetDisplayedDenominationCount(3), 0, "Active denomination 500 must show chips");
        Assert.AreEqual(0, chipPile.GetDisplayedDenominationCount(4), "Inactive denomination must show zero chips");
    }
}
