using System.Collections;
using UnityEngine;
using UnityEngine.SceneManagement;

public class CarController : MonoBehaviour
{
    public float speed = 0; // Adjust this according to your needs
    public float acceleration = 15f; // Adjust acceleration for smooth movement
    public float deceleration = 0.98f; // Adjust deceleration for smooth stopping
    public Rigidbody2D rb; // Reference to the Rigidbody component
    public string scene = "ResultScene10";
    public int stars = 0;
    public int m = 0;
    public int t = 5;
    public GameObject flag;
    public GameObject car;

    bool isMoving = false;

    Vector2 startPos;

    void Start()
    {
        rb = GetComponent<Rigidbody2D>(); // Get the Rigidbody component
	rb.gravityScale = 2f;
        flag = GameObject.Find("flag");
        car = GameObject.Find("car");
        Application.targetFrameRate = 60;
    }

    void Update()
    {
        if (Input.GetMouseButtonDown(0) && !isMoving)
        {
            startPos = Input.mousePosition;
        }
        else if (Input.GetMouseButtonUp(0) && !isMoving)
        {
            Vector2 endPos = Input.mousePosition;
            float swipeLength = endPos.x - startPos.x;

            if (swipeLength > 30)
            {
                speed += Mathf.Pow(swipeLength / PlayerPrefs.GetInt("Speed")*2, 2.2f)* 36;
                GetComponent<AudioSource>().Play();
                isMoving = true;
            }
        }

        if (isMoving)
        {
            rb.velocity = new Vector2(speed, rb.velocity.y);

            

            // Apply deceleration to gradually slow down
            speed *= deceleration;

            // Check if speed is negligible to stop the car
            if (Mathf.Abs(speed) < 0.01f)
            {
                speed = 0;
                StartCoroutine(LoadResultSceneWithDelay());
            }
        }
    }

    IEnumerator LoadResultSceneWithDelay()
    {
        yield return new WaitForSeconds(0.3f);

        float length = flag.transform.position.x - car.transform.position.x;

        isMoving = false;

        if (length <= 2)
            stars = 5 - m;
        else if (length > 2 && length <= 4)
            stars = 4 - m;
        else if (length > 4 && length <= 5.5f)
            stars = 3 - m;
        else if (length > 5.5f && length <= 11)
            stars = 2 - m;
        else if (length > 11)
            stars = 1 - m;

        if (stars < 0) stars = 0;

        SaveLevel(t);
        SaveStars(stars);
        PlayerPrefs.SetInt("Stars", stars);

        SceneManager.LoadScene(scene);
    }

    void SaveLevel(int level)
    {
        PlayerPrefs.SetInt("Level", level);
        PlayerPrefs.Save();
    }

    void SaveStars(int starsCount)
    {
        PlayerPrefs.SetInt("Stars", starsCount);
        PlayerPrefs.Save();
    }
}