using UdonSharp;
using UnityEngine;
using VRC.SDKBase;

// Per-frame presentation logic
[UdonBehaviourSyncMode(BehaviourSyncMode.None)]
public class HoldemPresentation : UdonSharpBehaviour
{
    // Plays the deal/flip sounds and reveals community cards as bettingRound advances
    public static void HandleBettingRoundReveal(HoldemGame game, int flop0, int flop1, int flop2, int turn, int river)
    {
        if (game.bettingRound == game.lastBettingRound) return;

        int oldRound = game.lastBettingRound;
        game.lastBettingRound = game.bettingRound;

        if (game.bettingRound == HoldemGame.PREFLOP)
        {
            game.dingPlayer.Play();
        }

        if (game.bettingRound == HoldemGame.FLOP || game.bettingRound == HoldemGame.TURN || game.bettingRound == HoldemGame.RIVER)
        {
            game.cardFlipPlayer.Play();
        }

        bool revealFlop = game.bettingRound >= HoldemGame.FLOP && oldRound < HoldemGame.FLOP;
        bool revealTurn = game.bettingRound >= HoldemGame.TURN && oldRound < HoldemGame.TURN;
        bool revealRiver = game.bettingRound >= HoldemGame.RIVER && oldRound < HoldemGame.RIVER;

        if (game.cardFlipController != null)
        {
            if (revealFlop) game.cardFlipController.RevealFlop(flop0, flop1, flop2);
            if (revealTurn) game.cardFlipController.RevealTurn(turn);
            if (revealRiver) game.cardFlipController.RevealRiver(river);
        }
        if (game.tableCardFlipController != null)
        {
            if (revealFlop) game.tableCardFlipController.RevealFlop(flop0, flop1, flop2);
            if (revealTurn) game.tableCardFlipController.RevealTurn(turn);
            if (revealRiver) game.tableCardFlipController.RevealRiver(river);
        }
    }

    // Plays deal/victory animations and hides/reveals hands as tableState advances.
    public static void HandleTableStateTransition(HoldemGame game)
    {
        if (game.tableState == game.lastTableState) return;

        // A non-owner can miss the short IDLE between hands (updates coalesce, or a frame hitch) and see
        // WINNER -> READY/PLAYING directly, so leaving WINNER must clean up just like entering IDLE.
        bool leftWinner = game.lastTableState == HoldemGame.TABLE_WINNER && game.tableState != HoldemGame.TABLE_WINNER;
        game.lastTableState = game.tableState;
        if (game.tableState == HoldemGame.TABLE_IDLE || leftWinner)
        {
            // Hide community cards (covers non-owner clients who receive state via serialisation
            // rather than running Transition directly).
            if (game.cardFlipController != null) game.cardFlipController.ResetAllCards();
            if (game.tableCardFlipController != null) game.tableCardFlipController.ResetAllCards();
            // Return to idle animation on all player cards
            for (int i = 0; i < game.seats; i++)
            {
                if (game.players[i] != null && game.players[i].grabbableHand != null)
                {
                    game.players[i].grabbableHand._ReturnToIdleAnimation();
                }
            }
            game._MarkHighlightsDirty();
        }
        if (game.tableState == HoldemGame.TABLE_PLAYING)
        {
            // Play deal animation on active hands. Index starts at 0 for actingSeat
            // (first to act in preflop) and increments for subsequent active players.
            int dealIndex = 0;
            for (int i = 0; i < game.seats; i++)
            {
                int seat = (game.actingSeat + i) % game.seats;
                if (game.playerState[seat] != HoldemGame.PLAYER_DEAD)
                {
                    if (game.players[seat] != null && game.players[seat].grabbableHand != null)
                    {
                        game.players[seat].grabbableHand.DealCards(dealIndex);
                    }
                    dealIndex++;
                }
            }
        }

        if (game.tableState == HoldemGame.TABLE_WINNER)
        {
            game.victoryPlayer.Play();
        }
        game._ApplyShowdownPresentation();
    }

