using UnityEngine;

public class FutureCar : MonoBehaviour
{
    [Header("Main Settings")]
    [Tooltip("Check to float in place, uncheck to move back and forth.")]
    public bool isFloatingInPlace = true;

    [Header("Floating Options (Only used if checked above)")]
    public float floatSpeed = 1f;
    public float floatAmplitude = 0.5f;

    [Header("Moving Options (Only used if unchecked above)")]
    public float moveSpeed = 5f;
    public float travelDistance = 20f;
    public float rotationSpeed = 3f;

    private Vector3 startPosition;
    private Vector3 targetPosition;
    private bool movingToTarget = true;
    private float initialY;

    void Start()
    {
        // Store the starting spot
        startPosition = transform.position;
        initialY = transform.position.y;

        // Calculate the end of the patrol path based on the car's initial forward direction
        targetPosition = startPosition + (transform.forward * travelDistance);
    }

    void Update()
    {
        if (isFloatingInPlace)
        {
            ApplyFloatingMotion();
        }
        else
        {
            ApplyPatrolMotion();
        }
    }

    private void ApplyFloatingMotion()
    {
        // Simple vertical bobbing using a Sine wave
        float newY = initialY + (Mathf.Sin(Time.time * floatSpeed) * floatAmplitude);
        transform.position = new Vector3(transform.position.x, newY, transform.position.z);
    }

    private void ApplyPatrolMotion()
    {
        // Determine which end of the line we are headed to
        Vector3 destination = movingToTarget ? targetPosition : startPosition;

        // 1. Move the car
        transform.position = Vector3.MoveTowards(transform.position, destination, moveSpeed * Time.deltaTime);

        // 2. Rotate the car to face the current destination
        Vector3 direction = (destination - transform.position).normalized;
        if (direction != Vector3.zero)
        {
            Quaternion lookRotation = Quaternion.LookRotation(direction);
            transform.rotation = Quaternion.Slerp(transform.rotation, lookRotation, Time.deltaTime * rotationSpeed);
        }

        // 3. If we are very close to the destination, flip the boolean to go the other way
        if (Vector3.Distance(transform.position, destination) < 0.1f)
        {
            movingToTarget = !movingToTarget;
        }
    }

    // This helps you see the path in the Scene View without pressing play
    private void OnDrawGizmosSelected()
    {
        if (!isFloatingInPlace)
        {
            Gizmos.color = Color.cyan;
            Vector3 endPoint = Application.isPlaying ? targetPosition : transform.position + (transform.forward * travelDistance);
            Vector3 startPoint = Application.isPlaying ? startPosition : transform.position;

            Gizmos.DrawLine(startPoint, endPoint);
            Gizmos.DrawWireSphere(endPoint, 0.5f);
        }
    }
}
