using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using TMPro;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.SceneManagement;

/// <summary>
/// Renders PokerChipPile layouts under scripted game situations in an isolated preview scene (the open scene is
/// never touched), and measures them: stacks with mixed denominations, stack heights by ring, chips that moved
/// between steps, and the readout against the chips under it and the reset button above it.
/// Each scenario writes a contact sheet (seat view over top view, frames row-major) and the metrics to
/// Temp/ChipPileHarness/&lt;run&gt;/.
/// </summary>
public static class ChipPileLayoutHarness
{
    private const BindingFlags InstanceFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
    private const int CellWidth = 400;
    private const int CellHeight = 300;
    private const int SheetColumns = 4;

    public class PileMetrics
    {
        public int Chips;
        public int Value;
        public int Stacks;
        public int MixedStacks;
        public int Tallest;
        public int Moved = -1;
        public float[] RingAverages = new float[0];
        public float ReadoutBottom = float.NaN;
        public float ReadoutTop = float.NaN;
        public float TallestUnderReadout = float.NaN;
        public float Ceiling;

        public bool ReadoutCovered => !float.IsNaN(ReadoutBottom) && TallestUnderReadout > ReadoutBottom;
        public bool ReadoutHitsCeiling => Ceiling > 0f && !float.IsNaN(ReadoutTop) && ReadoutTop > Ceiling;

        public override string ToString()
        {
            var sb = new StringBuilder();
            sb.Append($"value={Value} chips={Chips} stacks={Stacks} mixed={MixedStacks} tallest={Tallest}");
            if (Moved >= 0) sb.Append($" moved={Moved}");
            sb.Append(" rings=[");
            for (int i = 0; i < RingAverages.Length; i++)
                sb.Append(i == 0 ? "" : " ").Append(float.IsNaN(RingAverages[i]) ? "-" : RingAverages[i].ToString("F1"));
            sb.Append("]");
            if (!float.IsNaN(ReadoutBottom))
            {
                sb.Append($" readout={ReadoutBottom:F3}..{ReadoutTop:F3} under={TallestUnderReadout:F3}");
                if (Ceiling > 0f) sb.Append($" ceiling={Ceiling:F3}");
                if (ReadoutCovered) sb.Append(" COVERED");
                if (ReadoutHitsCeiling) sb.Append(" HITS_CEILING");
            }
            return sb.ToString();
        }
    }

    /* ---------------------------
     * Measuring (mode-agnostic: works from the chip transforms only)
     * --------------------------- */

    public static Dictionary<GameObject, Vector3> Snapshot(PokerChipPile pile, Func<GameObject, int> denominationOf)
    {
        var positions = new Dictionary<GameObject, Vector3>();
        foreach (Transform child in pile.transform)
            if (child.gameObject.activeSelf && denominationOf(child.gameObject) > 0)
                positions[child.gameObject] = child.localPosition;
        return positions;
    }

