using UnityEngine;

public class PlayerController : MonoBehaviour {
    public float moveSpeed = 5f;
    public LayerMask wallLayer;
    public GameObject projectilePrefab;

    BoxCollider2D playerCollider;
    Vector3 lastMoveDirection = Vector3.zero;
    float shootTimer = 0f;
    float shootInterval = 0.5f;
    GameController gameController;
    
    SpriteRenderer spriteRenderer;
    Animator animator;

    void Start() {
        playerCollider = GetComponent<BoxCollider2D>();
        gameController = FindFirstObjectByType<GameController>();
        spriteRenderer = GetComponent<SpriteRenderer>(); // Hämta SpriteRenderer
        animator = GetComponent<Animator>();
    }

    void Update() {
        float moveX = Input.GetAxis("Horizontal");
        float moveY = Input.GetAxis("Vertical");
        
        bool isMoving = (moveX != 0 || moveY != 0);
        animator.SetBool("isMoving", isMoving);


        Vector3 move = new Vector3(moveX, moveY, 0f) * moveSpeed * Time.deltaTime;
        Vector3 targetPosition = transform.position + move;

        if (moveX != 0 || moveY != 0) {
            lastMoveDirection = new Vector3(moveX, moveY, 0f).normalized;
        }

        if (!IsBlocked(targetPosition)) {
            transform.position = targetPosition;
        }

        // Flippa sprite beroende på riktning
        if (moveX > 0) {
            spriteRenderer.flipX = false; // Tittar åt höger
        } else if (moveX < 0) {
            spriteRenderer.flipX = true; // Tittar åt vänster
        }

        // Skjut bara om vi rör oss
        if (lastMoveDirection != Vector3.zero) {
            shootTimer += Time.deltaTime;
            if (shootTimer >= shootInterval) {
                ShootProjectile();
                shootTimer = 0f;
            }
        }
    }

    bool IsBlocked(Vector3 targetPos) {
        Bounds bounds = playerCollider.bounds;
        return Physics2D.OverlapBox(targetPos, bounds.size, 0f, wallLayer) != null;
    }

    void ShootProjectile() {
        GameObject projectile = Instantiate(projectilePrefab, transform.position, Quaternion.identity);
        projectile.GetComponent<ShotAway>().SetDirection(lastMoveDirection);
        Destroy(projectile, 3f);
    }

    
    void OnTriggerEnter2D(Collider2D other) {
        if (other.tag == "Enemy") {
            gameController.DrawHealth();
        }
    }
}