
using System.Reflection;
using NUnit.Framework;
using UnityEditor;
using UnityEngine;
using UnityEngine.UI;

public class PhysicalBettingPrefabTests
{
    [Test]
    public void HoldemPlayerPrefab_HasDynamicActiveDenominationSupport()
    {
        string path = HoldemPaths.Asset("DevPrefabs/HoldemPlayer.prefab");
        GameObject root = PrefabUtility.LoadPrefabContents(path);
        try
        {
            Transform stack = root.transform.Find("StackPile");
            Transform bet = root.transform.Find("BetPile");
            Transform raise = root.transform.Find("RaisePile");
            PokerChipPile source = stack.GetComponent<PokerChipPile>();
            GrabbablePile callController = bet.GetComponent<GrabbablePile>();
            Assert.IsNotNull(raise, "Physical raising requires a separate RaisePile root");
            PhysicalRaisePile raiseController = raise.GetComponent<PhysicalRaisePile>();


            Assert.IsTrue(source.supportsSelectableStackMode, "Only StackPile opts into selectable allocation");
            foreach (PokerChipPile pile in root.GetComponentsInChildren<PokerChipPile>(true))
            {
                Assert.AreEqual(pile == source, pile.supportsSelectableStackMode, pile.name);
                Assert.AreEqual(10, pile.stackHeight, pile.name + " must start a new stack after ten chips");
            }
            Assert.AreEqual(5, source.denominationOffsets.Length);
            Assert.AreEqual(5, raiseController.denominationZones.Length);
            Assert.AreEqual(5, raiseController.denominationColliders.Length);
            CollectionAssert.AreEqual(new[] { 5, 25, 100, 500, 2500 }, source.denominationValues);
            Assert.AreSame(source, raiseController.sourcePile);
            Assert.AreSame(raise.GetComponent<PokerChipPile>(), raiseController.raisePile);
            Assert.GreaterOrEqual(raiseController.selectionRadius, 0.02f,
                "Tracked controller origins need tolerance beyond fingertip contact");
            Assert.Greater(raiseController.selectionHeightAboveStack, 0f,
                "Tracked controller origins need a positive upper detection bound");
            Assert.GreaterOrEqual(raiseController.selectionHeightBelowStack, 0f);
            Assert.IsFalse(float.IsNaN(raiseController.handOffset.x) || float.IsNaN(raiseController.handOffset.y)
                || float.IsNaN(raiseController.handOffset.z),
            "Tracked hand calibration must be finite");
            Assert.AreEqual("", raiseController.pickup.InteractionText,
                "The dynamic amount preview must not include a redundant Grab label");
            Assert.AreSame(raiseController, root.GetComponent<HoldemPlayer>().physicalRaisePile);

            Assert.AreEqual(3, source.maxActiveDenominations);
            Assert.AreEqual(5, source.denominationOffsets.Length,
                "Five denomination offsets must exist for center-three fallback");

            for (int i = 0; i < 5; i++)
            {
                Assert.AreEqual("Denomination" + source.denominationValues[i], raiseController.denominationZones[i].name);
                Assert.AreSame(raiseController.denominationZones[i], raiseController.denominationColliders[i].transform);
                Assert.AreEqual(1, raiseController.denominationZones[i].GetComponents<Collider>().Length);
                Assert.IsFalse(raiseController.denominationColliders[i].enabled,
                    "Physical source zones must not affect legacy pickup behavior before runtime enablement");
            }
            Assert.AreEqual(1, bet.GetComponents<VRC.SDKBase.VRC_Pickup>().Length);
            Assert.AreEqual(1, bet.GetComponents<Rigidbody>().Length);
            Assert.AreEqual(1, bet.GetComponents<MMMaellon.SmartObjectSync>().Length);
            Assert.AreEqual(1, bet.GetComponents<PokerChipPile>().Length);
            Assert.AreEqual(1, bet.GetComponents<GrabbablePile>().Length);
            Assert.AreEqual(1, raise.GetComponents<VRC.SDKBase.VRC_Pickup>().Length);
            Assert.AreEqual(1, raise.GetComponents<Rigidbody>().Length);
            Assert.AreEqual(1, raise.GetComponents<MMMaellon.SmartObjectSync>().Length);
            Assert.AreEqual(1, raise.GetComponents<PokerChipPile>().Length);
            Assert.AreEqual(1, raise.GetComponents<PhysicalRaisePile>().Length);

            Transform round = root.transform.Find("RoundPile");
            Assert.IsNotNull(round.GetComponent<Rigidbody>());
            Assert.IsNull(round.Find("Colliders"), "PID piles must not retain the shrinking collider rig");

            Assert.AreSame(bet.gameObject, bet.GetComponent<BoxCollider>().gameObject,
                "The call pickup collider must be on the VRCPickup GameObject");
            Assert.AreSame(raise.gameObject, raise.GetComponent<CapsuleCollider>().gameObject,
                "VRChat requires the raise pickup collider on the VRCPickup GameObject");
            Assert.AreEqual(typeof(GrabbablePile), typeof(GrabbablePile)
                .GetMethod("Interact", BindingFlags.Instance | BindingFlags.Public).DeclaringType);
            Assert.AreNotEqual(typeof(PhysicalRaisePile), typeof(PhysicalRaisePile)
                .GetMethod("Interact", BindingFlags.Instance | BindingFlags.Public).DeclaringType);
            Assert.AreNotSame(callController.gameObject, raiseController.gameObject);
        }
        finally
        {
            PrefabUtility.UnloadPrefabContents(root);
        }
    }

/*
[Test]
    public void HoldemPlayerPrefab_CanvasFacesThePlayerAndReadoutIsWired()
    {
        string path = HoldemPaths.Asset("DevPrefabs/HoldemPlayer.prefab");
        GameObject root = PrefabUtility.LoadPrefabContents(path);
        try
        {
            Transform raise = root.transform.Find("RaisePile");
            PhysicalRaisePile raiseController = raise.GetComponent<PhysicalRaisePile>();
            Transform raiseCanvas = raise.Find("Canvas");
            Assert.IsNotNull(raiseCanvas);
            Assert.AreSame(raiseCanvas, raiseController.raisePile.text.transform.parent);
            Assert.AreSame(raiseCanvas.GetComponent<LookAtPlayerYawOnly>(),
                raiseController.raisePile.lookAtPlayer,
                "The held amount canvas must yaw toward the local player");
        }
        finally
        {
            PrefabUtility.UnloadPrefabContents(root);
        }
    }
*/


