using UdonSharp;
using UnityEngine;
using VRC.SDKBase;
using MMMaellon;

[UdonBehaviourSyncMode(BehaviourSyncMode.Manual)]
public class PhysicalRaisePile : UdonSharpBehaviour
{
    public PokerChipPile sourcePile;
    public PokerChipPile raisePile;
    public HoldemPlayer player;
    public VRC_Pickup pickup;
    public Collider targetCollider;
    public Transform initialTransform;
    public Collider ownCollider;
    public Transform[] denominationZones;
    public BoxCollider[] denominationColliders;
    public AudioPoolPlayer chipClinkPlayer;

    [Header("Hand selection")]
    public float selectionRadius = 0.06f;
    [Tooltip("World-space detection distance above the visible chip column.")]
    public float selectionHeightAboveStack = 0.1f;
    [Tooltip("World-space detection distance below the base of the chip column.")]
    public float selectionHeightBelowStack = 0.01f;

    [Tooltip("Offset from the tracked controller origin to the hand point used for chip picking, the selection collider, chip count, and the amount readout. Expressed in the arm-aligned frame: +Z points from the arm toward the hand, +Y stays world up. Authored for a 0.8m eye height and scaled by avatar size at runtime; a player's saved calibration replaces it.")]
    public Vector3 handOffset = new Vector3(0f, 0.09f, 0.05f);

    [Tooltip("Readout lift above the hand. Authored for a 0.8m eye height; scaled by avatar size at runtime.")]
    public float readoutYOffset = 0.05f;

    public Transform readout;

    [Header("Hover highlight")]
    [Tooltip("Proxy chip renderers under this pickup (chip mesh) that VRChat outlines. On hover proxy i takes the pose of real chip i of the hovered column; the selected top chips switch to the highlight materials and the rest are disabled, so only what you would grab is highlighted while the colliders still cover every column. Needs at least stackHeight entries.")]
    public Renderer[] highlightChips;
    [Tooltip("Materials on the proxy chips while no chips are selected: the invisible one, so only VRChat's outline shows around the whole column.")]
    public Material[] highlightIdleMaterials;
    [Tooltip("Materials on the proxy chips while some are selected: ChipHighlight fill, then ChipHighlight outline (the outline queue must be higher).")]
    public Material[] highlightSelectedMaterials;
    private int highlightMode;

    [UdonSynced] private int[] syncedRaiseCounts;
    [UdonSynced] private int syncedReservationVersion;
    [UdonSynced] private int syncedReservationEpoch = -1;
    [UdonSynced] private int syncedRepresentedBet;
    [UdonSynced] private int syncedSourceBaseline;
    [UdonSynced] private int syncedDisposition;

    private const int DISPOSITION_ACTIVE = 1;
    private const int DISPOSITION_RETURNED = 2;
    private const int DISPOSITION_CONSUMED = 3;

    private const int DISABLED = 0;
    private const int IDLE_SOURCE = 1;
    private const int HOVER_SOURCE = 2;
    private const int HELD_RAISE = 3;
    private const int DROP_PENDING = 4;
    private const int RETURNING = 5;
    private const int COMMITTED = 6;

    private Vector3 calibratedHandOffset;
    private bool hasCalibratedHandOffset;
    private SmartObjectSync objectSync;
    private CapsuleCollider pickupCapsule;
    private Vector3 carriedColliderCenter;
    private float carriedColliderRadius;
    private float carriedColliderHeight;
    private int carriedColliderDirection;
    private Rigidbody rb;
    private int state;
    private bool localPhysicalMode;
    private bool interactionRequested;
    private bool callActionActive;
    private bool remoteReservationNeedsPhysicalLayout;
    private int holdingHand = -1;
    private int dropToken;
    private int pendingDropToken;
    private float pendingDropResolveTime;
    private int previewDenomination = -1;
    private int previewColumn = -1;
    private int previewHand = -1;
    private int previewCount;
    private int previewTotal;
    private bool warnedConfiguration;
    private int hapticHand = -1;
    private int hapticDenomination = -1;
    private int hapticColumn = -1;
    private int hapticCount;

    private const float HAPTIC_DURATION = 0.04f;
    private const float HAPTIC_AMPLITUDE = 0.2f;
    private const float HAPTIC_FREQUENCY = 0.5f;

    private int[] localRaiseCounts;
    private int lastAppliedEpoch = -1;
    private int lastAppliedVersion = -1;
    private int representedRaiseValue;
    private int localReservationEpoch = -1;

    // HideHover is costly (calls into the piles, pickup texts, and a SmartObjectSync respawn that serializes), so
    // the per-frame paths run it once per state; anything that shows the hover or readout again clears the latch.
    private const float HIDDEN_REFRESH_SECONDS = 1f;
    private bool hoverHidden;
    private int hoverHiddenState = -1;
    private float hoverHiddenRefreshTime;
    // Set once RefreshInteraction has fully disabled the pile; cleared by anything that enables or shows part of it.
    // The seat UI refreshes interaction on every table change, and redoing the disable path costs far more than the
    // rest of that refresh.
    private bool disabledApplied;

private void Start()
    {
        objectSync = GetComponent<SmartObjectSync>();
        rb = GetComponent<Rigidbody>();
        if (pickup != null && Networking.LocalPlayer != null && !Networking.LocalPlayer.IsUserInVR())
            pickup.AutoHold = VRC_Pickup.AutoHoldMode.Yes;
        pickupCapsule = GetComponent<CapsuleCollider>();
        if (pickupCapsule != null)
        {
            carriedColliderCenter = pickupCapsule.center;
            carriedColliderRadius = pickupCapsule.radius;
            carriedColliderHeight = pickupCapsule.height;
            carriedColliderDirection = pickupCapsule.direction;
        }
        InteractionText = "";
        DisableInteractive = true;
        if (targetCollider == null && player != null && player.grabbableBetPile != null)
            targetCollider = player.grabbableBetPile.targetCollider;
        int denominationCount = sourcePile == null || sourcePile.denominationValues == null
            ? 0 : sourcePile.denominationValues.Length;
        EnsureArrays(denominationCount);
        if (initialTransform != null)
        {
            initialTransform.position = transform.position;
            initialTransform.rotation = transform.rotation;
        }
        ClearLocalCounts();
        SetPhysics(false);
        SetRootCollider(false);
        SetSourceColliders(false);
        SetPickupable(false);
        HideHover();
        state = DISABLED;
        TryApplySynchronizedReservation();
    }

