﻿using UdonSharp;
using UnityEngine;
using TMPro;

public class PokerChipPile : UdonSharpBehaviour
{
    [Header("Denomination Settings")]
    public int[] denominationValues = new int[] { 10, 50, 100, 500, 1000 };


    public bool supportsSelectableStackMode;
    public int minimumSelectableChipsPerDenomination = 10;
    public Vector3[] denominationOffsets;
    [Tooltip("Local-space shift applied to the whole selectable (immersive) layout, e.g. to keep the chips clear of the player's cards.")]
    public Vector3 selectableLayoutOffset = new Vector3(-0.1f, 0f, 0f);
    public LocalObjectPool[] denominationPools;

    [Header("Dynamic Active Denomination Settings")]
    public int maxActiveDenominations = 3;
    public Transform[] activeDenominationPositions;

    [Header("Chip Settings")]
    public float movingChipDrag = 0.35f;
    public float movingChipContactOffset = 0.002f;
    public PhysicMaterial movingChipMaterial;
    public float chipHeight = 0.003f;
    public int movingChipSolverIterations = 3;
    public int movingChipSolverVelocityIterations = 1;
    public float movingChipMaxDepenetrationVelocity = 2f;

    [Header("Stack Settings")]
    public int stackHeight = 10;
    public float hexSpacing = 0.035f;

    [Header("PID Gather")]
    public bool enableGatherPd = true;
    public float gatherPdSpring = 24f;
    public float gatherPidIntegral = 4f;
    public float gatherPidIntegralLimit = 0.08f;
    public float gatherPdDamping = 8f;
    public float gatherTransportDuration = 0.75f;
    public float gatherPdTargetRadius = 0.075f;
    public float gatherPdHoverHeight = 0.02f;
    public float gatherPdMaxAcceleration = 20f;
    public float gatherSettleDuration = 0.35f;

    [Header("Randomization")]
    public int seed = 12345;
    public float positionJitter = 0.004f;
    public float tiltDegrees = 2f;

    [Header("Natural Layout")]
    [Tooltip("Hex piles keep one denomination per stack with taller stacks in the middle, and between restacks only add or take chips at the stack tops instead of re-deriving the whole layout.")]
    public bool naturalLayout;
    [Tooltip("A pile counted from scratch (empty pile, restack after a win) takes this many chips of every denomination, smallest first, before the largest-first remainder.")]
    public int seedChipsPerDenomination = 5;
    public int centerStackHeight = 18;
    public int outerStackHeight = 5;
    [Tooltip("Ring of the hex grid where stacks reach outerStackHeight.")]
    public int profileRings = 4;
    public float heightJitter = 0.15f;
    [Tooltip("Chip count at which stacks may reach their full height; smaller piles stay lower and spread out.")]
    public int fullPileChips = 250;
    public float minimumFill = 0.3f;
    [Tooltip("Neighbouring stacks sit 0, 1 or 2 times this higher, so chips on adjacent stacks never share a height and z-fight.")]
    public float stackLift = 0.0003f;
    [Tooltip("No stacks within this angle of the pile's +x axis, e.g. to keep chips off the player's cards. The blocked area widens ring by ring like a cone. 0 disables it.")]
    public float blockedConeHalfAngle;
    [Tooltip("Pile-local height the readout must stay under, e.g. the reset button above the stack pile. 0 disables it.")]
    public float ceilingLocalY;
    [Tooltip("Gap between the readout's pivot and the ceiling.")]
    public float ceilingClearance = 0.02f;
    [Tooltip("Gap between the tallest chip under the readout and the readout's pivot; the readout rises to keep it.")]
    public float readoutClearance = 0.02f;
    public float readoutFootprintRadius = 0.045f;

    // Internal
    private Vector3[] stackPositions;
    private int maxStacks;
    private int maxChips;
    private int totalActiveChips;

    private int requestedTotalValue;
    private bool selectableStackMode;
    private Vector3 displayLocalOffset;
    private bool warnedMissingOffsets;
    private int previousTotalValue;

    private int[] activeDenominationSlots;
    private int[] prevActiveDenominationSlots;

    // Chips on the pile, per denomination: slot [denom * denomCapacity + c]
    private int[] sortedIndices;
    private int denomCapacity;
    private GameObject[] heldChips;
    private int[] heldPoolSlots;
    private int[] heldCounts;
    private int[] heldOffsets;
    private GameObject[] movingChips;
    private Rigidbody[] movingBodies;
    private Vector3[] gatherTargetLocal;
    private int gatherTargetCount = -1;
    private Vector3[] gatherIntegralErrors;
    private PhysicMaterial defaultRestingMaterial;
    private int movingChipCount;
    private bool gatherSettling;
    private float gatherStartTime;
    private float gatherEndTime;
    private bool gatherPdActive;

    // Animation (private — not tweakable in inspector)
    private float chipFallOffset = 0.04f;
    private float timeBetweenChipRepositioning = 0.02f;
    private float chipFallDuration = 0.1f;

    // Natural layout: which denomination each hex slot holds, how many chips, and how tall it may grow;
    // each held chip's slot and height, parallel to heldChips (-1 = not placed yet).
    private const int NaturalMaxStacks = 91;
    private const int AxialRadius = 5;
    private int[] stackRing;
    private float[] stackLiftY;
    private bool[] stackBlocked;
    private int[] stackNeighbors;
    private int[] stackDenom;
    private int[] stackCount;
    private int[] stackCapacity;
    private int[] heldStack;
    private int[] heldLevel;
    private int layoutSeed;
    private int layoutGeneration;
    private bool readoutBaseKnown;
    private Vector3 readoutBaseLocal;
    private bool readoutPlaced;
    private float readoutAppliedY;
    // Each denomination's stacks, [d * maxStacks + k] in claim order, so placing a chip only looks at its own stacks.
    private int[] denomStacks;
    private int[] denomStackCount;
    private int maxClaimedRing = -1;
    // Scratch buffers, so count changes do not allocate.
    private int[] naturalCounts;
    private int[] naturalFirstNew;
    private bool[] naturalDone;
    private int[] ascendingIndices;

    // Animation tracking
    private int[] prevCounts;
    private Transform[] animTargets;
    private Vector3[] animStartPositions;
    private Vector3[] animTargetPositions;
    private int animCount;
    private int animFirstPending;
    private float animStartTime;
    [HideInInspector] public bool preservePhysicsPlacement;
    [HideInInspector] public int harnessTotalValue;
    [HideInInspector] public PokerChipPile harnessDestination;


    [Header("Value display")]
    public TMP_Text text;
    public GameObject textGameObject;
    public LookAtPlayerYawOnly lookAtPlayer;


    public void UpdateText()
    {
        if (text == null)
            return;

        if (previousTotalValue > 0)
        {
            text.text = $"{previousTotalValue}";
            if (lookAtPlayer != null)
                lookAtPlayer.enabled = true;
        }
        else
        {
            text.text = "";
            if (lookAtPlayer != null)
                lookAtPlayer.enabled = false;
        }
    }

    public void OverrideText(string newValue)
    {
        if (text == null)
            return;

        text.text = newValue;
    }


    public void SetTextVisibility(bool visible)
    {
        if (textGameObject != null)
        {
            textGameObject.SetActive(visible);
        }
    }


    void Start()
    {
        // Validate pools are assigned
        if (denominationPools == null || denominationPools.Length != denominationValues.Length)
        {
            Debug.LogError("PokerChipPile: denominationPools array must match denominationValues length!");
            return;
        }

        for (int i = 0; i < denominationPools.Length; i++)
        {
            if (denominationPools[i] == null)
            {
                Debug.LogError($"PokerChipPile: Pool for denomination {denominationValues[i]} not assigned!");
            }
        }

        // Set a reasonable default for max stacks
        maxStacks = naturalLayout ? NaturalMaxStacks : 60;
        maxChips = maxStacks * stackHeight;

        int n = denominationValues.Length;
        prevCounts = new int[n];
        animTargets = new Transform[maxChips];
        animStartPositions = new Vector3[maxChips];
        animTargetPositions = new Vector3[maxChips];
        animCount = 0;

        // A denomination can never hold more chips than its pool
        denomCapacity = 1;
        for (int d = 0; d < n; d++)
        {
            if (denominationPools[d] == null || denominationPools[d].Pool == null) continue;
            int poolSize = denominationPools[d].Pool.Length;
            if (poolSize > denomCapacity) denomCapacity = poolSize;
        }
        if (denomCapacity > maxChips) denomCapacity = maxChips;

        sortedIndices = SortedDenominations();
        heldChips = new GameObject[n * denomCapacity];
        heldPoolSlots = new int[n * denomCapacity];
        heldCounts = new int[n];
        heldOffsets = new int[n];
        movingChips = new GameObject[n * denomCapacity];
        movingBodies = new Rigidbody[n * denomCapacity];
        gatherTargetLocal = new Vector3[n * denomCapacity];
        gatherIntegralErrors = new Vector3[n * denomCapacity];

        activeDenominationSlots = new int[n];
        prevActiveDenominationSlots = new int[n];
        for (int i = 0; i < n; i++) { activeDenominationSlots[i] = -1; prevActiveDenominationSlots[i] = -1; }

        heldStack = new int[n * denomCapacity];
        heldLevel = new int[n * denomCapacity];
        for (int i = 0; i < heldStack.Length; i++) heldStack[i] = -1;
        layoutSeed = seed;
        // The readout moves through its GameObject: Udon does not expose TMP_Text.transform.
        if (text != null && textGameObject != null)
        {
            readoutBaseLocal = transform.InverseTransformPoint(textGameObject.transform.position);
            readoutBaseKnown = true;
        }

        GenerateHexGrid();
        denomStacks = new int[n * maxStacks];
        denomStackCount = new int[n];
        naturalCounts = new int[n];
        naturalFirstNew = new int[n];
        naturalDone = new bool[n];
        ascendingIndices = SortedDenominationsAscending();
        SetTotalChips(0);
        UpdateText();
        SetTextVisibility(true);

        RefreshUpdateState();
    }

    /* ---------------------------
     * Public API
     * --------------------------- */

    /// <summary>
    /// Set the total chip value to display. Calculates and displays chips by denomination.
    /// </summary>
public void SetTotalChips(int totalValue)
    {
        if (totalValue < 0) totalValue = 0;
        requestedTotalValue = totalValue;
        if (previousTotalValue == totalValue) return;

        previousTotalValue = totalValue;
        UpdateText();
        if (UsesNaturalLayout())
        {
            SetNaturalTotal(totalValue, false);
            return;
        }
        if (selectableStackMode && maxActiveDenominations > 0)
            SelectActiveDenominations(totalValue);
        UpdateChipDisplay(selectableStackMode
            ? CalculateSelectableDenominationCounts(totalValue)
            : CalculateDenominationCounts(totalValue));
    }