    [Test]
    public void HoldemGamePrefab_WiresEveryPhysicalPileToThePlayArea()
    {
        string path = HoldemPaths.Asset("Prefabs/HoldemGame.prefab");
        GameObject root = PrefabUtility.LoadPrefabContents(path);
        try
        {
            HoldemPlayer[] players = root.GetComponentsInChildren<HoldemPlayer>(true);
            Assert.Greater(players.Length, 0);
            foreach (HoldemPlayer player in players)
            {
                Assert.IsNotNull(player.grabbableBetPile.targetCollider, player.name + " call target");
                Assert.IsNotNull(player.physicalRaisePile.targetCollider, player.name + " raise target");
                Assert.AreSame(player.grabbableBetPile.targetCollider, player.physicalRaisePile.targetCollider,
                    player.name + " must use one betting zone for call and raise drops");
                PokerChipPile source = player.stackPile;
                PokerChipPile destination = player.physicalRaisePile.raisePile;
                Assert.AreEqual(source.denominationPools.Length, destination.denominationPools.Length,
                    player.name + " raise pile pool count");
                for (int i = 0; i < source.denominationPools.Length; i++)
                    Assert.AreSame(source.denominationPools[i], destination.denominationPools[i],
                        player.name + " raise pile denomination " + i + " must share the source pool");
            }
        }
        finally
        {
            PrefabUtility.UnloadPrefabContents(root);
        }
    }

