using UnityEngine;
using Zenject;

namespace FlappyBird.Gameplay.Pipes
{
    /// <summary>
    /// Thin MonoBehaviour that lives on the pipe-pair prefab.
    /// Responsibilities:
    ///   - Expose top/bottom pipe transforms for positioning by the spawner
    ///   - Scroll leftward every frame
    ///   - Return itself to the pool when off-screen
    /// NO spawn logic lives here.
    /// </summary>
    public sealed class PipeView : MonoBehaviour, Core.IPoolable
    {
        [Tooltip("Transform of the top pipe (flipped, hanging from above).")]
        [SerializeField] private Transform topPipe;
        [Tooltip("Transform of the bottom pipe (standing upright).")]
        [SerializeField] private Transform bottomPipe;
        [Tooltip("Score trigger collider child sitting in the centre of the gap.")]
        [SerializeField] private ScoreTriggerView scoreTrigger;

        // ── Public accessors used by PipeSpawner ───────────────────────────
        public Transform TopPipe          => topPipe;
        public Transform BottomPipe       => bottomPipe;
        public ScoreTriggerView ScoreTrigger => scoreTrigger;

        // ── Injected ───────────────────────────────────────────────────────
        private IPipePool     _pool;
        private PipeSettings  _settings;
        [Inject]
        private void Construct(IPipePool pool, PipeSettings settings)
        {
            _pool     = pool;
            _settings = settings;
        }
        // ── Unity lifecycle ────────────────────────────────────────────────
        private void Update()
        {
            ScrollLeft();
        }
        // ── IPoolable ──────────────────────────────────────────────────────
        /// <summary>Called by the pool just before this pair is handed to the spawner.</summary>
        public void OnSpawn()
        {
            gameObject.SetActive(true);
        }
        /// <summary>Called by the pool when this pair is returned.</summary>
        public void OnDespawn()
        {
            gameObject.SetActive(false);
        }
        // ── Private helpers ────────────────────────────────────────────────
        /// <summary>Moves the pipe pair leftward and despawns when off-screen.</summary>
        private void ScrollLeft()
        {
            transform.position += Vector3.left * (_settings.ScrollSpeed * Time.deltaTime);
            if (transform.position.x <= _settings.DespawnX)
                _pool.Return(this);
        }

        // ── Zenject factory ────────────────────────────────────────────────
        /// <summary>
        /// Zenject factory used by PipePool to instantiate pipe-pair prefabs
        /// with full dependency injection applied.
        /// </summary>
        public sealed class Factory : PlaceholderFactory<PipeView> { }
    }
}