    private void EnsureArrays(int count)
    {
        if (count < 0) count = 0;
        if (syncedRaiseCounts == null || syncedRaiseCounts.Length != count) syncedRaiseCounts = new int[count];
        if (localRaiseCounts == null || localRaiseCounts.Length != count) localRaiseCounts = new int[count];
    }

private void Update()
    {
        if ((state == HELD_RAISE || state == DROP_PENDING) && TryCommitInPlayArea()) return;

        // The state test comes first: it is local, while CanHandleChips calls into the player.
        if ((state != IDLE_SOURCE && state != HOVER_SOURCE && state != HELD_RAISE) || !CanHandleChips())
        {
            HideHoverOnce();
            return;
        }
        UpdateHover();
    }

    // The readout pose has exactly one writer, and it runs last in the frame: Update and LateUpdate happen before
    // the pickup / SmartObjectSync move this object, and the readout is its child, so writing earlier makes the
    // text orbit the pickup. Rotation in VR belongs to this script (the look-at is told to stand down);
    // on desktop the look-at owns rotation and this script only places the readout.
    public override void PostLateUpdate()
    {
        if ((state != IDLE_SOURCE && state != HOVER_SOURCE
            && state != HELD_RAISE && state != DROP_PENDING) || !CanHandleChips()) return;
        PositionReadoutOnHand();
    }

    public override bool OnOwnershipRequest(VRCPlayerApi requestingPlayer, VRCPlayerApi requestedOwner)
    {
        if (!Utilities.IsValid(requestingPlayer) || !Utilities.IsValid(requestedOwner)) return false;
        if (requestingPlayer.playerId != requestedOwner.playerId) return false;
        if (HoldemAuthority.IsAuthority(requestingPlayer)) return true;
        return player != null && player.IsSeated() && Networking.IsOwner(requestingPlayer, player.gameObject);
    }

    public override void OnOwnershipTransferred(VRCPlayerApi newOwner)
    {
        dropToken++;
        if (pickup != null && pickup.IsHeld && (newOwner == null || !newOwner.isLocal)) pickup.Drop();
        if (state == DROP_PENDING && !Networking.IsOwner(gameObject)) state = DISABLED;
        RefreshInteraction();
    }

