using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    public GameObject respawnPosition;

    public GameObject deadBody;

    public TimerAction timer;

    [Header("Movement Settings")]
    public float moveSpeed = 8f;
    public float jumpForce = 12f;

    public float acceleration = 10f;
    public float deceleration = 10f;

    public LayerMask groundLayer;
    public Transform groundCheck;

    private Rigidbody2D rb;
    private float horizontal;
    private bool isGrounded;

    [Header("Animation")]
    public Animator anim;
    public ParticleSystem dust;

    private float lastDeathTime = 0f;

    private void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        rb.freezeRotation = true;
    }

    private void Update()
    {
        horizontal = Input.GetAxisRaw("Horizontal");

        isGrounded = Physics2D.OverlapCircle(groundCheck.position, 0.2f, groundLayer);

        if ((Input.GetButtonDown("Jump") || Input.GetKeyDown(KeyCode.W)) && isGrounded)
        {
            dust.Play();
            rb.linearVelocity = new Vector2(rb.linearVelocity.x, jumpForce);
        }

        //Animation of the character
        float horizontalSpeed = rb.linearVelocity.x; // Guardem la velocitat real (amb signe)
        anim.SetFloat("Speed", Mathf.Abs(horizontalSpeed) / 5f);

        //Positive speed right
        if (horizontalSpeed > 0.1f)
        {
            anim.gameObject.transform.localScale = new Vector3(-1, 1, 1);
        }
        //Negative speed left
        else if (horizontalSpeed < -0.1f)
        {
            anim.gameObject.transform.localScale = new Vector3(1, 1, 1);
        }
    }

    private void FixedUpdate()
    {
        float targetSpeed = horizontal * moveSpeed;

        float speedDif = targetSpeed - rb.linearVelocity.x;
        float accelRate = (Mathf.Abs(targetSpeed) > 0.01f) ? acceleration : deceleration;

        float movement = speedDif * accelRate;

        rb.AddForce(movement * Vector2.right, ForceMode2D.Force);
    }

    public void KillPlayer()
    {
        // Prevent dying more than once every 0.5 seconds
        if (Time.time < lastDeathTime + 0.5f) return;
        lastDeathTime = Time.time;

        Instantiate(deadBody, gameObject.transform.position, Quaternion.identity);
        gameObject.transform.position = respawnPosition.transform.position;

        if (timer != null) timer.ResetTime();
    }
}