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

public class AnimatedChipFlowTests
{
    private GameObject chipPileGo;
    private PokerChipPile chipPile;
    private readonly List<GameObject> poolObjects = new List<GameObject>();

    [SetUp]
    public void SetUp()
    {
        chipPileGo = new GameObject("ChipPileTest");
        chipPile = chipPileGo.AddComponent<PokerChipPile>();
        chipPile.denominationValues = new int[] { 5 };
    }

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

    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);
                Rigidbody rb = chip.AddComponent<Rigidbody>();
                rb.isKinematic = true;
                rb.useGravity = false;
                chip.AddComponent<BoxCollider>().enabled = false;
                pool.Pool[c] = chip;
            }

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

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

    [Test]
    public void SpawnDynamicChips_SpawnsChipsWithPhysicsEnabled()
    {
        BuildPileWithPools(5);
        Vector3 origin = new Vector3(1.5f, 0.7f, 2.1f);

        int spawned = chipPile.SpawnDynamicChips(15, origin);

        Assert.AreEqual(3, spawned, "15 value = 3 x 5 chips");
        Assert.AreEqual(15, chipPile.GetTotalDisplayedValue());
        Assert.AreEqual(3, (int)VrcRuntimeFake.GetPrivate(chipPile, "movingChipCount"));

        for (int i = 0; i < chipPileGo.transform.childCount; i++)
        {
            Transform chip = chipPileGo.transform.GetChild(i);
            Rigidbody rb = chip.GetComponent<Rigidbody>();
            Assert.IsNotNull(rb, chip.name + " must have Rigidbody");
            Assert.IsFalse(rb.isKinematic, chip.name + " must be non-kinematic");
            Assert.IsTrue(rb.useGravity, chip.name + " must have gravity enabled");
            Assert.AreEqual(chipPile.movingChipDrag, rb.drag, 0.0001f);
            Assert.AreEqual(CollisionDetectionMode.ContinuousSpeculative, rb.collisionDetectionMode);
            Assert.AreEqual(chipPile.movingChipSolverIterations, rb.solverIterations);
            Assert.AreEqual(chipPile.movingChipSolverVelocityIterations, rb.solverVelocityIterations);
            Assert.AreEqual(chipPile.movingChipMaxDepenetrationVelocity, rb.maxDepenetrationVelocity, 0.0001f);
            Collider col = chip.GetComponent<Collider>();
            Assert.IsNotNull(col, chip.name + " must have Collider");
            Assert.IsTrue(col.enabled, chip.name + " must have collider enabled");
            Assert.AreEqual(chipPile.movingChipContactOffset, col.contactOffset, 0.0001f);
        }
    }

    [Test]
    public void Start_DisablesIdleUpdateLoop()
    {
        BuildPileWithPools(5);

        Assert.IsFalse(chipPile.enabled,
            "PokerChipPile should not run Update while no chips are animating");
    }

    [Test]
    public void StartAnimatedGather_EnablesUpdateUntilGatherStops()
    {
        BuildPileWithPools(5);
        chipPile.SpawnDynamicChips(5, chipPileGo.transform.position);

        chipPile.StartAnimatedGather();
        Assert.IsTrue(chipPile.enabled, "PID gathering needs Update and FixedUpdate");

        chipPile.EndAnimatedContraction();
        Assert.IsFalse(chipPile.enabled, "A completed gather should stop ticking");
    }

    [Test]
    public void ManualChipDrop_StopsInDynamicPresentationMode()
    {
        BuildPileWithPools(5);
        chipPile.preservePhysicsPlacement = true;
        chipPile.SetTotalChips(5);
        Assert.IsTrue(chipPile.enabled);

        VrcRuntimeFake.SetPrivate(chipPile, "animStartTime", -1000f);
        VrcRuntimeFake.InvokeNoArg(chipPile, "Update");

        Assert.AreEqual(0, (int)VrcRuntimeFake.GetPrivate(chipPile, "animCount"));
        Assert.IsFalse(chipPile.enabled,
            "Dynamic presentation must not make the manual drop animation loop");
    }

    [Test]
    public void SpawnDynamicChips_PositionsNearOrigin()
    {
        BuildPileWithPools(10);
        Vector3 origin = new Vector3(5.0f, 1.0f, 10.0f);

        int spawned = chipPile.SpawnDynamicChips(25, origin);
        Assert.Greater(spawned, 0);

        for (int i = 0; i < chipPileGo.transform.childCount; i++)
        {
            Vector3 chipPos = chipPileGo.transform.GetChild(i).position;
            float horizontalDist = new Vector3(chipPos.x - origin.x, 0f, chipPos.z - origin.z).magnitude;
            Assert.Less(horizontalDist, 0.06f, "Chip " + i + " should be near origin horizontally");
            float verticalDist = Mathf.Abs(chipPos.y - origin.y);
            Assert.Less(verticalDist, 0.06f, "Chip " + i + " should be near origin vertically");
        }
    }

    [Test]
    public void SpawnDynamicChips_AccumulatesOnMultipleCalls()
    {
        BuildPileWithPools(20);
        Vector3 origin = new Vector3(2f, 0f, 3f);

        chipPile.SpawnDynamicChips(10, origin);
        chipPile.SpawnDynamicChips(5, origin);
        chipPile.SpawnDynamicChips(10, origin);

        Assert.AreEqual(25, chipPile.GetTotalDisplayedValue(), "10+5+10 = 25, 5 chips x 5 = 25");
        int[] heldCounts = (int[])VrcRuntimeFake.GetPrivate(chipPile, "heldCounts");
        Assert.AreEqual(5, heldCounts[0], "heldCounts[0] should be 5");
        int movingChipCount = (int)VrcRuntimeFake.GetPrivate(chipPile, "movingChipCount");
        Assert.AreEqual(5, movingChipCount, "All 5 chips should be in movingChips");
    }