    // Toggles the debug panel and tournament-lobby GameObject visibility when local ownership
    // changes (or every frame under HOLDEM_DEBUG).
    public static void UpdateOwnerVisibility(HoldemGame game, bool isOwner)
    {
#if HOLDEM_DEBUG
        game.uiDebugToggleText.text = $"Enable Debug (Master: {game.OwnerName(game.gameObject)})";

        // Sync toggle button visibility
        if (game.uiDebugToggle != null && game.uiDebugToggle.gameObject.activeSelf != isOwner)
        {
            game.uiDebugToggle.gameObject.SetActive(isOwner);
        }
#endif

        bool ownerChanged = !game.uiOwnerKnown || game.uiOwner != isOwner;
#if HOLDEM_DEBUG
        ownerChanged = true;
#endif
        if (!ownerChanged) return;

        game.uiOwnerKnown = true;
        game.uiOwner = isOwner;

        if (game.goDebug != null)
        {
            if (isOwner)
            {
                if (!game.goDebug.activeSelf)
                {
                    game.goDebug.SetActive(true);
                }

#if HOLDEM_DEBUG
                // Toggle MasterDebug panel based on toggle status
                Transform masterDebug = game.goDebug.transform.Find("MasterDebug");
                if (masterDebug != null && masterDebug.gameObject.activeSelf != game.uiDebugToggle.isOn)
                {
                    masterDebug.gameObject.SetActive(game.uiDebugToggle.isOn);
                }

                // The Log and DebugToggleText should be active
                Transform logTrans = game.goDebug.transform.Find("Log");
                if (logTrans != null && !logTrans.gameObject.activeSelf)
                {
                    logTrans.gameObject.SetActive(true);
                }
                if (game.uiDebugToggleText != null && !game.uiDebugToggleText.gameObject.activeSelf)
                {
                    game.uiDebugToggleText.gameObject.SetActive(true);
                }
#endif
            }
            else
            {
                if (game.goDebug.activeSelf)
                {
                    game.goDebug.SetActive(false);
                }
            }
        }

        if (game.tournamentGameObject != null)
        {
            game.tournamentGameObject.SetActive(isOwner);
        }
    }

    // Builds the winner-announcement text once per epoch change (hand resolution / reset to
    // idle-or-ready). flop0-4 are passed explicitly for the same reason as HandleBettingRoundReveal.
    public static void HandleEpochChange(HoldemGame game, int now, int flop0, int flop1, int flop2, int turn, int river)
    {
        game.lastLocalEpoch = game.epoch;
#if HOLDEM_DEBUG
        if (!Networking.IsOwner(game.gameObject))
        {
            string s =
                $"new state: now {now} epoch {game.epoch} state {game.tableState} bettingRound {game.bettingRound} headsUp {game.headsUp}\n" +
                $"dealer {game.dealerSeat} acting {game.actingSeat}\n" +
                $"bb {game.bigBlind} minRaise {game.minimumRaise} currentBet {game.currentBet} callOnly {game.callOnlyMask}\n" +
                $"last transition {game.lastTransitionMillis} elapsed {now - game.lastTransitionMillis}\n" +
                $"playerState [{game.JoinIntArray(game.playerState)}]\n" +
                $"stacks [{game.JoinIntArray(game.stacks)}]\n" +
                $"potCon [{game.JoinIntArray(game.potContribution)}]\n" +
                $"roundCon [{game.JoinIntArray(game.roundContribution)}]\n" +
                $"";
            Debug.Log("[Holdem] " + s);
        }
#endif
        // edge-triggered stuff
        if (game.tableState == HoldemGame.TABLE_WINNER)
        {
            game.winnerText = "";
            // Shares come from the dealer; winners' cards are revealed, so their hands can be named
            game.seatWinnings = new int[HoldemGame.MAX_SEATS];
            for (int i = 0; i < game.seats; i++) game.seatWinnings[i] = game.seatWinningsSynced[i];
            ulong[] handValues = game.wonByFold ? null : HoldemHandEvaluator.GetHandValues(
                game.seats, game.playerState, game.holeCards0, game.holeCards1, flop0, flop1, flop2, turn, river);
            for (int i = 0; i < game.seats; ++i)
            {
                if (game.playerState[i] != HoldemGame.PLAYER_DEAD && game.seatWinnings[i] > 0)
                {
                    game.winnerText += $"{game.players[i].OwnerName()} wins {game.seatWinnings[i]}";
                    if (!game.wonByFold)
                    {
                        game.winnerText += $" with {HoldemHandEvaluator.HandClass(handValues[i])}";
                    }
                    game.winnerText += "\n";
                }
            }
            Debug.Log("[Holdem] " + game.winnerText);
        }

        if (game.tableState == HoldemGame.TABLE_IDLE || game.tableState == HoldemGame.TABLE_READY)
        {
            game.seatWinnings = new int[HoldemGame.MAX_SEATS];
        }
    }

