using System.Collections.Generic;
using System.Reflection;
using NUnit.Framework;
using UnityEngine;
using VRC.SDKBase;

public class PhysicalRaisePileTests
{
    private readonly List<GameObject> objects = new List<GameObject>();
    private VrcRuntimeFake runtime;
    private HoldemGame game;
    private HoldemPlayer player;
    private PokerChipPile source;
    private PokerChipPile raise;

    private CapsuleCollider pickupCollider;
    private PhysicalRaisePile controller;
    private Material idleMaterial;
    private Material fillMaterial;
    private Material outlineMaterial;

    [SetUp]
    public void SetUp()
    {
        runtime = new VrcRuntimeFake();
        runtime.Install();

        game = Spawn("Game").AddComponent<HoldemGame>();
        game.playerState = new int[HoldemGame.MAX_SEATS];
        game.stacks = new int[HoldemGame.MAX_SEATS];
        game.roundContribution = new int[HoldemGame.MAX_SEATS];
        game.playerState[0] = HoldemGame.PLAYER_ACTING;
        game.stacks[0] = 500;
        game.currentBet = 100;
        game.minimumRaise = 100;
        game.epoch = 4;

        GameObject playerObject = Spawn("Player");
        player = playerObject.AddComponent<HoldemPlayer>();
        player.game = game;
        player.seatIdx = 0;
        runtime.Owners[playerObject] = runtime.LocalPlayer;
        VrcRuntimeFake.SetPrivate(player, "activePlayerId", runtime.LocalPlayer.playerId);

        int[] values = { 5, 25, 100, 500, 2500 };
        LocalObjectPool[] pools = BuildPools(values, 40);
        source = BuildPile("StackPile", values, pools, true);
        raise = BuildPile("RaisePile", values, pools, false);
        source.SetSelectableStackMode(true);
        source.SetTotalChips(400);
        raise.SetTotalChips(0);

        controller = raise.gameObject.AddComponent<PhysicalRaisePile>();
        controller.sourcePile = source;
        controller.raisePile = raise;

        pickupCollider = raise.gameObject.AddComponent<CapsuleCollider>();
        pickupCollider.center = new Vector3(0f, 0.02f, 0f);
        pickupCollider.direction = 1;
        pickupCollider.radius = 0.02f;
        pickupCollider.height = 0.06f;
        controller.ownCollider = pickupCollider;
        controller.player = player;
        System.Type pickupType = System.Type.GetType("VRC.SDK3.Components.VRCPickup, VRCSDK3");
        Assert.IsNotNull(pickupType, "VRCPickup SDK component type was not loaded");
        controller.pickup = (VRC_Pickup)raise.gameObject.AddComponent(pickupType);
        player.stackPile = source;
        player.physicalRaisePile = controller;
        runtime.Owners[raise.gameObject] = runtime.LocalPlayer;
        VrcRuntimeFake.InvokeNoArg(controller, "Start");
        player.SetPhysicalBettingEnabled(true);
        player.bet = player.GetPhysicalCallAmount();
        controller.SetInteractionEnabled(true);
        runtime.VrUsers[runtime.LocalPlayer.playerId] = true;
    }

    [TearDown]
    public void TearDown()
    {
        runtime.Uninstall();
        if (idleMaterial) Object.DestroyImmediate(idleMaterial);
        if (fillMaterial) Object.DestroyImmediate(fillMaterial);
        if (outlineMaterial) Object.DestroyImmediate(outlineMaterial);
        for (int i = objects.Count - 1; i >= 0; i--) if (objects[i]) Object.DestroyImmediate(objects[i]);
        objects.Clear();
    }

[Test]
    public void InitialGrab_BelowMinimumTransfersExactlyTheMinimumRaise()
    {
        Assert.IsTrue(BeginReservation(0, 0, 1));

        Assert.AreEqual(100, player.bet);
        Assert.AreEqual(100, raise.GetTotalDisplayedValue());
        Assert.AreEqual(5, raise.GetDisplayedDenominationCount(0));
        Assert.AreEqual(3, raise.GetDisplayedDenominationCount(1));
        Assert.AreEqual(5, source.GetDisplayedDenominationCount(0));
        Assert.AreEqual(7, source.GetDisplayedDenominationCount(1));
    }

[Test]
    public void GrabAtOrAboveMinimumKeepsCallOutsideTheRaisePile()
    {
        Assert.IsTrue(BeginReservation(1, 0, 6));

        Assert.AreEqual(100, player.bet, "The call stays pending until the pile reaches the play area");
        Assert.AreEqual(150, raise.GetTotalDisplayedValue(),
            "The physical raise pile contains only the selected raise increment");
    }

[Test]
    public void CallOverride_ReturnsActiveRaiseAndCommitsOnlyTheCall()
    {
        Assert.IsTrue(BeginReservation(1, 0, 6));
        Assert.AreEqual(150, raise.GetTotalDisplayedValue());
        Assert.AreEqual(250, source.GetTotalDisplayedValue());

        GameObject callObject = Spawn("CallPile");
        GrabbablePile callPile = callObject.AddComponent<GrabbablePile>();
        callPile.player = player;
        player.grabbableBetPile = callPile;
        bool committed = (bool)typeof(GrabbablePile).GetMethod("CommitPhysicalCall",
            BindingFlags.Instance | BindingFlags.NonPublic).Invoke(callPile, null);

        Assert.IsTrue(committed);
        Assert.AreEqual(100, player.bet, "The raise reservation must not change the call bet");
        Assert.AreEqual(game.epoch, player.committedEpoch);
        Assert.AreEqual(0, raise.GetTotalDisplayedValue());
        Assert.AreEqual(400, source.GetTotalDisplayedValue(),
            "Every reserved raise chip must return before call collection starts");
    }


    [Test]
    public void EnteringPlayAreaWhileHeld_CommitsImmediatelyAndCancelsReturn()
    {
        Assert.IsTrue(BeginReservation(0, 0, 1));
        GameObject targetObject = Spawn("BetTarget");
        BoxCollider target = targetObject.AddComponent<BoxCollider>();
        target.size = Vector3.one;
        controller.targetCollider = target;
        raise.transform.position = target.bounds.center;
        VrcRuntimeFake.SetPrivate(controller, "state", 3);

        InvokePrivate("Update");
        controller._ResolvePhysicalDrop();

        Assert.AreEqual(200, player.bet);
        Assert.AreEqual(game.epoch, player.committedEpoch);
        Assert.AreEqual(0, raise.GetTotalDisplayedValue());
        Assert.AreEqual(300, source.GetTotalDisplayedValue(),
            "The stale return must not put committed chips back into the stack");
    }

    [Test]
    public void DroppedOutsidePlayArea_ReturnsOnlyAfterTheDelayExpires()
    {
        Assert.IsTrue(BeginReservation(0, 0, 1));
        VrcRuntimeFake.SetPrivate(controller, "state", 3);
        controller.OnDrop();

        controller._ResolvePhysicalDrop();
        Assert.AreEqual(100, raise.GetTotalDisplayedValue(),
            "The return callback must remain pending during its grace period");

        VrcRuntimeFake.SetPrivate(controller, "pendingDropResolveTime", Time.time);
        controller._ResolvePhysicalDrop();
        Assert.AreEqual(0, raise.GetTotalDisplayedValue());
        Assert.AreEqual(400, source.GetTotalDisplayedValue());
    }


    [Test]
    public void ZeroSelection_DoesNotCreateReservation()
    {
        Assert.IsFalse(BeginReservation(0, 0, 0));
        Assert.AreEqual(100, player.bet);
        Assert.AreEqual(0, raise.GetTotalDisplayedValue());
        Assert.AreEqual(10, source.GetDisplayedDenominationCount(0));
    }

    [Test]
    public void ReturnReservation_RestoresExactCountsAndAutomaticCall()
    {
        Assert.IsTrue(BeginReservation(0, 0, 1));
        InvokePrivate("ReturnReservation", true);

        Assert.AreEqual(100, player.bet);
        Assert.AreEqual(0, raise.GetTotalDisplayedValue());
        Assert.AreEqual(10, source.GetDisplayedDenominationCount(0));
        Assert.AreEqual(10, source.GetDisplayedDenominationCount(1));
        Assert.AreEqual(1, source.GetDisplayedDenominationCount(2));
    }

[Test]
    public void StaleDropCallback_DoesNotResolveNewerHold()
    {
        Assert.IsTrue(BeginReservation(0, 0, 1));
        VrcRuntimeFake.SetPrivate(controller, "state", 4);
        VrcRuntimeFake.SetPrivate(controller, "pendingDropToken", 2);
        VrcRuntimeFake.SetPrivate(controller, "dropToken", 3);

        controller._ResolvePhysicalDrop();

        Assert.AreEqual(100, player.bet);
        Assert.AreEqual(100, raise.GetTotalDisplayedValue());
    }

    [Test]
    public void GrabSurface_IsOffWhenNoPileIsHovered()
    {
        Assert.IsFalse(pickupCollider.enabled, "Idle with no hover: nothing to highlight, grab or use");
        AssertZoneCollidersOff();

        Vector3 away = new Vector3(50f, 50f, 50f);
        runtime.SetTrackingPosition(runtime.LocalPlayer, VRC.SDKBase.VRCPlayerApi.TrackingDataType.LeftHand, away);
        runtime.SetTrackingPosition(runtime.LocalPlayer, VRC.SDKBase.VRCPlayerApi.TrackingDataType.RightHand, away);
        InvokePrivate("UpdateHover");

        Assert.IsFalse(pickupCollider.enabled);
        AssertZoneCollidersOff();
    }

    [Test]
    public void GrabSurface_CoversOnlyTheHoveredPile()
    {
        controller.selectionRadius = 0.02f;
        Assert.AreSame(controller.gameObject, pickupCollider.gameObject);
        Assert.IsNull(controller.GetComponent<BoxCollider>(), "A box pickup collider draws a large box highlight");

        HoverOver(2, 0);

        Assert.IsTrue(pickupCollider.enabled);
        AssertZoneCollidersOff();
        AssertColliderCoversOnly(2, 0);
        Vector3 reach = controller.transform.InverseTransformPoint(
            source.GetDenominationColumnWorldPosition(2, 0)) + Vector3.up * 0.06f;
        Assert.IsTrue(CapsuleCoversHorizontally(pickupCollider, reach),
            "The collider must reach above the pile for the hand offset");
        Assert.LessOrEqual(pickupCollider.center.y - pickupCollider.height * 0.5f,
            controller.transform.InverseTransformPoint(source.GetDenominationColumnWorldPosition(2, 0)).y + 0.0001f,
            "The collider must reach down to the base of the pile");
    }

    [Test]
    public void GrabSurface_FollowsTheHoverFromPileToPile()
    {
        controller.selectionRadius = 0.02f;
        source.SetTotalChips(3000);
        int split = -1;
        for (int i = 0; i < source.denominationValues.Length && split < 0; i++)
            if (source.GetDenominationColumnCount(i) >= 2) split = i;
        Assert.GreaterOrEqual(split, 0, "The fixture needs a denomination split over several piles");
        int other = -1;
        for (int i = 0; i < source.denominationValues.Length && other < 0; i++)
            if (i != split && source.GetDenominationColumnChipCount(i, 0) > 0) other = i;
        Assert.GreaterOrEqual(other, 0, "The fixture needs a second denomination with chips");

        int[,] route = { { split, 0 }, { split, 1 }, { other, 0 }, { split, 1 }, { split, 0 } };
        for (int step = 0; step < route.GetLength(0); step++)
        {
            HoverOver(route[step, 0], route[step, 1]);

            Assert.IsTrue(pickupCollider.enabled, "step " + step);
            AssertColliderCoversOnly(route[step, 0], route[step, 1]);
        }
    }

