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

public class GrabbableHandTests
{
    private VrcRuntimeFake vrc;
    private readonly List<GameObject> spawned = new List<GameObject>();

    private GrabbableHand hand;
    private SmartObjectSync sync;
    private VRC_Pickup pickup;

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

        var tableGo = Spawn("Table");
        var game = tableGo.AddComponent<HoldemGame>();
        var seat = Spawn("Seat").AddComponent<HoldemPlayer>();
        seat.game = game;
        game.players = new[] { seat };

        // Mirrors Hand.prefab: the pickup starts ungrabbable, theft flag read from the real prefab
        var go = Spawn("Hand");
        go.AddComponent<Rigidbody>();
        pickup = (VRC_Pickup)go.AddComponent(System.Type.GetType("VRC.SDK3.Components.VRCPickup, VRCSDK3"));
        pickup.pickupable = false;
        sync = go.AddComponent<SmartObjectSync>();
        sync.pickup = pickup;
        sync.rigid = go.GetComponent<Rigidbody>();
        sync.allowTheftFromSelf = HandPrefabSync().allowTheftFromSelf;
        sync.kinematicWhileHeld = false;
        sync.Start();
        sync._owner = vrc.LocalPlayer;

        hand = go.AddComponent<GrabbableHand>();
        hand.pickup = pickup;
        hand.objectSync = sync;
        hand.rb = go.GetComponent<Rigidbody>();
        hand.player = seat;
        hand.eyeUi = Spawn("Eye");
        seat.grabbableHand = hand;
    }

    [TearDown]
    public void TearDown()
    {
        vrc.Uninstall();
        foreach (var go in spawned) if (go) Object.DestroyImmediate(go);
        spawned.Clear();
    }

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

    private static SmartObjectSync HandPrefabSync()
    {
        string path = HoldemPaths.Asset("DevPrefabs/Hand.prefab");
        var root = UnityEditor.AssetDatabase.LoadAssetAtPath<GameObject>(path);
        Assert.IsNotNull(root, path);
        return root.GetComponentInChildren<SmartObjectSync>(true);
    }

    [Test]
    public void CardsStayGrabbableWhileHeldSoTheOtherHandCanTakeThem()
    {
        hand._MakeGrabbable();
        sync._state = SmartObjectSync.STATE_RIGHT_HAND_HELD; // the state setter's networking needs a live world
        sync.OnEnterState();

        // HoldemPlayer.RefreshSeatUi re-applies SetGrabbable(true) roughly every second mid-hold
        hand._MakeGrabbable();

        Assert.IsTrue(sync.IsHeld() && sync.IsLocalOwner(), "test must simulate a hold by the local owner");
        Assert.IsTrue(pickup.pickupable,
            "A held card must stay pickupable or it can't be passed to the other hand without releasing it");
    }

    [Test]
    public void CardsCanBeRegrabbedRightAfterDrop()
    {
        hand._MakeGrabbable();

        sync.genericHand_OnEnterState();
        sync.genericHand_OnExitState();

        Assert.IsTrue(pickup.pickupable);
    }

    [Test]
    public void MakeGrabbableDoesNotUnstickRigidbodyDuringAnActiveHold()
    {
        sync.kinematicWhileHeld = true;
        var rb = hand.GetComponent<Rigidbody>();

        hand._MakeGrabbable();
        sync.genericHand_OnEnterState(); // simulates OnPickup: SmartObjectSync locks the rigidbody while held
        SetPrivateField(hand, "isHeld", true); // mirrors GrabbableHand.OnPickup's own hold tracking

        // HoldemPlayer.RefreshSeatUi calls SetGrabbable(true) roughly every second while seated,
        // even while the card is still being held - it must not fight SmartObjectSync's hold state.
        hand._MakeGrabbable();

        Assert.IsTrue(rb.isKinematic,
            "A grabbable refresh must not un-kinematic the rigidbody mid-hold, or it destabilizes hand-to-hand transfers");
    }

    [Test]
    public void UngrabbableCardsStayUngrabbableAfterDrop()
    {
        hand._MakeGrabbable();
        sync.genericHand_OnEnterState();
        hand._MakeUngrabbable();

        sync.genericHand_OnExitState();

        Assert.IsFalse(pickup.pickupable);
    }

    [Test]
    public void ShowingCardsAsksTheTableToTick()
    {
        hand._MakeGrabbable();
        sync.genericHand_OnEnterState();
        var game = hand.player.game;

        hand.isVisibleToOthers = true;
        VrcRuntimeFake.InvokeNoArg(hand, "OnDeserialization");

        var requested = typeof(HoldemGame).GetField("transitionRequested",
            BindingFlags.NonPublic | BindingFlags.Instance).GetValue(game);
        Assert.IsTrue((bool)requested,
            "Only the table owner can publish the cards, so it has to tick");
    }

    [Test]
    public void EyeShowsWhenCardsAreShownWhileHeld()
    {
        hand._MakeGrabbable();
        sync.genericHand_OnEnterState();

        hand.isVisibleToOthers = true;
        VrcRuntimeFake.InvokeNoArg(hand, "OnDeserialization");

        Assert.IsTrue(hand.eyeUi.activeSelf);
    }

    #region Collider Mode Tests

    private (Collider[] flat, Collider[] bend) SetupColliderSets()
    {
        var flat = new Collider[] { hand.gameObject.AddComponent<BoxCollider>() };
        var bend = new Collider[]
        {
            hand.gameObject.AddComponent<BoxCollider>(),
            hand.gameObject.AddComponent<CapsuleCollider>(),
            hand.gameObject.AddComponent<CapsuleCollider>(),
        };
        hand.flatColliders = flat;
        hand.bendColliders = bend;
        return (flat, bend);
    }

    private static void AssertEnabled(Collider[] colliders, bool expected, string what)
    {
        foreach (var c in colliders)
            Assert.AreEqual(expected, c.enabled, what);
    }

    [Test]
    public void SetCardFoldingEnabled_True_UsesBendColliders()
    {
        var (flat, bend) = SetupColliderSets();

        hand.SetCardFoldingEnabled(true);

        AssertEnabled(bend, true, "bend colliders should be on when folding is enabled");
        AssertEnabled(flat, false, "flat collider should be off when folding is enabled");
    }

    [Test]
    public void SetCardFoldingEnabled_False_RestoresFlatCollider()
    {
        var (flat, bend) = SetupColliderSets();
        hand.SetCardFoldingEnabled(true);

        hand.SetCardFoldingEnabled(false);

        AssertEnabled(flat, true, "flat collider should be back on when folding is disabled");
        AssertEnabled(bend, false, "bend colliders should be off when folding is disabled");
    }

    [Test]
    public void ColliderMode_AppliesOnStartFromSerializedFlag()
    {
        var (flat, bend) = SetupColliderSets();
        hand.enableCardFolding = true;

        InvokePrivate(hand, "ApplyColliderMode");

        AssertEnabled(bend, true, "bend colliders");
        AssertEnabled(flat, false, "flat collider");
    }

    [Test]
    public void ColliderMode_ToleratesUnsetOrNullEntries()
    {
        hand.flatColliders = null;
        hand.bendColliders = new Collider[] { null };

        Assert.DoesNotThrow(() => hand.SetCardFoldingEnabled(true));
        Assert.DoesNotThrow(() => hand.SetCardFoldingEnabled(false));
    }

    [Test]
    public void HandPrefab_WiresColliderSetsToMatchingShapes()
    {
        string path = HoldemPaths.Asset("DevPrefabs/Hand.prefab");
        var root = UnityEditor.AssetDatabase.LoadAssetAtPath<GameObject>(path);
        Assert.IsNotNull(root, path);
        var prefabHand = root.GetComponent<GrabbableHand>();

        Assert.AreEqual(1, prefabHand.flatColliders.Length, "one large box collider");
        Assert.IsInstanceOf<BoxCollider>(prefabHand.flatColliders[0]);
        Assert.AreEqual(5, prefabHand.bendColliders.Length, "one small box + four capsules");

        int boxes = 0, capsules = 0;
        foreach (var c in prefabHand.bendColliders)
        {
            if (c is BoxCollider) boxes++;
            if (c is CapsuleCollider) capsules++;
        }
        Assert.AreEqual(1, boxes);
        Assert.AreEqual(4, capsules);

        var flatSize = ((BoxCollider)prefabHand.flatColliders[0]).size;
        foreach (var c in prefabHand.bendColliders)
        {
            if (c is BoxCollider box)
                Assert.Less(box.size.x * box.size.z, flatSize.x * flatSize.z,
                    "bend box must be smaller than the flat box");
        }

        foreach (var c in root.GetComponents<Collider>())
            Assert.That(System.Array.IndexOf(prefabHand.flatColliders, c) >= 0 ||
                        System.Array.IndexOf(prefabHand.bendColliders, c) >= 0,
                $"Collider {c} on the Hand is in neither set, so it would never toggle");
    }

    #endregion

    #region Card Peeking Tests

    private (BoxCollider surface, Transform card0, Transform card1,
        Transform[] bones0, Transform[] bones1)
        SetupPeekGeometry(int columns = 3, int rows = 5)
    {
        hand.peekColumns = columns;
        hand.peekRows = rows;
        hand.peekAxisA0 = Vector3.forward;
        hand.peekAxisB0 = Vector3.right;
        hand.peekAxisA1 = Vector3.forward;
        hand.peekAxisB1 = Vector3.right;
        var surfaceGo = Spawn("PeekSurface");
        surfaceGo.transform.position = Vector3.zero;
        var surface = surfaceGo.AddComponent<BoxCollider>();
        surface.center = Vector3.zero;
        surface.size = new Vector3(0.2f, 0.02f, 0.2f);
        surface.isTrigger = true;

        var card0Go = Spawn("Card0");
        card0Go.transform.SetParent(hand.transform);
        card0Go.transform.localPosition = new Vector3(-0.03f, 0f, -0.025f);

        var card1Go = Spawn("Card1");
        card1Go.transform.SetParent(hand.transform);
        card1Go.transform.localPosition = new Vector3(-0.03f, 0f, 0.025f);

        var container0 = Spawn("BonesContainer0");
        container0.transform.SetParent(card0Go.transform);
        container0.transform.localPosition = Vector3.zero;
        container0.transform.localRotation = Quaternion.identity;

        var container1 = Spawn("BonesContainer1");
        container1.transform.SetParent(card1Go.transform);
        container1.transform.localPosition = Vector3.zero;
        container1.transform.localRotation = Quaternion.identity;

        var count = columns * rows;
        var bones0 = new Transform[count];
        var bones1 = new Transform[count];

        for (int r = 0; r < rows; r++)
        {
            for (int c = 0; c < columns; c++)
            {
                int i = r * columns + c;
                float x = Mathf.Lerp(-0.04f, 0.04f, (float)c / (columns - 1));
                float z = Mathf.Lerp(-0.04f, 0.04f, (float)r / (rows - 1));

                bones0[i] = SpawnBone($"B0_{r}_{c}", container0.transform, x, z);
                bones1[i] = SpawnBone($"B1_{r}_{c}", container1.transform, x, z);
            }
        }

        return (surface, card0Go.transform, card1Go.transform, bones0, bones1);
    }

    private Transform SpawnBone(string name, Transform parent, float x, float z)
    {
        var go = Spawn(name);
        go.transform.SetParent(parent);
        go.transform.localPosition = new Vector3(x, 0f, z);
        go.transform.localRotation = Quaternion.identity;
        return go.transform;
    }

    private static T GetPrivateField<T>(object obj, string field)
    {
        return (T)typeof(GrabbableHand).GetField(field,
            BindingFlags.NonPublic | BindingFlags.Instance).GetValue(obj);
    }

    private static void SetPrivateField(object obj, string field, object value)
    {
        typeof(GrabbableHand).GetField(field,
            BindingFlags.NonPublic | BindingFlags.Instance).SetValue(obj, value);
    }

    private static object InvokePrivate(object obj, string method, params object[] args)
    {
        return typeof(GrabbableHand).GetMethod(method,
            BindingFlags.NonPublic | BindingFlags.Instance).Invoke(obj, args);
    }

    [Test]
    public void PeekRig_FailsWhenSurfaceNull()
    {
        hand.enableCardFolding = true;
        var (_, card0, card1, bones0, bones1) = SetupPeekGeometry();
        hand.peekSurface = null;
        hand.peekCard0 = card0;
        hand.peekCard1 = card1;
        hand.peekBones0 = bones0;
        hand.peekBones1 = bones1;

        InvokePrivate(hand, "InitializePeekRig");

        Assert.IsFalse(GetPrivateField<bool>(hand, "peekRigReady"));
    }

    [Test]
    public void PeekRig_InitializesWithValidSetup()
    {
        hand.enableCardFolding = true;
        var (surface, card0, card1, bones0, bones1) = SetupPeekGeometry();
        hand.peekSurface = surface;
        hand.peekCard0 = card0;
        hand.peekCard1 = card1;
        hand.peekBones0 = bones0;
        hand.peekBones1 = bones1;

        InvokePrivate(hand, "InitializePeekRig");

        Assert.IsTrue(GetPrivateField<bool>(hand, "peekRigReady"));
        Assert.IsNotNull(GetPrivateField<Vector3[]>(hand, "peekRestPositions0"));
        Assert.IsNotNull(GetPrivateField<Vector3[]>(hand, "peekRestPositions1"));
        Assert.AreEqual(15, GetPrivateField<Vector3[]>(hand, "peekRestPositions0").Length);
    }

    [Test]
    public void PeekRig_FailsWithWrongBoneCount()
    {
        hand.enableCardFolding = true;
        hand.peekColumns = 3;
        hand.peekRows = 5;
        var (surface, card0, card1, _, _) = SetupPeekGeometry();
        var wrongBones = new Transform[7];
        for (int i = 0; i < 7; i++)
            wrongBones[i] = Spawn($"W{i}").transform;
        hand.peekSurface = surface;
        hand.peekCard0 = card0;
        hand.peekCard1 = card1;
        hand.peekBones0 = wrongBones;
        hand.peekBones1 = wrongBones;

        InvokePrivate(hand, "InitializePeekRig");

        Assert.IsFalse(GetPrivateField<bool>(hand, "peekRigReady"));
    }

    [Test]
    public void FindPeekEdge_DetectsBottomEdgeContact()
    {
        hand.enableCardFolding = true;
        var (surface, card0, card1, bones0, bones1) = SetupPeekGeometry();
        hand.peekSurface = surface;
        hand.peekCard0 = card0;
        hand.peekCard1 = card1;
        hand.peekBones0 = bones0;
        hand.peekBones1 = bones1;

        InvokePrivate(hand, "InitializePeekRig");

        hand.transform.position = new Vector3(0f, -0.01f, 0f);

        var edge = (int)InvokePrivate(hand, "FindPeekEdge", 0.012f);
        Assert.GreaterOrEqual(edge, 0, "Should detect an edge");
        Assert.Less(edge, 4);
    }

    [Test]
    public void FindPeekEdge_ReturnsMinusOne_WhenFarAway()
    {
        hand.enableCardFolding = true;
        var (surface, card0, card1, bones0, bones1) = SetupPeekGeometry();
        hand.peekSurface = surface;
        hand.peekCard0 = card0;
        hand.peekCard1 = card1;
        hand.peekBones0 = bones0;
        hand.peekBones1 = bones1;

        InvokePrivate(hand, "InitializePeekRig");

        hand.transform.position = new Vector3(100f, 100f, 100f);

        var edge = (int)InvokePrivate(hand, "FindPeekEdge", 0.012f);
        Assert.AreEqual(-1, edge);
    }
    
    [Test]
    public void ResetPeekRig_RestoresBoneTransforms()
    {
        hand.enableCardFolding = true;
        var (surface, card0, card1, bones0, bones1) = SetupPeekGeometry();
        hand.peekSurface = surface;
        hand.peekCard0 = card0;
        hand.peekCard1 = card1;
        hand.peekBones0 = bones0;
        hand.peekBones1 = bones1;

        InvokePrivate(hand, "InitializePeekRig");
        var restPositions = GetPrivateField<Vector3[]>(hand, "peekRestPositions0");
        var restRotations = GetPrivateField<Quaternion[]>(hand, "peekRestRotations0");

        hand.transform.position = new Vector3(0f, -0.015f, 0f);
        hand.transform.rotation = Quaternion.Euler(15f, 0f, 0f);
        SetPrivateField(hand, "syncedPeekEdge", 2);

        InvokePrivate(hand, "ApplyPeekRig",
            hand.peekCard0, hand.peekBones0,
            GetPrivateField<Vector3[]>(hand, "peekRestPositions0"),
            GetPrivateField<Vector3[]>(hand, "peekTargets0"),
            hand.peekAxisA0, hand.peekAxisB0, 2);

        bool anyMoved = false;
        for (int i = 0; i < bones0.Length; i++)
        {
            if ((bones0[i].localPosition - restPositions[i]).sqrMagnitude > 0.000001f)
            { anyMoved = true; break; }
        }
        Assert.IsTrue(anyMoved, "Bones should have moved after ApplyPeekRig");

        InvokePrivate(hand, "ResetPeekRig");
        for (int i = 0; i < bones0.Length; i++)
        {
            Assert.AreEqual(restPositions[i], bones0[i].localPosition,
                $"Bone0[{i}] not restored");
            Assert.AreEqual(restRotations[i], bones0[i].localRotation,
                $"Bone0[{i}] rotation not restored");
        }
    }

    #endregion

    #region Bend Calibration Tests

    private void SetupCardFolding(BoxCollider surface, Transform card0, Transform card1,
        Transform[] bones0, Transform[] bones1)
    {
        hand.enableCardFolding = true;
        hand.peekSurface = surface;
        hand.peekCard0 = card0;
        hand.peekCard1 = card1;
        hand.peekBones0 = bones0;
        hand.peekBones1 = bones1;
        hand.peekBendStrength = 0.8f;
        hand.peekMaxCorrection = 0.04f;
        hand.peekLongEdgePenalty = 0.1f;
        hand.peekAxisRelaxFactor = 1.2f;

        InvokePrivate(hand, "InitializePeekRig");
    }

    private void ApplyPeekForEdge(int edge)
    {
        InvokePrivate(hand, "ApplyPeekRig",
            hand.peekCard0, hand.peekBones0,
            GetPrivateField<Vector3[]>(hand, "peekRestPositions0"),
            GetPrivateField<Vector3[]>(hand, "peekTargets0"),
            hand.peekAxisA0, hand.peekAxisB0, edge);
    }

    private static float MaxDisplacement(Vector3[] restPositions, Transform[] bones)
    {
        float max = 0f;
        for (int i = 0; i < bones.Length; i++)
        {
            float d = (bones[i].localPosition - restPositions[i]).magnitude;
            if (d > max) max = d;
        }
        return max;
    }

    private static float MaxPairwiseDeviation(Transform[] bones, int stride,
        Vector3[] restPositions, Transform cardSpace, float tolerance)
    {
        float maxDev = 0f;
        for (int i = 0; i + stride < bones.Length; i++)
        {
            float curDist = (bones[i].position - bones[i + stride].position).magnitude;
            float restDist = cardSpace.TransformVector(
                restPositions[i + stride] - restPositions[i]).magnitude;
            float dev = Mathf.Abs(curDist - restDist) / Mathf.Max(restDist, 0.0001f);
            if (dev > maxDev) maxDev = dev;
        }
        return maxDev;
    }

    [Test]
    public void Edges23_PreferredOverEdges01_AtSameDistance()
    {
        var (surface, card0, card1, bones0, bones1) = SetupPeekGeometry();
        SetupCardFolding(surface, card0, card1, bones0, bones1);

        hand.transform.position = new Vector3(0f, -0.01f, 0f);

        var edge = (int)InvokePrivate(hand, "FindPeekEdge", 0.012f);
        Assert.GreaterOrEqual(edge, 0, "Should detect an edge");
        Assert.That(edge == 2 || edge == 3,
            $"Should prefer short-axis edges (2 or 3), got {edge}");
    }

    [Test]
    public void Edge01_TriggersWhenEdges23TooFar()
    {
        var (surface, card0, card1, bones0, bones1) = SetupPeekGeometry();
        SetupCardFolding(surface, card0, card1, bones0, bones1);

        hand.transform.position = new Vector3(0f, 0.2f, 0f);

        var edge = (int)InvokePrivate(hand, "FindPeekEdge", 0.012f);
        Assert.AreEqual(-1, edge, "Should not trigger any edge when far above surface");
    }

    [Test]
    public void XYPlane_Bend_ProducesVisibleDisplacement()
    {
        var (surface, card0, card1, bones0, bones1) = SetupPeekGeometry();
        SetupCardFolding(surface, card0, card1, bones0, bones1);

        hand.transform.position = new Vector3(0f, -0.01f, 0f);
        hand.transform.rotation = Quaternion.Euler(15f, 0f, 0f);

        ApplyPeekForEdge(0);

        var restPositions = GetPrivateField<Vector3[]>(hand, "peekRestPositions0");
        float maxDisp = MaxDisplacement(restPositions, bones0);

        Assert.Greater(maxDisp, 0.001f,
            $"XY bend should produce visible displacement, got {maxDisp:F6}");
    }

    [Test]
    public void ZYPlane_Bend_RelaxesRowConstraint()
    {
        var (surface, card0, card1, bones0, bones1) = SetupPeekGeometry(5, 3);
        var columns = hand.peekColumns;
        SetupCardFolding(surface, card0, card1, bones0, bones1);

        hand.transform.position = new Vector3(0f, -0.01f, 0f);
        hand.transform.rotation = Quaternion.Euler(15f, 0f, 0f);

        var restPositions = GetPrivateField<Vector3[]>(hand, "peekRestPositions0");

        ApplyPeekForEdge(2);
        float colDev = MaxPairwiseDeviation(bones0, 1, restPositions, hand.peekCard0, 0.01f);
        float rowDev = MaxPairwiseDeviation(bones0, columns, restPositions, hand.peekCard0, 0.01f);

        Assert.Greater(rowDev, colDev * 1.5f,
            $"Edge 2: row deviation ({rowDev*100:F1}%) should be larger than column deviation ({colDev*100:F1}%)");
    }

    [Test]
    public void ZYBend_PreservesColumnDistances()
    {
        var (surface, card0, card1, bones0, bones1) = SetupPeekGeometry();
        SetupCardFolding(surface, card0, card1, bones0, bones1);

        hand.transform.position = new Vector3(0f, -0.01f, 0f);
        hand.transform.rotation = Quaternion.Euler(15f, 0f, 0f);

        var restPositions = GetPrivateField<Vector3[]>(hand, "peekRestPositions0");
        ApplyPeekForEdge(2);

        float maxDev = MaxPairwiseDeviation(bones0, 1, restPositions, hand.peekCard0, 0.01f);

        Assert.Less(maxDev, 0.05f,
            $"Column (X) distances should stay within 5% during Z bend, got {maxDev * 100f:F1}%");
    }

    [Test]
    public void XYBend_PreservesRowDistances()
    {
        var (surface, card0, card1, bones0, bones1) = SetupPeekGeometry();
        var columns = hand.peekColumns;
        SetupCardFolding(surface, card0, card1, bones0, bones1);

        hand.transform.position = new Vector3(0f, -0.01f, 0f);
        hand.transform.rotation = Quaternion.Euler(15f, 0f, 0f);

        var restPositions = GetPrivateField<Vector3[]>(hand, "peekRestPositions0");
        ApplyPeekForEdge(0);

        float maxDev = MaxPairwiseDeviation(bones0, columns, restPositions, hand.peekCard0, 0.01f);

        Assert.Less(maxDev, 0.05f,
            $"Row (Z) distances should stay within 5% during XY bend, got {maxDev * 100f:F1}%");
    }

    [Test]
    public void ConstraintConvergesForAllEdges()
    {
        var (surface, card0, card1, bones0, bones1) = SetupPeekGeometry();
        SetupCardFolding(surface, card0, card1, bones0, bones1);

        hand.transform.position = new Vector3(0f, -0.01f, 0f);
        hand.transform.rotation = Quaternion.Euler(15f, 0f, 0f);

        for (int edge = 0; edge < 4; edge++)
        {
            InvokePrivate(hand, "ResetPeekRig");
            ApplyPeekForEdge(edge);
        }

        Assert.Pass("All 4 edges converged without error");
    }

    [Test]
    public void BendStrength_Sweep_LogsDisplacements()
    {
        var (surface, card0, card1, bones0, bones1) = SetupPeekGeometry();
        SetupCardFolding(surface, card0, card1, bones0, bones1);

        hand.transform.position = new Vector3(0f, -0.01f, 0f);
        hand.transform.rotation = Quaternion.Euler(15f, 0f, 0f);

        float[] strengths = { 0.3f, 0.5f, 0.8f, 1.0f, 1.5f };
        var restPositions = GetPrivateField<Vector3[]>(hand, "peekRestPositions0");

        foreach (var strength in strengths)
        {
            hand.peekBendStrength = strength;
            InvokePrivate(hand, "ResetPeekRig");
            ApplyPeekForEdge(2);

            float maxDisp = MaxDisplacement(restPositions, bones0);
            Debug.Log($"[BendSweep] strength={strength:F1} maxDisplacement={maxDisp:F6}");
        }

        Assert.Pass("Bend strength sweep logged");
    }

    [Test]
    public void AxisRelax_Sweep_LogsColumnDeviations()
    {
        var (surface, card0, card1, bones0, bones1) = SetupPeekGeometry();
        SetupCardFolding(surface, card0, card1, bones0, bones1);

        hand.transform.position = new Vector3(0f, -0.01f, 0f);
        hand.transform.rotation = Quaternion.Euler(15f, 0f, 0f);

        float[] factors = { 1.0f, 1.1f, 1.2f, 1.3f, 1.5f };
        var restPositions = GetPrivateField<Vector3[]>(hand, "peekRestPositions0");

        foreach (var factor in factors)
        {
            hand.peekAxisRelaxFactor = factor;
            InvokePrivate(hand, "ResetPeekRig");
            ApplyPeekForEdge(2);

            float maxDev = MaxPairwiseDeviation(bones0, 1, restPositions, hand.peekCard0, 0.01f);
            Debug.Log($"[AxisRelax] factor={factor:F1} maxColumnDeviation={maxDev * 100f:F1}%");
        }

        Assert.Pass("Axis relaxation sweep logged");
    }

    [Test]
    public void PeekSnapHeight_RaisesBoneSnapPlaneWithoutChangingCollider()
    {
        var (surface, card0, card1, bones0, bones1) = SetupPeekGeometry();
        SetupCardFolding(surface, card0, card1, bones0, bones1);
        hand.peekSnapHeight = 0.001f;
        Vector3 originalCenter = surface.center;
        Vector3 originalSize = surface.size;

        ApplyPeekForEdge(2);

        Vector3 colliderBottom = surface.transform.TransformPoint(
            surface.center + Vector3.down * surface.size.y * 0.5f);
        Vector3 expectedSnapPoint = colliderBottom + surface.transform.up * hand.peekSnapHeight;
        for (int column = 0; column < hand.peekColumns; column++)
        {
            float heightError = Mathf.Abs(Vector3.Dot(
                bones0[column].position - expectedSnapPoint, surface.transform.up));
            Assert.Less(heightError, 0.00001f,
                $"Contact bone {column} should snap 1 mm above the collider bottom");
        }

        Assert.AreEqual(originalCenter, surface.center);
        Assert.AreEqual(originalSize, surface.size);
    }

    [Test]
    public void ZYBend_FadesEarlierThanXYBend()
    {
        var (surface, card0, card1, bones0, bones1) = SetupPeekGeometry();
        SetupCardFolding(surface, card0, card1, bones0, bones1);
        hand.transform.rotation = Quaternion.Euler(37.5f, 0f, 0f);

        float xyIntensity = (float)InvokePrivate(hand, "GetPeekAngleIntensity", 0);
        float zyIntensity = (float)InvokePrivate(hand, "GetPeekAngleIntensity", 2);

        Assert.AreEqual(1f, xyIntensity, 0.001f,
            "XY bending should retain the existing 45/60 degree thresholds");
        Assert.Greater(zyIntensity, 0f);
        Assert.Less(zyIntensity, 1f,
            "ZY bending should fade between 30 and 45 degrees");

        hand.transform.rotation = Quaternion.Euler(45f, 0f, 0f);
        zyIntensity = (float)InvokePrivate(hand, "GetPeekAngleIntensity", 2);
        Assert.Less(zyIntensity, 0.001f,
            "ZY bending should reach zero at 45 degrees");
    }

    #endregion

    // ---- bend-cards toggle edge cases ----

    private BoxCollider AddCollider(string name, bool enabled)
    {
        var c = Spawn(name).AddComponent<BoxCollider>();
        c.transform.SetParent(hand.transform);
        c.enabled = enabled;
        return c;
    }

    [Test]
    public void FoldingToggle_SwapsExactlyOneColliderSet_EveryTime()
    {
        var flat = AddCollider("Flat", true);
        var bend = AddCollider("Bend", false);
        hand.flatColliders = new Collider[] { flat };
        hand.bendColliders = new Collider[] { bend };

        for (int i = 0; i < 6; i++)
        {
            bool folding = i % 2 == 0;
            hand.SetCardFoldingEnabled(folding);
            Assert.AreEqual(!folding, flat.enabled, "flat set, step " + i);
            Assert.AreEqual(folding, bend.enabled, "bend set, step " + i);
        }
    }

    [Test]
    public void FoldingToggle_WithNullEntries_DoesNotThrow()
    {
        hand.flatColliders = new Collider[] { null, AddCollider("Flat", true) };
        hand.bendColliders = new Collider[] { null };

        Assert.DoesNotThrow(() => hand.SetCardFoldingEnabled(true));
        Assert.DoesNotThrow(() => hand.SetCardFoldingEnabled(false));
    }

    [Test]
    public void FoldingToggle_WithUnassignedRigAndColliders_DoesNotThrow()
    {
        Assert.DoesNotThrow(() => hand.SetCardFoldingEnabled(true));
        Assert.DoesNotThrow(() => hand.SetCardFoldingEnabled(false));
        Assert.DoesNotThrow(() => hand.SetCardFoldingEnabled(true));
    }
}
