﻿using UdonSharp;
using UnityEngine;
using VRC.SDKBase;
using VRC.Udon;
using TMPro;
using VRC.Udon.Common;
using VRC.Udon.Common.Interfaces;
using VRC.SDK3.UdonNetworkCalling;

/// <summary>
/// Per-player state tracking.
/// </summary>
[UdonBehaviourSyncMode(BehaviourSyncMode.Manual)]
public class HoldemPlayer : UdonSharpBehaviour
{
    public HoldemGame game;
    public int seatIdx;

    public UnityEngine.UI.Text uiBestHand;
    public TMP_Text uiJoinLeaveText;
    public HoldButton uiJoinLeaveButton;

    public GameObject dealerIndicator;

    //public GameObject goChipDisplay;
    public BettingUi bettingUi;

    //public UnityEngine.UI.Image uiStatusColor, uiStatusColorBackground;
    public MeshLoadingBar statusBar;

    public AudioPoolPlayer attentionCuePlayer;
    public AudioPoolPlayer tickTockPlayer;

    public PokerChipPile stackPile;
    public PokerChipPile betPile;
    public GrabbablePile grabbableBetPile;
    public PhysicalRaisePile physicalRaisePile;
    public GameObject checkObject;

    public GameObject goRespawnHandUi;

    public GameObject goCardHighlight;

    public GrabbableHand grabbableHand;

    public PokerChipPile roundContributionPile;

    public PokerChipPile playerPotPile;
    public TransformMoverUdon potPileMover;
    public Transform potPileWinTransform;

    public GameObject rebuyButton;

    public string OwnerName()
    {
        var owner = Networking.GetOwner(gameObject);
        if (owner == null) return "(Editor)";
        return owner.displayName;
    }
    private int OwnerId()
    {
        var owner = Networking.GetOwner(gameObject);
        if (owner == null) return -2;
        return owner.playerId;
    }

    public bool IsSeated()
    {
        return activePlayerId == OwnerId();
    }

    // Hack to disambiguate this object being explicitly active vs taken over by the room master
    // after player disconnect. If activePlayerId = Networking.GetOwner(gameObject).playerId, then
    // we're explicitly owned. To explicitly disown, set to a negative value.
    [UdonSynced] int activePlayerId = -1;

    // For the room master to record who is sat here
    public int ActivePlayerId() { return activePlayerId; }

    private PlayerBalanceComponent ActivePlayerBalanceComponent = null;
    public PlayerBalanceComponent OwnerPlayerBalanceComponent()
    {
        if (ActivePlayerBalanceComponent == null && activePlayerId != -1)
        {
            var player = VRCPlayerApi.GetPlayerById(activePlayerId);
            if (player != null && Utilities.IsValid(player))
            {
                ActivePlayerBalanceComponent = PlayerBalanceComponent.GetPlayerBalanceComponent(player);
            }
        }
        return ActivePlayerBalanceComponent;
    }

    bool isLocallySeated()
    {
        return IsSeated() && Networking.IsOwner(gameObject);
    }

    // Seated here and owned by this client
    public bool _IsLocallySeated()
    {
        return isLocallySeated();
    }

    // The local player's own hole card: the dealer's copy, or the privately delivered one
    public int LocalHoleCard(int index)
    {
        return HoleCard(index);
    }

    private bool IsSeatedAnywhere()
    {
        if (game.players == null) return false;
        for (int i = 0; i < game.seats; ++i)
        {
            var p = game.players[i];
            if (p != null && p.IsSeated() && Networking.IsOwner(p.gameObject)) return true;
        }
        return false;
    }

    // Seats only go to the player taking them, and occupied seats only to the master
    public override bool OnOwnershipRequest(VRCPlayerApi requestingPlayer, VRCPlayerApi requestedOwner)
    {
        if (!Utilities.IsValid(requestingPlayer) || !Utilities.IsValid(requestedOwner)) return false;
        if (requestingPlayer.playerId != requestedOwner.playerId) return false;
        return !IsSeated() || HoldemAuthority.IsAuthority(requestingPlayer);
    }

    public void _ToggleControl()
    {
        if (NetworkCalling.InNetworkCall) return;
        if (isLocallySeated()) {
            _ReleaseControl();
        } else
        {
            _TakeControl();
        }
    }

    public void _TakeControl()
    {
        if (IsSeated()) return; // can't take over
        if (game != null && game.authority != null && Networking.LocalPlayer != null
            && game.authority.IsFlagged(Networking.LocalPlayer.displayName)) return;

        if (game != null && game.isTournamentActive)
        {
            string localPlayerName = (Networking.LocalPlayer == null) ? "(Editor)" : Networking.LocalPlayer.displayName;
            if (game.tournamentPlayerNames[seatIdx] == localPlayerName && !game.tournamentEliminated[seatIdx])
            {
                // Allow rejoin if it is their tournament seat and they are not eliminated,
                // but only between hands (i.e. not during TABLE_PLAYING or TABLE_WINNER).
                if (game.tableState == HoldemGame.TABLE_PLAYING || game.tableState == HoldemGame.TABLE_WINNER)
                {
                    return;
                }
            }
            else
            {
                return; // block joining during active tournament
            }
        }

        PlayerBalanceComponent BalanceComponent = PlayerBalanceComponent.GetPlayerBalanceComponent(Networking.LocalPlayer);
        if (Networking.LocalPlayer == null && BalanceComponent == null)
        {
            BalanceComponent = ActivePlayerBalanceComponent;
        }
        if (!BalanceComponent || !BalanceComponent.IsReady())
        {
            return;
        }
        if (game != null && !game.isTournamentMode && BalanceComponent.GetBalance() <= 0)
        {
            return;
        }

        // Ensure UdonChips reference is set
        if (BalanceComponent.udonChips == null && game != null && game.udonChips != null)
        {
            BalanceComponent.udonChips = game.udonChips;
        }
        
        Networking.SetOwner(Networking.LocalPlayer, gameObject);
        // not sure if this can take effect immediately, but let's try
        activePlayerId = Networking.LocalPlayer == null ? -2 : Networking.LocalPlayer.playerId;
        ActivePlayerBalanceComponent = BalanceComponent;
        playerReady = true;
        RequestSerialization();
        game.seatChangeVersion++;
    }