    public override void OnPickup()
    {
        dropToken++;
        MarkShown();
        int selectedHand = previewHand;
        int selectedDenomination = previewDenomination;
        int selectedColumn = previewColumn;
        int selectedCount = previewCount;
        HideHover();
        SetSourceColliders(false);
        if (Networking.LocalPlayer != null) Networking.SetOwner(Networking.LocalPlayer, gameObject);
        if (state == DROP_PENDING && HasLocalReservation() && pickup != null)
        {
            holdingHand = PickupHandIndex(pickup.currentHand);
            state = HELD_RAISE;
            ConfigureCarriedCollider();
            CenterCarriedPileOnHand();
            SetRootCollider(true);
            SetPhysics(true);
            SetPickupable(true);
            return;
        }
        if (!CanHandleChips() || pickup == null)
        {
            if (pickup != null) pickup.Drop();
            RefreshInteraction();
            return;
        }

        holdingHand = PickupHandIndex(pickup.currentHand);
        if (selectedHand != holdingHand || selectedDenomination < 0 || selectedColumn < 0 || selectedCount <= 0)
        {
            Vector3 handPosition;
            float distance;
            selectedDenomination = Networking.LocalPlayer != null && !Networking.LocalPlayer.IsUserInVR()
                ? FindDesktopCandidate(out selectedColumn, out handPosition)
                : FindCandidateForHand(holdingHand, out selectedColumn, out handPosition, out distance);
            selectedCount = CandidateCount(selectedDenomination, selectedColumn, handPosition.y);
        }
        if (selectedDenomination < 0 || selectedCount <= 0
            || !BeginReservation(selectedDenomination, selectedColumn, selectedCount))
        {
            pickup.Drop();
            holdingHand = -1;
            RefreshInteraction();
            return;
        }

        state = HELD_RAISE;
        callActionActive = false;
        if (player != null) player.SetPhysicalRaiseActionActive(true);
        ConfigureCarriedCollider();
        CenterCarriedPileOnHand();
        SetRootCollider(true);
        SetPhysics(true);
        if (raisePile != null) raisePile.SetTextVisibility(true);
        if (chipClinkPlayer != null) chipClinkPlayer.Play();
    }

public override void OnDrop()
    {
        if (state != HELD_RAISE) return;
        HideHover();
        MarkShown();
        holdingHand = -1;
        state = DROP_PENDING;
        pendingDropToken = ++dropToken;
        pendingDropResolveTime = Time.time + 0.5f;
        SetPickupable(true);
        SetPhysics(true);
        if (raisePile != null)
        {
            if (_GetRepresentedRaiseValue() > 0)
                raisePile.OverrideText(_GetRepresentedRaiseValue().ToString());
            else
                raisePile.UpdateText();
            raisePile.SetTextVisibility(true);
        }
        if (chipClinkPlayer != null) chipClinkPlayer.Play();
        SendCustomEventDelayedSeconds(nameof(_ResolvePhysicalDrop), 0.5f);
    }

public override void OnPickupUseDown()
    {
        ApplyPreviewIncrease();
    }

private bool ApplyPreviewIncrease()
    {
        if (state != HELD_RAISE || player == null) return false;
        int denomination = previewHand == holdingHand ? previewDenomination : -1;
        int column = previewHand == holdingHand ? previewColumn : -1;
        int selectedCount = previewHand == holdingHand ? previewCount : 0;
        if (denomination < 0 || column < 0 || selectedCount <= 0)
        {
            Vector3 handPosition;
            float distance;
            if (Networking.LocalPlayer != null && !Networking.LocalPlayer.IsUserInVR())
                denomination = FindDesktopCandidate(out column, out handPosition);
            else
                denomination = FindCandidateForHand(holdingHand, out column, out handPosition, out distance);
            selectedCount = CandidateCount(denomination, column, handPosition.y);
        }
        if (denomination < 0 || selectedCount <= 0) return false;

        int moved = sourcePile.TransferColumnTopTo(raisePile, denomination, column, selectedCount);
        if (moved != selectedCount)
        {
            if (moved > 0) raisePile.TransferDenominationTo(sourcePile, denomination, moved);
            return false;
        }
        localRaiseCounts[denomination] += moved;
        RecomputeRepresentedRaise();
        PublishActiveReservation();
        if (chipClinkPlayer != null) chipClinkPlayer.Play();
        UpdateHover();
        return true;
    }

public void _ResolvePhysicalDrop()
    {
        if (state != DROP_PENDING || pendingDropToken != dropToken) return;
        if (pickup != null && pickup.IsHeld) return;
        if (Time.time + 0.01f < pendingDropResolveTime)
        {
            SendCustomEventDelayedSeconds(nameof(_ResolvePhysicalDrop), pendingDropResolveTime - Time.time);
            return;
        }

        if (TryCommitInPlayArea()) return;
        ReturnReservation(true);
    }

private bool TryCommitInPlayArea()
    {
        if (state != HELD_RAISE && state != DROP_PENDING) return false;
        Vector3 point = raisePile != null ? raisePile.transform.position : transform.position;
        bool inside = targetCollider != null
            && (targetCollider.ClosestPoint(point) - point).sqrMagnitude < 0.001f;
        if (!inside || !CanBetNow()) return false;

        int raiseValue = _GetRepresentedRaiseValue();
        if (raiseValue <= 0) raiseValue = RaiseValue(localRaiseCounts);
        if (!player.ApplyPhysicalRaise(raiseValue) || !player._CommitPhysicalBet()) return false;

        state = COMMITTED;
        dropToken++;
        if (pickup != null && pickup.IsHeld) pickup.Drop();
        bool animated = player.game != null && player.game.CollectCommittedChips(player);
        if (!animated && raisePile != null) raisePile.ReleaseAllToPools();
        ClearLocalCounts();
        PublishTerminal(DISPOSITION_CONSUMED);
        SetRootCollider(false);
        SetPhysics(false);
        SetPickupable(false);
        player.SetPhysicalRaiseActionActive(false);
        return true;
    }


    public void SetLocalPhysicalMode(bool enabled)
    {
        if (localPhysicalMode == enabled) return;
        localPhysicalMode = enabled;
        if (!enabled && HasLocalReservation()) ReturnReservation(true);
        UpdateSelectableLayout();
        RefreshInteraction();
    }

    public void SetInteractionEnabled(bool enabled)
    {
        interactionRequested = enabled;
        RefreshInteraction();
    }

    public void SetCallActionActive(bool active)
    {
        callActionActive = active;
        RefreshInteraction();
    }

public void _CancelReservationForCall()
    {
        if (HasLocalReservation()) ReturnReservation(true);
    }


    public void ResetForTurn(int epoch)
    {
        dropToken++;
        if (HasLocalReservation())
        {
            ReturnReservation(true);
            return;
        }
        if (raisePile != null && raisePile.GetTotalDisplayedValue() > 0) raisePile.ReleaseAllToPools();
        ClearLocalCounts();
        if (epoch > lastAppliedEpoch)
        {
            lastAppliedEpoch = epoch;
            lastAppliedVersion = -1;
            remoteReservationNeedsPhysicalLayout = false;
        }
        Respawn();
        RefreshInteraction();
    }

    public bool HasVisualReservationForEpoch(int epoch)
    {
        if (HasLocalReservation() && (localReservationEpoch < 0 || localReservationEpoch == epoch)) return true;
        return remoteReservationNeedsPhysicalLayout && syncedReservationEpoch == epoch;
    }

    public void OnPlayerStateDeserialized(int epoch)
    {
        if (syncedDisposition != DISPOSITION_ACTIVE && epoch > lastAppliedEpoch)
        {
            remoteReservationNeedsPhysicalLayout = false;
            lastAppliedEpoch = epoch;
            UpdateSelectableLayout();
        }
        TryApplySynchronizedReservation();
    }

