// Assets/_Project/Scripts/Gameplay/Draft/DraftPool.cs
using System.Collections.Generic;
using UnityEngine;

namespace TD.Gameplay.Draft
{
    /// <summary>
    /// Scene singleton holding every <see cref="DraftOption"/> available this match. The
    /// array index is the option's <c>DraftOptionId</c> — the stable identifier used to
    /// replicate offers and picks over the network (mirrors the tower catalog pattern).
    /// </summary>
    /// <remarks>
    /// Plain MonoBehaviour: identical on every peer (same assets), so there is nothing to
    /// sync. The server reads it to generate offers and apply picks; clients read it to
    /// render draft cards from the replicated option ids.
    /// </remarks>
    public class DraftPool : MonoBehaviour
    {
        public static DraftPool Instance { get; private set; }

        [Tooltip("Every DraftOption asset that can be offered this match. Array index is " +
                 "the DraftOptionId used over the network.")]
        [SerializeField] private DraftOption[] options;

        private void Awake()
        {
            if (Instance != null && Instance != this)
            {
                Debug.LogError("[DraftPool] Multiple instances detected. Only one per scene.");
                return;
            }
            Instance = this;
        }

        private void OnDestroy()
        {
            if (Instance == this) Instance = null;
        }

        /// <summary>Number of options in the pool.</summary>
        public int Count => options?.Length ?? 0;

        /// <summary>Returns the option at <paramref name="id"/> (its DraftOptionId), or null.</summary>
        public DraftOption Get(int id)
            => (options != null && id >= 0 && id < options.Length) ? options[id] : null;

        /// <summary>
        /// Server-only helper: collects the ids of every option currently valid to offer
        /// to <paramref name="clientId"/> (skips nulls and options whose
        /// <see cref="DraftOption.IsValidFor"/> returns false). Used by
        /// <see cref="DraftService"/> as the candidate set for the weighted draw.
        /// </summary>
        public void CollectValidIds(ulong clientId, List<int> into)
        {
            into.Clear();
            if (options == null) return;
            for (int i = 0; i < options.Length; i++)
            {
                if (options[i] == null) continue;
                if (options[i].IsValidFor(clientId)) into.Add(i);
            }
        }
    }
}
