using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Enemie_Movement_Kamikaze : MonoBehaviour
{
    public float speed = 3f;        // Bewegungsgeschwindigkeit
    private Transform player; // Referenz auf den Spieler
    public int life = 2;
    private Slider slider;
    public GameObject uiElement;
    Enemie_Spawn_System enemie_Spawn_System;
    [SerializeField] float dmg = 0.0f;

    void Start()
    {
        // Spieler-Objekt finden
        player = GameObject.FindGameObjectWithTag("Starship").transform;
        slider = FindObjectOfType<Slider>();
        enemie_Spawn_System = GameObject.Find("Enemie_Spawner_System").GetComponent<Enemie_Spawn_System>();
    }

    void Update()
    {
        if (player == null) return; // Falls kein Spieler gefunden wurde, nichts tun

        // 1. Richtung zum Spieler berechnen
        Vector2 direction = (player.position - transform.position).normalized;

        // 2. Gegner drehen (damit er den Spieler anvisiert)
        float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
        transform.rotation = Quaternion.Euler(0, 0, angle - 90);

        // 3. Bewegung zum Spieler
        transform.position = Vector2.MoveTowards(transform.position, player.position, speed * Time.deltaTime);
    }

    private void OnTriggerEnter2D(Collider2D other)
    {
        if (other.CompareTag("Player Bullet"))
        {
            Bullet_movement bulletScript = other.gameObject.GetComponent<Bullet_movement>();

            if (bulletScript != null)
            {
                life--;
                Debug.Log("Gegner Getroffen! -2");

                if (life <= 0)
                {
                    Destroy(gameObject);
                    enemie_Spawn_System.ChangeEnemyCounter(-1);
                }
            }
        }

        if (other.CompareTag("Starship"))
        {
            Destroy(gameObject);
            enemie_Spawn_System.ChangeEnemyCounter(-1);
            slider.value -= dmg;
        }

        if (other.CompareTag("Starship") && slider.value <= 0f) // zerstört das Starship bei 0hp oder weniger
        {
            Destroy(other.gameObject);
            //ChangeEnemyCounter(-1);

            if (other.CompareTag("Dead"))
            {
                uiElement.SetActive(true);
            }
        }
    }
}
