using UdonSharp;
using UnityEngine;
using UnityEngine.UI;
using VRC.SDKBase;
using VRC.SDK3.Persistence;
using TMPro;

/// <summary>
/// Drives a pool of plain (script-less) panels floating at every player's left shoulder,
/// showing balance and profit. All per-slot state lives in parallel arrays indexed by slot.
/// </summary>
[UdonBehaviourSyncMode(BehaviourSyncMode.None)]
public class ShoulderPanelManager : UdonSharpBehaviour
{
    private const string PersistenceEnabledKey = "WorldSettings/ShoulderPanels";
    private const string PersistenceHeightKey = "WorldSettings/ShoulderPanelHeight";
    private const int MaxPlayerIds = 1024;
    private const int RefreshPerFrame = 8;

    [Header("Pool (one entry per slot, 80 max players)")]
    public Transform[] panelRoots;
    public TMP_Text[] balanceTexts;
    public TMP_Text[] profitTexts;

    [Header("Settings UI")]
    public Toggle enableToggle;
    public Toggle[] allEnableToggles;
    public Slider heightSlider;
    public Slider[] allHeightSliders;

    [Header("Placement")]
    [Tooltip("Eye height (m) the panel offsets are authored for")]
    public float baseAvatarHeight = 1.6f;
    [Tooltip("Distance outward (arm +Z) from the arm/lower-arm midpoint in metres, before avatar scaling, when a player has no saved value")]
    public float defaultHeight = 0.1f;
    [Tooltip("Extra size multiplier applied on top of avatar scaling")]
    public float panelScale = 1.25f;
    [Tooltip("Panels of players farther than this (root to root, metres) are hidden before any bone is read. The panel materials dither out a little inside it (_FadeNear/_FadeFar), so nothing pops.")]
    public float visibleDistance = 5f;

    public Color balanceColor = new Color(1f, 0.9f, 0.3f);
    public Color positiveColor = new Color(0.65f, 1f, 0.7f);
    public Color negativeColor = new Color(1f, 0.65f, 0.65f);
    public Color neutralColor = Color.white;

    // Slot arrays
    private int[] slotPlayerId;
    private VRCPlayerApi[] slotPlayer;
    private PlayerBalanceComponent[] slotBalance;
    private float[] slotHeight;
    private int[] slotLastBalance;
    private int[] slotLastProfit;
    private bool[] slotVisible;
    private int[] playerSlot;

    private int slotCount;
    private int refreshCursor;
    private bool panelsEnabled;
    private bool isReady;
    private bool initialized;

    void Start()
    {
        Initialize();
        // On by default; a saved preference (OnPlayerRestored) overrides this
        if (enableToggle != null) enableToggle.SetIsOnWithoutNotify(true);
        ApplyToggle();
        ApplyHeight();
    }

    private void Initialize()
    {
        if (initialized) return;
        initialized = true;

        slotCount = panelRoots != null ? panelRoots.Length : 0;
        slotPlayerId = new int[slotCount];
        slotPlayer = new VRCPlayerApi[slotCount];
        slotBalance = new PlayerBalanceComponent[slotCount];
        slotHeight = new float[slotCount];
        slotLastBalance = new int[slotCount];
        slotLastProfit = new int[slotCount];
        slotVisible = new bool[slotCount];
        playerSlot = new int[MaxPlayerIds];

        for (int i = 0; i < slotCount; i++)
        {
            slotPlayerId[i] = -1;
            slotLastBalance[i] = int.MinValue;
            slotLastProfit[i] = int.MinValue;
            if (panelRoots[i] != null) panelRoots[i].gameObject.SetActive(false);
        }
        for (int i = 0; i < MaxPlayerIds; i++) playerSlot[i] = -1;
    }

    // ---------------------------------------------------------------- players

    public override void OnPlayerJoined(VRCPlayerApi player)
    {
        Initialize();
        AssignSlot(player);
    }

    public override void OnPlayerLeft(VRCPlayerApi player)
    {
        if (!initialized || player == null) return;
        int id = player.playerId;
        if (id < 0 || id >= MaxPlayerIds) return;
        int slot = playerSlot[id];
        if (slot < 0) return;

        playerSlot[id] = -1;
        slotPlayerId[slot] = -1;
        slotPlayer[slot] = null;
        slotBalance[slot] = null;
        slotLastBalance[slot] = int.MinValue;
        slotLastProfit[slot] = int.MinValue;
        slotVisible[slot] = false;
        if (panelRoots[slot] != null) panelRoots[slot].gameObject.SetActive(false);
    }