    /// <summary>
    /// Shows <paramref name="totalValue"/> counted from scratch (a few chips of every denomination, then the
    /// largest first) and stacked anew, like a dealer pushing a pot into a stack. Natural-layout piles only;
    /// others just set the total.
    /// </summary>
    public void ReseedTotal(int totalValue)
    {
        if (!UsesNaturalLayout())
        {
            SetTotalChips(totalValue);
            return;
        }
        if (totalValue < 0) totalValue = 0;
        requestedTotalValue = totalValue;
        previousTotalValue = totalValue;
        UpdateText();
        SetNaturalTotal(totalValue, true);
    }

    /// <summary>Restacks the chips on display without changing them. Natural-layout piles only.</summary>
    public void _RestackLayout()
    {
        if (!UsesNaturalLayout()) return;
        SettleAnimation();
        RebuildNaturalLayout(true);
        UpdateReadoutPosition();
    }

public void _HarnessSetTotalChips()
    {
        SetTotalChips(harnessTotalValue);
    }

    public void _HarnessTransferAllAnimated()
    {
        TransferAllAnimatedTo(harnessDestination);
    }


    public int GetTotalDisplayedValue()
    {
        if (heldCounts == null || denominationValues == null) return 0;
        int total = 0;
        int count = Mathf.Min(heldCounts.Length, denominationValues.Length);
        for (int i = 0; i < count; i++) total += heldCounts[i] * Mathf.Max(0, denominationValues[i]);
        return total;
    }

    /// <summary>
    /// Plays the fall-in animation for chips that arrived through an exact (teleporting) transfer: every chip
    /// above <paramref name="previousCounts"/> per denomination drops in from above, like chips added by SetTotalChips.
    /// </summary>
    public void AnimateChipsAddedSince(int[] previousCounts)
    {
        if (previousCounts == null || heldCounts == null || animTargets == null) return;
        SettleAnimation();
        for (int d = 0; d < heldCounts.Length; d++)
        {
            int baseSlot = d * denomCapacity;
            int firstNew = d < previousCounts.Length ? previousCounts[d] : 0;
            for (int chipIndex = firstNew; chipIndex < heldCounts[d]; chipIndex++)
            {
                GameObject chip = heldChips[baseSlot + chipIndex];
                if (chip == null || animCount >= animTargets.Length) continue;
                Transform chipTransform = chip.transform;
                Vector3 finalPosition = chipTransform.localPosition;
                animTargets[animCount] = chipTransform;
                animStartPositions[animCount] = finalPosition + Vector3.up * chipFallOffset;
                animTargetPositions[animCount] = finalPosition;
                chipTransform.localPosition = animStartPositions[animCount];
                animCount++;
            }
        }
        animStartTime = Time.time;
        RefreshUpdateState();
    }

    public void CopyDisplayedDenominationCounts(int[] destination)
    {
        if (destination == null) return;
        for (int i = 0; i < destination.Length; i++)
            destination[i] = heldCounts != null && i < heldCounts.Length ? heldCounts[i] : 0;
    }

    /// <summary>
    /// Calculate how many chips of each denomination are needed for the given total value.
    /// Uses greedy algorithm starting from highest denomination.
    /// </summary>
    private int[] CalculateDenominationCounts(int totalValue)
    {
        int[] counts = new int[denominationValues.Length];
        int remaining = totalValue;

        int[] order = sortedIndices != null ? sortedIndices : SortedDenominations();

        // Greedy allocation
        for (int i = 0; i < order.Length; i++)
        {
            int denomIndex = order[i];
            int denomValue = denominationValues[denomIndex];
            if (denomValue > 0)
            {
                counts[denomIndex] = remaining / denomValue;
                remaining = remaining % denomValue;
            }
        }

        return counts;
    }

private int[] CalculateSelectableDenominationCounts(int totalValue)
    {
        int count = denominationValues == null ? 0 : denominationValues.Length;
        int[] counts = new int[count];
        int remaining = Mathf.Max(0, totalValue);
        int[] ascending = SortedDenominationsAscending();
        bool hasActiveFilter = maxActiveDenominations > 0;

        for (int i = 0; i < ascending.Length; i++)
        {
            int denominationIndex = ascending[i];
            if (hasActiveFilter && !IsDenominationActive(denominationIndex)) continue;
            int value = denominationValues[denominationIndex];
            if (value <= 0 || remaining < value) continue;

            int seed = Mathf.Min(minimumSelectableChipsPerDenomination, remaining / value);
            counts[denominationIndex] += seed;
            remaining -= seed * value;
        }

        for (int i = ascending.Length - 1; i >= 0; i--)
        {
            int denominationIndex = ascending[i];
            if (hasActiveFilter && !IsDenominationActive(denominationIndex)) continue;
            int value = denominationValues[denominationIndex];
            if (value <= 0) continue;

            int extra = remaining / value;
            counts[denominationIndex] += extra;
            remaining -= extra * value;
        }

        return counts;
    }

    private int[] SortedDenominationsAscending()
    {
        int count = denominationValues == null ? 0 : denominationValues.Length;
        int[] indices = new int[count];
        for (int i = 0; i < count; i++) indices[i] = i;

        for (int i = 0; i < count - 1; i++)
        {
            for (int j = 0; j < count - i - 1; j++)
            {
                int left = indices[j];
                int right = indices[j + 1];
                if (denominationValues[left] > denominationValues[right])
                {
                    indices[j] = right;
                    indices[j + 1] = left;
                }
            }
        }
        return indices;
    }


    // Denomination indices sorted by value, highest first
    private int[] SortedDenominations()
    {
        int[] indices = new int[denominationValues.Length];
        for (int i = 0; i < indices.Length; i++)
        {
            indices[i] = i;
        }

        for (int i = 0; i < indices.Length - 1; i++)
        {
            for (int j = 0; j < indices.Length - i - 1; j++)
            {
                if (denominationValues[indices[j]] < denominationValues[indices[j + 1]])
                {
                    int temp = indices[j];
                    indices[j] = indices[j + 1];
                    indices[j + 1] = temp;
                }
            }
        }

        return indices;
    }

    /// <summary>
    /// Update the visual chip display based on denomination counts.
    /// Only chips that are added, removed or shifted are touched. Newly-added
    /// chips get the fall-in animation, and chips below the first changed
    /// denomination cascade.
    /// </summary>
private void UpdateChipDisplay(int[] counts)
    {
        if (sortedIndices == null || counts == null) return;
        SettleAnimation();

        int firstChangedSortedIndex = int.MaxValue;
        int oldCountForChanged = 0;
        for (int idx = 0; idx < sortedIndices.Length; idx++)
        {
            int denominationIndex = sortedIndices[idx];
            if (counts[denominationIndex] != prevCounts[denominationIndex])
            {
                firstChangedSortedIndex = idx;
                oldCountForChanged = prevCounts[denominationIndex];
                break;
            }
        }

        int layoutIndex = 0;
        for (int i = 0; i < sortedIndices.Length; i++)
        {
            int denominationIndex = sortedIndices[i];
            LocalObjectPool pool = denominationPools[denominationIndex];
            if (pool == null)
            {
                Debug.LogWarning("PokerChipPile: missing pool for denomination " + denominationValues[denominationIndex] + ".");
                continue;
            }

            int baseSlot = denominationIndex * denomCapacity;
            int held = heldCounts[denominationIndex];
            int targetOffset = selectableStackMode ? 0 : layoutIndex;
            bool shifted = heldOffsets[denominationIndex] != targetOffset;
            heldOffsets[denominationIndex] = targetOffset;

            bool slotChanged = false;
            if (selectableStackMode && maxActiveDenominations > 0 && prevActiveDenominationSlots != null)
            {
                int prevSlot = denominationIndex < prevActiveDenominationSlots.Length ? prevActiveDenominationSlots[denominationIndex] : -1;
                int currentSlot = activeDenominationSlots != null && denominationIndex < activeDenominationSlots.Length ? activeDenominationSlots[denominationIndex] : -1;
                slotChanged = prevSlot != currentSlot;
            }

            int wanted = Mathf.Max(0, counts[denominationIndex]);
            int capacity = Mathf.Min(denomCapacity, pool.Pool == null ? 0 : pool.Pool.Length);
            if (wanted > capacity) wanted = capacity;
            if (!selectableStackMode && layoutIndex + wanted > maxChips)
                wanted = Mathf.Max(0, maxChips - layoutIndex);

            while (held > wanted)
            {
                held--;
                pool.ReturnIndex(heldPoolSlots[baseSlot + held]);
                heldChips[baseSlot + held] = null;
            }
            int kept = held;

            while (held < wanted)
            {
                GameObject spawned = pool.TryToSpawn();
                if (spawned == null) break;
                spawned.transform.SetParent(transform);
                heldChips[baseSlot + held] = spawned;
                heldPoolSlots[baseSlot + held] = pool.lastSpawnedIndex;
                held++;
            }

            int firstNewIndex = i == firstChangedSortedIndex ? oldCountForChanged : 0;
            for (int chipIndex = 0; chipIndex < held; chipIndex++)
            {
                bool animate = selectableStackMode
                    ? i == firstChangedSortedIndex && chipIndex >= firstNewIndex
                    : i > firstChangedSortedIndex || (i == firstChangedSortedIndex && chipIndex >= firstNewIndex);
                if (chipIndex < kept && !shifted && !animate && !slotChanged) continue;

                Transform chipTransform = heldChips[baseSlot + chipIndex].transform;
                PlaceChip(chipTransform, denominationIndex, chipIndex,
                    selectableStackMode ? chipIndex : layoutIndex + chipIndex);

                if (animate && animCount < animTargets.Length)
                {
                    Vector3 finalPosition = chipTransform.localPosition;
                    animTargets[animCount] = chipTransform;
                    animStartPositions[animCount] = finalPosition + Vector3.up * chipFallOffset;
                    animTargetPositions[animCount] = finalPosition;
                    chipTransform.localPosition = animStartPositions[animCount];
                    animCount++;
                }
            }

            heldCounts[denominationIndex] = held;
            layoutIndex += held;
        }

        totalActiveChips = layoutIndex;
        for (int i = 0; i < counts.Length; i++) prevCounts[i] = counts[i];

        if (prevActiveDenominationSlots != null && activeDenominationSlots != null)
        {
            int copyLength = Mathf.Min(prevActiveDenominationSlots.Length, activeDenominationSlots.Length);
            for (int i = 0; i < copyLength; i++)
                prevActiveDenominationSlots[i] = activeDenominationSlots[i];
        }

        animStartTime = Time.time;
        RefreshUpdateState();
    }