    public static PileMetrics Measure(PokerChipPile pile, Func<GameObject, int> denominationOf,
        Dictionary<GameObject, Vector3> previous = null, float ceiling = 0f)
    {
        var metrics = new PileMetrics { Value = pile.GetTotalDisplayedValue(), Ceiling = ceiling };
        float spacing = Mathf.Max(0.0001f, pile.hexSpacing);
        var centers = new List<Vector2>();
        var counts = new List<int>();
        var denominations = new List<HashSet<int>>();

        foreach (Transform child in pile.transform)
        {
            int denomination = denominationOf(child.gameObject);
            if (!child.gameObject.activeSelf || denomination <= 0) continue;
            metrics.Chips++;
            Vector3 local = child.localPosition;
            var xz = new Vector2(local.x, local.z);
            int stack = -1;
            for (int i = 0; i < centers.Count && stack < 0; i++)
                if ((centers[i] - xz).magnitude < spacing * 0.5f) stack = i;
            if (stack < 0)
            {
                stack = centers.Count;
                centers.Add(xz);
                counts.Add(0);
                denominations.Add(new HashSet<int>());
            }
            counts[stack]++;
            denominations[stack].Add(denomination);

            if (previous != null && previous.TryGetValue(child.gameObject, out Vector3 before)
                && (before - local).sqrMagnitude > 1e-10f)
                metrics.Moved = Mathf.Max(0, metrics.Moved) + 1;
        }
        if (previous != null && metrics.Moved < 0) metrics.Moved = 0;

        metrics.Stacks = centers.Count;
        Vector2 origin = Vector2.zero;
        int maxRing = 0;
        var ringOf = new int[centers.Count];
        for (int i = 0; i < centers.Count; i++)
        {
            if (denominations[i].Count > 1) metrics.MixedStacks++;
            metrics.Tallest = Mathf.Max(metrics.Tallest, counts[i]);
            ringOf[i] = Mathf.RoundToInt((centers[i] - origin).magnitude / spacing);
            maxRing = Mathf.Max(maxRing, ringOf[i]);
        }
        if (centers.Count > 0)
        {
            var sums = new float[maxRing + 1];
            var stacksInRing = new int[maxRing + 1];
            for (int i = 0; i < centers.Count; i++)
            {
                sums[ringOf[i]] += counts[i];
                stacksInRing[ringOf[i]]++;
            }
            metrics.RingAverages = new float[maxRing + 1];
            for (int r = 0; r <= maxRing; r++)
                metrics.RingAverages[r] = stacksInRing[r] > 0 ? sums[r] / stacksInRing[r] : float.NaN;
        }

        TMP_Text text = pile.text;
        if (text != null && text.gameObject.activeInHierarchy && !string.IsNullOrEmpty(text.text))
        {
            text.ForceMeshUpdate();
            Bounds bounds = text.textBounds;
            float bottom = float.MaxValue, top = float.MinValue, halfWidth = 0f;
            Vector3 textCenter = pile.transform.InverseTransformPoint(text.transform.TransformPoint(bounds.center));
            for (int corner = 0; corner < 8; corner++)
            {
                Vector3 offset = new Vector3(
                    (corner & 1) == 0 ? -bounds.extents.x : bounds.extents.x,
                    (corner & 2) == 0 ? -bounds.extents.y : bounds.extents.y,
                    (corner & 4) == 0 ? -bounds.extents.z : bounds.extents.z);
                Vector3 local = pile.transform.InverseTransformPoint(text.transform.TransformPoint(bounds.center + offset));
                bottom = Mathf.Min(bottom, local.y);
                top = Mathf.Max(top, local.y);
                halfWidth = Mathf.Max(halfWidth, new Vector2(local.x - textCenter.x, local.z - textCenter.z).magnitude);
            }
            metrics.ReadoutBottom = bottom;
            metrics.ReadoutTop = top;
            metrics.TallestUnderReadout = 0f;
            foreach (Transform child in pile.transform)
            {
                if (!child.gameObject.activeSelf || denominationOf(child.gameObject) <= 0) continue;
                Vector3 local = child.localPosition;
                float horizontal = new Vector2(local.x - textCenter.x, local.z - textCenter.z).magnitude;
                if (horizontal > halfWidth + spacing * 0.5f) continue;
                metrics.TallestUnderReadout = Mathf.Max(metrics.TallestUnderReadout, local.y + pile.chipHeight);
            }
        }
        return metrics;
    }

    /* ---------------------------
     * Scenarios
     * --------------------------- */

    [MenuItem("Tools/Holdem/Chip Pile Layout Harness/Run (scene settings)")]
    public static void RunFromMenu()
    {
        string summary = Run(null, null);
        Debug.Log(summary);
    }

    /// <summary>
    /// Runs every scenario. <paramref name="naturalLayout"/> overrides the piles' naturalLayout flag when the field
    /// exists (null keeps the scene's values). Returns the metrics summary; images go to the run folder.
    /// </summary>
    public static string Run(string runName, bool? naturalLayout)
    {
        if (string.IsNullOrEmpty(runName)) runName = DateTime.Now.ToString("yyyyMMdd-HHmmss");
        string folder = Path.GetFullPath(Path.Combine(Application.dataPath, "..", "Temp", "ChipPileHarness", runName));
        Directory.CreateDirectory(folder);

        var summary = new StringBuilder();
        summary.AppendLine("Chip pile harness → " + folder);
        using (var stage = new Stage(naturalLayout))
        {
            PotGrowth(stage, folder, summary);
            OneShotValues(stage, folder, summary);
            StackUnderReset(stage, folder, summary);
            SmallChanges(stage, folder, summary);
        }
        File.WriteAllText(Path.Combine(folder, "metrics.txt"), summary.ToString());
        return summary.ToString();
    }

