using UnityEngine;

public class EnvironmentBuilder : MonoBehaviour
{
    [Header("Cliff Prefabs")]
    public GameObject[] largeCliffs;
    public GameObject[] smallCliffs;

    [Header("Grid Settings")]
    public int gridWidth = 3;
    public int gridHeight = 2;
    public float spacingMultiplier = 1.05f;
    public float verticalOffset = 0f;

    [ContextMenu("Generate Environment")]
    public void GenerateEnvironment()
    {
        ClearPrevious();

        Vector3 startPos = transform.position;

        for (int x = 0; x < gridWidth; x++)
        {
            for (int z = 0; z < gridHeight; z++)
            {
                GameObject prefab = largeCliffs[Random.Range(0, largeCliffs.Length)];
                Vector3 size = GetMeshSize(prefab);
                float xOffset = x * size.x * spacingMultiplier;
                float zOffset = z * size.z * spacingMultiplier;

                Vector3 pos = new Vector3(xOffset, 0f, zOffset) + startPos;
                float correctedY = GetCorrectedYPosition(prefab);
                pos.y = verticalOffset + correctedY;

                Instantiate(prefab, pos, Quaternion.identity, transform);
            }
        }

        for (int i = 0; i < smallCliffs.Length; i++)
        {
            GameObject prefab = smallCliffs[i];
            Vector3 size = GetMeshSize(prefab);
            Vector3 randomOffset = new Vector3(
                Random.Range(-size.x, gridWidth * size.x),
                0f,
                Random.Range(-size.z, gridHeight * size.z)
            );

            float correctedY = GetCorrectedYPosition(prefab);
            randomOffset.y = verticalOffset + correctedY;

            Instantiate(prefab, randomOffset + startPos, Quaternion.identity, transform);
        }
    }

    private Vector3 GetMeshSize(GameObject obj)
    {
        MeshFilter mf = obj.GetComponentInChildren<MeshFilter>();
        if (mf == null || mf.sharedMesh == null)
            return Vector3.one;

        Bounds bounds = mf.sharedMesh.bounds;
        Vector3 scale = obj.transform.localScale;
        return Vector3.Scale(bounds.size, scale);
    }

    private float GetCorrectedYPosition(GameObject obj)
    {
        MeshFilter mf = obj.GetComponentInChildren<MeshFilter>();
        if (mf == null || mf.sharedMesh == null)
            return 0f;

        Bounds bounds = mf.sharedMesh.bounds;
        float pivotBottomY = bounds.min.y * obj.transform.localScale.y;
        return -pivotBottomY;
    }

    private void ClearPrevious()
    {
        for (int i = transform.childCount - 1; i >= 0; i--)
        {
            DestroyImmediate(transform.GetChild(i).gameObject);
        }
    }
}
