using System.Collections.Generic;
using NUnit.Framework;
using UnityEngine;

public class ChipPresentationPathTests
{
    private readonly List<GameObject> spawned = new List<GameObject>();
    private LocalObjectPool pool;
    private HoldemGame game;
    private HoldemPlayer player;

    [SetUp]
    public void SetUp()
    {
        GameObject poolObject = Spawn("Pool");
        pool = poolObject.AddComponent<LocalObjectPool>();
        pool.denomination = 5;
        pool.Pool = new GameObject[20];
        for (int i = 0; i < pool.Pool.Length; i++)
        {
            GameObject chip = Spawn("Chip" + i);
            chip.transform.SetParent(poolObject.transform);
            Rigidbody body = chip.AddComponent<Rigidbody>();
            body.isKinematic = true;
            body.useGravity = false;
            chip.AddComponent<BoxCollider>().enabled = false;
            pool.Pool[i] = chip;
        }
        VrcRuntimeFake.InvokeNoArg(pool, "Start");

        game = Spawn("Game").AddComponent<HoldemGame>();
        game.seats = 1;
        game.tableState = HoldemGame.TABLE_PLAYING;
        game.potPile = CreatePile("Pot");

        player = Spawn("Player").AddComponent<HoldemPlayer>();
        player.game = game;
        player.seatIdx = 0;
        player.roundContributionPile = CreatePile("Round");
        player.playerPotPile = CreatePile("Winnings");
        game.players = new[] { player };

        game.SetAnimatedChipContainersEnabled(true);
    }

    [TearDown]
    public void TearDown()
    {
        for (int i = spawned.Count - 1; i >= 0; i--)
            if (spawned[i] != null) Object.DestroyImmediate(spawned[i]);
        spawned.Clear();
    }

    [Test]
    public void DynamicRoundClose_MaterializesMissingActionBeforePotTransfer()
    {
        game.potContribution[0] = 15;
        game.roundContribution[0] = 0;

        HoldemPresentation.PresentPlayingChipsDynamic(game, 0);

        Assert.AreEqual(0, player.roundContributionPile.GetTotalDisplayedValue());
        Assert.AreEqual(15, game.potPile.GetTotalDisplayedValue());
        Assert.AreEqual(3, (int)VrcRuntimeFake.GetPrivate(game.potPile, "movingChipCount"));
        for (int i = 0; i < game.potPile.transform.childCount; i++)
        {
            Rigidbody body = game.potPile.transform.GetChild(i).GetComponent<Rigidbody>();
            Assert.IsFalse(body.isKinematic, "Dynamic pot chips must remain physical during contraction");
            Assert.IsTrue(body.useGravity);
        }
    }

    [Test]
    public void DynamicActiveRound_ShowsPhysicalRoundPile()
    {
        game.roundContribution[0] = 15;

        HoldemPresentation.PresentPlayingChipsDynamic(game, 15);

        Assert.AreEqual(15, player.roundContributionPile.GetTotalDisplayedValue());
        Assert.AreEqual(3, (int)VrcRuntimeFake.GetPrivate(player.roundContributionPile, "movingChipCount"));
    }

    [Test]
    public void StaticRoundClose_RendersPotWithoutDynamicChips()
    {
        game.SetAnimatedChipContainersEnabled(false);
        game.potContribution[0] = 15;
        game.roundContribution[0] = 0;

        HoldemPresentation.PresentPlayingChipsStatic(game, 15);

        Assert.AreEqual(15, game.potPile.GetTotalDisplayedValue());
        Assert.AreEqual(0, (int)VrcRuntimeFake.GetPrivate(game.potPile, "movingChipCount"));
        for (int i = 0; i < game.potPile.transform.childCount; i++)
        {
            Rigidbody body = game.potPile.transform.GetChild(i).GetComponent<Rigidbody>();
            Assert.IsTrue(body.isKinematic, "Static pot chips must not enter physics simulation");
            Assert.IsFalse(body.useGravity);
        }
    }