    // Rebuilds the status/pot/round text and per-seat chip-pile visuals. Only called when the
    // UI change-detection gate in Update() determined something actually changed.
    public static void RefreshUI(HoldemGame game, int since, int levelSeconds, bool stateChanged)
    {
        int readyAndStacked = 0;
        int seated = 0;
        int pending = 0;
        int commited = 0;
        int inPlay = 0;
        for (int i = 0; i < game.seats; ++i)
        {
            bool isSeated = game.players[i].IsSeated();
            if (isSeated || (game.isTournamentActive && !game.tournamentEliminated[i]))
            {
                if (isSeated) seated++;

                bool isPlayerActiveInTournament = game.isTournamentActive && !game.tournamentEliminated[i] && game.stacks[i] > 0;
                bool isPlayerReadyForCash = !game.isTournamentActive && game.players[i].playerReady && game.stacks[i] >= game.bigBlind;

                if (isPlayerActiveInTournament || isPlayerReadyForCash) readyAndStacked++;
                if (game.playerState[i] != HoldemGame.PLAYER_DEAD) inPlay++;
                if (game.playerState[i] == HoldemGame.PLAYER_PENDING) pending++;
                if (game.playerState[i] == HoldemGame.PLAYER_COMMITED) commited++;
            }
        }

        if (game.isTournamentActive)
        {
            int levelRemainingSeconds = Mathf.Max(0, (int)(game.tournamentLevelDurationSeconds - levelSeconds));
            string timeStr = $"{levelRemainingSeconds / 60}m {levelRemainingSeconds % 60}s";
            int remainingPlayers = 0;
            int totalParts = 0;
            for (int i = 0; i < game.seats; i++)
            {
                if (game.playerRanks[i] > 0 || !game.tournamentEliminated[i]) totalParts++;
                if (!game.tournamentEliminated[i]) remainingPlayers++;
            }

            game.uiGameStatus.text = $"[TOURNAMENT] Level {game.currentBlindLevelIndex + 1} (Blinds {game.bigBlind / 2}/{game.bigBlind}) - Next level in {timeStr} - Players: {remainingPlayers}/{totalParts}\n" +
                (game.tableState == HoldemGame.TABLE_PLAYING ? "" :
                game.tableState == HoldemGame.TABLE_READY ? $"Dealing in {game.readyTimeoutSecs - since}s" :
                game.tableState == HoldemGame.TABLE_IDLE ? "Lobby / Pre-Hand" :
                game.winnerText + $"\nNext hand in {game.winnerTimeoutSecs - since}s...");
        }
        else if (game.isTournamentMode && !game.isTournamentActive)
        {
            game.uiGameStatus.text = $"[TOURNAMENT LOBBY] Seated: {seated}\n" +
                $"Buy-in: {game.tournamentBuyIn} | Starting Stack: {game.tournamentStartingStack}\n" +
                $"Waiting for Master to start...";
        }
        else
        {
            game.uiGameStatus.text =
                game.tableState == HoldemGame.TABLE_UNINITIALIZED ? "Uninitialized" :
                game.tableState == HoldemGame.TABLE_IDLE ? $"Idle ({readyAndStacked} players ready)\n" :
                game.tableState == HoldemGame.TABLE_READY ?
                  $"Dealing in {game.readyTimeoutSecs - since}..." :
                game.tableState == HoldemGame.TABLE_PLAYING ? "" :
                game.winnerText + $"\nNext game in {game.winnerTimeoutSecs - since}...";
        }
        int potTotal = 0, roundTotal = 0;
        for (int i = 0; i < game.seats; ++i)
        {
            potTotal += game.potContribution[i];
            roundTotal += game.roundContribution[i];
        }

        game.uiPot.text = $"{potTotal} (+{roundTotal} round)";
        game.uiRoundStatus.text = $"Current Bet: {game.currentBet}\nMin-raise: {game.minimumRaise}";

        if (game.uiTournamentSettingsInfo != null)
        {
            game.uiTournamentSettingsInfo.text = $"Tournament Mode: {(game.isTournamentMode ? "ENABLED" : "DISABLED")}\n" +
                $"Buy-In: {game.tournamentBuyIn} chips\n" +
                $"Starting Stack: {game.tournamentStartingStack} chips\n" +
                $"Status: {(game.isTournamentActive ? "ACTIVE" : "LOBBY")}";
        }
        var dealt = game.tableState == HoldemGame.TABLE_PLAYING || game.tableState == HoldemGame.TABLE_WINNER;
        game.uiPot.enabled = dealt;
        game.uiRoundStatus.enabled = dealt;

        if (!stateChanged || !game._IsChipPresentationModeReady()) return;

        if (game.tableState == HoldemGame.TABLE_PLAYING)
        {
            if (game.animatedChipContainersEnabled)
                PresentPlayingChipsDynamic(game, roundTotal);
            else
                PresentPlayingChipsStatic(game, potTotal);
            return;
        }

        if (game.animatedChipContainersEnabled)
        {
            game._DistributeDynamicPotToWinners();
            return;
        }

        game._DistributeStaticPotToWinners();
        for (int idx = 0; idx < game.seats; idx++)
        {
            if (game.seatWinnings[idx] > 0)
                game.players[idx].MovePotPile(game.potPile.transform);
        }
    }