    // Four seats bet from their stacks into round piles, which are swept into the pot after every round,
    // the way static mode presents a hand. Then the pot goes to a winner and is restacked a few times.
    private static void PotGrowth(Stage stage, string folder, StringBuilder summary)
    {
        var sheet = new Sheet("pot-growth");
        PokerChipPile pot = stage.CreatePile("Pot", stage.PotTemplate, false);
        var stacks = new PokerChipPile[4];
        var rounds = new PokerChipPile[4];
        for (int seat = 0; seat < 4; seat++)
        {
            stacks[seat] = stage.CreatePile("Stack" + seat, stage.StackTemplate, false, new Vector3(5f + seat, 0f, 0f));
            rounds[seat] = stage.CreatePile("Round" + seat, stage.RoundTemplate, false, new Vector3(5f + seat, 0f, 2f));
            Reseed(stacks[seat], 20000);
        }

        int[] bets = { 20, 40, 60, 100, 150, 250, 400, 600, 1000, 1500, 2500, 4000 };
        for (int round = 0; round < bets.Length; round++)
        {
            var before = Snapshot(pot, stage.DenominationOf);
            for (int seat = 0; seat < 4; seat++)
            {
                int bet = bets[round] * (seat == round % 4 ? 2 : 1);
                int moved = stacks[seat].TransferValueApproximateTo(rounds[seat], bet);
                if (moved < bet) rounds[seat].AddValueFromPool(bet - moved);
                rounds[seat].TransferAllTo(pot);
            }
            stage.Settle(pot);
            var metrics = Measure(pot, stage.DenominationOf, before);
            sheet.Add(stage, pot, $"round {round + 1}", metrics, summary);
        }

        PokerChipPile winner = stage.CreatePile("Winner", stage.PlayerPotTemplate, false);
        pot.TransferAllTo(winner);
        Invoke(winner, "_RestackLayout");
        stage.Settle(winner);
        sheet.Add(stage, winner, "won pot", Measure(winner, stage.DenominationOf), summary);
        for (int restack = 1; restack <= 3; restack++)
        {
            Invoke(winner, "_RestackLayout");
            stage.Settle(winner);
            sheet.Add(stage, winner, $"restack {restack}", Measure(winner, stage.DenominationOf), summary);
        }
        sheet.Save(folder);

        stage.Destroy(pot);
        stage.Destroy(winner);
        for (int seat = 0; seat < 4; seat++)
        {
            stage.Destroy(stacks[seat]);
            stage.Destroy(rounds[seat]);
        }
    }

    private static void OneShotValues(Stage stage, string folder, StringBuilder summary)
    {
        var sheet = new Sheet("one-shot");
        foreach (int value in new[] { 50, 730, 4260, 25000, 100000, 1000000 })
        {
            PokerChipPile pot = stage.CreatePile("Pot" + value, stage.PotTemplate, false);
            pot.SetTotalChips(value);
            stage.Settle(pot);
            sheet.Add(stage, pot, value.ToString(), Measure(pot, stage.DenominationOf), summary);
            stage.Destroy(pot);
        }
        sheet.Save(folder);
    }

    // The seat's own stack, with its readout and the betting menu's reset button above it.
    private static void StackUnderReset(Stage stage, string folder, StringBuilder summary)
    {
        var sheet = new Sheet("stack-under-reset");
        foreach (int value in new[] { 300, 1500, 5000, 20000, 60000, 200000 })
        {
            PokerChipPile stack = stage.CreatePile("Stack" + value, stage.StackTemplate, true);
            Reseed(stack, value);
            stage.Settle(stack);
            sheet.Add(stage, stack, value.ToString(),
                Measure(stack, stage.DenominationOf, null, stage.ResetBottomLocalY), summary);
            stage.Destroy(stack);
        }
        sheet.Save(folder);
    }

    // Paying and receiving small amounts: only the chips added or removed should move.
    private static void SmallChanges(Stage stage, string folder, StringBuilder summary)
    {
        var sheet = new Sheet("small-changes");
        PokerChipPile stack = stage.CreatePile("StackChanges", stage.StackTemplate, true);
        int value = 10000;
        Reseed(stack, value);
        stage.Settle(stack);
        sheet.Add(stage, stack, value.ToString(), Measure(stack, stage.DenominationOf, null, stage.ResetBottomLocalY), summary);
        foreach (int delta in new[] { -30, -470, 1000, -2500, 40, -6000 })
        {
            var before = Snapshot(stack, stage.DenominationOf);
            value += delta;
            stack.SetTotalChips(value);
            stage.Settle(stack);
            sheet.Add(stage, stack, (delta > 0 ? "+" : "") + delta + " → " + value,
                Measure(stack, stage.DenominationOf, before, stage.ResetBottomLocalY), summary);
        }
        sheet.Save(folder);
        stage.Destroy(stack);
    }

