using UnityEngine;

public class CatGameManager : MonoBehaviour
{
    public GameObject[] catFacePrefabs; // 고양이 얼굴 프리팹 배열 (1번부터 5번 프리팹까지 사용)
    public Transform dropPoint; // 고양이 얼굴이 떨어질 시작 지점
    private GameObject currentCatFace; // 현재 드롭 중인 고양이 얼굴
    private bool isCatFaceReadyToDrop = false; // 고양이 얼굴이 떨어질 준비 여부

    void Start()
    {
        SpawnCatFace(); // 첫 번째 고양이 얼굴 생성
    }

    void Update()
    {
        // 고양이 얼굴이 존재하는 경우에만 처리
        if (currentCatFace != null)
        {
            // 고양이 얼굴을 낙하하기 전에 방향키로 좌우 이동
            if (!isCatFaceReadyToDrop)
            {
                if (Input.GetKeyDown(KeyCode.LeftArrow))
                {
                    currentCatFace.transform.position += Vector3.left;
                   
                }
                if (Input.GetKeyDown(KeyCode.RightArrow))
                {
                    currentCatFace.transform.position += Vector3.right;
                   
                }
            }

            // 스페이스바를 눌렀을 때 고양이 얼굴을 떨어뜨림
            if (Input.GetKeyDown(KeyCode.Space) && !isCatFaceReadyToDrop)
            {
                isCatFaceReadyToDrop = true; // 낙하 준비 완료 상태로 변경
                Rigidbody2D rb = currentCatFace.GetComponent<Rigidbody2D>();
                if (rb != null)
                {
                    rb.gravityScale = 1; // 중력 적용 (고양이 얼굴이 떨어지도록)
                   
                }
                // 고양이가 떨어진 후 1초 후에 새로운 고양이 스폰
                Invoke("SpawnCatFace", 1f); // 여기서 시간을 1초로 설정
            }
        }
    }

    // 새로운 고양이를 스폰하는 함수
    void SpawnCatFace()
    {
        int index = UnityEngine.Random.Range(0, 5); // 0~4 범위에서 무작위로 프리팹 선택 (1번부터 5번까지)
        currentCatFace = Instantiate(catFacePrefabs[index], dropPoint.position, Quaternion.identity); // 중앙에서 고양이 얼굴 생성
        isCatFaceReadyToDrop = false; // 낙하 준비 상태 해제

        // 처음 생성할 때 중력을 적용하지 않음 (스페이스바를 누르기 전까지)
        Rigidbody2D rb = currentCatFace.GetComponent<Rigidbody2D>();
        if (rb != null)
        {
            rb.gravityScale = 0; // 스폰 시 중력 비활성화
            Debug.Log("Rigidbody found on: " + currentCatFace.name);
        }
        else
        {
            Debug.LogError("No Rigidbody2D found on " + currentCatFace.name);
        }

        // 생성된 고양이 얼굴의 이름 로그
        Debug.Log("Spawned Cat Face: " + currentCatFace.name);
    }

    // 충돌 감지 메서드
    void OnCollisionEnter2D(Collision2D collision)
    {
        Debug.Log("Collision detected with: " + collision.gameObject.name);

        // 충돌한 오브젝트가 CatFace 태그를 가지고 있는지 확인
        if (collision.gameObject.CompareTag("CatFace"))
        {
            Debug.Log("Valid collision with: " + collision.gameObject.name);
            MergeCatFace(collision.gameObject); // 충돌한 고양이 얼굴과 합성
        }
        else if (collision.gameObject.CompareTag("Ground")) // 지면과의 충돌 감지
        {
            Debug.Log("Cat face has landed on the ground: " + currentCatFace.name);
        }
        else
        {
            Debug.LogWarning("Collision with a non-CatFace object: " + collision.gameObject.tag);
        }
    }

    // 고양이 얼굴 합성 메서드
    void MergeCatFace(GameObject hitCatFace)
    {
        Debug.Log("Attempting to merge cat faces: " + currentCatFace.name + " with " + hitCatFace.name);
       
        int currentIndex = GetPrefabIndex(currentCatFace); // 현재 고양이 얼굴의 인덱스
        int hitIndex = GetPrefabIndex(hitCatFace); // 충돌한 고양이 얼굴의 인덱스

        Debug.Log("Current cat index: " + currentIndex + ", Hit cat index: " + hitIndex);

        // 충돌한 고양이 얼굴이 같을 때만 합성, 그리고 다음 프리팹이 존재하는 경우에만 합성
        if (currentIndex == hitIndex && currentIndex < catFacePrefabs.Length - 1)
        {
            int newIndex = currentIndex + 1;
            Vector3 mergePosition = currentCatFace.transform.position;

            // 합성 후 새로운 고양이 얼굴 생성
            GameObject newCatFace = Instantiate(catFacePrefabs[newIndex], mergePosition, Quaternion.identity);
            Debug.Log("Merged into new cat face: " + newCatFace.name);

            // 충돌한 고양이 얼굴과 현재 고양이 얼굴 제거
            Destroy(hitCatFace);
            Destroy(currentCatFace);

            // 새로운 합성된 고양이 얼굴로 대체
            currentCatFace = newCatFace;
            currentCatFace.GetComponent<Rigidbody2D>().gravityScale = 0; // 새로 생성된 고양이 얼굴이 떨어지지 않도록 중력 비활성화
            Debug.Log("New cat face ready: " + currentCatFace.name);
        }
        else
        {
            Debug.Log("Merge condition not met. CurrentIndex: " + currentIndex + ", HitIndex: " + hitIndex);
        }
    }

    // 고양이 얼굴 프리팹의 인덱스를 가져오는 메서드
    int GetPrefabIndex(GameObject catFace)
    {
        for (int i = 0; i < catFacePrefabs.Length; i++)
        {
            // 프리팹 이름에서 "(Clone)"을 제거하고 비교
            if (catFacePrefabs[i].name == catFace.name.Replace("(Clone)", "").Trim())
            {
                return i;
            }
        }
        return -1; // 프리팹을 찾지 못한 경우 -1 반환
    }
}