using UnityEngine;

public class PlayerController : MonoBehaviour
{
    public static PlayerController Instance;

    public float speed = 8f;
    public float fireCooldown = 0.18f;
    public GameObject bulletPrefab;

    private bool movingLeft;
    private bool movingRight;
    private float nextFireTime;

    private void Awake()
    {
        Instance = this;
    }

    private void Start()
    {
        GameManager.Instance?.RegisterPlayer(this);
    }

    private void Update()
    {
        float horizontal = 0f;
        if (movingLeft) horizontal -= 1f;
        if (movingRight) horizontal += 1f;
        horizontal += Input.GetAxisRaw("Horizontal");

        transform.Translate(Vector3.right * horizontal * speed * Time.deltaTime);
        transform.position = new Vector3(Mathf.Clamp(transform.position.x, -7.7f, 7.7f), transform.position.y, 0f);

        if (Input.GetKeyDown(KeyCode.Space) || Input.GetMouseButtonDown(0))
        {
            Fire();
        }
    }

    public void SetMoveLeft(bool value)
    {
        movingLeft = value;
    }

    public void SetMoveRight(bool value)
    {
        movingRight = value;
    }

    public void ResetPlayer()
    {
        transform.position = new Vector3(0f, -3.8f, 0f);
        movingLeft = false;
        movingRight = false;
    }

    public void Fire()
    {
        if (GameManager.Instance != null && GameManager.Instance.CurrentState != GameManager.GameState.Playing)
        {
            return;
        }

        if (Time.time < nextFireTime) return;

        nextFireTime = Time.time + fireCooldown;
        if (bulletPrefab == null)
        {
            bulletPrefab = CreateDefaultBulletPrefab();
        }

        var bullet = Instantiate(bulletPrefab, transform.position + Vector3.up * 0.75f, Quaternion.identity);
        bullet.tag = "PlayerBullet";
        bullet.SetActive(true);

        var bulletComponent = bullet.GetComponent<Bullet>();
        if (bulletComponent == null)
        {
            bullet.AddComponent<Bullet>();
        }

        var renderer = bullet.GetComponent<SpriteRenderer>();
        if (renderer != null)
        {
            renderer.color = Color.yellow;
        }

        var collider = bullet.GetComponent<Collider2D>();
        if (collider != null)
        {
            collider.isTrigger = true;
        }

        var rb = bullet.GetComponent<Rigidbody2D>();
        if (rb == null)
        {
            rb = bullet.AddComponent<Rigidbody2D>();
        }

        rb.gravityScale = 0f;
        rb.bodyType = RigidbodyType2D.Kinematic;
        rb.simulated = true;

        AudioManager.Instance?.PlayShoot();
    }

    private GameObject CreateDefaultBulletPrefab()
    {
        var bullet = new GameObject("DefaultBulletPrefab");
        bullet.AddComponent<SpriteRenderer>().color = Color.yellow;
        bullet.AddComponent<BoxCollider2D>();
        bullet.AddComponent<Rigidbody2D>();
        bullet.SetActive(false);
        return bullet;
    }
}