    private void AssignSlot(VRCPlayerApi player)
    {
        if (player == null || !Utilities.IsValid(player)) return;
        int id = player.playerId;
        if (id < 0 || id >= MaxPlayerIds || playerSlot[id] >= 0) return;

        for (int i = 0; i < slotCount; i++)
        {
            if (slotPlayerId[i] >= 0) continue;
            playerSlot[id] = i;
            slotPlayerId[i] = id;
            slotPlayer[i] = player;
            slotBalance[i] = PlayerBalanceComponent.GetPlayerBalanceComponent(player);
            slotHeight[i] = ReadHeight(player);
            return;
        }
    }

    private float ReadHeight(VRCPlayerApi player)
    {
        if (PlayerData.HasKey(player, PersistenceHeightKey))
            return PlayerData.GetFloat(player, PersistenceHeightKey);
        return defaultHeight;
    }

    public override void OnPlayerRestored(VRCPlayerApi player)
    {
        if (player == null) return;
        Initialize();
        AssignSlot(player);
        RefreshHeight(player);

        if (player.isLocal && !isReady)
        {
            isReady = true;
            if (enableToggle != null)
            {
                bool saved = !PlayerData.HasKey(player, PersistenceEnabledKey)
                    || PlayerData.GetInt(player, PersistenceEnabledKey) != 0;
                enableToggle.SetIsOnWithoutNotify(saved);
            }
            if (heightSlider != null && PlayerData.HasKey(player, PersistenceHeightKey))
            {
                float saved = Mathf.Clamp(PlayerData.GetFloat(player, PersistenceHeightKey),
                    heightSlider.minValue, heightSlider.maxValue);
                heightSlider.SetValueWithoutNotify(saved);
            }
            ApplyToggle();
            ApplyHeight();
        }
    }

    public override void OnPlayerDataUpdated(VRCPlayerApi player, PlayerData.Info[] infos)
    {
        if (player == null || player.isLocal) return;
        RefreshHeight(player);
    }

    private void RefreshHeight(VRCPlayerApi player)
    {
        if (!initialized || player == null || !Utilities.IsValid(player)) return;
        int id = player.playerId;
        if (id < 0 || id >= MaxPlayerIds) return;
        int slot = playerSlot[id];
        if (slot >= 0) slotHeight[slot] = ReadHeight(player);
    }

    // --------------------------------------------------------------- settings

    public void OnToggleChanged()
    {
        ApplyToggle();
    }

    public void OnHeightChanged()
    {
        ApplyHeight();
    }

    private void ApplyToggle()
    {
        if (enableToggle == null) return;
        panelsEnabled = enableToggle.isOn;
        if (isReady) PlayerData.SetInt(PersistenceEnabledKey, panelsEnabled ? 1 : 0);

        if (allEnableToggles != null)
        {
            for (int i = 0; i < allEnableToggles.Length; i++)
                if (allEnableToggles[i] != null) allEnableToggles[i].SetIsOnWithoutNotify(panelsEnabled);
        }

        if (!panelsEnabled && initialized) HideAll();
    }

    private void ApplyHeight()
    {
        if (heightSlider == null) return;
        float height = heightSlider.value;
        if (isReady) PlayerData.SetFloat(PersistenceHeightKey, height);

        if (allHeightSliders != null)
        {
            for (int i = 0; i < allHeightSliders.Length; i++)
                if (allHeightSliders[i] != null) allHeightSliders[i].SetValueWithoutNotify(height);
        }

        // Local persistence updates can lag, so apply to our own slot directly
        VRCPlayerApi local = Networking.LocalPlayer;
        if (initialized && local != null && Utilities.IsValid(local))
        {
            int id = local.playerId;
            if (id >= 0 && id < MaxPlayerIds && playerSlot[id] >= 0) slotHeight[playerSlot[id]] = height;
        }
    }

    private void HideAll()
    {
        for (int i = 0; i < slotCount; i++)
        {
            if (!slotVisible[i]) continue;
            slotVisible[i] = false;
            if (panelRoots[i] != null) panelRoots[i].gameObject.SetActive(false);
        }
    }

    // ----------------------------------------------------------------- update