    [Test]
    public void HoldemGamePrefab_HasFiveChipPoolsSizedForPeakDemand()
    {
        string path = HoldemPaths.Asset("Prefabs/HoldemGame.prefab");
        GameObject root = PrefabUtility.LoadPrefabContents(path);
        try
        {
            Transform poolRoot = root.transform.Find("PokerChipPools");
            string[] names = { "InvertedPool", "BlackPool", "GreenPool", "RedPool", "BluePool" };
            int[] values = { 5, 25, 100, 500, 2500 };
            // Sized from ChipPileLayoutHarness.MeasurePoolDemand on a 10-seat table: 100s and 500s peak near 190 and
            // 160 with selectable stacks; 2500s scale with the table's money (400 covers about 1M).
            int[] sizes = { 200, 200, 300, 300, 400 };
            for (int p = 0; p < names.Length; p++)
            {
                Transform poolTransform = poolRoot.Find(names[p]);
                LocalObjectPool pool = poolTransform.GetComponent<LocalObjectPool>();
                Assert.AreEqual(values[p], pool.denomination, names[p]);
                Assert.AreEqual(sizes[p], poolTransform.childCount, names[p]);
                Assert.AreEqual(sizes[p], pool.Pool.Length, names[p]);
                for (int i = 0; i < sizes[p]; i++)
                {
                    Assert.IsNotNull(pool.Pool[i]);
                    Assert.AreSame(poolTransform, pool.Pool[i].transform.parent);
                }
            }

            Transform pot = root.transform.Find("PokerChipPile");
            Assert.IsNotNull(pot.GetComponent<Rigidbody>());
            Assert.IsNull(pot.Find("Colliders"), "The central pot must use PID without shrinking colliders");
            Assert.AreEqual(HoldemPaths.Asset("DevPrefabs/PokerChipPile.prefab"),
                PrefabUtility.GetPrefabAssetPathOfNearestInstanceRoot(pot.gameObject));
        }
        finally
        {
            PrefabUtility.UnloadPrefabContents(root);
        }
    }

    [Test]
    public void WorldSettingsPrefab_HasDefaultOffPhysicalToggle()
    {
        string path = HoldemPaths.Asset("WorldSettings/WorldSettings.prefab");
        GameObject root = PrefabUtility.LoadPrefabContents(path);
        try
        {
            Transform physical = root.transform.Find("Canvas/Vertical/Experimental/CardToggles/PhysicalBettingToggle");
            Assert.IsNotNull(physical);
            Toggle toggle = physical.GetComponent<Toggle>();
            GlobalToggleFlags flags = physical.parent.GetComponent<GlobalToggleFlags>();
            Assert.IsFalse(toggle.isOn);
            Assert.AreSame(toggle, flags.physicalBettingToggle);
            Assert.AreEqual(0, flags.holdemPlayers.Length);
            Assert.AreEqual("Immersive betting (VR only)", physical.Find("Label").GetComponent<Text>().text);
            Transform animated = root.transform.Find("Canvas/Vertical/Experimental/CardToggles/AnimatedChipContainersToggle");
            Assert.IsNotNull(animated);
            Assert.IsFalse(animated.GetComponent<Toggle>().isOn);
            Assert.AreEqual("Dynamic Chips", animated.Find("Label").GetComponent<Text>().text);
        }
        finally
        {
            PrefabUtility.UnloadPrefabContents(root);
        }
    }

    [Test]
    public void EightPlayerTableRemainsAVariant()
    {
        GameObject asset = AssetDatabase.LoadAssetAtPath<GameObject>(HoldemPaths.Asset("Prefabs/HoldemGame8Player.prefab"));
        Assert.AreEqual(PrefabAssetType.Variant, PrefabUtility.GetPrefabAssetType(asset));
        Assert.AreEqual(HoldemPaths.Asset("Prefabs/HoldemGame.prefab"),
            AssetDatabase.GetAssetPath(PrefabUtility.GetCorrespondingObjectFromSource(asset)));
    }