    public override void OnDeserialization()
    {
        TryApplySynchronizedReservation();
    }

private bool BeginReservation(int denomination, int column, int selectedCount)
    {
        if (raisePile == null || sourcePile == null || player == null || HasLocalReservation()
            || selectedCount <= 0) return false;
        int movedSelected = sourcePile.TransferColumnTopTo(raisePile, denomination, column, selectedCount);
        if (movedSelected != selectedCount)
        {
            if (movedSelected > 0) raisePile.TransferAllTo(sourcePile);
            return false;
        }

        ClearLocalCounts();
        localRaiseCounts[denomination] = movedSelected;
        int selectedValue = RaiseValue(localRaiseCounts);
        int desiredBet = player.PreviewPhysicalRaise(selectedValue);
        int desiredRaise = Mathf.Max(0, desiredBet - player.GetPhysicalCallAmount());
        if (desiredRaise > selectedValue)
            sourcePile.TransferValueApproximateTo(raisePile, desiredRaise - selectedValue);
        raisePile.CopyDisplayedDenominationCounts(localRaiseCounts);
        RecomputeRepresentedRaise();
        PublishActiveReservation();
        return true;
    }

    /// <summary>
    /// The wager this reservation stands for. Chips only approximate it: it is at least the
    /// minimum raise increment, it never exceeds stack - call, and draining the source pile
    /// forces the exact all-in remainder even when the smallest denomination cannot represent it.
    /// </summary>
    private void RecomputeRepresentedRaise()
    {
        representedRaiseValue = 0;
        if (player == null || sourcePile == null || raisePile == null) return;
        int call = player.GetPhysicalCallAmount();
        int maxRaise = Mathf.Max(0, player.GetPhysicalStackValue() - call);
        if (maxRaise <= 0) return;
        if (sourcePile.GetTotalDisplayedValue() <= 0)
        {
            representedRaiseValue = maxRaise;
            return;
        }
        int chipValue = raisePile.GetTotalDisplayedValue();
        int minRaiseIncrement = Mathf.Max(0, player.GetPhysicalMinimumRaiseBet() - call);
        representedRaiseValue = Mathf.Clamp(Mathf.Max(chipValue, minRaiseIncrement), 0, maxRaise);
    }

    public int _GetRepresentedRaiseValue()
    {
        if (HasLocalReservation()) return representedRaiseValue;
        if (remoteReservationNeedsPhysicalLayout && syncedDisposition == DISPOSITION_CONSUMED)
            return Mathf.Max(0, representedRaiseValue);
        return 0;
    }


    private void ReturnReservation(bool publish)
    {
        if (state == RETURNING) return;
        state = RETURNING;
        dropToken++;
        if (raisePile != null && sourcePile != null) raisePile.TransferAllTo(sourcePile);
        ClearLocalCounts();
        if (player != null) player._ResetPhysicalBetToCall();
        if (publish) PublishTerminal(DISPOSITION_RETURNED);
        if (player != null) player.SetPhysicalRaiseActionActive(false);
        Respawn();
        RefreshInteraction();
    }

    private void PublishActiveReservation()
    {
        if (!Networking.IsOwner(gameObject) || player == null || player.game == null) return;
        for (int i = 0; i < syncedRaiseCounts.Length; i++) syncedRaiseCounts[i] = localRaiseCounts[i];
        syncedReservationEpoch = player.game.epoch;
        localReservationEpoch = syncedReservationEpoch;
        syncedRepresentedBet = representedRaiseValue;
        syncedSourceBaseline = SourceBaselineValue();
        syncedDisposition = DISPOSITION_ACTIVE;
        syncedReservationVersion++;
        lastAppliedEpoch = syncedReservationEpoch;
        lastAppliedVersion = syncedReservationVersion;
        remoteReservationNeedsPhysicalLayout = true;
        UpdateSelectableLayout();
        if (raisePile != null) raisePile.OverrideText(syncedRepresentedBet.ToString());
        MarkShown();
        RequestSerialization();
    }

    private void PublishTerminal(int disposition)
    {
        if (!Networking.IsOwner(gameObject) || player == null || player.game == null) return;
        for (int i = 0; i < syncedRaiseCounts.Length; i++) syncedRaiseCounts[i] = 0;
        syncedReservationEpoch = player.game.epoch;
        syncedRepresentedBet = player.bet;
        syncedSourceBaseline = sourcePile == null ? 0 : sourcePile.GetTotalDisplayedValue();
        syncedDisposition = disposition;
        syncedReservationVersion++;
        lastAppliedEpoch = syncedReservationEpoch;
        lastAppliedVersion = syncedReservationVersion;
        remoteReservationNeedsPhysicalLayout = disposition == DISPOSITION_CONSUMED;
        UpdateSelectableLayout();
        RequestSerialization();
    }