    void PostLateUpdate()
    {
        if (!panelsEnabled || !initialized) return;

        VRCPlayerApi local = Networking.LocalPlayer;
        if (local == null || !Utilities.IsValid(local)) return;
        Vector3 viewerPos = local.GetPosition();
        float visibleSqr = visibleDistance * visibleDistance;

        for (int i = 0; i < slotCount; i++)
        {
            if (slotPlayerId[i] < 0) continue;
            VRCPlayerApi player = slotPlayer[i];
            if (player == null || !Utilities.IsValid(player)) continue;

            // Distance first: one call, where placing the panel takes several bone reads
            bool visible = (player.GetPosition() - viewerPos).sqrMagnitude <= visibleSqr;
            if (visible != slotVisible[i])
            {
                Transform toggled = panelRoots[i];
                if (toggled == null) continue;
                slotVisible[i] = visible;
                toggled.gameObject.SetActive(visible);
            }
            if (!visible) continue;
            Transform root = panelRoots[i];
            if (root == null) continue;

            Vector3 upperArm = player.GetBonePosition(HumanBodyBones.LeftUpperArm);
            Vector3 lowerArm = player.GetBonePosition(HumanBodyBones.LeftLowerArm);
            float scale = player.GetAvatarEyeHeightAsMeters() / baseAvatarHeight;
            float offset = slotHeight[i] * scale;

            Vector3 pos;
            Quaternion rot;
            if (upperArm == Vector3.zero || lowerArm == Vector3.zero)
            {
                // Non-humanoid fallback: estimate from head, facing the player's left
                Quaternion yaw = Quaternion.Euler(0f, player.GetRotation().eulerAngles.y, 0f);
                Vector3 head = player.GetTrackingData(VRCPlayerApi.TrackingDataType.Head).position;
                pos = head + yaw * new Vector3(-0.2f, -0.25f, 0f) * scale + yaw * Vector3.left * offset;
                rot = yaw * Quaternion.Euler(0f, 90f, 0f);
            }
            else
            {
                // Arm bone axes: +Y runs along the arm. Panel +Z = arm -Z (front, panel -Z, faces arm +Z),
                // panel +X = arm Y (text runs along the arm), panel +Y = arm X.
                // Starts at the exact midpoint, offset along the arm +Z (panel -Z).
                Quaternion armRot = player.GetBoneRotation(HumanBodyBones.LeftUpperArm);
                rot = Quaternion.LookRotation(armRot * Vector3.back, armRot * Vector3.right);
                pos = (upperArm + lowerArm) * 0.5f + rot * Vector3.back * offset;
            }

            root.SetPositionAndRotation(pos, rot);
            root.localScale = Vector3.one * (scale * panelScale);
        }

        RefreshTexts();
    }

    private void RefreshTexts()
    {
        if (slotCount == 0) return;
        int budget = RefreshPerFrame < slotCount ? RefreshPerFrame : slotCount;
        for (int n = 0; n < budget; n++)
        {
            int i = refreshCursor;
            refreshCursor = (refreshCursor + 1) % slotCount;
            if (slotPlayerId[i] < 0 || !slotVisible[i]) continue;

            if (slotBalance[i] == null)
            {
                slotBalance[i] = PlayerBalanceComponent.GetPlayerBalanceComponent(slotPlayer[i]);
                if (slotBalance[i] == null) continue;
            }

            int balance = -1;
            int profit = 0;
            if (slotBalance[i].IsReady())
            {
                balance = slotBalance[i].GetBalance();
                profit = slotBalance[i].GetProfit();
            }
            if (balance == slotLastBalance[i] && profit == slotLastProfit[i]) continue;
            slotLastBalance[i] = balance;
            slotLastProfit[i] = profit;

            if (balanceTexts[i] != null)
            {
                balanceTexts[i].text = "B: " + (balance >= 0 ? FormatCompact(balance, false) : "-");
                balanceTexts[i].color = balanceColor;
            }
            if (profitTexts[i] != null)
            {
                profitTexts[i].text = "WL: " + (balance >= 0 ? FormatCompact(profit, true) : "-");
                profitTexts[i].color = profit > 0 ? positiveColor : (profit < 0 ? negativeColor : neutralColor);
            }
        }
    }

    // ------------------------------------------------------------- formatting

    /// <summary>Compact number: 999, 1.2k, 3.4M. With showSign, positives get a leading +.</summary>
    public static string FormatCompact(int value, bool showSign)
    {
        long abs = value < 0 ? -(long)value : value;
        string sign = value < 0 ? "-" : (showSign && value > 0 ? "+" : "");
        if (abs < 1000L) return sign + abs;
        if (abs < 1000000L) return sign + Scaled(abs, 1000L, "k");
        if (abs < 1000000000L) return sign + Scaled(abs, 1000000L, "M");
        return sign + Scaled(abs, 1000000000L, "B");
    }

    private static string Scaled(long abs, long unit, string suffix)
    {
        long tenths = abs * 10L / unit; // truncate, never round up across a unit boundary
        long whole = tenths / 10L;
        long frac = tenths - whole * 10L; // long % is not exposed to Udon
        if (whole >= 100L || frac == 0L) return whole + suffix;
        return whole + "." + frac + suffix;
    }
}