    /// <summary>
    /// Every frame, interpolate queued chips from their elevated start
    /// position down to their final position using a cubic ease-out
    /// curve that mimics gravity settling. Chips are staggered by
    /// timeBetweenChipRepositioning so the bottom chip lands first.
    /// </summary>
void Update()
    {
        if (gatherPdActive)
        {
            float now = Time.time;
            if (!gatherSettling && now >= gatherStartTime + Mathf.Max(0f, gatherTransportDuration))
                gatherSettling = true;
            if (now >= gatherEndTime)
                EndAnimatedContraction();
        }

        if (animCount == 0)
        {
            RefreshUpdateState();
            return;
        }

        // Chips fall for the same time with growing delays, so they land in queue order: the landed ones are a
        // prefix that is skipped, and the loop stops at the first chip that has not started falling. Each frame only
        // touches the few chips in the air, however long the queue is.
        float animationNow = Time.time;
        bool allLanded = true;
        for (int i = animFirstPending; i < animCount; i++)
        {
            float delay = i * timeBetweenChipRepositioning;
            float elapsed = animationNow - animStartTime - delay;
            if (elapsed <= 0f)
            {
                allLanded = false;
                break;
            }

            Transform t = animTargets[i];
            float progress = elapsed / chipFallDuration;
            if (t == null || progress >= 1f)
            {
                if (t != null) t.localPosition = animTargetPositions[i];
                if (i == animFirstPending) animFirstPending++;
                continue;
            }
            allLanded = false;

            float oneMinusT = 1f - progress;
            float eased = 1f - (oneMinusT * oneMinusT * oneMinusT);
            t.localPosition = Vector3.Lerp(animStartPositions[i], animTargetPositions[i], eased);
        }

        if (allLanded)
        {
            animCount = 0;
            animFirstPending = 0;
            RefreshUpdateState();
        }
    }

void FixedUpdate()
    {
        if (!enableGatherPd || !gatherPdActive || movingChipCount <= 0) return;

        int count = movingChipCount;
        float targetRadius = Mathf.Max(0f, gatherPdTargetRadius);
        // Each chip's slot on the sunflower spiral only depends on its index and the chip count,
        // so it is worked out once, not with sqrt/sin/cos per chip per step.
        if (gatherTargetCount != count)
        {
            gatherTargetCount = count;
            for (int i = 0; i < count; i++)
            {
                float angle = i * 2.399963f;
                float radius = targetRadius * Mathf.Sqrt((i + 0.5f) / count);
                gatherTargetLocal[i] = new Vector3(Mathf.Cos(angle) * radius, 0f, Mathf.Sin(angle) * radius);
            }
        }

        bool settling = gatherSettling;
        Quaternion rotation = transform.rotation;
        Vector3 up = rotation * Vector3.up;
        Vector3 basePoint = transform.position;
        if (!settling) basePoint += up * Mathf.Max(0f, gatherPdHoverHeight);
        float dt = Time.fixedDeltaTime;
        float spring = Mathf.Max(0f, gatherPdSpring);
        float integralGain = Mathf.Max(0f, gatherPidIntegral);
        float integralLimit = Mathf.Max(0f, gatherPidIntegralLimit);
        float integralLimitSqr = integralLimit * integralLimit;
        float damping = Mathf.Max(0f, gatherPdDamping);
        float maxAcceleration = Mathf.Max(0f, gatherPdMaxAcceleration);
        float maxAccelerationSqr = maxAcceleration * maxAcceleration;

        for (int i = 0; i < count; i++)
        {
            Rigidbody body = movingBodies[i];
            if (body == null || body.isKinematic) continue;

            Vector3 positionError = basePoint + rotation * gatherTargetLocal[i] - body.worldCenterOfMass;
            Vector3 controlledVelocity = body.velocity;
            if (settling)
            {
                positionError -= up * Vector3.Dot(positionError, up);
                controlledVelocity -= up * Vector3.Dot(controlledVelocity, up);
            }

            Vector3 integral = gatherIntegralErrors[i] + positionError * dt;
            if (settling) integral -= up * Vector3.Dot(integral, up);
            if (integralLimit <= 0f)
                integral = Vector3.zero;
            else if (integral.sqrMagnitude > integralLimitSqr)
                integral = integral.normalized * integralLimit;
            gatherIntegralErrors[i] = integral;

            Vector3 acceleration = positionError * spring + integral * integralGain - controlledVelocity * damping;
            if (maxAcceleration > 0f && acceleration.sqrMagnitude > maxAccelerationSqr)
                acceleration = acceleration.normalized * maxAcceleration;
            body.AddForce(acceleration, ForceMode.Acceleration);
        }
    }


    /* ---------------------------
     * Initialization
     * --------------------------- */

    private void GenerateHexGrid()
    {
        stackPositions = new Vector3[maxStacks];
        stackPositions[0] = Vector3.zero;
        stackRing = new int[maxStacks];
        stackDenom = new int[maxStacks];
        stackCount = new int[maxStacks];
        stackCapacity = new int[maxStacks];
        for (int i = 0; i < maxStacks; i++) stackDenom[i] = -1;

        // Axial coordinates of each slot (q along dirs[0], r along dirs[1]), to find neighbours without
        // comparing every pair of slots.
        int axialWidth = AxialRadius * 2 + 1;
        int[] axialToSlot = new int[axialWidth * axialWidth];
        for (int i = 0; i < axialToSlot.Length; i++) axialToSlot[i] = -1;
        int[] slotQ = new int[maxStacks];
        int[] slotR = new int[maxStacks];
        axialToSlot[AxialRadius * axialWidth + AxialRadius] = 0;
        int[] dirQ = new int[] { 1, 0, -1, -1, 0, 1 };
        int[] dirR = new int[] { 0, 1, 1, 0, -1, -1 };

        int index = 1;

        Vector3[] dirs = new Vector3[]
        {
            new Vector3(1f, 0f, 0f),
            new Vector3(0.5f, 0f, 0.866f),
            new Vector3(-0.5f, 0f, 0.866f),
            new Vector3(-1f, 0f, 0f),
            new Vector3(-0.5f, 0f, -0.866f),
            new Vector3(0.5f, 0f, -0.866f)
        };

        for (int ring = 1; index < maxStacks; ring++)
        {
            Vector3 pos = dirs[4] * ring * hexSpacing;
            int q = 0;
            int r = -ring;

            for (int dir = 0; dir < 6 && index < maxStacks; dir++)
            {
                for (int step = 0; step < ring && index < maxStacks; step++)
                {
                    stackRing[index] = ring;
                    slotQ[index] = q;
                    slotR[index] = r;
                    if (ring <= AxialRadius)
                        axialToSlot[(q + AxialRadius) * axialWidth + r + AxialRadius] = index;
                    stackPositions[index++] = pos;
                    pos += dirs[dir] * hexSpacing;
                    q += dirQ[dir];
                    r += dirR[dir];
                }
            }
        }

        // (q - r) mod 3 differs between every pair of neighbours, so adjacent stacks never share a lift.
        stackLiftY = new float[maxStacks];
        stackBlocked = new bool[maxStacks];
        for (int slot = 0; slot < maxStacks; slot++)
        {
            stackLiftY[slot] = (((slotQ[slot] - slotR[slot]) % 3 + 3) % 3) * stackLift;
            if (slot == 0 || blockedConeHalfAngle <= 0f) continue;
            Vector3 p = stackPositions[slot];
            stackBlocked[slot] = Mathf.Atan2(Mathf.Abs(p.z), p.x) * Mathf.Rad2Deg <= blockedConeHalfAngle + 0.5f;
        }

        stackNeighbors = new int[maxStacks * 6];
        for (int slot = 0; slot < maxStacks; slot++)
        {
            for (int dir = 0; dir < 6; dir++)
            {
                int q = slotQ[slot] + dirQ[dir] + AxialRadius;
                int r = slotR[slot] + dirR[dir] + AxialRadius;
                stackNeighbors[slot * 6 + dir] = q >= 0 && q < axialWidth && r >= 0 && r < axialWidth
                    ? axialToSlot[q * axialWidth + r]
                    : -1;
            }
        }
    }

    /* ---------------------------
     * Natural layout
     *
     * One denomination per stack, taller stacks in the middle of the hex grid. Between restacks chips are only
     * added to or taken from the tops of stacks, so a pot that grows over a hand never reshuffles. A stack's soft
     * height limit grows with the pile, so a small pile is low and spread out and a big one rises in the middle.
     * --------------------------- */

    private bool UsesNaturalLayout()
    {
        return naturalLayout && !selectableStackMode && stackDenom != null && heldStack != null && denomStacks != null;
    }

    private int HeldChipTotal()
    {
        int total = 0;
        for (int d = 0; d < heldCounts.Length; d++) total += heldCounts[d];
        return total;
    }

    // From an empty pile, or when reseeding, the counts are worked out from scratch. Otherwise the chips on display
    // stay: a lower total takes chips off (breaking a larger chip into change when nothing smaller fits), a higher
    // total adds chips largest first.
    private void SetNaturalTotal(int totalValue, bool reseed)
    {
        int n = denominationValues.Length;
        int[] counts = naturalCounts;
        if (reseed || HeldChipTotal() == 0)
        {
            SeededDenominationCounts(totalValue, counts);
            ApplyNaturalCounts(counts, true);
            return;
        }

        for (int d = 0; d < n; d++) counts[d] = heldCounts[d];
        int displayed = GetTotalDisplayedValue();
        int target = GreedyRepresentableValue(totalValue);

        int toRemove = displayed - target;
        while (toRemove > 0)
        {
            int pick = -1;
            int pickValue = -1;
            for (int d = 0; d < n; d++)
            {
                int value = denominationValues[d];
                if (counts[d] <= 0 || value <= 0 || value > toRemove || value <= pickValue) continue;
                pick = d;
                pickValue = value;
            }
            if (pick < 0)
            {
                // Nothing small enough: take the smallest larger chip and give change.
                for (int d = 0; d < n; d++)
                {
                    int value = denominationValues[d];
                    if (counts[d] <= 0 || value <= 0) continue;
                    if (pick < 0 || value < pickValue)
                    {
                        pick = d;
                        pickValue = value;
                    }
                }
            }
            if (pick < 0) break;
            counts[pick]--;
            toRemove -= pickValue;
        }

        int toAdd = toRemove < 0 ? -toRemove : target - displayed;
        if (toAdd > 0) AddGreedyCounts(counts, toAdd);
        ApplyNaturalCounts(counts, false);
    }

    // The part of totalValue the denominations can show, largest first (what CalculateDenominationCounts adds up to).
    private int GreedyRepresentableValue(int totalValue)
    {
        int remaining = Mathf.Max(0, totalValue);
        for (int i = 0; i < sortedIndices.Length; i++)
        {
            int value = denominationValues[sortedIndices[i]];
            if (value > 0) remaining %= value;
        }
        return Mathf.Max(0, totalValue) - remaining;
    }

    // A few chips of every denomination, smallest first, then the rest largest first.
    private void SeededDenominationCounts(int totalValue, int[] counts)
    {
        for (int d = 0; d < counts.Length; d++) counts[d] = 0;
        int remaining = Mathf.Max(0, totalValue);
        int seedCount = Mathf.Max(0, seedChipsPerDenomination);
        for (int i = 0; i < ascendingIndices.Length; i++)
        {
            int d = ascendingIndices[i];
            int value = denominationValues[d];
            if (value <= 0) continue;
            int take = Mathf.Min(seedCount, remaining / value);
            counts[d] += take;
            remaining -= take * value;
        }
        for (int i = ascendingIndices.Length - 1; i >= 0; i--)
        {
            int d = ascendingIndices[i];
            int value = denominationValues[d];
            if (value <= 0) continue;
            int take = remaining / value;
            counts[d] += take;
            remaining -= take * value;
        }
    }