    [Test]
    public void GrabSurface_TurnsOffAgainWhenTheHandLeavesThePile()
    {
        HoverOver(0, 0);
        Assert.IsTrue(pickupCollider.enabled);

        Vector3 away = new Vector3(50f, 50f, 50f);
        runtime.SetTrackingPosition(runtime.LocalPlayer, VRC.SDKBase.VRCPlayerApi.TrackingDataType.LeftHand, away);
        InvokePrivate("UpdateHover");

        Assert.IsFalse(pickupCollider.enabled);
    }

    [Test]
    public void GrabSurface_StaysOnWhileTheRaiseIsHeld()
    {
        HoverOver(1, 0);
        Assert.IsTrue(pickupCollider.enabled);
        VrcRuntimeFake.SetPrivate(controller, "state", 3);

        InvokePrivate("HideHover");

        Assert.IsTrue(pickupCollider.enabled, "Hiding the hover must not disable the carried collider");
    }

    private void AssertZoneCollidersOff()
    {
        if (controller.denominationColliders == null) return;
        for (int i = 0; i < controller.denominationColliders.Length; i++)
            if (controller.denominationColliders[i] != null)
                Assert.IsFalse(controller.denominationColliders[i].enabled, "zone " + i);
    }

    // The pickup collider must contain the hovered pile and no other pile of any denomination.
    private void AssertColliderCoversOnly(int denomination, int column)
    {
        for (int d = 0; d < source.denominationValues.Length; d++)
        {
            if (!source.IsDenominationActive(d)) continue;
            int columns = source.GetDenominationColumnCount(d);
            for (int c = 0; c < columns; c++)
            {
                Vector3 local = controller.transform.InverseTransformPoint(
                    source.GetDenominationColumnWorldPosition(d, c));
                bool covered = CapsuleCoversHorizontally(pickupCollider, local);
                Assert.AreEqual(d == denomination && c == column, covered, "pile " + d + ":" + c);
            }
        }
    }

    private static bool CapsuleCoversHorizontally(CapsuleCollider capsule, Vector3 local)
    {
        Vector3 delta = local - capsule.center;
        float along = capsule.direction == 0 ? delta.x : capsule.direction == 2 ? delta.z : delta.y;
        float across1 = capsule.direction == 0 ? delta.y : delta.x;
        float across2 = capsule.direction == 2 ? delta.y : delta.z;
        float straight = Mathf.Max(0f, capsule.height * 0.5f - capsule.radius);
        float overshoot = Mathf.Max(0f, Mathf.Abs(along) - straight);
        return overshoot * overshoot + across1 * across1 + across2 * across2
            <= capsule.radius * capsule.radius + 0.000001f;
    }

[Test]
    public void CarriedPile_CentersRootAndColliderOnTrackedHand()
    {
        Vector3 handPosition = new Vector3(1.2f, 1.1f, -0.4f);
        runtime.SetTrackingPosition(runtime.LocalPlayer,
            VRC.SDKBase.VRCPlayerApi.TrackingDataType.LeftHand, handPosition);
        VrcRuntimeFake.SetPrivate(controller, "holdingHand", 0);

        InvokePrivate("ConfigureCarriedCollider");
        InvokePrivate("CenterCarriedPileOnHand");

        Assert.AreEqual(handPosition, controller.transform.position);
        Assert.AreEqual(new Vector3(0f, 0.02f, 0f), pickupCollider.center,
            "The carried capsule returns to its authored compact shape");
        Assert.AreEqual(1, pickupCollider.direction);
        Assert.AreEqual(0.02f, pickupCollider.radius, 0.0001f);
        Assert.AreEqual(0.06f, pickupCollider.height, 0.0001f);
    }


[Test]
    public void Hover_PreviewIncrementsWhileIdle()
    {
        Vector3 hand = HandInsideColumn(0, 0, 0.25f);
        runtime.SetTrackingPosition(runtime.LocalPlayer, VRC.SDKBase.VRCPlayerApi.TrackingDataType.LeftHand, hand);
        runtime.SetTrackingPosition(runtime.LocalPlayer, VRC.SDKBase.VRCPlayerApi.TrackingDataType.RightHand,
            hand + Vector3.right * 10f);

        InvokePrivate("UpdateHover");

        Assert.AreEqual(0, VrcRuntimeFake.GetPrivate(controller, "previewHand"));
        Assert.AreEqual(1, VrcRuntimeFake.GetPrivate(controller, "previewCount"));
    }

    [Test]
    public void LowerHand_SelectsMoreChipsFromTheSameColumn()
    {
        Vector3 hand = HandInsideColumn(0, 0, 2.25f);
        runtime.SetTrackingPosition(runtime.LocalPlayer, VRC.SDKBase.VRCPlayerApi.TrackingDataType.LeftHand, hand);
        runtime.SetTrackingPosition(runtime.LocalPlayer, VRC.SDKBase.VRCPlayerApi.TrackingDataType.RightHand,
            hand + Vector3.right * 10f);

        InvokePrivate("UpdateHover");

        Assert.AreEqual(3, VrcRuntimeFake.GetPrivate(controller, "previewCount"));
    }

[Test]
    public void SelectionHeight_CoversZeroThroughFullColumn()
    {
        Vector3 hand = HandInsideColumn(0, 0, 0f);
        runtime.SetTrackingPosition(runtime.LocalPlayer, VRC.SDKBase.VRCPlayerApi.TrackingDataType.LeftHand, hand);
        runtime.SetTrackingPosition(runtime.LocalPlayer, VRC.SDKBase.VRCPlayerApi.TrackingDataType.RightHand,
            hand + Vector3.right * 10f);

        InvokePrivate("UpdateHover");
        Assert.AreEqual(0, VrcRuntimeFake.GetPrivate(controller, "previewCount"));

        hand = HandInsideColumn(0, 0, 9.25f);
        runtime.SetTrackingPosition(runtime.LocalPlayer, VRC.SDKBase.VRCPlayerApi.TrackingDataType.LeftHand, hand);
        InvokePrivate("UpdateHover");
        Assert.AreEqual(10, VrcRuntimeFake.GetPrivate(controller, "previewCount"));
    }

[Test]
    public void ShortColumns_VirtualTenthChipPositionSelectsNothing()
    {
        const float chipHeight = 0.003f;
        const float virtualTenthChip = 10f * chipHeight;
        for (int displayed = 1; displayed <= 9; displayed++)
        {
            float columnTop = displayed * chipHeight;
            Assert.AreEqual(0, PhysicalRaiseSelectionMath.SelectionCount(
                columnTop, virtualTenthChip, chipHeight, displayed, 10),
                displayed + " displayed chips");
            Assert.AreEqual(0, PhysicalRaiseSelectionMath.SelectionCount(
                columnTop, columnTop, chipHeight, displayed, 10),
                displayed + " displayed chips at their actual top");
        }
    }

[Test]
    public void ReadoutPosition_RotatesOffsetIntoTheArmAlignedFrame()
    {
        Vector3 hand = new Vector3(1f, 2f, 3f);
        Vector3 offset = new Vector3(0f, 0.09f, 0.05f);

        Assert.AreEqual(hand + offset,
            PhysicalRaiseSelectionMath.HandPoint(hand, Quaternion.identity, offset));
    }

    [Test]
    public void ReadoutPosition_StaysAboveTheHandWhenTheArmReverses()
    {
        Vector3 hand = new Vector3(0f, 1f, 0f);
        Vector3 offset = new Vector3(0f, 0.09f, 0.05f);
        Vector3 forwardArm = PhysicalRaiseSelectionMath.HandPoint(hand, Quaternion.identity, offset);
        Vector3 reverseArm = PhysicalRaiseSelectionMath.HandPoint(
            hand, Quaternion.Euler(0f, 180f, 0f), offset);

        Assert.AreEqual(forwardArm.y, reverseArm.y, 0.0001f,
            "The vertical offset must not flip when the arm points the other way");
        Assert.AreEqual(-forwardArm.z, reverseArm.z, 0.0001f,
            "The forward offset must follow the arm-to-hand direction");
    }



    [Test]
    public void Hover_AcceptsTrackedControllerOffsetFromTheVisibleHand()
    {
        Vector3 hand = HandInsideColumn(2, 0, 0.25f) + Vector3.forward * 0.05f;
        runtime.SetTrackingPosition(runtime.LocalPlayer, VRC.SDKBase.VRCPlayerApi.TrackingDataType.LeftHand, hand);
        runtime.SetTrackingPosition(runtime.LocalPlayer, VRC.SDKBase.VRCPlayerApi.TrackingDataType.RightHand,
            hand + Vector3.right * 10f);

        InvokePrivate("UpdateHover");
        Assert.AreEqual(2, VrcRuntimeFake.GetPrivate(controller, "previewDenomination"));
    }

[Test]
    public void HeldHover_ShowsCurrentRaiseAndTriggerIncrement()
    {
        Assert.IsTrue(BeginReservation(0, 0, 1));
        VrcRuntimeFake.SetPrivate(controller, "state", 3);
        VrcRuntimeFake.SetPrivate(controller, "holdingHand", 0);
        Vector3 hand = HandInsideColumn(0, 0, 0.25f);
        runtime.SetTrackingPosition(runtime.LocalPlayer, VRC.SDKBase.VRCPlayerApi.TrackingDataType.LeftHand, hand);

        InvokePrivate("UpdateHover");

        Assert.AreEqual("100 (+5)", raise.text.text);
        Assert.AreEqual("", controller.pickup.UseText);
        Assert.AreEqual(105, VrcRuntimeFake.GetPrivate(controller, "previewTotal"));
    }

[Test]
    public void TriggerIncrease_MovesTheDisplayedIncrementIntoTheHeldRaise()
    {
        Assert.IsTrue(BeginReservation(0, 0, 1));
        VrcRuntimeFake.SetPrivate(controller, "state", 3);
        VrcRuntimeFake.SetPrivate(controller, "holdingHand", 0);
        VrcRuntimeFake.SetPrivate(controller, "previewHand", 0);
        VrcRuntimeFake.SetPrivate(controller, "previewDenomination", 0);
        VrcRuntimeFake.SetPrivate(controller, "previewColumn", 0);
        VrcRuntimeFake.SetPrivate(controller, "previewCount", 1);

        bool increased = (bool)typeof(PhysicalRaisePile).GetMethod("ApplyPreviewIncrease",
            BindingFlags.Instance | BindingFlags.NonPublic).Invoke(controller, null);

        Assert.IsTrue(increased);
        Assert.AreEqual(100, player.bet);
        Assert.AreEqual(105, raise.GetTotalDisplayedValue());
    }

[Test]
    public void PickupUse_AddsAfterGrabAndRefreshesTheCanvasIndicator()
    {
        Assert.IsTrue(BeginReservation(0, 0, 1));
        VrcRuntimeFake.SetPrivate(controller, "state", 3);
        VrcRuntimeFake.SetPrivate(controller, "holdingHand", 0);
        Vector3 hand = HandInsideColumn(0, 0, 0.25f);
        runtime.SetTrackingPosition(runtime.LocalPlayer, VRC.SDKBase.VRCPlayerApi.TrackingDataType.LeftHand, hand);
        InvokePrivate("UpdateHover");
        Assert.AreEqual("100 (+5)", raise.text.text);

        controller.OnPickupUseDown();

        Assert.AreEqual(105, raise.GetTotalDisplayedValue());
        Assert.AreEqual("105 (+0)", raise.text.text);
    }

[Test]
    public void DesktopPickupUse_AddsChipsAndKeepsTheCanvasIndicatorCurrent()
    {
        runtime.VrUsers[runtime.LocalPlayer.playerId] = false;
        Assert.IsTrue(BeginReservation(2, 0, 1));
        VrcRuntimeFake.SetPrivate(controller, "state", 3);
        VrcRuntimeFake.SetPrivate(controller, "holdingHand", -1);
        InvokePrivate("UpdateHover");
        Assert.AreEqual(100, raise.GetTotalDisplayedValue());
        Assert.AreEqual("100 (+25)", raise.text.text);

        controller.OnPickupUseDown();

        Assert.AreEqual(125, raise.GetTotalDisplayedValue());
        Assert.AreEqual("125 (+25)", raise.text.text);
    }


