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

/// <summary>
/// Natural-layout piles: one denomination per stack, taller stacks in the middle, and chips that stay put while
/// the pile grows or shrinks; only a reseed or restack rebuilds it. Measured from the chip transforms with the
/// layout harness' metrics, so these check what a player would see.
/// </summary>
public class NaturalChipPileLayoutTests
{
    private static readonly int[] Values = { 10, 50, 100, 500, 1000 };
    private readonly List<GameObject> created = new List<GameObject>();
    private LocalObjectPool[] pools;

    [SetUp]
    public void SetUp()
    {
        pools = new LocalObjectPool[Values.Length];
        for (int d = 0; d < Values.Length; d++)
        {
            var poolGo = Track(new GameObject($"Pool_{Values[d]}"));
            var pool = poolGo.AddComponent<LocalObjectPool>();
            pool.denomination = Values[d];
            pool.Pool = new GameObject[200];
            for (int c = 0; c < pool.Pool.Length; c++)
            {
                var chip = new GameObject($"Chip{Values[d]}_{c}");
                chip.transform.SetParent(poolGo.transform);
                pool.Pool[c] = chip;
            }
            VrcRuntimeFake.InvokeNoArg(pool, "Start");
            pools[d] = pool;
        }
    }

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

    private GameObject Track(GameObject go)
    {
        created.Add(go);
        return go;
    }

    private PokerChipPile NaturalPile(string name = "Pile", bool withReadout = false, float ceiling = 0f,
        float blockedCone = 0f)
    {
        var go = Track(new GameObject(name));
        var pile = go.AddComponent<PokerChipPile>();
        pile.denominationValues = (int[])Values.Clone();
        pile.denominationPools = pools;
        pile.naturalLayout = true;
        pile.chipHeight = 0.004f;
        pile.hexSpacing = 0.03f;
        pile.positionJitter = 0.0015f;
        pile.ceilingLocalY = ceiling;
        pile.blockedConeHalfAngle = blockedCone;
        if (withReadout)
        {
            var textGo = new GameObject("Readout");
            textGo.transform.SetParent(go.transform, false);
            textGo.transform.localPosition = new Vector3(0f, 0.06f, 0f);
            pile.text = textGo.AddComponent<TMPro.TextMeshPro>();
            pile.textGameObject = textGo;
        }
        VrcRuntimeFake.InvokeNoArg(pile, "Start");
        return pile;
    }

    private static int DenominationOf(GameObject chip)
    {
        string name = chip.name;
        if (!name.StartsWith("Chip")) return 0;
        int underscore = name.IndexOf('_');
        return underscore > 4 && int.TryParse(name.Substring(4, underscore - 4), out int value) ? value : 0;
    }

    private static void Settle(PokerChipPile pile) => VrcRuntimeFake.InvokeNoArg(pile, "SettleAnimation");

    private static ChipPileLayoutHarness.PileMetrics Measure(PokerChipPile pile,
        Dictionary<GameObject, Vector3> before = null)
    {
        Settle(pile);
        return ChipPileLayoutHarness.Measure(pile, DenominationOf, before);
    }

    private static Dictionary<GameObject, Vector3> Snapshot(PokerChipPile pile)
    {
        Settle(pile);
        return ChipPileLayoutHarness.Snapshot(pile, DenominationOf);
    }

    private int DisplayedCount(PokerChipPile pile, int value) =>
        pile.GetDisplayedDenominationCount(System.Array.IndexOf(Values, value));

    [Test]
    public void EmptyPile_IsCountedWithAFewChipsOfEveryDenominationFirst()
    {
        PokerChipPile pile = NaturalPile();
        pile.seedChipsPerDenomination = 5;

        pile.SetTotalChips(25000);

        Assert.AreEqual(25000, pile.GetTotalDisplayedValue());
        foreach (int value in Values)
            Assert.GreaterOrEqual(DisplayedCount(pile, value), 5, $"{value} chips are seeded before the greedy remainder");
        Assert.AreEqual(21, DisplayedCount(pile, 1000), "The rest goes largest first");
    }

    [Test]
    public void SmallAmounts_OnlySeedTheChipsThatFit()
    {
        PokerChipPile pile = NaturalPile();
        pile.seedChipsPerDenomination = 5;

        pile.SetTotalChips(120);

        Assert.AreEqual(120, pile.GetTotalDisplayedValue());
        // 5x10 seeded, 1x50 is all of the 50s that fit, the remaining 20 goes to 10s.
        Assert.AreEqual(7, DisplayedCount(pile, 10));
        Assert.AreEqual(1, DisplayedCount(pile, 50));
        Assert.AreEqual(0, DisplayedCount(pile, 100));
    }