    /// <summary>
    /// Plays <paramref name="hands"/> hands at a <paramref name="seats"/>-seat table through the same pile calls
    /// static mode makes (bet piles, stacks, round piles swept into the pot, the pot pushed to the winner and merged
    /// into their stack, busted seats rebuying), with oversized pools, and reports the most chips each denomination's
    /// pool ever had out at once. That peak is what the shared scene pools must hold.
    /// </summary>
    public static string MeasurePoolDemand(int seats, int hands, int buyIn, bool? naturalLayout, bool selectableStacks,
        int randomSeed = 1, int maxTableMoney = 0)
    {
        const int OversizedPool = 600;
        var report = new StringBuilder();
        var random = new System.Random(randomSeed);
        using (var stage = new Stage(naturalLayout, OversizedPool))
        {
            LocalObjectPool[] pools = stage.Pools;
            var peak = new int[pools.Length];
            int peakTotal = 0;
            int largestStack = 0;
            void Sample()
            {
                int total = 0;
                for (int d = 0; d < pools.Length; d++)
                {
                    int inUse = pools[d].Pool.Length - pools[d].availableCount;
                    peak[d] = Mathf.Max(peak[d], inUse);
                    total += inUse;
                }
                peakTotal = Mathf.Max(peakTotal, total);
            }

            var stack = new PokerChipPile[seats];
            var bet = new PokerChipPile[seats];
            var round = new PokerChipPile[seats];
            var won = new PokerChipPile[seats];
            var stackValue = new int[seats];
            var pendingWinnings = new int[seats];
            PokerChipPile pot = stage.CreatePile("Pot", stage.PotTemplate, false);
            for (int s = 0; s < seats; s++)
            {
                var offset = new Vector3(2f + s, 0f, 0f);
                stack[s] = stage.CreatePile("Stack" + s, stage.StackTemplate, false, offset);
                bet[s] = stage.CreatePile("Bet" + s, stage.BetTemplate, false, offset + Vector3.forward);
                round[s] = stage.CreatePile("Round" + s, stage.RoundTemplate, false, offset + Vector3.forward * 2f);
                won[s] = stage.CreatePile("Won" + s, stage.PlayerPotTemplate, false, offset + Vector3.forward * 3f);
                if (selectableStacks) stack[s].SetSelectableStackMode(true);
                stackValue[s] = buyIn;
                Reseed(stack[s], buyIn);
            }
            Sample();

            int bigBlind = Mathf.Max(25, buyIn / 100 / 25 * 25);
            var inHand = new bool[seats];
            for (int hand = 0; hand < hands; hand++)
            {
                for (int s = 0; s < seats; s++)
                {
                    won[s].SetTotalChips(0);
                    if (pendingWinnings[s] > 0)
                    {
                        // The won pot joins the stack once the winner screen ends.
                        Reseed(stack[s], stackValue[s]);
                        pendingWinnings[s] = 0;
                    }
                    int tableMoney = 0;
                    for (int t = 0; t < seats; t++) tableMoney += stackValue[t];
                    // Busted seats rebuy while the table's money stays under the cap (0 = no cap).
                    if (stackValue[s] < bigBlind * 2 && (maxTableMoney <= 0 || tableMoney + buyIn <= maxTableMoney))
                    {
                        stackValue[s] = buyIn;
                        stack[s].SetTotalChips(buyIn);
                    }
                    inHand[s] = true;
                    largestStack = Mathf.Max(largestStack, stackValue[s]);
                }
                Sample();

                for (int street = 0; street < 4; street++)
                {
                    for (int s = 0; s < seats; s++)
                    {
                        if (!inHand[s] || stackValue[s] <= 0) continue;
                        if (street > 0 && random.NextDouble() < 0.2) { inHand[s] = false; continue; }
                        int amount = street == 0
                            ? bigBlind
                            : (1 + random.Next(Mathf.Max(1, stackValue[s] / 8 / 25))) * 25;
                        if (random.NextDouble() < 0.03) amount = stackValue[s];
                        amount = Mathf.Min(amount, stackValue[s]);

                        // Acting: the bet pile shows the bet over the reduced stack.
                        bet[s].SetTotalChips(amount);
                        stack[s].SetTotalChips(stackValue[s] - amount);
                        Sample();
                        // Committed: the bet moves to the round pile (spawned, as _TakeBetChipsFromStack does once the
                        // stack already shows the reduced amount).
                        bet[s].SetTotalChips(0);
                        stackValue[s] -= amount;
                        round[s].AddValueFromPool(amount);
                        Sample();
                    }
                    for (int s = 0; s < seats; s++) round[s].TransferAllTo(pot);
                    Sample();
                }

                int potValue = pot.GetTotalDisplayedValue();
                int first = random.Next(seats);
                int second = random.NextDouble() < 0.1 ? (first + 1 + random.Next(seats - 1)) % seats : -1;
                if (second >= 0)
                {
                    int half = potValue / 2 / 5 * 5;
                    pot.TransferValueApproximateTo(won[second], half);
                    Invoke(won[second], "_RestackLayout");
                    pendingWinnings[second] += won[second].GetTotalDisplayedValue();
                    stackValue[second] += won[second].GetTotalDisplayedValue();
                }
                int rest = pot.GetTotalDisplayedValue();
                pot.TransferAllTo(won[first]);
                Invoke(won[first], "_RestackLayout");
                pendingWinnings[first] += rest;
                stackValue[first] += rest;
                pot.SetTotalChips(0);
                Sample();
            }

            report.Append($"{seats} seats, {hands} hands, buy-in {buyIn}, money cap {(maxTableMoney > 0 ? maxTableMoney.ToString() : "none")}, natural={(naturalLayout?.ToString() ?? "scene")}, selectableStacks={selectableStacks}: ");
            for (int d = 0; d < pools.Length; d++)
                report.Append($"{pools[d].denomination}={peak[d]}{(peak[d] >= OversizedPool ? "(SATURATED)" : "")} ");
            report.Append($"| all={peakTotal} largestStack={largestStack}");
        }
        // Long runs can outlast an editor-automation call, so the result is also kept on disk.
        string folder = Path.GetFullPath(Path.Combine(Application.dataPath, "..", "Temp", "ChipPileHarness"));
        Directory.CreateDirectory(folder);
        File.AppendAllText(Path.Combine(folder, "pool-demand.txt"), report + Environment.NewLine);
        Debug.Log("[ChipPileLayoutHarness] " + report);
        return report.ToString();
    }