    [Test]
    public void PickupUse_BeforeGrabDoesNotMoveChips()
    {
        controller.OnPickupUseDown();

        Assert.AreEqual(0, raise.GetTotalDisplayedValue());
        Assert.AreEqual(400, source.GetTotalDisplayedValue());
    }


    [Test]
    public void OutOfTurnSelection_CanBeHandledButCannotCommit()
    {
        game.playerState[0] = HoldemGame.PLAYER_PENDING;
        controller.SetInteractionEnabled(false);
        Assert.IsTrue((bool)typeof(PhysicalRaisePile).GetMethod("CanHandleChips",
            BindingFlags.Instance | BindingFlags.NonPublic).Invoke(controller, null));
        Assert.IsFalse((bool)typeof(PhysicalRaisePile).GetMethod("CanBetNow",
            BindingFlags.Instance | BindingFlags.NonPublic).Invoke(controller, null));
        Assert.IsTrue(BeginReservation(0, 0, 1));

        GameObject targetObject = Spawn("BetTarget");
        BoxCollider target = targetObject.AddComponent<BoxCollider>();
        target.size = Vector3.one;
        controller.targetCollider = target;
        raise.transform.position = target.bounds.center;
        VrcRuntimeFake.SetPrivate(controller, "state", 3);
        controller.OnDrop();
        VrcRuntimeFake.SetPrivate(controller, "pendingDropResolveTime", Time.time);
        controller._ResolvePhysicalDrop();

        Assert.AreNotEqual(game.epoch, player.committedEpoch);
        Assert.AreEqual(0, raise.GetTotalDisplayedValue());
        Assert.AreEqual(10, source.GetDisplayedDenominationCount(0));
    }


    [Test]
    public void CoarseDenominations_MinRaiseTopsUpFromIdlePoolsAndCommits()
    {
        game.stacks[0] = 6000;
        game.currentBet = 0;
        game.minimumRaise = 125;
        player.bet = player.GetPhysicalCallAmount();
        source.SetTotalChips(6000);
        raise.SetTotalChips(0);

        Assert.IsTrue(BeginReservation(2, 0, 1), "Grabbing a single 100 must be accepted");

        Assert.AreEqual(125, controller._GetRepresentedRaiseValue(),
            "The reservation must stand for the full 125 minimum raise");
        Assert.AreEqual(125, raise.GetTotalDisplayedValue(),
            "A 25 chip must spawn from the idle pool to complete the raise");
        Assert.AreEqual(1, raise.GetDisplayedDenominationCount(1), "The spawned 25");
        Assert.AreEqual(1, raise.GetDisplayedDenominationCount(2));
        Assert.AreEqual(5900, source.GetTotalDisplayedValue());
        Assert.AreEqual("125", raise.text.text);
        Assert.IsTrue(game.IsValidBet(125, 0), "125 must be a legal min-raise");

        GameObject targetObject = Spawn("BetTarget");
        BoxCollider target = targetObject.AddComponent<BoxCollider>();
        target.size = Vector3.one;
        controller.targetCollider = target;
        raise.transform.position = target.bounds.center;
        VrcRuntimeFake.SetPrivate(controller, "state", 3);

        InvokePrivate("Update");
        controller._ResolvePhysicalDrop();

        Assert.AreEqual(125, player.bet, "The committed bet is the represented raise, not the chip approximation");
        Assert.AreEqual(game.epoch, player.committedEpoch);
        Assert.AreEqual(0, raise.GetTotalDisplayedValue());
    }

    [Test]
    public void NonRepresentableMinRaise_CommitsRepresentedRaiseWithApproximateChips()
    {
        game.stacks[0] = 6000;
        game.currentBet = 0;
        game.minimumRaise = 127;
        player.bet = player.GetPhysicalCallAmount();
        source.SetTotalChips(6000);
        raise.SetTotalChips(0);

        Assert.IsTrue(BeginReservation(2, 0, 1));

        Assert.AreEqual(125, raise.GetTotalDisplayedValue(),
            "Chips may only approximate the 127 raise as 125");
        Assert.AreEqual(127, controller._GetRepresentedRaiseValue());
        Assert.IsTrue(game.IsValidBet(127, 0));

        GameObject targetObject = Spawn("BetTarget");
        BoxCollider target = targetObject.AddComponent<BoxCollider>();
        target.size = Vector3.one;
        controller.targetCollider = target;
        raise.transform.position = target.bounds.center;
        VrcRuntimeFake.SetPrivate(controller, "state", 3);

        InvokePrivate("Update");
        controller._ResolvePhysicalDrop();

        Assert.AreEqual(127, player.bet, "The odd minimum raise must commit exactly");
        Assert.AreEqual(game.epoch, player.committedEpoch);
    }

    [Test]
    public void DrainingTheSource_CommitsExactAllInDespiteRemainder()
    {
        game.stacks[0] = 62;
        game.currentBet = 0;
        game.minimumRaise = 100;
        player.bet = player.GetPhysicalCallAmount();
        source.SetTotalChips(62);
        raise.SetTotalChips(0);

        Assert.IsTrue(BeginReservation(0, 0, 10), "Grabbing the whole first column of 5s");

        Assert.AreEqual(0, source.GetTotalDisplayedValue(), "Every displayed chip is taken");
        Assert.AreEqual(60, raise.GetTotalDisplayedValue(),
            "The chips undershoot the 62 stack by the unrepresentable 2");
        Assert.AreEqual(62, controller._GetRepresentedRaiseValue(),
            "Taking every remaining chip must force the exact all-in wager");
        Assert.IsTrue(game.IsValidBet(62, 0), "A short all-in is always legal");

        GameObject targetObject = Spawn("BetTarget");
        BoxCollider target = targetObject.AddComponent<BoxCollider>();
        target.size = Vector3.one;
        controller.targetCollider = target;
        raise.transform.position = target.bounds.center;
        VrcRuntimeFake.SetPrivate(controller, "state", 3);

        InvokePrivate("Update");
        controller._ResolvePhysicalDrop();

        Assert.AreEqual(62, player.bet, "The whole pile must be bettable despite the minimum denomination");
        Assert.AreEqual(game.epoch, player.committedEpoch);
    }

    [Test]
    public void TriggerAdds_GrowRepresentedRaiseAndFlipToAllInWhenSourceDrains()
    {
        game.stacks[0] = 262;
        game.currentBet = 0;
        game.minimumRaise = 100;
        player.bet = player.GetPhysicalCallAmount();
        source.SetTotalChips(262);
        raise.SetTotalChips(0);

        Assert.IsTrue(BeginReservation(0, 0, 10));
        Assert.AreEqual(100, raise.GetTotalDisplayedValue());
        Assert.AreEqual(100, controller._GetRepresentedRaiseValue());

        VrcRuntimeFake.SetPrivate(controller, "state", 3);
        VrcRuntimeFake.SetPrivate(controller, "holdingHand", 0);
        SetPreview(1, 0, 6);
        Assert.IsTrue(InvokeApplyPreviewIncrease());
        Assert.AreEqual(250, raise.GetTotalDisplayedValue());
        Assert.AreEqual(250, controller._GetRepresentedRaiseValue());
        Assert.AreEqual(10, source.GetTotalDisplayedValue());

        SetPreview(0, 0, 2);
        Assert.IsTrue(InvokeApplyPreviewIncrease());
        Assert.AreEqual(0, source.GetTotalDisplayedValue());
        Assert.AreEqual(260, raise.GetTotalDisplayedValue());
        Assert.AreEqual(262, controller._GetRepresentedRaiseValue(),
            "Draining the source with trigger adds must flip to the exact all-in");
    }

    [Test]
    public void HeldReadoutAndStackFormula_UseTheRepresentedRaise()
    {
        game.stacks[0] = 6000;
        game.currentBet = 100;
        game.minimumRaise = 125;
        player.bet = player.GetPhysicalCallAmount();
        source.SetTotalChips(5900);
        raise.SetTotalChips(0);

        Assert.IsTrue(BeginReservation(2, 0, 1));

        Assert.AreEqual(125, controller._GetRepresentedRaiseValue());
        Assert.AreEqual("125", raise.text.text);
        Assert.IsTrue(controller.HasVisualReservationForEpoch(game.epoch));
        Assert.AreEqual(5775, game.stacks[0] - player.GetPhysicalCallAmount()
            - controller._GetRepresentedRaiseValue(),
            "The stack readout must equal stack - call - grabbed raise");

        VrcRuntimeFake.SetPrivate(controller, "state", 3);
        InvokePrivate("HideHover");
        Assert.AreEqual("125", raise.text.text,
            "HideHover must keep showing the represented raise, not the chip approximation");
    }

    [Test]
    public void RemoteMirror_MaterializesSpawnedTopUpAndRespectsEpoch()
    {
        game.stacks[0] = 6000;
        game.currentBet = 0;
        game.minimumRaise = 125;
        player.bet = player.GetPhysicalCallAmount();
        source.SetTotalChips(6000);
        raise.SetTotalChips(0);

        VrcRuntimeFake.SetPrivate(controller, "syncedRaiseCounts", new int[] { 0, 1, 1, 0, 0 });
        VrcRuntimeFake.SetPrivate(controller, "syncedReservationEpoch", game.epoch);
        VrcRuntimeFake.SetPrivate(controller, "syncedRepresentedBet", 125);
        VrcRuntimeFake.SetPrivate(controller, "syncedSourceBaseline", 6000);
        VrcRuntimeFake.SetPrivate(controller, "syncedDisposition", 1);
        VrcRuntimeFake.SetPrivate(controller, "syncedReservationVersion", 9);

        InvokePrivate("TryApplySynchronizedReservation");

        Assert.AreEqual(125, raise.GetTotalDisplayedValue(),
            "Remote clients must spawn the 25 the owner topped up with");
        Assert.AreEqual(1, raise.GetDisplayedDenominationCount(1));
        Assert.AreEqual(5900, source.GetTotalDisplayedValue());
        Assert.AreEqual(125, controller._GetRepresentedRaiseValue());
        Assert.AreEqual("125", raise.text.text);
        Assert.IsTrue(controller.HasVisualReservationForEpoch(game.epoch));
        Assert.IsFalse(controller.HasVisualReservationForEpoch(game.epoch + 1),
            "A stale-epoch reservation must not own the stack display");
    }

    [Test]
    public void RemoteConsumedWindow_KeepsExposedRaiseUntilEpochAdvances()
    {
        game.stacks[0] = 6000;
        game.currentBet = 100;
        game.minimumRaise = 125;
        player.bet = 227;
        source.SetTotalChips(5775);
        raise.SetTotalChips(125);

        VrcRuntimeFake.SetPrivate(controller, "syncedRaiseCounts", new int[] { 0, 1, 1, 0, 0 });
        VrcRuntimeFake.SetPrivate(controller, "syncedReservationEpoch", game.epoch);
        VrcRuntimeFake.SetPrivate(controller, "syncedRepresentedBet", 227);
        VrcRuntimeFake.SetPrivate(controller, "syncedSourceBaseline", 5775);
        VrcRuntimeFake.SetPrivate(controller, "syncedDisposition", 3);
        VrcRuntimeFake.SetPrivate(controller, "syncedReservationVersion", 11);

        InvokePrivate("TryApplySynchronizedReservation");

        Assert.AreEqual(0, raise.GetTotalDisplayedValue(), "The consumed reservation must release its chips");
        Assert.AreEqual(127, controller._GetRepresentedRaiseValue(),
            "Remote viewers have no actionTaken flag; the committed raise must stay exposed");
        Assert.AreEqual(5773, game.stacks[0] - player.GetPhysicalCallAmount()
            - controller._GetRepresentedRaiseValue(),
            "The viewer stack readout must equal stack - call - committed raise");
        Assert.IsTrue(controller.HasVisualReservationForEpoch(game.epoch));

        VrcRuntimeFake.SetPrivate(controller, "syncedReservationEpoch", game.epoch + 1);
        Assert.IsFalse(controller.HasVisualReservationForEpoch(game.epoch),
            "Once the epoch moves past the commit the exposure must end");
    }

