using UnityEngine;

public class BossShip : MonoBehaviour
{
    [SerializeField] private float speed = 8f;
    [SerializeField] private float health = 3f;
    [SerializeField] private int pointsReward = 500;

    private float currentHealth;
    private Rigidbody2D rb;
    private SpriteRenderer spriteRenderer;
    private bool movingRight = true;

    private void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        spriteRenderer = GetComponent<SpriteRenderer>();
        currentHealth = health;
    }

    private void Update()
    {
        float direction = movingRight ? 1f : -1f;
        rb.velocity = new Vector2(direction * speed, -1f);

        if (transform.position.y < -10f ||
            transform.position.x < -12f ||
            transform.position.x > 12f)
        {
            Destroy(gameObject);
        }
    }

    private void OnTriggerEnter2D(Collider2D other)
    {
        if (!other.CompareTag("PlayerBullet")) return;
        TakeDamage(1f);
        Destroy(other.gameObject);
    }

    public void TakeDamage(float damage)
    {
        currentHealth -= damage;
        StartCoroutine(FlashDamage());
        if (currentHealth <= 0f)
            Die();
    }

    private void Die()
    {
        if (AudioManager.Instance != null)
            AudioManager.Instance.PlayExplosion(transform.position);
        if (GameManager.Instance != null)
            GameManager.Instance.AddScore(pointsReward);
        ExplosionEffect.Spawn(transform.position, 2.5f, 40);
        Destroy(gameObject);
    }

    private System.Collections.IEnumerator FlashDamage()
    {
        if (spriteRenderer != null) spriteRenderer.color = Color.red;
        yield return new WaitForSeconds(0.1f);
        if (spriteRenderer != null) spriteRenderer.color = Color.white;
    }

    public void SetDirection(bool right)
    {
        movingRight = right;
        if (spriteRenderer != null)
            spriteRenderer.flipX = !right;
    }
}