    private static void Reseed(PokerChipPile pile, int value)
    {
        if (!Invoke(pile, "ReseedTotal", value)) pile.SetTotalChips(value);
    }

    private static bool Invoke(PokerChipPile pile, string method, params object[] arguments)
    {
        MethodInfo info = typeof(PokerChipPile).GetMethod(method, InstanceFlags);
        if (info == null) return false;
        info.Invoke(pile, arguments);
        return true;
    }

    /* ---------------------------
     * Contact sheet
     * --------------------------- */

    private class Sheet
    {
        private readonly string name;
        private readonly List<Color32[]> cells = new List<Color32[]>();

        public Sheet(string name) { this.name = name; }

        public void Add(Stage stage, PokerChipPile pile, string label, PileMetrics metrics, StringBuilder summary)
        {
            summary.AppendLine($"[{name} #{cells.Count}] {label}: {metrics}");
            cells.Add(stage.RenderCell(pile));
        }

        public void Save(string folder)
        {
            if (cells.Count == 0) return;
            int columns = Mathf.Min(SheetColumns, cells.Count);
            int rows = (cells.Count + columns - 1) / columns;
            int cellHeight = CellHeight * 2;
            var texture = new Texture2D(columns * CellWidth, rows * cellHeight, TextureFormat.RGB24, false);
            var background = new Color32[texture.width * texture.height];
            for (int i = 0; i < background.Length; i++) background[i] = new Color32(20, 20, 20, 255);
            texture.SetPixels32(background);
            for (int i = 0; i < cells.Count; i++)
            {
                int x = (i % columns) * CellWidth;
                int y = (rows - 1 - i / columns) * cellHeight;
                texture.SetPixels32(x, y, CellWidth, cellHeight, cells[i]);
            }
            texture.Apply();
            File.WriteAllBytes(Path.Combine(folder, name + ".png"), texture.EncodeToPNG());
            UnityEngine.Object.DestroyImmediate(texture);
        }
    }

    /* ---------------------------
     * Preview scene
     * --------------------------- */

    private class Stage : IDisposable
    {
        public PokerChipPile PotTemplate, StackTemplate, BetTemplate, RoundTemplate, PlayerPotTemplate;
        public float ResetBottomLocalY;

        private readonly bool? naturalLayout;
        private readonly Scene scene;
        private readonly Camera camera;
        private readonly RenderTexture target;
        private readonly Texture2D readback;
        private readonly List<UnityEngine.Object> owned = new List<UnityEngine.Object>();
        private readonly Dictionary<GameObject, int> denominations = new Dictionary<GameObject, int>();
        private readonly LocalObjectPool[] pools;
        // The scene's denominations when there is a table to copy, else a stand-in set.
        private int[] values = { 10, 50, 100, 500, 1000 };
        public LocalObjectPool[] Pools => pools;
        private Bounds resetLocalBounds;
        private bool hasReset;