    private void TryApplySynchronizedReservation()
    {
        if (player == null || player.game == null || sourcePile == null || raisePile == null) return;
        if (syncedReservationVersion <= lastAppliedVersion) return;

        if (HasLocalReservation()) raisePile.TransferAllTo(sourcePile);
        if (syncedDisposition == DISPOSITION_ACTIVE)
        {
            sourcePile.SetSelectableStackMode(true);
            sourcePile.SetTotalChips(syncedSourceBaseline);
            ClearLocalCounts();
            for (int i = 0; i < syncedRaiseCounts.Length; i++)
            {
                int requested = Mathf.Max(0, syncedRaiseCounts[i]);
                int moved = sourcePile.TransferDenominationsWithSpawnTo(raisePile, i, requested);
                localRaiseCounts[i] = moved;
                if (moved != requested) return;
            }
            remoteReservationNeedsPhysicalLayout = true;
            representedRaiseValue = Mathf.Max(0, syncedRepresentedBet);
            raisePile.OverrideText(syncedRepresentedBet.ToString());
            raisePile.SetTextVisibility(true);
            MarkShown();
        }
        else if (syncedDisposition == DISPOSITION_RETURNED)
        {
            if (raisePile.GetTotalDisplayedValue() > 0) raisePile.TransferAllTo(sourcePile);
            sourcePile.SetTotalChips(syncedSourceBaseline);
            ClearLocalCounts();
            remoteReservationNeedsPhysicalLayout = false;
        }
        else if (syncedDisposition == DISPOSITION_CONSUMED)
        {
            if (raisePile.GetTotalDisplayedValue() > 0) raisePile.ReleaseAllToPools();
            ClearLocalCounts();
            // Remote viewers have no local actionTaken flag; keep exposing the committed
            // raise increment until the epoch advances so their stack readouts stay exact.
            representedRaiseValue = Mathf.Max(0, syncedRepresentedBet - player.GetPhysicalCallAmount());
            remoteReservationNeedsPhysicalLayout = true;
        }
        lastAppliedEpoch = syncedReservationEpoch;
        lastAppliedVersion = syncedReservationVersion;
        if (HasLocalReservation()) localReservationEpoch = syncedReservationEpoch;
        UpdateSelectableLayout();
        RefreshInteraction();
    }

private void UpdateHover()
    {
        int bestHand = -1;
        int bestDenomination = -1;
        int bestColumn = -1;
        Vector3 bestPosition = Vector3.zero;
        float bestDistance = float.MaxValue;
        bool desktopHeld = state == HELD_RAISE && Networking.LocalPlayer != null
            && !Networking.LocalPlayer.IsUserInVR();
        if (desktopHeld)
        {
            bestDenomination = FindDesktopCandidate(out bestColumn, out bestPosition);
            bestDistance = bestDenomination < 0 ? float.MaxValue : 0f;
        }
        else
        {
            int firstHand = state == HELD_RAISE ? holdingHand : 0;
            int lastHand = state == HELD_RAISE ? holdingHand : 1;
            for (int hand = firstHand; hand <= lastHand; hand++)
            {
                Vector3 position;
                int column;
                float distance;
                int denomination = FindCandidateForHand(hand, out column, out position, out distance);
                if (denomination < 0) continue;
                if (distance < bestDistance || (Mathf.Approximately(distance, bestDistance)
                    && (bestHand < 0 || hand < bestHand || (hand == bestHand
                        && (denomination < bestDenomination || (denomination == bestDenomination && column < bestColumn))))))
                {
                    bestHand = hand;
                    bestDenomination = denomination;
                    bestColumn = column;
                    bestPosition = position;
                    bestDistance = distance;
                }
            }
        }

        int count = CandidateCount(bestDenomination, bestColumn, bestPosition.y);
        if (bestDenomination < 0)
        {
            if (state == HOVER_SOURCE) state = IDLE_SOURCE;
            HideHoverOnce();
            return;
        }
        MarkShown();
        int columnChips = sourcePile.GetDenominationColumnChipCount(bestDenomination, bestColumn);
        if (state == HELD_RAISE)
        {
            // Already carrying a raise: VRChat's own outline is gone, but the chips the hand would add still glow.
            // With nothing selected there is nothing to show (the whole-column outline is VRChat's job).
            if (count > 0) SetHighlight(bestDenomination, bestColumn, columnChips, count);
            else SetHighlight(-1, -1, 0, 0);
        }
        else
        {
            SetHighlight(bestDenomination, bestColumn, columnChips, count);
            FitSelectionColliderToColumn(bestDenomination, bestColumn);
            SetRootCollider(true);
        }
        int denominationValue = sourcePile.GetDenominationValue(bestDenomination);
        int amount = count * denominationValue;
        int current = state == HELD_RAISE ? _GetRepresentedRaiseValue() : 0;
        previewDenomination = bestDenomination;
        previewColumn = bestColumn;
        previewHand = bestHand;
        previewCount = count;
        previewTotal = current + amount;
        BuzzOnAmountChange(bestHand, bestDenomination, bestColumn, count);
        bool held = state == HELD_RAISE;
        if (!held) state = HOVER_SOURCE;

        string preview = current.ToString() + " (+" + amount.ToString() + ")";
        if (pickup != null)
        {
            pickup.UseText = "";
            pickup.InteractionText = "";
        }
        if (raisePile != null)
        {
            raisePile.OverrideText(preview);
            raisePile.SetTextVisibility(true);
        }
    }

    // Proxy chip i sits on the real chip at height i of the hovered column, in the same pose (position and per-chip
    // yaw). With nothing selected every chip of the column is enabled with the invisible material, so VRChat's own
    // outline wraps the whole pile you would grab. With `selected` chips, only the top `selected` proxies stay on and
    // they switch to the highlight materials; the ones below are disabled so VRChat's outline skips them.
    private void SetHighlight(int denomination, int column, int columnChips, int selected)
    {
        if (highlightChips == null) return;
        int firstShown = 0;
        int shown = 0;
        int mode = 0;
        if (denomination >= 0 && column >= 0 && columnChips > 0 && sourcePile != null)
        {
            shown = Mathf.Min(columnChips, highlightChips.Length);
            int litCount = Mathf.Clamp(selected, 0, shown);
            mode = litCount > 0 ? 2 : 1;
            if (litCount > 0) firstShown = shown - litCount;
        }
        if (mode != highlightMode)
        {
            highlightMode = mode;
            Material[] materials = mode == 2 ? highlightSelectedMaterials : highlightIdleMaterials;
            if (materials != null && materials.Length > 0)
                for (int i = 0; i < highlightChips.Length; i++)
                    if (highlightChips[i] != null) highlightChips[i].sharedMaterials = materials;
        }
        for (int i = 0; i < highlightChips.Length; i++)
        {
            Renderer chip = highlightChips[i];
            if (chip == null) continue;
            bool on = i >= firstShown && i < shown;
            if (on)
            {
                Vector3 chipPosition = sourcePile.GetDenominationColumnChipWorldPosition(denomination, column, i);
                Quaternion chipRotation = sourcePile.GetDenominationColumnChipWorldRotation(denomination, column, i);
                chip.transform.SetPositionAndRotation(chipPosition, chipRotation);
            }
            if (chip.enabled != on) chip.enabled = on;
        }
    }