[Test]
    public void ReleaseAllToPools_ClearsMovingTrackingForReuse()
    {
        BuildPileWithPools(5);
        chipPile.SpawnDynamicChips(10, chipPileGo.transform.position);
        Assert.AreEqual(2, (int)VrcRuntimeFake.GetPrivate(chipPile, "movingChipCount"));

        chipPile.ReleaseAllToPools();
        Assert.AreEqual(0, (int)VrcRuntimeFake.GetPrivate(chipPile, "movingChipCount"));

        chipPile.SpawnDynamicChips(10, chipPileGo.transform.position);
        Assert.AreEqual(2, (int)VrcRuntimeFake.GetPrivate(chipPile, "movingChipCount"));
    }


public void AnimatedGatherFlow_LeavesChipsDynamic()
    {
        BuildPileWithPools(5);
        chipPile.BeginAnimatedGather(false);
        chipPile.SpawnDynamicChips(15, chipPileGo.transform.position);
        chipPile.StartAnimatedGather();
        chipPile.EndAnimatedContraction();

        Assert.AreEqual(15, chipPile.GetTotalDisplayedValue());
        Assert.AreEqual(3, (int)VrcRuntimeFake.GetPrivate(chipPile, "movingChipCount"));
        for (int i = 0; i < chipPileGo.transform.childCount; i++)
        {
            Rigidbody rb = chipPileGo.transform.GetChild(i).GetComponent<Rigidbody>();
            Assert.IsFalse(rb.isKinematic);
            Assert.IsTrue(rb.useGravity);
            Assert.IsTrue(chipPileGo.transform.GetChild(i).GetComponent<Collider>().enabled);
        }
    }

public void AnimatedGatherFlow_OnlyMakesNewChipsDynamic()
    {
        BuildPileWithPools(10);
        chipPile.SetTotalChips(5);
        SettleAnimation();

        chipPile.BeginAnimatedGather(false);
        chipPile.SpawnDynamicChips(10, chipPileGo.transform.position);
        chipPile.StartAnimatedGather();
        chipPile.EndAnimatedContraction();

        Assert.AreEqual(2, (int)VrcRuntimeFake.GetPrivate(chipPile, "movingChipCount"));
        Assert.AreEqual(15, chipPile.GetTotalDisplayedValue());
    }

public void TransferAllAnimatedTo_PreservesDynamicStateToDestination()
    {
        BuildPileWithPools(10);
        chipPile.SetTotalChips(5);
        SettleAnimation();

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

        destination.BeginAnimatedGather(false);
        Assert.AreEqual(1, chipPile.TransferAllAnimatedTo(destination));
        destination.StartAnimatedGather();
        destination.EndAnimatedContraction();

        Assert.AreEqual(0, chipPile.GetTotalDisplayedValue());
        Assert.AreEqual(5, destination.GetTotalDisplayedValue());
        Rigidbody rb = destGo.transform.GetChild(0).GetComponent<Rigidbody>();
        Assert.IsFalse(rb.isKinematic);
        Assert.IsTrue(rb.useGravity);
        Assert.IsTrue(destGo.transform.GetChild(0).GetComponent<Collider>().enabled);
    }

public void FinishAnimatedGather_LeavesPhysicsRunningAndStopsPid()
    {
        BuildPileWithPools(10);
        chipPile.BeginAnimatedGather(false);
        chipPile.SpawnDynamicChips(15, chipPileGo.transform.position);
        chipPile.StartAnimatedGather();
        chipPile.FinishAnimatedGather();

        Assert.AreEqual(0, (int)VrcRuntimeFake.GetPrivate(chipPile, "movingChipCount"));
        Assert.IsFalse((bool)VrcRuntimeFake.GetPrivate(chipPile, "gatherPdActive"));
        for (int i = 0; i < chipPileGo.transform.childCount; i++)
        {
            Rigidbody rb = chipPileGo.transform.GetChild(i).GetComponent<Rigidbody>();
            Assert.IsFalse(rb.isKinematic);
            Assert.IsTrue(rb.useGravity);
            Assert.IsTrue(chipPileGo.transform.GetChild(i).GetComponent<Collider>().enabled);
        }
    }