    [Test]
    public void StaticPotPiles_CommitStillUsesRepresentedRaise()
    {
        game.stacks[0] = 6000;
        game.currentBet = 0;
        game.minimumRaise = 127;
        game.animatedChipContainersEnabled = false;
        player.bet = player.GetPhysicalCallAmount();
        source.SetTotalChips(6000);
        raise.SetTotalChips(0);
        PokerChipPile contribution = BuildPile("ContributionPile",
            new int[] { 5, 25, 100, 500, 2500 }, source.denominationPools, false);
        player.roundContributionPile = contribution;

        Assert.IsTrue(BeginReservation(2, 0, 1));
        Assert.AreEqual(127, controller._GetRepresentedRaiseValue());

        GameObject targetObject = Spawn("BetTarget");
        BoxCollider target = targetObject.AddComponent<BoxCollider>();
        target.size = Vector3.one;
        controller.targetCollider = target;
        raise.transform.position = target.bounds.center;
        VrcRuntimeFake.SetPrivate(controller, "state", 3);

        InvokePrivate("Update");
        controller._ResolvePhysicalDrop();

        Assert.AreEqual(127, player.bet,
            "Static pot piles must commit the exact represented raise, not the chip approximation");
        Assert.AreEqual(game.epoch, player.committedEpoch);
        Assert.AreEqual(0, raise.GetTotalDisplayedValue(),
            "Without animated containers the raise chips return to their pools");
        Assert.AreEqual(0, contribution.GetTotalDisplayedValue(),
            "Static pot piles must not gather chips into the contribution pile");
    }

    [Test]
    public void LegacyBettingSystem_CannotGrabAndReportsNoReservation()
    {
        player.SetPhysicalBettingEnabled(false);

        Assert.IsFalse((bool)typeof(PhysicalRaisePile).GetMethod("CanHandleChips",
            BindingFlags.Instance | BindingFlags.NonPublic).Invoke(controller, null),
            "The old betting system must not handle physical chips");
        Assert.IsFalse((bool)typeof(PhysicalRaisePile).GetMethod("CanBetNow",
            BindingFlags.Instance | BindingFlags.NonPublic).Invoke(controller, null));
        Assert.AreEqual(0, controller._GetRepresentedRaiseValue());
        Assert.IsFalse(controller.HasVisualReservationForEpoch(game.epoch));
        Assert.AreEqual(0, raise.GetTotalDisplayedValue());
        Assert.AreEqual(400, source.GetTotalDisplayedValue(),
            "The stack must remain untouched without physical betting");
    }

    [Test]
    public void UiModeViewer_DuringRemoteRaise_DoesNotFightTheReservationForTheSourcePile()
    {
        game.stacks[0] = 6000;
        game.minimumRaise = 125;
        BuildSeatUi();
        source.SetTotalChips(5900);
        runtime.Owners[player.gameObject] = VrcRuntimeFake.MakePlayer(8, "Remote", false);
        player.SetPhysicalBettingEnabled(false);

        VrcRuntimeFake.SetPrivate(controller, "syncedRaiseCounts", new int[] { 0, 1, 1, 0, 0 });
        VrcRuntimeFake.SetPrivate(controller, "syncedReservationEpoch", game.epoch);
        VrcRuntimeFake.SetPrivate(controller, "syncedRepresentedBet", 125);
        VrcRuntimeFake.SetPrivate(controller, "syncedSourceBaseline", 5900);
        VrcRuntimeFake.SetPrivate(controller, "syncedDisposition", 1);
        VrcRuntimeFake.SetPrivate(controller, "syncedReservationVersion", 5);
        InvokePrivate("TryApplySynchronizedReservation");

        Assert.AreEqual(125, raise.GetTotalDisplayedValue());
        Assert.AreEqual(5800, source.GetTotalDisplayedValue(),
            "The mirrored reservation leaves the baseline minus the grabbed held chips");
        Assert.IsTrue(controller.HasVisualReservationForEpoch(game.epoch));

        InvokeRefreshSeatUi(HoldemGame.TABLE_PLAYING);

        Assert.AreEqual(5800, source.GetTotalDisplayedValue(),
            "A UI-mode viewer must not re-render the source pile out from under the reservation");
        Assert.AreEqual("5775", source.text.text,
            "The viewer's stack readout must show stack - call - represented raise");
        Assert.AreEqual("100 (Call)", player.betPile.text.text);
    }

    [Test]
    public void UiModeViewer_AfterRemoteCommit_ShowsCommittedBetUntilEpochAdvances()
    {
        game.stacks[0] = 6000;
        game.minimumRaise = 125;
        BuildSeatUi();
        runtime.Owners[player.gameObject] = VrcRuntimeFake.MakePlayer(8, "Remote", false);
        player.SetPhysicalBettingEnabled(false);
        player.bet = 225;
        source.SetTotalChips(5800);

        VrcRuntimeFake.SetPrivate(controller, "syncedRaiseCounts", new int[] { 0, 1, 1, 0, 0 });
        VrcRuntimeFake.SetPrivate(controller, "syncedReservationEpoch", game.epoch);
        VrcRuntimeFake.SetPrivate(controller, "syncedRepresentedBet", 225);
        VrcRuntimeFake.SetPrivate(controller, "syncedSourceBaseline", 5900);
        VrcRuntimeFake.SetPrivate(controller, "syncedDisposition", 3);
        VrcRuntimeFake.SetPrivate(controller, "syncedReservationVersion", 5);
        InvokePrivate("TryApplySynchronizedReservation");

        InvokeRefreshSeatUi(HoldemGame.TABLE_PLAYING);

        Assert.AreEqual("5775", source.text.text,
            "The committed window must show stack - committed bet");
        Assert.AreEqual("225 (Raise)", player.betPile.text.text,
            "The committed window must show the synced bet, not the pending call");
    }

    [Test]
    public void PhysicalModeRaiser_HoldDisplay_UsesRepresentedRaiseInSeatUi()
    {
        game.stacks[0] = 6000;
        game.minimumRaise = 125;
        BuildSeatUi();
        source.SetTotalChips(5900);

        Assert.IsTrue(BeginReservation(2, 0, 1));

        InvokeRefreshSeatUi(HoldemGame.TABLE_PLAYING);

        Assert.AreEqual("5775", source.text.text,
            "The raiser's own stack readout must be the exact number, not the chip approximation");
        Assert.AreEqual("100 (Call)", player.betPile.text.text);
    }

    [Test]
    public void UiModeBetting_NoReservation_KeepsLegacyBetDisplay()
    {
        BuildSeatUi();
        player.SetPhysicalBettingEnabled(false);
        player.bet = 150;

        InvokeRefreshSeatUi(HoldemGame.TABLE_PLAYING);

        Assert.AreEqual("350", source.text.text);
        Assert.AreEqual("150 (+50 to min-raise)", player.betPile.text.text);
    }

    private void BuildSeatUi()
    {
        player.uiJoinLeaveButton = Spawn("JoinLeaveButton").AddComponent<HoldButton>();
        player.uiJoinLeaveText = Spawn("JoinLeaveText").AddComponent<TMPro.TextMeshPro>();
        player.uiBestHand = Spawn("BestHand").AddComponent<UnityEngine.UI.Text>();
        player.dealerIndicator = Spawn("DealerIndicator");
        player.bettingUi = Spawn("BettingUi").AddComponent<BettingUi>();
        // Leaving physical mode on a live turn rebuilds the legacy buttons, which needs (empty) arrays to iterate.
        player.bettingUi.buttons = new GameObject[0];
        player.bettingUi.positions = new Transform[0];
        player.bettingUi.denominations = new int[0];
        player.statusBar = Spawn("StatusBar").AddComponent<MeshLoadingBar>();
        player.betPile = BuildPile("BetPile", new int[] { 5, 25, 100, 500, 2500 }, source.denominationPools, false);
        player.checkObject = Spawn("Check");
        player.goRespawnHandUi = Spawn("RespawnHandUi");
        player.goCardHighlight = Spawn("CardHighlight");
        player.grabbableHand = Spawn("Hand").AddComponent<GrabbableHand>();
    }

    private void InvokeRefreshSeatUi(int ts)
    {
        typeof(HoldemPlayer).GetMethod("RefreshSeatUi", BindingFlags.Instance | BindingFlags.NonPublic)
            .Invoke(player, new object[] { ts });
    }

    private void SetPreview(int denomination, int column, int count)
    {
        VrcRuntimeFake.SetPrivate(controller, "previewHand", 0);
        VrcRuntimeFake.SetPrivate(controller, "previewDenomination", denomination);
        VrcRuntimeFake.SetPrivate(controller, "previewColumn", column);
        VrcRuntimeFake.SetPrivate(controller, "previewCount", count);
    }

    private bool InvokeApplyPreviewIncrease()
    {
        return (bool)typeof(PhysicalRaisePile).GetMethod("ApplyPreviewIncrease",
            BindingFlags.Instance | BindingFlags.NonPublic).Invoke(controller, null);
    }

    [Test]
    public void HoverHighlight_NothingSelected_EnablesEveryChipOfTheHoveredPile()
    {
        Renderer[] proxies = BuildHighlightChips(source.stackHeight);
        for (int denomination = 0; denomination < source.denominationValues.Length; denomination++)
        {
            int chips = source.GetDenominationColumnChipCount(denomination, 0);
            if (chips <= 0) continue;

            HoverOver(denomination, 0, 0f);

            Assert.AreEqual(chips, EnabledCount(proxies), "denomination " + denomination);
            AssertOnRealChips(proxies, denomination, 0);
        }
    }

    [Test]
    public void HoverHighlight_SwitchesFromPileToPileWithTheHoverPosition()
    {
        Renderer[] proxies = BuildHighlightChips(source.stackHeight);
        source.SetTotalChips(1200);
        int first = FirstDenominationWithChips(0);
        int second = FirstDenominationWithChips(first + 1);
        Assert.GreaterOrEqual(first, 0);
        Assert.Greater(second, first, "The fixture needs two piles of different denominations");

        HoverOver(first, 0, 0f);
        Assert.AreEqual(source.GetDenominationColumnChipCount(first, 0), EnabledCount(proxies));
        AssertOnRealChips(proxies, first, 0);

        HoverOver(second, 0, 0f);
        Assert.AreEqual(source.GetDenominationColumnChipCount(second, 0), EnabledCount(proxies));
        AssertOnRealChips(proxies, second, 0);

        HoverOver(first, 0, 0f);
        Assert.AreEqual(source.GetDenominationColumnChipCount(first, 0), EnabledCount(proxies));
        AssertOnRealChips(proxies, first, 0);
    }