    public void _ReleaseControl()
    {
        if (Networking.IsOwner(game.gameObject) || isLocallySeated())
        {
            // if master is taking over
            Networking.SetOwner(Networking.LocalPlayer, gameObject);
            // no valid player will have a negative id (I think)
            activePlayerId = -1;
            ActivePlayerBalanceComponent = null;
            playerReady = false;
            RequestSerialization();
            game.seatChangeVersion++;
        }
    }

    // committed. internal logic should ensure that the bet is actually valid for
    // the game state.
    [UdonSynced] public int committedEpoch = -1;

    const int FOLD = -1;

    // pending/committed bet, -1 for FOLD , 0 for CHECK
    // -1 for FOLD during IDLE counts as sitting out,
    // as does not having enough chips for the big blind.
    [UdonSynced] public int bet = FOLD;

    [UdonSynced] public bool playerReady = false;
    [UdonSynced] public int rebuyVersion = 0;
    private int updateSeenEpoch = -1;
    private bool _wasActing = false;
    private int _lastInitBettingRound = -1;

    // moving this into a public function to avoid repetition
    // is there a cleaner way? probably, but having everything in the update loop makes things more difficult to handle while keeping it light
    // is there a funnier way to name the function? not likely
    private bool CanShowHoles()
    {
        var locallySeated = isLocallySeated();
        var playerState = game.playerState[seatIdx];
        var inPlay = playerState != HoldemGame.PLAYER_DEAD;
        var showdown = game.IsShowdown();
        var holes = inPlay && (locallySeated || (game.headsUp && !showdown) || (showdown && (game.aggressorSeat == seatIdx || (game.winnerMask & (1 << seatIdx)) != 0)));
        return holes;
    }

    private bool ShouldForceShowHoles()
    {
        var playerState = game.playerState[seatIdx];
        var inPlay = playerState != HoldemGame.PLAYER_DEAD;
        var showdown = game.IsShowdown();
        var forceShow = inPlay && showdown && (game.aggressorSeat == seatIdx || (game.winnerMask & (1 << seatIdx)) != 0 || IsShownBySeatedPlayer());
        return forceShow;
    }

    // Only the seated player can turn their own cards face up
    public bool IsShownBySeatedPlayer()
    {
        if (grabbableHand == null || !grabbableHand.isVisibleToOthers || !IsSeated()) return false;
        var handOwner = Networking.GetOwner(grabbableHand.gameObject);
        var seatOwner = Networking.GetOwner(gameObject);
        return handOwner != null && seatOwner != null && handOwner.playerId == seatOwner.playerId;
    }

    // This seat's own cards, sent privately by the table owner for the current hand
    private int privateHandId = -1;
    private int privateHole0 = -1;
    private int privateHole1 = -1;
    // Salt for the deal's commitment, so the cards can be proven to a new table owner
    private int privateSaltA;
    private int privateSaltB;
    private int requestedHandId = -1;
    private float holeCardRequestTime;
    private float recoveryReportTime;

    [NetworkCallable]
    public void ReceiveHoleCards(int dealtHandId, int card0, int card1, int saltA, int saltB)
    {
        VRCPlayerApi caller = NetworkCalling.CallingPlayer;
        if (game == null || !Utilities.IsValid(caller) || !Networking.IsOwner(caller, game.gameObject)) return;
        if (!isLocallySeated()) return;

        privateHandId = dealtHandId;
        privateHole0 = card0;
        privateHole1 = card1;
        privateSaltA = saltA;
        privateSaltB = saltB;
        _uiDirty = true;
        _UpdateCardDisplay();
        game._MarkHighlightsDirty();
    }

    // Dealer's copy, then our private cards, then whatever the table has revealed
    private int HoleCard(int index)
    {
        int shared = index == 0 ? game.holeCards0[seatIdx] : game.holeCards1[seatIdx];
        // A new owner doesn't have the dealer's copy until the hand is recovered
        if (Networking.IsOwner(game.gameObject) && shared >= 0) return shared;
        if (!isLocallySeated() || privateHandId != game.handId) return shared;
        return index == 0 ? privateHole0 : privateHole1;
    }

    // Our privately delivered cards for this hand, or false if we have none
    public bool _HasPrivateCards()
    {
        return isLocallySeated() && privateHandId == game.handId;
    }

    public int PrivateCard(int index)
    {
        return index == 0 ? privateHole0 : privateHole1;
    }

    public int PrivateSalt(int index)
    {
        return index == 0 ? privateSaltA : privateSaltB;
    }

