using TMPro;
using UnityEngine;

public class TimerAction : MonoBehaviour
{
    public float startTimeSec = 60f;
    private float currentTime;
    public TextMeshProUGUI timerText;

    public PlayerMovement player;

    [Header("Tremble Settings")]
    public float trembleThreshold = 10f; // Start shaking at 10s
    public float shakeAmount = 5f;       // How violent the shake is
    private Vector3 originalTextPosition;

    private void Start()
    {
        currentTime = startTimeSec;
        originalTextPosition = timerText.rectTransform.localPosition;
        DisplayTime(currentTime);
    }

    public void ResetTime()
    {
        currentTime = startTimeSec;
        // Reset position in case it stopped while shaking
        timerText.rectTransform.localPosition = originalTextPosition;
        DisplayTime(currentTime);
    }

    private void Update()
    {
        currentTime -= Time.deltaTime;

        if (currentTime <= 0f)
        {
            player.KillPlayer();
            ResetTime(); // Reset after death
        }

        HandleTremble();
        DisplayTime(currentTime);
    }

    private void HandleTremble()
    {
        if (currentTime <= trembleThreshold && currentTime > 0)
        {
            // Calculate a random offset
            float offsetX = Random.Range(-1f, 1f) * shakeAmount;
            float offsetY = Random.Range(-1f, 1f) * shakeAmount;

            // Apply the shake to the local position
            timerText.rectTransform.localPosition = originalTextPosition + new Vector3(offsetX, offsetY, 0);

            // Optional: Turn text red when trembling
            timerText.color = Color.red;
        }
        else
        {
            // Return to normal position and color
            timerText.rectTransform.localPosition = originalTextPosition;
            timerText.color = Color.white;
        }
    }

    void DisplayTime(float timeToDisplay)
    {
        if (timeToDisplay < 0) timeToDisplay = 0;

        int minutes = Mathf.FloorToInt(timeToDisplay / 60);
        int seconds = Mathf.FloorToInt(timeToDisplay % 60);

        timerText.text = string.Format("{0:00}:{1:00}", minutes, seconds);
    }
}