﻿using UdonSharp;
using UnityEngine;
using VRC.SDKBase;

/// <summary>
/// Main scoreboard controller. Collects player data, sorts by profit,
/// and updates row displays. Updates every 10 seconds.
/// </summary>
public class HoldemScoreboard : UdonSharpBehaviour
{
    [Header("Row References")]
    [Tooltip("Assign row prefabs in the order they should appear (rank 1, 2, 3, etc.)")]
    public HoldemRowPrefab[] rows;

    [Header("Update Settings")]
    [Tooltip("How often to refresh the scoreboard (in seconds)")]
    public float updateIntervalSeconds = 10f;

    [Header("Player Data Cache")]
    // Arrays to store player data for sorting
    // Max 40 players (world capacity)
    private VRCPlayerApi[] allPlayers = new VRCPlayerApi[40];
    private string[] playerNames = new string[40];
    private int[] playerProfits = new int[40];
    private int[] playerBalances = new int[40];
    private int playerCount = 0;

    private float lastUpdateTime = 0f;
    private bool isInitialized = false;

    void Start()
    {
        isInitialized = rows != null && rows.Length > 0;
        
        // Clear all rows initially
        ClearAllRows();
    }

    void Update()
    {
        if (!isInitialized) return;

        // Update every interval
        if (Time.time - lastUpdateTime >= updateIntervalSeconds)
        {
            lastUpdateTime = Time.time;
            RefreshScoreboard();
        }
    }

    /// <summary>
    /// Main refresh logic - collects data, sorts, and updates display.
    /// </summary>
    public void RefreshScoreboard()
    {
        CollectPlayerData();
        SortByProfit();
        UpdateRowDisplays();
    }

    /// <summary>
    /// Collects player data from all players in the instance.
    /// </summary>
    private void CollectPlayerData()
    {
        playerCount = 0;

        // Clear stale data from arrays to prevent duplication during sort
        // (Required because VRCPlayerApi.GetPlayers doesn't clear the array,
        // and insertion sort can shift stale entries into visible positions)
        for (int i = 0; i < allPlayers.Length; i++)
        {
            allPlayers[i] = null;
            playerNames[i] = null;
            playerProfits[i] = 0;
            playerBalances[i] = 0;
        }

        // Get all players in the instance
        VRCPlayerApi.GetPlayers(allPlayers);

        for (int i = 0; i < allPlayers.Length; i++)
        {
            VRCPlayerApi player = allPlayers[i];
            
            // Skip null/invalid players
            if (player == null || !Utilities.IsValid(player))
                continue;

            // Get player's balance component
            PlayerBalanceComponent balanceComp = PlayerBalanceComponent.GetPlayerBalanceComponent(player);
            
            // Skip players without a ready balance component
            if (balanceComp == null || !balanceComp.IsReady())
                continue;

            // Store player data
            playerNames[playerCount] = player.displayName;
            playerProfits[playerCount] = balanceComp.GetProfit();
            playerBalances[playerCount] = balanceComp.GetBalance();
            
            playerCount++;
            
            // Safety check - don't exceed array bounds
            if (playerCount >= playerNames.Length)
                break;
        }
    }

    /// <summary>
    /// Sorts player data by profit descending (highest profit at top).
    /// Uses simple insertion sort (efficient for small datasets).
    /// </summary>
    private void SortByProfit()
    {
        if (playerCount <= 1) return;

        // Insertion sort by profit descending
        for (int i = 1; i < playerCount; i++)
        {
            string tempName = playerNames[i];
            int tempProfit = playerProfits[i];
            int tempBalance = playerBalances[i];
            
            int j = i - 1;
            
            // Shift elements to the right while they have lower profit
            while (j >= 0 && playerProfits[j] < tempProfit)
            {
                playerNames[j + 1] = playerNames[j];
                playerProfits[j + 1] = playerProfits[j];
                playerBalances[j + 1] = playerBalances[j];
                j--;
            }
            
            playerNames[j + 1] = tempName;
            playerProfits[j + 1] = tempProfit;
            playerBalances[j + 1] = tempBalance;
        }
    }

    /// <summary>
    /// Updates the row displays with sorted data.
    /// Only fills up to the number of available rows.
    /// </summary>
    private void UpdateRowDisplays()
    {
        int rowsToShow = Mathf.Min(playerCount, rows.Length);

        // Update active rows
        for (int i = 0; i < rowsToShow; i++)
        {
            if (rows[i] != null)
            {
                rows[i].UpdateDisplay(
                    i + 1, // Rank starts at 1
                    playerNames[i],
                    playerProfits[i],
                    playerBalances[i]
                );
            }
        }

        // Clear unused rows
        for (int i = rowsToShow; i < rows.Length; i++)
        {
            if (rows[i] != null)
            {
                rows[i].Clear();
            }
        }
    }

    /// <summary>
    /// Clears all rows (hides them).
    /// </summary>
    private void ClearAllRows()
    {
        if (rows == null) return;
        
        for (int i = 0; i < rows.Length; i++)
        {
            if (rows[i] != null)
            {
                rows[i].Clear();
            }
        }
    }

    /// <summary>
    /// Public method to manually trigger a refresh (can be called from UI button).
    /// </summary>
    public void ManualRefresh()
    {
        RefreshScoreboard();
    }
}