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

/// <summary>
/// Edge cases and ordering races around the "animated chip containers" toggle. The toggle can flip at any
/// moment (mid-round, mid-transfer, during the winner screen) and Udon start order is undefined, so the
/// game must always end up with the pot and round piles showing the values the synced state says.
/// </summary>
public class ChipToggleEdgeCaseTests
{
    private readonly List<GameObject> spawned = new List<GameObject>();
    private VrcRuntimeFake runtime;
    private LocalObjectPool pool;
    private HoldemGame game;
    private HoldemPlayer player;

    [SetUp]
    public void SetUp()
    {
        runtime = new VrcRuntimeFake();
        runtime.Install();

        GameObject poolObject = Spawn("Pool");
        pool = poolObject.AddComponent<LocalObjectPool>();
        pool.denomination = 5;
        pool.Pool = new GameObject[40];
        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", true);

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

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

    // ---- ordering / first-initialisation races ----

    [Test]
    public void ToggleBeforePilesHaveStarted_DoesNotThrow()
    {
        // GlobalToggleFlags.Start can run before any PokerChipPile.Start (Udon start order is undefined).
        game.potPile = CreatePile("LatePot", false);
        player.roundContributionPile = CreatePile("LateRound", false);
        game.roundContribution[0] = 15;
        game.potContribution[0] = 30;

        Assert.DoesNotThrow(() => game.SetAnimatedChipContainersEnabled(false),
            "Toggling before the piles ran Start must not throw; an exception here aborts GlobalToggleFlags.Start");
        Assert.IsTrue(game._IsChipPresentationModeReady());
    }

    [Test]
    public void ToggleBeforePilesHaveStarted_PilesStillDrawAfterTheyStart()
    {
        PokerChipPile late = CreatePile("LateRound", false);
        player.roundContributionPile = late;
        game.roundContribution[0] = 15;

        try { game.SetAnimatedChipContainersEnabled(false); } catch (System.Exception) { }
        VrcRuntimeFake.InvokeNoArg(late, "Start");
        HoldemPresentation.PresentPlayingChipsStatic(game, 0);

        Assert.AreEqual(15, late.GetTotalDisplayedValue(),
            "A pile that started late must still render the round value the next time it is presented");
    }

    [Test]
    public void ToggleWithoutPlayersOrPiles_DoesNotThrow()
    {
        game.players = null;
        game.potPile = null;

        Assert.DoesNotThrow(() => game.SetAnimatedChipContainersEnabled(true));
        Assert.DoesNotThrow(() => game.SetAnimatedChipContainersEnabled(false));
    }

    [Test]
    public void EveryRealChange_ForcesAUiRedraw()
    {
        game.SetAnimatedChipContainersEnabled(false);
        VrcRuntimeFake.SetPrivate(game, "uiEpoch", 5);

        game.SetAnimatedChipContainersEnabled(false);
        Assert.AreEqual(5, (int)VrcRuntimeFake.GetPrivate(game, "uiEpoch"), "A no-op toggle must not force a redraw");

        game.SetAnimatedChipContainersEnabled(true);
        Assert.AreEqual(-1, (int)VrcRuntimeFake.GetPrivate(game, "uiEpoch"),
            "A real change must invalidate the UI gate, or the piles are never redrawn for the current epoch");

        VrcRuntimeFake.SetPrivate(game, "uiEpoch", 5);
        game.SetAnimatedChipContainersEnabled(false);
        Assert.AreEqual(-1, (int)VrcRuntimeFake.GetPrivate(game, "uiEpoch"));
    }

    // ---- toggling mid-round ----

    [Test]
    public void StaticToDynamicMidRound_KeepsRoundPileValue()
    {
        game.SetAnimatedChipContainersEnabled(false);
        game.roundContribution[0] = 15;
        HoldemPresentation.PresentPlayingChipsStatic(game, 0);
        Assert.AreEqual(15, player.roundContributionPile.GetTotalDisplayedValue(), "Sanity");

        game.SetAnimatedChipContainersEnabled(true);
        HoldemPresentation.PresentPlayingChipsDynamic(game, 15);

        Assert.AreEqual(15, player.roundContributionPile.GetTotalDisplayedValue(),
            "Switching to dynamic mode must neither lose nor double the pending bet");
    }

    [Test]
    public void DynamicToStaticMidRound_ShowsRoundAndPotFromSyncedState()
    {
        game.SetAnimatedChipContainersEnabled(true);
        game.roundContribution[0] = 10;
        game.potContribution[0] = 20;
        HoldemPresentation.PresentPlayingChipsDynamic(game, 10);

        game.SetAnimatedChipContainersEnabled(false);

        Assert.AreEqual(10, player.roundContributionPile.GetTotalDisplayedValue(),
            "Static reconcile must show the pending bet");
        Assert.AreEqual(20, game.potPile.GetTotalDisplayedValue(),
            "Static reconcile must show the pot");
    }

    [Test]
    public void RapidToggling_EndsConsistentWithSyncedState()
    {
        game.roundContribution[0] = 15;
        game.potContribution[0] = 25;
        for (int i = 0; i < 9; i++)
        {
            game.SetAnimatedChipContainersEnabled(i % 2 == 0);
            if (game.animatedChipContainersEnabled)
                HoldemPresentation.PresentPlayingChipsDynamic(game, 15);
            else
                HoldemPresentation.PresentPlayingChipsStatic(game, 25);
        }

        game.SetAnimatedChipContainersEnabled(false);
        HoldemPresentation.PresentPlayingChipsStatic(game, 25);

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

    [Test]
    public void ToggleOffDuringTransfer_LeavesNoDanglingTransferAndKeepsPot()
    {
        game.SetAnimatedChipContainersEnabled(true);
        game.potContribution[0] = 15;
        game.roundContribution[0] = 0;
        HoldemPresentation.PresentPlayingChipsDynamic(game, 0);
        Assert.IsNotNull(VrcRuntimeFake.GetPrivate(game, "activeChipTransferDestination"), "Sanity: a transfer is in flight");

        game.SetAnimatedChipContainersEnabled(false);

        Assert.IsNull(VrcRuntimeFake.GetPrivate(game, "activeChipTransferDestination"),
            "Switching to static mode must settle the in-flight transfer");
        Assert.AreEqual(15, game.potPile.GetTotalDisplayedValue(), "The pot must survive the toggle");
        Assert.DoesNotThrow(() => game._FinishActiveChipTransferDelayed(),
            "The stale delayed finish callback must be harmless after the toggle");
    }

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

        game.SetAnimatedChipContainersEnabled(true);
        game.SetAnimatedChipContainersEnabled(false);

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

    // ---- toggling around the winner screen ----

    [Test]
    public void ToggleOnDuringWinnerScreen_KeepsWinningsVisible()
    {
        game.SetAnimatedChipContainersEnabled(false);
        game.tableState = HoldemGame.TABLE_WINNER;
        game.potContribution[0] = 15;
        game.seatWinnings[0] = 15;
        game._SettleDynamicChipPresentationForWinners();
        player.playerPotPile.SetTotalChips(15);
        Assert.AreEqual(15, player.playerPotPile.GetTotalDisplayedValue(), "Sanity: static winnings are shown");

        game.SetAnimatedChipContainersEnabled(true);
        // RefreshUI re-runs for the current epoch after the toggle, taking the dynamic winner branch.
        game._DistributeDynamicPotToWinners();

        Assert.AreEqual(15, player.playerPotPile.GetTotalDisplayedValue(),
            "Re-presenting the winner screen in dynamic mode must not wipe winnings that are already shown " +
            "(the pot pile is empty by then, so there is nothing left to transfer)");
    }

    [Test]
    public void ToggleOffDuringWinnerScreen_ShowsWinningsStatically()
    {
        game.SetAnimatedChipContainersEnabled(true);
        game.tableState = HoldemGame.TABLE_WINNER;
        game.seatWinnings[0] = 15;
        game.potPile.SpawnDynamicChips(15, game.potPile.transform.position);
        game._DistributeDynamicPotToWinners();
        Assert.AreEqual(15, player.playerPotPile.GetTotalDisplayedValue(), "Sanity");

        game.SetAnimatedChipContainersEnabled(false);
        game._SettleDynamicChipPresentationForWinners();
        player.playerPotPile.SetTotalChips(game.seatWinnings[0]);

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

    // ---- multi-table world wiring ----

    [Test]
    public void GlobalToggle_ReachesEveryTable()
    {
        GameObject root = Spawn("Flags");
        GlobalToggleFlags flags = root.AddComponent<GlobalToggleFlags>();
        Toggle animated = Spawn("Animated").AddComponent<Toggle>();
        flags.animatedChipContainersToggle = animated;

        HoldemGame second = Spawn("Game2").AddComponent<HoldemGame>();
        HoldemPlayer secondSeat0 = Spawn("P2S0").AddComponent<HoldemPlayer>();
        secondSeat0.game = second;
        secondSeat0.seatIdx = 0;
        HoldemPlayer secondSeat1 = Spawn("P2S1").AddComponent<HoldemPlayer>();
        secondSeat1.game = second;
        secondSeat1.seatIdx = 1;
        player.seatIdx = 0;
        HoldemPlayer firstSeat1 = Spawn("P1S1").AddComponent<HoldemPlayer>();
        firstSeat1.game = game;
        firstSeat1.seatIdx = 1;
        flags.holdemPlayers = new[] { player, firstSeat1, secondSeat1, secondSeat0 };

        animated.SetIsOnWithoutNotify(true);
        flags.UpdateAnimatedChipContainers();

        Assert.IsTrue(game.animatedChipContainersEnabled, "Table 1 must receive the toggle");
        Assert.IsTrue(second.animatedChipContainersEnabled,
            "Table 2 must receive the toggle regardless of where its seat 0 sits in the list");
    }

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

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