using UnityEditor;
using UnityEngine;

// Builds a throwaway grid of chip columns in the open scene to eyeball the ChipHighlight shader on proxy chips.
// One row per chip colour, then a short (4 chip) column row; the column index along X is how many top chips are
// selected (0 = nothing selected, so only the invisible-material proxies, which render nothing here).
// The objects are DontSave, so they never end up in the scene file. Tweak ChipHighlightFill / ChipHighlightOutline
// in the inspector while this is on screen to see the change live.
public static class ChipHighlightPreview
{
    private const string RootName = "ChipHighlightPreview";
    private const string PlayerPrefab = "Assets/VrchatHoldem/DevPrefabs/HoldemPlayer.prefab";
    private const string MaterialDir = "Assets/VrchatHoldem/Materials/";
    private const float ChipHeight = 0.003f;
    private const float ColumnSpacing = 0.09f;
    private const float RowSpacing = 0.1f;

    [MenuItem("Holdem/Chip Highlight Preview/Build")]
    public static void Build()
    {
        Clear();
        Material fill = AssetDatabase.LoadAssetAtPath<Material>(MaterialDir + "ChipHighlightFill.mat");
        Material outline = AssetDatabase.LoadAssetAtPath<Material>(MaterialDir + "ChipHighlightOutline.mat");
        GameObject player = AssetDatabase.LoadAssetAtPath<GameObject>(PlayerPrefab);
        if (fill == null || outline == null || player == null)
        {
            Debug.LogError("ChipHighlightPreview: missing materials or " + PlayerPrefab);
            return;
        }

        // One mesh + material per chip colour, taken from the chips the pile actually spawns.
        var meshes = new System.Collections.Generic.List<Mesh>();
        var materials = new System.Collections.Generic.List<Material>();
        foreach (MeshRenderer renderer in player.GetComponentsInChildren<MeshRenderer>(true))
        {
            if (renderer.transform.parent == null || renderer.transform.parent.name != "Chips") continue;
            MeshFilter filter = renderer.GetComponent<MeshFilter>();
            if (filter == null || meshes.Contains(filter.sharedMesh)) continue;
            meshes.Add(filter.sharedMesh);
            materials.Add(renderer.sharedMaterial);
        }

        var root = new GameObject(RootName);
        root.hideFlags = HideFlags.DontSave;
        SceneView view = SceneView.lastActiveSceneView;
        root.transform.position = view != null ? view.pivot : Vector3.zero;

        int rows = meshes.Count;
        for (int row = 0; row < rows + 1; row++)
        {
            bool shortRow = row == rows;
            int chips = shortRow ? 4 : 10;
            int mesh = shortRow ? 0 : row;
            for (int selected = 0; selected <= chips; selected++)
            {
                Vector3 basePosition = root.transform.position
                    + new Vector3(selected * ColumnSpacing, 0f, -row * RowSpacing);
                BuildColumn(root.transform, meshes[mesh], materials[mesh], fill, outline, basePosition,
                    chips, selected, row * 100 + selected);
            }
        }

        if (view != null)
        {
            var bounds = new Bounds(root.transform.position + new Vector3(5 * ColumnSpacing, 0f, -rows * 0.5f * RowSpacing),
                new Vector3(11 * ColumnSpacing, 0.05f, (rows + 1) * RowSpacing));
            view.Frame(bounds, false);
        }
        Selection.activeGameObject = root;
    }

    [MenuItem("Holdem/Chip Highlight Preview/Clear")]
    public static void Clear()
    {
        GameObject existing = GameObject.Find(RootName);
        while (existing != null)
        {
            Object.DestroyImmediate(existing);
            existing = GameObject.Find(RootName);
        }
    }

    private static void BuildColumn(Transform parent, Mesh mesh, Material chipMaterial, Material fill, Material outline,
        Vector3 basePosition, int chips, int selected, int seed)
    {
        var column = new GameObject("Column sel=" + selected + "/" + chips);
        column.hideFlags = HideFlags.DontSave;
        column.transform.SetParent(parent, true);
        column.transform.position = basePosition;
        var random = new System.Random(seed);

        for (int i = 0; i < chips; i++)
        {
            Vector3 position = basePosition + Vector3.up * (i * ChipHeight);
            Quaternion rotation = Quaternion.Euler(-90f, (float)random.NextDouble() * 360f, 0f);

            CreateChip("Chip " + i, column.transform, mesh, chipMaterial, position, rotation);
            if (i >= chips - selected)
            {
                // Same pose as the real chip, exactly like PhysicalRaisePile.SetHighlight.
                GameObject proxy = CreateChip("Proxy " + i, column.transform, mesh, fill, position, rotation);
                proxy.GetComponent<MeshRenderer>().sharedMaterials = new[] { fill, outline };
            }
        }
    }

    private static GameObject CreateChip(string name, Transform parent, Mesh mesh, Material material,
        Vector3 position, Quaternion rotation)
    {
        var chip = new GameObject(name);
        chip.hideFlags = HideFlags.DontSave;
        chip.transform.SetParent(parent, true);
        chip.transform.SetPositionAndRotation(position, rotation);
        chip.AddComponent<MeshFilter>().sharedMesh = mesh;
        chip.AddComponent<MeshRenderer>().sharedMaterial = material;
        return chip;
    }
}