    public static void PresentPlayingChipsStatic(HoldemGame game, int potTotal)
    {
        // Move chips between piles instead of re-deriving denominations: new bets are added to the round pile
        // as-is, and a closed round's chips are transferred from the round piles into the pot.
        PokerChipPile pot = game.potPile;
        int roundTotal = 0;
        for (int i = 0; i < game.seats; i++) roundTotal += game.roundContribution[i];
        if (roundTotal == 0) game._CollectRoundPilesToPotStatic();
        for (int i = 0; i < game.seats; i++)
        {
            HoldemPlayer player = game.players[i];
            if (player == null) continue;
            PokerChipPile pile = player.roundContributionPile;
            if (pile != null)
            {
                int target = game.roundContribution[i];
                int displayed = pile.GetTotalDisplayedValue();
                if (target > displayed)
                {
                    int[] before = new int[pile.denominationValues.Length];
                    pile.CopyDisplayedDenominationCounts(before);
                    int addedValue = target - displayed;
                    game._TakeBetChipsFromStack(i, pile, addedValue);
                    pile.AnimateChipsAddedSince(before);
                }
                pile.SetTotalChips(target);
            }
            if (player.playerPotPile != null)
                player.playerPotPile.SetTotalChips(0);
        }
        if (pot != null) pot.SetTotalChips(potTotal);
        game._SnapshotPresentedPotContributions();
    }

    public static void PresentPlayingChipsDynamic(HoldemGame game, int roundTotal)
    {
        bool roundClosed = roundTotal == 0 && game.CollectRoundPilesToPot();
        for (int i = 0; i < game.seats; i++)
        {
            HoldemPlayer player = game.players[i];
            if (player == null) continue;
            PokerChipPile pile = player.roundContributionPile;
            if (!roundClosed && pile != null)
            {
                int delta = game.roundContribution[i] - pile.GetTotalDisplayedValue();
                if (delta > 0)
                    game.AnimateNewRoundChips(player, delta, pile.transform.position);
            }
            if (player.playerPotPile != null)
                player.playerPotPile.SetTotalChips(0);
        }
    }
}