    [Test]
    public void HoldemPlayerPrefab_RaisePickupUsesACapsuleInsteadOfABoxHighlight()
    {
        GameObject root = PrefabUtility.LoadPrefabContents(HoldemPaths.Asset("DevPrefabs/HoldemPlayer.prefab"));
        try
        {
            Transform raise = root.transform.Find("RaisePile");
            PhysicalRaisePile controller = raise.GetComponent<PhysicalRaisePile>();
            Assert.IsNull(raise.GetComponent<BoxCollider>(), "The large box pickup highlight must be gone");
            CapsuleCollider capsule = raise.GetComponent<CapsuleCollider>();
            Assert.IsNotNull(capsule);
            Assert.AreSame(capsule, controller.ownCollider);
            Assert.AreEqual(1, capsule.direction, "The compact carried shape is upright");
            Assert.LessOrEqual(capsule.radius, 0.03f);
        }
        finally
        {
            PrefabUtility.UnloadPrefabContents(root);
        }
    }

    [Test]
    public void HoldemGamePrefabs_KeepTheCapsulePickupWiredOnEverySeat()
    {
        foreach (string path in new[]
        {
            HoldemPaths.Asset("Prefabs/HoldemGame.prefab"),
            HoldemPaths.Asset("Prefabs/HoldemGame8Player.prefab")
        })
        {
            GameObject root = PrefabUtility.LoadPrefabContents(path);
            try
            {
                foreach (PhysicalRaisePile controller in root.GetComponentsInChildren<PhysicalRaisePile>(true))
                {
                    Assert.IsNotNull(controller.ownCollider, path + " " + controller.name + " ownCollider");
                    Assert.IsInstanceOf<CapsuleCollider>(controller.ownCollider, path + " " + controller.name);
                    Assert.IsNull(controller.GetComponent<BoxCollider>(), path + " " + controller.name);
                }
            }
            finally
            {
                PrefabUtility.UnloadPrefabContents(root);
            }
        }
    }

    [Test]
    public void HoldemPlayerPrefab_ImmersiveStackSitsTenCentimetresLeft()
    {
        GameObject root = PrefabUtility.LoadPrefabContents(HoldemPaths.Asset("DevPrefabs/HoldemPlayer.prefab"));
        try
        {
            PokerChipPile source = root.transform.Find("StackPile").GetComponent<PokerChipPile>();
            Assert.AreEqual(-0.1f, source.selectableLayoutOffset.x, 0.0001f);
            Assert.AreEqual(0f, source.selectableLayoutOffset.y, 0.0001f);
            Assert.AreEqual(0f, source.selectableLayoutOffset.z, 0.0001f);
        }
        finally
        {
            PrefabUtility.UnloadPrefabContents(root);
        }
    }

    [Test]
    public void HoldemPlayerPrefab_PileReadoutsHoverAlongWorldY()
    {
        GameObject root = PrefabUtility.LoadPrefabContents(HoldemPaths.Asset("DevPrefabs/HoldemPlayer.prefab"));
        try
        {
            foreach (string pile in new[] { "BetPile", "RoundPile", "StackPile", "RaisePile" })
            {
                LookAtPlayerYawOnly look = root.transform.Find(pile).GetComponent<PokerChipPile>().lookAtPlayer;
                Assert.IsNotNull(look, pile + " look-at");
                Assert.IsTrue(look.useWorldYOffset, pile + " readout must hover along world Y, not rotate with the pile");
                Assert.AreEqual(0.0641f, look.worldYOffset, 0.0001f, pile);
            }
        }
        finally
        {
            PrefabUtility.UnloadPrefabContents(root);
        }
    }
}