    // Proves our cards to the new table owner while it recovers the hand the old dealer left
    private void ReportHoleCardsForRecovery()
    {
        if (game.recoveryHandId != game.handId || !_HasPrivateCards()) return;
        if (Networking.IsOwner(game.gameObject) || Time.time < recoveryReportTime) return;

        recoveryReportTime = Time.time + 2f;
        int reportHandId = privateHandId;
        int card0 = privateHole0;
        int card1 = privateHole1;
        int saltA = privateSaltA;
        int saltB = privateSaltB;
        game.SendCustomNetworkEvent(NetworkEventTarget.Owner, nameof(HoldemGame.ReportHoleCards),
            reportHandId, card0, card1, saltA, saltB);
    }

    // Asks the dealer again if our cards haven't arrived a couple of seconds into the hand
    private void RequestMissingHoleCards(int ts, int playerState)
    {
        if (ts != HoldemGame.TABLE_PLAYING || playerState == HoldemGame.PLAYER_DEAD || !isLocallySeated()) return;
        if (Networking.IsOwner(game.gameObject) || privateHandId == game.handId) return;

        if (requestedHandId != game.handId)
        {
            requestedHandId = game.handId;
            holeCardRequestTime = Time.time + 2f;
        }
        if (Time.time < holeCardRequestTime) return;

        holeCardRequestTime = Time.time + 3f;
        game.SendCustomNetworkEvent(NetworkEventTarget.Owner, nameof(HoldemGame.RequestHoleCards));
    }

    // Updates grabbable hand cards
    public void _UpdateCardDisplay()
    {
        if (CanShowHoles() || IsShownBySeatedPlayer())
        {
            grabbableHand.SetCards(HoleCard(0), HoleCard(1));
            if (ShouldForceShowHoles())
            {
                grabbableHand._ForceToShowPosition();
            }
        }
        else
        {
            grabbableHand.SetCards(-1, -1);
        }
    }

    public void MovePotPile(Transform initialPosition)
    {
        if (!potPileMover.enabled)
        {
            playerPotPile.gameObject.SetActive(true);
            potPileMover.SetStartAndTarget(initialPosition, potPileWinTransform);
            potPileMover.enabled = true;
        }
    }

public void _PrepareDynamicPotPile()
    {
        if (playerPotPile == null || potPileWinTransform == null) return;
        if (potPileMover != null) potPileMover.enabled = false;
        playerPotPile.gameObject.SetActive(true);
        playerPotPile.transform.position = potPileWinTransform.position;
        playerPotPile.transform.rotation = potPileWinTransform.rotation;
    }


    private int previousRemaining = 0;
    private bool winningsPendingMerge;

    // Dirty-flag caches: skip redundant UI calls when state hasn't changed.
    private int _cachedTs = -1;
    private int _cachedPlayerState = -1;
    private int _cachedButtonState = -1;
    // Expensive preamble cache: IsSeatedAnywhere() loops 10 seats, each calling Networking API
    private bool _cachedSeatedAnywhere;
    private int _cachedSeatedAnywhereEpoch = -1;
    private int _cachedSeatChangeVersion = -1;

    // Seat UI is rebuilt only when one of these changes
    private int _uiEpoch = -1;
    private int _uiSeatChangeVersion = -1;
    private int _uiBet = int.MinValue;
    private bool _uiActionTaken;
    private bool _uiDirty = true;
    private float _uiNextRefreshTime;

    // Seat state from the last UI rebuild
    private bool _seated;
    private bool _locallySeated;
    private int _playerState;
    private bool _acting;
    private int _stack;
    private Color _statusBarColor = Color.black;

    public override void OnOwnershipTransferred(VRCPlayerApi player)
    {
        if (game != null) game.seatChangeVersion++;
    }

    // Hand visibility is synced on the hand, outside game state
    public void _OnHandVisibilityChanged()
    {
        _uiDirty = true;
        _UpdateCardDisplay();
        if (game != null)
        {
            game._MarkHighlightsDirty();
            game._RequestTransition();
        }
    }

