using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class CrackableRock : MonoBehaviour
{

    [SerializeField] Sprite[] crackSprites;
    [SerializeField] Button nextButton;

    [SerializeField] float moveSpeed = 5f;
    [SerializeField] Vector2 startOffset = new Vector2(-5f, 10f);
    [SerializeField] float rotationSpeed = 360f;

    [SerializeField] float shakeDuration = 0.1f;
    [SerializeField] float shakeMagnitude = 0.1f;

    private int currentClickCount = 0;
    private SpriteRenderer spriteRenderer;
    private Vector3 targetPosition;
    private bool canClick = false;

    void Start()
    {
        spriteRenderer = GetComponent<SpriteRenderer>();

        if (nextButton != null)
            nextButton.interactable = false;

        targetPosition = transform.position;

        transform.position = new Vector3(
            targetPosition.x + startOffset.x,
            targetPosition.y + startOffset.y,
            targetPosition.z
        );
    }

    void Update()
    {
        if (!canClick)
        {

            transform.position = Vector3.MoveTowards(transform.position, targetPosition, moveSpeed * Time.deltaTime);
            transform.Rotate(Vector3.forward * rotationSpeed * Time.deltaTime);
            if (Vector3.Distance(transform.position, targetPosition) < 0.01f)
            {

                transform.position = targetPosition;
                transform.rotation = Quaternion.identity;

                canClick = true;
            }
        }
    }

    void OnMouseDown()
    {
        if (!canClick) return;

        StartCoroutine(ShakeRock());

        currentClickCount++;

        if (currentClickCount <= crackSprites.Length)
        {
            int spriteIndex = currentClickCount - 1;
            if (spriteRenderer != null && crackSprites[spriteIndex] != null)
            {
                spriteRenderer.sprite = crackSprites[spriteIndex];
            }
        }
        else
        {
            BreakRock();
        }
    }

    IEnumerator ShakeRock()
    {
        float elapsed = 0.0f;

        while (elapsed < shakeDuration)
        {
            float x = Random.Range(-1f, 1f) * shakeMagnitude;
            float y = Random.Range(-1f, 1f) * shakeMagnitude;

            transform.position = targetPosition + new Vector3(x, y, 0);

            elapsed += Time.deltaTime;
            yield return null;
        }

        transform.position = targetPosition;
    }

    void BreakRock()
    {
        if (nextButton != null)
            nextButton.interactable = true;
        gameObject.SetActive(false);
    }
}