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

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

    // Pools live outside the pile's hierarchy on purpose: ReturnAllChips walks the pile's
    // direct children and treats every one of them as a chip to hand back to a pool.
    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>
    /// 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());
    }
}
