using NUnit.Framework;
using UnityEngine;

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

    [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);
    }

    [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
     * ----------------------------------------------------------- */

    /// <summary>
    /// When counts are unchanged, no animation is queued and
    /// prevCounts stays in sync.
    /// </summary>
    [Test]
    public void TestAnimation_NoAnimationWhenCountsUnchanged()
    {
        var prevField = typeof(PokerChipPile).GetField("prevCounts",
            System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);

        int[] prev = new int[] { 0, 1, 3, 0, 0 }; // 10=0, 50=1, 100=3
        prevField.SetValue(chipPile, prev);

        var updateMethod = typeof(PokerChipPile).GetMethod("UpdateChipDisplay",
            System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);

        int[] counts = new int[] { 0, 1, 3, 0, 0 };
        updateMethod.Invoke(chipPile, new object[] { counts });

        int[] updatedPrev = (int[])prevField.GetValue(chipPile);
        Assert.AreEqual(3, updatedPrev[2], "100 count unchanged");
        Assert.AreEqual(1, updatedPrev[1], "50 count unchanged");
    }

    /// <summary>
    /// Adding a high-value chip cascades: only the new chip of the
    /// changed denomination animates, but ALL lower-value chips
    /// animate (they get pushed up). Higher denominations are silent.
    /// EXAMPLE: 1×25 + 3×5 → 2×25 + 3×5:
    ///   only the 2nd 25 is new → it animates; all 5s cascade.
    /// </summary>
    [Test]
    public void TestAnimation_HighDenomChangeCascadesToLowerDenoms()
    {
        var prevField = typeof(PokerChipPile).GetField("prevCounts",
            System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);

        int[] prev = new int[] { 0, 1, 3, 0, 0 };  // 10=0, 50=1, 100=3
        prevField.SetValue(chipPile, prev);

        var updateMethod = typeof(PokerChipPile).GetMethod("UpdateChipDisplay",
            System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);

        // Add 1×1000 → firstChangedSortedIndex=4 (1000), only that new chip
        // animates + all 100s and 50s cascade
        int[] counts = new int[] { 0, 1, 3, 0, 1 };
        updateMethod.Invoke(chipPile, new object[] { counts });

        int[] updatedPrev = (int[])prevField.GetValue(chipPile);
        Assert.AreEqual(1, updatedPrev[4], "1000 count now 1 (only the new chip)");
        Assert.AreEqual(3, updatedPrev[2], "100 count unchanged (all cascade)");
        Assert.AreEqual(1, updatedPrev[1], "50 count unchanged (all cascade)");
    }

    /// <summary>
    /// When only the lowest denomination changes, only that denom
    /// animates (nothing below it). Higher denoms stay silent.
    /// </summary>
    [Test]
    public void TestAnimation_LowDenomChangeDoesNotAffectHigher()
    {
        var prevField = typeof(PokerChipPile).GetField("prevCounts",
            System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);

        int[] prev = new int[] { 2, 0, 3, 0, 1 };// 10=2, 50=0, 100=3, 500=0, 1000=1
        prevField.SetValue(chipPile, prev);

        var updateMethod = typeof(PokerChipPile).GetMethod("UpdateChipDisplay",
            System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);

        // Add 1×10 → only the new 10 chip animates, nothing above
        int[] counts = new int[] { 3, 0, 3, 0, 1 };
        updateMethod.Invoke(chipPile, new object[] { counts });

        int[] updatedPrev = (int[])prevField.GetValue(chipPile);
        Assert.AreEqual(3, updatedPrev[0], "10 count increased (only new chip animates)");
        Assert.AreEqual(1, updatedPrev[4], "1000 count unchanged (silent)");
    }

    /// <summary>
    /// When a denomination count decreases, still-existing chips
    /// of that denom and below cascade (their positions shifted).
    /// The removed chips are silently returned to pool.
    /// </summary>
    [Test]
    public void TestAnimation_CountDecreaseCascadesToRemaining()
    {
        var prevField = typeof(PokerChipPile).GetField("prevCounts",
            System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);

        int[] prev = new int[] { 3, 0, 2, 0, 1 };  // 10=3, 50=0, 100=2, 500=0, 1000=1
        prevField.SetValue(chipPile, prev);

        var updateMethod = typeof(PokerChipPile).GetMethod("UpdateChipDisplay",
            System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);

        // Remove 1×100 → remaining 1×100 and all 10s cascade
        int[] counts = new int[] { 3, 0, 1, 0, 1 };
        updateMethod.Invoke(chipPile, new object[] { counts });

        int[] updatedPrev = (int[])prevField.GetValue(chipPile);
        Assert.AreEqual(1, updatedPrev[2], "100 count decreased");
        Assert.AreEqual(1, updatedPrev[4], "1000 count unchanged (silent)");
    }

    /// <summary>
    /// First render (prevCounts all zero) → every chip is "new"
    /// and all denominations should animate.
    /// </summary>
    [Test]
    public void TestAnimation_FirstRenderAllChipsAnimate()
    {
        var prevField = typeof(PokerChipPile).GetField("prevCounts",
            System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);

        int[] freshPrev = new int[] { 0, 0, 0, 0, 0 };
        prevField.SetValue(chipPile, freshPrev);

        var updateMethod = typeof(PokerChipPile).GetMethod("UpdateChipDisplay",
            System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);

        int[] counts = new int[] { 0, 0, 0, 0, 0 };
        updateMethod.Invoke(chipPile, new object[] { counts });

        int[] updatedPrev = (int[])prevField.GetValue(chipPile);
        for (int i = 0; i < counts.Length; i++)
        {
            Assert.AreEqual(counts[i], updatedPrev[i],
                $"prevCounts[{i}] equals counts[{i}]");
        }
    }
}
