using UdonSharp;
using UnityEngine;
using VRC.SDKBase;
using VRC.Udon;

public class DunceCapPool : UdonSharpBehaviour
{
    [Header("Pool")]
    [Tooltip("Array of Dunce Cap GameObjects to use")]
    public GameObject[] dunceCaps;
    
    [Tooltip("Offset from the head bone")]
    public Vector3 headOffset = new Vector3(0, 0.25f, 0);

    [Header("Scaling")]
    [Tooltip("Base avatar eye height for default scale")]
    public float baseAvatarHeight = 1.6f;

    private Vector3[] initialScales;

    private int[] capPlayerIds;

    private const int MaxPlayerIds = 128;
    private PlayerBalanceComponent[] balanceCache;
    private bool _cacheDirty = true;

    private VRCPlayerApi[] playerBuffer;

    void Start()
    {
        if (dunceCaps != null)
        {
            initialScales = new Vector3[dunceCaps.Length];
            capPlayerIds = new int[dunceCaps.Length];
            for (int i = 0; i < dunceCaps.Length; i++)
            {
                if (dunceCaps[i] != null)
                {
                    initialScales[i] = dunceCaps[i].transform.localScale;
                    DunceCapInteract interact = dunceCaps[i].GetComponentInChildren<DunceCapInteract>(true);
                    if (interact != null)
                    {
                        interact.Initialize(this, i);
                    }
                }
                else
                {
                    initialScales[i] = Vector3.one;
                }
                capPlayerIds[i] = -1;
            }
        }

        balanceCache = new PlayerBalanceComponent[MaxPlayerIds];
        playerBuffer = new VRCPlayerApi[MaxPlayerIds];
    }

    public override void OnPlayerJoined(VRCPlayerApi player)
    {
        _cacheDirty = true;
    }

    public override void OnPlayerLeft(VRCPlayerApi player)
    {
        _cacheDirty = true;
    }

    public int GetAssignedPlayerId(int slot)
    {
        if (capPlayerIds == null) return -1;
        if (slot < 0 || slot >= capPlayerIds.Length) return -1;
        return capPlayerIds[slot];
    }

    private PlayerBalanceComponent GetCachedBalance(VRCPlayerApi player)
    {
        int id = player.playerId;
        if (balanceCache == null || id < 0 || id >= MaxPlayerIds)
        {
            return PlayerBalanceComponent.GetPlayerBalanceComponent(player);
        }

        if (balanceCache[id] == null)
        {
            balanceCache[id] = PlayerBalanceComponent.GetPlayerBalanceComponent(player);
        }
        return balanceCache[id];
    }

    void PostLateUpdate()
    {
        if (dunceCaps == null || dunceCaps.Length == 0) return;
        if (capPlayerIds == null || capPlayerIds.Length != dunceCaps.Length) return;

        if (_cacheDirty)
        {
            if (balanceCache != null)
            {
                for (int i = 0; i < balanceCache.Length; i++) balanceCache[i] = null;
            }
            _cacheDirty = false;
        }

        int playerCount = VRCPlayerApi.GetPlayerCount();
        if (playerBuffer == null || playerBuffer.Length < playerCount)
        {
            playerBuffer = new VRCPlayerApi[playerCount];
        }
        VRCPlayerApi.GetPlayers(playerBuffer);

        SortPlayersById(playerBuffer, playerCount);

        int capIndex = 0;

        for (int p = 0; p < playerCount; p++)
        {
            VRCPlayerApi player = playerBuffer[p];
            if (player == null || !player.IsValid()) continue;
            if (capIndex >= dunceCaps.Length) break;

            PlayerBalanceComponent balance = GetCachedBalance(player);
            if (balance == null || !balance.HasDunceCapSynced) continue;

            GameObject cap = dunceCaps[capIndex];
            if (cap != null)
            {
                if (!cap.activeSelf) cap.SetActive(true);

                Vector3 headPos = player.GetTrackingData(VRCPlayerApi.TrackingDataType.Head).position;
                Quaternion headRot = player.GetTrackingData(VRCPlayerApi.TrackingDataType.Head).rotation;

                float scaleMultiplier = player.GetAvatarEyeHeightAsMeters() / baseAvatarHeight;

                cap.transform.position = headPos + (headRot * (headOffset * scaleMultiplier));
                cap.transform.rotation = headRot;
                if (initialScales != null && capIndex < initialScales.Length)
                {
                    cap.transform.localScale = initialScales[capIndex] * scaleMultiplier;
                }
            }
            capPlayerIds[capIndex] = player.playerId;
            capIndex++;
        }

        // Disable any remaining caps in the pool
        for (int i = capIndex; i < dunceCaps.Length; i++)
        {
            capPlayerIds[i] = -1;
            if (dunceCaps[i] != null && dunceCaps[i].activeSelf)
            {
                dunceCaps[i].SetActive(false);
            }
        }
    }

    /// <summary>
    /// Insertion sort by playerId over the first <paramref name="count"/> entries.
    /// Player counts here are small, and this avoids allocating per frame.
    /// </summary>
    private void SortPlayersById(VRCPlayerApi[] players, int count)
    {
        for (int i = 1; i < count; i++)
        {
            VRCPlayerApi key = players[i];
            if (key == null) continue;
            int keyId = key.playerId;
            int j = i - 1;
            while (j >= 0 && (players[j] == null || players[j].playerId > keyId))
            {
                players[j + 1] = players[j];
                j--;
            }
            players[j + 1] = key;
        }
    }
}