    private void Update()
    {
        // XXX apparently udon will run some Update()s before Starts() so
        // HoldemGame's start might not initialize this
        if (game == null) return;
        // don't bother if game isn't initialized
        int ts = game.tableState;
        if (ts == HoldemGame.TABLE_UNINITIALIZED) return;

        int gameEpoch = game.epoch;
        int gameSeatChangeVersion = game.seatChangeVersion;
        float time = Time.time;
        if (_uiDirty || gameEpoch != _uiEpoch || gameSeatChangeVersion != _uiSeatChangeVersion
            || bet != _uiBet || actionTaken != _uiActionTaken || time >= _uiNextRefreshTime)
        {
            _uiDirty = false;
            _uiEpoch = gameEpoch;
            _uiSeatChangeVersion = gameSeatChangeVersion;
            _uiBet = bet;
            _uiActionTaken = actionTaken;
            RefreshSeatUi(ts);
            // Local seat refreshes every second for the rebuy balance
            _uiNextRefreshTime = time + (_locallySeated ? 1f : 2f) + seatIdx * 0.05f;
        }

        bool seated = _seated;
        bool locallySeated = _locallySeated;
        int playerState = _playerState;
        bool acting = _acting;
        int stack = _stack;

        if (acting)
        {
            var now = Networking.LocalPlayer == null ? (int)(Time.time * 1000) : Networking.GetServerTimeInMilliseconds();
            var timeout = game.lastTransitionMillis;
            int actionTimeoutSecs = game.actionTimeoutSecs;
            var remaining = actionTimeoutSecs - (now - timeout) / 1000;
            float remainingFloat = ((float) actionTimeoutSecs) - (((float) now) - ((float) timeout)) / 1000;
            float remainingPercentage = remainingFloat / ((float) actionTimeoutSecs);
            if (remainingPercentage < 0f) remainingPercentage = 0f;
            statusBar.SetProgress(remainingPercentage);
            statusBar.SetLoadingColor(_statusBarColor * Mathf.Lerp(0.9f, 1.0f, (Mathf.Sin(Time.time * 4f) + 1f) * 0.5f));

            if (previousRemaining > remaining && remaining <= 10 && locallySeated)
            {
                tickTockPlayer.Play();
            }

            previousRemaining = remaining;
        }

        // check if the hand is in the fold area, and its owned by the local player.
        if (locallySeated)
        {
            RequestMissingHoleCards(ts, playerState);
            ReportHoleCardsForRecovery();
        }
        bool folded = locallySeated && acting && grabbableHand.IsFolded();
        if (folded)
        {
            _UiFoldImmediately();
            grabbableHand.SetGrabbable(false);
        }

        // transition check
        if (updateSeenEpoch != gameEpoch)
        {
            updateSeenEpoch = gameEpoch;
            if (physicalRaisePile != null) physicalRaisePile.OnPlayerStateDeserialized(gameEpoch);
            // edge-triggered
            if (locallySeated)
            {
                // new turn, or a new betting round while still acting
                if (acting && (!_wasActing || _lastInitBettingRound != game.bettingRound))
                {
                    game.OpenPlayerChipContainer(this);
                    if (physicalBettingEnabled || IsCallOnly()) bettingUi.HideBettingControls();
                    else bettingUi.AdjustButtons(stack);
                    // start off with a call
                    bet = folded ? -1 : Mathf.Min(stack, game.currentBet - game.roundContribution[seatIdx]);
                    RequestSerialization();
                    // require the confirm again
                    actionTaken = false;
                    if (physicalBettingEnabled && grabbableBetPile != null)
                        grabbableBetPile._ResetPhysicalBetToCallDisplay();
                    if (physicalBettingEnabled && physicalRaisePile != null)
                        physicalRaisePile.ResetForTurn(gameEpoch);
                }
                else if (acting && actionTaken)
                {
                    // stale actoinTaken, leave bet as-is.
                    actionTaken = false;
                    if (physicalBettingEnabled && grabbableBetPile != null)
                        grabbableBetPile._ResetPhysicalBetToCallDisplay();
                    if (physicalBettingEnabled && physicalRaisePile != null)
                        physicalRaisePile.ResetForTurn(gameEpoch);
                }
                else if (!acting && _wasActing)
                {
                    // turn end
                    if (physicalBettingEnabled && physicalRaisePile != null)
                        physicalRaisePile.ResetForTurn(gameEpoch);
                    bet = 0;
                    committedEpoch = -1;
                    RequestSerialization();
                }
                // else: !acting && !_wasActing - already idle, nothing to do
                // else: acting && _wasActing && same bettingRound - join/money bump, preserve bet

                _wasActing = acting;
                if (acting) _lastInitBettingRound = game.bettingRound;
            }

            // reposition cards at start of the game.
            if (ts == HoldemGame.TABLE_READY) {
                grabbableHand.SetEnabled(false);
                grabbableHand._MoveBackToInitialPosition();
                grabbableHand._MakeInvisibleToOthers();
                potPileMover.enabled = false;
                playerPotPile.gameObject.SetActive(false);
            }

            if (ts == HoldemGame.TABLE_PLAYING) {
                if (playerState != HoldemGame.PLAYER_DEAD) grabbableHand.SetEnabled(seated);
                _UpdateCardDisplay();

                var bestHand = game.BestHandForRound(HoleCard(0), HoleCard(1));
                if (bestHand > 0UL && HoldemHandEvaluator.GetHandClassInt(bestHand) > 0)
                {
                    uiBestHand.text = HoldemHandEvaluator.HandClass(bestHand).ToString();
                } else
                {
                    uiBestHand.text = "";
                }
            }

            if (ts == HoldemGame.TABLE_WINNER)
            {
                _UpdateCardDisplay();
            }

            if (ts == HoldemGame.TABLE_IDLE)
            {
                grabbableHand.SetEnabled(false);
                grabbableHand._MakeInvisibleToOthers();
                grabbableHand._MoveBackToInitialPosition();
                potPileMover.enabled = false;
                playerPotPile.gameObject.SetActive(false);
            }
            
            // Play attention cue when this player's turn just started
            if (acting && isLocallySeated())
            {
                attentionCuePlayer.Play();
            }
        }
    }

    private const int BTN_LEAVE = 0, BTN_OCCUPIED = 1, BTN_REJOIN = 2, BTN_ELIMINATED = 3,
        BTN_TOURNEY_NAME = 4, BTN_HIDDEN = 5, BTN_JOIN = 6;

