﻿//#define HOLDEM_PROFILE

using UdonSharp;
using UnityEngine;
using VRC.SDKBase;
using VRC.Udon;
using VRC.SDK3.Persistence;
using System;
using TMPro;
using VRC.Udon.Common;

/// <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 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;

    void Start()
    {
    }

    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);
    }

    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;
    }

    public void ToggleControl()
    {
        if (isLocallySeated()) { 
            ReleaseControl(); 
        } else
        {
            TakeControl();
        }
    }

    public void TakeControl()
    {
        if (IsSeated()) return; // can't take over

        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 == TABLE_PLAYING || game.tableState == 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;
        }
        
        // 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;

    public const int
        TABLE_UNINITIALIZED = 0,
        TABLE_IDLE = 1,
        TABLE_READY = 2,
        TABLE_PLAYING = 3,
        TABLE_WINNER = 5
        ;

     public const int
        PLAYER_DEAD = 0,
        PLAYER_PENDING = 1,
        PLAYER_ACTING = 2,
        PLAYER_COMMITED = 3;

    public const int
        NOT_PLAYING = 0, PREFLOP = 1, FLOP = 2, TURN = 3, RIVER = 4, SHOWDOWN = 5;

    // 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 != PLAYER_DEAD;
        var winner = game.tableState == TABLE_WINNER;
        bool showdown = false;
        if (winner)
        {
            int challengers = 0;
            for (int i = 0; i < game.seats; ++i)
            {
                if (game.playerState[i] == PLAYER_COMMITED) challengers++;
            }
            if (challengers > 1) showdown = true;
        }
        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 != PLAYER_DEAD;
        var winner = game.tableState == TABLE_WINNER;
        bool showdown = false;
        if (winner)
        {
            int challengers = 0;
            for (int i = 0; i < game.seats; ++i)
            {
                if (game.playerState[i] == PLAYER_COMMITED) challengers++;
            }
            if (challengers > 1) showdown = true;
        }
        var forceShow = inPlay && showdown && (game.aggressorSeat == seatIdx || (game.winnerMask & (1 << seatIdx)) != 0 || grabbableHand.isVisibleToOthers);
        return forceShow;
    }

    // Updates grabbable hand cards
    public void UpdateCardDisplay()
    {
        if (CanShowHoles() || grabbableHand.isVisibleToOthers)
        {
            grabbableHand.SetCards(game.holeCards0[seatIdx], game.holeCards1[seatIdx]);
            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;
        }
    }

    private int previousRemaining = 0;

    // Dirty-flag caches: skip redundant UI calls when state hasn't changed.
    private int _cachedTs = -1;
    private int _cachedPlayerState = -1;
    private string _cachedButtonState = null; // "leave"|"occupied"|"rejoin"|"elim"|"tourney-name"|"hidden-other"|"join"
    // Expensive preamble cache: IsSeatedAnywhere() loops 10 seats, each calling Networking API
    private bool _cachedSeatedAnywhere;
    private int _cachedSeatedAnywhereEpoch = -1;
    private int _cachedSeatChangeVersion = -1;

    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
        if (game.tableState == TABLE_UNINITIALIZED) return;

#if HOLDEM_PROFILE
        game.profiler.Begin("Player.Update");
        game.profiler.Begin("Player.Preamble");
#endif
        // 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;

#if HOLDEM_PROFILE
        game.profiler.End(); // Player.Preamble
#endif

        int ts = game.tableState;
        bool tsChanged = ts != _cachedTs;
        _cachedTs = ts;

#if HOLDEM_PROFILE
        game.profiler.Begin("Player.UI Button State");