    private void ResetHaptics()
    {
        hapticHand = -1;
        hapticDenomination = -1;
        hapticColumn = -1;
        hapticCount = 0;
    }

    private void BuzzOnAmountChange(int hand, int denomination, int column, int count)
    {
        bool changed = hand != hapticHand || denomination != hapticDenomination
            || column != hapticColumn || count != hapticCount;
        hapticHand = hand;
        hapticDenomination = denomination;
        hapticColumn = column;
        hapticCount = count;
        if (!changed || hand < 0 || Networking.LocalPlayer == null || !Networking.LocalPlayer.IsUserInVR()) return;
        Networking.LocalPlayer.PlayHapticEventInHand(
            hand == 0 ? VRC_Pickup.PickupHand.Left : VRC_Pickup.PickupHand.Right,
            HAPTIC_DURATION, HAPTIC_AMPLITUDE, HAPTIC_FREQUENCY);
    }

    /// <summary>
    /// Installs the local player's calibrated hand-to-sample offset, expressed for a 0.8m eye height like the
    /// authored default. Implausible values are ignored so a bad save can never break chip selection.
    /// </summary>
    public void SetCalibratedHandOffset(Vector3 baseOffset)
    {
        if (!PhysicalRaiseSelectionMath.IsPlausibleOffset(baseOffset)) return;
        calibratedHandOffset = baseOffset;
        hasCalibratedHandOffset = true;
    }

    /// <summary>Drops the calibration so the authored handOffset applies again.</summary>
    public void _ClearCalibratedHandOffset()
    {
        hasCalibratedHandOffset = false;
        calibratedHandOffset = Vector3.zero;
    }

    /// <summary>The hand-to-sample offset in effect for the local player's current avatar size.</summary>
    public Vector3 _GetScaledHandOffset()
    {
        Vector3 baseOffset = hasCalibratedHandOffset ? calibratedHandOffset : handOffset;
        return baseOffset * AvatarScale();
    }

    private float AvatarScale()
    {
        VRCPlayerApi local = Networking.LocalPlayer;
        if (local == null) return 1f;
        return PhysicalRaiseSelectionMath.ScaleFactor(local.GetAvatarEyeHeightAsMeters());
    }

    private int FindCandidateForHand(int hand, out int bestColumn, out Vector3 handPosition, out float bestDistance)
    {
        bestColumn = -1;
        handPosition = Vector3.zero;
        bestDistance = float.MaxValue;
        if (sourcePile == null || Networking.LocalPlayer == null || hand < 0)
        {
            WarnConfiguration();
            return -1;
        }
        VRCPlayerApi.TrackingDataType type = hand == 0
            ? VRCPlayerApi.TrackingDataType.LeftHand : VRCPlayerApi.TrackingDataType.RightHand;
        VRCPlayerApi.TrackingData handData = Networking.LocalPlayer.GetTrackingData(type);
        handPosition = PhysicalRaiseSelectionMath.HandPoint(handData.position, handData.rotation,
            PhysicalRaiseSelectionMath.MirrorOffsetForHand(_GetScaledHandOffset(), hand != 0));
        Vector3 point = handPosition;
        float radius = selectionRadius;
        float below = selectionHeightBelowStack;
        float above = selectionHeightAboveStack;
        int bestDenomination = sourcePile.FindSelectableColumn(point, radius, below, above);
        if (bestDenomination >= 0)
        {
            bestColumn = sourcePile._GetFoundColumn();
            bestDistance = sourcePile._GetFoundDistance();
        }
        return bestDenomination;
    }

private int CandidateCount(int denomination, int column, float handWorldY)
    {
        if (sourcePile == null || denomination < 0 || column < 0) return 0;
        int displayed = sourcePile.GetDenominationColumnChipCount(denomination, column);
        float worldHeight = sourcePile.chipHeight * Mathf.Abs(sourcePile.transform.lossyScale.y);
        return PhysicalRaiseSelectionMath.SelectionCount(
            sourcePile.GetDenominationColumnTopWorldY(denomination, column), handWorldY,
            worldHeight, displayed, sourcePile.stackHeight);
    }

private void RefreshInteraction()
    {
        if (state == HELD_RAISE || state == DROP_PENDING || state == RETURNING || state == COMMITTED)
        {
            SetSourceColliders(false);
            if (state == COMMITTED) SetPickupable(false);
            return;
        }
        bool enabled = CanHandleChips() && !HasLocalReservation() && state != COMMITTED;
        if (!enabled && state == DISABLED && disabledApplied) return;
        state = enabled ? IDLE_SOURCE : (state == COMMITTED ? COMMITTED : DISABLED);
        // Idle there is no grab/interact surface at all: UpdateHover enables a collider fitted to the single hovered
        // pile, so VRChat only highlights and lets you grab the pile your hand is over.
        SetSourceColliders(false);
        SetRootCollider(false);
        SetPickupable(enabled);
        if (!enabled) HideHover();
        disabledApplied = !enabled && state == DISABLED;
    }

    private bool CanHandleChips()
    {
        return localPhysicalMode && !callActionActive && player != null
            && player.CanHandlePhysicalChips() && Networking.LocalPlayer != null;
    }

    private bool CanBetNow()
    {
        return interactionRequested && player != null && player.CanStartPhysicalRaise();
    }