    // Adds value to counts largest chip first, only as far as the pools (and chips this pile already holds) allow.
    private void AddGreedyCounts(int[] counts, int value)
    {
        for (int i = 0; i < sortedIndices.Length && value > 0; i++)
        {
            int d = sortedIndices[i];
            int chipValue = denominationValues[d];
            if (chipValue <= 0 || value < chipValue) continue;
            LocalObjectPool pool = d < denominationPools.Length ? denominationPools[d] : null;
            if (pool == null || pool.Pool == null) continue;
            int reusable = Mathf.Max(0, heldCounts[d] - counts[d]);
            int spawnable = Mathf.Max(0, pool.availableCount - Mathf.Max(0, counts[d] - heldCounts[d]));
            int room = Mathf.Min(Mathf.Min(denomCapacity, pool.Pool.Length) - counts[d], reusable + spawnable);
            int take = Mathf.Min(value / chipValue, room);
            if (take <= 0) continue;
            counts[d] += take;
            value -= take * chipValue;
        }
    }

    // Removes and spawns chips to reach counts. Kept chips stay where they are unless restacking; new chips fall in.
    private void ApplyNaturalCounts(int[] counts, bool restack)
    {
        SettleAnimation();
        int n = denominationValues.Length;
        int[] firstNew = naturalFirstNew;
        for (int d = 0; d < n; d++)
        {
            LocalObjectPool pool = d < denominationPools.Length ? denominationPools[d] : null;
            int baseSlot = d * denomCapacity;
            int held = heldCounts[d];
            int capacity = pool == null || pool.Pool == null ? 0 : Mathf.Min(denomCapacity, pool.Pool.Length);
            int wanted = Mathf.Clamp(counts[d], 0, capacity);

            while (held > wanted)
            {
                int index = baseSlot + held - 1;
                ForgetChipPlacement(index);
                if (pool != null) pool.ReturnIndex(heldPoolSlots[index]);
                heldChips[index] = null;
                heldPoolSlots[index] = -1;
                held--;
                heldCounts[d] = held;
            }
            firstNew[d] = held;

            while (held < wanted)
            {
                GameObject spawned = pool.TryToSpawn();
                if (spawned == null) break;
                spawned.transform.SetParent(transform);
                heldChips[baseSlot + held] = spawned;
                heldPoolSlots[baseSlot + held] = pool.lastSpawnedIndex;
                heldStack[baseSlot + held] = -1;
                held++;
            }
            heldCounts[d] = held;
        }

        // Both place only the chips they (re)assign.
        if (restack) RebuildNaturalLayout(true);
        else AssignUnplacedChips();

        for (int d = 0; d < n; d++)
        {
            int baseSlot = d * denomCapacity;
            for (int chipIndex = firstNew[d]; chipIndex < heldCounts[d] && animCount < animTargets.Length; chipIndex++)
            {
                Transform chipTransform = heldChips[baseSlot + chipIndex].transform;
                Vector3 finalPosition = chipTransform.localPosition;
                animTargets[animCount] = chipTransform;
                animStartPositions[animCount] = finalPosition + Vector3.up * chipFallOffset;
                animTargetPositions[animCount] = finalPosition;
                chipTransform.localPosition = animStartPositions[animCount];
                animCount++;
            }
            prevCounts[d] = heldCounts[d];
        }
        totalActiveChips = HeldChipTotal();
        animStartTime = Time.time;
        UpdateReadoutPosition();
        RefreshUpdateState();
    }

    private void RebuildNaturalLayout(bool newSeed)
    {
        if (newSeed)
        {
            layoutGeneration++;
            layoutSeed = seed + layoutGeneration * 7919;
        }
        ComputeStackCapacities();
        ClearNaturalLayout();
        float fill = NaturalFill(HeldChipTotal());

        // The denomination with the most chips claims stacks first, so it takes the middle of the pile.
        int n = heldCounts.Length;
        bool[] done = naturalDone;
        for (int i = 0; i < n; i++) done[i] = false;
        for (int pass = 0; pass < n; pass++)
        {
            int d = -1;
            for (int i = 0; i < n; i++)
                if (!done[i] && (d < 0 || heldCounts[i] > heldCounts[d])) d = i;
            done[d] = true;
            int baseSlot = d * denomCapacity;
            for (int chipIndex = 0; chipIndex < heldCounts[d]; chipIndex++)
                AssignChip(baseSlot + chipIndex, d, fill);
        }
    }

    private void ClearNaturalLayout()
    {
        if (stackDenom == null || heldStack == null) return;
        for (int s = 0; s < stackDenom.Length; s++)
        {
            stackDenom[s] = -1;
            stackCount[s] = 0;
        }
        for (int i = 0; i < heldStack.Length; i++) heldStack[i] = -1;
        if (denomStackCount != null)
            for (int d = 0; d < denomStackCount.Length; d++) denomStackCount[d] = 0;
        maxClaimedRing = -1;
    }

    private void AssignUnplacedChips()
    {
        if (stackCapacity[0] <= 0) ComputeStackCapacities();
        float fill = NaturalFill(HeldChipTotal());
        for (int orderIndex = 0; orderIndex < sortedIndices.Length; orderIndex++)
        {
            int d = sortedIndices[orderIndex];
            int baseSlot = d * denomCapacity;
            for (int chipIndex = 0; chipIndex < heldCounts[d]; chipIndex++)
                if (heldStack[baseSlot + chipIndex] < 0) AssignChip(baseSlot + chipIndex, d, fill);
        }
    }

    // Puts the chip on top of a stack and moves it there; nothing else on the pile is touched.
    private void AssignChip(int index, int denominationIndex, float fill)
    {
        int s = ChooseStack(denominationIndex, fill);
        if (s < 0)
        {
            heldStack[index] = -1;
            return;
        }
        heldStack[index] = s;
        heldLevel[index] = stackCount[s];
        stackCount[s]++;
        if (stackDenom[s] < 0) stackDenom[s] = denominationIndex;
        GameObject chip = heldChips[index];
        if (chip != null) PlaceNaturalChip(chip.transform, index);
    }

    // The own stack with the most room under its soft limit, else a new stack, else (grid full) the shortest
    // own stack, else the shortest stack of all.
    private int ChooseStack(int denominationIndex, float fill)
    {
        int listBase = denominationIndex * maxStacks;
        int owned = denomStackCount[denominationIndex];
        int best = -1;
        int bestSlack = 0;
        for (int k = 0; k < owned; k++)
        {
            int s = denomStacks[listBase + k];
            int slack = SoftCapacity(s, fill) - stackCount[s];
            if (slack > bestSlack)
            {
                best = s;
                bestSlack = slack;
            }
        }
        if (best >= 0) return best;

        best = ClaimFreeStack(denominationIndex);
        if (best >= 0) return best;

        int lowest = int.MaxValue;
        for (int k = 0; k < owned; k++)
        {
            int s = denomStacks[listBase + k];
            if (stackCount[s] >= lowest) continue;
            best = s;
            lowest = stackCount[s];
        }
        if (best >= 0) return best;
        for (int s = 0; s < maxStacks; s++)
        {
            if (stackCount[s] >= lowest || stackBlocked[s]) continue;
            best = s;
            lowest = stackCount[s];
        }
        return best;
    }

    // Free slots next to the denomination's own stacks come first, then next to any stack, nearer the middle
    // first; the seeded tie-break differs per denomination so colours grow in different directions. Slots are
    // numbered ring by ring, and nothing beyond the ring after the outermost claimed one can touch the pile, so the
    // search stops there.
    private int ClaimFreeStack(int denominationIndex)
    {
        int searchRing = maxClaimedRing + 1;
        int searchEnd = Mathf.Min(maxStacks, 1 + 3 * searchRing * (searchRing + 1));
        int best = -1;
        float bestScore = float.MaxValue;
        for (int s = 0; s < searchEnd; s++)
        {
            if (stackCount[s] > 0 || stackBlocked[s]) continue;
            bool nextToOwn = false;
            bool nextToAny = false;
            for (int k = 0; k < 6; k++)
            {
                int neighbor = stackNeighbors[s * 6 + k];
                if (neighbor < 0 || stackCount[neighbor] <= 0) continue;
                nextToAny = true;
                if (stackDenom[neighbor] == denominationIndex) nextToOwn = true;
            }
            float score = stackRing[s]
                + (nextToOwn ? 0f : 1.5f)
                + (nextToAny ? 0f : 3f)
                + 0.25f * (Hash01(s * 7907 + layoutSeed * 13 + denominationIndex * 101) + 1f);
            if (score < bestScore)
            {
                best = s;
                bestScore = score;
            }
        }
        if (best < 0) return -1;
        stackDenom[best] = denominationIndex;
        denomStacks[denominationIndex * maxStacks + denomStackCount[denominationIndex]] = best;
        denomStackCount[denominationIndex]++;
        if (stackRing[best] > maxClaimedRing) maxClaimedRing = stackRing[best];
        return best;
    }

    private float NaturalFill(int chipCount)
    {
        if (fullPileChips <= 0) return 1f;
        return Mathf.Clamp(Mathf.Sqrt(chipCount / (float)fullPileChips), Mathf.Clamp01(minimumFill), 1f);
    }

    private int SoftCapacity(int stack, float fill)
    {
        return Mathf.Max(1, Mathf.RoundToInt(stackCapacity[stack] * fill));
    }

    // Taller in the middle, falling off by ring, with seeded variation everywhere but the middle stack (so it
    // stays the tallest); scaled down as a whole under a ceiling.
    private void ComputeStackCapacities()
    {
        int ceilingCapacity = CeilingCapacity();
        float scale = centerStackHeight > ceilingCapacity ? ceilingCapacity / (float)centerStackHeight : 1f;
        for (int s = 0; s < maxStacks; s++)
        {
            float t = profileRings > 0 ? Mathf.Clamp01(stackRing[s] / (float)profileRings) : 1f;
            float jitter = stackRing[s] > 0 ? heightJitter * Hash01(s * 7919 + layoutSeed * 31 + 3) : 0f;
            float height = Mathf.Lerp(centerStackHeight, outerStackHeight, t) * scale * (1f + jitter);
            stackCapacity[s] = Mathf.Clamp(Mathf.RoundToInt(height), 1, ceilingCapacity);
        }
    }

    // Chips a stack may hold so the risen readout still clears the ceiling.
    private int CeilingCapacity()
    {
        if (ceilingLocalY <= 0f || chipHeight <= 0f) return 100000;
        float reserve = ceilingClearance + (text != null ? readoutClearance : 0f) + 2f * stackLift;
        return Mathf.Max(1, Mathf.FloorToInt((ceilingLocalY - displayLocalOffset.y - reserve) / chipHeight));
    }