#endif
        if (locallySeated)
        {
            if (tsChanged || _cachedButtonState != "leave")
            {
                uiJoinLeaveButton.DisableInteractive = false;
                uiJoinLeaveButton.secondsToHold = 1f;
                uiJoinLeaveText.text = "Leave (hold)";
                _cachedButtonState = "leave";
            }
        }
        else if (seated)
        {
            if (tsChanged || _cachedButtonState != "occupied")
            {
                uiJoinLeaveButton.DisableInteractive = true;
                uiJoinLeaveButton.StopHolding();
                uiJoinLeaveText.text = OwnerName();
                uiJoinLeaveButton.gameObject.SetActive(true);
                _cachedButtonState = "occupied";
            }
        }
        else if (game.isTournamentActive)
        {
            string localPlayerName = (Networking.LocalPlayer == null) ? "(Editor)" : Networking.LocalPlayer.displayName;
            bool isMyTournamentSeat = game.tournamentPlayerNames[seatIdx] == localPlayerName;
            if (isMyTournamentSeat && !game.tournamentEliminated[seatIdx])
            {
                if (tsChanged || _cachedButtonState != "rejoin")
                {
                    uiJoinLeaveButton.gameObject.SetActive(true);
                    uiJoinLeaveButton.DisableInteractive = false;
                    uiJoinLeaveButton.secondsToHold = 0f;
                    uiJoinLeaveText.text = "Rejoin";
                    _cachedButtonState = "rejoin";
                }
            }
            else
            {
                if (game.tournamentEliminated[seatIdx])
                {
                    if (tsChanged || _cachedButtonState != "elim")
                    {
                        uiJoinLeaveButton.StopHolding();
                        uiJoinLeaveButton.gameObject.SetActive(false);
                        uiJoinLeaveText.text = "Eliminated";
                        _cachedButtonState = "elim";
                    }
                }
                else
                {
                    if (tsChanged || _cachedButtonState != "tourney-name")
                    {
                        uiJoinLeaveButton.StopHolding();
                        uiJoinLeaveButton.gameObject.SetActive(false);
                        uiJoinLeaveText.text = game.tournamentPlayerNames[seatIdx];
                        _cachedButtonState = "tourney-name";
                    }
                }
            }
        }
        else if (seatedAnywhere)
        {
            if (tsChanged || _cachedButtonState != "hidden-other")
            {
                uiJoinLeaveButton.StopHolding();
                uiJoinLeaveButton.gameObject.SetActive(false);
                _cachedButtonState = "hidden-other";
            }
        }
        else
        {
            if (tsChanged || _cachedButtonState != "join")
            {
                uiJoinLeaveButton.gameObject.SetActive(true);
                uiJoinLeaveButton.DisableInteractive = false;
                uiJoinLeaveButton.secondsToHold = 0f;
                uiJoinLeaveText.text = "Join";
                _cachedButtonState = "join";
            }
        }
#if HOLDEM_PROFILE
        game.profiler.End(); // Player.UI Button State
#endif

#if HOLDEM_PROFILE
        game.profiler.Begin("Player.Mid-Logic");
#endif
        var betweenGames = ts == TABLE_IDLE || ts == TABLE_READY;

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

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

        var winner = ts == TABLE_WINNER;

#if HOLDEM_PROFILE
        game.profiler.Begin("Player.CanShowHoles");
#endif
        var holes = CanShowHoles();
#if HOLDEM_PROFILE
        game.profiler.End(); // Player.CanShowHoles
        game.profiler.Begin("Player.Mid-Glue");
#endif
        uiBestHand.enabled = holes && game.bettingRound >= FLOP;

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

        Color statusBarColor = playerState == PLAYER_DEAD ? Color.black :
            playerState == PLAYER_PENDING ? Color.white :
            playerState == PLAYER_ACTING ? Color.green :
            playerState == PLAYER_COMMITED ? Color.blue : Color.red;
#if HOLDEM_PROFILE
        game.profiler.End(); // Player.Mid-Glue
        game.profiler.End(); // Player.Mid-Logic
#endif

#if HOLDEM_PROFILE
        game.profiler.Begin("Player.Status Bar");
#endif
        // 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;
        }
#if HOLDEM_PROFILE
        game.profiler.End(); // Player.Status Bar
#endif

#if HOLDEM_PROFILE
        game.profiler.Begin("Player.Betting UI State");
#endif
        bettingUi.gameObject.SetActive(acting && locallySeated);

        //goChipDisplay.SetActive(seated);

        checkObject.SetActive(locallySeated && bet == 0 && acting && valid && !actionTaken);
        grabbableBetPile.SetGrabbable(locallySeated && bet > 0 && acting && valid && !actionTaken);

        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 == TABLE_IDLE || ts == TABLE_READY || ts == 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);
        }
#if HOLDEM_PROFILE
        game.profiler.End(); // Player.Betting UI State
#endif

#if HOLDEM_PROFILE
        game.profiler.Begin("Player.Stack Display");
#endif
#if HOLDEM_PROFILE
        game.profiler.Begin("Player.Stack Setup");