    private void ApplyJoinLeaveButton(int state)
    {
        if (state == BTN_LEAVE)
        {
            uiJoinLeaveButton.DisableInteractive = false;
            uiJoinLeaveButton.secondsToHold = 1f;
            uiJoinLeaveText.text = "Leave (hold)";
        }
        else if (state == BTN_OCCUPIED)
        {
            uiJoinLeaveButton.DisableInteractive = true;
            uiJoinLeaveButton.StopHolding();
            uiJoinLeaveText.text = OwnerName();
            uiJoinLeaveButton.gameObject.SetActive(true);
        }
        else if (state == BTN_REJOIN || state == BTN_JOIN)
        {
            uiJoinLeaveButton.gameObject.SetActive(true);
            uiJoinLeaveButton.DisableInteractive = false;
            uiJoinLeaveButton.secondsToHold = 0f;
            uiJoinLeaveText.text = state == BTN_REJOIN ? "Rejoin" : "Join";
        }
        else
        {
            uiJoinLeaveButton.StopHolding();
            uiJoinLeaveButton.gameObject.SetActive(false);
            if (state == BTN_ELIMINATED) uiJoinLeaveText.text = "Eliminated";
            else if (state == BTN_TOURNEY_NAME) uiJoinLeaveText.text = game.tournamentPlayerNames[seatIdx];
        }
    }