    [Test]
    public void NoStackEverHoldsTwoDenominations()
    {
        PokerChipPile pile = NaturalPile();
        int value = 0;
        foreach (int total in new[] { 730, 25000, 24970, 31000, 8040, 120000, 3050, 0, 4260 })
        {
            value = total;
            pile.SetTotalChips(total);
            var metrics = Measure(pile);
            Assert.AreEqual(0, metrics.MixedStacks, $"Mixed stack at {total}: {metrics}");
            Assert.AreEqual(total, pile.GetTotalDisplayedValue(), $"Value at {total}");
        }
        Assert.AreEqual(value, pile.GetTotalDisplayedValue());
    }

    [Test]
    public void GrowingAndShrinkingTheTotal_NeverMovesTheChipsThatStay()
    {
        PokerChipPile pile = NaturalPile();
        pile.SetTotalChips(10000);
        foreach (int total in new[] { 9970, 9500, 10500, 8000, 8040, 2040, 15000, 60000 })
        {
            var before = Snapshot(pile);
            pile.SetTotalChips(total);
            var metrics = Measure(pile, before);
            Assert.AreEqual(0, metrics.Moved, $"Chips moved going to {total}: {metrics}");
            Assert.AreEqual(total, pile.GetTotalDisplayedValue());
        }
    }

    [Test]
    public void PayingWithoutSmallChips_BreaksALargerChipIntoChange()
    {
        PokerChipPile pile = NaturalPile();
        pile.seedChipsPerDenomination = 0;
        pile.SetTotalChips(1000);
        Assert.AreEqual(1, DisplayedCount(pile, 1000));

        pile.SetTotalChips(970);

        Assert.AreEqual(970, pile.GetTotalDisplayedValue());
        Assert.AreEqual(0, DisplayedCount(pile, 1000), "The 1000 was broken");
    }

    [Test]
    public void PotFedByRoundPiles_KeepsEveryChipItAlreadyShows()
    {
        PokerChipPile pot = NaturalPile("Pot");
        PokerChipPile round = NaturalPile("Round");
        int expected = 0;
        foreach (int bet in new[] { 20, 40, 60, 100, 150, 250, 400, 600, 1000, 1500, 2500, 4000 })
        {
            var before = Snapshot(pot);
            round.SetTotalChips(bet * 4);
            round.TransferAllTo(pot);
            expected += bet * 4;
            var metrics = Measure(pot, before);
            Assert.AreEqual(0, metrics.Moved, $"Pot chips moved after a {bet} round: {metrics}");
            Assert.AreEqual(0, metrics.MixedStacks, metrics.ToString());
            Assert.AreEqual(expected, pot.GetTotalDisplayedValue());
        }
    }

    [Test]
    public void BigPile_IsTallestInTheMiddle()
    {
        PokerChipPile pile = NaturalPile();
        pile.ReseedTotal(150000);

        var metrics = Measure(pile);

        Assert.GreaterOrEqual(metrics.RingAverages.Length, 3, metrics.ToString());
        for (int ring = 1; ring < metrics.RingAverages.Length; ring++)
        {
            if (float.IsNaN(metrics.RingAverages[ring])) continue;
            Assert.GreaterOrEqual(metrics.RingAverages[0], metrics.RingAverages[ring], metrics.ToString());
        }
        Assert.Greater(metrics.RingAverages[1], metrics.RingAverages[metrics.RingAverages.Length - 1], metrics.ToString());
        Assert.Greater(metrics.Tallest, 10, "A big pile rises above the old ten-chip stacks: " + metrics);
    }

    [Test]
    public void SmallPile_StaysLowAndSpreadsOut()
    {
        PokerChipPile pile = NaturalPile();
        pile.seedChipsPerDenomination = 0;
        pile.SetTotalChips(30000); // 30 chips of 1000

        var metrics = Measure(pile);

        Assert.Less(metrics.Tallest, pile.centerStackHeight / 2, metrics.ToString());
        Assert.Greater(metrics.Stacks, 2, metrics.ToString());
    }

    [Test]
    public void Restack_KeepsTheChipsAndTheirValue()
    {
        PokerChipPile pile = NaturalPile();
        pile.SetTotalChips(53100);
        var chipsBefore = new HashSet<GameObject>(Snapshot(pile).Keys);

        pile._RestackLayout();

        var chipsAfter = new HashSet<GameObject>(Snapshot(pile).Keys);
        Assert.IsTrue(chipsBefore.SetEquals(chipsAfter), "Restacking reuses the same chips");
        Assert.AreEqual(53100, pile.GetTotalDisplayedValue());
        Assert.AreEqual(0, Measure(pile).MixedStacks);
    }

    [Test]
    public void ReseedTotal_RecountsAnExistingPile()
    {
        PokerChipPile pile = NaturalPile();
        pile.seedChipsPerDenomination = 0;
        pile.SetTotalChips(20000);
        Assert.AreEqual(0, DisplayedCount(pile, 10));

        pile.seedChipsPerDenomination = 4;
        pile.ReseedTotal(20000);

        // 4 of each seeded (2640), 17x1000, and the last 360 as 3x100 + 50 + 10.
        Assert.AreEqual(5, DisplayedCount(pile, 10), "A reseed counts the pile from scratch");
        Assert.AreEqual(20000, pile.GetTotalDisplayedValue());
    }