    private int FindDesktopCandidate(out int column, out Vector3 selectionPosition)
    {
        column = -1;
        selectionPosition = Vector3.zero;
        if (sourcePile == null || sourcePile.denominationValues == null) return -1;

        int bestDenomination = -1;
        int bestValue = -1;
        for (int denomination = 0; denomination < sourcePile.denominationValues.Length; denomination++)
        {
            if (sourcePile.maxActiveDenominations > 0 && !sourcePile.IsDenominationActive(denomination)) continue;
            if (sourcePile.GetDenominationColumnChipCount(denomination, 0) <= 0) continue;
            int value = sourcePile.GetDenominationValue(denomination);
            if (value <= bestValue) continue;
            bestValue = value;
            bestDenomination = denomination;
        }
        if (bestDenomination < 0) return -1;

        column = 0;
        selectionPosition = sourcePile.GetDenominationColumnWorldPosition(bestDenomination, column);
        float chipWorldHeight = sourcePile.chipHeight * Mathf.Abs(sourcePile.transform.lossyScale.y);
        selectionPosition.y = sourcePile.GetDenominationColumnTopWorldY(bestDenomination, column)
            - chipWorldHeight * 0.25f;
        return bestDenomination;
    }

    private bool HasLocalReservation()
    {
        if (localRaiseCounts == null) return false;
        for (int i = 0; i < localRaiseCounts.Length; i++) if (localRaiseCounts[i] > 0) return true;
        return false;
    }

    private int RaiseValue(int[] counts)
    {
        int value = 0;
        if (counts == null || sourcePile == null) return value;
        for (int i = 0; i < counts.Length; i++) value += counts[i] * sourcePile.GetDenominationValue(i);
        return value;
    }

    private int SourceBaselineValue()
    {
        return player != null && player.CanUsePhysicalBetting()
            ? player.GetPhysicalSourceBaselineValue() : player.GetPhysicalStackValue();
    }

    private void ClearLocalCounts()
    {
        representedRaiseValue = 0;
        if (localRaiseCounts == null) return;
        for (int i = 0; i < localRaiseCounts.Length; i++) localRaiseCounts[i] = 0;
    }

    private void UpdateSelectableLayout()
    {
        if (sourcePile != null) sourcePile.SetSelectableStackMode(localPhysicalMode || remoteReservationNeedsPhysicalLayout);
    }

private void Respawn()
    {
        SetPhysics(false);
        SetRootCollider(false);
        if (raisePile != null) raisePile.SetTextVisibility(false);
        if (Networking.IsOwner(gameObject) && objectSync != null) objectSync.Respawn();
        state = DISABLED;
        holdingHand = -1;
    }

    // Fits the pickup capsule around one chip pile: same reach as the hand selection (radius, a little below the
    // base, and above the top) so grabbing works anywhere the hover does, but nothing else is a grab target.
    private void FitSelectionColliderToColumn(int denomination, int column)
    {
        if (pickupCapsule == null || sourcePile == null || denomination < 0 || column < 0) return;
        Vector3 worldCenter = sourcePile.GetDenominationColumnWorldPosition(denomination, column);
        float bottomY = worldCenter.y - selectionHeightBelowStack;
        float topY = Mathf.Max(worldCenter.y, sourcePile.GetDenominationColumnTopWorldY(denomination, column))
            + selectionHeightAboveStack;
        Vector3 scale = transform.lossyScale;
        float radius = selectionRadius / Mathf.Max(0.0001f, Mathf.Max(Mathf.Abs(scale.x), Mathf.Abs(scale.z)));
        float height = Mathf.Max((topY - bottomY) / Mathf.Max(0.0001f, Mathf.Abs(scale.y)), radius * 2f);
        pickupCapsule.direction = 1;
        pickupCapsule.radius = radius;
        pickupCapsule.height = height;
        pickupCapsule.center = transform.InverseTransformPoint(
            new Vector3(worldCenter.x, (bottomY + topY) * 0.5f, worldCenter.z));
    }

private void ConfigureCarriedCollider()
    {
        if (pickupCapsule == null) return;
        pickupCapsule.direction = carriedColliderDirection;
        pickupCapsule.radius = carriedColliderRadius;
        pickupCapsule.height = carriedColliderHeight;
        pickupCapsule.center = carriedColliderCenter;
    }

private void PositionReadoutOnHand()
    {
        if (Networking.LocalPlayer == null || raisePile == null || readout == null) return;
        //Transform readout = raisePile.textGameObject.transform;
        if (Networking.LocalPlayer.IsUserInVR())
        {
            VRCPlayerApi.TrackingDataType type;
            if (holdingHand < 0)
            {
                type = VRCPlayerApi.TrackingDataType.RightHand;
                if (previewHand >= 0)
                {
                    type = previewHand == 0
                        ? VRCPlayerApi.TrackingDataType.LeftHand : VRCPlayerApi.TrackingDataType.RightHand;
                }
                else
                {
                    Vector3 leftPos = Networking.LocalPlayer.GetTrackingData(VRCPlayerApi.TrackingDataType.LeftHand).position;
                    Vector3 rightPos = Networking.LocalPlayer.GetTrackingData(VRCPlayerApi.TrackingDataType.RightHand).position;
                    Vector3 current = transform.position;
                    if ((leftPos - current).sqrMagnitude < (rightPos - current).sqrMagnitude)
                        type = VRCPlayerApi.TrackingDataType.LeftHand;
                }
            }
            else
            {
                type = holdingHand == 0
                    ? VRCPlayerApi.TrackingDataType.LeftHand : VRCPlayerApi.TrackingDataType.RightHand;
            }
            VRCPlayerApi.TrackingData hand = Networking.LocalPlayer.GetTrackingData(type);
            SetLookAtDriven(true);
            // While carried (or falling after a drop) the readout hangs above the pile itself: the pickup is gripped
            // away from the tracked controller origin, so anchoring to the hand makes the text stay put while the
            // chips swing around it. While idle it tracks the hand that is hovering the stacks.
            Vector3 anchor = state == HELD_RAISE || state == DROP_PENDING ? transform.position : hand.position;
            // Lift along world up (not any local frame) and face the viewer on every axis.
            readout.position = anchor + Vector3.up * (readoutYOffset * AvatarScale());
            VRCPlayerApi.TrackingData head = Networking.LocalPlayer.GetTrackingData(VRCPlayerApi.TrackingDataType.Head);
            readout.rotation = head.rotation;
        }
        else
        {
            SetLookAtDriven(false);
            // A look-at that hovers in world Y owns the position; a local offset here would rotate with the pile.
            LookAtPlayerYawOnly look = raisePile.lookAtPlayer;
            if (look == null || !look.useWorldYOffset) readout.localPosition = new Vector3(0f, 0.064f, 0f);
        }
    }