    // Drops a chip from its stack; chips above it in the same stack settle down one level. Chips only ever leave
    // from the top in practice, so the scan for chips above is the rare path.
    private void ForgetChipPlacement(int index)
    {
        if (heldStack == null || stackCount == null) return;
        int s = heldStack[index];
        if (s < 0) return;
        heldStack[index] = -1;
        int level = heldLevel[index];
        if (level < stackCount[s] - 1)
        {
            for (int d = 0; d < heldCounts.Length; d++)
            {
                int baseSlot = d * denomCapacity;
                for (int chipIndex = 0; chipIndex < heldCounts[d]; chipIndex++)
                {
                    int other = baseSlot + chipIndex;
                    if (other == index || heldStack[other] != s || heldLevel[other] <= level) continue;
                    heldLevel[other]--;
                    if (heldChips[other] != null) PlaceNaturalChip(heldChips[other].transform, other);
                }
            }
        }
        stackCount[s]--;
        if (stackCount[s] > 0) return;

        stackCount[s] = 0;
        int owner = stackDenom[s];
        stackDenom[s] = -1;
        if (owner < 0 || denomStackCount == null) return;
        int listBase = owner * maxStacks;
        int owned = denomStackCount[owner];
        for (int k = 0; k < owned; k++)
        {
            if (denomStacks[listBase + k] != s) continue;
            denomStacks[listBase + k] = denomStacks[listBase + owned - 1];
            denomStackCount[owner] = owned - 1;
            break;
        }
    }

    private void PlaceAllNaturalChips()
    {
        for (int d = 0; d < heldCounts.Length; d++)
        {
            int baseSlot = d * denomCapacity;
            for (int chipIndex = 0; chipIndex < heldCounts[d]; chipIndex++)
            {
                GameObject chip = heldChips[baseSlot + chipIndex];
                if (chip != null) PlaceNaturalChip(chip.transform, baseSlot + chipIndex);
            }
        }
    }

    // Position and yaw depend only on the chip's slot and height, so a chip that stays put never moves.
    private void PlaceNaturalChip(Transform chipTransform, int index)
    {
        int s = heldStack[index];
        if (s < 0) return;
        int level = heldLevel[index];
        Vector3 position = stackPositions[s] + displayLocalOffset;
        position.y += stackLiftY[s] + level * chipHeight;
        int hash = s * 977 + level * 131 + layoutSeed;
        position.x += Hash01(hash) * positionJitter;
        position.z += Hash01(hash + 17) * positionJitter;
        chipTransform.localPosition = position;
        chipTransform.localRotation = Quaternion.Euler(-90f, Hash01(hash + 43) * 360f, 0f);
    }

    // The readout rises to stay clear of the chips under it, but never past the ceiling. Written only when its
    // height changes.
    private void UpdateReadoutPosition()
    {
        if (textGameObject == null || !readoutBaseKnown) return;
        float y = readoutBaseLocal.y;
        if (UsesNaturalLayout())
        {
            float radiusSqr = readoutFootprintRadius * readoutFootprintRadius;
            int footprintRing = hexSpacing > 0f ? Mathf.CeilToInt(readoutFootprintRadius / hexSpacing) + 1 : AxialRadius;
            int searchEnd = Mathf.Min(maxStacks, 1 + 3 * footprintRing * (footprintRing + 1));
            for (int s = 0; s < searchEnd; s++)
            {
                if (stackCount[s] <= 0) continue;
                Vector3 stackBase = stackPositions[s] + displayLocalOffset;
                float dx = stackBase.x - readoutBaseLocal.x;
                float dz = stackBase.z - readoutBaseLocal.z;
                if (dx * dx + dz * dz > radiusSqr) continue;
                y = Mathf.Max(y, stackBase.y + stackLiftY[s] + stackCount[s] * chipHeight + readoutClearance);
            }
            if (ceilingLocalY > 0f)
                y = Mathf.Max(readoutBaseLocal.y, Mathf.Min(y, ceilingLocalY - ceilingClearance));
        }
        if (readoutPlaced && y == readoutAppliedY) return;
        readoutPlaced = true;
        readoutAppliedY = y;
        textGameObject.transform.position = transform.TransformPoint(new Vector3(readoutBaseLocal.x, y, readoutBaseLocal.z));
    }

    /* ---------------------------
     * Chip Placement
     * --------------------------- */

private void PlaceChip(Transform chipTransform, int denominationIndex, int chipIndexInDenomination, int globalStackIndex)
    {
        int safeStackHeight = Mathf.Max(1, stackHeight);
        int stackIndex = globalStackIndex / safeStackHeight;
        int heightIndex = globalStackIndex % safeStackHeight;
        if (stackIndex < 0) stackIndex = 0;
        if (stackIndex >= stackPositions.Length) stackIndex = stackPositions.Length - 1;

        Vector3 position;
        if (selectableStackMode)
        {
            int columnIndex = chipIndexInDenomination / safeStackHeight;
            heightIndex = chipIndexInDenomination % safeStackHeight;
            position = displayLocalOffset + DenominationOffset(denominationIndex)
                + Vector3.forward * (columnIndex * hexSpacing);
        }
        else
        {
            position = stackPositions[stackIndex] + displayLocalOffset;
        }
        position.y += heightIndex * chipHeight;

        int hash = denominationIndex * 1000 + chipIndexInDenomination + seed;
        if (!selectableStackMode)
        {
            position.x += Hash01(hash) * positionJitter;
            position.z += Hash01(hash + 17) * positionJitter;
        }

        chipTransform.localPosition = position;
        chipTransform.localRotation = Quaternion.Euler(-90f, ChipYaw(denominationIndex, chipIndexInDenomination), 0f);
    }

    private float ChipYaw(int denominationIndex, int chipIndexInDenomination)
    {
        return Hash01(denominationIndex * 1000 + chipIndexInDenomination + seed + 43) * 360f;
    }


    private float Hash01(int x)
    {
        x = (x << 13) ^ x;
        int n = (x * (x * x * 15731 + 789221) + 1376312589);
        return 1f - ((n & 0x7fffffff) / 1073741824f);
    }


public void SetSelectableStackMode(bool enabledMode)
    {
        enabledMode = enabledMode && supportsSelectableStackMode;
        if (selectableStackMode == enabledMode) return;
        SettleAnimation();
        selectableStackMode = enabledMode;
        if (naturalLayout && heldStack != null)
        {
            if (UsesNaturalLayout())
            {
                previousTotalValue = requestedTotalValue;
                SetNaturalTotal(requestedTotalValue, true);
                return;
            }
            ClearNaturalLayout();
            UpdateReadoutPosition();
        }
        ForceRerender();
    }

    public void SetDisplayLocalOffset(Vector3 offset)
    {
        if (displayLocalOffset == offset) return;
        SettleAnimation();
        displayLocalOffset = offset;
        if (UsesNaturalLayout())
        {
            PlaceAllNaturalChips();
            UpdateReadoutPosition();
            return;
        }
        ForceRerender();
    }

    public int GetDisplayedDenominationCount(int denominationIndex)
    {
        if (heldCounts == null || denominationIndex < 0 || denominationIndex >= heldCounts.Length) return 0;
        return heldCounts[denominationIndex];
    }

    public int GetDenominationValue(int denominationIndex)
    {
        if (denominationValues == null || denominationIndex < 0 || denominationIndex >= denominationValues.Length) return 0;
        return denominationValues[denominationIndex];
    }

    public Vector3 GetDenominationBaseWorldPosition(int denominationIndex)
    {
        if (denominationValues == null || denominationIndex < 0 || denominationIndex >= denominationValues.Length)
            return Vector3.zero;
        return transform.TransformPoint(displayLocalOffset + DenominationOffset(denominationIndex));
    }

    public int GetDenominationColumnCount(int denominationIndex)
    {
        int count = GetDisplayedDenominationCount(denominationIndex);
        if (count <= 0) return 0;
        return (count + Mathf.Max(1, stackHeight) - 1) / Mathf.Max(1, stackHeight);
    }

    public int GetDenominationColumnChipCount(int denominationIndex, int columnIndex)
    {
        if (columnIndex < 0) return 0;
        int remaining = GetDisplayedDenominationCount(denominationIndex)
            - columnIndex * Mathf.Max(1, stackHeight);
        return Mathf.Clamp(remaining, 0, Mathf.Max(1, stackHeight));
    }

    public Vector3 GetDenominationColumnWorldPosition(int denominationIndex, int columnIndex)
    {
        if (denominationValues == null || denominationIndex < 0 || denominationIndex >= denominationValues.Length
            || columnIndex < 0) return Vector3.zero;
        Vector3 local = displayLocalOffset + DenominationOffset(denominationIndex)
            + Vector3.forward * (columnIndex * hexSpacing);
        return transform.TransformPoint(local);
    }

    // World position of one displayed chip of a selectable-mode column (heightIndex 0 is the bottom chip), exactly
    // where PlaceChip puts it. Lets a proxy chip sit on the real chip.
    public Vector3 GetDenominationColumnChipWorldPosition(int denominationIndex, int columnIndex, int heightIndex)
    {
        if (denominationValues == null || denominationIndex < 0 || denominationIndex >= denominationValues.Length
            || columnIndex < 0 || heightIndex < 0) return Vector3.zero;
        Vector3 local = displayLocalOffset + DenominationOffset(denominationIndex)
            + Vector3.forward * (columnIndex * hexSpacing);
        local.y += heightIndex * chipHeight;
        return transform.TransformPoint(local);
    }

    // World rotation of that same chip, including its per-chip yaw.
    public Quaternion GetDenominationColumnChipWorldRotation(int denominationIndex, int columnIndex, int heightIndex)
    {
        int chipIndex = columnIndex * Mathf.Max(1, stackHeight) + heightIndex;
        return transform.rotation * Quaternion.Euler(-90f, ChipYaw(denominationIndex, chipIndex), 0f);
    }

    public float GetDenominationColumnTopWorldY(int denominationIndex, int columnIndex)
    {
        Vector3 basePosition = GetDenominationColumnWorldPosition(denominationIndex, columnIndex);
        int count = GetDenominationColumnChipCount(denominationIndex, columnIndex);
        return basePosition.y + count * chipHeight * Mathf.Abs(transform.lossyScale.y);
    }

    public float GetDenominationTopWorldY(int denominationIndex)
    {
        return GetDenominationColumnTopWorldY(denominationIndex, 0);
    }

    public int TransferColumnTopTo(PokerChipPile destination, int denominationIndex, int columnIndex, int count)
    {
        if (!CanTransferTo(destination, denominationIndex) || columnIndex < 0 || count <= 0) return 0;
        SettleAnimation();
        destination.SettleAnimation();

        int columnCount = GetDenominationColumnChipCount(denominationIndex, columnIndex);
        int moveCount = Mathf.Min(count, columnCount);
        moveCount = Mathf.Min(moveCount, destination.denomCapacity - destination.heldCounts[denominationIndex]);
        int sourceIndex = columnIndex * Mathf.Max(1, stackHeight) + columnCount - moveCount;
        int moved = 0;
        while (moved < moveCount && MoveChipAtTo(destination, denominationIndex, sourceIndex)) moved++;
        FinishExactMutation(destination);
        return moved;
    }