    [Test]
    public void HoverHighlight_MultiplePilesOfTheSameDenominationFollowTheirOwnColumn()
    {
        Renderer[] proxies = BuildHighlightChips(source.stackHeight);
        source.SetTotalChips(3000);
        int denomination = -1;
        for (int i = 0; i < source.denominationValues.Length; i++)
        {
            if (source.GetDenominationColumnCount(i) < 2) continue;
            denomination = i;
            break;
        }
        Assert.GreaterOrEqual(denomination, 0, "The fixture needs a denomination split over several piles");
        int columns = source.GetDenominationColumnCount(denomination);

        for (int pass = 0; pass < 2; pass++)
        {
            for (int column = 0; column < columns; column++)
            {
                HoverOver(denomination, column, 0f);

                Assert.AreEqual(source.GetDenominationColumnChipCount(denomination, column), EnabledCount(proxies),
                    "column " + column + ", pass " + pass);
                AssertOnRealChips(proxies, denomination, column);
            }
        }

        int shortColumn = columns - 1;
        int fullColumn = 0;
        HoverOver(denomination, shortColumn, 0f);
        int shortCount = EnabledCount(proxies);
        HoverOver(denomination, fullColumn, 0f);
        Assert.AreEqual(source.GetDenominationColumnChipCount(denomination, fullColumn), EnabledCount(proxies));
        Assert.GreaterOrEqual(EnabledCount(proxies), shortCount,
            "The partial last pile must not leave extra chips enabled when moving back to a full pile");
    }

    // ---- selection-aware highlight ----

    private void FindColumnWithAtLeast(int chips, out int denomination, out int column)
    {
        source.SetTotalChips(3000);
        for (int d = 0; d < source.denominationValues.Length; d++)
            for (int c = 0; c < source.GetDenominationColumnCount(d); c++)
                if (source.GetDenominationColumnChipCount(d, c) >= chips) { denomination = d; column = c; return; }
        Assert.Fail("The fixture needs a column with at least " + chips + " chips");
        denomination = -1;
        column = -1;
    }

    private static void AssertMaterials(Renderer renderer, params Material[] expected)
    {
        Material[] actual = renderer.sharedMaterials;
        Assert.AreEqual(expected.Length, actual.Length, renderer.name + " material count");
        for (int i = 0; i < expected.Length; i++) Assert.AreSame(expected[i], actual[i], renderer.name + " material " + i);
    }

    [Test]
    public void HoverHighlight_NothingSelected_UsesTheInvisibleMaterialOnTheWholeColumn()
    {
        Renderer[] proxies = BuildHighlightChips(source.stackHeight);
        int denomination, column;
        FindColumnWithAtLeast(3, out denomination, out column);
        int chips = source.GetDenominationColumnChipCount(denomination, column);

        HoverOver(denomination, column, 0f);

        Assert.AreEqual(0, VrcRuntimeFake.GetPrivate(controller, "previewCount"));
        Assert.AreEqual(chips, EnabledCount(proxies));
        AssertOnRealChips(proxies, denomination, column);
        for (int i = 0; i < chips; i++) AssertMaterials(proxies[i], idleMaterial);
    }

    [Test]
    public void HoverHighlight_SelectionEnablesOnlyTheTopSelectedChips()
    {
        Renderer[] proxies = BuildHighlightChips(source.stackHeight);
        int denomination, column;
        FindColumnWithAtLeast(3, out denomination, out column);
        int chips = source.GetDenominationColumnChipCount(denomination, column);

        HoverOver(denomination, column, 2.25f); // 3 chips selected

        Assert.AreEqual(3, VrcRuntimeFake.GetPrivate(controller, "previewCount"));
        Assert.AreEqual(3, EnabledCount(proxies));
        AssertOnRealChips(proxies, denomination, column, chips - 3);
        for (int i = chips - 3; i < chips; i++) AssertMaterials(proxies[i], fillMaterial, outlineMaterial);
    }

    [Test]
    public void HoverHighlight_SelectingTheWholeColumnHighlightsEveryChip()
    {
        Renderer[] proxies = BuildHighlightChips(source.stackHeight);
        int denomination, column;
        FindColumnWithAtLeast(3, out denomination, out column);
        int chips = source.GetDenominationColumnChipCount(denomination, column);

        HoverOver(denomination, column, chips - 0.75f);

        Assert.AreEqual(chips, VrcRuntimeFake.GetPrivate(controller, "previewCount"));
        Assert.AreEqual(chips, EnabledCount(proxies));
        AssertOnRealChips(proxies, denomination, column);
        for (int i = 0; i < chips; i++) AssertMaterials(proxies[i], fillMaterial, outlineMaterial);
    }

    [Test]
    public void HoverHighlight_LoweringTheHandGrowsTheHighlightDownwardFromTheTop()
    {
        Renderer[] proxies = BuildHighlightChips(source.stackHeight);
        int denomination, column;
        FindColumnWithAtLeast(4, out denomination, out column);
        int chips = source.GetDenominationColumnChipCount(denomination, column);

        for (int selected = 1; selected <= 4; selected++)
        {
            HoverOver(denomination, column, selected - 0.75f);
            Assert.AreEqual(selected, EnabledCount(proxies), selected + " selected");
            AssertOnRealChips(proxies, denomination, column, chips - selected);
        }
    }

    [Test]
    public void HoverHighlight_MovingBetweenNothingAndSomethingSelectedSwapsTheMaterials()
    {
        Renderer[] proxies = BuildHighlightChips(source.stackHeight);
        int denomination, column;
        FindColumnWithAtLeast(3, out denomination, out column);
        int chips = source.GetDenominationColumnChipCount(denomination, column);

        HoverOver(denomination, column, 0f);
        HoverOver(denomination, column, 1.25f);
        HoverOver(denomination, column, 0f);

        Assert.AreEqual(chips, EnabledCount(proxies));
        for (int i = 0; i < chips; i++) AssertMaterials(proxies[i], idleMaterial);

        HoverOver(denomination, column, 1.25f);
        for (int i = chips - 2; i < chips; i++) AssertMaterials(proxies[i], fillMaterial, outlineMaterial);
    }

    [Test]
    public void HoverHighlight_ProxiesFollowTheRealChipsYawNotAFixedRotation()
    {
        Renderer[] proxies = BuildHighlightChips(source.stackHeight);
        int denomination, column;
        FindColumnWithAtLeast(3, out denomination, out column);
        int chips = source.GetDenominationColumnChipCount(denomination, column);

        HoverOver(denomination, column, chips - 0.75f);

        bool anyYawDiffers = false;
        for (int i = 0; i < chips; i++)
        {
            Transform real = RealChip(denomination, column * source.stackHeight + i);
            Assert.AreEqual(0f, Quaternion.Angle(real.rotation, proxies[i].transform.rotation), 0.01f,
                "proxy " + i + " rotation vs the real chip");
            Assert.AreEqual(0f, Vector3.Distance(real.position, proxies[i].transform.position), 0.0001f,
                "proxy " + i + " position vs the real chip");
            if (i > 0 && Quaternion.Angle(proxies[0].transform.rotation, proxies[i].transform.rotation) > 1f)
                anyYawDiffers = true;
        }
        Assert.IsTrue(anyYawDiffers, "The fixture's chips should not all share one yaw");
    }

    [Test]
    public void HoverHighlight_DisablesEveryProxyChipWhenNothingIsHovered()
    {
        Renderer[] proxies = BuildHighlightChips(source.stackHeight);
        HoverOver(0, 0);
        Assert.Greater(EnabledCount(proxies), 0);

        Vector3 away = new Vector3(50f, 50f, 50f);
        runtime.SetTrackingPosition(runtime.LocalPlayer, VRC.SDKBase.VRCPlayerApi.TrackingDataType.LeftHand, away);
        runtime.SetTrackingPosition(runtime.LocalPlayer, VRC.SDKBase.VRCPlayerApi.TrackingDataType.RightHand, away);
        InvokePrivate("UpdateHover");

        Assert.AreEqual(0, EnabledCount(proxies));
    }

    // Holding the raise: the hovered chips the hand would add still glow, but nothing shows for an empty selection.
    private void HoldRaiseWithHand()
    {
        VrcRuntimeFake.SetPrivate(controller, "state", 3);
        VrcRuntimeFake.SetPrivate(controller, "holdingHand", 0);
    }

    [Test]
    public void HoverHighlight_WhileHolding_ShowsTheSelectedChipsWithTheHighlightMaterials()
    {
        Renderer[] proxies = BuildHighlightChips(source.stackHeight);
        int denomination, column;
        FindColumnWithAtLeast(3, out denomination, out column);
        int chips = source.GetDenominationColumnChipCount(denomination, column);
        HoverOver(denomination, column, 0f);
        HoldRaiseWithHand();

        Vector3 hand = HandInsideColumn(denomination, column, 1.25f); // 2 chips selected
        runtime.SetTrackingPosition(runtime.LocalPlayer, VRC.SDKBase.VRCPlayerApi.TrackingDataType.LeftHand, hand);
        runtime.SetTrackingPosition(runtime.LocalPlayer, VRC.SDKBase.VRCPlayerApi.TrackingDataType.RightHand,
            hand + Vector3.right * 10f);
        InvokePrivate("UpdateHover");

        Assert.AreEqual(2, VrcRuntimeFake.GetPrivate(controller, "previewCount"));
        Assert.AreEqual(2, EnabledCount(proxies));
        AssertOnRealChips(proxies, denomination, column, chips - 2);
        for (int i = chips - 2; i < chips; i++) AssertMaterials(proxies[i], fillMaterial, outlineMaterial);
    }

    [Test]
    public void HoverHighlight_WhileHolding_ShowsNothingWhenNoChipsAreSelected()
    {
        Renderer[] proxies = BuildHighlightChips(source.stackHeight);
        HoverOver(0, 0, 0f);
        Assert.Greater(EnabledCount(proxies), 0);
        HoldRaiseWithHand();

        Vector3 hand = HandInsideColumn(0, 0, 0f);
        runtime.SetTrackingPosition(runtime.LocalPlayer, VRC.SDKBase.VRCPlayerApi.TrackingDataType.LeftHand, hand);
        runtime.SetTrackingPosition(runtime.LocalPlayer, VRC.SDKBase.VRCPlayerApi.TrackingDataType.RightHand,
            hand + Vector3.right * 10f);
        InvokePrivate("UpdateHover");

        Assert.AreEqual(0, EnabledCount(proxies));
    }

    private Renderer[] BuildHighlightChips(int count)
    {
        var proxies = new Renderer[count];
        for (int i = 0; i < count; i++)
        {
            GameObject chip = Spawn("HighlightChip" + i);
            chip.transform.SetParent(controller.transform, false);
            MeshRenderer renderer = chip.AddComponent<MeshRenderer>();
            renderer.enabled = false;
            proxies[i] = renderer;
        }
        controller.highlightChips = proxies;
        idleMaterial = new Material(Shader.Find("Hidden/InternalErrorShader")) { name = "Idle" };
        fillMaterial = new Material(Shader.Find("Hidden/InternalErrorShader")) { name = "Fill" };
        outlineMaterial = new Material(Shader.Find("Hidden/InternalErrorShader")) { name = "Outline" };
        controller.highlightIdleMaterials = new[] { idleMaterial };
        controller.highlightSelectedMaterials = new[] { fillMaterial, outlineMaterial };
        for (int i = 0; i < count; i++) proxies[i].sharedMaterials = controller.highlightIdleMaterials;
        return proxies;
    }

    private void HoverOver(int denomination, int column)
    {
        HoverOver(denomination, column, 0.25f);
    }

    // chipDepth 0 puts the hand at the column top (nothing selected); N - 0.75 selects N chips from the top.
    private void HoverOver(int denomination, int column, float chipDepth)
    {
        Vector3 hand = HandInsideColumn(denomination, column, chipDepth);
        runtime.SetTrackingPosition(runtime.LocalPlayer, VRC.SDKBase.VRCPlayerApi.TrackingDataType.LeftHand, hand);
        runtime.SetTrackingPosition(runtime.LocalPlayer, VRC.SDKBase.VRCPlayerApi.TrackingDataType.RightHand,
            hand + Vector3.right * 10f);
        InvokePrivate("UpdateHover");
        Assert.AreEqual(denomination, VrcRuntimeFake.GetPrivate(controller, "previewDenomination"));
        Assert.AreEqual(column, VrcRuntimeFake.GetPrivate(controller, "previewColumn"));
    }