public void FinishAnimatedGather_PreservesPhysicsPlacement()
    {
        BuildPileWithPools(10);
        chipPile.SpawnDynamicChips(15, chipPileGo.transform.position);
        Vector3 position = new Vector3(0.2f, 0.03f, -0.15f);
        chipPileGo.transform.GetChild(0).localPosition = position;

        chipPile.FinishAnimatedGather();

        Assert.AreEqual(position, chipPileGo.transform.GetChild(0).localPosition);
        Assert.IsFalse(chipPileGo.transform.GetChild(0).GetComponent<Rigidbody>().isKinematic);
    }


    [Test]
    public void SpawnDynamicChips_ReturnsZeroWhenHeldCountsNull()
    {
        chipPile.denominationValues = new int[] { 5 };
        int spawned = chipPile.SpawnDynamicChips(20, Vector3.zero);
        Assert.AreEqual(0, spawned, "Must return 0 when heldCounts is null");
    }

    private void SettleAnimation()
    {
        VrcRuntimeFake.InvokeNoArg(chipPile, "SettleAnimation");
    }


public void GatherPid_UsesBoundedIntegralAndPullsTowardPile()
    {
        BuildPileWithPools(1);
        chipPile.enableGatherPd = true;
        chipPile.gatherPidIntegral = 10f;
        chipPile.gatherPidIntegralLimit = 0.02f;
        chipPile.BeginAnimatedGather(false);
        chipPile.SpawnDynamicChips(5, chipPileGo.transform.position);
        chipPile.StartAnimatedGather();

        Rigidbody body = chipPileGo.transform.GetChild(0).GetComponent<Rigidbody>();
        body.position = chipPileGo.transform.position + Vector3.right;
        for (int i = 0; i < 20; i++) VrcRuntimeFake.InvokeNoArg(chipPile, "FixedUpdate");

        Assert.Less(Vector3.Dot(body.GetAccumulatedForce(), Vector3.right), 0f);
        Vector3 integralError = ((Vector3[])VrcRuntimeFake.GetPrivate(chipPile, "gatherIntegralErrors"))[0];
        Assert.LessOrEqual(integralError.magnitude, chipPile.gatherPidIntegralLimit + 0.0001f);

        chipPile.EndAnimatedContraction();
        Assert.AreEqual(Vector3.zero,
            ((Vector3[])VrcRuntimeFake.GetPrivate(chipPile, "gatherIntegralErrors"))[0]);
    }


public void AnimatedGather_RestoresOriginalPhysicsMaterialWhenControlStops()
    {
        BuildPileWithPools(1);
        PhysicMaterial moving = new PhysicMaterial("Moving");
        PhysicMaterial resting = new PhysicMaterial("Resting");
        chipPile.movingChipMaterial = moving;

        chipPile.SpawnDynamicChips(5, chipPileGo.transform.position);
        Collider collider = chipPileGo.transform.GetChild(0).GetComponent<Collider>();
        collider.sharedMaterial = resting;
        chipPile.FinishAnimatedGather();
        chipPile.MakeDisplayedChipsDynamic();
        chipPile.StartAnimatedGather();

        Assert.AreSame(moving, collider.sharedMaterial);
        chipPile.EndAnimatedContraction();
        Assert.AreSame(resting, collider.sharedMaterial);
        Object.DestroyImmediate(moving);
        Object.DestroyImmediate(resting);
    }


public void AnimatedGather_TransitionsFromHoverToPlanarSettle()
    {
        BuildPileWithPools(1);
        chipPile.gatherTransportDuration = 1f;
        chipPile.gatherSettleDuration = 0.5f;
        chipPile.SpawnDynamicChips(5, chipPileGo.transform.position + Vector3.right);
        chipPile.StartAnimatedGather();

        Assert.IsFalse((bool)VrcRuntimeFake.GetPrivate(chipPile, "gatherSettling"));
        Assert.AreEqual(1.5f, chipPile.AnimatedGatherDuration(), 0.0001f);
        VrcRuntimeFake.SetPrivate(chipPile, "gatherStartTime", -2f);
        VrcRuntimeFake.SetPrivate(chipPile, "gatherEndTime", Time.time + 1f);
        VrcRuntimeFake.InvokeNoArg(chipPile, "Update");
        Assert.IsTrue((bool)VrcRuntimeFake.GetPrivate(chipPile, "gatherSettling"));
    }
}