    [Test]
    public void StaticActiveRound_ShowsStaticRoundPile()
    {
        game.SetAnimatedChipContainersEnabled(false);
        game.roundContribution[0] = 15;

        HoldemPresentation.PresentPlayingChipsStatic(game, 0);

        Assert.AreEqual(15, player.roundContributionPile.GetTotalDisplayedValue());
        Assert.AreEqual(0, (int)VrcRuntimeFake.GetPrivate(player.roundContributionPile, "movingChipCount"));
    }

[Test]
    public void StaticRaise_TransfersDeltaChipsIntoRoundPileWithoutRecalculating()
    {
        game.SetAnimatedChipContainersEnabled(false);
        player.stackPile = CreatePile("Stack");
        player.stackPile.SetTotalChips(100);
        game.roundContribution[0] = 10;
        HoldemPresentation.PresentPlayingChipsStatic(game, 0);
        Transform firstChip = player.roundContributionPile.transform.GetChild(0);

        game.roundContribution[0] = 25;
        HoldemPresentation.PresentPlayingChipsStatic(game, 0);

        Assert.AreEqual(25, player.roundContributionPile.GetTotalDisplayedValue());
        Assert.AreEqual(5, player.roundContributionPile.transform.childCount);
        Assert.AreSame(player.roundContributionPile.transform, firstChip.parent, "Existing chips must be kept, not respawned");
        Assert.AreEqual(0, (int)VrcRuntimeFake.GetPrivate(player.roundContributionPile, "movingChipCount"));
        for (int i = 0; i < player.roundContributionPile.transform.childCount; i++)
            Assert.IsTrue(player.roundContributionPile.transform.GetChild(i).GetComponent<Rigidbody>().isKinematic);
    }

    [Test]
    public void StaticRoundClose_TransfersRoundChipsIntoPot()
    {
        game.SetAnimatedChipContainersEnabled(false);
        game.roundContribution[0] = 15;
        HoldemPresentation.PresentPlayingChipsStatic(game, 0);
        Transform roundChip = player.roundContributionPile.transform.GetChild(0);

        game.potContribution[0] = 15;
        game.roundContribution[0] = 0;
        HoldemPresentation.PresentPlayingChipsStatic(game, 15);

        Assert.AreEqual(0, player.roundContributionPile.GetTotalDisplayedValue());
        Assert.AreEqual(15, game.potPile.GetTotalDisplayedValue());
        Assert.AreSame(game.potPile.transform, roundChip.parent, "Round chips must move into the pot, not be respawned");
        Assert.AreEqual(0, (int)VrcRuntimeFake.GetPrivate(game.potPile, "movingChipCount"));
        Assert.IsTrue(roundChip.GetComponent<Rigidbody>().isKinematic);
    }

    [Test]
    public void StaticRaise_AccumulatesAcrossMultipleUpdates()
    {
        game.SetAnimatedChipContainersEnabled(false);
        player.stackPile = CreatePile("Stack");
        player.stackPile.SetTotalChips(100);
        Transform firstChip = null;
        int[] contributions = { 5, 15, 30, 30, 45 };
        for (int i = 0; i < contributions.Length; i++)
        {
            game.roundContribution[0] = contributions[i];
            HoldemPresentation.PresentPlayingChipsStatic(game, 0);
            Assert.AreEqual(contributions[i], player.roundContributionPile.GetTotalDisplayedValue());
            if (firstChip == null) firstChip = player.roundContributionPile.transform.GetChild(0);
        }
        Assert.AreSame(player.roundContributionPile.transform, firstChip.parent);
        Assert.AreEqual(9, player.roundContributionPile.transform.childCount);
    }

    [Test]
    public void StaticRaise_SpawnsFromPoolWhenStackPileIsEmpty()
    {
        game.SetAnimatedChipContainersEnabled(false);
        player.stackPile = CreatePile("Stack");
        game.roundContribution[0] = 20;

        HoldemPresentation.PresentPlayingChipsStatic(game, 0);

        Assert.AreEqual(20, player.roundContributionPile.GetTotalDisplayedValue());
        Assert.AreEqual(0, player.stackPile.GetTotalDisplayedValue());
        Assert.AreEqual(0, (int)VrcRuntimeFake.GetPrivate(player.roundContributionPile, "movingChipCount"));
    }

    [Test]
    public void StaticRaise_WithoutStackPileFallsBackToRecalculation()
    {
        game.SetAnimatedChipContainersEnabled(false);
        player.stackPile = null;
        game.roundContribution[0] = 10;
        HoldemPresentation.PresentPlayingChipsStatic(game, 0);

        game.roundContribution[0] = 35;
        HoldemPresentation.PresentPlayingChipsStatic(game, 0);

        Assert.AreEqual(35, player.roundContributionPile.GetTotalDisplayedValue());
    }

