using UdonSharp;
using UnityEngine;

[UdonBehaviourSyncMode(BehaviourSyncMode.None)]
public class LocalObjectPool : UdonSharpBehaviour
{
    [Header("Pool Configuration")]
    public GameObject[] Pool;
    public int denomination;

    [Header("Debug")]
    public int availableCount;
    public int spawnedCount;

    // Pool slot of the object returned by the last successful TryToSpawn
    [HideInInspector] public int lastSpawnedIndex = -1;

    private bool[] available;
    private int[] freeSlots;
    private int freeCount;

    void Start()
    {
        EnsureInitialized();
    }

    public bool EnsureInitialized()
    {
        if (available != null && freeSlots != null) return true;
        InitializePool();
        return available != null && freeSlots != null;
    }

    private void InitializePool()
    {
        if (Pool == null || Pool.Length == 0)
        {
            Debug.LogWarning("LocalObjectPool: Pool array is empty or null!");
            return;
        }

        available = new bool[Pool.Length];
        freeSlots = new int[Pool.Length];
        freeCount = 0;

        // Push in reverse so the lowest slot spawns first
        for (int i = Pool.Length - 1; i >= 0; i--)
        {
            if (Pool[i] != null)
            {
                Pool[i].SetActive(false);
                available[i] = true;
                freeSlots[freeCount++] = i;
            }
            else
            {
                Debug.LogWarning($"LocalObjectPool: Pool[{i}] is null!");
                available[i] = false;
            }
        }

        UpdateDebugCounts();
    }

    /// <summary>
    /// Try to spawn an object from the pool.
    /// Returns the spawned GameObject, or null if no objects are available.
    /// </summary>
    public GameObject TryToSpawn()
    {
        lastSpawnedIndex = -1;
        if (!EnsureInitialized())
        {
            Debug.LogError("LocalObjectPool: Pool not initialized!");
            return null;
        }

        while (freeCount > 0)
        {
            int i = freeSlots[--freeCount];
            available[i] = false;
            if (Pool[i] == null) continue;

            Pool[i].SetActive(true);
            lastSpawnedIndex = i;
            UpdateDebugCounts();
            return Pool[i];
        }

        UpdateDebugCounts();
        return null;
    }

    /// <summary>
    /// Return the object in the given pool slot, as reported by lastSpawnedIndex.
    /// </summary>
    public void ReturnIndex(int index)
    {
        if (available == null || index < 0 || index >= Pool.Length || available[index]) return;

        GameObject go = Pool[index];
        if (go != null)
        {
            Rigidbody body = go.GetComponent<Rigidbody>();
            if (body != null)
            {
                if (!body.isKinematic)
                {
                    body.velocity = Vector3.zero;
                    body.angularVelocity = Vector3.zero;
                }
                body.useGravity = false;
                body.isKinematic = true;
                body.collisionDetectionMode = CollisionDetectionMode.Discrete;
            }

            Collider[] colliders = go.GetComponents<Collider>();
            for (int i = 0; i < colliders.Length; i++) colliders[i].enabled = false;

            go.transform.SetParent(transform);
            go.transform.localPosition = Vector3.zero;
            go.transform.localRotation = Quaternion.identity;
            go.SetActive(false);
        }

        available[index] = true;
        freeSlots[freeCount++] = index;
        UpdateDebugCounts();
    }

    /// <summary>
    /// Return an object to the pool by reference.
    /// </summary>
    public void Return(GameObject go)
    {
        if (go == null)
        {
            Debug.LogWarning("LocalObjectPool: Attempted to return null object!");
            return;
        }

        for (int i = 0; i < Pool.Length; i++)
        {
            if (Pool[i] == go)
            {
                ReturnIndex(i);
                return;
            }
        }
    }

    private void UpdateDebugCounts()
    {
        availableCount = freeCount;
        spawnedCount = Pool.Length - freeCount;
    }
}