    public int TransferDenominationTo(PokerChipPile destination, int denominationIndex, int count)
    {
        if (!CanTransferTo(destination, denominationIndex) || count <= 0) return 0;
        SettleAnimation();
        destination.SettleAnimation();

        int moveCount = Mathf.Min(count, heldCounts[denominationIndex]);
        moveCount = Mathf.Min(moveCount, destination.denomCapacity - destination.heldCounts[denominationIndex]);
        int moved = 0;
        while (moved < moveCount)
        {
            int sourceIndex = heldCounts[denominationIndex] - 1;
            if (!MoveChipAtTo(destination, denominationIndex, sourceIndex)) break;
            moved++;
        }
        FinishExactMutation(destination);
        return moved;
    }

    public int TransferAllTo(PokerChipPile destination)
    {
        if (destination == null || heldCounts == null) return 0;
        int moved = 0;
        for (int denominationIndex = 0; denominationIndex < heldCounts.Length; denominationIndex++)
            moved += TransferDenominationTo(destination, denominationIndex, heldCounts[denominationIndex]);
        return moved;
    }

    public void OpenContainer()
        {
            StopGatherControl(false);
        }

    public void BeginAnimatedGather(bool potSize)
        {
            StopGatherControl(false);
        }

public int TransferAllAnimatedTo(PokerChipPile destination)
        {
            if (destination == null || destination == this || heldCounts == null) return 0;
            //CancelAnimationInPlace();
            SettleAnimation();
            destination.SettleAnimation();
            ReleaseMovingTracking();

            int moved = 0;
            for (int denominationIndex = 0; denominationIndex < heldCounts.Length; denominationIndex++)
            {
                while (heldCounts[denominationIndex] > 0)
                {
                    int sourceIndex = heldCounts[denominationIndex] - 1;
                    GameObject chip = heldChips[denominationIndex * denomCapacity + sourceIndex];
                    if (chip == null || !MoveChipAtTo(destination, denominationIndex, sourceIndex)) break;
                    destination.AddMovingChip(chip);
                    moved++;
                }
            }

            RepositionHeldChips();
            RefreshExactTotals();
            destination.RefreshExactTotals();
            return moved;
        }

    public int TransferApproximateValueAnimatedTo(PokerChipPile destination, int targetValue, bool takeRemainder)
        {
            if (destination == null || destination == this || heldCounts == null) return 0;
            SettleAnimation();
            destination.SettleAnimation();

            int movedValue = 0;
            while (true)
            {
                int remaining = Mathf.Max(0, targetValue - movedValue);
                int selectedDenomination = -1;
                int selectedValue = -1;

                for (int denominationIndex = 0; denominationIndex < heldCounts.Length; denominationIndex++)
                {
                    if (heldCounts[denominationIndex] <= 0) continue;
                    int value = denominationValues[denominationIndex];
                    if (takeRemainder)
                    {
                        selectedDenomination = denominationIndex;
                        break;
                    }
                    if (value <= remaining && value > selectedValue)
                    {
                        selectedDenomination = denominationIndex;
                        selectedValue = value;
                    }
                }

                if (selectedDenomination < 0 && !takeRemainder && movedValue < targetValue)
                {
                    int smallestValue = int.MaxValue;
                    for (int denominationIndex = 0; denominationIndex < heldCounts.Length; denominationIndex++)
                    {
                        if (heldCounts[denominationIndex] <= 0) continue;
                        int value = denominationValues[denominationIndex];
                        if (value < smallestValue)
                        {
                            selectedDenomination = denominationIndex;
                            smallestValue = value;
                        }
                    }
                }

                if (selectedDenomination < 0 || (!takeRemainder && movedValue >= targetValue)) break;
                int sourceIndex = heldCounts[selectedDenomination] - 1;
                if (!MoveChipAtTo(destination, selectedDenomination, sourceIndex)) break;
                GameObject chip = destination.heldChips[selectedDenomination * destination.denomCapacity
                    + destination.heldCounts[selectedDenomination] - 1];
                destination.AddMovingChip(chip);
                movedValue += Mathf.Max(0, denominationValues[selectedDenomination]);
            }

            RefreshExactTotals();
            destination.RefreshExactTotals();
            return movedValue;
        }


    /// <summary>
    /// Move up to targetValue of chips into the destination, largest denomination first.
    /// Chips that are not currently displayed (their denomination is inactive on this pile)
    /// are spawned from idle pool slots, so the transfer only fails to reach the target when
    /// the remainder is smaller than the smallest denomination or every pool is exhausted.
    /// Never moves more than targetValue.
    /// </summary>
    public int TransferValueApproximateTo(PokerChipPile destination, int targetValue)
    {
        if (destination == null || destination == this || heldCounts == null || targetValue <= 0) return 0;
        SettleAnimation();
        destination.SettleAnimation();

        int remaining = targetValue;
        int movedValue = 0;
        while (remaining > 0)
        {
            int bestDenomination = -1;
            int bestValue = -1;
            for (int denominationIndex = 0; denominationIndex < denominationValues.Length; denominationIndex++)
            {
                int value = denominationValues[denominationIndex];
                if (value <= 0 || value > remaining || value <= bestValue) continue;
                if (heldCounts[denominationIndex] > 0)
                {
                    bestDenomination = denominationIndex;
                    bestValue = value;
                }
                else if (denominationPools != null && denominationIndex < denominationPools.Length
                    && denominationPools[denominationIndex] != null
                    && denominationPools[denominationIndex].availableCount > 0)
                {
                    bestDenomination = denominationIndex;
                    bestValue = value;
                }
            }

            if (bestDenomination < 0 || !CanTransferTo(destination, bestDenomination)) break;

            int sourceIndex = heldCounts[bestDenomination] - 1;
            if (sourceIndex < 0)
            {
                LocalObjectPool pool = denominationPools[bestDenomination];
                if (heldCounts[bestDenomination] >= denomCapacity) break;
                GameObject spawned = pool.TryToSpawn();
                if (spawned == null) break;
                spawned.transform.SetParent(transform);
                sourceIndex = heldCounts[bestDenomination];
                int baseSlot = bestDenomination * denomCapacity;
                heldChips[baseSlot + sourceIndex] = spawned;
                heldPoolSlots[baseSlot + sourceIndex] = pool.lastSpawnedIndex;
                heldCounts[bestDenomination]++;
            }

            if (!MoveChipAtTo(destination, bestDenomination, sourceIndex)) break;
            movedValue += bestValue;
            remaining -= bestValue;
        }

        if (movedValue > 0) FinishExactMutation(destination);
        return movedValue;
    }

    /// <summary>
    /// Spawn up to targetValue of chips from idle pool slots into this pile, largest denomination first,
    /// without touching the chips already on display. Never adds more than targetValue. Returns the value added.
    /// </summary>
    public int AddValueFromPool(int targetValue)
    {
        if (heldCounts == null || denominationPools == null || targetValue <= 0) return 0;
        SettleAnimation();

        int remaining = targetValue;
        while (remaining > 0)
        {
            int bestDenomination = -1;
            int bestValue = -1;
            for (int denominationIndex = 0; denominationIndex < denominationValues.Length; denominationIndex++)
            {
                int value = denominationValues[denominationIndex];
                if (value <= 0 || value > remaining || value <= bestValue) continue;
                if (denominationIndex >= denominationPools.Length || denominationPools[denominationIndex] == null
                    || denominationPools[denominationIndex].availableCount <= 0
                    || heldCounts[denominationIndex] >= denomCapacity) continue;
                bestDenomination = denominationIndex;
                bestValue = value;
            }
            if (bestDenomination < 0) break;

            LocalObjectPool pool = denominationPools[bestDenomination];
            GameObject spawned = pool.TryToSpawn();
            if (spawned == null) break;
            spawned.transform.SetParent(transform);
            int slot = bestDenomination * denomCapacity + heldCounts[bestDenomination];
            heldChips[slot] = spawned;
            heldPoolSlots[slot] = pool.lastSpawnedIndex;
            heldCounts[bestDenomination]++;
            remaining -= bestValue;
        }

        int added = targetValue - remaining;
        if (added > 0) FinishExactMutation(null);
        return added;
    }

    /// <summary>
    /// Move exactly <paramref name="count"/> chips of one denomination into the destination,
    /// spawning from idle pool slots when this pile does not display enough of them.
    /// Returns the number moved; callers treat a short result as stale state.
    /// </summary>
    public int TransferDenominationsWithSpawnTo(PokerChipPile destination, int denominationIndex, int count)
    {
        if (destination == null || destination == this || heldCounts == null || count <= 0) return 0;
        if (!CanTransferTo(destination, denominationIndex)) return 0;
        SettleAnimation();
        destination.SettleAnimation();

        int moved = 0;
        while (moved < count && heldCounts[denominationIndex] > 0)
        {
            if (!MoveChipAtTo(destination, denominationIndex, heldCounts[denominationIndex] - 1)) break;
            moved++;
        }

        LocalObjectPool pool = denominationIndex < denominationPools.Length ? denominationPools[denominationIndex] : null;
        while (moved < count && pool != null && pool.availableCount > 0
            && heldCounts[denominationIndex] < denomCapacity)
        {
            GameObject spawned = pool.TryToSpawn();
            if (spawned == null) break;
            spawned.transform.SetParent(transform);
            int baseSlot = denominationIndex * denomCapacity;
            heldChips[baseSlot + heldCounts[denominationIndex]] = spawned;
            heldPoolSlots[baseSlot + heldCounts[denominationIndex]] = pool.lastSpawnedIndex;
            heldCounts[denominationIndex]++;
            if (!MoveChipAtTo(destination, denominationIndex, heldCounts[denominationIndex] - 1)) break;
            moved++;
        }

        if (moved > 0) FinishExactMutation(destination);
        return moved;
    }

    public void StartAnimatedGather()
        {
            if (movingChipCount <= 0)
            {
                StopGatherControl(false);
                return;
            }

            gatherPdActive = true;
            gatherTargetCount = -1;
            gatherSettling = gatherTransportDuration <= 0f;
            gatherStartTime = Time.time;
            gatherEndTime = gatherStartTime
                + Mathf.Max(0f, gatherTransportDuration)
                + Mathf.Max(0f, gatherSettleDuration);
            for (int i = 0; i < movingChipCount; i++)
            {
                gatherIntegralErrors[i] = Vector3.zero;
                SetMovingMaterial(i, true);
            }
            RefreshUpdateState();
        }




    public void EndAnimatedContraction()
        {
            StopGatherControl(false);
        }

