using FlappyBird.Pipes;
using UnityEngine;
using Zenject;
using FlappyBird.Ground;

namespace FlappyBird.Bird
{
    /// <summary>
    /// MonoBehaviour facade for the Bird prefab.
    /// Responsibilities (AI_RULES.md rule #1):
    ///   - Holds component references
    ///   - Forwards Unity lifecycle events to BirdController
    ///   - Detects input in Update only ? all logic lives in BirdController
    /// </summary>
    [RequireComponent(typeof(Rigidbody2D))]
    public class BirdView : MonoBehaviour
    {
        public Rigidbody2D Rigidbody { get; private set; }

        private IBirdController _controller;

        [Inject]
        public void Construct(IBirdController controller)
        {
            _controller = controller;
        }

        private void Awake()
        {
            Rigidbody = GetComponent<Rigidbody2D>();
        }

        private void Start()
        {
            _controller.Bind(this);
        }

        /// <summary>
        /// Input detection only ? no logic.
        /// Delegates to IBirdController on tap/click/space.
        /// </summary>
        private void Update()
        {
            if (_controller == null)
            {
                return;
            }

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

        /// <summary>
        /// Physics-tick delegation ? no input here.
        /// </summary>
        private void FixedUpdate()
        {
            if (_controller == null)
            {
                return;
            }

            _controller.FixedTick();
        }

        private void OnCollisionEnter2D(Collision2D collision)
        {
            if (_controller == null || collision == null)
            {
                return;
            }

            if (!IsPipeCollision(collision.collider) && !IsGroundCollision(collision.collider))
            {
                return;
            }

            _controller.HandleCollision();
        }

        private void OnTriggerEnter2D(Collider2D other)
        {
            if (_controller == null || other == null || !IsGroundCollision(other))
            {
                return;
            }

            _controller.HandleCollision();
        }

        private static bool IsPipeCollision(Collider2D collider)
        {
            return collider.GetComponentInParent<PipeView>() != null;
        }

        private static bool IsGroundCollision(Collider2D collider)
        {
            return collider.GetComponentInParent<GroundView>() != null;
        }
    }
}