    private void RefreshSeatUi(int ts)
    {
        // isLocallySeated() calls IsSeated() internally, so reuse that result
        // to avoid a duplicate Networking.GetOwner() call.
        int localOwnerId = OwnerId();
        var seated = activePlayerId == localOwnerId;
        var locallySeated = seated && Networking.IsOwner(gameObject);

        // Expensive 10-seat loop + Networking API calls; recompute only on epoch change or join/leave.
        if (_cachedSeatedAnywhereEpoch != game.epoch || _cachedSeatChangeVersion != game.seatChangeVersion)
        {
            _cachedSeatedAnywhere = IsSeatedAnywhere();
            _cachedSeatedAnywhereEpoch = game.epoch;
            _cachedSeatChangeVersion = game.seatChangeVersion;
        }
        bool seatedAnywhere = _cachedSeatedAnywhere;

        bool tsChanged = ts != _cachedTs;
        _cachedTs = ts;

        int buttonState;
        if (locallySeated) buttonState = BTN_LEAVE;
        else if (seated) buttonState = BTN_OCCUPIED;
        else if (game.isTournamentActive)
        {
            string localPlayerName = (Networking.LocalPlayer == null) ? "(Editor)" : Networking.LocalPlayer.displayName;
            bool eliminated = game.tournamentEliminated[seatIdx];
            if (game.tournamentPlayerNames[seatIdx] == localPlayerName && !eliminated) buttonState = BTN_REJOIN;
            else buttonState = eliminated ? BTN_ELIMINATED : BTN_TOURNEY_NAME;
        }
        else buttonState = seatedAnywhere ? BTN_HIDDEN : BTN_JOIN;

        if (tsChanged || buttonState != _cachedButtonState)
        {
            ApplyJoinLeaveButton(buttonState);
            _cachedButtonState = buttonState;
        }

        var betweenGames = ts == HoldemGame.TABLE_IDLE || ts == HoldemGame.TABLE_READY;

        var playerState = game.playerState[seatIdx];
        var inPlay = playerState != HoldemGame.PLAYER_DEAD;

        bool dealerIndicatorEnabled = ts == HoldemGame.TABLE_PLAYING && game.dealerSeat == seatIdx;
        dealerIndicator.SetActive(dealerIndicatorEnabled);

        var winner = ts == HoldemGame.TABLE_WINNER;

        var holes = CanShowHoles();
        uiBestHand.enabled = holes && game.bettingRound >= HoldemGame.FLOP;

        var acting = playerState == HoldemGame.PLAYER_ACTING;
        var valid = game.IsValidBet(bet, seatIdx);

        Color statusBarColor = playerState == HoldemGame.PLAYER_DEAD ? Color.black :
            playerState == HoldemGame.PLAYER_PENDING ? Color.white :
            playerState == HoldemGame.PLAYER_ACTING ? Color.green :
            playerState == HoldemGame.PLAYER_COMMITED ? Color.blue : Color.red;

        // Cache-then-compare: skip SetActive/SetColor if state unchanged
        if (tsChanged || _cachedPlayerState != playerState)
        {
            statusBar.gameObject.SetActive(seated || (game.isTournamentActive && !game.tournamentEliminated[seatIdx]));
            if (acting)
                statusBar.SetLoadingColor(statusBarColor);
            else
                statusBar.SetColor(statusBarColor);
            _cachedPlayerState = playerState;
        }

        bettingUi.gameObject.SetActive(acting && locallySeated && !physicalBettingEnabled);

        //goChipDisplay.SetActive(seated);

        checkObject.SetActive(locallySeated && bet == 0 && acting && valid && !actionTaken);
        var stack = game.stacks[seatIdx];
        bool canUseBetPile = locallySeated && acting && valid && !actionTaken;
        if (physicalBettingEnabled)
        {
            if (grabbableBetPile != null)
                grabbableBetPile.SetPhysicalGrabbable(
                    CanUsePhysicalCallPile(canUseBetPile));
            if (physicalRaisePile != null)
                physicalRaisePile.SetInteractionEnabled(CanStartPhysicalRaise());
        }
        else
        {
            if (grabbableBetPile != null) grabbableBetPile.SetGrabbable(canUseBetPile && bet > 0);
            if (physicalRaisePile != null) physicalRaisePile.SetInteractionEnabled(false);
        }

        grabbableHand.SetGrabbable(locallySeated && inPlay && !ShouldForceShowHoles());
        goRespawnHandUi.SetActive(locallySeated && inPlay);
        goCardHighlight.SetActive(((game.winnerMask & (1 << seatIdx)) != 0) && !betweenGames && (seated || (game.isTournamentActive && !game.tournamentEliminated[seatIdx])));
        if (rebuyButton != null)
        {
            var idleOrShowdown = ts == HoldemGame.TABLE_IDLE || ts == HoldemGame.TABLE_READY || ts == HoldemGame.TABLE_WINNER;
            var canRebuy = locallySeated
                && idleOrShowdown
                && !game.isTournamentMode
                && game.wasSeated[seatIdx]
                && game.stacks[seatIdx] < game.maxBuyIn;
            if (canRebuy)
            {
                var balanceComponent = OwnerPlayerBalanceComponent();
                int balance = balanceComponent != null ? balanceComponent.GetBalance() : 0;
                canRebuy = balance > game.stacks[seatIdx];
            }
            rebuyButton.SetActive(canRebuy);
            // Visibility changed after the physical interaction refresh above; re-run it so the chip colliders yield.
            if (physicalBettingEnabled && physicalRaisePile != null)
                physicalRaisePile.SetInteractionEnabled(CanStartPhysicalRaise());
        }

        var displayStack = stack;
        if (ts == HoldemGame.TABLE_WINNER)
        {
            displayStack = displayStack - game.seatWinnings[seatIdx];
        }
        // Once the winner screen ends the won pot joins the stack; count and stack it anew, like a dealer would.
        bool winningsJoinStack = winningsPendingMerge && ts != HoldemGame.TABLE_WINNER;
        winningsPendingMerge = ts == HoldemGame.TABLE_WINNER && game.seatWinnings[seatIdx] > 0;

        if (game.isTournamentActive && game.tournamentEliminated[seatIdx])
        {
            stackPile.OverrideText("OUT");
            stackPile.SetTotalChips(0);
            uiJoinLeaveText.text = "Eliminated";
            betPile.SetTotalChips(0);
        }
        else
        {
            // A live physical-chip reservation owns the source pile regardless of whether this
            // client uses UI or physical betting, so every client presents the seat the same way.
            bool reservationOwnsSource = physicalRaisePile != null
                && physicalRaisePile.HasVisualReservationForEpoch(game.epoch);
            if (winningsJoinStack && !reservationOwnsSource) stackPile.ReseedTotal(stack);
            if (acting && (UsesAuthoritativeCallPresentation() || reservationOwnsSource))
            {
                int call = GetPhysicalCallAmount();
                if (!reservationOwnsSource) stackPile.SetTotalChips(Mathf.Max(0, stack - call));
                int displayedBet = IsCallOnly() ? call : bet;
                // The raiser's bet only exceeds the call after committing; viewers learn this
                // from the synced bet before the epoch advances, so keep showing the commit.
                bool committedPendingEpoch = reservationOwnsSource && !IsCallOnly() && bet > call;
                int displayedStack = reservationOwnsSource && !actionTaken && !committedPendingEpoch
                    ? Mathf.Max(0, stack - call - physicalRaisePile._GetRepresentedRaiseValue())
                    : Mathf.Max(0, stack - Mathf.Max(0, displayedBet));
                stackPile.OverrideText(displayedStack.ToString());
                if (!actionTaken)
                {
                    if (committedPendingEpoch)
                    {
                        betPile.SetTotalChips(bet);
                        betPile.OverrideText(GetBetGreaterThanZero());
                    }
                    else
                    {
                        betPile.SetTotalChips(call);
                        if (call > 0) betPile.OverrideText(call.ToString() + " (Call)");
                    }
                }
                else betPile.SetTotalChips(0);
            }
            else if (acting && bet > 0)
            {
                var left = stack - bet;
                stackPile.SetTotalChips(left);
                if (!actionTaken)
                {
                    betPile.SetTotalChips(bet);
                    betPile.OverrideText(GetBetGreaterThanZero());
                }
                else
                {
                    betPile.SetTotalChips(0);
                }
            }
            else
            {
                if (!reservationOwnsSource) stackPile.SetTotalChips(displayStack);
                if (stack > 0)
                {
                    int idleDisplayedStack = reservationOwnsSource
                        ? Mathf.Max(0, stack - GetPhysicalCallAmount() - physicalRaisePile._GetRepresentedRaiseValue())
                        : stack;
                    stackPile.OverrideText($"{idleDisplayedStack}");
                }
                else
                {
                    stackPile.OverrideText("");
                }
                betPile.SetTotalChips(0);
            }
        }

        if (!acting)
        {
            statusBar.SetProgress(1f);
        }

        _seated = seated;
        _locallySeated = locallySeated;
        _playerState = playerState;
        _acting = acting;
        _stack = stack;
        _statusBarColor = statusBarColor;
    }

    private string GetBetGreaterThanZero()
    {
        var totalBet = game.roundContribution[seatIdx] + bet;
        if (bet == game.stacks[seatIdx])
        {
            return bet.ToString() + " (All-in)";
        }
        if (game.currentBet == totalBet)
        {
            return bet.ToString() + " (Call)";
        } else if (totalBet > game.currentBet)
        {
            int minBetToRaise = MinRaiseBet();
            if (bet < minBetToRaise)
            {
                return bet.ToString() + " (+" + (minBetToRaise - bet).ToString() + " to min-raise)";
            } else
            {
                return bet.ToString() + " (Raise)";
            }
        } else
        {
            return bet.ToString() + " (+" + (game.currentBet - totalBet).ToString() + " to call)";
        }
    }