    private int FirstDenominationWithChips(int start)
    {
        for (int i = Mathf.Max(0, start); i < source.denominationValues.Length; i++)
            if (source.GetDenominationColumnChipCount(i, 0) > 0) return i;
        return -1;
    }

    private static int EnabledCount(Renderer[] proxies)
    {
        int enabled = 0;
        for (int i = 0; i < proxies.Length; i++) if (proxies[i].enabled) enabled++;
        return enabled;
    }

    // Proxy i must sit exactly on the real chip at height i of the column (same position and yaw). `firstEnabled`
    // is the lowest proxy that should be on; the ones below it must be off.
    private void AssertOnRealChips(Renderer[] proxies, int denomination, int column, int firstEnabled = 0)
    {
        int chips = source.GetDenominationColumnChipCount(denomination, column);
        for (int i = 0; i < proxies.Length; i++)
        {
            Assert.AreEqual(i >= firstEnabled && i < chips, proxies[i].enabled, "proxy " + i + " of " + chips);
            if (!proxies[i].enabled) continue;
            Vector3 expectedPosition = source.GetDenominationColumnChipWorldPosition(denomination, column, i);
            Quaternion expectedRotation = source.GetDenominationColumnChipWorldRotation(denomination, column, i);
            Assert.AreEqual(0f, Vector3.Distance(expectedPosition, proxies[i].transform.position), 0.0001f,
                "proxy " + i + " position");
            Assert.AreEqual(0f, Quaternion.Angle(expectedRotation, proxies[i].transform.rotation), 0.01f,
                "proxy " + i + " rotation");
        }
    }

    private Transform RealChip(int denomination, int chipIndex)
    {
        GameObject[] held = (GameObject[])VrcRuntimeFake.GetPrivate(source, "heldChips");
        int capacity = (int)VrcRuntimeFake.GetPrivate(source, "denomCapacity");
        return held[denomination * capacity + chipIndex].transform;
    }

    private bool BeginReservation(int denomination, int column, int count)
    {
        MethodInfo method = typeof(PhysicalRaisePile).GetMethod("BeginReservation",
            BindingFlags.Instance | BindingFlags.NonPublic);
        return (bool)method.Invoke(controller, new object[] { denomination, column, count });
    }

    private Vector3 HandInsideColumn(int denomination, int column, float chipDepth)
    {
        Vector3 target = source.GetDenominationColumnWorldPosition(denomination, column);
        target.y = source.GetDenominationColumnTopWorldY(denomination, column)
            - source.chipHeight * Mathf.Abs(source.transform.lossyScale.y) * chipDepth;
        // The fake tracking rotation is identity, so the hand point is hand + handOffset.
        return target - controller.handOffset;
    }

    private void InvokePrivate(string name, params object[] args)
    {
        typeof(PhysicalRaisePile).GetMethod(name, BindingFlags.Instance | BindingFlags.NonPublic)
            .Invoke(controller, args);
    }

    private PokerChipPile BuildPile(string name, int[] values, LocalObjectPool[] pools, bool selectable)
    {
        GameObject go = Spawn(name);
        PokerChipPile pile = go.AddComponent<PokerChipPile>();
        pile.denominationValues = values;
        pile.denominationPools = pools;
        pile.supportsSelectableStackMode = selectable;
        pile.stackHeight = 10;
        pile.denominationOffsets = new[]
        {
            new Vector3(-0.12f, 0f, 0f), new Vector3(-0.06f, 0f, 0f), Vector3.zero,
            new Vector3(0.06f, 0f, 0f), new Vector3(0.12f, 0f, 0f)
        };
        GameObject readout = Spawn(name + "Readout");
        readout.transform.SetParent(go.transform);
        pile.text = readout.AddComponent<TMPro.TextMeshPro>();
        pile.textGameObject = readout;
        VrcRuntimeFake.InvokeNoArg(pile, "Start");
        return pile;
    }

    private LocalObjectPool[] BuildPools(int[] values, int capacity)
    {
        var pools = new LocalObjectPool[values.Length];
        for (int denomination = 0; denomination < values.Length; denomination++)
        {
            GameObject poolObject = Spawn("Pool" + values[denomination]);
            LocalObjectPool pool = poolObject.AddComponent<LocalObjectPool>();
            pool.denomination = values[denomination];
            pool.Pool = new GameObject[capacity];
            for (int chip = 0; chip < capacity; chip++)
            {
                GameObject chipObject = Spawn("Chip" + values[denomination] + "_" + chip);
                chipObject.transform.SetParent(poolObject.transform);
                pool.Pool[chip] = chipObject;
            }
            VrcRuntimeFake.InvokeNoArg(pool, "Start");
            pools[denomination] = pool;
        }
        return pools;
    }

    private GameObject Spawn(string name)
    {
        GameObject go = new GameObject(name);
        objects.Add(go);
        return go;
    }


[Test]
    public void ThirteenChips_WithTenChipStack_CapsEachColumnByConfiguredStackCapacity()
    {
        const int totalChips = 13;
        const int maxStackedChips = 10;
        Assert.AreEqual(10, PhysicalRaiseSelectionMath.ChipsInColumn(totalChips, 0, maxStackedChips));
        Assert.AreEqual(3, PhysicalRaiseSelectionMath.ChipsInColumn(totalChips, 1, maxStackedChips));
        Assert.AreEqual(0, PhysicalRaiseSelectionMath.ChipsInColumn(totalChips, 2, maxStackedChips));
        Assert.AreEqual(10, PhysicalRaiseSelectionMath.SelectionCount(
            0.03f, -1f, 0.003f, 13, maxStackedChips));
    }

    // ---- Immersive betting feedback round: readout, buy-in, blind-adjusted commits, haptics, colliders, layout ----

    /// <summary>The readout as in the prefab: a child of the pickup, which is rotated and scaled non-uniformly.</summary>
    private Transform BuildReadout()
    {
        Transform readout = Spawn("Readout").transform;
        readout.SetParent(controller.transform, false);
        controller.transform.SetPositionAndRotation(new Vector3(3f, 0.5f, -2f), Quaternion.Euler(20f, 130f, 35f));
        controller.transform.localScale = new Vector3(1f, 1.5f, 0.8f);
        controller.readout = readout;
        return readout;
    }

    private LookAtPlayerYawOnly BuildReadoutLookAt(Transform readout)
    {
        LookAtPlayerYawOnly look = readout.gameObject.AddComponent<LookAtPlayerYawOnly>();
        look.followPlayerGaze = true;
        raise.lookAtPlayer = look;
        VrcRuntimeFake.InvokeNoArg(look, "Start");
        return look;
    }

    /// <summary>One VRChat frame in engine order; the last Post-LateUpdate writer wins.</summary>
    private void RunFrame(LookAtPlayerYawOnly look, bool lookRunsFirst)
    {
        InvokePrivate("Update");
        for (int i = 0; i < 3; i++)
        {
            if (lookRunsFirst) { if (look != null) look.PostLateUpdate(); controller.PostLateUpdate(); }
            else { controller.PostLateUpdate(); if (look != null) look.PostLateUpdate(); }
        }
    }

    private void UseRightHand(Vector3 position, Quaternion rotation)
    {
        runtime.SetTrackingPosition(runtime.LocalPlayer, VRCPlayerApi.TrackingDataType.RightHand, position);
        runtime.SetTrackingRotation(runtime.LocalPlayer, VRCPlayerApi.TrackingDataType.RightHand, rotation);
        VrcRuntimeFake.SetPrivate(controller, "holdingHand", 1);
    }

    private static void AssertPose(Transform readout, Vector3 position, Quaternion rotation, string message)
    {
        Assert.AreEqual(position.x, readout.position.x, 0.0001f, message + " (x)");
        Assert.AreEqual(position.y, readout.position.y, 0.0001f, message + " (y)");
        Assert.AreEqual(position.z, readout.position.z, 0.0001f, message + " (z)");
        Assert.Less(Quaternion.Angle(rotation, readout.rotation), 0.1f, message + " (rotation)");
    }

    [Test]
    public void Readout_SitsStraightUpFromTheHandInWorldSpace_WhateverThePickupOrHandDoes()
    {
        Transform readout = BuildReadout();
        Vector3 hand = new Vector3(1f, 1.2f, -0.3f);
        UseRightHand(hand, Quaternion.Euler(70f, 25f, 40f));

        controller.PostLateUpdate();

        Vector3 expected = hand + Vector3.up * controller.readoutYOffset;
        AssertPose(readout, expected, readout.rotation, "hand pitched, pickup rotated and scaled");

        // The pickup keeps moving and turning; the readout must stay pinned above the hand.
        controller.transform.SetPositionAndRotation(new Vector3(-4f, 2f, 1f), Quaternion.Euler(-50f, 10f, 80f));
        controller.PostLateUpdate();
        AssertPose(readout, expected, readout.rotation, "pickup moved again");

        UseRightHand(hand + Vector3.forward * 0.4f, Quaternion.Euler(-80f, 200f, 10f));
        controller.PostLateUpdate();
        AssertPose(readout, hand + Vector3.forward * 0.4f + Vector3.up * controller.readoutYOffset,
            readout.rotation, "hand moved and turned");
    }

    [Test]
    public void Readout_LiftScalesWithAvatarEyeHeight()
    {
        Transform readout = BuildReadout();
        Vector3 hand = new Vector3(1f, 1.2f, -0.3f);
        UseRightHand(hand, Quaternion.identity);

        runtime.EyeHeight = 1.6f;
        controller.PostLateUpdate();
        AssertPose(readout, hand + Vector3.up * (controller.readoutYOffset * 2f), readout.rotation, "double size");

        runtime.EyeHeight = 0.4f;
        controller.PostLateUpdate();
        AssertPose(readout, hand + Vector3.up * (controller.readoutYOffset * 0.5f), readout.rotation, "half size");
    }

    [Test]
    public void HandOffset_ScalesWithAvatarEyeHeight()
    {
        runtime.EyeHeight = 0.8f;
        Assert.AreEqual(0f, (controller._GetScaledHandOffset() - controller.handOffset).magnitude, 0.0001f);

        runtime.EyeHeight = 1.6f;
        Assert.AreEqual(0f, (controller._GetScaledHandOffset() - controller.handOffset * 2f).magnitude, 0.0001f);
    }

    [Test]
    public void CalibratedHandOffset_ReplacesTheDefaultAndStillScales()
    {
        Vector3 calibrated = new Vector3(0.02f, 0.14f, 0.08f);
        controller.SetCalibratedHandOffset(calibrated);

        runtime.EyeHeight = 0.8f;
        Assert.AreEqual(0f, (controller._GetScaledHandOffset() - calibrated).magnitude, 0.0001f);

        runtime.EyeHeight = 0.4f;
        Assert.AreEqual(0f, (controller._GetScaledHandOffset() - calibrated * 0.5f).magnitude, 0.0001f);
    }

    [Test]
    public void ClearCalibratedHandOffset_BringsBackTheAuthoredDefault()
    {
        controller.SetCalibratedHandOffset(new Vector3(0.02f, 0.14f, 0.08f));

        controller._ClearCalibratedHandOffset();

        Assert.AreEqual(0f, (controller._GetScaledHandOffset() - controller.handOffset).magnitude, 0.0001f);
    }

    [Test]
    public void CalibratedHandOffset_IgnoresImplausibleValues()
    {
        controller.SetCalibratedHandOffset(new Vector3(0f, 5f, 0f));
        controller.SetCalibratedHandOffset(new Vector3(float.NaN, 0f, 0f));

        Assert.AreEqual(0f, (controller._GetScaledHandOffset() - controller.handOffset).magnitude, 0.0001f);
    }