        public int MakeDisplayedChipsDynamic()
        {
            if (heldCounts == null || heldChips == null) return 0;
            SettleAnimation();
            int added = 0;
            int scatterIndex = 0;
            for (int denominationIndex = 0; denominationIndex < heldCounts.Length; denominationIndex++)
            {
                int baseSlot = denominationIndex * denomCapacity;
                for (int chipIndex = 0; chipIndex < heldCounts[denominationIndex]; chipIndex++)
                {
                    GameObject chip = heldChips[baseSlot + chipIndex];
                    if (chip == null || IsMovingChip(chip)) continue;
                    float angle = scatterIndex * 2.399963f;
                    float radius = 0.008f * Mathf.Sqrt(scatterIndex);
                    chip.transform.position = transform.position
                        + transform.right * (Mathf.Cos(angle) * radius)
                        + transform.forward * (Mathf.Sin(angle) * radius)
                        + transform.up * (0.04f + scatterIndex * chipHeight * 0.2f);
                    AddMovingChip(chip);
                    added++;
                    scatterIndex++;
                }
            }
            return added;
        }

        public int SpawnDynamicChips(int totalValue, Vector3 worldSpawnPosition)
        {
            if (heldCounts == null) return 0;
            SettleAnimation();

            int[] counts = selectableStackMode
                ? CalculateSelectableDenominationCounts(totalValue)
                : CalculateDenominationCounts(totalValue);

            int spawned = 0;
            for (int d = 0; d < denominationValues.Length; d++)
            {
                int wanted = Mathf.Max(0, counts[d]);
                if (wanted == 0) continue;

                LocalObjectPool pool = denominationPools[d];
                if (pool == null) continue;

                int baseSlot = d * denomCapacity;
                int current = heldCounts[d];
                int capacity = Mathf.Min(denomCapacity, pool.Pool == null ? 0 : pool.Pool.Length);
                int target = heldCounts[d] + wanted;

                while (current < target && current < capacity)
                {
                    GameObject chip = pool.TryToSpawn();
                    if (chip == null) break;
                    chip.transform.SetParent(transform);

                    float angle = spawned * 2.399963f;
                    float radius = 0.008f * Mathf.Sqrt(spawned);
                    chip.transform.position = worldSpawnPosition
                        + Vector3.right * (Mathf.Cos(angle) * radius)
                        + Vector3.forward * (Mathf.Sin(angle) * radius)
                        + Vector3.up * (0.04f + spawned * chipHeight * 0.2f);
                    float yaw = Hash01(d * 1000 + spawned + seed + 99) * 360f;
                    chip.transform.rotation = Quaternion.Euler(-90f, yaw, 0f);

                    heldChips[baseSlot + current] = chip;
                    heldPoolSlots[baseSlot + current] = pool.lastSpawnedIndex;
                    current++;
                    AddMovingChip(chip);
                    spawned++;
                }
                heldCounts[d] = current;
            }

            RefreshExactTotals();
            return spawned;
        }



    /// <summary>
    /// Turns every held chip back into a static stack chip: physics and colliders off, snapped to its layout slot.
    /// Used when leaving dynamic mode so chips that were left physical do not dangle on the table.
    /// </summary>
    public void _FreezeChipsToStaticLayout()
    {
        if (heldCounts == null || heldChips == null) return;
        StopGatherControl(true);
        SettleAnimation();
        for (int i = 0; i < heldChips.Length; i++)
        {
            GameObject chip = heldChips[i];
            if (chip == null) continue;
            Rigidbody body = chip.GetComponent<Rigidbody>();
            if (body != null)
            {
                if (!body.isKinematic)
                {
                    body.velocity = Vector3.zero;
                    body.angularVelocity = Vector3.zero;
                }
                body.useGravity = false;
                body.isKinematic = true;
                body.collisionDetectionMode = CollisionDetectionMode.Discrete;
            }
            Collider[] colliders = chip.GetComponents<Collider>();
            for (int c = 0; c < colliders.Length; c++) colliders[c].enabled = false;
        }
        if (UsesNaturalLayout()) _RestackLayout();
        else RepositionHeldChips();
    }

    public void FinishAnimatedGather()
        {
            StopGatherControl(true);
            RefreshExactTotals();
        }

    private void ReleaseMovingTracking()
        {
            StopGatherControl(true);
        }

        private bool IsMovingChip(GameObject chip)
        {
            for (int i = 0; i < movingChipCount; i++)
                if (movingChips[i] == chip) return true;
            return false;
        }

    public float AnimatedGatherDuration()
        {
            return Mathf.Max(0f, gatherTransportDuration) + Mathf.Max(0f, gatherSettleDuration);
        }

    private void AddMovingChip(GameObject chip)
    {
        if (chip == null || movingChips == null || movingChipCount >= movingChips.Length) return;
        if (IsMovingChip(chip)) return;

        Vector3 worldPosition = chip.transform.position;
        Quaternion worldRotation = chip.transform.rotation;

        chip.transform.SetParent(transform);
        chip.transform.position = worldPosition;
        chip.transform.rotation = worldRotation;

        Collider[] chipColliders = chip.GetComponents<Collider>();

        for (int i = 0; i < chipColliders.Length; i++)
        {
            Collider chipCollider = chipColliders[i];
            chipCollider.enabled = true;
            chipCollider.contactOffset = Mathf.Max(0.001f, movingChipContactOffset);
        }

        Rigidbody chipBody = chip.GetComponent<Rigidbody>();
        if (chipBody != null)
        {
            chipBody.drag = Mathf.Max(0f, movingChipDrag);
            chipBody.collisionDetectionMode = CollisionDetectionMode.ContinuousSpeculative;
            chipBody.solverIterations = Mathf.Max(1, movingChipSolverIterations);
            chipBody.solverVelocityIterations = Mathf.Max(1, movingChipSolverVelocityIterations);
            chipBody.maxDepenetrationVelocity = Mathf.Max(0.1f, movingChipMaxDepenetrationVelocity);
            chipBody.isKinematic = false;
            chipBody.useGravity = true;
        }

        int index = movingChipCount++;
        movingChips[index] = chip;
        movingBodies[index] = chipBody;
        gatherIntegralErrors[index] = Vector3.zero;

        if (defaultRestingMaterial == null && chipColliders.Length > 0)
            defaultRestingMaterial = chipColliders[0].sharedMaterial;

        SetMovingMaterial(index, true);
    }

    private void SetMovingMaterial(int index, bool moving)
    {
        if (index < 0 || index >= movingChipCount) return;

        GameObject chip = movingChips[index];
        if (chip == null) return;

        Collider[] chipColliders = chip.GetComponents<Collider>();
        if (chipColliders.Length == 0) return;

        PhysicMaterial material = moving
            ? movingChipMaterial
            : defaultRestingMaterial;

        for (int i = 0; i < chipColliders.Length; i++)
        {
            chipColliders[i].sharedMaterial = material;
        }
    }

    private void StopGatherControl(bool clearTracking)
    {
        gatherPdActive = false;
        gatherSettling = false;
        gatherStartTime = 0f;
        gatherEndTime = 0f;
        for (int i = 0; i < movingChipCount; i++)
        {
            SetMovingMaterial(i, false);
            gatherIntegralErrors[i] = Vector3.zero;
            if (!clearTracking) continue;
            movingChips[i] = null;
            movingBodies[i] = null;

        }
        if (clearTracking) movingChipCount = 0;
        RefreshUpdateState();
    }

    private void RefreshUpdateState()
    {
        if (sortedIndices == null) return;
        enabled = animCount > 0 || gatherPdActive;
    }

    public void ReleaseAllToPools()
    {
        if (heldCounts == null || denominationPools == null) return;
        StopGatherControl(true);
        SettleAnimation();
        for (int denominationIndex = 0; denominationIndex < heldCounts.Length; denominationIndex++)
        {
            LocalObjectPool pool = denominationIndex < denominationPools.Length ? denominationPools[denominationIndex] : null;
            int baseSlot = denominationIndex * denomCapacity;
            while (heldCounts[denominationIndex] > 0)
            {
                int index = --heldCounts[denominationIndex];
                if (pool != null) pool.ReturnIndex(heldPoolSlots[baseSlot + index]);
                heldChips[baseSlot + index] = null;
                heldPoolSlots[baseSlot + index] = -1;
            }
        }
        ClearNaturalLayout();
        FinishExactMutation(null);
    }

    private bool CanTransferTo(PokerChipPile destination, int denominationIndex)
    {
        if (destination == null || destination == this || heldCounts == null || destination.heldCounts == null) return false;
        if (denominationIndex < 0 || denominationIndex >= heldCounts.Length
            || denominationIndex >= destination.heldCounts.Length) return false;
        if (denominationValues == null || destination.denominationValues == null
            || denominationIndex >= denominationValues.Length || denominationIndex >= destination.denominationValues.Length
            || denominationValues[denominationIndex] != destination.denominationValues[denominationIndex]) return false;
        if (denominationPools == null || destination.denominationPools == null
            || denominationIndex >= denominationPools.Length || denominationIndex >= destination.denominationPools.Length
            || denominationPools[denominationIndex] != destination.denominationPools[denominationIndex]) return false;
        return true;
    }

    private bool MoveChipAtTo(PokerChipPile destination, int denominationIndex, int sourceIndex)
    {
        int sourceCount = heldCounts[denominationIndex];
        int destinationCount = destination.heldCounts[denominationIndex];
        if (sourceIndex < 0 || sourceIndex >= sourceCount || destinationCount >= destination.denomCapacity) return false;

        int sourceBase = denominationIndex * denomCapacity;
        int destinationBase = denominationIndex * destination.denomCapacity;
        GameObject chip = heldChips[sourceBase + sourceIndex];
        if (chip == null) return false;

        ForgetChipPlacement(sourceBase + sourceIndex);
        destination.heldChips[destinationBase + destinationCount] = chip;
        destination.heldPoolSlots[destinationBase + destinationCount] = heldPoolSlots[sourceBase + sourceIndex];
        if (destination.heldStack != null) destination.heldStack[destinationBase + destinationCount] = -1;
        destination.heldCounts[denominationIndex] = destinationCount + 1;
        chip.transform.SetParent(destination.transform);

        for (int i = sourceIndex; i < sourceCount - 1; i++)
        {
            heldChips[sourceBase + i] = heldChips[sourceBase + i + 1];
            heldPoolSlots[sourceBase + i] = heldPoolSlots[sourceBase + i + 1];
            if (heldStack == null) continue;
            heldStack[sourceBase + i] = heldStack[sourceBase + i + 1];
            heldLevel[sourceBase + i] = heldLevel[sourceBase + i + 1];
        }
        heldChips[sourceBase + sourceCount - 1] = null;
        heldPoolSlots[sourceBase + sourceCount - 1] = -1;
        if (heldStack != null) heldStack[sourceBase + sourceCount - 1] = -1;
        heldCounts[denominationIndex] = sourceCount - 1;
        return true;
    }

    private void FinishExactMutation(PokerChipPile other)
    {
        RepositionHeldChips();
        RefreshExactTotals();
        if (other != null)
        {
            other.RepositionHeldChips();
            other.RefreshExactTotals();
        }
    }

