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

public class CrackableRock : MonoBehaviour
{
    [Header("Rock Settings")]
    public Sprite[] crackSprites;
    public Button nextButton;

    [Header("Movement Settings")]
    public float moveSpeed = 5f;
    public Vector2 startOffset = new Vector2(-5f, 10f);

    [Header("Shake Settings")]
    public float shakeDuration = 0.1f; 
    public 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);

            if (Vector3.Distance(transform.position, targetPosition) < 0.01f)
            {
                transform.position = targetPosition;
                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);
    }
}