using UnityEngine;

public class Bullet : MonoBehaviour
{
    public float speed = 20f;
    private Rigidbody2D rb;
    public int damage = 1;
    public int maxBounces = 3;
    private int currentBounces = 0;

    private void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        rb.velocity = transform.right * speed;
    }

    private void Update()
    {
        RotateInMovementDirection();
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.layer == LayerMask.NameToLayer("Roof") || collision.gameObject.layer == LayerMask.NameToLayer("Ground"))
        {
            if (currentBounces < maxBounces)
            {
                Deflect(collision);
                currentBounces++;
            }
            else
            {
                Destroy(gameObject);
            }
        }
        else
        {
            if (gameObject.tag == "EnemyBullet")
            {
                if (collision.gameObject.tag == "Player")
                {
                    PlayerHealth player = collision.collider.GetComponent<PlayerHealth>();
                    if (player != null)
                    {
                        player.TakeDamage(damage);
                        Destroy(gameObject);
                    }
                }
            }

            Destructible destructible = collision.gameObject.GetComponent<Destructible>();
            if (destructible != null)
            {
                destructible.OnHit();
                Destroy(gameObject);
            }


            if (collision.gameObject.tag == "Platform")
            {
                Debug.Log("Bullet hit a platform");
            }
            else
            {
                Destroy(gameObject);
            }


        }
    }

    private void Deflect(Collision2D collision)
    {
        Debug.Log("Bullet hit a deflecting surface");

        ContactPoint2D contact = collision.GetContact(0);
        Vector2 normal = contact.normal;
        Debug.Log("Normal: " + normal);

        Vector2 reflectedVelocity = Vector2.Reflect(rb.velocity, normal);
        Debug.Log("Reflected Velocity (before normalization): " + reflectedVelocity);

        reflectedVelocity = reflectedVelocity.normalized * speed;
        Debug.Log("Reflected Velocity (after normalization): " + reflectedVelocity);

        rb.velocity = reflectedVelocity;
    }

    private void RotateInMovementDirection()
    {
        Vector2 velocity = rb.velocity;

        float angle = Mathf.Atan2(velocity.y, velocity.x) * Mathf.Rad2Deg;
        transform.rotation = Quaternion.Euler(new Vector3(0, 0, angle));
    }
}