    private void RepositionHeldChips()
    {
        if (heldCounts == null || heldChips == null) return;
        if (UsesNaturalLayout())
        {
            AssignUnplacedChips();
            totalActiveChips = HeldChipTotal();
            UpdateReadoutPosition();
            return;
        }
        bool hasActiveFilter = maxActiveDenominations > 0 && selectableStackMode;
        for (int i = 0; hasActiveFilter && i < heldCounts.Length; i++)
        {
            if (IsDenominationActive(i)) continue;
            int baseSlot = i * denomCapacity;
            LocalObjectPool pool = i < denominationPools.Length ? denominationPools[i] : null;
            while (heldCounts[i] > 0)
            {
                int index = --heldCounts[i];
                if (pool != null) pool.ReturnIndex(heldPoolSlots[baseSlot + index]);
                heldChips[baseSlot + index] = null;
                heldPoolSlots[baseSlot + index] = -1;
            }
        }
        int compactIndex = 0;
        for (int orderIndex = 0; orderIndex < sortedIndices.Length; orderIndex++)
        {
            int denominationIndex = sortedIndices[orderIndex];
            int baseSlot = denominationIndex * denomCapacity;
            heldOffsets[denominationIndex] = selectableStackMode ? 0 : compactIndex;
            for (int chipIndex = 0; chipIndex < heldCounts[denominationIndex]; chipIndex++)
            {
                GameObject chip = heldChips[baseSlot + chipIndex];
                if (chip != null) PlaceChip(chip.transform, denominationIndex, chipIndex,
                    selectableStackMode ? chipIndex : compactIndex + chipIndex);
            }
            compactIndex += heldCounts[denominationIndex];
        }
        totalActiveChips = compactIndex;
    }

    private void RefreshExactTotals()
    {
        int value = GetTotalDisplayedValue();
        requestedTotalValue = value;
        previousTotalValue = value;
        if (prevCounts != null)
            for (int i = 0; i < prevCounts.Length; i++) prevCounts[i] = heldCounts[i];
        UpdateText();
    }

    private Vector3 DenominationOffset(int denominationIndex)
    {
        if (!selectableStackMode) return Vector3.zero;
        Vector3 offset = BaseDenominationOffset(denominationIndex);
        // Inactive denominations are parked far away; keep them there.
        return offset.x >= 50000f ? offset : offset + selectableLayoutOffset;
    }

    private Vector3 BaseDenominationOffset(int denominationIndex)
    {
        if (maxActiveDenominations > 0)
        {
            int slotIndex = GetActiveSlotIndex(denominationIndex);
            if (slotIndex < 0)
                return new Vector3(100000f, 0f, 0f);
            if (activeDenominationPositions != null && activeDenominationPositions.Length > 0
                && slotIndex < activeDenominationPositions.Length
                && activeDenominationPositions[slotIndex] != null)
                return transform.InverseTransformPoint(activeDenominationPositions[slotIndex].position);
            if (denominationOffsets != null)
            {
                int totalOffsets = denominationOffsets.Length;
                int centerStart = (totalOffsets - maxActiveDenominations) / 2;
                int offsetIndex = centerStart + slotIndex;
                if (offsetIndex >= 0 && offsetIndex < totalOffsets)
                    return denominationOffsets[offsetIndex];
            }
            return Vector3.zero;
        }
        if (denominationOffsets != null && denominationIndex >= 0 && denominationIndex < denominationOffsets.Length)
            return denominationOffsets[denominationIndex];
        if (!warnedMissingOffsets)
        {
            warnedMissingOffsets = true;
            Debug.LogWarning("PokerChipPile: denominationOffsets must match denominationValues; missing entries use zero.");
        }
        return Vector3.zero;
    }

    // PhysicalRaisePile's hand selection runs here so the per-frame hover costs one cross-behaviour call per hand
    // instead of several per column. Returns the closest column within reach of the point, or -1; the column and
    // its squared horizontal distance are then read with _GetFoundColumn / _GetFoundDistance.
    private int foundColumn = -1;
    private float foundDistance = float.MaxValue;

    // Where the selectable columns can be: horizontal reach from the pile's position and the vertical span. Rebuilt
    // only when something that places a column changes, so a hand nowhere near the pile is rejected without
    // working out every column's world position.
    private int[] reachCounts;
    private int[] reachSlots;
    private bool reachSelectable;
    private Vector3 reachOffset;
    private Vector3 reachPosition;
    private Quaternion reachRotation;
    private bool reachValid;
    private float reachMaxDistance;
    private float reachMinY;
    private float reachMaxY;

    private void RefreshReach()
    {
        int n = heldCounts == null ? 0 : heldCounts.Length;
        int slots = activeDenominationSlots == null ? 0 : activeDenominationSlots.Length;
        Vector3 position = transform.position;
        Quaternion rotation = transform.rotation;
        bool changed = !reachValid || reachCounts == null || reachCounts.Length != n
            || reachSlots == null || reachSlots.Length != slots
            || reachSelectable != selectableStackMode || reachOffset != displayLocalOffset
            || reachPosition != position || reachRotation != rotation;
        if (!changed)
        {
            for (int i = 0; i < n; i++)
            {
                if (reachCounts[i] != heldCounts[i]) { changed = true; break; }
            }
        }
        if (!changed)
        {
            for (int i = 0; i < slots; i++)
            {
                if (reachSlots[i] != activeDenominationSlots[i]) { changed = true; break; }
            }
        }
        if (!changed) return;

        if (reachCounts == null || reachCounts.Length != n) reachCounts = new int[n];
        if (reachSlots == null || reachSlots.Length != slots) reachSlots = new int[slots];
        for (int i = 0; i < n; i++) reachCounts[i] = heldCounts[i];
        for (int i = 0; i < slots; i++) reachSlots[i] = activeDenominationSlots[i];
        reachSelectable = selectableStackMode;
        reachOffset = displayLocalOffset;
        reachPosition = position;
        reachRotation = rotation;
        reachValid = true;

        reachMaxDistance = -1f;
        reachMinY = float.MaxValue;
        reachMaxY = float.MinValue;
        int denominationCount = denominationValues == null ? 0 : denominationValues.Length;
        for (int denomination = 0; denomination < denominationCount; denomination++)
        {
            if (maxActiveDenominations > 0 && !IsDenominationActive(denomination)) continue;
            int columnCount = GetDenominationColumnCount(denomination);
            for (int column = 0; column < columnCount; column++)
            {
                Vector3 center = GetDenominationColumnWorldPosition(denomination, column);
                float dx = center.x - position.x;
                float dz = center.z - position.z;
                reachMaxDistance = Mathf.Max(reachMaxDistance, Mathf.Sqrt(dx * dx + dz * dz));
                reachMinY = Mathf.Min(reachMinY, center.y);
                reachMaxY = Mathf.Max(reachMaxY, GetDenominationColumnTopWorldY(denomination, column));
            }
        }
    }

    public int FindSelectableColumn(Vector3 point, float radius, float heightBelow, float heightAbove)
    {
        foundColumn = -1;
        foundDistance = float.MaxValue;
        RefreshReach();
        // No columns, or the point is outside every column's reach
        if (reachMaxDistance < 0f || point.y < reachMinY - heightBelow || point.y > reachMaxY + heightAbove) return -1;
        float px = point.x - reachPosition.x;
        float pz = point.z - reachPosition.z;
        float reach = reachMaxDistance + radius;
        if (px * px + pz * pz > reach * reach) return -1;

        int bestDenomination = -1;
        int denominationCount = denominationValues == null ? 0 : denominationValues.Length;
        float radiusSqr = radius * radius;
        for (int denomination = 0; denomination < denominationCount; denomination++)
        {
            if (maxActiveDenominations > 0 && !IsDenominationActive(denomination)) continue;
            int columnCount = GetDenominationColumnCount(denomination);
            for (int column = 0; column < columnCount; column++)
            {
                Vector3 center = GetDenominationColumnWorldPosition(denomination, column);
                float dx = point.x - center.x;
                float dz = point.z - center.z;
                float distance = dx * dx + dz * dz;
                if (distance > radiusSqr) continue;
                if (point.y < center.y - heightBelow
                    || point.y > GetDenominationColumnTopWorldY(denomination, column) + heightAbove) continue;
                if (distance < foundDistance || (Mathf.Approximately(distance, foundDistance)
                    && (bestDenomination < 0 || denomination < bestDenomination
                        || (denomination == bestDenomination && column < foundColumn))))
                {
                    foundDistance = distance;
                    bestDenomination = denomination;
                    foundColumn = column;
                }
            }
        }
        return bestDenomination;
    }

    public int _GetFoundColumn() { return foundColumn; }
    public float _GetFoundDistance() { return foundDistance; }

    public bool IsDenominationActive(int denominationIndex)
    {
        return GetActiveSlotIndex(denominationIndex) >= 0;
    }

    private int GetActiveSlotIndex(int denominationIndex)
    {
        if (maxActiveDenominations <= 0 || activeDenominationSlots == null
            || denominationIndex < 0 || denominationIndex >= activeDenominationSlots.Length)
            return -1;
        return activeDenominationSlots[denominationIndex];
    }

    private void SelectActiveDenominations(int totalValue)
    {
        int count = denominationValues == null ? 0 : denominationValues.Length;
        if (prevActiveDenominationSlots == null || prevActiveDenominationSlots.Length != count)
            prevActiveDenominationSlots = new int[count];
        for (int i = 0; i < count; i++)
            prevActiveDenominationSlots[i] = activeDenominationSlots != null && i < activeDenominationSlots.Length ? activeDenominationSlots[i] : -1;

        if (activeDenominationSlots == null || activeDenominationSlots.Length != count)
            activeDenominationSlots = new int[count];
        for (int i = 0; i < count; i++) activeDenominationSlots[i] = -1;

        int targetIndex = -1;
        for (int i = count - 1; i >= 0; i--)
        {
            if (denominationValues[i] * 2 < totalValue)
            {
                targetIndex = i;
                break;
            }
        }

        int activeCount = Mathf.Min(maxActiveDenominations, count);
        if (targetIndex >= activeCount - 1)
        {
            for (int i = 0; i < activeCount; i++)
            {
                int denomIndex = targetIndex - (activeCount - 1 - i);
                if (denomIndex >= 0 && denomIndex < count)
                    activeDenominationSlots[denomIndex] = i;
            }
        }
        else
        {
            for (int i = 0; i < activeCount; i++)
                activeDenominationSlots[i] = i;
        }
    }

    private void ForceRerender()
    {
        if (sortedIndices == null) return;
        for (int i = 0; i < heldOffsets.Length; i++) heldOffsets[i] = int.MinValue;
        if (selectableStackMode && maxActiveDenominations > 0)
            SelectActiveDenominations(requestedTotalValue);
        UpdateChipDisplay(selectableStackMode
            ? CalculateSelectableDenominationCounts(requestedTotalValue)
            : CalculateDenominationCounts(requestedTotalValue));
    }

    private void SettleAnimation()
    {
        for (int i = animFirstPending; i < animCount; i++)
        {
            if (animTargets[i] != null) animTargets[i].localPosition = animTargetPositions[i];
        }
        animCount = 0;
        animFirstPending = 0;
        RefreshUpdateState();
    }


private void CancelAnimationInPlace()
    {
        animCount = 0;
        animFirstPending = 0;
        RefreshUpdateState();
    }
}
