using UnityEngine;

// 슬라이딩 장애물 패턴이 켜질 때마다 매달린 장애물 위치를 섞는다.
public class SlideObstaclePattern : MonoBehaviour
{
    public Transform[] obstacles; // 위치를 바꿀 고공 장애물들
    public float[] xPositions = { -1.65f, -0.55f, 0.55f, 1.65f }; // 선택 가능한 로컬 x 위치
    public float minSpacing = 1.5f; // 두 장애물 사이의 최소 간격

    private void OnEnable()
    {
        if(obstacles == null || obstacles.Length == 0 || xPositions == null || xPositions.Length == 0)
        {
            return;
        }

        int firstIndex = Random.Range(0, xPositions.Length);

        if(obstacles.Length == 1 || xPositions.Length == 1)
        {
            PlaceObstacle(obstacles[0], xPositions[firstIndex]);
            return;
        }

        int secondIndex = PickSecondIndex(firstIndex);

        float leftX = xPositions[firstIndex];
        float rightX = xPositions[secondIndex];

        if(leftX > rightX)
        {
            float temp = leftX;
            leftX = rightX;
            rightX = temp;
        }

        PlaceObstacle(obstacles[0], leftX);
        PlaceObstacle(obstacles[1], rightX);
    }

    private int PickSecondIndex(int firstIndex)
    {
        for(int i = 0; i < 12; i++)
        {
            int candidateIndex = Random.Range(0, xPositions.Length);

            if(candidateIndex != firstIndex && Mathf.Abs(xPositions[candidateIndex] - xPositions[firstIndex]) >= minSpacing)
            {
                return candidateIndex;
            }
        }

        int bestIndex = firstIndex;
        float bestDistance = 0f;

        for(int i = 0; i < xPositions.Length; i++)
        {
            float distance = Mathf.Abs(xPositions[i] - xPositions[firstIndex]);

            if(distance > bestDistance)
            {
                bestDistance = distance;
                bestIndex = i;
            }
        }

        return bestIndex;
    }

    private void PlaceObstacle(Transform obstacle, float xPosition)
    {
        if(obstacle == null)
        {
            return;
        }

        Vector3 localPosition = obstacle.localPosition;
        localPosition.x = xPosition;
        obstacle.localPosition = localPosition;
    }
}