        public int DenominationOf(GameObject chip) => denominations.TryGetValue(chip, out int value) ? value : 0;

        public Stage(bool? naturalLayout, int poolSizeOverride = 0)
        {
            this.naturalLayout = naturalLayout;
            scene = EditorSceneManager.NewPreviewScene();
            FindSceneTemplates();
            if (PotTemplate != null && PotTemplate.denominationValues != null
                && PotTemplate.denominationValues.Length == values.Length)
                values = (int[])PotTemplate.denominationValues.Clone();

            var lightGo = AddRoot(new GameObject("Key Light"));
            var light = lightGo.AddComponent<Light>();
            light.type = LightType.Directional;
            light.intensity = 1.1f;
            lightGo.transform.rotation = Quaternion.Euler(50f, -30f, 0f);
            var fillGo = AddRoot(new GameObject("Fill Light"));
            var fill = fillGo.AddComponent<Light>();
            fill.type = LightType.Directional;
            fill.intensity = 0.45f;
            fillGo.transform.rotation = Quaternion.Euler(30f, 150f, 0f);

            var felt = AddRoot(GameObject.CreatePrimitive(PrimitiveType.Plane));
            UnityEngine.Object.DestroyImmediate(felt.GetComponent<Collider>());
            felt.transform.localScale = Vector3.one * 0.2f;
            felt.GetComponent<Renderer>().sharedMaterial = Owned(new Material(Shader.Find("Standard")) { color = new Color(0.05f, 0.28f, 0.12f) });

            var cameraGo = AddRoot(new GameObject("Harness Camera"));
            camera = cameraGo.AddComponent<Camera>();
            camera.scene = scene;
            camera.enabled = false;
            camera.clearFlags = CameraClearFlags.SolidColor;
            camera.backgroundColor = new Color(0.18f, 0.18f, 0.2f);
            camera.fieldOfView = 25f;
            camera.nearClipPlane = 0.01f;
            camera.farClipPlane = 10f;
            target = Owned(new RenderTexture(CellWidth, CellHeight, 24) { antiAliasing = 4 });
            readback = Owned(new Texture2D(CellWidth, CellHeight, TextureFormat.RGB24, false));

            pools = new LocalObjectPool[values.Length];
            LocalObjectPool[] scenePools = PotTemplate != null ? PotTemplate.denominationPools : null;
            for (int d = 0; d < values.Length; d++)
            {
                var poolGo = AddRoot(new GameObject("Pool" + values[d]));
                poolGo.transform.position = new Vector3(0f, -10f, 0f);
                var pool = poolGo.AddComponent<LocalObjectPool>();
                pool.denomination = values[d];
                int size = poolSizeOverride > 0 ? poolSizeOverride : scenePools != null && d < scenePools.Length && scenePools[d] != null && scenePools[d].Pool != null
                    ? scenePools[d].Pool.Length : 200;
                GameObject template = scenePools != null && d < scenePools.Length && scenePools[d] != null
                    && scenePools[d].Pool != null && scenePools[d].Pool.Length > 0 ? scenePools[d].Pool[0] : null;
                pool.Pool = new GameObject[size];
                for (int c = 0; c < size; c++)
                {
                    GameObject chip = template != null ? CloneChip(template) : FallbackChip(d);
                    chip.name = "Chip" + values[d] + "_" + c;
                    chip.transform.SetParent(poolGo.transform, false);
                    denominations[chip] = values[d];
                    pool.Pool[c] = chip;
                }
                CallPrivate(pool, "Start");
                pools[d] = pool;
            }
        }