    private void SetLookAtDriven(bool driven)
    {
        LookAtPlayerYawOnly look = raisePile != null ? raisePile.lookAtPlayer : null;
        if (look != null && look.externallyDriven != driven) look.externallyDriven = driven;
    }


    private void SetPhysics(bool active)
    {
        if (active) disabledApplied = false;
        if (rb == null) return;
        rb.useGravity = active;
        rb.isKinematic = !active;
        if (!active)
        {
            rb.velocity = Vector3.zero;
            rb.angularVelocity = Vector3.zero;
        }
    }

    private void SetRootCollider(bool enabledValue)
    {
        if (enabledValue) disabledApplied = false;
        if (ownCollider != null)
        {
            ownCollider.enabled = enabledValue;
            ownCollider.isTrigger = false;
        }
    }

    private void SetSourceColliders(bool enabledValue)
    {
        if (enabledValue) disabledApplied = false;
        if (denominationColliders == null) return;
        bool hasActiveFilter = sourcePile != null && sourcePile.maxActiveDenominations > 0;
        for (int i = 0; i < denominationColliders.Length; i++)
        {
            if (denominationColliders[i] == null) continue;
            if (hasActiveFilter && !sourcePile.IsDenominationActive(i))
            {
                denominationColliders[i].enabled = false;
                continue;
            }
            denominationColliders[i].enabled = enabledValue;
        }
    }

    private void SetPickupable(bool enabledValue)
    {
        if (enabledValue) disabledApplied = false;
        DisableInteractive = true;
        InteractionText = "";
        if (pickup != null) pickup.InteractionText = "";
        if (objectSync != null) objectSync.pickupable = enabledValue;
        else if (pickup != null) pickup.pickupable = enabledValue;
    }

    // The hover or readout is visible again, so the next hide (per-frame or RefreshInteraction) must really run
    private void MarkShown()
    {
        hoverHidden = false;
        disabledApplied = false;
    }

    // Per-frame form of HideHover. The respawn only runs when the hidden state changes; while hidden, the rest is
    // redone every HIDDEN_REFRESH_SECONDS in case something outside this script showed the readout. A carried raise
    // keeps its live readout, so it is never latched.
    private void HideHoverOnce()
    {
        if (state == HELD_RAISE)
        {
            HideHover();
            MarkShown();
            return;
        }
        float now = Time.time;
        if (hoverHidden && hoverHiddenState == state)
        {
            if (now < hoverHiddenRefreshTime) return;
            hoverHiddenRefreshTime = now + HIDDEN_REFRESH_SECONDS;
            HideHoverVisuals();
            return;
        }
        HideHover();
        hoverHidden = true;
        hoverHiddenState = state;
        hoverHiddenRefreshTime = now + HIDDEN_REFRESH_SECONDS;
    }

private void HideHover()
    {
        HideHoverVisuals();
        if (state == IDLE_SOURCE && Networking.IsOwner(gameObject) && objectSync != null)
            objectSync.Respawn();
    }

    private void HideHoverVisuals()
    {
        SetHighlight(-1, -1, 0, 0);
        if (state == IDLE_SOURCE || state == HOVER_SOURCE) SetRootCollider(false);
        ResetHaptics();
        previewDenomination = -1;
        previewColumn = -1;
        previewHand = -1;
        previewCount = 0;
        previewTotal = 0;
        if (pickup != null)
        {
            pickup.InteractionText = "";
            pickup.UseText = "";
        }
        if (state == HELD_RAISE && raisePile != null)
        {
            raisePile.OverrideText(_GetRepresentedRaiseValue().ToString());
            raisePile.SetTextVisibility(true);
        }
        else if (raisePile != null)
        {
            raisePile.UpdateText();
            raisePile.SetTextVisibility(false);
        }
    }

    private int PickupHandIndex(VRC_Pickup.PickupHand hand)
    {
        if (hand == VRC_Pickup.PickupHand.Left) return 0;
        if (hand == VRC_Pickup.PickupHand.Right) return 1;
        return -1;
    }



    private void WarnConfiguration()
    {
        if (warnedConfiguration) return;
        warnedConfiguration = true;
        Debug.LogWarning("PhysicalRaisePile: source pile or VR tracking configuration is incomplete.");
    }


private void CenterCarriedPileOnHand()
    {
        if (Networking.LocalPlayer == null || !Networking.LocalPlayer.IsUserInVR() || holdingHand < 0) return;
        VRCPlayerApi.TrackingDataType type = holdingHand == 0
            ? VRCPlayerApi.TrackingDataType.LeftHand : VRCPlayerApi.TrackingDataType.RightHand;
        VRCPlayerApi.TrackingData hand = Networking.LocalPlayer.GetTrackingData(type);
        transform.SetPositionAndRotation(hand.position, hand.rotation);
    }
}