    [Test]
    public void CalibratedHandOffset_DrivesTheChipCount()
    {
        controller.SetCalibratedHandOffset(new Vector3(0f, 0.2f, 0f));
        Vector3 hand = source.GetDenominationColumnWorldPosition(0, 0);
        float chip = source.chipHeight * Mathf.Abs(source.transform.lossyScale.y);
        // Hand point sits on the top chip, 2.25 chips deep, once the 0.2m calibrated offset is added.
        hand.y = source.GetDenominationColumnTopWorldY(0, 0) - chip * 2.25f - 0.2f;
        runtime.SetTrackingPosition(runtime.LocalPlayer, VRC.SDKBase.VRCPlayerApi.TrackingDataType.LeftHand, hand);
        runtime.SetTrackingPosition(runtime.LocalPlayer, VRC.SDKBase.VRCPlayerApi.TrackingDataType.RightHand,
            hand + Vector3.right * 10f);

        InvokePrivate("UpdateHover");

        Assert.AreEqual(3, VrcRuntimeFake.GetPrivate(controller, "previewCount"));
    }

    private void HoldPileOffsetFromHand(int state, Vector3 pilePosition, Vector3 handPosition)
    {
        Assert.IsTrue(BeginReservation(0, 0, 1));
        VrcRuntimeFake.SetPrivate(controller, "state", state);
        controller.transform.position = pilePosition;
        UseRightHand(handPosition, Quaternion.identity);
    }

    [Test]
    public void CarriedReadout_StaysAbovePileWhileTheHandRotatesAroundIt()
    {
        Transform readout = BuildReadout();
        Vector3 pile = new Vector3(1f, 1.2f, 0.5f);
        // The pickup is gripped away from the tracked controller origin, so turning the hand swings it around.
        HoldPileOffsetFromHand(3, pile, pile + new Vector3(0.06f, -0.03f, 0.09f));
        Vector3 expected = pile + Vector3.up * controller.readoutYOffset;

        foreach (Quaternion handRotation in new[]
        {
            Quaternion.identity, Quaternion.Euler(0f, 90f, 0f), Quaternion.Euler(70f, 200f, 30f), Quaternion.Euler(-90f, 0f, 45f)
        })
        {
            runtime.SetTrackingRotation(runtime.LocalPlayer, VRCPlayerApi.TrackingDataType.RightHand, handRotation);
            // The pickup swings with the hand; only the pile position matters to the readout.
            controller.transform.rotation = handRotation;
            controller.PostLateUpdate();
            AssertPose(readout, expected, readout.rotation, "hand rotation " + handRotation.eulerAngles);
        }

        pile += new Vector3(0.3f, 0.2f, -0.4f);
        controller.transform.position = pile;
        controller.PostLateUpdate();
        AssertPose(readout, pile + Vector3.up * controller.readoutYOffset, readout.rotation, "pile moved");
    }

    [Test]
    public void DroppedPile_ReadoutStaysAboveItWhileItFalls()
    {
        Transform readout = BuildReadout();
        Vector3 pile = new Vector3(-1f, 0.9f, 2f);
        HoldPileOffsetFromHand(4, pile, pile + Vector3.right * 0.5f);
        controller.transform.rotation = Quaternion.Euler(80f, 40f, 120f);

        controller.PostLateUpdate();

        AssertPose(readout, pile + Vector3.up * controller.readoutYOffset, readout.rotation,
            "tumbling pile must not swing the text");
    }

    [Test]
    public void Readout_PoseIsWrittenAfterThePickupMoves_NotDuringUpdate()
    {
        Transform readout = BuildReadout();
        UseRightHand(new Vector3(0.5f, 1f, 0.5f), Quaternion.identity);
        Vector3 sentinel = new Vector3(9f, 9f, 9f);
        readout.position = sentinel;

        InvokePrivate("Update");
        Assert.Less((readout.position - sentinel).magnitude, 0.001f,
            "Update runs before the pickup moves, so it must not place the readout");

        controller.PostLateUpdate();
        Assert.Greater((readout.position - sentinel).magnitude, 1f);
    }

    [Test]
    public void Readout_FacesTheViewOnEveryAxis_WhileTheHandAndPickupRotate()
    {
        Transform readout = BuildReadout();
        Quaternion head = Quaternion.Euler(35f, 200f, 20f);
        runtime.SetTrackingRotation(runtime.LocalPlayer, VRCPlayerApi.TrackingDataType.Head, head);
        Assert.IsTrue(BeginReservation(0, 0, 1));
        VrcRuntimeFake.SetPrivate(controller, "state", 3);
        UseRightHand(new Vector3(1f, 1f, 1f), Quaternion.Euler(10f, 300f, 90f));

        controller.PostLateUpdate();

        Assert.Less(Quaternion.Angle(head, readout.rotation), 0.1f,
            "The carried amount must follow pitch and roll of the view, not only yaw");
    }

    [Test]
    public void Readout_HasASingleWriter_WhateverTheScriptOrder()
    {
        Transform readout = BuildReadout();
        LookAtPlayerYawOnly look = BuildReadoutLookAt(readout);
        Quaternion head = Quaternion.Euler(-25f, 75f, 15f);
        runtime.SetTrackingRotation(runtime.LocalPlayer, VRCPlayerApi.TrackingDataType.Head, head);
        Vector3 hand = new Vector3(0.2f, 1.1f, 0.7f);
        UseRightHand(hand, Quaternion.Euler(50f, 10f, 0f));
        Vector3 expected = hand + Vector3.up * controller.readoutYOffset;

        RunFrame(look, true);
        Assert.IsTrue(look.externallyDriven, "In VR the raise pile takes ownership of the readout pose");
        AssertPose(readout, expected, head, "look-at ran before the raise pile");

        // Scramble the pose the way the pickup would, then run the opposite order.
        controller.transform.rotation = Quaternion.Euler(90f, 0f, 0f);
        readout.rotation = Quaternion.Euler(0f, 90f, 0f);
        RunFrame(look, false);
        AssertPose(readout, expected, head, "look-at ran after the raise pile");
    }

    [Test]
    public void LookAtPlayer_StandsDownWhileAnotherScriptDrivesTheTransform()
    {
        Transform readout = Spawn("Readout").transform;
        LookAtPlayerYawOnly look = readout.gameObject.AddComponent<LookAtPlayerYawOnly>();
        look.followPlayerGaze = true;
        VrcRuntimeFake.InvokeNoArg(look, "Start");
        Quaternion head = Quaternion.Euler(30f, 40f, 0f);
        runtime.SetTrackingRotation(runtime.LocalPlayer, VRCPlayerApi.TrackingDataType.Head, head);

        look.externallyDriven = true;
        readout.rotation = Quaternion.identity;
        for (int i = 0; i < 6; i++) look.PostLateUpdate();
        Assert.AreEqual(Quaternion.identity, readout.rotation);

        look.externallyDriven = false;
        for (int i = 0; i < 3; i++) look.PostLateUpdate();
        Assert.Less(Quaternion.Angle(head, readout.rotation), 0.1f);
    }

    [Test]
    public void RaisePile_NeverTogglesTheLookAtEnabledFlag()
    {
        Transform readout = BuildReadout();
        LookAtPlayerYawOnly look = BuildReadoutLookAt(readout);
        Assert.IsTrue(BeginReservation(0, 0, 1));

        foreach (bool initial in new[] { false, true })
        {
            look.enabled = initial;
            // Only the carried/committed states: idle refreshes call HideHover -> PokerChipPile.UpdateText,
            // which is the designated owner of the flag.
            foreach (int state in new[] { 3, 4, 6 })
            {
                VrcRuntimeFake.SetPrivate(controller, "state", state);
                InvokePrivate("RefreshInteraction");
                Assert.AreEqual(initial, look.enabled, "RefreshInteraction in state " + state);
            }
            InvokePrivate("Respawn");
            Assert.AreEqual(initial, look.enabled, "Respawn");
            // Start is left out: it calls HideHover -> PokerChipPile.UpdateText, the flag's designated owner.
            controller.PostLateUpdate();
            Assert.AreEqual(initial, look.enabled, "PostLateUpdate");
        }
    }

    [Test]
    public void Readout_OnDesktop_OnlyPositionsItAndLeavesRotationToTheLookAt()
    {
        runtime.VrUsers[runtime.LocalPlayer.playerId] = false;
        Transform readout = BuildReadout();
        LookAtPlayerYawOnly look = BuildReadoutLookAt(readout);
        Quaternion sentinel = Quaternion.Euler(12f, 34f, 56f);
        readout.localRotation = sentinel;

        controller.PostLateUpdate();

        Assert.IsFalse(look.externallyDriven, "Desktop keeps the look-at as the rotation owner");
        Assert.AreEqual(new Vector3(0f, 0.064f, 0f), readout.localPosition);
        Assert.Less(Quaternion.Angle(sentinel, readout.localRotation), 0.01f);
    }

    [TestCase(false)]
    [TestCase(true)]
    public void LookAtPlayer_WorldYOffset_KeepsPoseCorrectOnEveryFrameWhileTheParentTumbles(bool followGaze)
    {
        Transform readout = BuildReadout();
        LookAtPlayerYawOnly look = readout.gameObject.AddComponent<LookAtPlayerYawOnly>();
        look.useWorldYOffset = true;
        look.worldYOffset = 0.0641f;
        look.followPlayerGaze = followGaze;
        Quaternion head = Quaternion.Euler(-10f, 75f, 5f);
        Vector3 headPosition = new Vector3(4f, 1.6f, -3f);
        runtime.SetTrackingRotation(runtime.LocalPlayer, VRCPlayerApi.TrackingDataType.Head, head);
        runtime.SetTrackingPosition(runtime.LocalPlayer, VRCPlayerApi.TrackingDataType.Head, headPosition);
        VrcRuntimeFake.InvokeNoArg(look, "Start");

        // The look-at throttles itself; the grabbed pile still turns every single frame, so every frame must be right.
        for (int frame = 0; frame < 9; frame++)
        {
            controller.transform.SetPositionAndRotation(new Vector3(-1f, 1.3f, 2f) + Vector3.right * frame * 0.05f,
                Quaternion.Euler(30f + frame * 40f, frame * 55f, 20f + frame * 25f));
            look.PostLateUpdate();

            Assert.AreEqual(controller.transform.position.y + 0.0641f, readout.position.y, 0.0001f, "y, frame " + frame);
            if (followGaze)
            {
                Assert.Less(Quaternion.Angle(head, readout.rotation), 0.1f, "gaze rotation, frame " + frame);
            }
            else
            {
                Vector3 toPlayer = headPosition - readout.position;
                toPlayer.y = 0f;
                Assert.AreEqual(1f, Vector3.Dot(readout.up, Vector3.up), 0.0001f, "stays upright, frame " + frame);
                Assert.AreEqual(1f, Vector3.Dot(-readout.forward, toPlayer.normalized), 0.0001f,
                    "faces the player, frame " + frame);
            }
        }
    }

    [Test]
    public void LookAtPlayer_WorldYOffset_HoversAboveTheParentWhateverItsRotationOrScale()
    {
        Transform readout = BuildReadout();
        LookAtPlayerYawOnly look = readout.gameObject.AddComponent<LookAtPlayerYawOnly>();
        look.useWorldYOffset = true;
        look.worldYOffset = 0.0641f;
        VrcRuntimeFake.InvokeNoArg(look, "Start");

        Quaternion[] poses =
        {
            Quaternion.identity, Quaternion.Euler(90f, 0f, 0f), Quaternion.Euler(20f, 130f, 35f), Quaternion.Euler(0f, 0f, 180f)
        };
        foreach (Quaternion pose in poses)
        {
            controller.transform.SetPositionAndRotation(new Vector3(-1f, 1.3f, 2f), pose);
            look.PostLateUpdate();
            Vector3 expected = controller.transform.position + Vector3.up * 0.0641f;
            Assert.AreEqual(expected.x, readout.position.x, 0.0001f, "x for " + pose.eulerAngles);
            Assert.AreEqual(expected.y, readout.position.y, 0.0001f, "y for " + pose.eulerAngles);
            Assert.AreEqual(expected.z, readout.position.z, 0.0001f, "z for " + pose.eulerAngles);
        }
    }

