using System.Reflection;
using NUnit.Framework;
using UdonSharpEditor;
using UnityEditor;
using UnityEngine;
using UnityEngine.UI;

// The real InfoPanel prefab, not a hand-built stand-in: the biggest-win cards must be wired, laid out and drawn.
public class PanelBalancePrefabTests
{
    private const BindingFlags Priv = BindingFlags.NonPublic | BindingFlags.Instance;
    private const int CLUBS = 0, DIAMONDS = 13, HEARTS = 26;
    private static int Card(int suit, int rank) { return suit + rank - 2; }

    private static readonly string AmountKey = PlayerBalanceComponent.SaveKeyPrefix + "HoldemBigWinAmountV2";
    private static readonly string HandKey = PlayerBalanceComponent.SaveKeyPrefix + "HoldemBigWinCardsV2";

    private VrcRuntimeFake fake;
    private GameObject root;
    private GameObject balanceRoot;
    private PanelBalance panel;
    private RawImage[] cards;
    private RawImage[] glows;

    [SetUp]
    public void SetUp()
    {
        fake = new VrcRuntimeFake();
        fake.Install(1);
        fake.MasterId = 1;

        root = PrefabUtility.LoadPrefabContents(HoldemPaths.Asset("Prefabs/InfoPanel.prefab"));
        panel = root.GetComponentInChildren<PanelBalance>(true);
        Assert.IsNotNull(panel, "PanelBalance missing from InfoPanel");
        UdonSharpEditorUtility.CopyUdonToProxy(panel);

        balanceRoot = new GameObject("Balance");
        var balance = balanceRoot.AddComponent<PlayerBalanceComponent>();
        balance.CurrentSyncedBalance = 10000;
        typeof(PlayerBalanceComponent).GetField("bIsReady", Priv).SetValue(balance, true);
        Field("balanceComponent").SetValue(panel, balance);
        Field("isInitialized").SetValue(panel, true);

        cards = (RawImage[])Field("bestHandCards").GetValue(panel);
        glows = (RawImage[])Field("bestHandHighlights").GetValue(panel);
    }

    [TearDown]
    public void TearDown()
    {
        fake.Uninstall();
        Object.DestroyImmediate(balanceRoot);
        PrefabUtility.UnloadPrefabContents(root);
    }

    private static FieldInfo Field(string name)
    {
        return typeof(PanelBalance).GetField(name, Priv);
    }

    private void ShowHand(int h0, int h1, int f0, int f1, int f2, int turn, int river)
    {
        fake.SeedInt(AmountKey, 2000);
        fake.SeedInt(HandKey, HoldemHandEvaluator.PackBestFive(h0, h1, f0, f1, f2, turn, river));
        panel.OnBalanceChanged();
        Canvas.ForceUpdateCanvases();
    }

    [Test]
    public void BothCardAndHighlightSlotsAreWired()
    {
        Assert.AreEqual(5, cards.Length);
        Assert.AreEqual(5, glows.Length);
        for (int i = 0; i < 5; i++)
        {
            Assert.IsNotNull(cards[i], "card " + i);
            Assert.IsNotNull(glows[i], "highlight " + i);
            Assert.AreSame(cards[i].transform.parent, glows[i].transform.parent, "slot " + i);
            Assert.Less(glows[i].transform.GetSiblingIndex(), cards[i].transform.GetSiblingIndex(),
                "the highlight is drawn first, behind the card");
        }
    }

    [Test]
    public void StoredWinDrawsAllFiveCardsWithRealSize()
    {
        ShowHand(Card(CLUBS, 9), Card(DIAMONDS, 9), Card(HEARTS, 9), Card(CLUBS, 11), Card(DIAMONDS, 7), -1, -1);

        for (int i = 0; i < 5; i++)
        {
            Assert.IsTrue(cards[i].enabled, "card " + i + " enabled");
            Assert.IsTrue(cards[i].gameObject.activeInHierarchy, "card " + i + " active");
            Assert.Greater(cards[i].rectTransform.rect.width, 1f, "card " + i + " width");
            Assert.Greater(cards[i].rectTransform.rect.height, 1f, "card " + i + " height");
            Assert.IsNotNull(cards[i].mainTexture, "card " + i + " texture (from its material)");
            Assert.Greater(cards[i].color.a, 0f);
        }
    }

    [Test]
    public void HoleCardsGetTheHighlightBehindTheirCard()
    {
        ShowHand(Card(CLUBS, 9), Card(DIAMONDS, 9), Card(HEARTS, 9), Card(CLUBS, 11), Card(DIAMONDS, 7), -1, -1);

        int lit = 0;
        for (int i = 0; i < 5; i++)
        {
            if (!glows[i].enabled) continue;
            lit++;
            Assert.IsNotNull(glows[i].material);
            Assert.LessOrEqual(glows[i].material.renderQueue, 3000, "must not sort in front of the cards");
            Assert.Greater(glows[i].rectTransform.rect.width, cards[i].rectTransform.rect.width, "visible border");
        }
        Assert.AreEqual(2, lit);
    }

    // Variants record layout-driven RectTransform values as overrides; any stale one on a card collapses it to 0x0.
    [TestCase("Prefabs/InfoPanel.prefab")]
    [TestCase("InfoPanel/InfoPanelCorkboard.prefab")]
    [TestCase("parent.prefab")]
    public void EveryPrefabThatEmbedsThePanelGivesTheCardsRealSize(string asset)
    {
        GameObject contents = PrefabUtility.LoadPrefabContents(HoldemPaths.Asset(asset));
        try
        {
            Canvas.ForceUpdateCanvases();
            int checkedCards = 0;
            foreach (PanelBalance embedded in contents.GetComponentsInChildren<PanelBalance>(true))
            {
                UdonSharpEditorUtility.CopyUdonToProxy(embedded);
                RawImage[] faces = (RawImage[])Field("bestHandCards").GetValue(embedded);
                for (int i = 0; i < faces.Length; i++)
                {
                    Assert.Greater(faces[i].rectTransform.rect.width, 1f, asset + " card " + i + " width");
                    Assert.Greater(faces[i].rectTransform.rect.height, 1f, asset + " card " + i + " height");
                    checkedCards++;
                }
            }
            Assert.Greater(checkedCards, 0, "no PanelBalance found in " + asset);
        }
        finally
        {
            PrefabUtility.UnloadPrefabContents(contents);
        }
    }
}