        private void FindSceneTemplates()
        {
            HoldemGame game = UnityEngine.Object.FindObjectOfType<HoldemGame>(true);
            if (game == null) return;
            PotTemplate = game.potPile;
            HoldemPlayer player = game.players != null && game.players.Length > 0 ? game.players[0] : null;
            if (player == null) return;
            StackTemplate = player.stackPile;
            BetTemplate = player.betPile;
            RoundTemplate = player.roundContributionPile;
            PlayerPotTemplate = player.playerPotPile;

            BoxCollider reset = player.bettingUi != null && player.bettingUi.resetButton != null
                ? player.bettingUi.resetButton.GetComponentInChildren<BoxCollider>(true) : null;
            if (reset == null || StackTemplate == null) return;
            Transform pileTransform = StackTemplate.transform;
            bool first = true;
            for (int corner = 0; corner < 8; corner++)
            {
                Vector3 offset = Vector3.Scale(reset.size * 0.5f, new Vector3(
                    (corner & 1) == 0 ? -1f : 1f, (corner & 2) == 0 ? -1f : 1f, (corner & 4) == 0 ? -1f : 1f));
                Vector3 local = pileTransform.InverseTransformPoint(reset.transform.TransformPoint(reset.center + offset));
                if (first) resetLocalBounds = new Bounds(local, Vector3.zero);
                else resetLocalBounds.Encapsulate(local);
                first = false;
            }
            hasReset = true;
            ResetBottomLocalY = resetLocalBounds.min.y;
        }

        public PokerChipPile CreatePile(string name, PokerChipPile template, bool withReadoutAndReset, Vector3? position = null)
        {
            var go = AddRoot(new GameObject(name));
            go.transform.position = position ?? Vector3.zero;
            go.transform.localScale = template != null ? template.transform.lossyScale : Vector3.one * 0.8f;
            var pile = go.AddComponent<PokerChipPile>();
            if (template != null) CopySettings(template, pile);
            pile.denominationValues = (int[])values.Clone();
            pile.denominationPools = pools;
            pile.text = null;
            pile.textGameObject = null;
            pile.lookAtPlayer = null;
            pile.activeDenominationPositions = null;
            if (naturalLayout.HasValue) SetField(pile, "naturalLayout", naturalLayout.Value);

            if (withReadoutAndReset && template != null && template.text != null)
            {
                pile.text = CloneReadout(template, go.transform);
                pile.textGameObject = pile.text.gameObject;
            }
            if (withReadoutAndReset && hasReset)
            {
                WireBox(go.transform, resetLocalBounds, new Color(1f, 0.15f, 0.15f));
                SetField(pile, "ceilingLocalY", resetLocalBounds.min.y);
            }
            CallPrivate(pile, "Start");
            return pile;
        }

        public void Destroy(PokerChipPile pile)
        {
            if (pile == null) return;
            pile.ReleaseAllToPools();
            foreach (LocalObjectPool pool in pools)
                foreach (GameObject chip in pool.Pool)
                    if (chip != null && chip.transform.parent == pile.transform)
                        chip.transform.SetParent(pool.transform, false);
            UnityEngine.Object.DestroyImmediate(pile.gameObject);
        }

        public void Settle(PokerChipPile pile) => CallPrivate(pile, "SettleAnimation");

        public Color32[] RenderCell(PokerChipPile pile)
        {
            Vector3 center = pile.transform.position;
            Vector3 focus = center + Vector3.up * 0.04f;
            var cell = new Color32[CellWidth * CellHeight * 2];

            // Seat view (top half of the cell)
            camera.transform.position = center + new Vector3(0f, 0.2f, -0.36f);
            camera.transform.LookAt(focus);
            FaceReadout(pile);
            Capture(cell, CellHeight);

            // Top-down view (bottom half)
            camera.transform.position = center + new Vector3(0f, 0.55f, 0f);
            camera.transform.rotation = Quaternion.LookRotation(Vector3.down, Vector3.forward);
            Capture(cell, 0);
            return cell;
        }

        private void FaceReadout(PokerChipPile pile)
        {
            if (pile.text == null) return;
            Vector3 forward = pile.text.transform.position - camera.transform.position;
            forward.y = 0f;
            if (forward.sqrMagnitude > 1e-6f) pile.text.transform.rotation = Quaternion.LookRotation(forward);
        }

        private void Capture(Color32[] cell, int rowOffset)
        {
            camera.targetTexture = target;
            camera.Render();
            RenderTexture previous = RenderTexture.active;
            RenderTexture.active = target;
            readback.ReadPixels(new Rect(0, 0, CellWidth, CellHeight), 0, 0);
            readback.Apply();
            RenderTexture.active = previous;
            camera.targetTexture = null;
            Color32[] pixels = readback.GetPixels32();
            Array.Copy(pixels, 0, cell, rowOffset * CellWidth, pixels.Length);
        }