#endif
        var stack = game.stacks[seatIdx];

        var displayStack = stack;
        if (ts == TABLE_WINNER)
        {
#if HOLDEM_PROFILE
            game.profiler.Begin("Player.Stack GetWinnings");
#endif
            displayStack = displayStack - game.getWinningsForPlayerIdx(seatIdx);
#if HOLDEM_PROFILE
            game.profiler.End(); // Player.Stack GetWinnings
#endif
        }
#if HOLDEM_PROFILE
        game.profiler.End(); // Player.Stack Setup
#endif

        if (game.isTournamentActive && game.tournamentEliminated[seatIdx])
        {
#if HOLDEM_PROFILE
            game.profiler.Begin("Player.Stack Eliminated");
#endif
            stackPile.OverrideText("OUT");
            stackPile.SetTotalChips(0);
            uiJoinLeaveText.text = "Eliminated";
            betPile.SetTotalChips(0);
#if HOLDEM_PROFILE
            game.profiler.End(); // Player.Stack Eliminated
#endif
        }
        else
        {
            if (acting && bet > 0)
            {
#if HOLDEM_PROFILE
                game.profiler.Begin("Player.Stack ActingBet");
#endif
                var left = stack - bet;
                stackPile.SetTotalChips(left);
                if (!actionTaken)
                {
                    betPile.SetTotalChips(bet);
#if HOLDEM_PROFILE
                    game.profiler.Begin("Player.Stack BetText");
#endif
                    betPile.OverrideText(GetBetGreaterThanZero());
#if HOLDEM_PROFILE
                    game.profiler.End(); // Player.Stack BetText
#endif
                }
                else
                { 
                    betPile.SetTotalChips(0);
                }
#if HOLDEM_PROFILE
                game.profiler.End(); // Player.Stack ActingBet
#endif
            }
            else
            {
#if HOLDEM_PROFILE
                game.profiler.Begin("Player.Stack Normal");
#endif
                stackPile.SetTotalChips(displayStack);
                if (stack > 0)
                {
                    stackPile.OverrideText($"{stack}");
                }
                else
                {
                    stackPile.OverrideText("");
                }
                betPile.SetTotalChips(0);
#if HOLDEM_PROFILE
                game.profiler.End(); // Player.Stack Normal
#endif
            }
        }
#if HOLDEM_PROFILE
        game.profiler.End(); // Player.Stack Display
#endif

#if HOLDEM_PROFILE
        game.profiler.Begin("Player.Timeout & Progress");
#endif
        if (acting)
        {
#if HOLDEM_PROFILE
            game.profiler.Begin("Player.Timeout GetTime");
#endif
            var now = Networking.LocalPlayer == null ? (int)(Time.time * 1000) : Networking.GetServerTimeInMilliseconds();
            var timeout = game.lastTransitionMillis;
            var remaining = game.actionTimeoutSecs - (now - timeout) / 1000;
            float remainingFloat = ((float) game.actionTimeoutSecs) - (((float) now) - ((float) timeout)) / 1000;
            float remainingPercentage = remainingFloat / ((float) game.actionTimeoutSecs);
            if (remainingPercentage < 0f) remainingPercentage = 0f;
#if HOLDEM_PROFILE
            game.profiler.End(); // Player.Timeout GetTime
            game.profiler.Begin("Player.Timeout SetProgress");
#endif
            statusBar.SetProgress(remainingPercentage);
#if HOLDEM_PROFILE
            game.profiler.End(); // Player.Timeout SetProgress
#endif

            if (previousRemaining > remaining && remaining <= 10 && locallySeated)
            {
#if HOLDEM_PROFILE
                game.profiler.Begin("Player.Timeout TickTock");
#endif
                tickTockPlayer.Play();
#if HOLDEM_PROFILE
                game.profiler.End(); // Player.Timeout TickTock
#endif
            }

            previousRemaining = remaining;
        }
        else
        {
            statusBar.SetProgress(1f);
        }
#if HOLDEM_PROFILE
        game.profiler.End(); // Player.Timeout & Progress
#endif

        // check if the hand is in the fold area, and its owned by the local player.
#if HOLDEM_PROFILE
        game.profiler.Begin("Player.Fold Check");
#endif
#if HOLDEM_PROFILE
        game.profiler.Begin("Player.Fold IsFolded");
#endif
        bool folded = locallySeated && acting && grabbableHand.IsFolded();
#if HOLDEM_PROFILE
        game.profiler.End(); // Player.Fold IsFolded
