using DavidJalbert;
using UnityEngine;
using UnityEngine.ProBuilder.MeshOperations;
using UnityEngine.UI;

public class PotentialKineticEnergyScript : MonoBehaviour
{

    [SerializeField] TinyCarController Car;
    [SerializeField] Transform SphereCast;
    [SerializeField] LayerMask GroundLayer;
    [SerializeField] Slider PotentialEnergySlider;
    [SerializeField] Slider KineticEnergyEnergySlider;
    [SerializeField] Slider ThermalSlider;
    [SerializeField] Slider VelocitySlider;
    [SerializeField] float ThermalSpeed;

    [SerializeField] float lerpSpeed = 5f;

    float _triggerHeight;
    float _peakPotential;
    bool _inTrigger;
    private void OnCollisionEnter(Collision collision)
    {
        if (Car.getBody().velocity.magnitude > 1) ThermalSlider.value += 5;

    }
    private void OnTriggerEnter(Collider other)
    {

        if (other.CompareTag("Edge"))
        {
            _triggerHeight = other.transform.position.y;
            PotentialEnergySlider.maxValue = _triggerHeight;
            KineticEnergyEnergySlider.maxValue = _triggerHeight;

            _peakPotential = Car.transform.position.y;
            _inTrigger = true;
        }
    }

    private void OnTriggerExit(Collider other)
    {
        if (other.CompareTag("Edge"))
            _inTrigger = false;
    }

    private void Update()
    {
        VelocitySlider.value = Car.getBody().velocity.magnitude;

        float targetPotential = 0f;
        float targetKinetic = 0f;

        if (_inTrigger && !IsGrounded())
        {
            float potential = Mathf.Clamp(Car.transform.position.y, 0, _triggerHeight);
            targetPotential = potential;

            if (potential > _peakPotential)
                _peakPotential = potential;

            targetKinetic = (potential < _peakPotential) ? _peakPotential - potential : 0f;
        }

        PotentialEnergySlider.value = Mathf.Lerp(PotentialEnergySlider.value, targetPotential, lerpSpeed * Time.deltaTime);
        KineticEnergyEnergySlider.value = Mathf.Lerp(KineticEnergyEnergySlider.value, targetKinetic, lerpSpeed * Time.deltaTime);

        if(Car.getBody().velocity.sqrMagnitude > 1)
            ThermalSlider.value = Mathf.Lerp(ThermalSlider.value, 100, ThermalSpeed * Time.deltaTime);
        else
            ThermalSlider.value = Mathf.Lerp(ThermalSlider.value, 0, .5f * Time.deltaTime);
    }

    private bool IsGrounded() => Physics.CheckSphere(SphereCast.position, .5f, GroundLayer);
}