    [TestCase(true)]
    [TestCase(false)]
    public void Readout_OnDesktop_HoversAlongWorldYOfThePile_WhateverTheScriptOrder(bool lookRunsFirst)
    {
        runtime.VrUsers[runtime.LocalPlayer.playerId] = false;
        Transform readout = BuildReadout();
        LookAtPlayerYawOnly look = BuildReadoutLookAt(readout);
        look.useWorldYOffset = true;
        look.worldYOffset = 0.0641f;

        for (int frame = 0; frame < 6; frame++)
        {
            controller.transform.SetPositionAndRotation(new Vector3(1f, 0.8f, -2f) + Vector3.forward * frame * 0.1f,
                Quaternion.Euler(30f + frame * 50f, frame * 40f, 70f + frame * 20f));
            RunFrame(look, lookRunsFirst);

            Vector3 expected = controller.transform.position + Vector3.up * 0.0641f;
            Assert.AreEqual(expected.x, readout.position.x, 0.0001f, "x, frame " + frame);
            Assert.AreEqual(expected.y, readout.position.y, 0.0001f, "y, frame " + frame);
            Assert.AreEqual(expected.z, readout.position.z, 0.0001f, "z, frame " + frame);
        }
    }

    [Test]
    public void Readout_IdleWithNoHandHeld_FollowsTheNearestHand()
    {
        Transform readout = BuildReadout();
        controller.transform.position = new Vector3(0f, 1f, 0f);
        runtime.SetTrackingPosition(runtime.LocalPlayer, VRCPlayerApi.TrackingDataType.LeftHand, new Vector3(0.1f, 1f, 0f));
        runtime.SetTrackingPosition(runtime.LocalPlayer, VRCPlayerApi.TrackingDataType.RightHand, new Vector3(5f, 1f, 0f));
        VrcRuntimeFake.SetPrivate(controller, "holdingHand", -1);

        controller.PostLateUpdate();

        Assert.AreEqual(0.1f, readout.position.x, 0.0001f);
        Assert.AreEqual(1f + controller.readoutYOffset, readout.position.y, 0.0001f);
    }

    [Test]
    public void ShownBuyInButton_ReleasesTheChipCollidersSoItCanBeClicked()
    {
        player.rebuyButton = Spawn("BuyIn");
        InvokePrivate("RefreshInteraction");

        Assert.IsFalse(player.CanHandlePhysicalChips(), "Chips are not handled while the buy-in button is offered");
        Assert.IsFalse(pickupCollider.enabled, "The pickup collider would sit in front of the button");
    }

    [Test]
    public void HiddenBuyInButton_KeepsTheChipCollidersActive()
    {
        player.rebuyButton = Spawn("BuyIn");
        player.rebuyButton.SetActive(false);
        InvokePrivate("RefreshInteraction");

        Assert.IsTrue(player.CanHandlePhysicalChips());
        HoverOver(0, 0);
        Assert.IsTrue(pickupCollider.enabled, "A hidden buy-in button must not stop the pile from being grabbed");
    }

    private void SetBlindPosted()
    {
        game.roundContribution[0] = 50;
        game.currentBet = 150;
        game.minimumRaise = 100;
        player.bet = player.GetPhysicalCallAmount();
        source.SetTotalChips(game.stacks[0] - player.GetPhysicalCallAmount());
    }

    private bool InvokeCallPileCommit()
    {
        GameObject callObject = Spawn("CallPile");
        GrabbablePile callPile = callObject.AddComponent<GrabbablePile>();
        callPile.player = player;
        player.grabbableBetPile = callPile;
        return (bool)typeof(GrabbablePile).GetMethod("CommitPhysicalCall",
            BindingFlags.Instance | BindingFlags.NonPublic).Invoke(callPile, null);
    }

    private void DropRaiseInPlayArea()
    {
        GameObject targetObject = Spawn("BetTarget");
        BoxCollider target = targetObject.AddComponent<BoxCollider>();
        target.size = Vector3.one;
        controller.targetCollider = target;
        raise.transform.position = target.bounds.center;
        VrcRuntimeFake.SetPrivate(controller, "state", 3);
        InvokePrivate("Update");
    }

    private void AssertCommittedAndCleared(int expectedBet)
    {
        Assert.IsTrue((bool)VrcRuntimeFake.GetPrivate(player, "actionTaken"), "The bet must be confirmed");
        Assert.AreEqual(expectedBet, player.bet);
        Assert.AreEqual(game.epoch, player.committedEpoch);
        Assert.AreEqual(0, raise.GetTotalDisplayedValue(), "The raise chips must be consumed");
        InvokeRefreshSeatUi(HoldemGame.TABLE_PLAYING);
        Assert.AreEqual(0, player.betPile.GetTotalDisplayedValue(), "The call chips must be cleared");
    }

    [Test]
    public void BlindAdjustedRaise_DroppedInPlayArea_ConfirmsTheBetAndClearsTheCallChips()
    {
        BuildSeatUi();
        InvokeRefreshSeatUi(HoldemGame.TABLE_PLAYING);
        Assert.AreEqual(100, player.betPile.GetTotalDisplayedValue(), "The call chips start on the table");
        Assert.IsTrue(BeginReservation(0, 0, 1));
        Assert.AreEqual(100, raise.GetTotalDisplayedValue(), "One 5-chip is adjusted up to the minimum raise");

        DropRaiseInPlayArea();

        AssertCommittedAndCleared(200);
    }

    [Test]
    public void BlindAdjustedRaise_WithBlindAlreadyPosted_ConfirmsTheBetAndClearsTheCallChips()
    {
        SetBlindPosted();
        BuildSeatUi();
        InvokeRefreshSeatUi(HoldemGame.TABLE_PLAYING);
        Assert.IsTrue(BeginReservation(0, 0, 1));

        DropRaiseInPlayArea();

        AssertCommittedAndCleared(200);
    }

    [Test]
    public void BlindAdjustedRaise_CallOverride_ConfirmsTheCallAndClearsBothPiles()
    {
        BuildSeatUi();
        InvokeRefreshSeatUi(HoldemGame.TABLE_PLAYING);
        Assert.IsTrue(BeginReservation(0, 0, 1));

        Assert.IsTrue(InvokeCallPileCommit());

        AssertCommittedAndCleared(100);
        Assert.AreEqual(400, source.GetTotalDisplayedValue(), "The adjusted raise chips return to the stack");
    }

    [Test]
    public void BlindAdjustedRaise_CallOverride_WithBlindAlreadyPosted_ConfirmsTheCall()
    {
        SetBlindPosted();
        BuildSeatUi();
        InvokeRefreshSeatUi(HoldemGame.TABLE_PLAYING);
        Assert.IsTrue(BeginReservation(0, 0, 1));

        Assert.IsTrue(InvokeCallPileCommit());

        AssertCommittedAndCleared(100);
    }

    [Test]
    public void CallPile_CommitsTheCurrentCallEvenWhenTheStoredBetIsStale()
    {
        BuildSeatUi();
        player.bet = 250;

        Assert.IsTrue(InvokeCallPileCommit());

        AssertCommittedAndCleared(100);
    }

    private void HoverHand(int hand, float chipDepth)
    {
        VRCPlayerApi.TrackingDataType type = hand == 0
            ? VRCPlayerApi.TrackingDataType.LeftHand : VRCPlayerApi.TrackingDataType.RightHand;
        runtime.SetTrackingPosition(runtime.LocalPlayer, type, HandInsideColumn(0, 0, chipDepth));
        runtime.SetTrackingPosition(runtime.LocalPlayer,
            hand == 0 ? VRCPlayerApi.TrackingDataType.RightHand : VRCPlayerApi.TrackingDataType.LeftHand,
            new Vector3(50f, 50f, 50f));
    }

    [Test]
    public void Hover_BuzzesTheHoveringHandWhenTheAmountChanges()
    {
        HoverHand(0, 0.25f);
        InvokePrivate("UpdateHover");

        Assert.AreEqual(1, runtime.HapticCalls.Count);
        Assert.AreEqual(VRC_Pickup.PickupHand.Left, runtime.HapticCalls[0].Hand);
        Assert.Greater(runtime.HapticCalls[0].Amplitude, 0f);
        Assert.Greater(runtime.HapticCalls[0].Duration, 0f);
        Assert.LessOrEqual(runtime.HapticCalls[0].Duration, 0.1f, "The buzz is small");

        InvokePrivate("UpdateHover");
        Assert.AreEqual(1, runtime.HapticCalls.Count, "An unchanged amount must not buzz again");

        HoverHand(0, 2.5f);
        InvokePrivate("UpdateHover");
        Assert.AreEqual(2, runtime.HapticCalls.Count, "Lowering the hand selects more chips");
    }

    [Test]
    public void Hover_BuzzesTheRightHandWhenThatHandSelects()
    {
        HoverHand(1, 0.25f);
        InvokePrivate("UpdateHover");

        Assert.AreEqual(1, runtime.HapticCalls.Count);
        Assert.AreEqual(VRC_Pickup.PickupHand.Right, runtime.HapticCalls[0].Hand);
    }

    [Test]
    public void Hover_BuzzesAgainAfterLeavingAndReenteringTheStack()
    {
        HoverHand(0, 0.25f);
        InvokePrivate("UpdateHover");
        runtime.SetTrackingPosition(runtime.LocalPlayer, VRCPlayerApi.TrackingDataType.LeftHand,
            new Vector3(50f, 50f, 50f));
        InvokePrivate("UpdateHover");
        Assert.AreEqual(1, runtime.HapticCalls.Count, "Leaving the stack is silent");

        HoverHand(0, 0.25f);
        InvokePrivate("UpdateHover");
        Assert.AreEqual(2, runtime.HapticCalls.Count);
    }

    [Test]
    public void Hover_DoesNotBuzzOnDesktop()
    {
        runtime.VrUsers[runtime.LocalPlayer.playerId] = false;
        HoverHand(0, 0.25f);
        InvokePrivate("UpdateHover");

        Assert.AreEqual(0, runtime.HapticCalls.Count);
    }

    [Test]
    public void ImmersiveStackLayout_IsShiftedLeftOfTheCards()
    {
        Vector3 shifted = source.GetDenominationColumnWorldPosition(2, 0);
        source.selectableLayoutOffset = Vector3.zero;
        Vector3 unshifted = source.GetDenominationColumnWorldPosition(2, 0);

        Assert.AreEqual(-0.1f, shifted.x - unshifted.x, 0.0001f,
            "The selectable layout sits 0.1 to the left");
        Assert.AreEqual(0f, shifted.z - unshifted.z, 0.0001f);
        Assert.AreEqual(0f, shifted.y - unshifted.y, 0.0001f);

        source.SetSelectableStackMode(false);
        Assert.AreEqual(source.transform.position.x,
            source.GetDenominationColumnWorldPosition(2, 0).x, 0.0001f,
            "The shift is immersive-only");
    }

    [Test]
    public void ImmersiveStackLayout_LeavesNonSelectablePilesAlone()
    {
        Assert.AreEqual(raise.transform.position.x,
            raise.GetDenominationColumnWorldPosition(2, 0).x, 0.0001f);
    }
}