    [Test]
    public void Readout_RisesAboveTheChipsButStaysUnderTheCeiling()
    {
        const float ceiling = 0.104f;
        PokerChipPile pile = NaturalPile("Stack", true, ceiling);

        foreach (int total in new[] { 300, 5000, 60000, 200000 })
        {
            pile.ReseedTotal(total);
            var metrics = Measure(pile);
            float readoutY = pile.transform.InverseTransformPoint(pile.text.transform.position).y;
            float tallestTop = metrics.Tallest * pile.chipHeight;

            Assert.LessOrEqual(readoutY, ceiling - pile.ceilingClearance + 1e-5f, $"{total}: {metrics}");
            Assert.GreaterOrEqual(readoutY, tallestTop + pile.readoutClearance - 1e-5f, $"{total}: {metrics}");
            Assert.GreaterOrEqual(readoutY, 0.06f - 1e-5f, "The readout never sinks below where it was placed");
        }
    }

    [Test]
    public void SelectableModeRoundTrip_RestacksWithoutMixing()
    {
        PokerChipPile pile = NaturalPile();
        pile.supportsSelectableStackMode = true;
        pile.maxActiveDenominations = 0;
        pile.denominationOffsets = new Vector3[Values.Length];
        pile.SetTotalChips(12000);

        pile.SetSelectableStackMode(true);
        pile.SetSelectableStackMode(false);

        Assert.AreEqual(12000, pile.GetTotalDisplayedValue());
        Assert.AreEqual(0, Measure(pile).MixedStacks);
    }

    // Lowest chip of each stack, keyed by the stack's xz centre.
    private static List<Vector3> StackBases(PokerChipPile pile)
    {
        Settle(pile);
        var bases = new List<Vector3>();
        foreach (Transform child in pile.transform)
        {
            if (!child.gameObject.activeSelf || DenominationOf(child.gameObject) <= 0) continue;
            Vector3 local = child.localPosition;
            int found = bases.FindIndex(b => new Vector2(b.x - local.x, b.z - local.z).magnitude < pile.hexSpacing * 0.5f);
            if (found < 0) bases.Add(local);
            else if (local.y < bases[found].y) bases[found] = local;
        }
        return bases;
    }

    [Test]
    public void NeighbouringStacks_NeverStartAtTheSameHeight()
    {
        PokerChipPile pile = NaturalPile();
        pile.positionJitter = 0f;
        pile.ReseedTotal(150000);

        var bases = StackBases(pile);
        int neighbourPairs = 0;
        for (int i = 0; i < bases.Count; i++)
        for (int j = i + 1; j < bases.Count; j++)
        {
            float distance = new Vector2(bases[i].x - bases[j].x, bases[i].z - bases[j].z).magnitude;
            if (distance > pile.hexSpacing * 1.1f) continue;
            neighbourPairs++;
            Assert.Greater(Mathf.Abs(bases[i].y - bases[j].y), pile.stackLift * 0.5f,
                $"Stacks at {bases[i]} and {bases[j]} share a height");
        }
        Assert.Greater(neighbourPairs, 10);
    }

    [Test]
    public void BlockedCone_WidensRingByRing()
    {
        PokerChipPile pile = NaturalPile(blockedCone: 30f);
        var ring = (int[])VrcRuntimeFake.GetPrivate(pile, "stackRing");
        var blocked = (bool[])VrcRuntimeFake.GetPrivate(pile, "stackBlocked");
        var perRing = new int[6];
        for (int s = 0; s < blocked.Length; s++)
            if (blocked[s]) perRing[ring[s]]++;

        Assert.AreEqual(new[] { 0, 1, 3, 3, 5, 5 }, perRing);
    }

    [Test]
    public void BlockedCone_NeverGetsAStack_EvenWhenThePileIsFull()
    {
        PokerChipPile pile = NaturalPile(blockedCone: 30f);
        pile.positionJitter = 0f;

        foreach (int total in new[] { 10000, 50000, 150000, 400000 })
        {
            pile.ReseedTotal(total);
            foreach (Vector3 b in StackBases(pile))
            {
                if (new Vector2(b.x, b.z).magnitude < pile.hexSpacing * 0.5f) continue;
                float angle = Mathf.Atan2(Mathf.Abs(b.z), b.x) * Mathf.Rad2Deg;
                Assert.Greater(angle, 30.5f, $"{total}: stack at {b} is inside the cone");
            }
        }
    }

    [Test]
    public void ReleaseAllToPools_ThenRefill_StartsAFreshPile()
    {
        PokerChipPile pile = NaturalPile();
        pile.SetTotalChips(40000);
        pile.ReleaseAllToPools();
        Assert.AreEqual(0, Measure(pile).Chips);

        pile.SetTotalChips(4260);

        var metrics = Measure(pile);
        Assert.AreEqual(4260, pile.GetTotalDisplayedValue());
        Assert.AreEqual(0, metrics.MixedStacks, metrics.ToString());
    }
}