        private TMP_Text CloneReadout(PokerChipPile template, Transform pile)
        {
            TMP_Text source = template.text;
            GameObject clone = UnityEngine.Object.Instantiate(source.gameObject);
            foreach (MonoBehaviour behaviour in clone.GetComponentsInChildren<MonoBehaviour>(true))
                if (!(behaviour is TMP_Text)) UnityEngine.Object.DestroyImmediate(behaviour);
            AddRoot(clone);
            clone.SetActive(true);
            // The readout is UI text; outside its world-space canvas it needs one of its own to render.
            if (clone.GetComponent<Canvas>() == null) clone.AddComponent<Canvas>().renderMode = RenderMode.WorldSpace;
            clone.transform.SetParent(pile, false);
            clone.transform.localPosition = template.transform.InverseTransformPoint(source.transform.position);
            Vector3 sourceScale = source.transform.lossyScale;
            Vector3 pileScale = template.transform.lossyScale;
            clone.transform.localScale = new Vector3(sourceScale.x / pileScale.x, sourceScale.y / pileScale.y, sourceScale.z / pileScale.z);
            return clone.GetComponent<TMP_Text>();
        }

        private void WireBox(Transform parent, Bounds bounds, Color color)
        {
            var material = Owned(new Material(Shader.Find("Unlit/Color")) { color = color });
            Vector3 min = bounds.min, max = bounds.max;
            float thickness = 0.0015f;
            for (int axis = 0; axis < 3; axis++)
            {
                for (int a = 0; a < 2; a++)
                {
                    for (int b = 0; b < 2; b++)
                    {
                        var edge = GameObject.CreatePrimitive(PrimitiveType.Cube);
                        UnityEngine.Object.DestroyImmediate(edge.GetComponent<Collider>());
                        AddRoot(edge);
                        edge.transform.SetParent(parent, false);
                        Vector3 position = bounds.center;
                        Vector3 scale = Vector3.one * thickness;
                        int u = (axis + 1) % 3, v = (axis + 2) % 3;
                        position[u] = a == 0 ? min[u] : max[u];
                        position[v] = b == 0 ? min[v] : max[v];
                        scale[axis] = bounds.size[axis];
                        edge.transform.localPosition = position;
                        edge.transform.localScale = scale;
                        edge.GetComponent<Renderer>().sharedMaterial = material;
                    }
                }
            }
        }

        private GameObject CloneChip(GameObject template)
        {
            GameObject chip = UnityEngine.Object.Instantiate(template);
            foreach (MonoBehaviour behaviour in chip.GetComponentsInChildren<MonoBehaviour>(true))
                UnityEngine.Object.DestroyImmediate(behaviour);
            return AddRoot(chip);
        }

        private GameObject FallbackChip(int denomination)
        {
            Color[] colors = { Color.white, Color.red, Color.blue, Color.green, Color.black };
            var chip = AddRoot(GameObject.CreatePrimitive(PrimitiveType.Cylinder));
            UnityEngine.Object.DestroyImmediate(chip.GetComponent<Collider>());
            chip.transform.localScale = new Vector3(0.039f, 0.0018f, 0.039f);
            chip.GetComponent<Renderer>().sharedMaterial = Owned(new Material(Shader.Find("Standard")) { color = colors[denomination % colors.Length] });
            return chip;
        }

        private GameObject AddRoot(GameObject go)
        {
            if (go.transform.parent != null) go.transform.SetParent(null);
            SceneManager.MoveGameObjectToScene(go, scene);
            return go;
        }

        private T Owned<T>(T asset) where T : UnityEngine.Object
        {
            owned.Add(asset);
            return asset;
        }

        public void Dispose()
        {
            EditorSceneManager.ClosePreviewScene(scene);
            foreach (UnityEngine.Object asset in owned)
                if (asset != null) UnityEngine.Object.DestroyImmediate(asset);
        }
    }

    // Copies the template's tuning (numbers, flags, number arrays) but none of its object references.
    private static void CopySettings(PokerChipPile source, PokerChipPile destination)
    {
        foreach (FieldInfo field in typeof(PokerChipPile).GetFields(BindingFlags.Instance | BindingFlags.Public))
        {
            Type type = field.FieldType;
            if (type.IsPrimitive || type == typeof(Vector3) || type == typeof(int[]) || type == typeof(Vector3[]))
            {
                object value = field.GetValue(source);
                if (value is Array array) value = array.Clone();
                field.SetValue(destination, value);
            }
        }
    }

    private static void SetField(object target, string name, object value)
    {
        FieldInfo field = target.GetType().GetField(name, InstanceFlags);
        if (field != null) field.SetValue(target, value);
    }

    private static void CallPrivate(object target, string method)
    {
        MethodInfo info = target.GetType().GetMethod(method, InstanceFlags);
        if (info != null) info.Invoke(target, null);
    }
}