#endif
        if (folded)
        {
#if HOLDEM_PROFILE
            game.profiler.Begin("Player.Fold UiFold");
#endif
            UiFoldImmediately();
            grabbableHand.SetGrabbable(false);
#if HOLDEM_PROFILE
            game.profiler.End(); // Player.Fold UiFold
#endif
        }
#if HOLDEM_PROFILE
        game.profiler.End(); // Player.Fold Check
#endif

        // transition check
#if HOLDEM_PROFILE
        game.profiler.Begin("Player.Epoch Check");
#endif
        if (updateSeenEpoch != game.epoch)
        {
            updateSeenEpoch = game.epoch;
#if HOLDEM_PROFILE
            game.profiler.Begin("Player.Epoch Body");
#endif
            // edge-triggered
            if (locallySeated)
            {
                if (acting)
                {
                    if (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;
                } else
                {
                    // once it comes around to us again, make sure we aren't
                    // accidentally already commited from the past
                    bet = 0;
                    committedEpoch = -1;
                    RequestSerialization();
                }
            }

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

            if (ts == TABLE_PLAYING) {
                if (game.bettingRound == PREFLOP && playerState != PLAYER_DEAD) grabbableHand.SetEnabled(seated);
                UpdateCardDisplay();

                var bestHand =
                    game.bettingRound == RIVER ? game.BestPlayerHandSeat(seatIdx) :
                    game.bettingRound == TURN ? game.BestPlayerHandTurnSeat(seatIdx) :
                    game.bettingRound == FLOP ? game.BestPlayerHandFlop(seatIdx) : 0;
                if (bestHand > 0UL && game.GetHandClassInt(bestHand) > 0)
                {
                    uiBestHand.text = game.HandClass(bestHand).ToString();
                } else
                {
                    uiBestHand.text = "";
                }
            }

            if (ts == TABLE_WINNER)
            {
                UpdateCardDisplay();
            }

            if (ts == 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())
            {
                Debug.Log("Playing cue sound");
                attentionCuePlayer.Play();
            }
#if HOLDEM_PROFILE
            game.profiler.End(); // Player.Epoch Body
#endif
        }
#if HOLDEM_PROFILE
        game.profiler.End(); // Player.Epoch Check
        game.profiler.End(); // Player.Update
#endif
    }

    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 = game.currentBet + game.minimumRaise - game.roundContribution[seatIdx];
            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 actionTaken = false;

    public void UiConfirmImmediately()
    {
        if (!isLocallySeated()) return;

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

    public void UiFoldImmediately()
    {
        if (!isLocallySeated()) 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 int CallAmount()
    {
        return Mathf.Min(game.currentBet - game.roundContribution[seatIdx], game.stacks[seatIdx]);
    }

    public void UiBetMinRaise()
    {
        if (!isLocallySeated()) return;
        if (IsCallOnly())
        {
            bet = CallAmount();
            RequestSerialization();
            return;
        }
        int minBetToRaise = game.currentBet + game.minimumRaise - game.roundContribution[seatIdx];
        bet = Mathf.Min(minBetToRaise, game.stacks[seatIdx]);
        RequestSerialization();
    }

    public void UiBetCall()
    {
        if (!isLocallySeated()) return;
        bet = CallAmount();
        RequestSerialization();
    }

    private void AdjustBet(int delta)
    {
        if (!isLocallySeated()) 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 = game.currentBet + game.minimumRaise - game.roundContribution[seatIdx];
            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)
        {
            game.seatChangeVersion++;
            if (Networking.IsOwner(game.gameObject))
            {
                Debug.Log("[HoldemPlayer] OnDeserialization");
                game.Transition();
            }
        }
    }

public void UiRebuy()
    {
        if (!isLocallySeated()) 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();
    }

#if HOLDEM_DEBUG
    public void ClaimWelfare()
    {
        if (!isLocallySeated()) return;

        var nowSeconds = (DateTime.UtcNow.Ticks / TimeSpan.TicksPerSecond);
        var lastClaim = PlayerData.GetLong(Networking.LocalPlayer, "HoldemWelfareLastClaim");
        
        const int WELFARE_COOLDOWN_SECONDS = 15 * 60;
        if (nowSeconds - lastClaim < WELFARE_COOLDOWN_SECONDS) return;
 
        var amount = 100;
        PlayerBalanceComponent.ModifyBalance(Networking.LocalPlayer, amount);
        PlayerData.SetLong("HoldemWelfareLastClaim", nowSeconds);
    }
#endif
}