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

public class Droid : MonoBehaviour
{
    private bool jumpKeyWasPressed;
    private float horizontalInput;
    private bool isGrounded;
    private Rigidbody rigidbodyComponent;

    private int energyDisksCollected = 0;
    private float speedMultiplier = 1f;
    private float jumpMultiplier = 1f;
    private bool isInvincible = false; // Empêche les dégâts multiples


    [SerializeField] private int life = 2; // Niveau de vie initial
    [SerializeField] private GameObject fusee;
    [SerializeField] private UIManager uiManager;

    void Start()
    {
        rigidbodyComponent = GetComponent<Rigidbody>();

        // Recherche automatique du UIManager
        if (uiManager == null)
        {
            uiManager = FindObjectOfType<UIManager>();
            if (uiManager == null)
            {
                Debug.LogError("UIManager is not assigned and could not be found in the scene!");
            }
        }
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            jumpKeyWasPressed = true;
        }

        horizontalInput = Input.GetAxis("Horizontal");

        if (Input.GetKeyDown(KeyCode.S))
        {
            LaunchRocket();
        }

        // Vérifie si le droïde tombe sous -10 en Y
        if (transform.position.y < -10)
        {
            TriggerGameOver();
        }
    }

    private void FixedUpdate()
    {
        rigidbodyComponent.velocity = new Vector3(horizontalInput * 2 * speedMultiplier, rigidbodyComponent.velocity.y, 0);

        if (jumpKeyWasPressed && isGrounded)
        {
            rigidbodyComponent.AddForce(Vector3.up * 5 * jumpMultiplier, ForceMode.VelocityChange);
            jumpKeyWasPressed = false;
        }
    }

    private void OnCollisionStay(Collision collision)
    {
        isGrounded = true;
    }

    private void OnCollisionExit(Collision collision)
    {
        isGrounded = false;
    }

    private IEnumerator InvincibilityDelay()
{
    isInvincible = true; // Active l'invincibilité
    yield return new WaitForSeconds(1.0f); // Attendre 1 seconde (modifiable)
    isInvincible = false; // Désactive l'invincibilité
}


    private void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.layer == 8) // Disques énergétiques
        {
            Destroy(other.gameObject);
            energyDisksCollected++;
            life++; // Augmente la vie
            Debug.Log("Vie augmentée : " + life);

            // Augmente les capacités après 3 disques collectés
            if (energyDisksCollected == 3)
            {
                speedMultiplier = 2f;
                jumpMultiplier = 2f;
            }
        }

        if (other.gameObject.layer == 14) // Ennemis
        {
            life -= 2; // Réduit la vie
            Debug.Log("Vie réduite : " + life);
            Destroy(other.gameObject);
             StartCoroutine(InvincibilityDelay());

            if (life <= 0)
            {
                TriggerGameOver();
            }
        }

        if (other.tag == "Exit")
        {
            SceneManager.LoadScene("scene1");
        }
    }

    private void LaunchRocket()
    {
        GameObject rocket = Instantiate(fusee, transform.position, transform.rotation);
        Rigidbody rocketRigidbody = rocket.GetComponent<Rigidbody>();

        rocketRigidbody.velocity = new Vector3(20, rocketRigidbody.velocity.y, 0);
    }

    private void TriggerGameOver()
    {
        if (uiManager != null)
        {
            uiManager.TriggerGameOver();
        }
        Debug.Log("Game Over");
    }
}