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

public class CarController11 : MonoBehaviour
{
    public float speed = 0; // Adjust this according to your needs
    public float acceleration = 435f; // Adjust acceleration for smooth movement
    public float deceleration = 0.6f; // Adjust deceleration for smooth stopping
    public Rigidbody2D rb; // Reference to the Rigidbody component
    public string scene = "ResultScene11";
    public int stars = 0;
    public int level = 11;
    public GameObject flag;
    public GameObject car;
    public float x = 1.0f;
    public float swipeThreshold = 30f; // Adjust the swipe threshold

    bool isMoving = false;
    Vector2 startPos;

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

    void ReplaceCollider()
    {
      // Remove BoxCollider if it exists
      BoxCollider2D boxCollider = GetComponent<BoxCollider2D>();
      if (boxCollider != null)
          Destroy(boxCollider);


      CapsuleCollider2D capsuleCollider = gameObject.AddComponent<CapsuleCollider2D>();
      capsuleCollider.size = new Vector2(2.2f, 0.9f); // Default size
      capsuleCollider.offset = new Vector2(0, 0.2f); // Offset
      capsuleCollider.direction = CapsuleDirection2D.Horizontal; // Horizontal direction

      // Calculate the scale of the object
      Vector3 scale = transform.lossyScale;

      // Scale the collider horizontally based on the maximum scale component
      float maxSize = Mathf.Max(scale.x, scale.y, scale.z);
      capsuleCollider.size = new Vector2(capsuleCollider.size.x * maxSize, capsuleCollider.size.y);
    }

    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;

            // Check if the swipe is in the forward direction (to the right)
            if (swipeLength > swipeThreshold)
            {
                // Calculate speed based on swipe length and acceleration
                speed = swipeLength / PlayerPrefs.GetInt("Speed");
                //speed = speed * rb.mass;
                rb.velocity = new Vector2(speed, 0f);

                GetComponent<AudioSource>().Play();
                isMoving = true;
            }
        }

        // Move the car forward when it's supposed to be moving
        if (isMoving)
        {

            // Apply a deceleration factor to gradually slow down
            rb.velocity *= deceleration;

            // Check if the car is almost stopped
            if (speed < 0.1f)
            {
                StartCoroutine(DelayedExecution());
            }
        }
    }

    IEnumerator DelayedExecution()
    {
        yield return new WaitForSeconds(x);
        float length = flag.transform.position.x - car.transform.position.x;
        isMoving = false; // Reset the flag when the car stops moving

        // Determine stars based on distance
        if (length <= 2)
            stars = 5;
        else if (length <= 4)
            stars = 4;
        else if (length <= 6)
            stars = 3;
        else if (length <= 14)
            stars = 2;
        else
            stars = 1;

        // Save level and stars
        SaveLevel(level);
        SaveStars(stars);
        PlayerPrefs.SetInt("Stars", stars);
        SceneManager.LoadScene(scene);
    }

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

    // Method to save the stars count
    void SaveStars(int starsCount)
    {
        PlayerPrefs.SetInt("Stars", starsCount);
        PlayerPrefs.Save(); // Save the PlayerPrefs to disk
    }
}
