using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlatformerPlayerController : MonoBehaviour
{
    [SerializeField] private Rigidbody2D rb;

    [SerializeField] private float Speed;

    [SerializeField] private float JumpForce;
    [SerializeField] private float FallMultiplier;
    [SerializeField] private float SmallJumpForce;

    [SerializeField] private bool IsGrounded;
    [SerializeField] private LayerMask WhatIsGround;
    [SerializeField] private Transform FeetPos;
    [SerializeField] private float CheckRadius;

    [SerializeField] private float CoyoteTime;
    [SerializeField] private float CoyoteTimer;

    [SerializeField] private int Jumps = 1;
    [SerializeField] private int JumpCounter;

    private Vector2 Move;

    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    void Update()
    {
        Move.x = Input.GetAxisRaw("Horizontal") * Speed;
        Move.y = rb.velocity.y;

        IsGrounded = Physics2D.OverlapCircle(FeetPos.position, CheckRadius, WhatIsGround);

        if (!IsGrounded)
        {
            if (CoyoteTimer <= CoyoteTime)
            {
                if (Input.GetButtonDown("Jump"))
                {
                    Move.y = JumpForce;
                    JumpCounter = Jumps - 1;
                }
            }
            else
            {
                if(JumpCounter > 0)
                {
                    Move.y = JumpForce;
                    JumpCounter--;
                }
            }
        }

        if (IsGrounded)
        {
            JumpCounter = Jumps;
            CoyoteTimer = 0;
            if (Input.GetButtonDown("Jump"))
            {
                Move.y = JumpForce;
                JumpCounter--;
            }
        }
        else
        {
            CoyoteTimer += Time.deltaTime;

            if (rb.velocity.y < 0)
            {
                var fallspeed = Vector2.up * Physics2D.gravity.y * (FallMultiplier - 1) * Time.deltaTime;
                Move.y += fallspeed.y;
            }
            else if (rb.velocity.y > 0 && !Input.GetButton("Jump"))
            {
                var fallspeed = Vector2.up * Physics2D.gravity.y * (SmallJumpForce - 1) * Time.deltaTime;
                Move.y += fallspeed.y;
            }
        }

        rb.velocity = Move;
    }
}