    private bool physicalBettingEnabled;
    private bool physicalRaiseActionActive;
    private bool actionTaken = false;

    // Seat actions come from this player's own UI; the same events sent over the network are ignored
    private bool IsLocalSeatAction()
    {
        return !NetworkCalling.InNetworkCall && isLocallySeated();
    }

    public void _UiConfirmImmediately()
    {
        if (!IsLocalSeatAction()) return;

        committedEpoch = game.epoch;
        actionTaken = true;
        RequestSerialization();
    }

    public void _UiFoldImmediately()
    {
        if (!IsLocalSeatAction()) return;
        bet = -1;
        _UiConfirmImmediately();
    }

    public void _UiBetClear() { AdjustBet(-bet); }
    public void _UiBetD1000() { AdjustBet(-1000); }
    public void _UiBetD100() { AdjustBet(-100); }
    public void _UiBetD10() { AdjustBet(-10); }
    public void _UiBetP10() { AdjustBet(10); }
    public void _UiBetP100() { AdjustBet(100); }
    public void _UiBetP1000() { AdjustBet(1000); }

    public void _UiBetP5() { AdjustBet(5); }
    public void _UiBetP25() { AdjustBet(25); }
    public void _UiBetP500() { AdjustBet(500); }
    public void _UiBetP2500() { AdjustBet(2500); }

    private bool IsCallOnly()
    {
        return ((game.callOnlyMask >> seatIdx) & 1) != 0;
    }

    private bool UsesAuthoritativeCallPresentation()
    {
        return physicalBettingEnabled || IsCallOnly();
    }

private bool CanUsePhysicalCallPile(bool canUseBetPile)
    {
        return canUseBetPile && GetPhysicalCallAmount() > 0;
    }

    private int CallAmount()
    {
        return Mathf.Min(game.currentBet - game.roundContribution[seatIdx], game.stacks[seatIdx]);
    }

    private int MinRaiseBet()
    {
        return game.currentBet + game.minimumRaise - game.roundContribution[seatIdx];
    }

    public void _UiBetMinRaise()
    {
        if (!IsLocalSeatAction()) return;
        if (IsCallOnly())
        {
            bet = CallAmount();
            RequestSerialization();
            return;
        }
        int minBetToRaise = MinRaiseBet();
        bet = Mathf.Min(minBetToRaise, game.stacks[seatIdx]);
        RequestSerialization();
    }

    public void _UiBetCall()
    {
        if (!IsLocalSeatAction()) return;
        bet = CallAmount();
        RequestSerialization();
    }

    private void AdjustBet(int delta)
    {
        if (!IsLocalSeatAction()) return;
        int newBet = Mathf.Min(Mathf.Max(0, bet + delta), game.stacks[seatIdx]);

        if (IsCallOnly())
        {
            bet = Mathf.Min(newBet, CallAmount());
            RequestSerialization();
            return;
        }
        
        if (delta > 0 && newBet > 0)
        {
            int minBetToRaise = MinRaiseBet();
            if (newBet < minBetToRaise)
            {
                newBet = Mathf.Min(minBetToRaise, game.stacks[seatIdx]);
            }
        }
        
        bet = newBet;
        RequestSerialization();
    }

    override public void OnDeserialization()
    {
        ActivePlayerBalanceComponent = null;
        if (activePlayerId != -1)
        {
            ActivePlayerBalanceComponent = PlayerBalanceComponent.GetPlayerBalanceComponent(VRCPlayerApi.GetPlayerById(activePlayerId));
        }
        
        if (game != null)
        {
            if (physicalRaisePile != null) physicalRaisePile.OnPlayerStateDeserialized(game.epoch);
            game.seatChangeVersion++;
            if (Networking.IsOwner(game.gameObject))
            {
                Debug.Log("[HoldemPlayer] OnDeserialization");
                game._RequestTransition();
            }
        }
    }

    public void _UiRebuy()
    {
        if (!IsLocalSeatAction()) return;
        if (game.isTournamentMode) return;
        
        int currentStack = game.stacks[seatIdx];
        if (currentStack >= game.maxBuyIn) return;
        
        var balanceComponent = OwnerPlayerBalanceComponent();
        if (balanceComponent == null) return;
        
        int balance = balanceComponent.GetBalance();
        if (balance <= 0) return;
        
        int targetStack = Mathf.Min(balance, game.maxBuyIn);
        int rebuyAmount = targetStack - currentStack;
        if (rebuyAmount <= 0) return;
        
        rebuyVersion++;
        RequestSerialization();
    }


public void SetPhysicalBettingEnabled(bool enabled)
    {
        if (physicalBettingEnabled == enabled) return;

        if (physicalRaisePile != null) physicalRaisePile.SetLocalPhysicalMode(enabled);
        // Only an uncommitted turn of the local seat is affected by the mode; this is false when not acting.
        bool liveTurn = IsLiveLocalTurn();
        if (!enabled && liveTurn) _ResetPhysicalBetToCall();
        physicalBettingEnabled = enabled;
        if (enabled && liveTurn)
        {
            // Start from a plain call like a fresh turn; a leftover legacy raise would compound with dragged chips.
            _ResetPhysicalBetToCall();
            if (bettingUi != null) bettingUi.HideBettingControls();
        }
        else if (!enabled && liveTurn && !IsCallOnly() && bettingUi != null)
        {
            // The legacy buttons are only built at the turn-start edge, which already ran in physical mode.
            bettingUi.AdjustButtons(game.stacks[seatIdx]);
        }
        if (grabbableBetPile != null) grabbableBetPile.SetPhysicalBettingEnabled(enabled);
        _uiDirty = true;
    }