    [Test]
    public void StaticRoundClose_AddsToChipsAlreadyInPot()
    {
        game.SetAnimatedChipContainersEnabled(false);
        game.potContribution[0] = 10;
        HoldemPresentation.PresentPlayingChipsStatic(game, 10);
        Transform potChip = game.potPile.transform.GetChild(0);

        game.roundContribution[0] = 15;
        HoldemPresentation.PresentPlayingChipsStatic(game, 10);
        Transform roundChip = player.roundContributionPile.transform.GetChild(0);
        Assert.AreEqual(10, game.potPile.GetTotalDisplayedValue(), "Pot must not change while the round is open");

        game.potContribution[0] = 25;
        game.roundContribution[0] = 0;
        HoldemPresentation.PresentPlayingChipsStatic(game, 25);

        Assert.AreEqual(25, game.potPile.GetTotalDisplayedValue());
        Assert.AreEqual(0, player.roundContributionPile.GetTotalDisplayedValue());
        Assert.AreSame(game.potPile.transform, potChip.parent);
        Assert.AreSame(game.potPile.transform, roundChip.parent);
    }

    [Test]
    public void StaticRoundClose_ActionArrivingWithTheCloseIsTransferredFromStackToPot()
    {
        game.SetAnimatedChipContainersEnabled(false);
        player.stackPile = CreatePile("Stack");
        player.stackPile.SetTotalChips(50);
        HoldemPresentation.PresentPlayingChipsStatic(game, 0);
        var stackChips = new HashSet<Transform>();
        for (int i = 0; i < player.stackPile.transform.childCount; i++)
            stackChips.Add(player.stackPile.transform.GetChild(i));

        // The final call and the round close land in one synced update: the round pile never showed the chips.
        game.potContribution[0] = 15;
        game.roundContribution[0] = 0;
        HoldemPresentation.PresentPlayingChipsStatic(game, 15);

        Assert.AreEqual(15, game.potPile.GetTotalDisplayedValue());
        Assert.AreEqual(0, player.roundContributionPile.GetTotalDisplayedValue());
        Assert.AreEqual(3, game.potPile.transform.childCount);
        for (int i = 0; i < game.potPile.transform.childCount; i++)
        {
            Transform chip = game.potPile.transform.GetChild(i);
            Assert.IsTrue(stackChips.Contains(chip), "Pot chips must be transferred from the stack, not recalculated");
            Assert.IsTrue(chip.GetComponent<Rigidbody>().isKinematic);
        }
        Assert.AreEqual(0, (int)VrcRuntimeFake.GetPrivate(game.potPile, "movingChipCount"));
    }

    [Test]
    public void StaticNewHand_ClearsPilesInsteadOfTransferring()
    {
        game.SetAnimatedChipContainersEnabled(false);
        game.potContribution[0] = 20;
        game.roundContribution[0] = 10;
        HoldemPresentation.PresentPlayingChipsStatic(game, 20);

        game.potContribution[0] = 0;
        game.roundContribution[0] = 0;
        HoldemPresentation.PresentPlayingChipsStatic(game, 0);

        Assert.AreEqual(0, player.roundContributionPile.GetTotalDisplayedValue());
        Assert.AreEqual(0, game.potPile.GetTotalDisplayedValue());
    }

    [Test]
    public void StaticRoundClose_FixesPotWhenItDriftedFromSyncedState()
    {
        game.SetAnimatedChipContainersEnabled(false);
        game.roundContribution[0] = 15;
        HoldemPresentation.PresentPlayingChipsStatic(game, 0);

        // A late joiner / toggle can leave the pot out of step with the contribution total.
        game.potContribution[0] = 40;
        game.roundContribution[0] = 0;
        HoldemPresentation.PresentPlayingChipsStatic(game, 40);

        Assert.AreEqual(40, game.potPile.GetTotalDisplayedValue());
        Assert.AreEqual(0, player.roundContributionPile.GetTotalDisplayedValue());
    }

    [Test]
    public void StaticRaise_WithExhaustedPool_StillEndsAtSyncedValueOrCapacity()
    {
        game.SetAnimatedChipContainersEnabled(false);
        player.stackPile = CreatePile("Stack");
        game.roundContribution[0] = 50;
        HoldemPresentation.PresentPlayingChipsStatic(game, 0);

        game.roundContribution[0] = 5000; // far beyond the 20-chip pool
        Assert.DoesNotThrow(() => HoldemPresentation.PresentPlayingChipsStatic(game, 0));

        Assert.LessOrEqual(player.roundContributionPile.GetTotalDisplayedValue(), 5000);
        Assert.GreaterOrEqual(player.roundContributionPile.GetTotalDisplayedValue(), 50);
    }

    [Test]
    public void DynamicToStaticMidRound_ContinuesByTransferringChips()
    {
        game.roundContribution[0] = 15;
        HoldemPresentation.PresentPlayingChipsDynamic(game, 15);
        game.SetAnimatedChipContainersEnabled(false);
        player.stackPile = CreatePile("Stack");
        player.stackPile.SetTotalChips(50);

        for (int i = 0; i < player.roundContributionPile.transform.childCount; i++)
            Assert.IsTrue(player.roundContributionPile.transform.GetChild(i).GetComponent<Rigidbody>().isKinematic,
                "Toggling to static must freeze chips dynamic mode left physical");

        game.roundContribution[0] = 30;
        HoldemPresentation.PresentPlayingChipsStatic(game, 0);

        Assert.AreEqual(30, player.roundContributionPile.GetTotalDisplayedValue());
        Assert.AreEqual(6, player.roundContributionPile.transform.childCount);
        for (int i = 0; i < player.roundContributionPile.transform.childCount; i++)
        {
            Transform chip = player.roundContributionPile.transform.GetChild(i);
            Assert.IsTrue(chip.GetComponent<Rigidbody>().isKinematic);
            Assert.IsFalse(chip.GetComponent<Collider>().enabled);
        }
    }

    [Test]
    public void ReapplyingDynamicMode_DoesNotFreezeActiveChips()
    {
        game.potPile.SpawnDynamicChips(5, game.potPile.transform.position);
        game.potPile.StartAnimatedGather();

        game.SetAnimatedChipContainersEnabled(true);

        Rigidbody body = game.potPile.transform.GetChild(0).GetComponent<Rigidbody>();
        Assert.IsFalse(body.isKinematic);
        Assert.IsTrue(body.GetComponent<Collider>().enabled);
    }

    [Test]
    public void PresentationMode_ConfiguresPilePlacementPolicy()
    {
        Assert.IsTrue(game.potPile.preservePhysicsPlacement);
        Assert.IsTrue(player.roundContributionPile.preservePhysicsPlacement);

        game.SetAnimatedChipContainersEnabled(false);

        Assert.IsFalse(game.potPile.preservePhysicsPlacement);
        Assert.IsFalse(player.roundContributionPile.preservePhysicsPlacement);
    }


    [Test]
    public void WinnerBoundary_SettlesDynamicObjectsAndReturnsToStaticValues()
    {
        game.potPile.SpawnDynamicChips(15, game.potPile.transform.position);
        Assert.AreEqual(15, game.potPile.GetTotalDisplayedValue());

        game._SettleDynamicChipPresentationForWinners();
        player.playerPotPile.SetTotalChips(10);

        Assert.AreEqual(0, game.potPile.GetTotalDisplayedValue());
        Assert.AreEqual(0, player.roundContributionPile.GetTotalDisplayedValue());
        Assert.AreEqual(10, player.playerPotPile.GetTotalDisplayedValue());
    }

[Test]
    public void DynamicWinnerBoundary_TransfersPhysicalPotChips()
    {
        game.potPile.SpawnDynamicChips(15, game.potPile.transform.position);
        game.seatWinnings[0] = 15;

        game._DistributeDynamicPotToWinners();

        Assert.AreEqual(0, game.potPile.GetTotalDisplayedValue());
        Assert.AreEqual(15, player.playerPotPile.GetTotalDisplayedValue());
        Assert.AreEqual(3, player.playerPotPile.transform.childCount);
        foreach (Transform chip in player.playerPotPile.transform)
        {
            Assert.IsFalse(chip.GetComponent<Rigidbody>().isKinematic);
            Assert.IsTrue(chip.GetComponent<Collider>().enabled);
        }
    }


    private PokerChipPile CreatePile(string name)
    {
        GameObject pileObject = Spawn(name);
        PokerChipPile pile = pileObject.AddComponent<PokerChipPile>();
        pile.denominationValues = new[] { 5 };
        pile.denominationPools = new[] { pool };
        pile.gatherTransportDuration = 0f;
        VrcRuntimeFake.InvokeNoArg(pile, "Start");
        return pile;
    }

    private GameObject Spawn(string name)
    {
        GameObject value = new GameObject(name);
        spawned.Add(value);
        return value;
    }
}