    // The local seat is acting and has not committed yet, whichever betting mode is on.
    private bool IsLiveLocalTurn()
    {
        return !NetworkCalling.InNetworkCall && isLocallySeated()
            && game != null && game.playerState != null && seatIdx >= 0
            && seatIdx < game.playerState.Length
            && game.playerState[seatIdx] == HoldemGame.PLAYER_ACTING && !actionTaken;
    }

    public bool CanUsePhysicalBetting()
    {
        return physicalBettingEnabled && IsLiveLocalTurn();
    }

    public bool CanStartPhysicalRaise()
    {
        return CanUsePhysicalBetting() && !IsCallOnly() && game.stacks != null
            && seatIdx < game.stacks.Length && game.stacks[seatIdx] > 0;
    }

    public bool CanHandlePhysicalChips()
    {
        // The chip colliders sit in front of the buy-in button; release them while it is offered.
        if (rebuyButton != null && rebuyButton.activeSelf) return false;
        return physicalBettingEnabled && !NetworkCalling.InNetworkCall && isLocallySeated()
            && game != null && game.stacks != null && seatIdx >= 0 && seatIdx < game.stacks.Length
            && game.stacks[seatIdx] > 0;
    }

    public int GetPhysicalCallAmount()
    {
        return Mathf.Max(0, CallAmount());
    }

    public int GetPhysicalMinimumRaiseBet()
    {
        return Mathf.Max(0, MinRaiseBet());
    }

    public int GetPhysicalStackValue()
    {
        if (game == null || game.stacks == null || seatIdx < 0 || seatIdx >= game.stacks.Length) return 0;
        return Mathf.Max(0, game.stacks[seatIdx]);
    }

    public int GetPhysicalSourceBaselineValue()
    {
        return Mathf.Max(0, GetPhysicalStackValue() - GetPhysicalCallAmount());
    }

    public int PreviewPhysicalRaise(int selectedAmount)
    {
        if (game == null || game.stacks == null || seatIdx < 0 || seatIdx >= game.stacks.Length) return 0;
        int stack = Mathf.Max(0, game.stacks[seatIdx]);
        int call = GetPhysicalCallAmount();
        if (IsCallOnly()) return Mathf.Min(call, stack);

        int minimumRaiseBet = GetPhysicalMinimumRaiseBet();
        if (stack <= minimumRaiseBet) return stack;
        return Mathf.Clamp(Mathf.Max(call + Mathf.Max(0, selectedAmount), minimumRaiseBet), 0, stack);
    }

    public int PreviewPhysicalIncrease(int selectedAmount)
    {
        if (game == null || game.stacks == null || seatIdx < 0 || seatIdx >= game.stacks.Length) return 0;
        int stack = Mathf.Max(0, game.stacks[seatIdx]);
        if (IsCallOnly()) return Mathf.Min(GetPhysicalCallAmount(), stack);
        return Mathf.Clamp(bet + Mathf.Max(0, selectedAmount), 0, stack);
    }

    public bool ApplyPhysicalRaise(int raiseValue)
    {
        if (!CanUsePhysicalBetting() || IsCallOnly()) return false;
        int call = GetPhysicalCallAmount();
        int stack = GetPhysicalStackValue();
        int target = call + Mathf.Max(0, raiseValue);
        int minimum = GetPhysicalMinimumRaiseBet();
        if (target > stack || (target < minimum && target != stack)) return false;
        SetPhysicalBet(target);
        return bet == target;
    }

    public bool ApplyPhysicalIncrease(int selectedAmount)
    {
        if (!CanUsePhysicalBetting() || IsCallOnly() || selectedAmount <= 0) return false;
        int target = bet + selectedAmount;
        if (target > GetPhysicalStackValue()) return false;
        SetPhysicalBet(target);
        return bet == target;
    }

    public void _ResetPhysicalBetToCall()
    {
        if (!CanUsePhysicalBetting()) return;
        SetPhysicalBet(GetPhysicalCallAmount());
    }

    public bool _CommitPhysicalBet()
    {
        if (!CanUsePhysicalBetting() || !game.IsValidBet(bet, seatIdx)) return false;
        committedEpoch = game.epoch;
        actionTaken = true;
        RequestSerialization();
        _uiDirty = true;
        return true;
    }

    private void SetPhysicalBet(int value)
    {
        if (bet == value) return;
        bet = value;
        RequestSerialization();
        _uiDirty = true;
    }

    public void SetPhysicalCallActionActive(bool active)
    {
        if (physicalRaisePile != null) physicalRaisePile.SetCallActionActive(active);
    }

public void SetPhysicalRaiseActionActive(bool active)
    {
        physicalRaiseActionActive = active;
        if (grabbableBetPile != null) grabbableBetPile.SetPhysicalGrabbable(
            CanUsePhysicalBetting() && GetPhysicalCallAmount() > 0
            && Networking.LocalPlayer != null && Networking.LocalPlayer.IsUserInVR());
    }
}
